language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <kern/syscall.h> extern void putchar(int c); extern int getchar(void); int main(void) { putchar('a'); putchar('b'); putchar('c'); /* while(1) { int c = getchar(); putchar(c); if(c == 'q') break; } */ return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <math.h> static double count_quest(double p, double q); int main() { double n, p, q; double t = 0.0; int i; printf("n (1<=n<=1000000) ="); scanf("%lf", &n); printf("p (0<=n<=100) ="); scanf("%lf", &p); printf("q (1<=n<=100) ="); scanf("%lf", &q); /* for 1st item */ t = count_quest(p, q); /* for 2nd ~ nth items */ for(i = 1; i < n; i++) { int mi = pow(2,i); int newp = p / mi; t += count_quest((double)newp, q); } printf("t = %0.2lf\n", t); } static double count_quest(double p, double q) { double add_count; int yu, i_count; double r, rt; int i, j; /* i_count is the max steps that can't get item */ add_count = (100 - p) / q; yu = (100 - (int)p) % (int)q; if (yu != 0) add_count += 1; i_count = (int)add_count; r = 1 * p / 100; for (i = 0; i < i_count; i++) { rt = (100 - p) / 100; for (j = 1; j <= i; j++) { rt *= (100 - p - j * q) / 100; } if ((p + j * q) <= 100) rt *= (j + 1) * (p + j * q) / 100; else rt *= (j + 1) * 100 / 100; r += rt; } return r; }
C
/* ** EPITECH PROJECT, 2018 ** my_put_nbr ** File description: ** A function that print a number */ #include "include/function.h" int conversion_for_decimal(int rest) { if (rest >= 0 && rest <= 9) rest = rest + 48; return (rest); } int my_put_nbr(int nb) { if (nb >= 10) { my_put_nbr(nb / 10); my_putchar(nb % 10 + 48); } else my_putchar(nb + 48); }
C
#include <stdio.h> // printf #include <signal.h> typedef int Int; typedef int Bool; typedef int Unit; #define false 0 #define true 1 #define unit 0 Bool and(Bool a, Bool b) { return a && b; } Bool or(Bool a, Bool b) { return a || b; } Bool xor(Bool a, Bool b) { return a != b; } Bool not(Bool a) { return !a; } Bool beq(Bool a, Bool b) { return a == b; } Bool bneq(Bool a, Bool b) { return a != b; } Int add(Int a, Int b) { return a + b; } Int sub(Int a, Int b) { return a - b; } Int mul(Int a, Int b) { return a * b; } Int div(Int a, Int b) { return a / b; } Int mod(Int a, Int b) { return a % b; } Bool ieq(Int a, Int b) { return a == b; } Bool ineq(Int a, Int b) { return a != b; } Bool gt(Int a, Int b) { return a > b; } Bool geq(Int a, Int b) { return a >= b; } Bool lt(Int a, Int b) { return a < b; } Bool leq(Int a, Int b) { return a <= b; } void iprint(Int a) { printf("%d\n", a); } void bprint(Bool a) { printf("%d\n", a); } void abort() { fprintf(stderr, "abort"); #ifdef _WIN32 void exit(int const); exit(-SIGABRT); #else raise(SIGABRT); #endif }
C
#include <stdio.h> #include <stdlib.h> #define Maxterm 20 #define True 1 #define False 0 typedef struct Node* NodePtr; typedef struct ListNode* ListNodePtr; struct Node{ int id; ListNodePtr child; NodePtr parent; }; struct ListNode{ NodePtr data; ListNodePtr next; }; int num = 0; int count = 0; int starting[Maxterm]; int ending[Maxterm]; int visit[Maxterm] = {False}; void insert_child(NodePtr *top , int i){ top[i]->id = i; if(starting[i] == -1){ return; } ListNodePtr first = malloc(sizeof(struct ListNode)); first->data = malloc(sizeof(struct Node)); first->data = top[starting[i]]; first->next = NULL; top[i]->child = first; int j = starting[i]; if(j == -1) return; while(starting[j] != -1){ ListNodePtr tmp = malloc(sizeof(struct ListNode)); tmp->data = malloc(sizeof(struct Node)); tmp->data = top[starting[j]]; tmp->next = NULL; first->next = tmp; first = tmp; j = starting[j]; } } void link_change(NodePtr *top , int i){ top[top[i]->parent->id]->child->data = top[starting[i]]; top[i]->child->data = top[top[i]->parent->id]; visit[top[i]->parent->id] = True; visit[i] = True; } int map(NodePtr *top){ int cnt = 0; for(int i = 0 ; i < num ; i++){ if(visit[i] == True){ cnt = cnt + 1; } } return cnt; } int main(){ scanf("%d", &num); for (int i = 0 ; i < num ; i++){ scanf("%d", &starting[i]); } NodePtr top[num]; for(int i = 0 ; i < num ; i++){ top[i] = malloc(sizeof(struct Node)); top[i]->child = NULL; top[i]->parent = NULL; } // 輸入Node for (int i = 0 ; i < num ; i++){ insert_child(top , i); for(int j = 0 ; j < num ; j++){ if(j == starting[i]){ top[j]->parent = top[i]; } } } for(int i = 0 ; i < num ; i++){ if(starting[i] == -1 || top[i]->parent == NULL){ visit[i] = True; } } // visit 要全走過 while(count != num){ for(int i = 0 ; i < num ; i++){ if(visit[starting[i]] == True && visit[i] == False){ link_change(top , i); } } count = map(top); } // 測試印出結果 printf("visit\t: "); for(int i = 0 ; i < num ; i++){ printf("%d\t" , visit[i]); } printf("\nNode\t: "); for (int i = 0 ; i < num ; i++){ printf("%d\t" , top[i]->id); } printf("\nTo\t: "); for (int i = 0 ; i < num ; i++){ if(top[i]->child != NULL) printf("%d\t" , top[i]->child->data->id); else printf("-1\t"); } printf("\nParent\t: "); for (int i = 0 ; i < num ; i++){ if(top[i]->parent != NULL) printf("%d\t" , top[i]->parent->id); else printf("-1\t"); } printf("\n"); for (int i = 0 ; i < num ; i++){ printf("\nNode %d->" , i); ListNodePtr x = top[i]->child; while(x){ NodePtr y = x->data; printf("%d->" , y->id); x = x->next; } } printf("\n"); // 測試印出結果 return 0; }
C
/* ヘッダファイルのインクルード */ #include <stdio.h> /* 標準入出力 */ #include <stdlib.h> /* 標準ユーティリティ */ /* main関数 */ int main(void){ /* 変数・配列の宣言 */ char str[16]; /* 数値文字列を格納するchar型配列str(長さ16) */ double d; /* double型変数d */ /* 入力フォーム */ printf("str: "); /* strの入力フォームを出力. */ scanf("%s", str); /* scanfで入力された文字列をstrに格納. */ /* atofで数値文字列strを倍精度浮動小数点数値dに変換. */ d = atof(str); /* atofにstrを渡すことで, dに変換された浮動小数点数値が返る. */ /* dの出力. */ printf("d = %lf\n", d); /* dを出力. */ /* プログラムの終了. */ return 0; /* 0を返して正常終了. */ }
C
#include <stdio.h> void inc(int *p); void pstr(char *c); struct s { int val; char *name; }; int main() { int *p; int i; i = 9; p = &i; printf("i is located at %p\n", p); printf("value of i: %d\n", i); inc(p); printf("i incremented: %d\n", i); char name[] = "Parker"; pstr(name); } void inc(int *p) { *p = *p + 1; } //uses pointer arithmetic to print a string void pstr(char *c) { if (*c == '\0') printf("\n"); else { printf("%c", *c); pstr(c+1); } }
C
#include <stdio.h> int isEven(int); int main() { int n; printf("Enter a number: "); scanf("%d", &n); if (isEven(n)) printf("Even number\n"); else printf("Odd number\n"); return 0; } int isEven(int n) { return !(n % 2); }
C
#ifndef UNIP_PIM_CLINIC_SETUP_H #define UNIP_PIM_CLINIC_SETUP_H #include <stdio.h> #include <stdlib.h> #include <io.h> void setup() { // Verifica se a pasta de dados esta criada int check = mkdir("dados"); if (!check) { mkdir("dados/tmp"); printf("* NECESSARIO CRIAR ESTRUTURA DE ARQUIVOS * \n\n"); // Validar se arquivos de usuários existe FILE *usuarios; usuarios = fopen("dados/usuarios.txt", "r"); if (usuarios == NULL) { printf("ARQUIVO DE USUARIOS SENDO CRIADO..... \n"); FILE *arquivo; arquivo = fopen("dados/usuarios.txt", "w+"); fprintf(arquivo, "%d %s %s %d\n", 1, "admin", "admin", 1); fclose(arquivo); printf("ARQUIVO DE USUARIOS CRIADO COM SUCESSO !\n"); } fclose(usuarios); // Validar se arquivos de medicos existe FILE *medicos; medicos = fopen("dados/medicos.txt", "r"); if (medicos == NULL) { printf("ARQUIVO DE MEDICOS SENDO CRIADO..... \n"); FILE *arquivo; arquivo = fopen("dados/medicos.txt", "w+"); fclose(arquivo); printf("ARQUIVO DE MEDICOS CRIADO COM SUCESSO !\n"); } fclose(medicos); // Validar se arquivos de agendas existe FILE *agendas; agendas = fopen("dados/agendas.txt", "r"); if (agendas == NULL) { printf("ARQUIVO DE AGENDAS SENDO CRIADO..... \n"); FILE *arquivo; arquivo = fopen("dados/agendas.txt", "w+"); fclose(arquivo); printf("ARQUIVO DE AGENDAS CRIADO COM SUCESSO !\n"); } fclose(agendas); // Validar se arquivos de cadastro existe FILE *cadastro; cadastro = fopen("dados/cadastro.txt", "r"); if (cadastro == NULL) { printf("ARQUIVO DE CADASTRO SENDO CRIADO..... \n"); FILE *arquivo; arquivo = fopen("dados/cadastro.txt", "w+"); fclose(arquivo); printf("ARQUIVO DE CADASTRO CRIADO COM SUCESSO !\n"); } fclose(cadastro); // Validar se o arquivo de usuários existe FILE *cadastropaciente; cadastropaciente = fopen("dados/pacientes.txt", "r"); if (cadastropaciente == NULL) { printf("ARQUIVO DE PACIENTES SENDO CRIADO..... \n"); FILE *arquivo; arquivo = fopen("dados/pacientes.txt", "w+"); fclose(arquivo); printf("ARQUIVO DE PACIENTES CRIADO COM SUCESSO !\n"); } fclose(cadastropaciente); // Verificar se o arquivo de feedback existe FILE *feedback; feedback = fopen("dados/feedbacks.txt", "r"); if (feedback == NULL) { printf("ARQUIVO DE FEEDBACK SENDO CRIADO..... \n"); FILE *arquivo; arquivo = fopen("dados/feedback.txt", "w+"); fclose(arquivo); printf("ARQUIVO DE FEEDBACK CRIADO COM SUCESSO !\n"); } fclose(feedback); printf("\n\n** ESTRUTURA CRIADA, EXECUTE O PROGRAMA NOVAMENTE **\n\n"); system("pause"); exit(0); } } #endif //UNIP_PIM_CLINIC_SETUP_H
C
/** Program 4.4 Various input formatting options for reading integers are experimented in the program shown in Fig. 4.4. */ ///program begin #include<stdio.h> #include<conio.h> //main() function begin int main() { int a,b,c,x,y,z; int p,q,r; printf("Enter three integer numbers\n"); scanf("%d %*d %d",&a,&b,&c); printf("%d %d %d \n\n",a,b,c); printf("Enter two 4-digit numbers\n"); scanf("%2d %4d",&x,&y); printf("%d %d\n\n", x,y); printf("Enter two integers\n"); scanf("%d %d", &a,&x); printf("%d %d \n\n",a,x); printf("Enter a nine digit number\n"); scanf("%3d %4d %3d",&p,&q,&r); printf("%d %d %d \n\n",p,q,r); printf("Enter two three digit numbers\n"); scanf("%d %d",&x,&y); printf("%d %d",x,y); getch(); return 0; } //main() end ///program end /** output Enter three integer numbers 1 2 3 1 3 -3577 Enter two 4-digit numbers 6789 4321 67 89 Enter two integers 44 66 4321 44 Enter a nine-digit number 123456789 66 1234 567 Enter two three-digit numbers 123 456 89 123 */
C
#include<stdio.h> int main() { int i,j,r,c; printf("enter the rows and columns of matrices:\n"); scanf("%d%d",&r,&c); int arr1[r][c],arr2[r][c],arr3[r][c]; printf("enter the values of 1st matrix:\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("%d X %d :\t",i,j); scanf("%d",&arr1[i][j]); } } printf("enter the values of 2st matrix:\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("%d X %d :\t",i,j); scanf("%d",&arr2[i][j]); } } printf("the resultant matrix is:\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("%d\t",arr1[i][j]-arr2[i][j]); } printf("\n"); } return 0; }
C
/* * L3_dd_trg/input_drv_mouse * Mostly from the excellent ELDD book... */ #define pr_fmt(fmt) "%s:%s(): " fmt, KBUILD_MODNAME, __func__ #include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/input.h> #include <linux/platform_device.h> #include <linux/mutex.h> // copy_[to|from]_user() #include <linux/version.h> #if LINUX_VERSION_CODE > KERNEL_VERSION(4, 11, 0) #include <linux/uaccess.h> #else #include <asm/uaccess.h> #endif MODULE_DESCRIPTION("Input driver - example, simple mouse emulator demo; ref: ELDD book"); /* * We *require* the module to be released under GPL license (as well) to please * several core driver routines (like sysfs_create_group, * platform_device_register_simple, etc which are exported to GPL only (using * the EXPORT_SYMBOL_GPL() macro)) */ MODULE_LICENSE("Dual MIT/GPL"); MODULE_VERSION("0.1"); #define OURMODNAME "input_drv_mouse" #define SYSFS_FILE1 vms static struct input_dev *vms_input_dev; static struct platform_device *sysfs_demo_platdev; /* Device structure */ /* Note that in both the show and store methods, the buffer 'buf' is * a *kernel*-space buffer. (So don't try copy_[from|to]_user stuff!) * * From linux/device.h: --snip-- // interface for exporting device attributes struct device_attribute { struct attribute attr; ssize_t (*show)(struct device *dev, struct device_attribute *attr, char *buf); ssize_t (*store)(struct device *dev, struct device_attribute *attr, const char *buf, size_t count); }; */ static ssize_t vms_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int x, y; sscanf(buf, "%d%d", &x, &y); dev_dbg(dev, "%s(): count=%zu; (%d, %d) reported up\n", __func__, count, x, y); /* Report relative coordinates via the event interface */ input_report_rel(vms_input_dev, REL_X, x); input_report_rel(vms_input_dev, REL_Y, y); input_sync(vms_input_dev); /* "- The first statement generates a REL_X event or a relative device movement in the X direction. - The second produces a REL_Y event or a relative movement in the Y direction. - input_sync() indicates that this event is complete, so the input subsystem collects these two events into a single evdev packet and sends it out of the door through /dev/input/eventX, where X is the interface number assigned to the vms driver. An application reading this file will receive event packets in the input_event format described earlier. Run the coords_gen user mode app in one window.. Can use the evtest app to 'see' events as they occur: f.e.: $ sudo evtest /dev/input/event7 Input driver version is 1.0.1 Input device ID: bus 0x0 vendor 0x0 product 0x0 version 0x0 Input device name: "Unknown" Supported events: Event type 0 (EV_SYN) Event type 2 (EV_REL) Event code 0 (REL_X) Event code 1 (REL_Y) Properties: Testing ... (interrupt to exit) Event: time 1610437930.721948, type 2 (EV_REL), code 0 (REL_X), value -3 Event: time 1610437930.721948, type 2 (EV_REL), code 1 (REL_Y), value 6 Event: time 1610437930.721948, -------------- SYN_REPORT ------------ Event: time 1610437931.724963, type 2 (EV_REL), code 0 (REL_X), value -17 Event: time 1610437931.724963, type 2 (EV_REL), code 1 (REL_Y), value -15 Event: time 1610437931.724963, -------------- SYN_REPORT ------------ Event: time 1610437932.745446, type 2 (EV_REL), code 0 (REL_X), value -13 Event: time 1610437932.745446, type 2 (EV_REL), code 1 (REL_Y), value -15 Event: time 1610437932.745446, -------------- SYN_REPORT ------------ [ ... ] ^C$ Alternately, to request gpm (general purpose mouse) to attach to this event interface and accordingly chase the cursor around your screen, do this: sudo gpm -m /dev/input/eventX -t evdev */ return count; } /* The DEVICE_ATTR{_RW|RO|WO}() macro instantiates a struct device_attribute * dev_attr_<name> here... * The name of the 'show' callback function is llkdsysfs_pgoff_show */ static DEVICE_ATTR_WO(vms); /* it's show callback is above.. */ /* * From <linux/device.h>: DEVICE_ATTR{_RW} helper interfaces (linux/device.h): --snip-- #define DEVICE_ATTR_RW(_name) \ struct device_attribute dev_attr_##_name = __ATTR_RW(_name) #define __ATTR_RW(_name) __ATTR(_name, 0644, _name##_show, _name##_store) --snip-- and in <linux/sysfs.h>: #define __ATTR(_name, _mode, _show, _store) { \ .attr = {.name = __stringify(_name), \ .mode = VERIFY_OCTAL_PERMISSIONS(_mode) }, \ .show = _show, \ .store = _store, \ } */ static int __init input_drv_mouse_init(void) { int stat = 0; if (unlikely(!IS_ENABLED(CONFIG_SYSFS))) { pr_warn("sysfs unsupported! Aborting ...\n"); return -EINVAL; } // LDM: register with a bus; here we register our platform device with the platform bus /* 0. Register a (dummy) platform device; required as we need a * struct device *dev pointer to create the sysfs file with * the device_create_file() API: * struct platform_device *platform_device_register_simple( * const char *name, int id, * const struct resource *res, unsigned int num); */ #define PLAT_NAME "vms" sysfs_demo_platdev = platform_device_register_simple(PLAT_NAME, -1, NULL, 0); if (IS_ERR(sysfs_demo_platdev)) { stat = PTR_ERR(sysfs_demo_platdev); pr_info("error (%d) registering our platform device, aborting\n", stat); goto out1; } // 1. Create our sysfile file : /* The device_create_file() API creates a sysfs attribute file for * given device (1st parameter); the second parameter is the pointer * to it's struct device_attribute structure dev_attr_<name> which was * instantiated by our DEV_ATTR{_RW|RO} macros above ... * API used: * int device_create_file(struct device *dev, * const struct device_attribute *attr); */ stat = device_create_file(&sysfs_demo_platdev->dev, &dev_attr_vms); /* * A potentially confusing aspect: as this is the first time, we * explain it via this comment: * The &dev_attr_SYSFS_FILE1 above (2nd param to the * device_create_file() API), is actually *instantiated* via this * declaration above: * static DEVICE_ATTR_WO(SYSFS_FILE1); * This DEVICE_ATTR{_RW|RO|WO}() macro instantiates a * struct device_attribute dev_attr_<name> data structure! * ... and hence we automatically get the rd/wr callbacks registered. * (IOW, the DEVICE_ATTR_XX(name) macro becomes a * struct device_attribute dev_attr_name data structure!) */ if (stat) { pr_info("device_create_file failed (%d), aborting now\n", stat); goto out2; } pr_debug("sysfs file (/sys/devices/platform/%s/%s) created\n", PLAT_NAME, "vms"); /* Allocate an input device data structure */ vms_input_dev = input_allocate_device(); if (!vms_input_dev) { dev_warn(&sysfs_demo_platdev->dev, "input_alloc_device() failed\n"); goto out3; } vms_input_dev->name = "virtual mouse (vms)"; vms_input_dev->phys = "virtual/input0"; /* Announce that the virtual mouse will generate relative coordinates */ set_bit(EV_REL, vms_input_dev->evbit); /* declare the event codes that our virt mouse produces */ set_bit(REL_X, vms_input_dev->relbit); // rel 'x' movement set_bit(REL_Y, vms_input_dev->relbit); // rel 'y' movement #if 0 // If your virtual mouse is also capable of generating button clicks, you need to add this set_bit(EV_KEY, vms_input_dev->evbit); /* Event Type is EV_KEY */ set_bit(BTN_0, vms_input_dev->keybit); /* Event Code is BTN_0 */ #endif // LDM: register with a kernel framework; here we register with the input subsystem stat = input_register_device(vms_input_dev); if (stat) { input_free_device(vms_input_dev); goto out3; } pr_info("Virtual Mouse Driver Initialized.\n"); return 0; /* success */ out3: device_remove_file(&sysfs_demo_platdev->dev, &dev_attr_vms); out2: platform_device_unregister(sysfs_demo_platdev); out1: return stat; } static void __exit input_drv_mouse_cleanup(void) { /* Unregister from kernel input framework */ input_unregister_device(vms_input_dev); /* Cleanup sysfs nodes */ device_remove_file(&sysfs_demo_platdev->dev, &dev_attr_vms); /* Unregister the (dummy) platform device */ platform_device_unregister(sysfs_demo_platdev); pr_info("removed\n"); } module_init(input_drv_mouse_init); module_exit(input_drv_mouse_cleanup);
C
#include "mpi.h" #include <stdio.h> #include <stdlib.h> #include "../helper.c" #include "../init.c" MPI_Status status; double A[m][n], x[n], b[m]; int main(int argc, char **argv) { int num_procs, my_rank, num_workers, rows; int i, j, from_file, print_flag; double start, start_node, start_calc, start_comm_1, start_comm_2; double stop, stop_node, stop_calc, stop_comm_1, stop_comm_2; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &num_procs); MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); from_file = atoi(argv[1]); print_flag = atoi(argv[2]); if (my_rank == 0) { if (from_file) { read_matrix(m, n, A, argv[3], " "); read_vector(n, x, argv[4], " "); } else { if (print_flag) { printf("Perkalian matriks (%dx%d) vektor (%dx1) I . x = b\n", n, n, n); } init_matrix_i(n, A); init_vector(n, x); } } start = MPI_Wtime(); rows = m / num_procs; double recA[rows][n]; double sendb[rows]; start_comm_1 = MPI_Wtime(); MPI_Bcast(&x, n, MPI_DOUBLE, 0, MPI_COMM_WORLD); MPI_Scatter(&A, rows*n, MPI_DOUBLE, &recA, rows*n, MPI_DOUBLE, 0, MPI_COMM_WORLD); stop_comm_1 = MPI_Wtime(); start_calc = MPI_Wtime(); for (i=0; i<rows; i++) { sendb[i] = 0.0; for (j=0; j<n; j++) { sendb[i] = sendb[i] + recA[i][j] * x[j]; } } if (my_rank == 0) { for (i=rows*num_procs; i<m; i++) { b[i] = 0.0; for (j=0; j<n; j++) { b[i] = b[i] + A[i][j] * x[j]; } } } stop_calc = MPI_Wtime(); start_comm_2 = MPI_Wtime(); MPI_Gather(&sendb, rows, MPI_DOUBLE, &b, rows, MPI_DOUBLE, 0, MPI_COMM_WORLD); stop_comm_2 = MPI_Wtime(); stop = MPI_Wtime(); if (print_flag) { char *ptr = "Process %d, calculation: %.9f s, Bcast-Scatter: %.9f s, Gather: %.9f s\n"; printf(ptr, my_rank, stop_calc-start_calc, stop_comm_1-start_comm_1, my_rank, stop_comm_2-start_comm_2); } MPI_Finalize(); if (my_rank == 0) { if (!print_flag) { print_vector(m, b); } else { printf("TOTAL TIME : %.9f s\n", stop - start); } } return 0; }
C
#pragma once #include "list.h" // Сделаем стек на основе списка: struct stack { Node* head; }; typedef struct stack Stack; void stack_init(Stack* s) { s->head = list_create(); } void push(Stack* s, int x) { list_add_first(&(s->head), x); } int pop(Stack* s) { return list_remove_first(&(s->head)); } void stack_print(Stack s) { list_print(s.head); } void stack_destroy(Stack* s) { list_destroy(&(s->head)); }
C
/* ** Copyright 2012, albuer@gmail.com ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ #include <upil_config.h> #define LOG_TAG "UPIL_SM" //#define LOG_NDEBUG 0 // 0 - Enable LOGV, 1 - Disable LOGV #include <utils/Log.h> #include "state_machine.h" #include "upil.h" #define MAX_STATE_MACHINE 64 static FSM s_sm_pool[MAX_STATE_MACHINE]; static const char *event_str[] = UPIL_EVENT_STRING_TABLE; static const char *ctl_str[] = UPIL_CTL_STRING_TABLE; static const char *unknown_msg = "unknown"; extern void remove_from_list(MSG* msg); const char* msg2str(int msg) { const char* ret = unknown_msg; if (msg>=UPIL_CTL_BEGIN && msg<UPIL_CTL_MAX) ret = ctl_str[msg-UPIL_CTL_BEGIN]; else if (msg>=UPIL_EVT_BEGIN && msg<UPIL_EVT_MAX) ret = event_str[msg-UPIL_EVT_BEGIN]; return ret; } /* * ȡָ״̬ID״̬ * : * fsm - Ŀ״̬ * id - Ҫҵ״̬ID * ֵ: * ҵ򷵻״̬ * Ҳ򷵻 NULL */ static FSM_STATE* get_state(FSM* fsm, FSM_STATE_ID id) { int i=0; for (;i<fsm->size;i++) if (fsm->table[i].id==id) return &(fsm->table[i]); return NULL; } /* * ȡе״̬ * : * ֵ: * ؿ״ֵ̬ * ûп״̬򷵻 -1 */ static FSM* get_idle_fsm() { int i=0; for (;i<MAX_STATE_MACHINE;i++) if (!s_sm_pool[i].table) return &s_sm_pool[i]; return NULL; } /* * ״̬ת * ˳ǰ״̬˳ٵ״̬Ľ뺯 * : * fsm - Ŀ״̬ * id - Ҫת״̬ * ֵ: * תɹת򷵻HANDLED * ޷ҵ״̬򷵻NOT_HANDLED */ static int transition_to(FSM* fsm, FSM_STATE_ID id) { FSM_STATE* new_state; ENTER_LOG(); if (fsm->cur_state && fsm->cur_state->id == id) { upil_warn("Same state, not transition\n"); LEAVE_LOG(); return HANDLED; } new_state = get_state(fsm, id); if (!new_state) { upil_error("unknown state(%d), can't transition to it\n", id); LEAVE_LOG(); return NOT_HANDLED; } upil_dbg("[%s]: State transition [%s] -> [%s]\n", fsm->name, fsm->cur_state?fsm->cur_state->name:"NULL", new_state->name); if (fsm->cur_state && fsm->cur_state->exit_func) { upil_dbg("Execute exit func"); fsm->cur_state->exit_func(fsm); } // תµ״̬ fsm->cur_state = new_state; if (fsm->cur_state->enter_func) { upil_dbg("Execute enter func"); fsm->cur_state->enter_func(fsm); } // ƳٵϢ process_defer_msg(&fsm->handler.defer_msg_queue); LEAVE_LOG(); return HANDLED; } /* * ¼ָ״̬ĵǰ״̬ȥ * : * fsm - Ŀ״̬ * event - ¼ * ֵ: * ɣ HANDLED * ޷ NOT_HANDLED */ static int process_msg(FSM* fsm, MSG* msg) { int ret = HANDLED; ENTER_LOG(); if (fsm->cur_state && fsm->cur_state->process_func) { upil_dbg("[%s]: in [%s] process %s(%d)\n", fsm->name, fsm->cur_state->name, msg2str(msg->what), msg->what); // õǰ״̬¼Ϣ ret = fsm->cur_state->process_func(fsm, msg); } LEAVE_LOG(); return ret; } /* ״̬Ϣڴ˷ַ״̬ȥ 0 ֵ <0 ʱ˳״̬ */ int sm_process_message(int fd, short flags, void *param) { int ret = HANDLED; MSG* msg = (MSG*)param; ENTER_LOG(); upil_dbg("Process msg(%p) event(%p) what(%d)", msg, &msg->ev, msg->what); // ϢӶƳ remove_from_list(msg); if (msg->what==UPIL_EVT_SM_TRANSITION) // ״̬ת ret = transition_to((FSM*)msg->handler->owner, *((int*)msg->data)); else // Ϣ ret = process_msg((FSM*)msg->handler->owner, msg); upil_printf(MSG_MSGDUMP, "free msg(%p)", msg); // ͷ free(msg); LEAVE_LOG(); return (ret==HANDLED)?0:-1; } /* ֵ: 0 - Ϣͳɹ -1 - Ϣʧ */ int sm_send_message_delay(HANDLER* handler, int what, void* data, int data_size, int msec) { MSG* msg = NULL; ENTER_LOG(); msg = sm_obtain_message(handler, what, data, data_size); if (msg) send_message_delay(msg, msec); LEAVE_LOG(); return msg?0:-1; } /* * ״̬ת * : * fsm - Ŀ״̬ * id - Ŀ״̬ * ֵ: * ɣ HANDLED * ޷ NOT_HANDLED */ int sm_transition_to(FSM* fsm, FSM_STATE_ID id) { int ret = 0; ENTER_LOG(); ret = sm_send_message_delay(&fsm->handler, UPIL_EVT_SM_TRANSITION, (void*)&id, sizeof(id), 0); LEAVE_LOG(); return ret; } int sm_set_init_state(FSM* fsm, FSM_STATE_ID id) { int ret = 0; ENTER_LOG(); ret = transition_to(fsm, id); LEAVE_LOG(); return ret; } // FSMɾָϢIDϢ void sm_remove_message_id(FSM* fsm, int what) { remove_message_id(&fsm->handler.msg_queue, what); remove_message_id(&fsm->handler.defer_msg_queue, what); } /* * ͨúȡһе״̬ * : * table - ״̬״̬б * size - ״̬бС * ֵ: * ط䵽״̬ * ʧܣ򷵻 NULL */ FSM* sm_obtain_fsm(FSM_STATE* table, int size) { FSM* fsm = NULL; ENTER_LOG(); upil_info("obtain FSM."); if ((fsm=get_idle_fsm()) != NULL) { upil_info("start handler for the FSM."); if (start_handler(&fsm->handler, sm_process_message)) { LEAVE_LOG(); return NULL; } fsm->handler.owner = (void*)fsm; fsm->table = table; fsm->size = size; fsm->cur_state = NULL; fsm->name[0] = '\0'; } else upil_error("*** No IDLE FSM!"); LEAVE_LOG(); return fsm; } // ڽʱmainУʼ״̬ void sm_init_pool(void) { int i=0; ENTER_LOG(); upil_info("Init FSM pool"); for (;i<MAX_STATE_MACHINE;i++) { s_sm_pool[i].name[0] = '\0'; s_sm_pool[i].table = NULL; s_sm_pool[i].size = 0; s_sm_pool[i].cur_state = NULL; } LEAVE_LOG(); }
C
#include "file_writer.h" FILE* open_log_file(char *path) { FILE* fp = fopen(path,"a"); return fp; } void write_log_to_file(FILE* file, unsigned long long free_memory) { if (file) { fprintf(file,"free_memory=%llu\n",free_memory); } } void close_log_file(FILE* file) { if (file) { fclose(file); } }
C
#include "Polygon.h" //polygon logic AlesiaPolygon* alesia__polygon__createPolygon(float x,float y) { AlesiaPolygon* result = calloc(sizeof(AlesiaPolygon),1); result->next = NULL; result->vertex = NULL; result->vertexCount = 0; result->initX = x; result->initY = y; result->lastX = x; result->lastY = y; result->minHeight = y; result->maxHeight = y; result->minWidth = x; return result; } void alesia__polygon__destroyPolygon(AlesiaPolygon* polygon) { if(polygon->next != NULL) alesia__polygon__destroyPolygon(polygon->next); free(polygon->vertex); free(polygon); } void alesia__polygon__addLine(AlesiaPolygon* polygon,int x2,int y2) { AlesiaVertex vertex; vertex.type = ALESIA_LINE; vertex.begin = priv__alesia__makePoint(polygon->lastX,polygon->lastY); vertex.end = priv__alesia__makePoint(x2,y2); priv__alesia__polygon__addVertex(polygon,vertex); polygon->lastX = x2; polygon->lastY = y2; polygon->maxHeight = MAX(polygon->maxHeight,y2); polygon->minHeight = MIN(polygon->minHeight,y2); polygon->minWidth = MIN(polygon->minWidth,x2); } void priv__alesia__polygon__addVertex(AlesiaPolygon* polygon,AlesiaVertex newVertex) { polygon->vertexCount++; polygon->vertex = realloc(polygon->vertex,polygon->vertexCount * sizeof(AlesiaVertex)); polygon->vertex[polygon->vertexCount - 1] = newVertex; } void alesia__polygon__addCurve(AlesiaPolygon* polygon,float xc,float yc,float xc2,float yc2,int endX,int endY) { AlesiaVertex vertex; vertex.type = ALESIA_BEZIER; vertex.begin = priv__alesia__makePoint(polygon->lastX,polygon->lastY); vertex.end = priv__alesia__makePoint(endX,endY); vertex.xc2 = xc2; vertex.yc2 = yc2; vertex.xc = xc; vertex.yc = yc; vertex.bezier.p1 = vertex.begin; vertex.bezier.p4 = vertex.end; vertex.bezier.p2 = priv__alesia__makePoint(xc,yc); vertex.bezier.p3 = priv__alesia__makePoint(xc2,yc2); priv__alesia__polygon__addVertex(polygon,vertex); polygon->lastX = endX; polygon->lastY = endY; polygon->minHeight = MIN(polygon->minHeight,yc); polygon->minHeight = MIN(polygon->minHeight,yc2); polygon->minHeight = MIN(polygon->minHeight,endY); polygon->maxHeight = MAX(polygon->maxHeight,yc); polygon->maxHeight = MAX(polygon->maxHeight,yc2); polygon->maxHeight = MAX(polygon->maxHeight,endY); polygon->minWidth = MAX(polygon->minWidth,xc); polygon->minWidth = MAX(polygon->minWidth,xc2); polygon->minWidth = MAX(polygon->minWidth,endX); } int priv__alesia__isPointInPolygon(AlesiaPolygon* polygon,float x,float y) { AlesiaVertex fakeVertex; fakeVertex.type = ALESIA_LINE; fakeVertex.begin.y = y; fakeVertex.begin.x = -100000; fakeVertex.end = priv__alesia__makePoint(x,y); int i; unsigned int collision = 0; for(i = 0; i < polygon->vertexCount;i++) { AlesiaPoint point[10]; if(priv__alesia__vertexIntersect(fakeVertex,polygon->vertex[i],&point) > 0) collision++; } if(collision % 2 == 0) return FALSE; return TRUE; } AlesiaPolygon* priv__alesia__operatePolygon(AlesiaOperation op,AlesiaPolygon* base,AlesiaPolygon* operand) { AlesiaPolygon* result = alesia__polygon__createPolygon(base->initX,base->initY); int i,j; for(i = 0; i < base->vertexCount;i++) { for(j = 0;j < operand->vertexCount;j++) { AlesiaVertex* operandVertex = &operand->vertex[j]; AlesiaVertex* baseVertex = &base->vertex[i]; AlesiaPoint points[10]; int collisionCount = priv__alesia__vertexIntersect(*operandVertex,*baseVertex,&points); int k; for(k = 0;k < collisionCount;k += 2) { AlesiaVertex newVertex; AlesiaPoint p1; AlesiaPoint p2 = points[k]; if(k == 0) p1 = operandVertex->begin; else if(k == collisionCount - 1) p1 = operandVertex->end; else p1 = points[k - 1]; //we split the operand vertice if(baseVertex->type == ALESIA_LINE) { if(operandVertex->type == ALESIA_LINE) { newVertex.type = ALESIA_LINE; newVertex.begin = p1; newVertex.end = p2; } else if(operandVertex->type == ALESIA_BEZIER) { newVertex.type = ALESIA_BEZIER; newVertex.begin = p1; newVertex.end = p2; newVertex.bezier.p1 = p1; newVertex.bezier.p4 = p2; AlesiaBezier split1; AlesiaBezier split2; float ts[5]; int tCount = priv__alesia__getBezierTForValue(operandVertex->bezier.p1.x,operandVertex->bezier.p2.x,operandVertex->bezier.p3.x,operandVertex->bezier.p4.x,p1.x,&ts); if(tCount > 0) { float t = ts[0]; //so 0, but it might not be the 0 index one priv__alesia__splitBezier(operandVertex->bezier,t,&split1,&split2); newVertex.bezier.p2 = split1.p2; newVertex.bezier.p3 = split2.p3; } } } priv__alesia__polygon__addVertex(result,newVertex); } if(collisionCount == 0) //No collision we add the vertex directly { //one condition that lines is not exactly inside the shape //if the points is in the shape, we remove the vertex completely if(priv__alesia__isPointInPolygon(base,operandVertex->begin.x,operandVertex->begin.y) == FALSE) { priv__alesia__polygon__addVertex(result,*baseVertex); } } } } return result; } int priv__alesia__vertexIntersect(AlesiaVertex v1,AlesiaVertex v2,AlesiaPoint* points) { AlesiaPoint* p1 = NULL; AlesiaPoint* p2 = NULL; AlesiaPoint* p3 = NULL; AlesiaPoint* p4 = NULL; AlesiaBezier* bez1 = NULL; AlesiaBezier* bez2 = NULL; if(v1.type == ALESIA_LINE) { p1 = &v1.begin; p2 = &v1.end; } else if(v1.type == ALESIA_BEZIER) { bez1 = &v1.bezier; } if(v2.type == ALESIA_LINE) { if(p1 == NULL) { p1 = &v2.begin; p2 = &v2.end; } else { p3 = &v2.begin; p4 = &v2.end; } } else if(v2.type == ALESIA_BEZIER) { if(bez1 == NULL) bez1 = &v2.bezier; else bez2 = &v2.begin; } if(bez1 != NULL & bez2 != NULL) return priv__alesia__bezierBezierIntersect(*bez1,*bez2,points); else if(p1 != NULL && p3 != NULL) return priv__alesia__lineIntersect(*p1,*p2,*p3,*p4,points); return priv__alesia__bezierLineIntersect(*p1,*p2,*bez1,points); }
C
/* -*- C -*- */ #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #define WPIPE "\\\\.\\pipe\\oskTERM" int main(int argc, char *argv[]) { HANDLE hPipe = INVALID_HANDLE_VALUE; char input[80]; printf("Running as %s\n", argv[0]); if( !strcmp(argv[0],"send") ) { hPipe = CreateNamedPipe(WPIPE, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, 512, 512, 0, NULL); if (hPipe == INVALID_HANDLE_VALUE) { printf(TEXT("CreateNamedPipe failed, GLE=%d.\n"), GetLastError()); return -1; } gets(input); write(hPipe, input, strlen(input)); CloseHandle(hPipe); } else { hPipe = open(WPIPE, 0666); if( hPipe == INVALID_HANDLE_VALUE ) { perror("open"); return -1; } read(hPipe, input, 80); printf("Read: '%s'\n", input); CloseHandle(hPipe); } return 0; }
C
/* program 12 transpose of sparse matrix mohammed jasim e 31/3/15 s1337 */ #include <stdio.h> #define MAX 40 void read(int s[][3]); void display_sparse(int [][3]); void transpose(int [][3], int [][3]); void display(int [][3]); int main() { int a[MAX][3], b[MAX][3]; int flag; printf("Enter the order of the matrix\n"); read(a); printf("\n\nORIGINAL MATRIX: \n"); printf("Sparse Matrix Form\n"); display_sparse(a); transpose(a,b); printf("\n\nTRANSPOSE OF THE MATRIX: \n"); printf("\tSparse Matrix Form\n"); display_sparse(b); printf("\tMatrix Form\n"); display(b); return 0; } void read(int s[][3]) { int i, j, k=0, in; scanf("%d%d", &s[0][0], &s[0][1]); printf("Enter elements\n"); for(i=0; i<s[0][0]; i++) for(j=0; j<s[0][1]; j++) { scanf("%d", &in); if( in != 0 ) { k++; s[k][0] = i; s[k][1] = j; s[k][2] = in; } } s[0][2] = k; } void display_sparse(int s[][3]) { int i, j; for( i=0; i < s[0][2] + 1; i++) { for(j=0; j<3; ++j) printf("%3d", s[i][j]); printf("\n"); } } void transpose(int a[][3], int b[][3]) { int i, j, k=1; b[0][0] = a[0][1]; b[0][1] = a[0][0]; b[0][2] = a[0][2]; for( i = 0; i < a[0][1]; ++i) for( j = 0; j <= a[0][2]; ++j) { if(a[j][1] == i) { b[k][1] = a[j][0]; b[k][0] = i; b[k++][2] = a[j][2]; } } } void display(int a[][3]) { int i, j, k=1; for( i=j=0; i < a[0][0];++i) { for(j=0; j < a[0][1]; ++j) if( i == a[k][0] && j == a[k][1] ) printf("%3d", a[k++][2]); else printf("%3d", 0); printf("\n"); } } /* OUTPUT Enter the order of the matrix 3 3 Enter elements 11 22 33 0 0 0 44 0 0 ORIGINAL MATRIX: Sparse Matrix Form 3 3 4 0 0 11 0 1 22 0 2 33 2 0 44 TRANSPOSE OF THE MATRIX: Sparse Matrix Form 3 3 4 0 0 11 0 2 44 1 0 22 2 0 33 Matrix Form 11 0 44 22 0 0 33 0 0 */
C
#include <stdio.h> #include <stdlib.h> int ser(int *x, int lo, int up, int y); int main(void) { int array[10] = { 2,3,8,9,55,22,33,44,77,88 }; printf(" %d", ser(array,0,9,77)); system("pause"); return 0; } int ser(int *x, int lo, int up, int y) { if(lo<=up) { int mid =lo+ (up-lo) / 2; if (y == x[mid]) { return mid; } else if(y< x[mid]) { return ser(x, lo, mid - 1, y); } else { return ser(x, mid + 1, up, y); } } else { return -1; } }
C
#include "../includes/redNeuronal.h" #include <time.h> #include <math.h> /*ESTA VARIBLE SE USA PARA LAS CONDICIONES DE PARADA*/ redNeuronal* redpre=NULL; int etapa=0; double ecmAnt, ecmAhr; redNeuronal* iniRedPerceptron(int entrada, int oculta,int salida, double tasa){ double* pesos= NULL,** salidas= NULL; int i=0, j=0; redNeuronal* red=NULL; if( entrada==0 || salida==0 ) return NULL; if(red==NULL){ red= malloc(sizeof(redNeuronal)); } srand(time(NULL)); red->entradas=entrada; red->salidas=salida; red->ocultas=0; red->tasa=tasa; red->neuronas=malloc(sizeof(neurona)*(1+entrada+salida)); for(i =0; i< (1+entrada+salida); i++){ iniNeurona2( &(red->neuronas[i])); } /*INICIALIZACION NEURONAS DE ENTRADA*/ for(i=0; i<entrada; i++){ setNeurona(&red->neuronas[i], 0.0, 0, NULL, NULL); } /*INICIALIZACION NEURONA DE SESGO*/ setNeurona(&red->neuronas[entrada], 0, 0, NULL, NULL); actualizaNeuronaEntrada(&(red->neuronas[entrada]), 1.0); /*INICIALIZACION NEURONAS DE SALIDA*/ pesos= (double*) malloc(sizeof(double)*(entrada+1)); salidas= (double**) realloc(salidas, sizeof(double*)*(entrada+1)); for(i=0; i<entrada+1; i++){ salidas[i]= &(red->neuronas[i]).salida; } for(i=1+entrada; i<salida+1+entrada; i++){ for(j=0; j<entrada+1; j++){ if(aleat!=0) pesos[j]= (double)rand()/(double)RAND_MAX -0.5; else pesos[j]=0; } setNeurona(&red->neuronas[i], aleat!=0 ? (double)rand()/(double)RAND_MAX -0.5 : 0, entrada+1, pesos, salidas); } free(pesos); free(salidas); return red; } redNeuronal* iniRedRetropropagacion(int entrada, int oculta,int salida, double tasa){ double* pesos= NULL,** salidas= NULL; int i=0, j=0; redNeuronal* red=NULL; if( entrada==0 || salida==0 ) return NULL; if(red==NULL){ red= malloc(sizeof(redNeuronal)); } srand(time(NULL)); red->entradas=entrada; red->salidas=salida; red->ocultas=oculta; red->tasa=tasa; red->neuronas=malloc(sizeof(neurona)*(2+entrada+salida+oculta)); for(i =0; i< (1+entrada+salida); i++){ iniNeurona2( &(red->neuronas[i])); } /*INICIALIZACION NEURONAS DE ENTRADA*/ for(i=0; i<entrada; i++){ setNeurona(&red->neuronas[i], 0.0, 0, NULL, NULL); } /*INICIALIZACION NEURONA DE SESGO*/ setNeurona(&red->neuronas[entrada], 0, 0, NULL, NULL); actualizaNeuronaEntrada(&(red->neuronas[entrada]), 1.0); /**/ /*INICIALIZACION NEURONAS DE OCULTA*/ pesos= (double*) malloc(sizeof(double)*(entrada+2)); salidas= (double**) realloc(salidas, sizeof(double*)*(entrada+2)); for(i=0; i<entrada+2; i++){ salidas[i]= &(red->neuronas[i]).salida; } for(i=1+entrada; i<oculta+1+entrada; i++){ for(j=0; j<entrada+1; j++){ pesos[j]= (double)rand()/(double)RAND_MAX -0.5; } setNeurona(&red->neuronas[i], 0, entrada+1, pesos, salidas); } setNeurona(&red->neuronas[entrada+oculta+1], 0, 0, NULL, NULL); actualizaNeuronaEntrada(&(red->neuronas[entrada+oculta+1]), 1.0); /*cambiado entrada por oculta*/ /*INICIALIZACION NEURONAS DE SALIDA*/ pesos= (double*) realloc(pesos, sizeof(double)*(oculta+1)); salidas= (double**) realloc(salidas, sizeof(double*)*(oculta+1)); for(i=0; i<oculta+1; i++){ salidas[i]= &(red->neuronas[i+entrada+1]).salida; } /*Añadido el "+oculta"*/ for(i=2+entrada+oculta; i<salida+2+entrada+oculta; i++){ for(j=0; j<1+oculta; j++){ pesos[j]= (double)rand()/(double)RAND_MAX -0.5; } setNeurona(&red->neuronas[i], 0, 1+oculta, pesos, salidas); } free(pesos); free(salidas); return red; } void destRed1(redNeuronal* red){ int i=0, n=0; if(red->ocultas == 0){ n= 1+ red->entradas + red->salidas ; }else{ n= 2+ red->entradas + red->salidas + red->ocultas; } for(i=0; i<n; i++){ destroyNeurona(&red->neuronas[i]); } free(red->neuronas); free(red); } void destRed2(redNeuronal* red){ int i=0, n=0; if(red->ocultas == 0){ n= 1+ red->entradas + red->salidas ; }else{ n= 2+ red->entradas + red->salidas + red->ocultas; } n= 1+ red->entradas + red->salidas +red->ocultas; for(i=0; i<n; i++){ destroyNeurona(&(red->neuronas[i])); } free(red->neuronas); } int copiaRed(const redNeuronal* redIn, redNeuronal* redOut){ int numNeu1=0, i=0; if (redIn==NULL|| redOut==NULL){ return 1; } numNeu1= 1+ redIn->entradas + redIn->salidas + redIn->ocultas; redOut->neuronas= malloc(sizeof(neurona)*numNeu1); for(i=0 ; i<numNeu1;i++){ iniNeurona2(&redOut->neuronas[i]); } redOut->entradas= redIn->entradas; redOut->salidas= redIn->salidas; redOut->ocultas= redIn->ocultas; redOut->tasa= redIn->tasa; /*COPIAMOS LA RED*/ for(i=0; i< numNeu1; i++){ copiaNeurona(&redIn->neuronas[i], &redOut->neuronas[i]); } return 0; } int actualizaSalida(redNeuronal* red, double (*fActualizacion)(neurona*), double* entrada){ int i = 0; if ((red == NULL) || (fActualizacion == NULL) || (entrada == NULL)){ return 1; } /*printf("actualiza neuronas de entrada\n"); */for(i = 0 ; i < red->entradas ; i++) actualizaNeuronaEntrada(&(red->neuronas[i]), entrada[i]); /*printf("actualiza neuronas de salida\n"); */ if(red->ocultas > 0){ for(i = red->entradas+1 ; i < (red->entradas + red->ocultas + red->salidas +2); i++){ (*fActualizacion)(&(red->neuronas[i])); } } else{ for(i = red->entradas+1 ; i < (red->entradas + red->salidas)+1 ; i++){ (*fActualizacion)(&(red->neuronas[i])); } } return 0; } int actualizaSalida2(redNeuronal* red, double (*fActualizacion)(neurona*), double* entrada){ int i = 0; if ((red == NULL) || (fActualizacion == NULL) || (entrada == NULL)){ return 1; } /*printf("actualiza neuronas de entrada\n"); */for(i = 0 ; i < red->entradas ; i++) actualizaNeuronaEntrada(&(red->neuronas[i]), entrada[i]); /*printf("actualiza neuronas de salida\n"); */ if(red->ocultas > 0){ for(i = red->entradas+1 ; i < (red->entradas + red->ocultas + red->salidas +2); i++){ if (i < red->entradas + red->ocultas + 2){ (*fActualizacion)(&(red->neuronas[i])); } else{ actualizaNeuronaLineal(&(red->neuronas[i])); } } } else{ for(i = red->entradas+1 ; i < (red->entradas + red->salidas)+1 ; i++){ (*fActualizacion)(&(red->neuronas[i])); } } return 0; } double actualizaPesosPerceptron(redNeuronal* red, double* t){ int i=0, j=0; double val=0; if(red==NULL || t==NULL){ return 1; } for(i=0; i<red->salidas; i++){ /*printf("esp:%d res:%1.1f\n", t[i], red->neuronas[i+1+red->entradas].salida); */ val=red->neuronas[i+1+red->entradas].salida; if( (t[i]==0 && val!=0) || (t[i]==-1 && val!=-1) || (t[i]==1 && val!=1)){ /*printf("se reajusta la salida %d\n", i); */for(j=0; j<red->entradas; j++){ (&red->neuronas[i+1+red->entradas])->pesos[j]+= red->tasa*t[i]*red->neuronas[j].salida; /*printf("j=%d %2.4f ", j, (&red->neuronas[i+1+red->entradas])->pesos[j]); */ } (&red->neuronas[i+1+red->entradas])->pesos[j]+= red->tasa*t[i]; /*printf("j=%d %2.4f\n", j, (&red->neuronas[i+1+red->entradas])->pesos[j]); */ } } return 0; } double actualizaPesosAdaline(redNeuronal* red, double* t){ int i=0, j=0; double esperado=0, prediccion=0; if(red==NULL || t==NULL){ return 1; } for(i=0; i<red->salidas; i++){ esperado= t[i]; prediccion=red->neuronas[i+red->entradas+1].salida; /*printf("se reajusta la salida %d\n", i); */for(j=0; j<red->entradas+1; j++){ (&red->neuronas[i+1+red->entradas])->pesos[j]+= red->tasa* (esperado - prediccion)* (*red->neuronas[i+1+red->entradas].entradas[j]); /*printf("j=%d %2.4f ", j, (&red->neuronas[i+1+red->entradas])->pesos[j]); */ } /*printf("j=%d %2.4f\n", j, (&red->neuronas[i+1+red->entradas])->pesos[j]); */ } return 0; } double actualizaPesosRetropropagacion(redNeuronal* red, double* t){ double delta = 0.0; int i = 0, j = 0, k=0; double ecm=0, prediccion=0, esperado=0; /*DELTAS DE SALIDA*/ for(i = 2 + red->ocultas + red->entradas, j = 0; i < 2 + red->salidas + red->ocultas + red->entradas; ++i, j++){ prediccion = red->neuronas[i].salida; esperado = (double)t[j]; ecm += pow(esperado - prediccion,2); delta = esperado - prediccion; delta *= 0.5 * (1 -prediccion); delta *= (1 + prediccion); (&red->neuronas[i])->delta = delta; } /*DELTAS DE OCULTA*/ for(k=0, i = 1 + red->entradas; i < 1 + red->entradas + red->ocultas; ++i, k++){ delta = 0; prediccion=red->neuronas[i].salida; for(j = red->entradas + 2 + red->ocultas; j < red->salidas + red->entradas + 2 + red->ocultas; ++j){ delta += red->neuronas[j].delta * red->neuronas[j].pesos[k]; } delta *= 0.5 * (1 + prediccion); delta *= (1 - prediccion); (&red->neuronas[i])->delta = delta; } /*PESOS DE SALIDA*/ for(i = 2+red->entradas+red->ocultas; i < 2+red->entradas+red->ocultas+red->salidas; ++i){ for(j = 0; j < red->neuronas[i].nentradas; ++j){ (&red->neuronas[i ])->pesos[j] += red->tasa * red->neuronas[i].delta * (*red->neuronas[i].entradas[j]); } } /*PESOS DE OCULTA*/ for(i = 1+red->entradas; i < 1+red->entradas+red->ocultas; ++i){ for(j = 0; j < red->neuronas[i].nentradas; ++j){ (&red->neuronas[i])->pesos[j] += red->tasa * red->neuronas[i].delta * (*red->neuronas[i].entradas[j]); } } return ecm; } double actualizaPesosRetropropagacion2(redNeuronal* red, double* t){ double delta = 0.0; int i = 0, j = 0, k=0; double ecm=0, prediccion=0, esperado=0; /*DELTAS DE SALIDA*/ for(i = 2 + red->ocultas + red->entradas, j = 0; i < 2 + red->salidas + red->ocultas + red->entradas; ++i, j++){ prediccion = red->neuronas[i].salida; esperado = (double)t[j]; ecm += pow(esperado - prediccion,2); delta = esperado - prediccion; (&red->neuronas[i])->delta = delta; } /*DELTAS DE OCULTA*/ for(k=0, i = 1 + red->entradas; i < 1 + red->entradas + red->ocultas; ++i, k++){ delta = 0; prediccion=red->neuronas[i].salida; for(j = red->entradas + 2 + red->ocultas; j < red->salidas + red->entradas + 2 + red->ocultas; ++j){ delta += red->neuronas[j].delta * red->neuronas[j].pesos[k]; } delta *= 0.5 * (1 + prediccion); delta *= (1 - prediccion); (&red->neuronas[i])->delta = delta; } /*PESOS DE SALIDA*/ for(i = 2+red->entradas+red->ocultas; i < 2+red->entradas+red->ocultas+red->salidas; ++i){ for(j = 0; j < red->neuronas[i].nentradas; ++j){ (&red->neuronas[i ])->pesos[j] += red->tasa * red->neuronas[i].delta * (*red->neuronas[i].entradas[j]); } } /*PESOS DE OCULTA*/ for(i = 1+red->entradas; i < 1+red->entradas+red->ocultas; ++i){ for(j = 0; j < red->neuronas[i].nentradas; ++j){ (&red->neuronas[i])->pesos[j] += red->tasa * red->neuronas[i].delta * (*red->neuronas[i].entradas[j]); } } return ecm; } int paradaPerceptron(redNeuronal* red){ int i=0, j=0, num=0; if(redpre==NULL){ redpre=malloc(sizeof(redNeuronal)); redpre->entradas=0; redpre->ocultas=0; redpre->salidas=0; copiaRed(red, redpre); etapa=0; return 1; } if(etapa==maxEtapas){ destRed1(redpre); redpre=NULL; return 0; } if(etapa%100==0) printf("etapa:%d\n", etapa); num=1 + red->entradas + red->salidas; for(i=0; i< num; i++){ for(j=0;j<red->neuronas[i].nentradas; j++){ if(red->neuronas[i].pesos[j] != redpre->neuronas[i].pesos[j]){ destRed2(redpre); copiaRed(red, redpre); etapa++; return 1; } } } printf("etapa2:%d\n", etapa); /*destRed2(redpre); */free(redpre); redpre=NULL; return 0; } int paradaAdaline(redNeuronal* red){ int i=0, j=0, num=0; if(redpre==NULL){ redpre=malloc(sizeof(redNeuronal)); redpre->entradas=0; redpre->ocultas=0; redpre->salidas=0; copiaRed(red, redpre); etapa=0; return 1; } if(etapa==maxEtapas){ destRed1(redpre); redpre=NULL; return 0; } if(etapa%100==0) printf("etapa:%d\n", etapa); num=1 + red->entradas + red->salidas; for(i=0; i< num; i++){ for(j=0;j<red->neuronas[i].nentradas; j++){ if(red->neuronas[i].pesos[j] > redpre->neuronas[i].pesos[j] + maxTolerancia || red->neuronas[i].pesos[j] < redpre->neuronas[i].pesos[j] - maxTolerancia){ destRed2(redpre); copiaRed(red, redpre); etapa++; return 1; } } } printf("etapa2:%d\n", etapa); destRed1(redpre); redpre=NULL; return 0; } double absolute(double val){ if(val<0) return -val; return val; } int paradaRetropropagacion2(redNeuronal* red){ if (etapa ==0){ ecmAnt=ecmAhr; etapa++; return 1; } if (etapa==maxEtapas) return 0; etapa++; if(absolute(ecmAhr -ecmAnt)>maxTolerancia){ if(etapa%100==0) printf("etapa %d %1.8f ecm:%1.4f\n", etapa, absolute(ecmAnt - ecmAhr), ecmAhr); ecmAnt=ecmAhr; return 1; } return 0; } int paradaRetropropagacion(redNeuronal* red){ if (etapa ==0){ ecmAnt=ecmAhr; etapa++; return 1; } if (etapa==maxEtapas) return 0; etapa++; if(absolute(1.0 - ecmAhr/ecmAnt)>maxTolerancia){ if(etapa%100==0) printf("etapa %d %1.8f ecm:%1.4f\n", etapa, absolute(1.0 - ecmAhr/ecmAnt), ecmAhr); ecmAnt=ecmAhr; return 1; } return 0; } redNeuronal* redTrain(int tentrada, datos* data, redNeuronal* (*fini)(int, int, int, double), int (*fsalida) (redNeuronal*, double (*fActualizacion)(neurona*), double*), int (*fParada) (redNeuronal*), double (*fPesos) (redNeuronal*, double*), double (*fActualizacion)(neurona*), int nentreada, int nsalida, int noculta, double tasa){ redNeuronal* red= NULL; int i=0, fallos=0; FILE * f=NULL,* fecm=NULL; double ecm=0; if(data==NULL || nentreada==0 || nsalida==0){ printf("algo raro aha pasado\n"); printf("%d\n", nentreada); printf("%d\n", nsalida); return NULL; } red =(*fini)(nentreada, noculta, nsalida, tasa); if(red==NULL){ return NULL; } f=fopen("adaptacion.data", "w"); fecm=fopen("ecm.data", "w"); while((*fParada)(red)){ /*QUITAR ESO PARA LA ENTREGA*/ fallos=redTest(adapt, red,fsalida, fActualizacion); fprintf(f, "%2.4f\n", (double)fallos/(double)data->ndatos); /**/ for(i=0, ecm=0; i<data->ndatos; i++){ (*fsalida) (red, (*fActualizacion), data->atributos[i]); ecm+=(*fPesos) (red, data->clase[i]); } ecmAhr=ecm/(data->ndatos*data->nclases); fprintf(fecm, "%1.6f\n",ecm/(data->ndatos*data->nclases) ); } fclose(fecm); fclose(f); return red; } double redTest(datos* data, redNeuronal* red, int (*fsalida) (redNeuronal*, double (*fActualizacion)(neurona*), double*), double (*fActualizacion)(neurona*)){ int i=0, j=0; double res=0; int* salidas= malloc(sizeof(int) * red->salidas); for(i=0; i<data->ndatos; i++){ (*fsalida) (red, (*fActualizacion), data->atributos[i]); salidasBipolares(salidas, red); for(j=0; j < red->salidas; j++){ if(salidas[j]!=data->clase[i][j]){ res++; /*break;*/ } } } free(salidas); return res; } void salidasBipolares(int* salida, redNeuronal* red){ int i=0, pos=2 + red->entradas + red->ocultas; for(i=0; i < red->salidas ; i++){ if(red->neuronas[i+pos].salida<0) salida[i] = -1; else salida[i] = 1; } } int clasificar(datos* data, redNeuronal* red, int (*fsalida) (redNeuronal*, double (*fActualizacion)(neurona*), double*), double (*fActualizacion)(neurona*), FILE* fout){ int i=0, j=0, k=0; char s[32]=""; double maxRed=-100; int maxR=0; if(fout ==NULL || red==NULL || data==NULL) return 1; for(i=0; i<data->ndatos; i++,maxRed=INT_MIN){ (*fsalida) (red, (*fActualizacion), data->atributos[i]); for(j=0, maxRed=INT_MIN; j<data->nclases; j++){ if(red->ocultas==0){ if(maxRed<red->neuronas[j + 1 + red->entradas].salida){ maxRed= red->neuronas[j + 1 + red->entradas].salida; maxR=j; } } else{ /*printf("%1.4f ", red->neuronas[j + 2 + red->entradas+ red->ocultas].salida); */if(maxRed<red->neuronas[j + 2 + red->entradas+ red->ocultas].salida){ maxRed= red->neuronas[j + 2 + red->entradas +red->ocultas].salida; maxR=j; } } } for(j= 0; j< data->nclases; j++){ if(j==maxR) sprintf(s, "1.0 "); else sprintf(s, "-1.0 "); k=0; while(s[k]!='\0'){ printf("%s\n", s); fwrite(&s[k++], 1,1, fout); } } s[0]='\n'; fwrite(&s[0], 1,1, fout); } return 0; } int clasificarSerie(datos* data, redNeuronal* red, int (*fsalida) (redNeuronal*, double (*fActualizacion)(neurona*), double*), double (*fActualizacion)(neurona*), FILE* fout){ int i=0, j=0; if(fout ==NULL || red==NULL || data==NULL) return 1; for(i=0; i<data->ndatos; i++){ (*fsalida) (red, (*fActualizacion), data->atributos[i]); for(j=0; j<data->nclases; j++){ fprintf(fout, "%1.4f %1.4f %1.4f ", red->neuronas[j + 2 + red->entradas + red->ocultas].salida, data->atributos[i][data->natributos-1], data->clase[i][j]); } fprintf(fout, "\n"); } return 0; } int clasificarSerieRetroalimentado(datos* data, redNeuronal* red, int (*fsalida) (redNeuronal*, double (*fActualizacion)(neurona*), double*), double (*fActualizacion)(neurona*), FILE* fout){ int i=0, j=0; double* t = NULL; /*Por ahora esto es numero magico*/ int iteraciones = nf; if(fout ==NULL || red==NULL || data==NULL){ printf("fallo\n"); return 1; } t = malloc(sizeof(double) * data->natributos); for(i = 0; i < data->natributos; i++){ t[i] = data->atributos[0][i]; } for(i=0; i<iteraciones; i++){ (*fsalida) (red, (*fActualizacion), t); for(j=0; j < data->natributos; j++){ fprintf(fout, "%1.4f ", t[j]); } for(j=0; j< data->nclases; j++){ fprintf(fout, "%1.4f ", red->neuronas[j + 2 + red->entradas + red->ocultas].salida); } fprintf(fout, "%1.4f\n", data->clase[i][0]); for(j = 0; j < data->natributos; j++){ t[j]=t[j+1]; } for(j= 0; j< red->salidas; j++){ t[j +red->entradas - red->salidas] = red->neuronas[j + 2 + red->entradas + red->ocultas].salida; } } free(t); return 0; } void printSalidas(redNeuronal* red){ int i=0; printf("salida ocultas:\n"); for(i=1+red->entradas; i< 1+red->entradas+ red->ocultas; i++){ printf("%1.4f ", red->neuronas[i].salida); } printf("\nsalida de la red:\n"); for(i=2+red->entradas+ red->ocultas; i< 2+red->entradas+ red->ocultas+red->salidas; i++){ printf("%1.4f ", red->neuronas[i].salida); } printf("\n"); } void printPesos(redNeuronal * red){ int i=0, j=0; neurona n; printf("entradas %d\n", red->entradas); printf("salidas %d\n", red->salidas); printf("ocultas %d\n", red->ocultas); printf("pesos\n"); printf("ocultas:\n"); for(i=0; i< red->ocultas; i++){ n=red->neuronas[red->entradas+1 +i]; for(j=0; j<n.nentradas; j++){ printf("%1.4f ", n.pesos[j]); } printf("\n"); } printf("salidas:\n"); for(i=0; i< red->salidas; i++){ if(red->ocultas==0) n=red->neuronas[red->entradas+1 +i]; else n=red->neuronas[red->entradas+ red->ocultas +2 +i]; for(j=0; j<n.nentradas; j++){ printf("%1.4f ", n.pesos[j]); } printf("\n"); } printf("\n"); }
C
/* ** get_light.c for Raytracer2 in /rendu/semestre_02/gfx_raytracer2 ** ** Made by Ludovic Petrenko ** Login <ludonope@epitech.net> ** ** Started on Wed May 18 05:37:31 2016 Ludovic Petrenko ** Last update Sun May 22 16:12:10 2016 Ludovic Petrenko */ #include "raytracer.h" #include "tools/math.h" static void get_lum(double *col, t_scene *s, t_intersect *inter, int m) { t_vec3 l; t_vec3 r; double ln; int i; double is; double id; double dist; double rv; double tmp; t_ray ray; t_intersect shadow; i = -1; if (s->lights[m].light.type == DIRECTIONNAL) { while (++i < 3) { ln = dot_vec3(inter->norm, s->lights[m].light.dir); col[i] = MAX(ln, 0) * s->lights[m].light.color.argb[i] / 255.0 * s->lights[m].light.power; } return ; } l = sub_vec3(s->lights[m].pos, inter->pos); dist = vec3_len(l); l = div_vec3(l, dist); dist -= s->lights[m].light.radius; ln = dot_vec3(l, inter->norm); ln = MAX(ln, 0.0); r = vec3_normalize(sub_vec3(mult_vec3(inter->norm, 2 * ln), l)); is = s->lights[m].light.power / dist; id = s->lights[m].light.radius * is; rv = -dot_vec3(r, inter->dir); rv = MAX(rv, 0.0); ray.pos = add_vec3(inter->pos, mult_vec3(inter->norm, 0.00001)); ray.dir = l; ray.env = NULL; scene_intersect(s, &ray, &shadow); if (shadow.dist < dist - 0.0001) return ; while (++i < 3) { tmp = inter->mat->diffuse * MAX(ln, 0) * id * s->lights[m].light.color.argb[i] / 255.0; col[i] += MAX(tmp, 0); tmp = inter->mat->specular * pow(rv, inter->mat->shininess) * is * s->lights[m].light.color.argb[i] / 255.0; col[i] += MAX(tmp, 0); } } void get_light(t_scene *s, t_intersect *inter, double *col) { int i; int m; double max; double total; i = m = -1; while (++i < 3) col[i] = s->spec.bg_color.argb[i] / 255.0 * s->spec.ambiant; max = total = 0; while (++m < s->nb_light) { get_lum(col, s, inter, m); max = MAX(s->lights[m].light.power, max); total += s->lights[m].light.power; } i = -1; while (++i < 3) col[i] /= total / max; }
C
/******************************************************************************* ** File: ** ** TaskInput.c ** ** Contents: ** uC/OS-II programming ** ** History: ** Date Name Description ** ------------------------------------------------------------------------ ** *******************************************************************************/ #include "includes.h" #include "ui.h" extern sIMAGEINFO calcImg; // Touch 센서 성능 최적화(캘리브레이션) #define KEY_SCAN_TASK_PRIO TASK_1_PRIO /* Set priority of keyboard scan task */ void Touch_Calibration(void); // Key 함수 원형 INT8U KeyGetKey(INT16U to); void KeyInit (int prio); // TOUCH GET KEY int TOUCHGetKey(int orig_x, int orig_y); // 세마포어 extern OS_EVENT *TOUCH_SEM; extern OS_EVENT *INPUT_SEM; extern OS_EVENT *LCD_SEM; // 광역 키코드 버퍼 int KeyCode; const unsigned int TouchKeyMatrix[]={ POS_C,0xFF,0xFF,0xFF,POS_RESULT,0xFF,POS_0,POS_PLUSMINUS,0xFF,POS_PLUS, POS_BACKSPACE,POS_1,POS_2,POS_3,POS_MINUS,0xFF,POS_4,POS_5,POS_6,POS_MUL, POS_CE,POS_7,POS_8,POS_9,POS_DIV }; // // 태스크 'TaskInput' // void TaskInput(void *pdata) { char button, touchkey; pdata = pdata; /* 컴파일러 경고를 막기 위함 */ // 터치 패드 캘리브레이션 Touch_Calibration(); // KEY PORT 초기화 KeyInit(KEY_SCAN_TASK_PRIO); // 세마포어 전달(LCD_SEM) OSSemPost(LCD_SEM); for(;;) { // // timed 세마포어 대기(from TOUCH_ISR) OSTimeDly (10); // 100msec // button= KeyGetKey(10); button= 0xFF; // 세마포어 확인(from TOUCH_ISR) if(OSSemAccept(TOUCH_SEM)) { touchkey= TOUCHGetKey(calcImg.orig_x, calcImg.orig_y); if(touchkey != 0xFF) { KeyCode = touchkey; OSSemPost(INPUT_SEM); Uart_Printf("SCANKEY[TOUCH] = %d\n", KeyCode); continue; } } if(button != 0xFF) { // 세마포어 전달 KeyCode = TouchKeyMatrix[button]; if(KeyCode == 0xFF) { continue; } OSSemPost(INPUT_SEM); Uart_Printf("SCANKEY[BUTTON] = %d\n", button); } } } /*----------------------------------------------------------------------------- * Program : TaskInput.C -----------------------------------------------------------------------------*/
C
/* ID: baikaiz1 PROG: castle LANG: C */ /** * Copyright (c) 2012 ZhongLigang. All Rights Reserved * $Id$ * * @file castle.c * @author ligang <ZhongLigang@gmail.com> * @date 2012-12-18 01:35:12 */ #include <stdlib.h> #include <stdio.h> #define MAX_ROWS 50 int matrix[MAX_ROWS][MAX_ROWS][5] = {0}; int sizes[MAX_ROWS*MAX_ROWS+1] = {0}; int queue[MAX_ROWS*MAX_ROWS+1] = {0}, head = 0, tail = 0; int col, row; int room_no; int room_max = 0, remove_row, remove_col; char remove_wall; void travel() { int i, j, current; while (head < tail) { current = queue[head++]; i = current / col; j = current % col; matrix[i][j][0] = room_no; sizes[room_no]++; if (matrix[i][j][1] && j >= 1 && matrix[i][j-1][0] == 0) { matrix[i][j-1][0] = -1; queue[tail++] = i*col+j-1; } if (matrix[i][j][2] && i >= 1 && matrix[i-1][j][0] == 0) { matrix[i-1][j][0] = -1; queue[tail++] = (i-1)*col+j; } if (matrix[i][j][3] && j < col-1 && matrix[i][j+1][0] == 0) { matrix[i][j+1][0] = -1; queue[tail++] = i*col+j+1; } if (matrix[i][j][4] && i < row-1 && matrix[i+1][j][0] == 0) { matrix[i+1][j][0] = -1; queue[tail++] = (i+1)*col+j; } }; } int main(int argc, char** argv) { FILE *fin, *fout; fin = fopen("castle.in", "r"); fout = fopen("castle.out", "w"); int i, j, relation; fscanf(fin, "%d %d", &col, &row); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { matrix[i][j][0] = 0; fscanf(fin, "%d", &relation); matrix[i][j][1] = !(relation & 1); matrix[i][j][2] = !(relation & 2); matrix[i][j][3] = !(relation & 4); matrix[i][j][4] = !(relation & 8); } } room_no = 0; head = 0; tail = 0; for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { if (matrix[i][j][0] == 0) { matrix[i][j][0] = -1; queue[tail++] = i*col+j; room_no++; travel(); } } } fprintf(fout, "%d\n", room_no); int m = 0; for (i = 1; i <= room_no; i++) { if (sizes[i] > m) { m = sizes[i]; } } fprintf(fout, "%d\n", m); int room_size_1, room_size_2; for (j = 0; j < col; j++) { for (i = row - 1; i >= 0; i--) { room_size_1 = sizes[matrix[i][j][0]]; // North wall if (i >= 1) { room_size_2 = sizes[matrix[i-1][j][0]]; if (matrix[i-1][j][0] != matrix[i][j][0] && room_size_2+room_size_1 > room_max) { room_max = room_size_2+room_size_1; remove_row = i + 1; remove_col = j + 1; remove_wall = 'N'; } } // East wall if (j < col - 1) { room_size_2 = sizes[matrix[i][j+1][0]]; if (matrix[i][j+1][0] != matrix[i][j][0] && room_size_2+room_size_1 > room_max) { room_max = room_size_2+room_size_1; remove_row = i + 1; remove_col = j + 1; remove_wall = 'E'; } } } } fprintf(fout, "%d\n", room_max); fprintf(fout, "%d %d %c\n", remove_row, remove_col, remove_wall); return 0; }
C
#include <stdio.h> #include <stdalign.h> int main(int argc, char *argv[]) { (void)argc; (void)argv; #pragma pack(push, 1) struct foo { char c1; int i; char c2; }; #pragma pack(pop) struct bar { char c1; int i; char c2; }; printf("alignof int: %ld\n", alignof(int)); // 4 printf("alignof foo: %ld\n", alignof(struct foo)); // 1 printf("alignof bar: %ld\n", alignof(struct bar)); // 4 printf("sizeof int: %ld\n", sizeof(int)); // 4 printf("sizeof foo: %ld\n", sizeof(struct foo)); // 6 printf("sizeof bar: %ld\n", sizeof(struct bar)); // 12 return 0; }
C
/** 3. Analyse the following code. **/ #include <stdio.h> #include <sys/types.h> #include <unistd.h> int main(void) { fork(); fork(); fork(); printf("SCOMP!\n"); return 0; } /** * a) How many processes are created by this code? **/ /* * 7 processes and the father process. */ /** * b) Draw a process tree that describes the processes created. **/ /* * */ /** * c) How many times is “SCOMP” printed? **/ /* * 8 vezes- 1 para o processo pai e 7 para os filhos */
C
#include<stdio.h> int main() { int m,n,i; printf("Enter the value of m="); scanf("%d",&m); printf("Enter the value of n="); scanf("%d",&n); printf("Even numbers are- "); for(i=m;i<=n;i++) { if(i%2==0) { printf("%d, ",i); } } printf("\nOdd numbers are- "); for(i=m;i<=n;i++) { if(i%2!=0) { printf("%d, ",i); } } getch(); }
C
#include<stdio.h> #include<stdlib.h> void main() { int temp1,temp2,temp3,temp4,i,winsize=8,noframes,moreframes; char c; int reciever(int); int simulate(int); temp4=0,temp1=0,temp2=0,temp3=0; printf("Enter number of frames"); scanf("%d",&noframes); for(i=0;i<200;i++) moreframes=noframes; while(moreframes>=0) { temp1=simulate(winsize); winsize-=temp1; temp4+=temp1; if(temp4 >noframes) temp4 = noframes; for(i=temp3+1;i<=temp4;i++) printf("\nsending frame %d",i); temp2=reciever(temp1); temp3+=temp2; if(temp3 > noframes) temp3 = noframes; printf("\n acknowledgement for the frames up to %d",temp3); moreframes-=temp2; temp4=temp3; if(winsize<=0) winsize=8; } printf("\n end of sliding window protocol"); } int reciever(int temp1) { int i; for(i=1;i<100;i++) rand(); i=rand()%temp1; return i; } int simulate(int winsize) { int temp1,i; for(i=1;i<50;i++) temp1=rand(); if(temp1==0) temp1=simulate(winsize); i = temp1%winsize; if(i==0) return winsize; else return temp1%winsize; }
C
#include <stdio.h> int main(void) { int pieces, code; float total = 0; float pay, sales, hours; printf("Enter employee's number code (-1 to end): "); scanf_s("%d", &code); while (code != -1) { switch (code) { case 1: printf("Enter the manager's pay rate: "); scanf_s("%f", &pay); printf("Weekly pay is: %.2f\n\n", pay); total += pay; break; case 2: printf("Enter hourly worker's pay rate: "); scanf_s("%f", &pay); printf("Enter the number of hours worked: "); scanf_s("%f", &hours); if (hours > 40) pay = (pay * 40) + ((hours - 40) * (pay * 1.5)); else pay = pay * hours; printf("Weekly pay is: %.2f\n\n", pay); total += pay; break; case 3: printf("Enter commission employee's gross weekly sales: "); scanf_s("%f", &sales); pay = 250 + (.057 * sales); printf("Weekly pay is: %.2f\n\n", pay); total += pay; break; case 4: printf("\nEnter the number of pieces completed: "); scanf_s("%d", &pieces); printf("Enter the employee's per piece pay rate: "); scanf_s("%f", &pay); pay = pieces * pay; printf("Weekly pay is: %.2f\n\n", pay); total += pay; break; default: printf("You have entered an invalid code.\n"); } printf("\nEnter employee's number code (-1 to end): "); scanf_s("%d", &code); } printf("\nThe total payroll for the week is: %.2f\n", total); return 0; }
C
#include <stdio.h> #include "wrapper.h" extern void NGCALLF(derrf,DERRF)(double *, double *); extern void NGCALLF(derrcf,DERRCF)(int *, double *, double *); NhlErrorTypes erf_W( void ) { /* * Input variables */ /* * Argument # 0 */ void *x; double *tmp_x = NULL; int ndims_x; ng_size_t dsizes_x[NCL_MAX_DIMENSIONS]; NclBasicDataTypes type_x; /* * Return variable */ void *result; double *tmp_result = NULL; ng_size_t *dsizes_result; NclBasicDataTypes type_result; /* * Various */ int i, size_output, ret; /* * Retrieve parameters. * * Note any of the pointer parameters can be set to NULL, which * implies you don't care about its value. */ /* * Get argument # 0 */ x = (void*)NclGetArgValue( 0, 1, &ndims_x, dsizes_x, NULL, NULL, &type_x, DONT_CARE); /* * Allocate space for coercing input to double if necessary. */ if(type_x != NCL_double) { type_result = NCL_float; tmp_x = (void *)calloc(1, sizeof(double)); if(tmp_x == NULL) { NhlPError(NhlFATAL,NhlEUNKNOWN,"erf: Unable to allocate memory for temporary input array"); return(NhlFATAL); } } else { type_result = NCL_double; } /* * Calculate size of leftmost dimensions, which is basically the whole * array because the Fortran routine is expecting scalars. */ size_output = 1; for(i = 0; i < ndims_x; i++) size_output *= dsizes_x[i]; /* * Allocate space for output array. */ if(type_result != NCL_double) { result = (void *)calloc(size_output, sizeof(float)); tmp_result = (double *)calloc(1,sizeof(double)); if(tmp_result == NULL) { NhlPError(NhlFATAL,NhlEUNKNOWN,"erfc: Unable to allocate memory for temporary output array"); return(NhlFATAL); } } else { result = (void *)calloc(size_output, sizeof(double)); } if(result == NULL) { NhlPError(NhlFATAL,NhlEUNKNOWN,"erfc: Unable to allocate memory for output array"); return(NhlFATAL); } /* * Allocate space for output dimension sizes and set them. */ dsizes_result = (ng_size_t*)calloc(ndims_x,sizeof(ng_size_t)); if( dsizes_result == NULL ) { NhlPError(NhlFATAL,NhlEUNKNOWN,"erf: Unable to allocate memory for holding dimension sizes"); return(NhlFATAL); } for(i = 0; i < ndims_x; i++) dsizes_result[i] = dsizes_x[i]; /* * Loop across dimensions and call the Fortran routine for each * one-dimensional subsection. */ for(i = 0; i < size_output; i++) { /* * Coerce subsection of x (tmp_x) to double if necessary. */ if(type_x != NCL_double) { coerce_subset_input_double(x,tmp_x,i,type_x,1,0,NULL,NULL); } else { tmp_x = &((double*)x)[i]; } /* * Point temporary output array to void output array if appropriate. */ if(type_result == NCL_double) tmp_result = &((double*)result)[i]; /* * Call the Fortran routine. */ NGCALLF(derrf,DERRF)(tmp_x, tmp_result); /* * Coerce output back to float if necessary. */ if(type_result == NCL_float) { coerce_output_float_only(result,tmp_result,1,i); } } /* * Free unneeded memory. */ if(type_x != NCL_double) NclFree(tmp_x); if(type_result != NCL_double) NclFree(tmp_result); /* * Return value back to NCL script. */ ret = NclReturnValue(result,ndims_x,dsizes_result,NULL,type_result,0); NclFree(dsizes_result); return(ret); } NhlErrorTypes erfc_W( void ) { /* * Input variables */ /* * Argument # 0 */ void *x; double *tmp_x = NULL; int ndims_x; ng_size_t dsizes_x[NCL_MAX_DIMENSIONS]; NclBasicDataTypes type_x; /* * Return variable */ void *result; double *tmp_result = NULL; ng_size_t *dsizes_result; NclBasicDataTypes type_result; /* * Various */ int i, size_output, iopt = 0, ret; /* * Retrieve parameters. * * Note any of the pointer parameters can be set to NULL, which * implies you don't care about its value. */ /* * Get argument # 0 */ x = (void*)NclGetArgValue( 0, 1, &ndims_x, dsizes_x, NULL, NULL, &type_x, DONT_CARE); /* * Allocate space for coercing input to double if necessary. */ if(type_x != NCL_double) { type_result = NCL_float; tmp_x = (void *)calloc(1, sizeof(double)); if(tmp_x == NULL) { NhlPError(NhlFATAL,NhlEUNKNOWN,"erfc: Unable to allocate memory for temporary input array"); return(NhlFATAL); } } else { type_result = NCL_double; } /* * Calculate size of leftmost dimensions, which is basically the whole * array because the Fortran routine is expecting scalars. */ size_output = 1; for(i = 0; i < ndims_x; i++) size_output *= dsizes_x[i]; /* * Allocate space for output array. */ if(type_result != NCL_double) { result = (void *)calloc(size_output, sizeof(float)); tmp_result = (double *)calloc(1,sizeof(double)); if(tmp_result == NULL) { NhlPError(NhlFATAL,NhlEUNKNOWN,"erfc: Unable to allocate memory for temporary output array"); return(NhlFATAL); } } else { result = (void *)calloc(size_output, sizeof(double)); } if(result == NULL) { NhlPError(NhlFATAL,NhlEUNKNOWN,"erfc: Unable to allocate memory for output array"); return(NhlFATAL); } /* * Allocate space for output dimension sizes and set them. */ dsizes_result = (ng_size_t*)calloc(ndims_x,sizeof(ng_size_t)); if( dsizes_result == NULL ) { NhlPError(NhlFATAL,NhlEUNKNOWN,"erfc: Unable to allocate memory for holding dimension sizes"); return(NhlFATAL); } for(i = 0; i < ndims_x; i++) dsizes_result[i] = dsizes_x[i]; /* * Loop across all dimensions and call the Fortran routine for each * one-dimensional subsection. */ for(i = 0; i < size_output; i++) { /* * Coerce subsection of x (tmp_x) to double if necessary. */ if(type_x != NCL_double) { coerce_subset_input_double(x,tmp_x,i,type_x,1,0,NULL,NULL); } else { tmp_x = &((double*)x)[i]; } /* * Point temporary output array to void output array if appropriate. */ if(type_result == NCL_double) tmp_result = &((double*)result)[i]; /* * Call the Fortran routine. */ NGCALLF(derrcf,DERRCF)(&iopt, tmp_x, tmp_result); /* * Coerce output back to float if necessary. */ if(type_result == NCL_float) { coerce_output_float_only(result,tmp_result,1,i); } } /* * Free unneeded memory. */ if(type_x != NCL_double) NclFree(tmp_x); if(type_result != NCL_double) NclFree(tmp_result); /* * Return value back to NCL script. */ ret = NclReturnValue(result,ndims_x,dsizes_result,NULL,type_result,0); NclFree(dsizes_result); return(ret); }
C
#include <cs50.h> #include <stdio.h> int main() { int h; int acrsum; do { printf("Height: "); h = get_int(); } while(h < 0 || h > 23); if(h==1) { printf("##\n"); } else { acrsum = h + 1; for(int across=0; across < h; across++) { for(int down=0; down < acrsum; down++) { if(down >= acrsum-across - 2) printf("#"); else printf(" "); } printf("\n"); } } }
C
/*-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-== Project 6 File: ListFunctions.c Created by: Fritts and Slayter Last edit on: 11/29/2013 (Fritts) Description: Functions for adding, deleteing, searching, and replacing data in linked lists. ==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-*/ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <stdint.h> #include "ListFunctions.h" #include "memoryHandler.h" #include "defs.h" // Add head ptrs struct envNode *envHead; // Head for environment variable list int envVarCount; struct envNode *cmdHead; // Head for cmd alias list int cmdVarCount; void init_ll(void) { envHead = NULL; cmdHead = NULL; envVarCount = 0; cmdVarCount = 0; } // *************** ENVIRONMENT VARIABLE FUNCTIONS *************** void nshInsert(struct envNode **envHead, char *name, char *value, int envVarCount) { struct envNode *node = (struct envNode *)nshMalloc(sizeof(struct envNode)); // create a new node envVariable *variable = (envVariable *)nshMalloc(sizeof(envVariable)); variable->name = (char *)nshMalloc(sizeof(char)*(strlen(name)+1)); // malloc space for name and value variable->value = (char *)nshMalloc(sizeof(char)*(strlen(value)+1)); strcpy(variable->name, name); strcpy(variable->value, value); node->next = NULL; //preset to NULL needed node->previous = NULL; //preset to NULL needed node->variable = variable; //set the node variable pointer to malloced var pointer above if (envHead == NULL || envVarCount == 0) { // If head is null, create it node->next = NULL; (*envHead) = node; //printf("creating head\n"); } else { // find proper place to insert //printf("push on head\n"); struct envNode *current = *envHead; while (current != NULL) { if (strcmp(node->variable->name, current->variable->name) > 0) { // if the string is greater, keep going if (current->next != NULL) { current = current->next; } else { // push onto tail current->next = node; node->previous = current; break; } } else { if (current->previous != NULL) { // Insert in middle of list current = current->previous; // This block links up the nodes node->next = current->next; current->next = node; node->next->previous = node; node->previous = current; current = node; } else { // Insert at head node->next = current; current->previous = node; } break; } } // make sure head is updated while (current != NULL) { if (current->previous == NULL) { (*envHead) = current; break; } current = current->previous; } } } int containsEnvVar(struct envNode *envHead, char *varName) { struct envNode *current = envHead; while (current != NULL) { if (strcmp(current->variable->name, varName) == 0) { // variable found return 1; } /*else if (strcmp(current->variable->name, varName) > 0) { // we've gone further than where the var would be return 0; // abort search }*/ current = current->next; } return 0; } //given name return value char* nshFind(struct envNode *envHead, char *varName) { struct envNode *current = envHead; while (current != NULL) { if (strcmp(current->variable->name, varName) == 0) { // variable found return current->variable->value; } /*else if (strcmp(current->variable->name, varName) > 0) { // we've gone further than where the var would be return (char *)NULL; // abort search }*/ current = current->next; } return (char *)NULL; } //given value return name char* nshFindAlias(struct envNode *envHead, char *varName) { // same as nshFind, but returns cmd alias wants to run struct envNode *current = envHead; while (current != NULL) { if (strcmp(current->variable->value, varName) == 0) { return current->variable->name; } /*else if (strcmp(current->variable->name, varName) > 0) { return (char *)NULL; }*/ current = current->next; } return (char *)NULL; } void nshUpdate(struct envNode *envHead, char *varName, char *varValue) { DEBUG printf("nshUpdate() called with\t NAME: %s\t VALUE:%s\n",varName,varValue); struct envNode *current = envHead; while (current != NULL) // same search code as above { DEBUG printf("comparing\t %s\t%s\n",current->variable->name,varName); if (strcmp(current->variable->name, varName) == 0) { break; } current = current->next; } DEBUG printf("nshFree(%s)\n",current->variable->value); nshFree(current->variable->value); // free the value DEBUG printf("nshMalloc(%zu)\n",(strlen(varValue)+1)); current->variable->value = (char *)nshMalloc(strlen(varValue)+1); // malloc and set new value DEBUG printf("strcpy(%s,%s)\n",current->variable->value, varValue); strcpy(current->variable->value, varValue); } void nshDisplayOne(struct envNode *envHead, char *varName) { // display one variable/alias by name struct envNode *current = envHead; while (current != NULL) { if (strcmp(current->variable->name, varName) == 0) { printf("%s = %s\n", varName, current->variable->value); return; } current = current->next; } printf("%s: Variable not found\n", varName); } void nshDisplayAll(struct envNode *envHead) { // display all variables/alias struct envNode *current = envHead; while (current != NULL) { printf("%s = %s\n", current->variable->name, current->variable->value); current = current->next; } } void nshRemove(struct envNode **envHead, char *varName, bool isAlias) { struct envNode *current = *envHead; struct envNode *temp; //printf("[DEBUG] Clearing var\n"); while (current != NULL) { // find variable to clear if (strcmp(current->variable->name, varName) == 0 && !isAlias) { break; } else if (strcmp(current->variable->value, varName) == 0) { break; } current = current->next; } if (current->next == NULL && current->previous == NULL) { // node is the only one in the list current = (struct envNode *)NULL; } else if (current->next == NULL && current->previous != NULL) { // node is at the tail of list current = current->previous; current->next = (struct envNode *)NULL; } else if (current->next != NULL && current->previous == NULL) { // node is the head of list current = current->next; current->previous = (struct envNode *)NULL; } else if (current->next != NULL && current->previous != NULL) { // node is the middle of the list temp = current->next; current = current->previous; current->next = temp; } if (current != NULL) { while (current->previous != NULL) { // place current back at the head current = current->previous; } } (*envHead) = current; // update the list } void nshNext(struct envNode **envHead) { // progress through list *envHead = (*envHead)->next; } int containsCmdAliasByAliasName(struct envNode *cmdHead, char *aliasName) { // returns 1 if command alias exists struct envNode *current = cmdHead; // check using alias name while (current != NULL) { if (strcmp(current->variable->value, aliasName) == 0) { return 1; } current = current->next; } return 0; }
C
/** * Author: Jack Keating * Date: 2019/01/15 * * A simple hello world program in C * */ #include<stdlib.h> #include<stdio.h> int main(int argc, char **argv) { printf("Jack Keating\n"); printf("Mechanical Engineering\n"); printf("Max Van Arsdall\n"); printf("Undecided\n"); return 0; }
C
#include <stdio.h> #include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> int main(int argc, char *argv[]) { const gsl_rng_type * T; gsl_rng * r; //select random number generator r = gsl_rng_alloc(gsl_rng_mt19937); FILE *fp; const int N = 1000,Iters = 100000; int accepted = 0; int ii; double x_0,alpha,candidate,a,a_rate; fp = fopen("./data/mcmc_serial.dat","w"); //generate random starting point x_0 = gsl_ran_flat(r,-20,20); alpha = 1.0; for (ii = 0; ii < Iters; ii++) { candidate = x_0+gsl_ran_gaussian(r,alpha); a = ((gsl_ran_gaussian_pdf(candidate,1)+gsl_ran_gaussian_pdf(candidate-10,2)))/((gsl_ran_gaussian_pdf(x_0,1)+gsl_ran_gaussian_pdf(x_0-10,2))); //printf("a = %f\n",a); if(gsl_rng_uniform(r)<a) { x_0 = candidate; accepted++; } fprintf(fp,"%f\n",x_0); if(ii%100==0&&ii!=0) { a_rate = accepted/(double)(ii); printf("acceptance rate = %f\n",a_rate); printf("alpha = %f\n",alpha); if(a_rate>0.45) { alpha = alpha*1.5; } else if(a_rate<0.25) { alpha = alpha/1.5; } } } fclose(fp); gsl_rng_free(r); system("gnuplot mcmc_serial.plt"); printf("Number accpeted = %d",accepted); return 0; }
C
#include<stdio.h> #include<stdlib.h> int main() { int a = 2; int b = 0; b = (a == 2) ? (3) : (4); printf("b = %d\n", b); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include"../inc/supplier.h" char New_Supplier_ID(Supplier Supp) { char a; FILE *f1=fopen("data1.csv","r"); if(f1==NULL) { perror("Unable to open the file"); } char buff[1024];//stores the first 1024 lines into buff int rc=0,cc=0,q=0; while(fgets(buff, 1024, f1)) { cc=0; rc++; if(rc==1) continue; char *field = strtok(buff,","); while(field) { field = strtok(NULL,","); cc++; } q++; } fclose(f1); FILE* fp = fopen("data1.csv", "a+"); if (!fp) { // Error in file opening printf("Can't open file\n"); } sprintf(Supp.ID,"%d",++q); fprintf(fp,"%s,%s,%s,%s,%s,%s,%s\n",Supp.ID,Supp.name,Supp.City,Supp.Mobile_Number,Supp.email,Supp.Medicines,Supp.Quantity ); printf("\nNew added to record\n"); a='y'; fclose(fp); return a; }
C
#include "tls-socket.h" #include "sockutil.h" #include <openssl/bio.h> #include <openssl/ssl.h> #include <openssl/err.h> #include <stdio.h> #include <stdlib.h> struct tls_socket_t { socket_t tcp; SSL_CTX *ctx; SSL* ssl; }; int tls_socket_init() { SSL_library_init(); SSL_load_error_strings(); ERR_load_BIO_strings(); OpenSSL_add_ssl_algorithms(); return 0; } int tls_socket_cleanup() { EVP_cleanup(); return 0; } int tls_socket_close(struct tls_socket_t* tls) { if(tls) { if(tls->ssl) { SSL_shutdown(tls->ssl); SSL_free(tls->ssl); tls->ssl = NULL; } if(tls->ctx) { SSL_CTX_free(tls->ctx); tls->ctx = NULL; } if(socket_invalid != tls->tcp && 0 != tls->tcp) { socket_close(tls->tcp); tls->tcp = socket_invalid; } free(tls); } return 0; } int tls_socket_getfd(tls_socket_t* tls) { return SSL_get_fd(tls->ssl); } tls_socket_t* tls_socket_bind(const char* ip, unsigned int port) { struct tls_socket_t* tls; tls = (struct tls_socket_t*)calloc(1, sizeof(*tls)); tls->tcp = socket_tcp_listen(AF_UNSPEC, ip, (unsigned short)port, 64, 0, 1); if(socket_invalid == tls->tcp) { tls_socket_close(tls); return NULL; } tls->ctx = SSL_CTX_new(SSLv23_client_method()); if (!tls->ctx) { tls_socket_close(tls); return NULL; } socket_setnonblock(tls->tcp, 0); tls->ssl = SSL_new(tls->ctx); SSL_set_fd(tls->ssl, tls->tcp); //r = SSL_accept(tls->ssl); return tls; } static int tls_connect(struct tls_socket_t* tls) { int r; tls->ctx = SSL_CTX_new(SSLv23_client_method()); if (!tls->ctx) return -1; socket_setnonblock(tls->tcp, 0); tls->ssl = SSL_new(tls->ctx); SSL_set_fd(tls->ssl, tls->tcp); r = SSL_connect(tls->ssl); return 1 == r ? 0 : -1; } struct tls_socket_t* tls_socket_connect(const char* host, unsigned int port, int timeout) { struct tls_socket_t* tls; tls = (struct tls_socket_t*)calloc(1, sizeof(*tls)); tls->tcp = socket_connect_host(host, (u_short)port, timeout); if(socket_invalid == tls->tcp) { tls_socket_close(tls); return NULL; } if(0 == tls_connect(tls)) return tls; ERR_get_error(); tls_socket_close(tls); return NULL; } tls_socket_t* tls_socket_connect2(const struct sockaddr* addr, int timeout) { int r; struct tls_socket_t* tls; tls = (struct tls_socket_t*)calloc(1, sizeof(*tls)); tls->tcp = socket_tcp(); r = socket_connect_by_time(tls->tcp, addr, socket_addr_len(addr), timeout); if (0 != r) { tls_socket_close(tls); return NULL; } if(0 == tls_connect(tls)) return tls; ERR_print_errors_fp(stderr); tls_socket_close(tls); return NULL; } tls_socket_t* tls_socket_connect3(int fd) { struct tls_socket_t* tls; tls = (struct tls_socket_t*)calloc(1, sizeof(*tls)); tls->tcp = fd; if(0 == tls_connect(tls)) return tls; ERR_print_errors_fp(stderr); tls_socket_close(tls); return NULL; } static int tls_accept(struct tls_socket_t* tls) { int r; tls->ctx = SSL_CTX_new(SSLv23_client_method()); if (!tls->ctx) return -1; socket_setnonblock(tls->tcp, 0); tls->ssl = SSL_new(tls->ctx); SSL_set_fd(tls->ssl, tls->tcp); r = SSL_accept(tls->ssl); return 1 == r ? 0 : -1; } tls_socket_t* tls_socket_accept(int fd) { struct tls_socket_t* tls; tls = (struct tls_socket_t*)calloc(1, sizeof(*tls)); tls->tcp = fd; if(0 == tls_accept(tls)) return tls; ERR_print_errors_fp(stderr); tls_socket_close(tls); return NULL; } int tls_socket_read(tls_socket_t* tls, void* data, int bytes) { return SSL_read(tls->ssl, data, bytes); } int tls_socket_write(tls_socket_t* tls, const void* data, int bytes) { return SSL_write(tls->ssl, data, bytes); }
C
#include <stdio.h> int compare( const void* a, const void* b) { int int_a = * ( (int*) a ); int int_b = * ( (int*) b ); if ( int_a == int_b ) return 0; else if ( int_a < int_b ) return -1; else return 1; } int main(void){ int vetor[10]=[6,5,2,3,4,1,9,8,7,0]; int i; qsort( vetor, 10, sizeof(int), compare ) system("pause"); return 0; }
C
#include<stdio.h> #include<unistd.h> int main() { /*this is my first program in C*/ printf("Hello World, This is my first code!"); printf("I Love C!!!"); return (0); }
C
/** * @file Calculator.c * @author mhmdreda99 (Moreda491999@gmail.com) * @brief * @version 1.1 * @date 2020-12-28 * * @copyright Copyright (c) 2020 * */ /***************************************************************************** * Module HEADER FILE * *****************************************************************************/ #include "../include/Calculator.h" /***************************************************************************** * Private FUNCTIONS Prototypes * *****************************************************************************/ static void add(void);//addition static void subtract(void);//subtraction static void multiply(void);//multiplication static void divide(void); //division static void Calc_logic(void); // operates other function /***************************************************************************** * Public FUNCTIONS Definitions * *****************************************************************************/ void Calc_App(void){ User_Interface(); Get_User_Input(); Calc_logic(); Print_Result(); } /***************************************************************************** * Private FUNCTIONS Definitions * *****************************************************************************/ static void Calc_logic(void){ switch(option){ case '+': add(); break; case '-': subtract(); break; case '*': multiply(); break; case '/': divide(); break; default: break; } } static void add(void){ result=num1 + num2 ; } static void subtract(void){ result=num1 - num2 ; } static void multiply(void){ result=num1 * num2 ; } static void divide(void){ result=num1 / num2 ; }
C
// // Created by Holly Gong on 27/8/20. // #include "game.h" #include <stdlib.h> struct Game* create_game(struct Board* board1, struct Board* board2,struct Player* p1, struct Player* p2, int point) { struct Board* temp = create_board(board1->width, board1->height); printf("%s", print_board(temp)); printf("===\n"); printf("%s", print_board(board1)); struct Position* position; int p1Point = 0; int p2Point = 0; while (1) { char posY; char posX; char empty; printf("(Your move)>"); //TODO: 这里还是只处理了单个数字情况 scanf("%c%c%c", &posY, &posX, &empty); position = create_position(posX - '1', posY - 'A', '.'); if(process_input(board2, temp, position, 1)) { printf("Hit\n"); p1Point++; } else { printf("Miss\n"); } printf("(CPU move)>"); //TODO: 这里还是只处理了单个数字情况 scanf("%c%c%c", &posY, &posX, &empty); position = create_position(posX - '1', posY - 'A', '.'); if(process_input(board1, board1, position, 0)) { printf("Hit\n"); p2Point++; } else { printf("Miss\n"); } printf("%s", print_board(temp)); printf("===\n"); printf("%s", print_board(board1)); if (p1Point == point) { printf("Game over - you win\n"); break; } else if (p2Point == point) { printf("Game over - you lose\n"); break; } } } int process_input(struct Board* dataBoard, struct Board* showBoard, struct Position* position, int bot) { for (int i = 0; i < dataBoard->height * dataBoard->width; i++) { if (equal_pos(dataBoard->positions[i], position)) { if (dataBoard->positions[i]->display != '.' && dataBoard->positions[i]->display != '/') { showBoard->positions[i]->display = '*'; return 1; } else { if (bot) { showBoard->positions[i]->display = '/'; } return 0; } } } }
C
//#include<reg51.h> #include<stdio.h> #define lcd P1 //lcd --> port p1 is defined sbit rs=P1^0; sbit en=P1^1; sbit SDA=P2^1; // serial _data sbit SCL=P2^0; //serial clock sbit next=P2^2; //increment digit sbit inc=P2^3; //increment value sbit set=P2^4; //set time char ack; //acknowledge step unsigned char k; unsigned int hour=0, min=0, sec=0; // delay subroutine void delay(int t) { int i,j; for(i=0;i<t;i++) for(j=0;j<1200;j++); } void data_en() { rs=1; en=1; delay(1); en=0; } void lcd_data(unsigned char d) { lcd=d & 0xf0; data_en(); lcd=(d<<4) & 0xf0; data_en(); } void cmd_en(void) { rs=0; en=1; delay(1); en=0; } void lcd_cmd(unsigned char c) { lcd=c & 0xf0; cmd_en(); lcd=(c<<4) & 0xf0; cmd_en(); } void lcdprint(char *str) { while(*str) { lcd_data(*str); str++; } } void lcd_init(void) { lcd_cmd(0x02); lcd_cmd(0x28); lcd_cmd(0x0c); lcd_cmd(0x01); } //"start" function for communicate with ds1307 RTC void I2C_Start() { SDA=1; SCL=1; SDA=0; SCL=0; } //"stop" function for communicate wit ds1307 RTC void I2C_Stop() { SDA=0; SCL=1; SDA=1; SCL=0; } //"send" data to ds1307 unsigned char I2C_Send(unsigned char Data) { char i; char ack_bit; for(i=0;i<8;i++) { if(Data & 0x80) SDA=1; else SDA=0; SCL=1; Data<<=1; SCL=0; } SDA=1; SCL=1; SDA=0;//ack_bit=SDA; SCL=0; return ack_bit; } //read data from ds1307 unsigned char I2C_Read(char ack) { unsigned char i, Data=0; SDA=1; for(i=0;i<8;i++) { Data<<=1; do { SCL=1; } while(SCL==0); if(SDA) Data|=1; SCL=0; } if(ack) SDA=0; else SDA=1; SCL=1; SCL=0; SDA=1; return Data; } //bcd_2_dec conversion int BCDToDecimal(char bcdByte) { char a,b,dec; a=(((bcdByte & 0xF0) >> 4) * 10); b=(bcdByte & 0x0F); dec=a+b; return dec; } char DecimalToBCD (int decimalByte) { char a,b,bcd; a=((decimalByte / 10) << 4); b= (decimalByte % 10); bcd=a|b; return bcd; } //function to display time on LCD void show_time() { char var[5]; lcd_cmd(0x80); lcdprint("Time:"); sprintf(var,"%d",hour); lcdprint(var); sprintf(var,":%d",min); lcdprint(var); sprintf(var,":%d",sec); lcdprint(var); lcdprint(" "); lcdprint(" "); } //time set function void set_time() { lcd_cmd(0x0e); while(k<7) { while(k==1) //set hour { if(inc==0) { hour++; while(inc==0); if(hour==24) { hour=00; } show_time(); } if(next==0) { k=2; while(next==0); } lcd_cmd(0xc5); } while(k==2) //set min { if(inc==0) { min++; while(inc==0); if(min==60) { min=00; } show_time(); } if(next==0) { k=6; while(next==0); } lcd_cmd(0xc8); } } } void main() { lcd_init(); lcdprint("Digital Clock"); lcd_cmd(0xc0); lcdprint(" Using I2C & RTC "); delay(200); lcd_cmd(0x01); delay(100); show_time(); //display time delay(300); while(1) { I2C_Start(); I2C_Send(0xD0); I2C_Send(0x00); I2C_Start(); I2C_Send(0xD1); sec=BCDToDecimal(I2C_Read(1)); min=BCDToDecimal(I2C_Read(1)); hour=BCDToDecimal(I2C_Read(1)); I2C_Stop(); show_time(); //display time delay(50); } }
C
#include "assembler/label_table.h" #include "assembler/label.h" #include <stdlib.h> #include <stdio.h> #include <string.h> struct AssemblyLabelTable* alloc_label_table() { struct AssemblyLabelTable* table = malloc(sizeof(struct AssemblyLabelTable)); table->labels = NULL; table->count = 0; table->alloc_count = 0; return table; } void grow_label_table(struct AssemblyLabelTable* table) { table->alloc_count += 2; table->labels = realloc( table->labels, sizeof(struct AssemblyLabel*) * table->alloc_count ); } void dealloc_label_table(struct AssemblyLabelTable* table) { free(table->labels); free(table); } void print_label_table(const struct AssemblyLabelTable* table) { for(uint16_t i = 0; i < table->count; i++) { printf("0x%x: %s\n", table->labels[i]->address, table->labels[i]->label); } } bool table_has_label_str( const struct AssemblyLabelTable* table, const char* label ) { for(uint16_t i = 0; i < table->count; i++) { if(strcmp(label, table->labels[i]->label) == 0) { return true; } } return false; } void add_label_to_table( struct AssemblyLabelTable* table, struct AssemblyLabel* label ) { if(table->count == table->alloc_count) { grow_label_table(table); } table->labels[table->count] = label; table->count++; }
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <math.h> #include <stdlib.h> int check_date(int year, int month, int days) { if (month > 12) { return 0; } else { switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: if (days > 31) { return 0; } else return 1; break; case 4: case 6: case 9: case 11: if (days > 30) { return 0; } else return 1; break; case 2: if (year % 4 == 0 && year % 100 != 0) { if (days > 29) { return 0; } else return 1; } else { if (days > 30) { return 0; } else return 1; } break; default: break; } } } int main(void) { int year, month, days; int flag = 1; printf("¥ ( )? "); scanf("%d%d%d", &year, &month, &days); while (1) { flag = check_date(year, month, days); if (flag == 1) { printf("Է ¥ %d %d %dԴϴ.\n", year, month, days); break; } else { printf("߸ Էϼ̽ϴ. ȿ ¥ Էϼ.\n"); printf("¥ ( )? "); scanf("%d%d%d", &year, &month, &days); } } return 0; }
C
/* * main.c * * Created on: Jan 22, 2014 * Author: mody */ #include <stdlib.h> #include <string.h> #include <avr/io.h> /* Scheduler include files. */ #include "FreeRTOS.h" #include"FreeRTOSConfig.h" #include "task.h" #include"usart.h" /*Set the priorties*/ #define Task1_PRIORITY1 2 #define Task2_PRIORITY2 1 /*Declaring the prototypes of functions*/ void uart_print_Task1 ( void * pvParameters ); void uart_print_Task2 ( void * pvParameters ); /*Declare the handle for task 2*/ xTaskHandle xTask2Handle; /*The main*/ int main (void) { /*The cont Tasks*/ xTaskCreate(uart_print_Task1, ( signed char * ) "Task1", configMINIMAL_STACK_SIZE,NULL, Task1_PRIORITY1,&xTask2Handle); xTaskCreate(uart_print_Task2, ( signed char * ) "Task2", configMINIMAL_STACK_SIZE,NULL, Task2_PRIORITY2, NULL ); /*Start scheduler function*/ vTaskStartScheduler(); while(1) { } return(0); } /*Function of Tasks*/ void uart_print_Task1 ( void * pvParameters ) { unsigned portBASE_TYPE uxPriority; uxPriority=uxTaskPriorityGet(NULL); USART_Init(); while(1) { USART_putstring("Task 1 is running \r\n"); USART_putstring("About to raise the Task 2 priority\r\n"); vTaskPrioritySet( xTask2Handle,(uxPriority+1)); //vTaskDelay(1000); } } void uart_print_Task2 ( void * pvParameters ) { unsigned portBASE_TYPE uxPriority; uxPriority=uxTaskPriorityGet(NULL); USART_Init(); while(1) { USART_putstring("Task 2 is running \r\n"); USART_putstring("About to lower the Task 2 priority\r\n"); vTaskPrioritySet( NULL, (uxPriority-2) ); vTaskDelay(1000); //_delay_ms(1000); } }
C
#include <stdio.h> #include <stdlib.h> #include "dll.h" /* Initialize an empty list in which the head and the tail are the same, i.e. they both point to a dummy node. */ dll_t *init_dll() { dll_t *dll = calloc(1, sizeof(dll_t)); dll_node_t *node = calloc(1, sizeof(dll_t)); node->next = node; node->prev = node; dll->head = node; // empty list consists of only dll->tail = node; return dll; } /* Add new node with data to back of list. */ void append(dll_t *dll, void *data) { dll_node_t *head = dll->head; dll_node_t *node = calloc(1, sizeof(dll_node_t)); node->data = data; node->next = dll->head; node->prev = dll->tail; dll->head->prev = node; dll->tail->next = node; dll->tail = node; if (dll->head != head) { printf("Fuck something's wrong...\n"); } } /* Delete a node from the list. */ void del(dll_t *dll, dll_node_t *node) { node->prev->next = node->next; node->next->prev = node->prev; if (node == dll->tail) { // need to update tail node if we're deleting it dll->tail = node->prev; } free(node); } /* Delete all nodes from the list. */ void deinit_dll(dll_t *dll) { dll_node_t *node = dll->head->next; while (node != dll->head) { dll_node_t *next = node->next; del(dll, node); node = next; } free(dll); }
C
#define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_STATIC #include "stb_image.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #define STB_IMAGE_WRITE_STATIC #include "stb_image_write.h" #include "CStbImage.h" unsigned char* load_image(const char* path, int* width, int* height, int* channels, int desired_channels) { stbi_uc* pixels = stbi_load(path, width, height, channels, desired_channels); return pixels; } unsigned char* load_image_from_memory(const unsigned char* buffer, int len, int* width, int* height, int* channels, int desired_channels) { stbi_uc* pixels = stbi_load_from_memory(buffer, len, width, height, channels, desired_channels); return pixels; } void free_image(void* pixels){ stbi_image_free(pixels); } int write_image_bmp(const char* path, int width, int height, int bpp, const void* data) { return stbi_write_bmp(path, width, height, bpp, data); } int write_image_jpg(const char* path, int width, int height, int bpp, const void* data, int quality) { return stbi_write_jpg(path, width, height, bpp, data, quality); } int write_image_png(const char* path, int width, int height, int bpp, const void* data) { return stbi_write_png(path, width, height, bpp, data, width*bpp); } int write_image_bmp_to_func(write_func* func, void * context, int width, int height, int bpp, const void* data) { return stbi_write_bmp_to_func(func, context, width, height, bpp, data); } int write_image_jpg_to_func(write_func* func, void * context, int width, int height, int bpp, const void* data, int quality) { return stbi_write_jpg_to_func(func, context, width, height, bpp, data, quality); } int write_image_png_to_func(write_func* func, void* context, int width, int height, int bpp, const void* data) { return stbi_write_png_to_func(func, context, width, height, bpp, data, width*bpp); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* pstate_env.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hgrampa <hgrampa@student.21-school.ru> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/16 13:16:05 by hgrampa #+# #+# */ /* Updated: 2021/04/29 14:08:40 by hgrampa ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" #include "parser.h" #include "environment.h" #include "errors.h" static char *get_var_name(char **line) { char *name; char *anchor; int len; anchor = *line; len = 0; while (env_isname_char(**line)) { len++; (*line)++; } name = ft_strndup(anchor, len); if (name == NULL) return (NULL); return (name); } static int pstate_set_value(struct s_pcontext *context, char *name) { char *value; value = env_get_value(context->env, name); if (value == NULL) return (1); if (pcontext_previous_state(context) == pstate_wquotes) pbuffer_add_str(context, value); else { while (*value != '\0') { if (ft_strchr(_PRS_DELIMITERS, *value) != NULL) { if (!pbuffer_close(context)) return (0); } else { if (!pbuffer_add_char(context, *value)) return (0); } value++; } } return (1); } static int pstate_rename_var(char **line, struct s_pcontext *context) { char *name; if (env_isname_char(**line) && !ft_isdigit(**line)) { name = get_var_name(line); if (name == NULL) return (pcontext_end_process(context, err_print(NULL, 0, 1))); if (!pstate_set_value(context, name)) { free(name); return (0); } free(name); return (pcontext_return_state(context)); } else if (**line == '?') { if (!pstate_set_value(context, "?")) return (0); } (*line)++; return (pcontext_return_state(context)); } static int pstate_env_to_anchor_exit(char *anchor, char **line, struct s_pcontext *context) { *line = anchor; return (pcontext_return_state(context)); } int pstate_env(char **line, struct s_pcontext *context) { char *anchor; anchor = *(line) + 1; if (*anchor == '\0' || ft_strchr(_PRS_DELIMITERS, *anchor) != NULL || ft_strchr(_PRS_CONTROLERS, *anchor) != NULL) { if (!pbuffer_add_char(context, **line)) return (0); *line = anchor; return (pcontext_return_state(context)); } else if (ft_strchr(_PRS_QUOTES, *anchor) != NULL) { if (pcontext_previous_state(context) == pstate_wquotes) { if (!pbuffer_add_char(context, **line)) return (0); pstate_env_to_anchor_exit(anchor, line, context); } else pstate_env_to_anchor_exit(anchor, line, context); } (*line)++; return (pstate_rename_var(line, context)); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <math.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <pthread.h> #include <errno.h> #include <string.h> #include "stringops.h" int main() { char file1[FILENAME_LENGTH], file2[FILENAME_LENGTH]; printf("Enter names of file1 and file2\n"); scanf("%s", file1); scanf("%s", file2); //FILE *f1 = fopen(file1, "w"); //FILE *f2 = fopen(file2, "w"); // if (f1 == NULL || f2 == NULL) { // printf("Error opening files\n"); // return 1; // } char area1_n[] = "area1"; char mutex1_n[] = "mutex1"; char size_data1_n[] = "size_data1"; int area1 = shm_open(area1_n, O_RDWR | O_CREAT, S_IRWXO | S_IRWXU); int mutex1_ = shm_open(mutex1_n, O_RDWR | O_CREAT, S_IRWXO | S_IRWXU); int size_data1 = shm_open(size_data1_n, O_RDWR | O_CREAT, S_IRWXO | S_IRWXU); char area2_n[] = "area2"; char mutex2_n[] = "mutex2"; char size_data2_n[] = "size_data2"; int area2 = shm_open(area2_n, O_RDWR | O_CREAT, S_IRWXO | S_IRWXU); int mutex2_ = shm_open(mutex2_n, O_RDWR | O_CREAT, S_IRWXO | S_IRWXU); int size_data2 = shm_open(size_data2_n, O_RDWR | O_CREAT, S_IRWXO | S_IRWXU); if (area1 == -1 || mutex1_ == -1 || area2 == -1 || mutex2_ == -1) { printf("Error accessing memory in shm_open\n"); return 2; } if (ftruncate(area1, getpagesize()) == -1 || ftruncate(area2, getpagesize()) == -1) { printf("ftruncate error\n"); return 3; } if (ftruncate(size_data1, sizeof(int)) == -1 || ftruncate(size_data2, sizeof(int)) == -1) { printf("ftruncate error\n"); return 3; } if (ftruncate(mutex1_, sizeof(pthread_mutex_t)) == -1 || ftruncate(mutex2_, sizeof(pthread_mutex_t)) == -1) { printf("ftruncate error\n"); return 3; } char* data1 = (char*) mmap(NULL, getpagesize(), PROT_READ | PROT_WRITE, MAP_SHARED, area1, 0); int* data_s1 = (int*) mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, size_data1, 0); pthread_mutex_t* mutex1 = (pthread_mutex_t *) mmap(NULL, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_SHARED, mutex1_, 0); char* data2 = (char*) mmap(NULL, getpagesize(), PROT_READ | PROT_WRITE, MAP_SHARED, area2, 0); int* data_s2 = (int*) mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, size_data2, 0); pthread_mutex_t* mutex2 = (pthread_mutex_t *) mmap(NULL, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_SHARED, mutex2_, 0); if (data1 == MAP_FAILED || mutex1 == MAP_FAILED || data_s1 == MAP_FAILED || data2 == MAP_FAILED || mutex2 == MAP_FAILED || data_s2 == MAP_FAILED) { printf("mmap error\n"); return 4; } pthread_mutexattr_t mutex1_at, mutex2_at; if (pthread_mutexattr_init(&mutex1_at) != 0 || pthread_mutexattr_init(&mutex2_at) != 0) { printf("Error mutex attributes init\n"); return 5; } if (pthread_mutexattr_setpshared(&mutex1_at, PTHREAD_PROCESS_SHARED) != 0 || pthread_mutexattr_setpshared(&mutex2_at, PTHREAD_PROCESS_SHARED) != 0) { printf("Error mutex scope change\n"); return 6; } if (pthread_mutex_init(mutex1, &mutex1_at) != 0 || pthread_mutex_init(mutex2, &mutex2_at) != 0) { printf("Error mutex init\n"); return 7; } if (pthread_mutex_lock(mutex1) != 0 || pthread_mutex_lock(mutex2) != 0) { printf("Error mutex lock\n"); return 8; } pid_t id1 = fork(); if (id1 == -1) { printf("Error creating process\n"); return 9; } if (id1 == 0) { //this is child char* argv[] = {file1, mutex1_n, area1_n, size_data1_n, (char *) NULL}; if (execv("lab4-child", argv) == -1) { printf("Error execv1\n"); printf("%s\n", strerror(errno)); return 9; } } //this is parent pid_t id2 = fork(); if (id2 == -1) { printf("Error creating process\n"); return 9; } if (id2 == 0) { //this is second child char* argv[] = {file2, mutex2_n, area2_n, size_data2_n, (char *) NULL}; if (execv("lab4-child", argv) == -1) { printf("Error execv2\n"); printf("%s\n", strerror(errno)); return 9; } } //this is parent and there are two children *data_s1 = 0; *data_s2 = 0; // pthread_mutex_unlock(mutex1); // pthread_mutex_unlock(mutex2); if (pthread_mutex_unlock(mutex1) != 0 || pthread_mutex_unlock(mutex2) != 0) { printf("Error mutex unlock\n"); return 8; } char str[STRLENGTH]; strnull(str); while (1 == 1) { printf("Enter string\n"); scanf("%s", &str); if (is_exit(str) == 1) { if (pthread_mutex_lock(mutex1) != 0 || pthread_mutex_lock(mutex2) != 0) { printf("Error mutex lock\n"); return 8; } *data_s1 = -1; *data_s2 = -1; if (pthread_mutex_unlock(mutex1) != 0 || pthread_mutex_unlock(mutex2) != 0) { printf("Error mutex unlock\n"); return 8; } break; } int cnt; if (get_length(str) > 10) { //to area2 if (pthread_mutex_lock(mutex2) != 0) { printf("Error mutex lock\n"); return 8; } for (cnt = 0; str[cnt] != '\0'; ++cnt) { data2[cnt] = str[cnt]; } data2[cnt] = '\0'; *data_s2 = ++cnt; if (pthread_mutex_unlock(mutex2) != 0) { printf("Error mutex unlock\n"); return 8; } } else { //to area1 if (pthread_mutex_lock(mutex1) != 0) { printf("Error mutex lock\n"); return 8; } for (cnt = 0; str[cnt] != '\0'; ++cnt) { data1[cnt] = str[cnt]; } data1[cnt] = '\0'; *data_s1 = ++cnt; if (pthread_mutex_unlock(mutex1) != 0) { printf("Error mutex unlock\n"); return 8; } } } return 0; }
C
#include <stdio.h> #include <stdlib.h> void Trim(int arr[],int size) { int left = 0; int right = size - 1; int tmp = 0; while (left < right) { while ((left < right) && (arr[left] % 2 == 1)) { left++; } while ((left < right) && (arr[right] % 2 == 0)) { right--; } if (left < right) { tmp = arr[left]; arr[left] = arr[right]; arr[right] = tmp; } } } int main() { int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; Trim(a, sizeof(a) / 4); for (int i = 0; i < sizeof(a) / 4; i++) { printf("%d ", a[i]); } printf("\n"); system("pause"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <time.h> #define N_MAX 25600 float c_dot_product(const float *lhs, const float *rhs, size_t size) { assert(lhs && rhs); float sum = 0; for (size_t i = 0; i < size; i++) sum += lhs[i] * rhs[i]; return sum; } float asm_dot_product(const float *lhs, const float *rhs, size_t size) { assert(lhs && rhs); float res = 0.0f; __asm__( "\n\t mov rsi, %1" "\n\t mov rdi, %2" "\n\t mov rax, %3" "\n\t xor rcx, rcx" "\n\t xorps xmm0, xmm0" "\n\t _start:" "\n\t\t cmp rax, 4" "\n\t\t jl _end" "\n\t\t movdqu xmm3, [rsi + rcx]" "\n\t\t movdqu xmm2, [rdi + rcx]" "\n\t\t vmulps xmm1, xmm2, xmm3" "\n\t\t haddps xmm1, xmm1" "\n\t\t haddps xmm1, xmm1" "\n\t\t psrldq xmm1, 4" "\n\t\t addss xmm0, xmm1" "\n\t\t xorps xmm1, xmm1" "\n\t\t sub rax, 4" "\n\t\t add rcx, 16" "\n\t\t jmp _start" "\n\t _end:" "\n\t\t test rax, rax" "\n\t\t jz _return" "\n\t\t movss xmm1, [rsi + rcx]" "\n\t\t movss xmm2, [rdi + rcx]" "\n\t\t mulss xmm1, xmm2" "\n\t\t addss xmm0, xmm1" "\n\t\t add rcx, 4" "\n\t\t dec rax" "\n\t\t jmp _end" "\n\t _return:" "\n\t\t movss %0, xmm0" : "=m" (res) : "m"(lhs), "m"(rhs), "m"(size) : "rax", "rcx", "rsi", "rdi", "xmm0", "xmm1", "xmm2", "xmm3", "xmm7" ); return res; } static inline void make_radnom_arrays(float *fst, float *snd) { for (size_t i = 0; i < N_MAX; i++) { *(fst + i) = 1; *(snd + i) = 1.0f / ((int) i + N_MAX); } } double get_function_excec_time(const float *lhs, const float *rhs, \ float (*func)(const float *, const float *, size_t), \ float *res) { clock_t start; start = clock(); for (int i = 0; i < 1000; i++) *res = func(lhs, rhs, N_MAX); return ((double) clock() - start) / CLOCKS_PER_SEC; } int main() { float a[N_MAX]; float b[N_MAX]; float c_res, asm_res; make_radnom_arrays(a, b); double c_excec_time = get_function_excec_time(a, b, c_dot_product, &c_res); printf("[C] Excec time = %lf\n\t res = %f\n", c_excec_time, c_res); double asm_excec_time = get_function_excec_time(a, b, asm_dot_product, &asm_res); printf("[ASM] Excec time = %lf\n\t res = %f\n", asm_excec_time, asm_res); return 0; }
C
/*СμѧУȤζ˶ᣬеһĿǣӡ ϻһЩӣÿдһ֣ʾҲɲμͼ л ʱվϽǵдšӡֵĸԺڵĸԽǵĸӻλáһֱҪֽ Ҫ·߸պùɡл仰 СһһжֿܵԾ·أ*/ #include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int f(int x,int y); int main(int argc, char *argv[]) { printf("%d",f(5,4)); return 0; } //ijλһж߷ int f(int x,int y){ if(x==1||y==1) return 1; return f(x-1,y)+f(x,y-1); }
C
/* * Demo.c * * Created on: Feb 14, 2017 * Author: Sweitz */ #include <stdio.h> #include <string.h> void copyDataBad(char *id) { char smallerBuffer[10]; strcpy(smallerBuffer, id); } int main(void) { char *userId = "0123456789"; copyDataBad(userId); return 0; }
C
#include <process.h> void send_mes_sync(int *buf, int can) { chan[can] = *buf; while(chan[can] != -1){} return; } void receive_mes(int *buf, int can) { while(chan[can] == -1){} *buf = chan[can]; chan[can] = -1; return; } void T1 (void *threadno) { int buffer = 10; send_mes_sync(&buffer, 0); return; } void T2 (void *threadno) { int buffer; receive_mes(&buffer, 0); printf("%d", buffer); return; }
C
#include <zeckendorf.h> #include <arithmetic.h> #include "zrep.h" #include <stdlib.h> #include <string.h> // cf. paper by Frougny et al. // add_same_len(s1, s2, len) returns the sum of Zeckendorf representations given by s1 and s2 // requires: s1 and s2 are char arrays of length len representing Zeckendorf representations with possible leading ZEROs // effects: allocates memory (caller must call z_clear) static zrep *add_same_len(const char *s1, const char *s2, const size_t len) { const char TWO = ONE + 1; const char THREE = TWO + 1; if (s1[0] == ONE && s2[0] == ONE) { char *cpy1 = malloc((len + 1) * sizeof(char)); memcpy(cpy1 + 1, s1, len * sizeof(char)); cpy1[0] = ZERO; char *cpy2 = malloc((len + 1) * sizeof(char)); memcpy(cpy2 + 1, s2, len * sizeof(char)); cpy2[0] = ZERO; zrep *zans = add_same_len(cpy1, cpy2, len + 1); free(cpy1); free(cpy2); return zans; } char *ans = malloc((len + 1) * sizeof(char)); ans[0] = ZERO; // add pointwise for (size_t i = 1; i <= len; ++i) { if (s1[i - 1] != s2[i - 1]) { ans[i] = ONE; } else if (s1[i - 1] == s2[i - 1] && s1[i - 1] == ONE) { ans[i] = TWO; } else { ans[i] = ZERO; } } // first stage // eliminate TWOs for (size_t i = 0; i <= len - 2; ++i) { if (i < len - 2 && ans[i] == ZERO && ans[i + 1] == TWO && ans[i + 2] == ZERO) { ans[i] = ONE; ans[i + 1] = ZERO; ans[i + 2] = ZERO; ans[i + 3] += 1; } else if (i < len - 2 && ans[i] == ZERO && ans[i + 1] == THREE && ans[i + 2] == ZERO) { ans[i] = ONE; ans[i + 1] = ONE; ans[i + 2] = ZERO; ans[i + 3] += 1; } else if (ans[i] == ZERO && ans[i + 1] == TWO && ans[i + 2] == ONE) { ans[i] = ONE; ans[i + 1] = ONE; ans[i + 2] = ZERO; } else if (ans[i] == ZERO && ans[i + 1] == ONE && ans[i + 2] == TWO) { ans[i] = ONE; ans[i + 1] = ZERO; ans[i + 2] = ONE; } } // clean-up if (len > 1 && ans[len - 2] == ZERO && ans[len - 1] == THREE && ans[len] == ZERO) { ans[len - 2] = ONE; ans[len - 1] = ONE; ans[len] = ONE; } else if (len > 1 && ans[len - 2] == ZERO && ans[len - 1] == TWO && ans[len] == ZERO) { ans[len - 2] = ONE; ans[len - 1] = ZERO; ans[len] = ONE; } else if (len > 2 && ans[len - 3] == ZERO && ans[len - 2] == ONE && ans[len - 1] == TWO && ans[len] == ZERO) { ans[len - 3] = ONE; ans[len - 2] = ZERO; ans[len - 1] = ONE; ans[len] = ZERO; } else if (ans[len - 1] == ZERO && ans[len] == THREE) { ans[len - 1] = ONE; ans[len] = ONE; } else if (ans[len - 1] == ZERO && ans[len] == TWO) { ans[len - 1] = ONE; ans[len] = ZERO; } // second stage // first pass from right to left for (size_t i = len; i >= 2; --i) { if (ans[i] == ONE && ans[i - 1] == ONE && ans[i - 2] == ZERO) { ans[i] = ZERO; ans[i - 1] = ZERO; ans[i - 2] = ONE; } } // second pass from left to right for (size_t i = 0; i <= len - 2; ++i) { if (ans[i] == ZERO && ans[i + 1] == ONE && ans[i + 2] == ONE) { ans[i] = ONE; ans[i + 1] = ZERO; ans[i + 2] = ZERO; } } // remove leading ZEROs char *pos = memchr(ans, ONE, len * sizeof(char)); size_t ans_len = len + 1 + ans - pos; return zrep_new(memmove(ans, pos, ans_len * sizeof(char)), ans_len); } // add_len(s1, s2, len1, len2, len) returns the sum of Zeckendorf representations given by s1 and s2 // requires: s1 and s2 are char arrays of lengths len1 and len2 respectively representing Zeckendorf representations // effects: allocates memory (caller must call z_clear) static zrep *add_len(const char *s1, const char *s2, const size_t len1, const size_t len2) { // add leading ZEROs to make lengths equal, then use add_same_len if (len1 > len2) { char *cp = malloc(len1 * sizeof(char)); memset(cp, ZERO, (len1 - len2) * sizeof(char)); memcpy(cp + len1 - len2, s2, len2 * sizeof(char)); zrep *ans = add_same_len(s1, cp, len1); free(cp); return ans; } else if (len1 < len2) { return add_len(s2, s1, len2, len1); } else { return add_same_len(s1, s2, len1); } } zrep *z_add(const zrep *z1, const zrep *z2) { return add_len(zrep_arr(z1), zrep_arr(z2), zrep_len(z1), zrep_len(z2)); }
C
// // OrdList.h // DataStructure // // Created by 润蕾 on 2018/4/15. // Copyright © 2018年 润蕾. All rights reserved. // #ifndef OrdList_h #define OrdList_h /* ADT OrderedList{ 数据对象:D = {a(i) | a(i) € Node, i = 1, 2……, n >= 0} 数据关系:R1 = {<a(i-1), a(i)> | a(i) € Node } 基本操作: InitList(&L) 操作结果:构造一个空的有序表L DestroyList(&L) 初始条件:有序表L存在 操作结果:销毁有序表L AppendElem(&L, p) 初始条件:有序表L存在 操作结果:在有序表L的末尾插入结点p InsertAfter(&L, p, e) 初始条件:有序表L存在,p指向的结点在链表L内 操作结果:将元素e插在p指向结点之后,插入失败返回false LocateElem(L,e) 初始条件:有序表L存在 操作结果:返回指针p,指向不大于e的最大元素的结点,若有元素=e,则返回null } */ #include "Node.h" typedef struct OrderedList{ LinkType head, tail; } OrderedList; OrderedList *InitList(void); void DestroyList(OrderedList *L); void AppendElem(OrderedList *L, LinkType s); status InsertAfter(OrderedList *L, LinkType p, ElemType e); LinkType LocateElem(OrderedList *L, ElemType e); OrderedList *InitList(void){ //需要增设头指针作为MakeNode的参数 OrderedList *L; L = (OrderedList*)malloc(sizeof(OrderedList)); if (L) { L->head = MakeNode(' '); if(L->head) L->tail = L->head; else L->head = L->tail = NULL; } return L; }//InitList void DestroyList(OrderedList *L){ LinkType p,s; p = L->head; while(p){ s = p; p = p->next; FreeNode(s); } L->head = L->tail = NULL; } void AppendElem(OrderedList *L, LinkType s){ if(L->head && s){ //需要增设有序链表的尾指针,否则AppendElem的时间复杂度为O(n),而此函数又经常用到 L->tail->next = s; L->tail = s; } }//AppendElem status InsertAfter(OrderedList *L, LinkType p, ElemType e){ LinkType q; q = MakeNode(e); if(!q) return FALSE; if(!p->next){ L->tail = q; } q->next = p->next; p->next = q; return TRUE; } LinkType LocateElem(OrderedList *L, ElemType e){ LinkType s,p; s = L->head; p = L->head->next; while(p && p->data <= e){ if(p->data == e) return NULL; s = p; p = p->next; } return s; } #endif /* OrdList_h */
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <time.h> #include <sys/time.h> #include <stdint.h> #include <inttypes.h> #define MATRIX_A_ROWS 3 #define MATRIX_A_COLUMNS 2 #define MATRIX_B_ROWS 2 #define MATRIX_B_COLUMNS 3 #define NUM_THREADS 9 void *calc_cell(void *args); int **init_matrix(int row, int column); void fill_matrix(int row, int column, int **matrix); pthread_t tid[9]; typedef struct { int i; int j; int **mr; int **ma; int **mb; } args_struct; struct timespec start, stop; void get_time(){ uint64_t delta_us = (stop.tv_sec - start.tv_sec) * 1000000 + (stop.tv_nsec - start.tv_nsec) / 1000; printf("Took %" PRIu64 "ms\n", delta_us); //printf("took %lu\n", delta_us); } void set_start(){ clock_gettime(CLOCK_MONOTONIC_RAW, &start); } void set_stop(){ clock_gettime(CLOCK_MONOTONIC_RAW, &stop); } void *calc_cell(void *args){ int sum,k; sum = 0; args_struct *m_args = args; for (k = 0; k < MATRIX_B_ROWS; k++) { sum = sum + m_args -> ma[m_args->i][k] * m_args -> mb[k][m_args->j]; } m_args -> mr[m_args->i][m_args->j] = sum; free(m_args); pthread_exit(0); } void matrix_multiplication(int **ma, int **mb, int **mr){ int i,j,k = 0; for (i = 0; i < MATRIX_A_ROWS; i++) { for (j = 0; j < MATRIX_B_COLUMNS; j++) { args_struct *args = (args_struct*)malloc(sizeof(args_struct)); args -> i = i; args -> j = j; args -> mr = mr; args -> ma = ma; args -> mb = mb; printf("creating thread\n"); pthread_create(&(tid[k]), NULL, &calc_cell, args); k++; } } } void print_matrix(int row, int column, int **matrix){ int i,j; for(i = 0; i < row; i++){ printf("|"); for (j = 0; j < column; j++){ if(j != column - 1) printf("%d,", matrix[i][j]); else printf("%d", matrix[i][j]); } printf("|\n"); } } int** init_matrix(int row, int column){ int **matrix = (int**)malloc(sizeof(int *)*row); int i; for(i = 0; i < row; i++){ int cell_size = sizeof(int)*column; matrix[i] = (int*)malloc(cell_size); } return matrix; } void fill_matrix(int row, int column, int **matrix){ int i,j; for(i = 0; i < row; i++){ for (j = 0; j < column; j++){ printf("Insert [%d][%d] element: ",i,j); scanf("%d",&matrix[i][j]); printf("\n"); } } } void fill_matrix_with_zeros(int row, int column, int **matrix){ int i,j; for(i = 0; i < row; i++){ for (j = 0; j < column; j++){ matrix[i][j] = 0; } } } int main(){ set_start(); int **matrix_a = init_matrix(MATRIX_A_ROWS, MATRIX_A_COLUMNS); int **matrix_b = init_matrix(MATRIX_B_ROWS, MATRIX_B_COLUMNS); int **mr = init_matrix(MATRIX_A_ROWS, MATRIX_B_COLUMNS); printf("Fill matrix a: \n"); fill_matrix(MATRIX_A_ROWS,MATRIX_A_COLUMNS, matrix_a); printf("Fill matrix b: \n"); fill_matrix(MATRIX_B_ROWS,MATRIX_B_COLUMNS, matrix_b); fill_matrix_with_zeros(MATRIX_A_ROWS,MATRIX_B_COLUMNS, mr); matrix_multiplication(matrix_a, matrix_b, mr); int i; for(i = 0; i < NUM_THREADS; i++){ printf("joining thread n: %d\n", i); pthread_join(tid[i], NULL); } set_stop(); print_matrix(MATRIX_A_ROWS,MATRIX_B_COLUMNS, mr); get_time(); return 0; }
C
#include <stdio.h> void mergesort(int a[], int i, int j); void merge(int a[], int i1, int j1, int i2, int j2); unsigned long long int nCr (int n, int r); int main() { int count = 0; int n, i, k, t, b = 0; scanf("%d", &t); for (int l = 0; l < t; l++) { // printf("Enter no of elements:"); scanf("%d", &n); int a[n]; scanf("%d", &k); // printf("Enter array elements:"); for (i = 0; i < n; i++) scanf("%d", &a[i]); mergesort(a, 0, n - 1); // printf("\nSorted array is :"); // for (i = 0; i < n; i++) // printf("%d\n", a[i]); for (int i = 0; i < n; i++) { if( i > k - 1) count++; if(a[k - 1] == a[i]) b++; else break; } printf("%llu\n", nCr(b, b - count)); } return 0; } unsigned long long int nCr (int n, int r) { unsigned long long int res = 1; int k = r >= (float)n / 2 ? n - r : r; int i , j; for(i = n, j = 1; i > n - k, j <= k; i--,j++){ res = (res * i )/ j; } return res; } void mergesort(int a[], int i, int j) { int mid; if (i < j) { mid = (i + j) / 2; mergesort(a, i, mid); //left recursion mergesort(a, mid + 1, j); //right recursion merge(a, i, mid, mid + 1, j); //merging of two sorted sub-arrays } } void merge(int a[], int i1, int j1, int i2, int j2) { int temp[50]; //array used for merging int i, j, k; i = i1; //beginning of the first list j = i2; //beginning of the second list k = 0; while (i <= j1 && j <= j2) //while elements in both lists { if (a[i] < a[j]) temp[k++] = a[i++]; else temp[k++] = a[j++]; } while (i <= j1) //copy remaining elements of the first list temp[k++] = a[i++]; while (j <= j2) //copy remaining elements of the second list temp[k++] = a[j++]; //Transfer elements from temp[] back to a[] for (i = i1, j = 0; i <= j2; i++, j++) a[i] = temp[j]; }
C
#include <stdio.h> #include<conio.h> int sarrus(int m[3][3]) { return (m[0][0] * m[1][1] * m[2][2]) + (m[0][1] * m[1][2] * m[2][0]) + (m[0][2] * m[1][0] * m[2][1]) - (m[0][2] * m[1][1] * m[2][0]) - (m[0][1] * m[1][0] * m[2][2]) - (m[0][0] * m[1][2] * m[2][1]); } void matrixPrint(int m[3][3]) { int i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { printf("%i ", m[i][j]); } printf("\n"); } } void matrixSwap(int* m1[], int* m2[]) { int aux[3][3]; int i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { aux[i][j] = m1[i][j]; } } } int main() { int i, j, k, l; int aux[3][3]; int v[4][3][3] = { { {-2, 2, 3}, {-1, 1, 3}, {2, 0, -1} }, // v[0] { { 3, 1, 5}, { 2, 0, 1}, {1, 4, 3} }, // v[1] { {-2, 2, 3}, {-1, 1, 3}, {4, 1, -4} }, // v[2] { { 1, 2, 3}, { 0, 2, 3}, {3, 0, -1} } // v[3] }; for (i = 0; i < 4; i++) { //printf("v[%i] = \n", i); //matrixPrint(v[i]); printf("det(v[%i]) = %i\n", i, sarrus(v[i])); } for (i = 0; i < 4 - 1; i++) { for (j = i + 1; j < 4; j++) { if (sarrus(v[i]) > sarrus(v[j])) { printf("v[%i] > v[%i]\n", i, j); // Swap for (k = 0; k < 3; k++) { for (l = 0; l < 3; l++) { aux[k][l] = v[i][k][l]; v[i][k][l] = v[j][k][l]; v[j][k][l] = aux[k][l]; } } } } } for (i = 0; i < 4; i++) { printf("v[%i] = \n", i); matrixPrint(v[i]); } getch(); return 0; }
C
#include <stdio.h> int main() { float a = 3.1415921, b = 3.14; double c = 23412.123412341; printf("a = %f, b = %f\n", a, b); printf("c = %lf\n", c); return 0; }
C
#include <stdio.h> #define PAWN 0 #define KNIGHT 1 #define BISHOP 2 #define ROOK 3 #define QUEEN 4 #define KING 5 #define BLACK 0 #define WHITE 1 #define VIRGIN 16 #define EMPTY -1 void piece2character(int code){ char *character_string = "pnbrqk"; if (code == EMPTY){ putchar(' '); return; } int type = (code >> 1) & 7; putchar(character_string[type] + ((code & 1) ? ('A' - 'a') : 0)); } void print_line(){ int i; for (i=0; i<8; ++i){ printf("+---"); } printf("+\n"); } void print_board(int *board){ int i; for (i=0; i<8; ++i){ print_line(); int j; for (j=0; j<8; ++j){ printf("+ "); piece2character(board[i*8 + j]); printf(" "); } printf("+"); printf("\n"); } print_line(); } void put_fen(int *board, char *fen){ int i; i=0; while (1){ if (fen[i] == ' '){ break; } if ( ('a' < fen[i] && fen[i] < 'z') || ('A' < fen[i] && fen [i] <'Z') ){ int index=i; int rank = 0; while (1){ if (index == 0) break; --index; if (fen[index] == '/'){ ++rank; } } int file = 0; index = i; while (1){ if (index == 0) break; --index; if (fen[index] == '/') break; if ( ('a' < fen[index] && fen[index] < 'z') || ('A' < fen[index] && fen[index] < 'Z') ){ ++file; } else if ('0' < fen[index] && fen[index] < '9'){ file += fen[index] - '0'; } } int piece; int type = fen[i]; int color = BLACK; if ('A' < type && type < 'Z'){ type += ('a' - 'A'); color = WHITE; } switch (type){ case 'p': piece = PAWN; break; case 'r': piece = ROOK; break; case 'n': piece = KNIGHT; break; case 'b': piece = BISHOP; break; case 'q': piece = QUEEN; break; case 'k': piece = KING; break; } if (piece == PAWN){ if (color == BLACK && file == 1){ piece |= (VIRGIN >> 1); } else if (color == WHITE && file == 6){ piece |= (VIRGIN >> 1); } } piece <<= 1; piece |= color; board[rank * 8 + file] = piece; } ++i; } } int main (){ int board[64] = {0}; int i; for (i=0; i<64; ++i) board[i] = EMPTY; put_fen(board, "r3kbnr/8/pppppppp/b1K3N1/RP2P2R/4nq2/P1PP1PPP/2BQ1BN1 "); print_board(board); return 0; }
C
//{======================================================================= //! @file stack_cpu4.h //! @date 11.11.2013 4:10 //! @author Andrey Drobyshev <immortalguardian1@gmail.com> //! @version 4.0 //! //! This program contains functions for work with stack CPU. //}======================================================================= #include "../Stack/stckcount.h" #include "../System/commands.h" #include "../System/registers.h" #include "../System/constants.h" #include <strings.h> #include <assert.h> #include <stdio.h> //{========================================================================================================================= //! @def ASSERT(cpu) - checks out if the cpu structure is ok. If it's not, prints dump. //! //! @param cpu - adress of cpu structure. //}========================================================================================================================= #define ASSERT(cpu) \ {if (!(cpu_ok (cpu))) \ { \ printf ("####################################\n"); \ printf ("#All is gone bad\n"); \ printf ("#Program was unexpectedly aborted\n"); \ printf ("####################################\n\n"); \ cpu_dump (cpu); \ abort (); \ }} //{========================================================================================================================= //! @def EXE_ERROR - aborts program if something is wrong //}========================================================================================================================= #define EXE_ERROR { \ printf ("######################################\n"); \ printf ("#Invalid input\n"); \ printf ("#Program was unexpectedly aborted\n"); \ printf ("######################################\n"); \ abort (); \ } typedef struct { stack_t* stack; stack_t* call_stack; elem_t* mem; elem_t ax; elem_t bx; elem_t cx; elem_t dx; } cpu_t; //{========================================================================== //! Function cpu_delete - destroys cpu structure. //! //! @param cpu Pointer to cpu we need to destroy. //! //! @return 1 if it's been done. //! //! @note The function has assertion checks. //}========================================================================== int cpu_delete (cpu_t* cpu); //{========================================================================== //! Function cpu_dump - prints information about current cpu state. //! //! @param cpu Pointer to cpu. //! //! @return Nothing to be returned. //}=========================================================================== void cpu_dump (const cpu_t* const cpu); //{========================================================================== //! Function cpu_new - create cpu structure of needed stack size. //! //! @return Pointer to the cpu. //! //! @note The function has assertion checks. //}=========================================================================== cpu_t* cpu_new (); //{========================================================================== //! Function cpu_ok - checks out if cpu is ok. //! //! @param cpu Pointer to the stack. //! //! @return 1 it's ok. //! 0 if not. //}=========================================================================== int cpu_ok (const cpu_t* const cpu); //{========================================================================== //! Function cpu_run - reads user's asm program from text file and run it. //! //! @param cpu Pointer to cpu. //! @param **exec_file Input file's name. //! //! @return Result of program's work (stack top). //! //! @note The function has assertion checks. //}=========================================================================== elem_t cpu_run (cpu_t* const cpu, FILE** out_file); //{========================================================================== //! Function cpu_mov Copies value to CPU register. //! //! @param cpu Pointer to cpu. //! @param arg1 Register code. //! @param arg2 A number or another register code. //! //! @return 1 if it's ok. //}=========================================================================== int cpu_mov (cpu_t* cpu, elem_t arg1, elem_t arg2, const char* mode); //{========================================================================== //! Function push_reg Pushes a value from register into stack. //! //! @param cpu Pointer to cpu. //! @param reg_code Register code. //! //! @return 1 if it's ok. //}=========================================================================== int cpu_push_reg (cpu_t* cpu, int reg_code); //{========================================================================== //! Function pop_reg Moves a value from stack into register. //! //! @param cpu Pointer to cpu. //! @param reg_code Register code. //! //! @return 1 if it's ok. //}=========================================================================== int cpu_pop_reg (cpu_t* cpu, int reg_code); //{========================================================================== //! Function real_to_int This magic function receives a real number //! and gives it back just like it's integer. //! //! @param val A real number. //! //! @return Integer value. //}=========================================================================== int real_to_int (double val); //{========================================================================== //! Function in_reg To read a number from keyboard and put it into //! CPU register. //! //! @param *cpu Pointer to CPU structure. //! @param cnt Memory counter current value. //! //! @return 0 if it's OK. //! -1 if there's no such a register. //}=========================================================================== int in_reg (cpu_t* cpu, int cnt); cpu_t* cpu_new () { cpu_t* cpu = (cpu_t*) calloc (1, sizeof (cpu_t)); cpu->mem = (elem_t*) calloc (MEM_SIZE, sizeof (elem_t)); cpu->ax = 0; cpu->bx = 0; cpu->cx = 0; cpu->dx = 0; cpu->stack = stack_new (STACK_SIZE); cpu->call_stack = stack_new (CALL_STACK_SIZE); ASSERT(cpu); return cpu; } int cpu_delete (cpu_t* cpu) { ASSERT(cpu); cpu->ax = POISON; cpu->bx = POISON; cpu->cx = POISON; cpu->dx = POISON; stack_delete (cpu->stack); stack_delete (cpu->call_stack); unsigned punisher = 0; for (punisher = 0; punisher <= MEM_SIZE - 1; punisher ++) { assert (punisher >= 0); assert (punisher <= MEM_SIZE - 1); cpu->mem [punisher] = POISON; } free (cpu->mem); free (cpu); cpu->stack = NULL; cpu->call_stack = NULL; cpu->mem = NULL; return 0; } int cpu_push_reg (cpu_t* cpu, int reg_code) { switch (reg_code) { case REG_AX: { stack_push (cpu->stack, cpu->ax); return 0; } case REG_BX: { stack_push (cpu->stack, cpu->bx); return 0; } case REG_CX: { stack_push (cpu->stack, cpu->cx); return 0; } case REG_DX: { stack_push (cpu->stack, cpu->dx); return 0; } } return 1; } int cpu_pop_reg (cpu_t* cpu, int reg_code) { switch (reg_code) { case REG_AX: { stack_pop (cpu->stack, &(cpu->ax)); return 0; } case REG_BX: { stack_pop (cpu->stack, &(cpu->bx)); return 0; } case REG_CX: { stack_pop (cpu->stack, &(cpu->cx)); return 0; } case REG_DX: { stack_pop (cpu->stack, &(cpu->dx)); return 0; } } return 1; } int cpu_ok (const cpu_t* const cpu) { return (cpu != NULL && stack_ok (cpu->stack) && cpu->mem != NULL && stack_ok (cpu->call_stack)); } void cpu_dump (const cpu_t* const cpu) { printf ("\n####################################\n"); printf ("#CPU [%x] is", cpu); if (cpu_ok (cpu)) printf (" ok\n"); else printf (" BAD!\n"); printf ("\n#ax = %g\n", cpu->ax); printf ("\n#bx = %g\n", cpu->bx); printf ("\n#cx = %g\n", cpu->cx); printf ("\n#dx = %g\n", cpu->dx); if (!(cpu->mem)) printf ("\n#ERROR: memory blocks are damaged"); else { printf ("####################################\n"); printf ("#Memory [%x] map\n\n", cpu->mem); unsigned mem_prnt = 0; for (mem_prnt = 0; mem_prnt <= MEM_SIZE - 1; mem_prnt++) { assert (mem_prnt >= 0); assert (mem_prnt <= MEM_SIZE - 1); printf ("%4x %g\n", mem_prnt, cpu->mem [mem_prnt]); } } if (!(cpu->call_stack)) printf ("\n#ERROR: call stack doesn't exist\n"); else stack_dump (cpu->call_stack); if (!(cpu->stack)) printf ("\n#ERROR: stack doesn't exist\n"); else stack_dump (cpu->stack); return; } elem_t cpu_run (cpu_t* const cpu, FILE** out_file) { ASSERT (cpu); char halt_flag = 0; int cnt = -1; elem_t buf_val1 = 0, buf_val2 = 0; while (1) { cnt++; switch (real_to_int (cpu->mem [cnt])) { case CMD_ERROR: EXE_ERROR; case CMD_HALT: { halt_flag = 1; break; } case CMD_PUSH_NUM: { stack_push (cpu->stack, cpu->mem [++cnt]); break; } case CMD_PUSH_REG: { cpu_push_reg (cpu, cpu->mem [++cnt]); break; } case CMD_POP_REG: { cpu_pop_reg (cpu, cpu->mem [++cnt]); break; } case CMD_MOV_NUM: { cpu_mov (cpu, cpu->mem [cnt + 1], cpu->mem [cnt + 2], "n"); cnt += 2; break; } case CMD_MOV_REG: { cpu_mov (cpu, cpu->mem [cnt + 1], cpu->mem [cnt + 2], "r"); cnt += 2; break; } case CMD_ADD: { stack_add (cpu->stack); break; } case CMD_SUB: { stack_sub (cpu->stack); break; } case CMD_MUL: { stack_mul (cpu->stack); break; } case CMD_DIV: { stack_div (cpu->stack); break; } case CMD_SIN: { stack_sin (cpu->stack); break; } case CMD_COS: { stack_cos (cpu->stack); break; } case CMD_TAN: { stack_tan (cpu->stack); break; } case CMD_SQRT: { stack_sqrt (cpu->stack); break; } case CMD_EXP: { stack_exp (cpu->stack); break; } case CMD_POW: { stack_pow (cpu->stack); break; } case CMD_DUMP: { cpu_dump (cpu); break; } case CMD_NOP: break; case CMD_JMP: { cnt = cpu->mem [cnt + 1]; cnt--; break; } case CMD_JE: { stack_pop (cpu->stack, &buf_val1); stack_pop (cpu->stack, &buf_val2); if (buf_val1 == buf_val2) { cnt = cpu->mem [cnt + 1]; cnt--; } else cnt++; break; } case CMD_JNE: { stack_pop (cpu->stack, &buf_val1); stack_pop (cpu->stack, &buf_val2); if (buf_val1 != buf_val2) { cnt = cpu->mem [cnt + 1]; cnt--; } else cnt++; break; } case CMD_JA: { stack_pop (cpu->stack, &buf_val1); stack_pop (cpu->stack, &buf_val2); if (buf_val1 < buf_val2) { cnt = cpu->mem [cnt + 1]; cnt--; } else cnt++; break; } case CMD_JB: { stack_pop (cpu->stack, &buf_val1); stack_pop (cpu->stack, &buf_val2); if (buf_val1 > buf_val2) { cnt = cpu->mem [cnt + 1]; cnt--; } else cnt++; break; } case CMD_JAE: { stack_pop (cpu->stack, &buf_val1); stack_pop (cpu->stack, &buf_val2); if (buf_val1 <= buf_val2) { cnt = cpu->mem [cnt + 1]; cnt--; } else cnt++; break; } case CMD_JBE: { stack_pop (cpu->stack, &buf_val1); stack_pop (cpu->stack, &buf_val2); if (buf_val1 >= buf_val2) { cnt = cpu->mem [cnt + 1]; cnt--; } else cnt++; break; } case CMD_OUT: { stack_pop (cpu->stack, &buf_val1); fprintf (*out_file, "%g ", buf_val1); break; } case CMD_IN_REG: { in_reg (cpu, cnt); cnt++; break; } case CMD_CALL: { stack_push (cpu->call_stack, (cnt + 1)); cnt = cpu->mem [cnt + 1]; cnt--; break; } case CMD_RET: { stack_pop (cpu->call_stack, &buf_val1); cnt = buf_val1; break; } } if (halt_flag) break; } stack_pop (cpu->stack, &buf_val1); return buf_val1; } int real_to_int (double val) { return val; } int cpu_mov (cpu_t* cpu, elem_t arg1, elem_t arg2, const char* mode) { elem_t* pointer1 = NULL; elem_t* pointer2 = NULL; if (mode == "n") { switch (real_to_int (arg1)) { case REG_AX: { cpu->ax = arg2; return 0; } case REG_BX: { cpu->bx = arg2; return 0; } case REG_CX: { cpu->cx = arg2; return 0; } case REG_DX: { cpu->dx = arg2; return 0; } } } if (mode == "r") { switch (real_to_int (arg1)) { case REG_AX: { pointer1 = &(cpu->ax); break; } case REG_BX: { pointer1 = &(cpu->bx); break; } case REG_CX: { pointer1 = &(cpu->cx); break; } case REG_DX: { pointer1 = &(cpu->dx); break; } } switch (real_to_int (arg2)) { case REG_AX: { pointer2 = &(cpu->ax); break; } case REG_BX: { pointer2 = &(cpu->bx); break; } case REG_CX: { pointer2 = &(cpu->cx); break; } case REG_DX: { pointer2 = &(cpu->dx); break; } } *pointer1 = *pointer2; } return 1; } int load_program (cpu_t* cpu, FILE** exec_file) { unsigned cnt = 0; elem_t buf_val = 0; while (1) { fscanf (*exec_file, "%lg", &buf_val); if (!(feof (*exec_file))) cpu->mem [cnt++] = buf_val; else break; } fclose (*exec_file); return 0; } int in_reg (cpu_t* cpu, int cnt) { switch (real_to_int(cpu->mem [cnt + 1])) { case REG_AX: { scanf ("%lg", &(cpu->ax)); return 0; } case REG_BX: { scanf ("%lg", &(cpu->bx)); return 0; } case REG_CX: { scanf ("%lg", &(cpu->cx)); return 0; } case REG_DX: { scanf ("%lg", &(cpu->dx)); return 0; } } return -1; }
C
#include <stdio.h> #include <string.h> char arr[21]; int main() { int i; int max,len; scanf("%s",arr); len = strlen(arr); max = (len)/2-1; for(i=0;i<=max;i++) if(arr[0+i]!=arr[len-1-i]) {puts("false"); return 0;} puts("true"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* map.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: znazam <znazam@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/11 08:32:23 by znazam #+# #+# */ /* Updated: 2019/07/12 09:08:32 by znazam ### ########.fr */ /* */ /* ************************************************************************** */ #inlcude "fdf.h" int fun(t_env *env) { int y = 0; int x; while (y < 3) { x = 0; while (x < 3) { printf(“%i, %i : %lf\n”, y, x, env->map[y][x]); x++; } y++; } return 0; } int fun(t_env *env) { int y = 0; int x; while (y < 3) { x = 0; while (x < 3) { printf(“%i, %i : %lf\n”, y, x, env->map[y][x]); x++; } y++; } return 0; } int my_key_funct(int keycode) { printf(“key event %d\n”, keycode ); // mlx_pixel_put(mlx, window, 300, 300, 0xFF00FF); // to handle the key input for the program to respond towards to if (keycode == 53) exit(0); return (0); } int exitb(void) { exit(1); return (0); } int main(int argc, char **argv) { t_env v; v.mlx_ptr = mlx_init(); v.win_ptr = mlx_new_window(v.mlx_ptr, 500, 500, “FDF”); v.map[0][0] = 0; v.map[0][1] = 0; v.map[0][2] = 0; v.map[1][0] = 0; v.map[1][1] = 1; v.map[1][2] = 0; v.map[2][0] = 0; v.map[2][1] = 0; v.map[2][2] = 0; if (argc != 2) { printf(“Invalid parameters\n”); printf(“usage : ./fdf map”); } else { argv = NULL; mlx_loop_hook(v.mlx_ptr, fun, &v); mlx_key_hook(v.win_ptr, my_key_funct, 0); mlx_hook(v.win_ptr, 17, 0L, exit_button, &v); mlx_loop(v.mlx_ptr); } return (0); }
C
#include <unistd.h> #include <sys/types.h> #include <errno.h> #include <stdio.h> #include <sys/wait.h> #include <stdlib.h> int main() { pid_t pidA; int randVal; int status; pidA= fork(); if (pidA >= 0) /* fork succeeded */ { if (pidA == 0) /* fork() returns 0 to the child process */ { printf("CHILD process!\n"); printf("CHILD PID: %d\n", getpid()); printf("CHILD parent's PID is: %d\n", getppid()); printf("CHILD copy of pidA is: %d\n", pidA); printf("CHILD Sleeping for 1 second...\n"); sleep(1); /* sleep for 1 second */ randVal = rand()%1000; printf("CHILD Process Random Value: %drandVal "); printf("CHILD: Goodbye!\n"); exit(randVal); /* child exits with user-provided return code */ } else /* fork() returns new pid to the parent process */ { printf("Parent process!\n"); printf("Parent's PID: %d\n", getpid()); printf("Praent's copy of pidA is %d\n", pidA); printf("PARENT waiting for the child to exit.\n"); wait(&status); /* wait for child to exit, and store its status */ printf("PARENT: Child's exit code is: %d\n", WEXITSTATUS(status)); printf("PARENT: Goodbye!\n"); exit(0); /* parent exits */ } } else { perror("fork"); exit(0); } }
C
#include <math.h> #include "arm.h" int32 signed_sat(int64 val, int32 n, bool *issat) { int32 pown = powl(2, n - 1); int32 pown1 = pown - 1; if (val < -pown) { *issat = true; return -pown; } else if (val > pown1) { *issat = true; return pown1; } else { *issat = false; return val; } } uint32 unsigned_sat(int64 val, uint32 n, bool *issat) { int32 pown = powl(2, n); int32 pown1 = pown - 1; if (val < 0) { *issat = true; return 0; } else if (val > pown1) { *issat = true; return pown1; } else { *issat = false; return val; } }
C
#include "string.h" #include "stdlib.h" #include "SymbolTable.h" void initializeTable(SymbolTable *S){ int index = 0; S->keys[index] = "SP"; S->addresses[index] = 0; index++; S->keys[index] = "LCL"; S->addresses[index] = 1; index++; S->keys[index] = "ARG"; S->addresses[index] = 2; index++; S->keys[index] = "THIS"; S->addresses[index] = 3; index++; S->keys[index] = "THAT"; S->addresses[index] = 4; index++; S->keys[index] = "R0"; S->addresses[index] = 0; index++; S->keys[index] = "R1"; S->addresses[index] = 1; index++; S->keys[index] = "R2"; S->addresses[index] = 2; index++; S->keys[index] = "R3"; S->addresses[index] = 3; index++; S->keys[index] = "R4"; S->addresses[index] = 4; index++; S->keys[index] = "R5"; S->addresses[index] = 5; index++; S->keys[index] = "R6"; S->addresses[index] = 6; index++; S->keys[index] = "R7"; S->addresses[index] = 7; index++; S->keys[index] = "R8"; S->addresses[index] = 8; index++; S->keys[index] = "R9"; S->addresses[index] = 9; index++; S->keys[index] = "R10"; S->addresses[index] = 10; index++; S->keys[index] = "R11"; S->addresses[index] = 11; index++; S->keys[index] = "R12"; S->addresses[index] = 12; index++; S->keys[index] = "R13"; S->addresses[index] = 13; index++; S->keys[index] = "R14"; S->addresses[index] = 14; index++; S->keys[index] = "R15"; S->addresses[index] = 15; index++; S->keys[index] = "SCREEN"; S->addresses[index] = 16384; index++; S->keys[index] = "KBD"; S->addresses[index] = 24576; index++; S->index = index; S->varIndex = 16; } void addEntry(SymbolTable *S, char *symbol, int address){ S->keys[S->index] = symbol; S->addresses[S->index] = address; S->index++; } int getIndexOf(SymbolTable *S, char *symbol){ for (int i = 0; i < S->index; i++) { if (!strcmp(S->keys[i], symbol)) return i; } return -1; } int getAddress(SymbolTable *S, char *symbol){ int index = getIndexOf(S, symbol); if (index == -1) { addEntry(S, symbol, S->varIndex); S->varIndex++; return S->varIndex - 1; } else return S->addresses[index]; }
C
#include <stdio.h> int main() { #if 0 // pointer type int data = 0x12345678; printf("%p\n", &data); printf("%x\n", *(&data)); printf("%x\n", *((int*)0x7ffee4452a98)); printf("%x\n", *((char*)0x7ffee4452a98)); printf("%x\n", *((short*)0x7ffee4452a98)); printf("%x\n", *((int*)0x7ffee4452a98)); return 0; // NULL is used for pointer which is not used right now. // NULL cannot be read and written int * pa = NULL; // NULL (void *)0 * pa = 100; if(* pa != NULL) printf("%d", *pa); #endif int *p = (int*)0x0001; int data = 0x0001; printf("p = %#x p+1 = %#x\n", p, p+1); printf("data = %#x data+1 = %#x\n", data, data+1); printf("(double*)p = %#x (double*)p+1 = %#x\n", (double*)p, (double*)p+1); printf("(int)p = %#x (int)p+1 = %#x\n", (int)p, (int)p+1); printf("%x\n",++p); printf("%x\n",++data); // int arr[10]; int pHead = (int)&arr[0]; int pTail = (int)&arr[9]; printf("%d\n", pTail - pHead); return 0; }
C
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> // Ce bo datoteka prevelika, bo prebral samo 10000 znakov. #define BUFSIZE 10000 #define err(mess) { fprintf( stderr, "napaka: %s\n", mess); exit(1); } void delete_line( int fd, int vrstica); void main( int argc, char *argv[]) { int fd; int n; char buf[BUFSIZE]; if ( argc == 3) // append line { // odpre argumet 1. Ce ne obstaja, ga bo naredu. Bo appendu. Dodam rw za vse. fd = open( argv[1], O_CREAT | O_WRONLY | O_APPEND, 0666); if ( fd < 0) { err("open") } // Preberem ceu file v buffer - ni narejeno za velike datoteke n = read(STDIN_FILENO, buf, BUFSIZE); if ( n < 0) { err("read") } if ( write( fd, buf, n) != n) { err("read") } } else if ( argc == 4) // delete line { fd = open( argv[1], O_RDWR, 0666); if ( fd < 0) { err("open") } // Funkciji podam vrstico za izbris delete_line( fd, atoi(argv[3])); } else { err("Uporaba:\n\tedi <datoteka> a\n\tedi <datoteka> d <stevilka:vrstice.\n"); } close(fd); } void delete_line( int fd, int vrstica) { char buf[BUFSIZE]; int n; int i, j; int lines; int zacetek = 0, konec, dolzina; n = read( fd, buf, BUFSIZE); if ( n < 0) { err("read") } i = 0; // stevec znakov lines = 0; do { if ( buf[i] == '\n') { lines++; if ( lines == vrstica - 1) { zacetek = i + 1; } } i++; // Loopamo, dokler ne najdemo vrstice. } while ( lines < vrstica); konec = i - 1; // Zapomnimo si azcectek in koenc nase vrstice in zracunamo dolzino. dolzina = konec - zacetek + 1; printf("zacetek: %d, konec: %d, dolzina %d, n: %d\n", zacetek, konec, dolzina, n); // gremo od konca +1 do konca datoeke. for (j = konec + 1; j <= n - 1; j++) { buf[j - dolzina] = buf[j]; //za vecje datoteke bolje memcpy } // grem na zacetek fajla lseek( fd, 0, SEEK_SET); // zapisem celoten buffer if (write( fd, buf, n - dolzina) != n - dolzina) { err("write") } // Odrezem od tam naprej. ftruncate( fd, n - dolzina); }
C
#ifndef HASH_TABLE_H #define HASH_TABLE_H #include <stdlib.h> // mutate typedef of key_t, object_t and hf_param_t typedef int key_t; typedef int object_t; typedef int hf_param_t; typedef struct l_node { key_t key; object_t *obj; struct l_node *next; } list_node_t; typedef struct { int size; list_node_t **table; int (*hash_function)(key_t, hf_param_t); hf_param_t hf_param; } hashtable_t; list_node_t *get_node() { list_node_t *tmp; tmp = (list_node_t *) malloc( sizeof(list_node_t) ); return tmp; } void return_node(list_node_t *node) { free(node); } hashtable_t *create_hashtable(int size, int (*hash_function)(key_t, hf_param_t), hf_param_t hf_param) { hashtable_t *tmp; int i; tmp = (hashtable_t *) malloc( sizeof(hashtable_t) ); tmp->size = size; tmp->table = (list_node_t **) malloc(size*sizeof(list_node_t *)); tmp->hash_function = hash_function; tmp->hf_param = hf_param; for( i=0; i<size; i++ ) (tmp->table)[i] = NULL; return tmp; } object_t *ht_find(hashtable_t *ht, key_t query_key) { list_node_t *tmp_node; int i; i = ht->hash_function(query_key, ht->hf_param ); tmp_node = (ht->table)[i]; while( tmp_node != NULL && tmp_node->key != query_key ) tmp_node = tmp_node->next; if( tmp_node == NULL ) return NULL; else return tmp_node->obj; } void ht_insert(hashtable_t *ht, key_t new_key, object_t *new_obj) { list_node_t *tmp_node; int i; i = ht->hash_function(new_key, ht->hf_param ); tmp_node = (ht->table)[i]; (ht->table)[i] = get_node(); ((ht->table)[i])->next = tmp_node; ((ht->table)[i])->key = new_key; ((ht->table)[i])->obj = new_obj; } object_t *ht_delete(hashtable_t *ht, key_t del_key) { list_node_t *tmp_node; int i; object_t *tmp_obj; i = ht->hash_function(del_key, ht->hf_param ); tmp_node = (ht->table)[i]; if( tmp_node == NULL ) return NULL; if( tmp_node->key == del_key ) { tmp_obj = tmp_node->obj; (ht->table)[i] = tmp_node->next; return_node( tmp_node ); return tmp_obj; } while( tmp_node->next != NULL && tmp_node->next->key != del_key ) tmp_node = tmp_node->next; if( tmp_node->next == NULL ) return NULL; else { list_node_t *tmp_node2; tmp_node2 = tmp_node->next; tmp_node->next = tmp_node2->next; tmp_obj = tmp_node2->obj; return_node( tmp_node2 ); return tmp_obj; } } // create your hash function or use our default function (division method) int division_function(key_t key, hf_param_t hf_param) { return key % hf_param; } #endif
C
#include <stdio.h> int main() { int aux, numero1, numero2; printf("Escribe un primer n%cmero:\n", 163); scanf( "%d", &numero1 ); printf("Escribe un segundo n%cmero:\n", 163); scanf( "%d", &numero2 ); printf( "Los valores se han intercambiado\n" ); aux = numero1; numero1 = numero2; numero2 = aux; printf("El valor del primer n%cmero ha cambiado a %d\n", 163, numero1 ); printf("El valor del segundo n%cmero ha cambiado a %d\n", 163, numero2 ); return 0; }
C
/* * My drawing snake funs */ #include "my_snake.h" void init_curses() { /* 开启 curses 模式 */ initscr(); /* * 开启 cbreak 模式,除了DELETE\CTRL 等仍被视为特殊控制字元外 * 一切输入的字符将立刻被一一读取 */ cbreak(); /* * 用来决定当输入资料时 * 按下 RETURN 键是否被对应为 NEWLINE 字符 */ nonl(); /* * echo() and noecho() * 此函式用来控制从键盘输入字元时是否将字元显示在终端机上 */ noecho(); intrflush( stdscr, false ); /* * 当开启 keypad 後, 可以使用键盘上的一些特殊字符 * 如上下左右>等方向键 */ keypad( stdscr, true ); /* 将做清除萤幕的工作 */ refresh(); } void draw_head( SPOS *shead ) { if ( shead == NULL ) { return ; } mvwaddch( stdscr, shead->y, shead->x, '@' ); /* switch (dir) { case 1: // UP mvwaddch( stdscr, shead->y, shead->x, '^' ); break; case 2: // DOWN mvwaddch( stdscr, shead->y, shead->x, 'v' ); break; case 3: // RIGTH mvwaddch( stdscr, shead->y, shead->x, '>' ); break; case 4: // LEFT mvwaddch( stdscr, shead->y, shead->x, '<' ); break; default : break; } */ } void draw_body( SPOS *point ) { if ( point == NULL ) { return; } mvwaddch( stdscr, point->y, point->x, '&' ); } void draw_food( SPOS *point ) { if ( point == NULL ) { return; } mvwaddch( stdscr, point->y, point->x, '$' ); } void clear_ch( SPOS *point ) { if ( point == NULL ) { return; } mvwaddch( stdscr, point->y, point->x, ' ' ); } void get_size() { wmove( stdscr, LINES - 3, COLS - 3 ); getyx( stdscr, length, width ); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* updatePlace.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: emamenko <emamenko@student.42.us.org> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/01 12:47:53 by emamenko #+# #+# */ /* Updated: 2019/04/02 13:04:56 by emamenko ### ########.fr */ /* */ /* ************************************************************************** */ #include "header.h" int pow_int(int p) { return (1 << p); } unsigned int setPlace(unsigned int parkingRow, int pos) { return (parkingRow | (pow_int(pos))); } unsigned int clearPlace(unsigned int parkingRow, int pos) { return (parkingRow & (~pow_int(pos))); } unsigned int updatePlace(unsigned int parkingRow, int pos, int value) { return (value == 1 ? setPlace(parkingRow, pos) : clearPlace(parkingRow, pos)); }
C
#include <stdio.h> #include <stdlib.h> extern char ** environ; int main(){ char* s = getenv("USER"); printf("user is: %d\n", s ); const int consint; // consint = 32432; int data[5] = {10, 30, 60, 50, 40}; char string[] = "A B C 0123"; unsigned int temp; printf("data: %d\n", *(data + 1)); printf("Swapping\n"); temp = data[0]; data[0] = data[4]; data[4] = temp; for(size_t idx = 0; idx < 5; idx++){ printf("data[%zu] = %d\n", idx, *(data + idx) ); } return 0; }
C
#define MAX_QUEUE_SIZE 5000 typedef int element_type; //ring buffer //one slot is intentially set aside to mark if the buffer is full typedef struct{ volatile element_type data[MAX_QUEUE_SIZE + 1]; volatile int head; volatile int tail; } queue_type; extern void init_queue(queue_type * queue); //block until the element is pushed into the queue extern void push(queue_type * queue, const element_type* element); //block until an element is popped out of the queue extern void pop(queue_type * queue, element_type* element);
C
#include <stdlib.h> #include <stdio.h> #include <assert.h> #include "uthread.h" #include "uthread_sem.h" #ifdef VERBOSE #define VERBOSE_PRINT(S, ...) printf (S, ##__VA_ARGS__); #else #define VERBOSE_PRINT(S, ...) ; #endif #define MAX_ITEMS 10 const int NUM_ITERATIONS = 200; const int NUM_CONSUMERS = 2; const int NUM_PRODUCERS = 2; int producer_wait_count; // # of times producer had to wait int consumer_wait_count; // # of times consumer had to wait int histogram [MAX_ITEMS+1]; // histogram [i] == # of times list stored i items struct Sem { uthread_sem_t mutex; uthread_sem_t notMax; uthread_sem_t numItems; // sem for number of items int items; }; struct Sem* createSem() { struct Sem* s = malloc(sizeof(struct Sem)); s->mutex = uthread_sem_create(1); s->notMax = uthread_sem_create(MAX_ITEMS); s->numItems = uthread_sem_create(0); s->items = 0; return s; } void* producer (void* v) { struct Sem* s = v; // 1. acquire wrap_mutex for (int i=0; i<NUM_ITERATIONS; i++) { VERBOSE_PRINT("producer wait on s->notMax\n"); uthread_sem_wait(s->notMax); // 2. acquire mutex // CRITICAL SECTION uthread_sem_wait(s->mutex); assert(s->items < MAX_ITEMS); s->items++; VERBOSE_PRINT("producer inc'd s->items: %d\n", s->items); VERBOSE_PRINT("producer signaling s->numItems\n"); uthread_sem_signal(s->numItems); histogram[s->items]++; // END CRITICAL SECTION uthread_sem_signal(s->mutex); } return NULL; } void* consumer (void* v) { struct Sem* s = v; // 1. acquire wrap_mutex for (int i=0; i<NUM_ITERATIONS; i++) { VERBOSE_PRINT("consumer waiting on s->numItems\n"); uthread_sem_wait(s->numItems); // 2. acquire mutex // CRITICAL SECTION uthread_sem_wait(s->mutex); assert(s->items > 0); s->items--; VERBOSE_PRINT("consumer dec'd s->items: %d\n", s->items); VERBOSE_PRINT("consumer signaling s->notMax since we have consumed\n"); uthread_sem_signal(s->notMax); histogram[s->items]++; uthread_sem_signal(s->mutex); } return NULL; } int main (int argc, char** argv) { uthread_t t[4]; uthread_init (4); struct Sem* s = createSem(); for (int i = 0; i < NUM_PRODUCERS; i++) { t[i] = uthread_create(producer, s); } for (int i = 0; i < NUM_CONSUMERS; i++) { t[i + NUM_PRODUCERS] = uthread_create(consumer, s); } for (int i = 0; i < NUM_PRODUCERS + NUM_CONSUMERS; i++) { uthread_join(t[i], NULL); } printf ("producer_wait_count=%d, consumer_wait_count=%d\n", producer_wait_count, consumer_wait_count); printf ("items value histogram:\n"); int sum=0; for (int i = 0; i <= MAX_ITEMS; i++) { printf (" items=%d, %d times\n", i, histogram [i]); sum += histogram [i]; } assert (sum == sizeof (t) / sizeof (uthread_t) * NUM_ITERATIONS); }
C
#include<stm32f10x.h> #include"bianma.h" #include"delay.h" //DIOΪģʽ void DIO_IN(void) { GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; // GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); } //DIOΪģʽ void DIO_OUT(void) { GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; // GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); } //SPIʼ void SPI_init(void) { GPIO_InitTypeDef GPIO_InitStructure; RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOA, ENABLE); //ʱ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0|GPIO_Pin_1|GPIO_Pin_2; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; // GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //ƵΪ50HZ GPIO_Init(GPIOA, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; // GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); CS(1); CLK(0); DIO(1); } //ʹָ void send_com(unsigned int com) { unsigned int i; CS(1); delay_us(10); DIO_OUT(); delay_us(10); CS(0); CLK(0); delay_us(50); for(i=8;i>0;i--) { if(com&(0x01<<(i-1))) DIO(1); else DIO(0); CLK(1); delay_us(10); CLK(0); delay_us(10); } CS(1); } //ָ void send_datacom(unsigned int data,unsigned int com) { unsigned int i,j; CS(1); delay_us(10); DIO_OUT(); delay_us(10); CS(0); CLK(0); delay_us(50); for(i=8;i>0;i--) { if(com&(0x01<<(i-1))) DIO(1); else DIO(0); CLK(1); delay_us(10); CLK(0); if(i==0) delay_us(40); else delay_us(10); } for(j=8;j>0;j--) { if(data&(0x01<<(j-1))) DIO(1); else DIO(0); CLK(1); delay_us(10); CLK(0); delay_us(10); } delay_us(20); CS(1); } //ݺ unsigned int receive(unsigned int com) { unsigned int i,j,rebuf; rebuf=0; CS(1); delay_us(10); DIO_OUT(); delay_us(10); CS(0); CLK(0); delay_us(50); for(i=8;i>0;i--) { if(com&(0x01<<(i-1))) DIO(1); else DIO(0); CLK(1); delay_us(10); CLK(0); if(i==1) delay_us(30); else delay_us(10); } DIO_IN(); for(j=8;j>0;j--) { CLK(1); delay_us(10); rebuf=rebuf<<1; if(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_2)) rebuf|=1; else rebuf|=0; delay_us(10); CLK(0); delay_us(10); } DIO_OUT(); delay_us(10); CS(1); return rebuf; } unsigned int getkeycode(unsigned int dat) { unsigned int key; switch(dat) { case 0x07: key = 0x01;break; case 0x0f: key = 0x02;break; case 0x17: key = 0x03;break; case 0x1f: key = 0x04;break; case 0x27: key = 0x05;break; case 0x2f: key = 0x06;break; case 0x37: key = 0x07;break; case 0x3f: key = 0x08;break; case 0x06: key = 0x09;break; case 0x0e: key = 0x0a;break; case 0x16: key = 0x0b;break; case 0x1e: key = 0x0c;break; case 0x26: key = 0x0d;break; case 0x2e: key = 0x0e;break; case 0x36: key = 0x0f;break; case 0x3e: key = 0x10;break; case 0x05: key = 0x11;break; case 0x0d: key = 0x12;break; case 0x15: key = 0x13;break; case 0x1d: key = 0x14;break; case 0x25: key = 0x15;break; case 0x2d: key = 0x16;break; case 0x35: key = 0x17;break; case 0x3d: key = 0x18;break; default: key = 0xff;break; } return key; } // // unsigned int Key=0xff; // unsigned int dat=0; // if(!GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_3)) // { // Key=receive(0x15); // delay_us(10); // if(!GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_3)) // { // delay_us(10); // while(!GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_3)); // delay_us(10); // dat=getkeycode(Key); // printf("ֵ%d\r\n",dat); // } // } // //} // } /**/ //while(1) //{ // send_com(0xbf); // send_com(0xa4); // send_datacom(0x07,0x98); // send_datacom(0x01,0x80); // //delay_us(5); // send_datacom(0x02,0x81); // //delay_us(5); // send_datacom(0x03,0x82); // //delay_us(5); // send_datacom(0x04,0x83); // //delay_us(5); // send_datacom(0x05,0x84); // //delay_us(5); // send_datacom(0x06,0x85); // //delay_us(5); // send_datacom(0x07,0x86); // //delay_us(5); // send_datacom(0x08,0x87); // //delay_us(5); /**/
C
/** * @file fileUtils.h * @author Bastien T. * @date 21 January 2018 * @brief Utility functions for files */ #ifndef TP3_UTILS_H #define TP3_UTILS_H #include <sys/types.h> /** * Returns a concatenation of the folder and the filename * @param folder The folder where resides the file * @param filename The file's name * @return A new char of the format folder/filename */ char* getPath(char* folder, char *filename); /** * Makes a copy of the file at @p src to @p dest * @param srcFolder The source file's folder * @param src The filename of the source * @param destFolder The destination file's folder * @param dest The filename of the destination * @return The number of bytes written */ ssize_t copyFile(char *srcFolder, char *src, char *destFolder, char *dest); /** * Opens the file pointed by @p filename with the given @p flags * @param path The path * @param flags The flags to open the file with * @param ... If used with O_CREAT, the mode to set the file with * @return The file descriptor pointing to the file */ int openFile(char *path, int flags, ...); /** * Seeks at the @p offset starting either from the beginning, current position or end * @param fd The file descriptor of the file to seek into * @param offset The offset at which to start from * @param from The position from which to seek */ void seekFile(int fd, off_t offset, int from); /** * Writes the given @p buf into the file * @param fd The file descriptor * @param buf The buffer to write * @param length The length of the buffer * @return The number of bytes written */ ssize_t writeFile(int fd, void *buf, size_t length); /** * Seeks at the @p offset starting from the beginning, current position or end, then writes the given @p buf into the file * @param fd The file descriptor * @param buf The buffer to write * @param offset The offset at which to start from * @param from The position from which to seek * @param length The length of the buffer * @return The number of bytes written */ ssize_t writeFileOff(int fd, void *buf, off_t offset, int from, size_t length); /** * Reads @p length bytes into the given buffer * @param fd The file descriptor * @param buf The buffer that will contain the read bytes * @param length The number of bytes to read * @return The number of bytes actually read */ ssize_t readFile(int fd, void *buf, size_t length); /** * Seeks at the @p offset starting from the beginning, current position or end, then reads @p length bytes into the given buffer * @param fd The file descriptor * @param buf The buffer that will contain the read bytes * @param offset The offset at which to start from * @param from The position from which to seek * @param length The number of bytes to read * @return The number of bytes actually read */ ssize_t readFileOff(int fd, void *buf, off_t offset, int from, size_t length); /** * Closes a file * @param fd The file descriptor */ void closeFile(int fd); #endif
C
#include<stdio.h> #include<conio.h> #include<ctype.h> void main() { char character; clrscr(); printf("Enter the input:\n"); character=getchar(); if(isalpha(character)>0) printf("The input is a letter\n"); else if(isdigit(character)>0) printf("The input is a digit\n"); else printf("The input is not a alphanumeric\n"); getch(); }
C
//counter implemented w/ threads #include <stdio.h> #include <pthread.h> #include <stdlib.h> #define NUM_THREADS 100 #define NUM_ITERATIONS 5000 //data structure definition typedef struct __counter_t { int value; pthread_mutex_t lock; } counter_t; void init(counter_t *c) { c->value = 0; pthread_mutex_init(&c->lock, NULL); } void increment(counter_t *c) { pthread_mutex_lock(&c->lock); // To lock the mutex c->value++; pthread_mutex_unlock(&c->lock); // To unlock the mutex } int get(counter_t *c) { pthread_mutex_lock(&c->lock); int rc = c->value; pthread_mutex_unlock(&c->lock); return rc; } void* incrementCounter(void * arg) { counter_t *counterPtr = (counter_t *)arg; int i; for(i = 0; i < NUM_ITERATIONS; i++) { increment(counterPtr); } } int main() { //set up array of threads pthread_t threads[NUM_THREADS]; //initialize shared counter variable counter_t *my_counter = malloc(sizeof(counter_t)); init(my_counter); // Create those threads! long i; for (i = 0; i < NUM_THREADS; i++) { pthread_create(&threads[i], NULL, incrementCounter, (void *)my_counter); } // Use pthread_join to make the main thread pause for (i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], NULL); } printf("my counter's value: %d\n", get(my_counter)); return 0; }
C
#include<stdio.h> #include<stdlib.h> void main() { int r,c,r2,c2,i,j; printf("enter the row and column of first matrix-->"); scanf("%d%d",&r,&c); printf("enter the row and column of second matrix-->"); scanf("%d%d",&r2,&c2); int *arr=malloc(r*c*sizeof(int)); int *arr2=malloc(r2*c2*sizeof(int)); printf("enter the elements of matrix 1:"); read(arr,r,c); display(arr,r,c); printf("enter the elements of matrix 2:"); read(arr2,r2,c2); display(arr2,r2,c2); printf("tuple form of matrix 1:"); tuple(arr,r,c); printf("tuple form of matrix 2:"); tuple(arr2,r2,c2); printf("transpose of tuple form of matrix 1:"); transpose(arr,c,r); printf("transpose of tuple form of matrix 2:"); transpose(arr2,c2,r2); printf("sum of matrices:sum="); sum(arr,arr2,r,c,r2,c2); free(arr); free(arr2); } void read(int *x,int m,int n) { int i,j; for(i=0;i<m;i++) { for(j=0;j<n;j++) { scanf("%d",&*(x+i*n+j)); } } } void display(int *x,int m,int n) { int i,j; for(i=0;i<m;i++) { for(j=0;j<n;j++) { printf(" %d ",*(x+i*n+j)); } printf("\n"); } } void tuple(int *x,int m,int n) { int i,j; printf("("); for(i=0;i<m;i++) { for(j=0;j<n;j++) { printf("(%d %d %d)",i,j,*(x+i*n+j)); } } printf(")\n"); } void transpose(int *x,int m,int n) { int i,j; printf("("); for(i=0;i<m;i++) { printf("("); for(j=0;j<n;j++) { if(j==n-1) { printf("%d",*(x+j*n+i)); } else { printf(" %d ",*(x+j*n+i)); } } printf(")"); } printf(")\n"); } void sum(int *x,int *y,int m,int n,int p,int q) { int i,j; if(m==p && n==q) printf("("); for(i=0;i<m;i++) { printf("("); for(j=0;j<n;j++) { if(j==n-1) { printf(" %d ",*(x+i*n+j)+*(y+i*n+j)); } else { printf(" %d ",*(x+i*n+j)+*(y+i*n+j)); } } printf(")"); } printf(")\n"); }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <signal.h> void despiertaNormal(){ } void ejecutals(){ printf("ejecutando ls\n"); if(fork() == 0) execlp("ls", "ls", NULL); else wait(NULL); } void ejecutapstree(){ printf("ejecutando pstree\n"); if(fork() == 0) execlp("pstree", "pstree", "-p", NULL); else wait(NULL); } int main(int argc, char * argv[]){ int pid, pidarb, pida, pidb, pidx, pidy, pidz, i; int tiempo; char procesoSeleccionado; if(argc == 3){ tiempo = atoi(argv[2]); // pasamos a entero la cadena. procesoSeleccionado = argv[1][0]; // primera caracter del segundo argumento pidarb = getpid(); printf("Soy el proceso arb: mi pid es %d\n", pidarb); for(i = 1; i <= 2; i++){ pid = fork(); if(pid != 0){ // el padre se sale del bucle. break; }else{ if(i == 1){ pida = getpid(); printf("Soy el proceso A: mi pid es %d. Mi padre %d\n", pida, pidarb);// vuelve a hacer el bucle con i = 2. } if(i == 2){ pidb = getpid(); printf("Soy el proceso B: mi pid es %d. Mi padre %d. Mi abuelo %d\n", pidb, pida, pidarb); } } } if(i == 1){ wait(NULL); printf("Soy arb y muero\n"); // la ultima sentencia arb, tiene que esperar a A. } if(i == 2){ // A sale del bucle con 2 signal(SIGUSR1, ejecutapstree); signal(SIGUSR2, despiertaNormal); wait(NULL); // aqui espera A. printf("Soy A y muero\n"); } if(i == 3){ // EL PROCESO B. for(i = 1; i <= 3; i++){ pid = fork(); if(pid != 0){ switch(i){ case 1: pidx = pid; break; case 2: pidy = pid; break; case 3: pidz = pid; break; } } if(pid == 0){ switch(i){ case 1: //pidX = getpid(); printf("Soy el proceso X: mi pid es %d. Mi padre %d. Mi abuelo %d. Mi bisabuelo %d\n", getpid(), pidb, pida, pidarb); signal(SIGUSR1, ejecutals); signal(SIGUSR2, despiertaNormal); pause(); break; case 2: //pidY = getpid(); printf("Soy el proceso Y: mi pid es %d. Mi padre %d. Mi abuelo %d. Mi bisabuelo %d\n", getpid(), pidb, pida, pidarb); signal(SIGUSR1, ejecutals); signal(SIGUSR2, despiertaNormal); pause(); break; case 3: printf("Soy el proceso Z: mi pid es %d. Mi padre %d. Mi abuelo %d. Mi bisabuelo %d\n", getpid(), pidb, pida, pidarb); // Z tiene que dormir el tiempo que se le indique en // el parametro. //sleep(tiempo); signal(SIGALRM, despiertaNormal); alarm(tiempo); pause(); // Z debe mandar las señales al resto de procesos. switch(procesoSeleccionado){ case 'X': // EJECUTA COMANDO kill(pidx, SIGUSR1); signal(SIGALRM, despiertaNormal); alarm(tiempo); pause(); // DESPIERTA NORMAL kill(pidy, SIGUSR2); break; case 'Y': kill(pidy, SIGUSR1); signal(SIGALRM, despiertaNormal); alarm(tiempo); pause(); kill(pidx, SIGUSR2); break; case 'A': kill(pida, SIGUSR1); signal(SIGALRM, despiertaNormal); alarm(tiempo); pause(); kill(pidy, SIGUSR2); kill(pidx, SIGUSR2); break; case 'B': kill(pidb, SIGUSR1); signal(SIGALRM, despiertaNormal); alarm(tiempo); pause(); kill(pidx, SIGUSR2); kill(pidy, SIGUSR2); break; } break; } switch(i){ case 1: printf("Soy X y muero\n"); break; case 2: printf("Soy Y y muero\n"); break; case 3: printf("Soy Z y muero\n"); break; } break; // los hijos de B se salen del bucle. } }//Cierre for if(i == 4){ // PADRE. cuando acaba el bucle tiene que esperar a sus tres hijos, para no morirse antes que ellos. signal(SIGUSR1, ejecutapstree); signal(SIGUSR2, despiertaNormal); for(i = 1; i <= 3; i++){ wait(NULL); } printf("Soy B y muero\n"); } } } else{ printf("Error. Uso: %s <proceso> <tiempo>\n", argv[0]); } return 0; }
C
// Write a program that opens the text.txt file (with the `fopen()` system call) located in this directory // and then calls `fork()` to create a new process. Can both the child and parent access the file descriptor // returned by `fopen()`? What happens when they are written to the file concurrently? //Answer: It looks like they work fine together #include <stdio.h> #include <unistd.h> #include <stdlib.h> int main(void) { FILE * fp; fp = fopen("text.txt", "w+"); pid_t pid = fork(); if (pid == 0) { printf("I'm the child process, and my pid is %d!\n", getpid()); fprintf(fp, "We are in Child, pid:%d\n", getpid()); } else { printf("I'm the parent process, and my pid is %d!\n", getpid()); fprintf(fp, "We are in Parent, pid:%d\n", getpid()); } fclose(fp); return 0; }
C
#include <sys/timeb.h> #include <errno.h> #include "lp.h" #include "lp_internal.h" #ifdef WIN32 #define HAVE_FTIME #endif /* Implement floattime() for various platforms */ static double floattime(void) { /* There are three ways to get the time: (1) gettimeofday() -- resolution in microseconds (2) ftime() -- resolution in milliseconds (3) time() -- resolution in seconds In all cases the return value is a float in seconds. Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may fail, so we fall back on ftime() or time(). Note: clock resolution does not imply clock accuracy! */ #ifdef HAVE_GETTIMEOFDAY { struct timeval t; #ifdef GETTIMEOFDAY_NO_TZ if (gettimeofday(&t) == 0) return (double)t.tv_sec + t.tv_usec*0.000001; #else /* !GETTIMEOFDAY_NO_TZ */ if (gettimeofday(&t, (struct timezone *)NULL) == 0) return (double)t.tv_sec + t.tv_usec*0.000001; #endif /* !GETTIMEOFDAY_NO_TZ */ } #endif /* !HAVE_GETTIMEOFDAY */ { #if defined(HAVE_FTIME) struct timeb t; ftime(&t); return (double)t.time + (double)t.millitm * (double)0.001; #else /* !HAVE_FTIME */ time_t secs; time(&secs); return (double)secs; #endif /* !HAVE_FTIME */ } } /* * modf(x) * * return a pair (r, y). r is the integral part of * x and y is the fractional part of x, both holds * the same sign as x. */ static lp_obj* time_time(LP) { return lp_number_from_double(lp, floattime()); } /* * init math module, namely, set its dictionary */ void time_init(LP) { /* * new a module dict for math */ lp_obj* time_mod = lp_dict(lp); /* * bind math functions to math module */ lp_setkv(lp, time_mod, lp_string(lp, "time"), lp_fnc(lp, time_time)); /* * bind special attributes to math module */ lp_setkv(lp, time_mod, lp_string(lp, "__doc__"), lp_string(lp, "This module is always available. It provides access to the\n" "time-rel functions defined by the C standard.")); lp_setkv(lp, time_mod, lp_string(lp, "__name__"), lp_string(lp, "time")); lp_setkv(lp, time_mod, lp_string(lp, "__file__"), lp_string(lp, __FILE__)); /* * bind to tiny modules[] */ lp_setkv(lp, lp->modules, lp_string(lp, "time"), time_mod); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_print_arg.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mchindri <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/01/10 14:02:57 by mchindri #+# #+# */ /* Updated: 2016/02/07 11:07:39 by mchindri ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" static int ft_is_number(t_type_format form) { if (ft_strchr("diouxXp", form.conv)) return (1); return (0); } static int ft_is_char(t_type_format form) { if (form.conv == 'c' || NULL == ft_strchr(CONVERTOR, form.conv) || form.conv == '%') return (1); return (0); } static int ft_is_fractional(t_type_format form) { if (ft_strchr("aAeEgG", form.conv)) return (1); return (0); } int ft_print_arg(t_type_format format, va_list *ap) { if (ft_is_number(format)) return (ft_print_number(format, ap)); else if (format.conv == 's') if (format.len_mod[0] == '\0') return (ft_print_string(format, ap)); else return (ft_print_wstring(format, ap)); else if (ft_is_char(format)) return (ft_print_char(format, ap)); else if (ft_is_fractional(format)) return (ft_print_fractional(format, ap)); else if (format.conv == 'n') return (-1); return (-2); }
C
/* * Copyright © 2018-NOW Synapse Research Innovation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * \file ctype.h * \brief Character handling. * * \author Srikanth Anantharam * \date 14-01-2018 * \copyright Apache License */ #pragma once /** * \brief tests for any alphanumeric character. * * \param[in] c a character. * \return \c true: if \p c is an alphanumeric character, \c false: otherwise. * * The \c isalnum function tests for any character for which \c isalpha or * \c isdigit is true. */ int isalnum(const int c); /** * \brief tests for any alphabetic character. * * \param[in] c a character. * \return \c true: if \p c is an alphabetic character, \c false: otherwise. * * The \c isalpha function tests for any character for which \c isupper or * \c islower is true, or any character that is one of a locale-specific set of * alphabetic characters for which none of \c iscntrl, \c isdigit, \c ispunct, * or \c isspace is \c true. In the \c "C" locale, \c isalpha returns true only * for the characters for which \c isupper or \c islower is true. */ int isalpha(const int c); /** * \brief tests for any blank character. * * \param[in] c a character. * \return \c true: if \p c is \c ' ' or \c '\\t', \c false: otherwise. * * The \c isblank function tests for any character that is a standard blank * character or is one of a locale-specific set of characters for which * \c isspace is \c true and that is used to separate words within a line of * text. The standard blank characters are the following: space (\c ' '), and * horizontal tab (\c '\\t'). In the \c "C" locale, \c isblank returns \c true * only for the standard blank characters. */ int isblank(const int c); /** * \brief tests for any control character. * * \param[in] c a character. * \return \c true: if \p c is a control character, \c false: otherwise. */ int iscntrl(const int c); /** * \brief tests for any decimal-digit character. * * \param[in] c a character. * \return \c true: if \p c is a decimal-digit character, \c false: otherwise. */ int isdigit(const int c); /** * \brief tests for any printing character except space (\c ' '). * * \param[in] c a character. * \return \c true: if \p c is a printing character other than space, \c false: * otherwise. */ int isgraph(const int c); /** * \brief tests for any character that is a lowercase letter. * * \param[in] c a character. * \return \c true: if \p c is a lowercase letter character, \c false: otherwise. * * The \c islower function tests for any character that is a lowercase letter * or is one of a locale-specific set of characters for which none of \c iscntrl * , \c isdigit, \c ispunct, or \c isspace is \c true. In the \c "C" locale, * \c islower returns \c true only for the lowercase letters. */ int islower(const int c); /** * \brief tests for any printing character including space (\c ' '). * * \param[in] c a character. * \return \c true: if \p c is a printing character including space, \c false: * otherwise. */ int isprint(const int c); /** * \brief tests for any punctuation character. * * \param[in] c a character. * \return \c true: if \p c is a punctuation character, \c false: otherwise. * * The \c ispunct function tests for any printing character that is one of a * locale-specific set of punctuation characters for which neither \c isspace * nor \c isalnum is \c true. In the \c "C" locale, \c ispunct returns \c true * for every printing character for which neither \c isspace nor \c isalnum is * \c true. */ int ispunct(const int c); /** * \brief tests for any white-space character. * * \param[in] c a character. * \return \c true: if \p c is a white-space character, \c false: otherwise. * * The \c isspace function tests for any character that is a standard white- * space character or is one of a locale-specific set of characters for which * \c isalnum is \c false. The standard white-space characters are the following * : space (\c ' '), form feed (\c '\\f'), new-line(\c '\\n'), carriage return * (\c '\\r'), horizontal tab (\c '\\t'), and vertical tab (\c '\\v'). In the * \c "C" locale, \c isspace returns \c true only for the standard white-space * characters. */ int isspace(const int c); /** * \brief tests for any character that is an uppercase letter. * * \param[in] c a character. * \return \c true: if \p c is an uppercase letter, \c false: otherwise. * * The \c isupper function tests for any character that is an uppercase letter * or is one of a locale-specific set of characters for which none of \c iscntrl * , \c isdigit, \c ispunct, or \c isspace is \c true. In the \c "C" locale, * \c isupper returns \c true only for the uppercase letters. */ int isupper(const int c); /** * \brief tests for any hexadecimal-digit character. * * \param[in] c a character. * \return \c true: if \p c is a hexadecimal-digit character, \c false: * otherwise. * * */ int isxdigit(const int c); /** * \brief converts an uppercase letter to a corresponding lowercase letter. * * \param[in] c a character. * \return lowercase letter if \p c is a uppercase letter (\c isupper is \c * true) and a corresponfing lowercase letter exists, otherwise the * argument is returned unchanged. */ int tolower(const int c); /** * \brief converts a lowercase letter to corresponding uppercase letter. * * \param[in] c a character. * \return uppercase letter if \p c is a lowercase letter (\c islower is \c * true) and a corresponfing uppercase letter exists, otherwise the * argument is returned unchanged. */ int toupper(const int c);
C
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys/ioctl.h> int main(int argc, char * argv[]) { char *arg = argv[1]; int i = atoi(arg); int f = open("/dev/BufferedMem", O_RDWR); if (f == -1) printf("file open error\n"); ioctl(f, _IOR('Q', 2, int), &i); return 0; }
C
#ifndef __RETRUINO_H_INCLUDED__ #define __RETRUINO_H_INCLUDED__ #include <TFT.h> #include <Arduios_Kernel.h> /* The Retruino library is used to access the components of the Retruino in a hardware independet way, that means, if you have another hardware just change the library and everything works. */ extern struct Input { const uint8_t JOY_X = 1; const uint8_t JOY_Y = 0; // Returns the position of the joystick in the given axis // Returns values between 0 and 1024 uint16_t readJoystick(uint8_t joystick); // Returns the dir of the joystick in the given axis // Returns values between -1 and 1 int8_t readJoystickDirection(uint8_t joystick); } input; extern struct Display { // display digital pin definition static const uint8_t CS = 10; static const uint8_t DC = 9; static const uint8_t RES = 8; // tft screen const TFT TFT_DISPLAY = TFT(CS, DC, RES); // tft screen constants uint8_t WIDTH; uint8_t HEIGHT; uint8_t HALF_WIDTH; uint8_t HALF_HEIGHT; // This method should be called before using the display // By default its called by the Desktop so no need to call anymore void setup(); // Colors are always hex colors // I think the parameters rest are self reponding // Method used to draw a pixel void drawPixel (uint8_t x, uint8_t y, uint32_t color); // Method used to draw a line void drawLine (uint8_t x1, uint8_t y1, uint8_t x2, uint8_t y2, uint32_t color); // Method used to draw the bounds of a rectangle void drawRect (uint8_t x, uint8_t y, uint8_t w, uint8_t h, uint32_t color); // Method used to draw a filled rectangle void fillRect (uint8_t x, uint8_t y, uint8_t w, uint8_t h, uint32_t color); // Method used to draw the bounds of a circle void drawCircle (uint8_t x, uint8_t y, uint8_t r, uint32_t color); // Method used to draw a filled circle void fillCircle (uint8_t x, uint8_t y, uint8_t r, uint32_t color); // Method used to draw string text void drawText (uint8_t x, uint8_t y, String &text, uint32_t color, uint8_t size); // Method used to draw char[] text void drawText (uint8_t x, uint8_t y, char text[], uint32_t color, uint8_t size); // This method fills the display with the given color void fill (uint32_t color); private: uint8_t red; uint8_t green; uint8_t blue; void getColorValues (uint32_t color); } display; #endif
C
/* * ttycap - routines for dealing with the teletype capability data base * Bill Joy UCB September 25, 1977 */ #ifdef ibm char ttycap[] "dd:ttycap"; #else char ttycap[] "/etc/ttycap"; #endif /* extern */ static char *tbuf; tgetent(bp, name) char *bp, *name; { register char *cp; register int /* cap, */ c; char *cap; /* int ibuf[259]; */ tbuf = bp; cap = fopen(ttycap, "r"); if (!cap) return (-1); for (;;) { for (cp = bp, c = getc(cap); c != -1; c = getc(cap)) { if (c == '\n') { if (cp > bp && cp[-1] == '\\'){ cp--; continue; } break; } *cp++ = c; } *cp = 0; if (c == -1) { fclose(cap); return (0); } if (tnamatch(name)) { fclose(cap); return (1); } } } tnamatch(np) char *np; { register char *Np, *Bp; for (Bp = tbuf; *Bp && *Bp != ':'; Bp++) { for (Np = np; *Np && *Bp != '|' && *Bp != ':' && *Bp == *Np; Bp++, Np++) continue; if (*Np == 0 && (*Bp == '|' || *Bp == ':' || *Bp == 0)) return (1); while (*Bp && *Bp != ':' && *Bp != '|') Bp++; if (*Bp == 0) break; } return (0); } tskip(bp, i) register char *bp; register int i; { for (; i > 0; i--) { while (*bp && *bp != ':') bp++; if (*bp == ':') bp++; } return (bp); } tgetnum(id) char *id; { register int i, base; register char *bp; for (bp = tskip(tbuf, 3); *bp != 0; bp = tskip(bp, 1)) { if (*bp++ != id[0] || *bp == 0 || *bp++ != id[1]) continue; if (*bp != '#') continue; bp++; base = 10; if (*bp == '0') base = 8; i = 0; while (*bp >= '0' && *bp <= '9') i =* base, i =+ *bp++ - '0'; return (i); } return (-1); } tgetflag(id) char *id; { register char *bp; for (bp = tskip(tbuf, 3); *bp; bp = tskip(bp, 1)) if (*bp++ == id[0] && *bp != 0 && *bp == id[1]) return (1); return (0); } tgetstr(id, area) char *id, **area; { register char *cp; register int i; register char *bp; for (bp = tskip(tbuf, 3); *bp != 0; bp = tskip(bp, 1)) { if (*bp++ != id[0] || *bp == 0 || *bp++ != id[1]) continue; if (*bp != '=') continue; bp++; return (tdecode(bp, area)); } return (0); } tdecode(str, area) register char *str; char **area; { register char *cp; register int c; int i; cp = *area; while ((c = *str++) && c != ':') { switch (c) { case '^': if (*str >= 'a' && *str <= 'z') c = *str++ & 037; break; case '\\': switch (*str) { case 'E': str++; c = 033; break; case '^': case '\\': case ':': c = *str++; break; case 'n': c = '\n'; str++; break; case 'r': c = '\r'; str++; break; case 't': c = '\t'; str++; break; case 'b': c = '\b'; str++; break; default: if (*str >= '0' && *str <= '9') { c = 0, i = 3; do c =<< 3, c=| *str++ - '0'; while (--i && *str >= '0' && *str <= '9'); } else if (*str) c = *str++; break; } } *cp++ = c; } *cp++ = 0; str = *area; *area = cp; return (str); }
C
#include <stdio.h> #include <stdlib.h> # define PRIMO 262139 int hashN(int n){ return n%PRIMO; } int main(void){ int v[PRIMO]; int n; scanf("%d", &n); for (int i = 0; i < n; i++){ int t; scanf("%d", &t); v[hashN(t)] = t; } int c; while(scanf("%d", &c)==1){ int t = hashN(c); if(v[t] == c) printf("Numero proibid\n"); else if(v[t] == 0) printf("não\n"); else if(v[t] != c) printf("Colisão socorro"); } return 0; }
C
/* * $Id: ShakerSort.c 6 2006-09-10 15:35:16Z marcus $ * * ShakerSort * Recolocando MIN e MAX por iteracao * */ void ShakerSort (long k[], int n) { int x,y; // loops de transversao int tmp, min, max; // de trabalho int i=n-1; // Extremo D for( x=0; x<(n-x-2); x++ ) { min = x; max = x; for( y=x+1; y<(n-x-1); y++ ) { if( k[y] < k[min] ) { min = y; // guarda a posicao do minimo } // end if if( k[y] > k[max] ) { max = y; // guarda a posicao do maximo } // end if } // end for; //Poe o minimo no extremo E (q nem BubbleSort) tmp = k[min]; k[min] = k[x]; k[x] = tmp; //Poe o maximo no extremo D tmp = k[max]; k[max] = k[y]; k[y] = tmp; } // end x }
C
#include <stdio.h> #include <stdlib.h> #define gc getchar_unlocked int get_i() { char c = gc(); while(c<'0' || c>'9') c = gc(); int ret = 0; while(c>='0' && c<='9') { ret = 10 * ret + c - 48; c = gc(); } return ret; } static void put_i(unsigned int n) { #define BSIZE 6 char buf[BSIZE]; int bn = BSIZE-1; while (1) { buf[bn--] = '0'+(n%10); n = n / 10; if (n == 0) break; } while (bn<BSIZE-1) putchar(buf[++bn]); putchar('\n'); } int compare(void const*, void const*); int main(int argc, char const *argv[]) { int test_cases,number_of_items,sum,follow,i; int array[1000]; test_cases=get_i(); while(test_cases--) { sum=0; number_of_items=get_i(); for(i=0;i<number_of_items;i++) { scanf("%d",&array[i]); } qsort(array,number_of_items,sizeof(int),compare); i=number_of_items-1; while(i>=0) { if (i-1>=0) sum+=array[i]+array[i-1]; else sum+=array[i]; i-=4; } put_i(sum); } return 0; } int compare(void const *p,void const *q) { return (*(int*)p-*(int*)q); } ''
C
#include <libraries/dos.h> #include "tree.h" struct FileHandler* filehandler; int bytes_written; int loop; int arraysize; UWORD* gpointer; char fp[5]; char tobewritten[4]; UWORD result; void main() { printf("Size of UWORD: %d\n", sizeof(UWORD)); // 52 rows, 58 colums. 52*58 = 3016 bits // 377 bytes no padding // 52 rows, 64 colums with padding. = 3328 bits = 416 bytes filehandler = Open("tree.dat", MODE_NEWFILE); if (filehandler == NULL) printf("Could not open the file!\n"); else { sprintf( tobewritten, "%d", tree.Width); bytes_written = Write( filehandler, tobewritten, sizeof(char)*2); printf("%d bytes written.\n", bytes_written); sprintf( tobewritten, "%d", tree.Height); bytes_written = Write( filehandler, tobewritten, sizeof(char)*2); printf("%d bytes written.\n", bytes_written); sprintf( tobewritten, "%d", tree.Depth); bytes_written = Write( filehandler, tobewritten, sizeof(char)); printf("%d bytes written.\n", bytes_written); sprintf( tobewritten, "%d", sizeof(treeData)/sizeof(UWORD)); bytes_written = Write( filehandler, tobewritten, sizeof(char)*3); printf("%d bytes written.\n", bytes_written); gpointer = treeData; for(loop = 0; loop < (sizeof(treeData)/sizeof(UWORD)); loop++) { sprintf(tobewritten, "%04X", *gpointer); bytes_written = Write(filehandler, tobewritten, sizeof(char)*4); gpointer++; } printf("A lot of bytes written. Size of tobewritten: %d\n", sizeof(tobewritten)); printf("Time to read them back out.\n"); Seek(filehandler, 0, OFFSET_BEGINNING); bytes_written = Read(filehandler, fp, sizeof(char)*2); result = strtol( fp, NULL, 10); printf("Read %d bytes. Width: %d\n", bytes_written, result); bytes_written = Read(filehandler, fp, sizeof(char)*2); result = strtol( fp, NULL, 10); printf("Read %d bytes. Width: %d\n", bytes_written, result); bytes_written = Read(filehandler, fp, sizeof(char)); result = strtol( fp, NULL, 10); printf("Read %d bytes. Depth: %d\n", bytes_written, result); bytes_written = Read(filehandler, fp, sizeof(char)*3); result = strtol( fp, NULL, 10); printf("Read %d bytes. Array Size: %d\n", bytes_written, result); arraysize = result; for(loop = 0; loop < arraysize; loop++) { bytes_written = Read(filehandler, fp, sizeof(char)*4); result = strtol( fp, NULL, 16); printf("%04X,", result); } printf("\n"); Close(filehandler); } }
C
#ifndef __MSA_rules_ye_Maths__ #define __MSA_rules_ye_Maths__ #include <math.h> /***************************** Misc *************************************/ #define MSA_pF(vv) ( (float*)(&vv) ) // cast as pointer to float /* #define _Step(x,a) ((x)>=(a)?1:0) // return 1 or 0 depending on sign #define _Sign(x) ( x ? (x < 0 ? -1 : 1) : 0 ) // return -1 or 1 depending on sign //#define _Sign2(x, t) ( x<-t ? -1 : (x>t ? 1 : 0) ) #define _Min(a,b) __min(a,b) // ((a)<(b)?(a):(b)) #define _Max(a,b) __max(a,b) // ((a)<(b)?(b):(a)) #define _Abs(x) (float)fabs(x) // ((x)<0?(-(x)):(x)) #define _Floor(x) (float)floor(x) // ((int)(x) - ((x) < 0 && (x) != (int)(x))) #define _Ceil(x) (float)ceil(x) // ((int)(x) + ((x) > 0 && (x) != (int)(x))) #define _Lerp(x,a,b) ((a) + (x)*((b)-(a))) // linear interpolate #define _Smooth01(x) ((x)*(x)*(3 - 2*(x))) // smooth a 0...1 number at the ends 0 and 1 #define _In(x,a,b) ((x>=a) && (x<=b)) // return true if x is in the range a...b #define _Clamp(x,a,b) if(x<a) x=a; else if(x>b) x=b; // clamp a value x to the range a...b #define _BoxStep(x,a,b) _Clamp( ((x)-(a)) / (float)((b)-(a)) ,0, 1) // return 0...1 depending on where x is relative to a...b #define _SmoothStep(x,a,b) _Smooth01(_BoxStep(a,b,x)) #define _PULSE(x,a,b) (step(a,x) - step(b,x)) #define _Bias(b,x) powf((x),logf(b)/_LOG05) #define _Gain(g,x) ((x)<0.5)?(bias(1-(g),2*(x))/2):(1-bias(1-(g),(2)-(2)*x)/2) #define _Gamma(g,x) powf((x),1/(g)); #define _Rand01 ((rand()&0xFF)/(float)0xFF) */ #define PI 3.14159265359f #define TWO_PI (2.0f * PI) #define HALF_PI (0.5f * PI) #define INV_PI (1.0f / PI) #define DEG2RAD (PI / 180.0f) #define RAD2DEG (180.0f / PI) //#define LOG05 -0.693147180559945f #define _Sin(Rad) (float)sin(Rad) #define _Cos(Rad) (float)cos(Rad) /* static float SinArray[65536]; static float CosArray[65536]; inline float _Sin(float fRad) { _Clamp(fRad, 0, TWOPI); return SinArray[(WORD)(fRad * 65536.0f/TWOPI)]; }; inline float _Cos(float fRad) { _Clamp(fRad, 0, TWOPI); return CosArray[(WORD)(fRad * 65536.0f/TWOPI)]; }; */ int __inline MSA_InitMath() { /* for(int c=0; c<65536; c++) { SinArray[c] = (float)sin(c * TWOPI / 65536.0f); CosArray[c] = (float)cos(c * TWOPI / 65536.0f); } */ return TRUE; } /************************************** Vectors *************************************************/ typedef struct { float x, y; } MSA_FVECT2; // float Vector2 typedef struct { int x, y; } MSA_IVECT2; // int Vector2 typedef struct { float x, y, z; } MSA_FVECT3; // float Vector3 typedef struct { int x, y, z; } MSA_IVECT3; // int Vector3 typedef struct { float x, y, z, w; } MSA_FVECT4; // float Vector4 typedef struct { int x, y, z, w; } MSA_IVECT4; // int Vector4 #define MSA_fV2(vv) (*(MSA_FVECT2*)(&vv)) // cast vv as MSA_FVECT2 #define MSA_fV3(vv) (*(MSA_FVECT3*)(&vv)) // cast vv as MSA_FVECT3 #define MSA_fV4(vv) (*(MSA_FVECT4*)(&vv)) // cast vv as MSA_FVECT4 #define MSA_iV2(vv) (*(MSA_IVECT2*)(&vv)) // cast vv as MSA_IVECT2 #define MSA_iV3(vv) (*(MSA_IVECT3*)(&vv)) // cast vv as MSA_IVECT3 #define MSA_iV4(vv) (*(MSA_IVECT4*)(&vv)) // cast vv as MSA_IVECT4 #define MSA_SetV2(vv,X,Y) { vv.x = X; vv.y = Y; } #define MSA_SetV3(vv,X,Y,Z) { vv.x = X; vv.y = Y; vv.z = Z; } #define MSA_SetV4(vv,X,Y,Z,W) { vv.x = X; vv.y = Y; vv.z = Z; vv.w = W; } #define MSA_IncV2(v1,v2) { v1.x += v2.x; v1.y += v2.y; } #define MSA_IncV3(v1,v2) { v1.x += v2.x; v1.y += v2.y; v1.z += v2.z; } #define MSA_IncV4(v1,v2) { v1.x += v2.x; v1.y += v2.y; v1.z += v2.z; v1.w += v2.w; } #define MSA_IncV2f(v,X,Y) { v.x += X; v.y += Y; } #define MSA_IncV3f(v,X,Y,Z) { v.x += X; v.y += Y; v.z += Z; } #define MSA_IncV4f(v,X,Y,Z,W) { v.x += X; v.y += Y; v.z += Z; v.w += W; } #define MSA_AddV2(v1,v2,vr) { vr.x = v1.x + v2.x; vr.y = v1.y + v2.y; } #define MSA_AddV3(v1,v2,vr) { vr.x = v1.x + v2.x; vr.y = v1.y + v2.y; vr.z = v1.z + v2.z; } #define MSA_AddV4(v1,v2,vr) { vr.x = v1.x + v2.x; vr.y = v1.y + v2.y; vr.z = v1.z + v2.z; vr.w = v1.w + v2.w; } #define MSA_AddV2f(v1,X,Y,vr) { vr.x = v1.x + X; vr.y = v1.y + Y; } #define MSA_AddV3f(v1,X,Y,Z,vr) { vr.x = v1.x + X; vr.y = v1.y + Y; vr.z = v1.z + Z; } #define MSA_AddV4f(v1,X,Y,Z,W,vr) { vr.x = v1.x + X; vr.y = v1.y + Y; vr.z = v1.z + Z; vr.w = v1.w + W; } #define MSA_DecV2(v1,v2) { v1.x -= v2.x; v1.y -= v2.y; } #define MSA_DecV3(v1,v2) { v1.x -= v2.x; v1.y -= v2.y; v1.z -= v2.z; } #define MSA_DecV4(v1,v2) { v1.x -= v2.x; v1.y -= v2.y; v1.z -= v2.z; v1.w -= v2.w; } #define MSA_SubV2(v1,v2,vr) { vr.x = v1.x - v2.x; vr.y = v1.y - v2.y; } #define MSA_SubV3(v1,v2,vr) { vr.x = v1.x - v2.x; vr.y = v1.y - v2.y; vr.z = v1.z - v2.z; } #define MSA_SubV4(v1,v2,vr) { vr.x = v1.x - v2.x; vr.y = v1.y - v2.y; vr.z = v1.z - v2.z; vr.w = v1.w - v2.w; } #define MSA_MulV2f(vv,f) { vv.x *= f; vv.y *= f; } #define MSA_MulV3f(vv,f) { vv.x *= f; vv.y *= f; vv.z *= f; } #define MSA_MulV4f(vv,f) { vv.x *= f; vv.y *= f; vv.z *= f; vv.w *= f; } #define MSA_LenV2(vv) ((float)sqrt(vv.x*vv.x + vv.y*vv.y)) #define MSA_LenV3(vv) ((float)sqrt(vv.x*vv.x + vv.y*vv.y + vv.z*vv.z)) #define MSA_LenV4(vv) ((float)sqrt(vv.x*vv.x + vv.y*vv.y + vv.z*vv.z + vv.w*vv.w)) #define MSA_NormV2(vv) { float f = (1.0f/MSA_LenV2(vv)); MSA_MulV2f(vv, f); } #define MSA_NormV3(vv) { float f = (1.0f/MSA_LenV3(vv)); MSA_MulV3f(vv, f); } #define MSA_NormV4(vv) { float f = (1.0f/MSA_LenV4(vv)); MSA_MulV4f(vv, f); } #define MSA_DotV2(v1,v2) ( v1.x*v2.x + v1.y*v2.y ) #define MSA_DotV3(v1,v2) ( v1.x*v2.x + v1.y*v2.y + v1.z*v2.z ) #define MSA_DotV4(v1,v2) ( v1.x*v2.x + v1.y*v2.y + v1.z*v2.z + v1.w*v2.w) // CAN BE SAME VECT3 #define MSA_CrossV3(v1,v2,vr) { MSA_FVECT3 v; v.x=v1.y*v2.z-v1.z*v2.y; v.z=v1.x*v2.y-v1.y*v2.x; v.y=v1.z*v2.x-v1.x*v2.z; MSA_SetV3(vr, v.x, v.y, v.z); } /*float __inline __fastcall MSA_CrossV3(MSA_FVECT3 &v1, MSA_FVECT3 &v2, MSA_FVECT3 &vr) { MSA_FVECT3 v; v.x = v1.y * v2.z - v1.z * v2.y; v.z = v1.x * v2.y - v1.y * v2.x; v.y = v1.z * v2.x - v1.x * v2.z; MSA_SetV3(vr, v.x, v.y, v.z); } */ // Calculate normal of triangle given by points v1,v2,v3 and store in vR void __inline __fastcall MSA_CalcNorm(MSA_FVECT3 &v1, MSA_FVECT3 &v2, MSA_FVECT3 &v3, MSA_FVECT3 &vR) { MSA_FVECT3 Edge1 = v2; MSA_FVECT3 Edge2 = v3; MSA_DecV3(Edge1, v1); // Edge1 = v2 - v1; MSA_DecV3(Edge2, v1); // Edge2 = v3 - v1; MSA_CrossV3(Edge1, Edge2, vR); // vR = Edge1 x Edge2 MSA_NormV3(vR); } /************************************* Matrices ***********************************************/ typedef struct { MSA_FVECT4 x; MSA_FVECT4 y; MSA_FVECT4 z; MSA_FVECT4 t; BOOL bChanged; } MSA_MATRIX44; const MSA_MATRIX44 MSA_m44Identity = { {1,0,0,0}, {0,1,0,0}, {0,0,1,0}, {0,0,0,1}, TRUE }; #define MSA_InitM44(m44) { m44 = MSA_m44Identity; } #define MSA_InitRotM44(m44) { MSA_SetV3(m44.x, 1, 0, 0); MSA_SetV3(m44.y, 0, 1, 0); MSA_SetV3(m44.z, 0, 0, 1); m44.bChanged = TRUE; } #define MSA_InitPosM44(m44) { MSA_SetPosM44(m44, 0, 0, 0); m44.bChanged = TRUE; } #define MSA_SetPosM44(m44,X,Y,Z) { MSA_SetV3(m44.t, X, Y, Z); m44.bChanged = TRUE; } #define MSA_MoveM44f(m44,X,Y,Z) { MSA_IncV3f(m44.t, X, Y, Z); m44.bChanged = TRUE; } #define MSA_MoveM44(m44,v3, fDist) { MSA_MoveM44f(m44, v3.x*fDist, v3.y*fDist, v3.z*fDist) } // CANNOT BE SAME MATRIX void __inline __fastcall MSA_InvM44( MSA_MATRIX44 &m44S, MSA_MATRIX44 &m44R ) { // Set the last column m44R.x.w = 0.0f; m44R.y.w = 0.0f; m44R.z.w = 0.0f; m44R.t.w = 1.0f; // Transform the position m44R.t.x = - MSA_DotV3( m44S.x, m44S.t ); m44R.t.y = - MSA_DotV3( m44S.y, m44S.t ); m44R.t.z = - MSA_DotV3( m44S.z, m44S.t ); // Transform the rotation m44R.x.x = m44S.x.x; m44R.y.y = m44S.y.y; m44R.z.z = m44S.z.z; m44R.x.y = m44S.y.x; m44R.y.x = m44S.x.y; m44R.x.z = m44S.z.x; m44R.z.x = m44S.x.z; m44R.y.z = m44S.z.y; m44R.z.y = m44S.y.z; m44R.bChanged = TRUE; } /* X Y Z W Xx Yx Zx Wx 1 0 0 0 x Xy Yy Zy Wy 0 C -S 0 y Xz Yz Zz Wz 0 S C 0 z Xt Yt Zt Wt 0 0 0 1 t */ void __inline __fastcall MSA_RotM44_X( MSA_MATRIX44 &m44, float fRad ) { float C = _Cos(fRad); float S = _Sin(fRad); float Yx = m44.y.x; float Yy = m44.y.y; float Yz = m44.y.z; m44.y.x = Yx * C + m44.z.x * S; m44.z.x = Yx *-S + m44.z.x * C; m44.y.y = Yy * C + m44.z.y * S; m44.z.y = Yy *-S + m44.z.y * C; m44.y.z = Yz * C + m44.z.z * S; m44.z.z = Yz *-S + m44.z.z * C; m44.bChanged = TRUE; } /* X Y Z W Xx Yx Zx Wx C 0 -S 0 x Xy Yy Zy Wy 0 1 0 0 y Xz Yz Zz Wz S 0 C 0 z Xt Yt Zt Wt 0 0 0 1 t */ void __inline __fastcall MSA_RotM44_Y( MSA_MATRIX44 &m44, float fRad ) { float C = _Cos(fRad); float S = _Sin(fRad); float Yx = m44.y.x; float Yy = m44.y.y; float Yz = m44.y.z; m44.y.x = Yx * C + m44.z.x * S; m44.z.x = Yx *-S + m44.z.x * C; m44.y.y = Yy * C + m44.z.y * S; m44.z.y = Yy *-S + m44.z.y * C; m44.y.z = Yz * C + m44.z.z * S; m44.z.z = Yz *-S + m44.z.z * C; m44.bChanged = TRUE; } /* X Y Z W Xx Yx Zx Wx C -S 0 0 x Xy Yy Zy Wy S C 0 0 y Xz Yz Zz Wz 0 0 1 0 z Xt Yt Zt Wt 0 0 0 1 t */ void __inline __fastcall MSA_RotM44_Z( MSA_MATRIX44 &m44, float fRad ) { float C = _Cos(fRad); float S = _Sin(fRad); float Xx = m44.x.x; float Xy = m44.x.y; float Xz = m44.z.z; m44.x.x = Xx * C + m44.y.x * S; m44.y.x = Xx *-S + m44.y.x * C; m44.x.y = Xy * C + m44.y.y * S; m44.y.y = Xy *-S + m44.y.y * C; m44.x.z = Xz * C + m44.y.z * S; m44.y.z = Xz *-S + m44.y.z * C; m44.bChanged = TRUE; } /************************************* Quaternions ***********************************************/ typedef struct { float x, y, z, w; BOOL bChanged; } MSA_QUAT; const MSA_QUAT MSA_QuatIdentity = {0,0,0,1,TRUE}; #define MSA_SetQUAT(q,X,Y,Z,W) { q.x = X; q.y = Y; q.z = Z; q.w = W; q.bChanged = TRUE; } //#define MSA_InitQUAT(q) { MSA_SetQUAT(q, 0, 0, 0, 1); } #define MSA_InitQUAT(q) { q = MSA_QuatIdentity; } #define MSA_InvQUAT(qS,qD) { MSA_SetQUAT(qD, -qS.x, -qS.y, -qS.z, qS.w); } #define MSA_RotQUAT_f(qA,X,Y,Z,fRad) { MSA_QUAT qt; MSA_NewQUAT(qt, X, Y, Z, fRad); MSA_MulQUAT(qA, qt, qA); } #define MSA_RotQUAT_v3(qA,v3,fRad) { MSA_QUAT qt; MSA_NewQUAT(qt, MSA_fV3(v3), fRad); MSA_MulQUAT(qA, qt, qA); } // Create Quat from axis (x,y,z) and angle fRad and store in qR void __inline __fastcall MSA_NewQUAT(MSA_QUAT &qR, float x, float y, float z, float fRad) { float s2 = _Sin(0.5f * fRad); qR.x = x * s2; qR.y = y * s2; qR.z = z * s2; qR.w = _Cos(0.5f * fRad); // MSA_NormV4(qR); qR.bChanged = TRUE; } // Create Quat from axis (v3Axis) and angle fRad and store in qR void __inline __fastcall MSA_NewQUAT(MSA_QUAT &qR, MSA_FVECT3 &v3Axis, float fRad) { float s2 = _Sin(0.5f * fRad); qR.x = v3Axis.x * s2; qR.y = v3Axis.y * s2; qR.z = v3Axis.z * s2; qR.w = _Cos(0.5f * fRad); // MSA_NormV4(qR); qR.bChanged = TRUE; } // CAN BE SAME TARGET //w1.v2 + w2.v1 + v1 x v2, w1.w2 - v1.v2 void __inline __fastcall MSA_MulQUAT(MSA_QUAT &qA, MSA_QUAT &qB, MSA_QUAT &qR) { MSA_FVECT3 va = MSA_fV3(qA); MSA_MulV3f(va, qB.w); MSA_FVECT3 vb = MSA_fV3(qB); MSA_MulV3f(vb, qA.w); qR.w = qA.w * qB.w - MSA_DotV3(qA, qB); MSA_CrossV3(qA, qB, qR); MSA_IncV3(qR, va); MSA_IncV3(qR, vb); // MSA_NormV4(qR); qR.bChanged = TRUE; } /* | 2 2 | | 1 - 2Y - 2Z 2XY - 2ZW 2XZ + 2YW | | | | 2 2 | M = | 2XY + 2ZW 1 - 2X - 2Z 2YZ - 2XW | | | | 2 2 | | 2XZ - 2YW 2YZ + 2XW 1 - 2X - 2Y | | */ void __inline _fastcall MSA_Quat2M44(MSA_QUAT &q, MSA_MATRIX44 &m44) { float xx = q.x * q.x; float xy = q.x * q.y; float xz = q.x * q.z; float xw = q.x * q.w; float yy = q.y * q.y; float yz = q.y * q.z; float yw = q.y * q.w; float zz = q.z * q.z; float zw = q.z * q.w; m44.x.x = 1 - 2 * ( yy + zz ); m44.x.y = 2 * ( xy - zw ); m44.x.z = 2 * ( xz + yw ); m44.y.x = 2 * ( xy + zw ); m44.y.y = 1 - 2 * ( xx + zz ); m44.y.z = 2 * ( yz - xw ); m44.z.x = 2 * ( xz - yw ); m44.z.y = 2 * ( yz + xw ); m44.z.z = 1 - 2 * ( xx + yy ); /* mat[3] = mat[7] = mat[11 = mat[12] = mat[13] = mat[14] = 0; mat[15] = 1; */ m44.bChanged = TRUE; } /* inline __declspec(naked) int __fastcall _Floor(float &f) // int i=(int)f; if(i>f) i--; { __asm { fld dword ptr[ecx] frndint fcom dword ptr[ecx] fistp dword ptr[esp-4] fnstsw ax test ah,41h jne ItsOk dec dword ptr[esp-4] ItsOk: mov eax,dword ptr[esp-4] ret } } inline __declspec(naked) int __fastcall _Ceil(float &f) // int i=(int)f; if(i>f) i--; { __asm { fld dword ptr[ecx] frndint fcom dword ptr[ecx] fistp dword ptr[esp-4] fnstsw ax test ah,1 je ItsOk inc dword ptr[esp-4] ItsOk: mov eax,dword ptr[esp-4] ret } } /********************************************************************************/ #endif // __MSA_rules_ye_Maths__
C
/* * CSF Assignment 1 * Arbitrary-precision integer data type * Function implementations */ #include <stdlib.h> #include <string.h> #include <assert.h> #include "apint.h" #include <stdio.h> #include <math.h> /* Parameters: val (unsigned 64 bit value) * Declare and initialize new ApInt using val * */ ApInt *apint_create_from_u64(uint64_t val) { /* TODO: implement */ ApInt *ap = (ApInt*) malloc(sizeof(ApInt)); assert(ap != NULL); //check memory allocation ap->len = 1; ap->flags = 1; //1 = 0/+, 0 = - , unsigned, so always + ap->data = (uint64_t *)calloc(1, sizeof(uint64_t)); ap->data[0] = val; return ap; } /* * char to int conversion for hex values * used in apint_create_from_hex * returns -1 if invalid hex character * */ int charToInt(char c) { int new_value; switch(c) { case 'a': case 'A': new_value = 10; break; case 'b': case 'B': new_value = 11; break; case 'c': case 'C': new_value = 12; break; case 'd': case 'D': new_value = 13; break; case 'e': case 'E': new_value = 14; break; case 'f': case 'F': new_value = 15; break; default: if (c >= '0' && c <= '9') { new_value = (int) (c - '0'); } else { new_value = -1; } break; } return new_value; } /* * Determines if string is all 0 * Return 1: if all 0, 0 if not all 0 * Used in apint_create_from_hex */ int hex_is_zero(const char *hex) { for (int i=0; hex[i]; i++) { if (hex[i] != '0') { return 0; } } return 1; } /* * Parameters: ApInt to be filled with data from hex string, hex string, start index for hex string * Returns the same ApInt pointer or NULL if invalid hex character * Used in apint_create_from_hex */ ApInt * fill_data_from_hex(ApInt * ap, const char * hex, int start) { int string_counter = strlen(hex) - 1; //subtract 1 for final position uint64_t new_value = 0, mult_counter = 1; int char_to_int_value = 0, hex_counter = 0, data_counter = 0; char current_char; while(string_counter >= start) { //start reading from highest elem of string until start position current_char = *(hex + string_counter); char_to_int_value = charToInt(current_char); if (char_to_int_value < 0) { //invalid character (not hex) apint_destroy(ap); //free data in ap return NULL; } else { new_value = char_to_int_value; //valid hex } new_value = new_value * mult_counter; //set to next set of bits mult_counter *= 16; if (hex_counter == 15) { ap->data[data_counter] = ap->data[data_counter] + new_value; if (string_counter > start) { data_counter++; } mult_counter = 1; hex_counter = 0; } else { ap->data[data_counter] = ap->data[data_counter] + new_value; hex_counter++; //move to next hex elem } string_counter--; } return ap; } /* * Converts string of hex values to ApInt * Returns pointer to ApInt instance, NULL if invalid hex string */ ApInt *apint_create_from_hex(const char *hex) { ApInt *ap = (ApInt*) malloc(sizeof(ApInt)); assert(ap != NULL); //check memory allocation ap->flags = 1; int start = 0; if (*hex == '-') { //neg hex value ap->flags = 0; //1 = 0/+, 0 = - start++; //if neg, start reading hex at next char } if (hex_is_zero(hex+start)) { //if 0, only assign 1 length data set_zero_data(ap); return ap; } while(*(hex + start) == '0') { //ignore leading zeros start++; } ap->len = (strlen(hex) - start) / 16; if ((strlen(hex) - start) % 16 > 0) { //account for leftover bits ap->len = ap->len + 1; } ap->data = (uint64_t *)calloc(ap->len, sizeof(uint64_t)); return fill_data_from_hex(ap, hex, start); } /* * Destructor, frees memory in data and ApInt */ void apint_destroy(ApInt *ap) { /* TODO: implement */ free(ap->data); free(ap); } /* * Determines if ApInt data is equal to 0 * Loops through all elements of ApInt data array * Returns 0 if apint is positive or negative * Returns 1 if apint is 0 * */ int apint_is_zero(const ApInt *ap) { unsigned int i; //all elements of data must be 0 for (i=0; i<ap->len; i++) { if(ap->data[i] != 0) { return 0; } } return 1; } /* * Determines if ApInt is negative * Returns 0 if apint is 0 or positive * Returns 1 if apint is negative * */ int apint_is_negative(const ApInt *ap) { if (apint_is_zero(ap) == 1) { return 0; } return (ap->flags == 1) ? 0 : 1; } /* * Returns the bits at position n of ApInt data array * Returns 0 if n is out of bounds */ uint64_t apint_get_bits(const ApInt *ap, unsigned n) { if (n > ap->len - 1) { return 0; } return ap->data[n]; } /* * Determines position of highest bit set to 1 in ApInt * Returns -1 if no highest bit (value is 0) */ int apint_highest_bit_set(const ApInt *ap) { uint64_t highest = 0x8000000000000000UL; //highest bit uint64_t current_elem; int data_pos = ap->len - 1; for (; data_pos >= 0; data_pos--) { current_elem = ap->data[data_pos]; //while loop starts at highest bit and decrements until match found for (int count = 63; count >= 0; count--) { if (highest & current_elem) { //if true, then current_elem is highest bit return data_pos * 64 + count; } highest = highest >> 1; //move to next bit on the right } } return -1; } /* * Converts uint64_t to hex char */ char intToChar(uint64_t i) { char new_value = '0'; switch(i) { case 10: new_value = 'a'; break; case 11: new_value = 'b'; break; case 12: new_value = 'c'; break; case 13: new_value = 'd'; break; case 14: new_value = 'e'; break; case 15: new_value = 'f'; break; default: new_value = (char) i + '0'; break; } return new_value; } /* * Reverses given hex string * Format to remove leading zeros, include negative sign, null terminator * */ char * rev_hex_string(const ApInt *ap, char * hex) { int is_neg = ap->flags == 0 ? 1 : 0; //reverse string uint32_t total_hex_len = 16 * ap->len; char * rev_hex = calloc(total_hex_len , sizeof(char)); for (uint32_t i = 0; i < total_hex_len; i++) { rev_hex[i] = hex[total_hex_len -1 - i]; } //remove leading 0s uint32_t start = 0; while(*(rev_hex + start) == '0') { start++; } char * final_hex = calloc( ap->len*16 - start + 1 + is_neg, sizeof(char)); size_t f_hex_count = 0; if (is_neg) { final_hex[f_hex_count++] = '-'; } for (uint32_t i = start; i < total_hex_len; i++) { final_hex[f_hex_count++] = *(rev_hex + i); } final_hex[f_hex_count] = '\0'; free(rev_hex); return final_hex; } /* * Converts ApInt data to a char array of the hex value */ char *apint_format_as_hex(const ApInt *ap) { if (apint_is_zero(ap) == 1) { char *hex = malloc(2*sizeof(char)); hex[0] = '0'; hex[1] = '\0'; return hex; } char *hex = calloc((16 * ap->len), sizeof(char)); memset(hex, '0', 16 * ap->len * sizeof(char)); int hex_length = 0; uint64_t div, rem; for (uint16_t i=0; i< ap->len; i++) { div = ap->data[i] / 16; rem = ap->data[i] % 16; hex_length = 16*i; hex[hex_length++] = intToChar(rem); while(div > 0) { rem = div % 16; div = div / 16; hex[hex_length++] = intToChar(rem); } } char * final = rev_hex_string(ap, hex); free(hex); return final; } /* * Creates new instance of ApInt with same data value and opposite flag * If 0, flag remains 1 */ ApInt *apint_negate(const ApInt *ap) { uint32_t i; int is_zero = 1; //1 if true, 0 if false ApInt *ap2 = (ApInt*) malloc(sizeof(ApInt)); assert(ap2 != NULL); //check if memory allocated //copy length and data of ap to negated ap ap2->len = ap->len; ap2->data = (uint64_t *)calloc(ap2->len, sizeof(uint64_t)); for (i=0; i<ap->len; i++) { ap2->data[i] = ap->data[i]; if(ap->data[i] != 0) { is_zero = 0; } } if (is_zero == 1) { ap2->flags = ap->flags; //flag 1 for data == 0 } else { ap2->flags = (ap->flags == 0) ? 1: 0; //input opposite flag } return ap2; } /* * Allocates memory for ApInt data array * Sets flag, len, data for condition 0 * Flag is 1 for 0 */ void set_zero_data(ApInt *ap) { ap->len = 1; ap->data = (uint64_t *)calloc(ap->len, sizeof(uint64_t)); ap->data[0] = 0UL; ap->flags = 1; } /* * Perform mathematical subtraction for two ApInt instances */ ApInt *calc_sub(const ApInt *a, const ApInt *b, ApInt *diff) { int a_greater = left_greater(a, b); const ApInt *greater = a; const ApInt *less = b; if (a_greater == 0) { //subtraction of equal values is 0 set_zero_data(diff); return diff; } else if (a_greater == -1) { greater = b; less = a; } uint64_t next_borrow = 0, prev_borrow = 0; diff->flags = greater->flags; //flags and len from larger value diff->len = greater->len; diff->data = (uint64_t *)calloc(diff->len, sizeof(uint64_t)); for (uint32_t pos = 0; pos < greater->len; pos++) { if (pos <= less->len - 1) { if (greater->data[pos] < less->data[pos] + prev_borrow) { //overflow next_borrow = 1; } else { next_borrow = 0; } diff->data[pos] = greater->data[pos] - less->data[pos] - prev_borrow; } else { //if less is shorter than greater if (greater->data[pos] - prev_borrow > greater->data[pos]) { //overflow next_borrow = 1; } else { next_borrow = 0; } diff->data[pos] = greater->data[pos] - prev_borrow; } prev_borrow = next_borrow; } return diff; } /* * Performs mathematical addition */ ApInt *calc_add(const ApInt *a, const ApInt *b, ApInt *sum) { int a_greater = left_greater(a, b); const ApInt *greater = a; const ApInt *less = b; if (apint_is_zero(a) == 1 && apint_is_zero(b) == 1) { //addition of equal values set_zero_data(sum); return sum; } if (a_greater == -1) { greater = b; less = a; } uint64_t next_carry = 0, prev_carry = 0; sum->flags = greater->flags; //set flags and len of greater sum->len = greater->len; sum->data = (uint64_t *)calloc(sum->len, sizeof(uint64_t)); uint64_t sum_value; for (uint32_t pos = 0; pos < greater->len; pos++) { if (pos <= less->len - 1) { sum_value = greater->data[pos] + less->data[pos] + prev_carry; if (sum_value < greater->data[pos] || sum_value < less->data[pos]) { next_carry = 1; } else { next_carry = 0; } } else { sum_value = greater->data[pos] + prev_carry; if (sum_value < greater->data[pos]) { next_carry = 1; } else { next_carry = 0; } } sum->data[pos] = sum_value; prev_carry = next_carry; } //allocate additional data for carry over if (prev_carry == 1) { sum->data = (uint64_t *)realloc(sum->data, (sum->len + 1)*sizeof(uint64_t)); sum->data[sum->len] = 1UL; sum->len = sum->len + 1; } return sum; } /* * Returns addition of two ApInt instances */ ApInt *apint_add(const ApInt *a, const ApInt *b) { ApInt *result = (ApInt*) malloc(sizeof(ApInt)); assert(result != NULL); //check memory allocation if (a->flags == b->flags) { //if both neg/pos, then data is sum result = calc_add(a, b, result); } else { //if opposite flags, then data is difference result = calc_sub(a, b, result); } return result; } /* * Returns subtraction of two ApInt instances */ ApInt *apint_sub(const ApInt *a, const ApInt *b) { ApInt *neg_b = apint_negate(b); ApInt *result = apint_add(a, neg_b); //subtraction is addition of neg number apint_destroy(neg_b); return result; } /* * Determines if left is greater in magnitude than right * Returns 1: left magnitude greater, -1: right magnitude greater, 0: equal magnitude */ int left_greater(const ApInt *left, const ApInt *right) { int length = left->len; //compare length, greater length = greater magnitude if (left->len > right->len) { return 1; } if (left->len < right->len) { return -1; } //length is equal, compare each data value starting at highest bits for (int i=length-1; i>=0; i--) { if (left->data[i] > right->data[i]) { return 1; } else if (left->data[i] < right->data[i]) { return -1; } } return 0; } /* * Determines if left is greater than right (includes signs) * Returns 1: left > right, -1: right > left, 0: right == left */ int apint_compare(const ApInt *left, const ApInt *right) { if (left->flags > right->flags) { return 1; //left pos, right neg } if (left->flags < right->flags) { return -1; //left neg, right pos } if (left->flags == 0) { //both neg return -1 * left_greater(left, right); } if (left->flags == 1) { //both pos return left_greater(left, right); } return 0; } /* * Left shift by 1 * Uses apint_lshift_n */ ApInt *apint_lshift(ApInt *ap) { return apint_lshift_n(ap, 1); } /* * Performs shifts of elements of data array * Left shift by multiples of 64 bits */ ApInt *full_left_shifts(ApInt *ap, ApInt *ap_shift, unsigned full_shifts) { for (uint32_t i=0; i<ap_shift->len; i++) { if (i < full_shifts) { ap_shift->data[i] = 0UL; } else { ap_shift->data[i] = ap->data[i - full_shifts]; } } return ap_shift; } /* * Performs bit by bit shifts of data array * Left shift of bits less than 64 */ ApInt *bit_left_shifts(ApInt *ap, ApInt *ap_shift, unsigned indiv_shifts) { uint64_t prev_overflow = 0UL, this_overflow = 0UL, compare_with = 0x8000000000000000UL; uint64_t right_shift = compare_with; for (unsigned i=0; i<indiv_shifts-1; i++) { right_shift = right_shift >> 1; compare_with = compare_with | right_shift; } for (uint32_t i=0; i<ap_shift->len; i++) { if (i < ap->len) { this_overflow = compare_with & ap->data[i]; ap_shift->data[i] = ap->data[i] << indiv_shifts; ap_shift->data[i] = ap_shift->data[i] | prev_overflow; } else { ap_shift->data[i] = prev_overflow; } prev_overflow = this_overflow >> (64-indiv_shifts); } return ap_shift; } /* * Returns new ApInt instance of shifted left n times */ ApInt *apint_lshift_n(ApInt *ap, unsigned n) { ApInt *ap_shift = (ApInt*) malloc(sizeof(ApInt)); assert(ap_shift != NULL); //check memory allocation ap_shift->flags = ap->flags; int highest_bit = apint_highest_bit_set(ap); int full_shifts = (n+1+highest_bit)/64; int indiv_shifts = (n+1+highest_bit) % 64; ap_shift->len = full_shifts; if (indiv_shifts > 0) { //allocate an additional element of data array ap_shift->len += 1; } ap_shift->data = (uint64_t *)calloc(ap_shift->len, sizeof(uint64_t)); if (n % 64 == 0) { //only shift by multiples of 64 return full_left_shifts(ap, ap_shift, n/64); } else if (n / 64 > 0) { //shift by multiples of 64, then bit-by-bit full_left_shifts(ap, ap_shift, n/64); bit_left_shifts(ap_shift, ap_shift, n%64); return ap_shift; } else { //only shift for n<64, bit-by-bit bit_left_shifts(ap, ap_shift, n); } return ap_shift; }
C
#ifndef DATABASE_UTILITIES_H #define DATABASE_UTILITIES_H #include <stdbool.h> #include <sqlite3.h> #include "cryptography.h" #define PUB_MSG_TYPE 1 #define PRIV_MSG_TYPE 2 /* holds the user information fetched from the database on a successful login or register */ typedef struct fetched_user_info { unsigned char iv[IV_SIZE+1]; unsigned int encrypt_sz; unsigned char *encrypted_keys; } fetched_userinfo_t; /* this struct holds the information stored in the database for messages */ typedef struct messages_components { /* every message has these variables */ int type; unsigned int msglen; unsigned char *message; unsigned int certlen; char *cert; unsigned int siglen; unsigned char *sig; char *sender; /* only a private message has these variables */ unsigned int reclen; char* recipient; unsigned char *iv; unsigned int s_symkeylen; unsigned char *s_symkey; unsigned int r_symkeylen; unsigned char *r_symkey; } msg_components_t; /* a queue of message component structs, created and modified when messages are fetched from the database. This is returned on success for private and public messages and holds, in chronological order, the messages fetched from the database. */ typedef struct msg_qeue { unsigned int size; unsigned int top; /* stores the rowid of the last message added */ signed long long max_rowid; msg_components_t **messages; } msg_queue_t; /* functions for the user info struct */ bool is_fetched_userinfo_legal(fetched_userinfo_t *f); void free_fetched_userinfo(fetched_userinfo_t *f); /* functions for msg_components_t */ msg_components_t *assign_msg_components(sqlite3_stmt *res); void initialize_msg_components(msg_components_t *m); void free_msg_components(msg_components_t *m); /* functions for msg_queue_t */ msg_queue_t *initialize_msg_queue(void); int add_msg_component(msg_queue_t *q, msg_components_t *m); void free_msg_queue(msg_queue_t *q); #endif
C
/************************************************************************************** : Weather : WeatherInfo.h : WeatherInfo, . **************************************************************************************/ #ifndef WEATHER_INFO_H #define WEATHER_INFO_H // #define C_SCALE 0 #define F_SCALE 1 // #define CITY_NANE_SIZE 64 #define WIND_DIR_SIZE 5 // Show // WeatherInfo typedef void (*WeatherInfo_Show_Method)(void*, int); // WeatherInfo typedef struct _weatherInfo { // char cityName[CITY_NANE_SIZE]; // // int minTempC; int maxTempC; // // int minTempF; int maxTempF; // int preasure; // int humidity; // int windSpeed; // char windDirection[WIND_DIR_SIZE]; // int cloudiness; // int precipitation; // Show - // WeatherInfo_Show_Method Show; } WEATHER_INFO, *PWEATHER_INFO; // WeatherInfo PWEATHER_INFO WeatherInfo_Constructor(void); // WeatherInfo void WeatherInfo_Destructor(PWEATHER_INFO _this); // void WeatherInfo_Show(void * _this, int scale); #endif
C
#include "jpg.h" #include "targa.h" #include <sys/time.h> #ifdef PSOC #ifdef BENCH_JPEG #undef PSOC #endif #ifndef PSOC unsigned long micros() { struct timeval tv; gettimeofday(&tv,NULL); return (1000000*tv.tv_sec) + tv.tv_usec; } int main() { // load image from disk tga_image tga; load_tga(&tga, "test.tga"); uint8_t* buf = (uint8_t*) calloc(1, tga.width * tga.height * sizeof(uint8_t)); uint32_t start_t = micros(); uint8_t* compressed_image; uint32_t encoded_data_n = 0; for (int i = 0; i < 1000; i++) { // compress iamge encoded_data_n = 0; compressed_image = compress_channel(&encoded_data_n, tga.image_data, tga.width, tga.height); if (i == 0) { for (int j = 0; j < encoded_data_n; j++) printf("0x%x,", compressed_image[j]); } // decompress image decompress_channel(buf, compressed_image, tga.width, tga.height); } uint32_t end_t = micros(); printf("DT: %.2fms", (float) (end_t - start_t) / 1000.0f); // decoded the image tga_write_mono("out.tga", buf, tga.width, tga.height); } #endif
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "bibl.h" #include "entree_sortie.h" #define TMAX 41 #define LMAX 100000 // TOUT MARCHE SAUF DOUBLON void initialise_biblio(Biblio* bib) { bib->L=NULL; bib->nbliv=0; } s_livre* creer_livre( int num, char* tit, char* aut ) { s_livre* li = (s_livre*)malloc(sizeof(s_livre)); if( li ) { li->num = num; li->titre = strdup(tit); li->auteur = strdup(aut); li->suiv = NULL; } return li; } void insertion_livre( s_livre* liv, Biblio* bibli ) { liv->suiv = bibli->L; bibli->L = liv; bibli->nbliv++; } void lecture_n_entree(char *nomfic,int n,Biblio *B) { FILE* F; int i; int num; char* titre= (char*) malloc(TMAX*sizeof(char)); char* auteur= (char*) malloc(TMAX*sizeof(char)); int test=B->nbliv; if(titre==NULL || auteur==NULL){ printf("Erreur lors de l'allocation de titre ou auteur\n"); return; } if(n<=0){ printf("n trop petit\n"); return; } s_livre* li=NULL; if(((F=fopen(nomfic,"r"))==NULL)){ printf("Le fichier %s n'existe pas.\n",nomfic); return; } for(i=0;i<n;i++){ num = GetEntier(F); GetChaine(F, TMAX, titre); GetChaine(F, TMAX, auteur); li=creer_livre(num,titre,auteur); insertion_livre(li,B); } if(test+n!= B->nbliv){ printf("Erreur dans l'insertion des livres dans la bibliothèque\n"); } } int recherche_ouv_num(int n,Biblio* B) { s_livre* courant = B->L; while(courant!=NULL){ if(courant->num==n){ printf("Livre trouvé! Titre: %s Auteur:%s Num:%d\n",courant->titre,courant->auteur,courant->num); return 1; } courant=courant->suiv; } printf("Le livre dont le numéro d'ouvrage est:%d n'a pas été trouvé.\n",n); return 0; } void recherche_ouv_titre(char* titre,Biblio* B) { int i; s_livre* courant = B->L; for (i = 0; i <B->nbliv; i++){ if(strcmp(titre,courant->titre)==0){ printf("Livre trouvé. Auteur: %s num: %d\n",courant->auteur,courant->num); return; } courant=courant->suiv; } printf("Le livre dont le titre est:%s n'a pas été trouvé.\n",titre); } void recherche_livre_par_auteur(char* auteur, Biblio* B) { int bool=0; s_livre* courant = B->L; while(courant!=NULL) { if(strcmp(auteur,courant->auteur)==0){ printf("Titre: %s num: %d\n",courant->titre,courant->num); bool=1; } courant = courant->suiv; } if(bool==0) { printf("L'auteur n'est pas dans la bibliothèque\n"); } } void suppression_ouvrage(int n,Biblio* B) { s_livre* courant =B->L; if(courant->num==n){ //Si le livre se trouve en première position s_livre* tmp=B->L->suiv; free(courant->auteur); free(courant->titre); free(courant); if(courant==NULL)printf("Ouvrage %d supprimé de la bibliotheque\n",n); courant=tmp; B->nbliv--; return; } while(courant){ if(courant->suiv->num==n){ s_livre* tmp=courant->suiv->suiv; free(courant->suiv->auteur); free(courant->suiv->titre); free(courant->suiv); courant->suiv=tmp; B->nbliv--; return; } courant=courant->suiv; } printf("Le livre dont le numéro d'ouvrage est:%d n'a pas été trouvé.\n",n); } void cherche_double(Biblio* B,Biblio* bis) { //MARCHE PAS initialise_biblio(bis); s_livre* courant=B->L; if(!courant->suiv){ printf("La bibliotheque contient seulement 1 livre\n"); return; } s_livre* tmp=courant->suiv; while(courant){ while(tmp){ if((strcmp(tmp->auteur,courant->auteur))==0 && (strcmp(tmp->titre,courant->titre)==0)){ insertion_livre(courant,bis); printf("le livre %s par l'auteur %s a été trouvé en double.\n",tmp->titre,tmp->auteur); } tmp=tmp->suiv; } courant=courant->suiv; } } void afficher_biblio(Biblio* B) { s_livre* courant = B->L; if(B==NULL || B->nbliv==0){ printf("La bibliothèque est vide\n"); return; } while(courant!=NULL){ printf("Num:%d Titre:%s Auteur:%s\n",courant->num,courant->titre,courant->auteur); courant=courant->suiv; } } void supprimer_biblio(Biblio* B){ s_livre* courant=B->L; while(B->nbliv!=0){ suppression_ouvrage(courant->num,B); courant=courant->suiv; } //free(B); }
C
#include<stdio.h> #include<stdlib.h> #define N 100 #define swap(a,b) {int temp=a;a=b;b=temp;} int arr[N]; void bubble_sort(int * a) { for ( int i = 0; i < N; i++) { int max = a[i]; int index = i; for (int j = i+1; j < N; j++) { if (a[j] > max) { max = a[j]; index = j; } } swap(a[i], a[index]); } } int main() { for (int i = 0; i < N; i++) { arr[i] = rand() % N; } bubble_sort(arr); for (int i = 0; i < N; i++) { printf("%4d", arr[i]); if (i % 10 == 9) { printf("\n"); } } system("pause"); }