language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include<math.h>
#include<stdio.h>
int main()
{int n=0,no,cp,r,ans=0;
printf("ENTER A NO\n");
scanf("%d",&no);
cp=no;
while(no>0)
{
no=no/10;
n=n+1;
}
no=cp;
while(cp>0)
{
r=cp%10;
ans=ans+pow(r,n);
cp=cp/10;
}
if(ans==no)
printf("ANGSTROM NUMBER");
else
printf("NOT A ANGSTROM NUMBER");
return 0;
}
|
C
|
#include <mouse.h>
double g_coge_mouse_pos_x;
double g_coge_mouse_pos_y;
double g_coge_mouse_last_pos_x;
double g_coge_mouse_last_pos_y;
double g_coge_mouse_dx;
double g_coge_mouse_dy;
double g_coge_mouse_scroll_dx;
double g_coge_mouse_scroll_dy;
int g_coge_is_first_mouse;
int g_coge_mouse_buttons[GLFW_MOUSE_BUTTON_LAST + 1];
int g_coge_mouse_buttons_changed[GLFW_MOUSE_BUTTON_LAST + 1];
void coge_init_mouse() {
g_coge_mouse_pos_x = 0;
g_coge_mouse_pos_y = 0;
g_coge_mouse_last_pos_x = 0;
g_coge_mouse_last_pos_y = 0;
g_coge_mouse_dx = 0;
g_coge_mouse_dy = 0;
g_coge_mouse_scroll_dx = 0;
g_coge_mouse_scroll_dy = 0;
g_coge_is_first_mouse = 1;
int i;
for (i = 0; i < GLFW_MOUSE_BUTTON_LAST + 1; i++) {
g_coge_mouse_buttons[i] = 0;
g_coge_mouse_buttons_changed[i] = 0;
}
}
void coge_mouse_cursor_pos_callback(GLFWwindow * window, double _x, double _y) {
g_coge_mouse_pos_x = _x;
g_coge_mouse_pos_y = _y;
if (g_coge_is_first_mouse) {
g_coge_mouse_last_pos_x = g_coge_mouse_pos_x;
g_coge_mouse_last_pos_x = g_coge_mouse_pos_y;
g_coge_is_first_mouse = 0;
}
g_coge_mouse_dx = g_coge_mouse_pos_x - g_coge_mouse_last_pos_x;
g_coge_mouse_dy = g_coge_mouse_pos_y - g_coge_mouse_last_pos_y;
g_coge_mouse_last_pos_x = g_coge_mouse_pos_x;
g_coge_mouse_last_pos_y = g_coge_mouse_pos_y;
}
void coge_mouse_button_callback(GLFWwindow * window, int button, int action, int mods) {
if (action != GLFW_RELEASE) {
if (!g_coge_mouse_buttons[button]) {
g_coge_mouse_buttons[button] = 1;
}
}
else {
g_coge_mouse_buttons[button] = 0;
}
g_coge_mouse_buttons_changed[button] = action != GLFW_REPEAT;
}
void coge_mouse_wheel_callback(GLFWwindow * window, double _dx, double _dy) {
g_coge_mouse_scroll_dx = _dx;
g_coge_mouse_scroll_dy = _dy;
}
double coge_get_mouse_pos_x() {
return g_coge_mouse_pos_x;
}
double coge_get_mouse_pos_y() {
return g_coge_mouse_pos_y;
}
double coge_get_mouse_dx() {
double _dx = g_coge_mouse_dx;
g_coge_mouse_dx = 0;
return _dx;
}
double coge_get_mouse_dy() {
double _dy = g_coge_mouse_dy;
g_coge_mouse_dy = 0;
return _dy;
}
double coge_get_mouse_scroll_dx() {
double sdx = g_coge_mouse_scroll_dx;
g_coge_mouse_scroll_dx = 0;
return sdx;
}
double coge_get_mouse_scroll_dy() {
double sdy = g_coge_mouse_scroll_dy;
g_coge_mouse_scroll_dy = 0;
return sdy;
}
int coge_mouse_button(int button) {
return g_coge_mouse_buttons[button];
}
int coge_mouse_button_changed(int button) {
int ret = g_coge_mouse_buttons_changed[button];
g_coge_mouse_buttons_changed[button] = 0;
return ret;
}
int coge_mouse_button_down(int button) {
return g_coge_mouse_buttons[button] && coge_mouse_button_changed(button);
}
int coge_mouse_button_up(int button) {
return !g_coge_mouse_buttons[button] && coge_mouse_button_changed(button);
}
|
C
|
#include<stdio.h>
void using_if(void);
void using_switch(void);
void using_while(void);
int main()
{
using_if();
using_switch();
using_while();
return 0;
}
void using_if(void)
{
if(printf("Hello world \n ")){}
}
void using_switch(void)
{
switch(printf("Hello world \n")){}
}
void using_while(void)
{
while(!printf("Hello world \n")){}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
int main(int argc, char **argv)
{
int i;
double x, sum, pi = 0;
long num_steps = atol(argv[1]);
int threads = atoi(argv[2]);
double step = 1.0 / num_steps;
double start, finish;
FILE *fp;
omp_set_num_threads(threads);
start = omp_get_wtime();
#pragma omp parallel private(i, x, sum)
{
int id = omp_get_thread_num();
for (i = id, sum = 0; i < num_steps; i += threads)
{
x = (i + 0.5) *step;
sum += 4.0 / (1.0 + x * x);
}
#pragma omp critical
pi += sum * step;
}
finish = omp_get_wtime();
fp = fopen("pi_openmp time.txt", "a");
fprintf(fp, "n = %ld, threads = %d, time = %lf\n", num_steps, threads, finish-start);
return 0;
}
|
C
|
/*
* motor.c
*
* Created on: Dec. 28, 2020
* Author: damien sabljak
*/
#define MOTOR_ARMED 1
#define MOTOR_DISARMED 2
#define MOTOR_ARMING_PULSE_WIDTH 7
#include"stm32f1xx_hal.h"
TIM_HandleTypeDef htim4;
uint8_t timChannels[] = {TIM_CHANNEL_1,TIM_CHANNEL_2,TIM_CHANNEL_3,TIM_CHANNEL_4};
void Motor_Arm()
{
//ARM PWM Signals
HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_1);
HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_2);
HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_3);
HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_4);
uint16_t pulse_width = 7;
}
void Motor_Set_Speed_Single(uint8_t MotorNum, int16_t speed_scaled)
{
//input: (0 to 1000), this gets converted to between 800 and 1600 (see clock speed calcs)
int16_t speed_converted = 8*(speed_scaled/10) + 800;
__HAL_TIM_SET_COMPARE(&htim4, timChannels[MotorNum], speed_converted);
}
void Motor_Set_Speed_All(int16_t speed_scaled1, int16_t speed_scaled2, int16_t speed_scaled3, int16_t speed_scaled4)
{
//CONVENTION from front left clockwise
Motor_Set_Speed_Single(0, speed_scaled1);
Motor_Set_Speed_Single(3, speed_scaled2);
Motor_Set_Speed_Single(1, speed_scaled3);
Motor_Set_Speed_Single(2, speed_scaled4);
}
|
C
|
#include "monty.h"
int val = 0;
/**
* main - receives arguments and then passes to stack
* @argc: argument count
* @argv: argument vector
* Return: 0 if success
*/
int main(int argc, char **argv)
{
char *l, *symbol;
unsigned int line_num;
size_t len;
stack_t *stack;
FILE *ar;
if (argc != 2)
arguments_error();
ar = fopen(argv[1], "r");
if (ar == NULL)
file_error(argv[1]);
stack = NULL;
l = symbol = NULL;
len = 0;
line_num = 0;
while (getline(&l, &len, ar) != -1 && val == 0)
{
line_num++;
symbol = strtok(l, "\n\t\r ");
if (symbol == NULL || strncmp(symbol, "#", 1) == 0)
continue;
if (strcmp(symbol, "push") == 0)
{
symbol = strtok(NULL, "\n\t\r ");
_push(&stack, line_num, symbol);
}
else
op_func(symbol, &stack, line_num);
}
free_all(stack, l, ar);
if (val != 0)
exit(EXIT_FAILURE);
return (EXIT_SUCCESS);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* uinteger.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rkeli <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/07/19 14:15:57 by rkeli #+# #+# */
/* Updated: 2019/07/19 14:15:57 by rkeli ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
void uint_char(va_list ap)
{
char *in;
int tmplen;
int len;
unsigned int arg;
arg = (unsigned char)va_arg(ap, unsigned int);
in = ft_stoa(arg);
len = (int)ft_strlen(in);
tmplen = (g_f->plu || g_f->spc) ? g_f->wid - len - 1 +
(arg == 0 && g_f->dot) : g_f->wid - len + (arg == 0 && g_f->dot);
if (tmplen <= 0)
{
u_print_sign(g_f->plu, g_f->spc);
tmplen = g_f->pre - len;
addcharn('0', tmplen);
if (!(!g_f->pre && !arg && g_f->dot))
g_vector = ft_vector(g_vector, in, 5, 0);
}
else if (g_f->min)
u_minus(arg, len, in);
else if (g_f->dot)
u_precision(arg, len, in);
else
u_zero_and_else(arg, in, tmplen);
free(in);
}
void uint_short(va_list ap)
{
char *in;
int tmplen;
int len;
unsigned int arg;
arg = (unsigned short)va_arg(ap, unsigned int);
in = ft_stoa(arg);
len = (int)ft_strlen(in);
tmplen = (g_f->plu || g_f->spc) ? g_f->wid - len - 1 +
(arg == 0 && g_f->dot) : g_f->wid - len + (arg == 0 && g_f->dot);
if (tmplen <= 0)
{
u_print_sign(g_f->plu, g_f->spc);
tmplen = g_f->pre - len;
addcharn('0', tmplen);
if (!(!g_f->pre && !arg && g_f->dot))
g_vector = ft_vector(g_vector, in, 5, 0);
}
else if (g_f->min)
u_minus(arg, len, in);
else if (g_f->dot)
u_precision(arg, len, in);
else
u_zero_and_else(arg, in, tmplen);
free(in);
}
void uint_int(va_list ap)
{
char *in;
int tmplen;
int len;
unsigned int arg;
arg = va_arg(ap, unsigned int);
in = ft_stoa((unsigned int)arg);
len = (int)ft_strlen(in);
tmplen = (g_f->plu || g_f->spc) ? g_f->wid - len - 1 +
(arg == 0 && g_f->dot) : g_f->wid - len + (arg == 0 && g_f->dot);
if (tmplen <= 0)
{
u_print_sign(g_f->plu, g_f->spc);
tmplen = g_f->pre - len;
addcharn('0', tmplen);
if (!(!g_f->pre && !arg && g_f->dot))
g_vector = ft_vector(g_vector, in, 5, 0);
}
else if (g_f->min)
u_minus(arg, len, in);
else if (g_f->dot)
u_precision(arg, len, in);
else
u_zero_and_else(arg, in, tmplen);
free(in);
}
void uint_long(va_list ap)
{
char *in;
int tmplen;
int len;
unsigned long arg;
arg = va_arg(ap, unsigned long);
in = ft_stoa((unsigned long)arg);
len = (int)ft_strlen(in);
tmplen = (g_f->plu || g_f->spc) ? g_f->wid - len - 1 +
(arg == 0 && g_f->dot) : g_f->wid - len + (arg == 0 && g_f->dot);
if (tmplen <= 0)
{
u_print_sign(g_f->plu, g_f->spc);
tmplen = g_f->pre - len;
addcharn('0', tmplen);
if (!(!g_f->pre && !arg && g_f->dot))
g_vector = ft_vector(g_vector, in, 5, 0);
}
else if (g_f->min)
u_minus(arg, len, in);
else if (g_f->dot)
u_precision(arg, len, in);
else
u_zero_and_else(arg, in, tmplen);
free(in);
}
void uint_long_long(va_list ap)
{
char *in;
int tmplen;
int len;
unsigned long long arg;
arg = va_arg(ap, unsigned long long);
in = ft_stoa(arg);
len = (int)ft_strlen(in);
tmplen = (g_f->plu || g_f->spc) ? g_f->wid - len - 1 +
(arg == 0 && g_f->dot) : g_f->wid - len + (arg == 0 && g_f->dot);
if (tmplen <= 0)
{
u_print_sign(g_f->plu, g_f->spc);
tmplen = g_f->pre - len;
addcharn('0', tmplen);
if (!(!g_f->pre && !arg && g_f->dot))
g_vector = ft_vector(g_vector, in, 5, 0);
}
else if (g_f->min)
u_minus(arg, len, in);
else if (g_f->dot)
u_precision(arg, len, in);
else
u_zero_and_else(arg, in, tmplen);
free(in);
}
|
C
|
#define _XOPEN_SOURCE 700
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdbool.h>
#include <inttypes.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <utime.h>
#include <limits.h>
#include <sys/types.h>
#include <pwd.h>
#define BUF_SIZE (4096)
#define osAssert(cond,msg) osErrorFatal(cond,msg,__FILE__,__LINE__)
void osErrorFatal(bool cond,const char *msg, const char *fname,int line){
if(!cond){
perror(msg);
fprintf(stderr,"%s:%d\n",fname,line);
exit(EXIT_FAILURE);
}
}
int main(int argc, char** argv){
osAssert(3==argc,"Upotreba: ./umask_demo putanja prava");
const char *fpath=argv[1];
const char *accessStr=argv[2];
mode_t accessMode= (mode_t)strtol(accessStr,NULL,8);
mode_t oldMask=umask(0);
int fd=open(fpath,O_CREAT,accessMode);
osAssert(-1!=fd,"Kreiranje fajla nije uspelo");
close(fd);
umask(oldMask);
return 0;
}
|
C
|
/**
* @file
* VuoVerticalAlignment implementation.
*
* @copyright Copyright © 2012–2020 Kosada Incorporated.
* This code may be modified and distributed under the terms of the MIT License.
* For more information, see https://vuo.org/license.
*/
#include <string.h>
#include "type.h"
/// @{
#ifdef VUO_COMPILER
VuoModuleMetadata({
"title" : "Vertical Alignment",
"description" : "Vertical alignment.",
"keywords" : [ ],
"version" : "1.0.0",
"dependencies" : [
"VuoList_VuoVerticalAlignment"
]
});
#endif
/// @}
/**
* @ingroup VuoVerticalAlignment
* Decodes the JSON object @c js to create a new value.
*
* @eg{
* {
* "replaceThis" : -1
* }
* }
*/
VuoVerticalAlignment VuoVerticalAlignment_makeFromJson(json_object * js)
{
const char *valueAsString = "";
if (json_object_get_type(js) == json_type_string)
valueAsString = json_object_get_string(js);
if (strcmp(valueAsString, "center") == 0)
return VuoVerticalAlignment_Center;
else if (strcmp(valueAsString, "bottom") == 0)
return VuoVerticalAlignment_Bottom;
return VuoVerticalAlignment_Top;
}
/**
* @ingroup VuoVerticalAlignment
* Encodes @c value as a JSON object.
*/
json_object * VuoVerticalAlignment_getJson(const VuoVerticalAlignment value)
{
char *valueAsString = "top";
if (value == VuoVerticalAlignment_Center)
valueAsString = "center";
else if (value == VuoVerticalAlignment_Bottom)
valueAsString = "bottom";
return json_object_new_string(valueAsString);
}
/**
* Returns a list of values that instances of this type can have.
*/
VuoList_VuoVerticalAlignment VuoVerticalAlignment_getAllowedValues(void)
{
VuoList_VuoVerticalAlignment l = VuoListCreate_VuoVerticalAlignment();
VuoListAppendValue_VuoVerticalAlignment(l, VuoVerticalAlignment_Top);
VuoListAppendValue_VuoVerticalAlignment(l, VuoVerticalAlignment_Center);
VuoListAppendValue_VuoVerticalAlignment(l, VuoVerticalAlignment_Bottom);
return l;
}
/**
* @ingroup VuoVerticalAlignment
* Returns a compact string representation of @c value.
*/
char * VuoVerticalAlignment_getSummary(const VuoVerticalAlignment value)
{
char *valueAsString = "Top";
if (value == VuoVerticalAlignment_Center)
valueAsString = "Center";
else if (value == VuoVerticalAlignment_Bottom)
valueAsString = "Bottom";
return strdup(valueAsString);
}
/**
* Returns true if the two values are equal.
*/
bool VuoVerticalAlignment_areEqual(const VuoVerticalAlignment valueA, const VuoVerticalAlignment valueB)
{
return valueA == valueB;
}
/**
* Returns true if `valueA` is less than `valueB`.
*/
bool VuoVerticalAlignment_isLessThan(const VuoVerticalAlignment valueA, const VuoVerticalAlignment valueB)
{
return valueA < valueB;
}
|
C
|
#include <stdio.h>
#include <math.h>
void main(){
typedef struct Puntos{
int xy[3][3];
}Punto;
int i;
int j;
Punto pun[3];
for(i=0;i<2;i++){
for(j=0;j<1;j++){
printf("\nIngrese el punto [x][y] %i,%i: ",i,j);
scanf("%i",&pun[i].xy[i][j]);
}
}
}
|
C
|
#include<stdio.h>
main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,m,k;
scanf("%d%d%d",&n,&m,&k);
int diff = (n>m)?n-m:m-n;
int left=0,actual;
if(k<diff)
{
printf("%d\n",diff-k);
}
else
{
printf("%d\n",left);
}
}
}
|
C
|
#include<stdio.h>
#include<math.h>
#define LAMBDA 0.001
int main(){
double t;
float r;
int i,R;
for(i=1;i<=27;i++){
printf("--");
}
printf("\n");
for(t=0;t<=3000;t+=150){
r=exp(-LAMBDA*t);
R=(int)(50*r+0.5);
printf(" |");
for(i=1;i<=R;++i){
printf("*");
}
printf("#\n");
}
for(i=1;i<3;++i){
printf(" |\n");
}
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef ioctl
void my_err(const char *err_string,int line)
{
fprintf(stderr,"line:%d",line);
perror(err_string);
exit(1);
}
int main(){
int ret;
int access_mode;
int fd;
if((fd=open("example.c",O_CREAT|O_TRUNC|O_RDWR,S_IRWXU))==-1){
my_err("open",__LINE__);
}
if((ret=fcntl(fd,F_SETFL,O_APPEND))<0){
my_err("fcntl",__LINE__);
}
if((ret=fcntl(fd,F_GETFL,0))<0){
my_err("fcntl",__LINE__);
}
access_mode =ret&O_ACCMODE;
if(access_mode==O_RDONLY){
printf("example access mode: read only");
}else if (access_mode==O_WRONLY) {
printf("example access mode:write only");
}else if (access_mode==O_RDWR) {
printf("example access mode: read+write");
}
if(ret&O_APPEND){
printf(",append");
}
if(ret&O_NONBLOCK){
printf(",nonblock");
}
if(ret&O_SYNC){
printf(",sync");
}
printf("\n");
return 0;
}
#endif
|
C
|
/*http://pages.cs.wisc.edu/~remzi/OSTEP/threads-sema.pdf*/
/*page 13*/
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define PHILS 5
sem_t forks[PHILS];
void think(int name) {
printf("\nthinking - %d", name);
}
void eat(int name) {
printf("\neating - %d", name);
}
int left(int p) {
return p;
}
int right(int p) {
return (p+1) % PHILS;
}
void getforks(int p) {
if (p == (PHILS -1 )) {
sem_wait(&forks[right(p)]);
sem_wait(&forks[left(p)]);
} else {
sem_wait(&forks[left(p)]);
sem_wait(&forks[right(p)]);
}
}
void putforks(int p) {
sem_post(&forks[left(p)]);
sem_post(&forks[right(p)]);
}
void *philosopher(void *arg) {
int name = *(int *)arg;
while(1) {
think(name);
getforks(name);
eat(name);
putforks(name);
}
return NULL;
}
int main(int argc, char *argv[]) {
int i;
pthread_t philosophers[PHILS];
int philNames[PHILS];
for(i = 0; i < PHILS; i++) {
sem_init(&forks[i], 0, 1);
philNames[i] = i;
}
for(i = 0; i < PHILS; i++) {
pthread_create(&philosophers[i], NULL, philosopher, &philNames[i]);
}
for(i = 0; i < PHILS; i++) {
pthread_join(philosophers[i], NULL);
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/*
whiplace: multiple stream replacement
USAGE:
whiplace keyfile targetfile
*/
void exit_memory_failure(void) {
fprintf(stderr, "memory error\n");
exit(EXIT_FAILURE);
}
void exit_no_sep_failure(char *s) {
fprintf(stderr, "character separator not found in line %s\n", s);
exit(EXIT_FAILURE);
}
int cmp_wrapper(const void *a, const void *b) {
const char **ia = (const char **) a;
const char **ib = (const char **) b;
return strcmp(*ia, *ib);
}
void symsplit(char **keys, char **values, const char c) {
// Symbolic split of key-value pairs on char 'c'. Keys and values are
// The first occurence of 'c' is replaced by '\0' and the pointer in
// 'values' is assigned to the next character. Pointers in 'keys' and
// 'values' at the same index point to different positions of the same
// string.
int i, j;
// Iterate over 'keys' array.
for (i = 0 ; keys[i] != NULL ; i++) {
for (j = 0 ; keys[i][j] != c ; j++)
if (keys[i][j] == '\0') exit_no_sep_failure(keys[i]);
keys[i][j] = '\0';
values[i] = keys[i] + j+1;
}
}
struct keyval get_key_values (FILE *f) {
// Read in key-value pairs from file, one pair per line.
char iob[IO_BUFFER_SIZE];
int nitems = 0;
// Count lines. Hope to hit '\n' on every call to 'fgets'.
// If not, overestimate 'nitems' and assign too much memory.
fseek(f, 0, SEEK_SET);
while(fgets(iob, IO_BUFFER_SIZE, f) != NULL) nitems++;
char **keys = (char **) malloc((nitems+1) * sizeof(char *));
char **values = (char **) malloc((nitems+1) * sizeof(char *));
if ((keys == NULL) || (values == NULL)) exit_memory_failure();
int len, i = 0;
// Read file again and copy lines to 'keys'.
fseek(f, 0, SEEK_SET);
while (fgets(iob, IO_BUFFER_SIZE, f) != NULL) {
len = strlen(iob);
// Chomp (replace '\n' by '\0').
if (iob[len-1] == '\n') iob[--len] = '\0';
char *temp = (char *) malloc((len+1) * sizeof(char));
if (temp == NULL) exit_memory_failure();
strcpy(temp, iob);
keys[i++] = temp;
}
// Add sentinels.
keys[i] = NULL;
values[i] = NULL;
// Split the key/value on tab character and sort.
symsplit(keys, values, '\t');
qsort(keys, nitems, sizeof(char *), cmp_wrapper);
struct keyval kv = {
.keys = keys,
.values = values,
.nitems = nitems
};
return kv;
}
struct trienode *create_node(void) {
struct trienode *new_node = NULL; // Required to reclaim memory.
new_node = malloc(sizeof(struct trienode));
if (new == NULL) exit_memory_failure();
new_node->key_index = -1;
new_node->chars = NULL;
new_node->children = NULL;
return new;
}
void build_trie(struct trienode *thisnode, int down, const int up,
const char **keys, const int depth) {
// 'thisnode': current node.
// 'up': upper limit of key index for descent of current node.
// 'down': lower limit of key index for descent of current node.
// 'keys': whiplace key set.
// 'depth': depth of current node in the trie.
// Temp arrays.
int min[256], max[256];
// Allocate too much. Will realloc() later.
thisnode->chars = (char *) malloc(256 * sizeof(char));
// Specify key index if a key finishes here (and skip the key).
if (keys[down][depth] == '\0') thisnode->key = down++;
// Here function.
void allocate(int k) {
// Allocate memory for characters and children.
thisnode->children = \
(struct trienode **) calloc(k+1, sizeof(struct trienode *));
if (thisnode->children == NULL) exit_memory_failure();
// Add the sentinels.
thisnode->chars[k] = '\0';
thisnode->children[k] = NULL;
}
if (down > up) {
// This is a leaf node.
allocate(0);
}
else {
// This is a branch node.
int i, j = 0;
thisnode.chr = keys[down][depth];
min[0] = max[0] = down;
// Gather and count letters at given depth.
for (i = down + 1 ; i < up + 1 ; i++) {
if (thisnode.chr != keys[i][depth]) {
// New character.
j++;
thisnode->chars[j] = keys[i][depth];
min[j] = max[j] = i;
}
else {
/* Increment total count for character. */
++max[j];
}
}
// Allocate memory for (j+1) children.
allocate(j+1);
// Depth-first recursion.
for (i = 0 ; i < j + 1 ; i++) {
thisnode->children[i] = newnode();
build_tree(thisnode->children[i], min[i], max[i],
keys, depth + 1);
}
}
}
int find_char(const char c, const string sorted_keys) {
/*
* Find char c in sorted string by bisection. Return
* its index in sorted_keys if match, -1 otherwise.
*/
int down = 0;
int up = strlen(sorted_keys) - 1;
int diff;
while (up > down) {
diff = sorted_keys[(up+down)/2] - c;
if (diff < 0) {
/* The key is too small, we can it. */
down = (up + down) / 2 + 1;
}
else if (diff > 0) {
/* The key is too large, we can also skip. */
up = (up + down) / 2 - 1;
}
else {
/* Found the match. */
return (up + down) / 2;
}
}
/*
* Now up and down are either equal, or up < down.
* In the first case we need to check one last key,
* in the second, we're already done.
*/
if ((up == down) && (sorted_keys[up] == c)) {
return up;
}
/* No match. */
return -1;
}
int keycomp (string stream, string key) {
/*
* Compare a key to a stream. Return -1, if no match is
* found in the stream, the length of the key otherwise.
*/
int i = 0;
while (key[i] == stream[i]) {
i++;
if (key[i] == '\0') {
/* Matched until end of key. */
return i;
}
}
/* Did not match. */
return -1;
}
int whip(const string stream, struct trienode *node) {
/*
* Match the current position of the stream with
* the key tree. Return -1 if no match is found,
* and the key index otherwise.
*/
char c = stream[0];
int j, i = 0;
int charmatch, keymatch = -1;
do {
if ((*node).key > -1) {
keymatch = (*node).key;
}
/* Find char match. */
if ((*node).branch) {
/* Node is a branch: find where to go next */
charmatch = find_char(c, (*node).chars);
j = 1;
}
else {
/* Node is a stem: check whether it matches stream. */
j = keycomp(stream + i, (*node).chars);
charmatch = 0;
}
if ((charmatch > -1) && (j > -1)) {
node = (*node).children[charmatch];
i += j; // 1 if branch, key length otherwise.
c = stream[i];
}
}
/*
* Continue until no character matches. Leaf
* nodes can't match, which stop the loop.
*/
while ((charmatch > -1) && (j > -1));
return keymatch;
}
void whiplace (FILE *keyf, FILE *streamf, FILE *outf) {
int i;
/* Get and sort keys + values. */
const struct keyval kv = get_key_values(keyf);
/* Check key duplicates. */
for (i = 0 ; i < kv.nitems -2; i++) {
if (strcmp(kv.keys[i], kv.keys[i+1]) == 0) {
fprintf(stderr, "key '%s' duplicated\n", kv.keys[i]);
exit(EXIT_FAILURE);
}
}
/* Build the key tree. */
struct trienode * const root = newnode();
build_tree(root, 0, kv.nitems-1, kv.keys, 0);
/* Let it whip! */
string buffer = (string) shift(streamf, 0);
while (buffer[0] != '\0') {
i = whip(buffer, root);
if (i > -1) {
/* Found a match. */
fprintf(outf, "%s", kv.values[i]);
buffer = (string) shift(streamf, strlen(kv.keys[i]));
}
else {
fprintf(outf, "%c", buffer[0]);
buffer = (string) shift(streamf, 1);
}
}
return;
}
int main (int argc, string argv[]) {
string USAGE = "\n"
"whiplace: multiple stream replacement\n\n"
"USAGE:\n"
" whiplace keyfile targetfile\n\n";
/* Options and arguments processing. */
if ((argc < 2) || (argc > 4)) {
fprintf(stderr, USAGE);
exit(EXIT_FAILURE);
}
string keyfname = NULL;
keyfname = argv[1];
string fname = argc > 2 ? argv[2] : NULL;
string outfname = argc > 3 ? argv[3] : NULL;
FILE *keyf = fopen(keyfname, "r");
FILE *streamf = (fname == NULL) ? stdin : fopen(fname, "r");
FILE *outf = (outfname == NULL) ? stdout : fopen(outfname, "w");
if (keyf == NULL) {
fprintf(stderr, "cannot open key file %s\n", keyfname);
exit(EXIT_FAILURE);
}
if (streamf == NULL) {
fprintf(stderr, "cannot open stream %s\n", fname);
exit(EXIT_FAILURE);
}
if (outf == NULL) {
fprintf(stderr, "cannot open file %s for writing\n", outfname);
exit(EXIT_FAILURE);
}
/* (End of option parsing). */
whiplace(keyf, streamf, outf);
/* Wrap up. */
fflush(outf);
fclose(keyf);
fclose(streamf);
fclose(outf);
exit(EXIT_SUCCESS);
}
|
C
|
/* **********************************************
* C program to convert Hexadecimal to Decimal *
************************************************/
#include <stdio.h>
#include <math.h>
int main()
{
int hex[20], dec, i, j, ch, p;
i = 0;
p=0;
dec=0;
// Read a Hexadecimal value
printf("Enter a Hexadecimal value : ");
while ((ch=getchar()) != '\n') {
if ((ch > 47 && ch < 58) || (ch > 64 && ch < 71))
hex[i++] = ch;
}
// Convert Hexadecimal to Decimal
for (j = i-1; j >= 0; j-- ) {
if (hex[j] > 57)
dec += (hex[j] - 55) * (int)pow((double)16, p);
else
dec += (hex[j] - 48) * (int)pow((double)16, p);
p++;
}
// Print the hexadecimal value
printf("Decimal value is : %d",dec);
//Wait for key press
printf("\n\nPress any key to continue...");
getchar();
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
int main(){
float a,b,c;
printf("Enter the first Number:\n");
scanf("%f",&a);
printf("Enter the second Number:\n");
scanf("%f",&b);
c=(a+b)/2;
printf("The Sum of the two numbers are: %f", c);
}
|
C
|
/* Penguin */
/*
* Copyright (C) Argonne National Laboratory
*
* Argonne does not guarantee this software in any manner and is
* not responsible for any damages that may result from its use.
* Furthermore, Argonne does not provide any formal support for this
* software. This is an experimental program. This software
* or any part of it may be freely copied and redistributed,
* provided that this paragraph is included in each source file.
*
*/
/*
* io.c -- input/output routines
*
*/
#include "header.h"
#define SYM_TAB_SIZE 50
static struct sym_ent *Sym_tab[SYM_TAB_SIZE];
#ifdef ROO
/*************
*
* init_sym_tab_for_roo()
*
* Insert dummy nodes so that all slaves will share table with master.
*
*************/
init_sym_tab_for_roo()
{
int i;
for (i=0; i < SYM_TAB_SIZE; i++) {
Sym_tab[i] = get_sym_ent();
Sym_tab[i]->sym_num = -1;
str_copy("dummy_node", Sym_tab[i]->name);
}
} /* init_sym_tab_for_roo */
#endif
/*************
*
* print_variable(fp, variable)
*
*************/
void print_variable(fp, t)
FILE *fp;
struct term *t;
{
int i;
if (t->sym_num != 0)
fprintf(fp, "%s", sn_to_str(t->sym_num));
else if (Flags[PROLOG_STYLE_VARIABLES].val) {
fprintf(fp, "%c", (t->varnum % 26) + 'A');
i = t->varnum / 26;
if (i > 0)
fprintf(fp, "%d", i);
}
else {
if (t->varnum <= 2)
fprintf(fp, "%c", 'x'+t->varnum);
else if (t->varnum <= 5)
fprintf(fp, "%c", 'r'+t->varnum);
else
fprintf(fp, "%c%d", 'v', t->varnum);
}
} /* print_variable */
/*************
*
* str_print_variable(str, ip, variable)
*
*************/
void str_print_variable(str, ip, t)
char *str;
int *ip;
struct term *t;
{
int i;
char *s2, s3[100];
if (t->sym_num != 0) {
s2 = sn_to_str(t->sym_num);
str_copy(s2, str += *ip);
*ip += strlen(s2);
}
else if (Flags[PROLOG_STYLE_VARIABLES].val) {
str[(*ip)++] = (t->varnum % 26) + 'A';
i = t->varnum / 26;
if (i > 0) {
sprintf(s3, "%d", i);
str_copy(s3, str+*ip);
*ip += strlen(s3);
}
}
else {
if (t->varnum <= 2)
str[(*ip)++] = t->varnum + 'x';
else if (t->varnum <= 5)
str[(*ip)++] = t->varnum + 'r';
else {
str[(*ip)++] = 'v';
sprintf(s3, "%d", t->varnum);
str_copy(s3, str+*ip);
*ip += strlen(s3);
}
}
} /* str_print_variable */
/*************
*
* print_term(file_ptr, term) -- Print a term to a file.
*
* Variables 0-5 are printed as x,y,z,u,v,w, and equalities
* and negated equalities are printed in infix.
*
*************/
void print_term(fp,t)
FILE *fp;
struct term *t;
{
struct rel *r;
struct term *t1;
if (t == NULL)
fprintf(fp, "(nil)");
else if (t->type == NAME) { /* name */
if (t->sym_num == Nil_sym_num)
fprintf(fp, "[]");
else
fprintf(fp, "%s", sn_to_str(t->sym_num));
}
else if (t->type == VARIABLE) /* variable */
print_variable(fp, t);
else { /* complex */
if (t->sym_num == Cons_sym_num) { /* list notation */
fprintf(fp, "[");
print_term(fp, t->farg->argval);
if (proper_list(t) == 0) {
fprintf(fp, "|");
print_term(fp, t->farg->narg->argval);
fprintf(fp, "]");
}
else {
t1 = t->farg->narg->argval;
while (t1->sym_num != Nil_sym_num) {
fprintf(fp, ",");
print_term(fp, t1->farg->argval);
t1 = t1->farg->narg->argval;
}
fprintf(fp, "]");
}
} /* list notation */
else if (t->sym_num == Eq_sym_num && t->varnum != TERM) {
/* (t1 = t2) or (t1 != t2) */
fprintf(fp, "(");
print_term(fp, t->farg->argval);
if (t->occ.lit != NULL && t->occ.lit->sign == 0)
fprintf(fp, " != ");
else
fprintf(fp, " = ");
print_term(fp, t->farg->narg->argval);
fprintf(fp, ")");
}
else if (Flags[BIRD_PRINT].val && is_symbol(t, "a", 2))
bird_print(fp, t);
else if (Flags[BIRD_PRINT].val && is_symbol(t, "j", 2)) {
print_term(fp, t->farg->argval);
fprintf(fp, " + ");
print_term(fp, t->farg->narg->argval);
}
else if (Flags[BIRD_PRINT].val && is_symbol(t, "f", 2)) {
print_term(fp, t->farg->argval);
print_term(fp, t->farg->narg->argval);
}
else if (Flags[BIRD_PRINT].val && is_symbol(t, "g", 1)) {
fprintf(fp, "-(");
print_term(fp, t->farg->argval);
fprintf(fp, ")");
}
else {
fprintf(fp, "%s", sn_to_str(t->sym_num));
fprintf(fp, "(");
r = t->farg;
while(r != NULL) {
print_term(fp, r->argval);
r = r->narg;
if(r != NULL)
fprintf(fp, ",");
}
fprintf(fp, ")");
}
}
} /* print_term */
/*************
*
* str_print_term(string, ip, term) -- Print a term to a string.
*
* Variables 0-5 are printed as x,y,z,u,v,w, and equalities
* and negated equalities are printed in infix.
*
*************/
void str_print_term(str, ip, t)
char *str;
int *ip;
struct term *t;
{
struct rel *r;
struct term *t1;
char *s2;
if (t == NULL) {
str_copy("(nil)", str+*ip);
*ip += 5;
}
else if (t->type == NAME) { /* name */
if (t->sym_num == Nil_sym_num) {
str_copy("[]", str+*ip);
*ip += 2;
}
else {
s2 = sn_to_str(t->sym_num);
str_copy(s2, str+*ip);
*ip += strlen(s2);
}
}
else if (t->type == VARIABLE) /* variable */
str_print_variable(str, ip, t);
else { /* complex */
if (t->sym_num == Cons_sym_num) { /* list notation */
str[(*ip)++] = '[';
str_print_term(str, ip, t->farg->argval);
if (proper_list(t) == 0) {
str[(*ip)++] = '|';
str_print_term(str, ip, t->farg->narg->argval);
str[(*ip)++] = ']';
}
else {
t1 = t->farg->narg->argval;
while (t1->sym_num != Nil_sym_num) {
str[(*ip)++] = ',';
str_print_term(str, ip, t1->farg->argval);
t1 = t1->farg->narg->argval;
}
str[(*ip)++] = ']';
}
} /* list notation */
else if (t->sym_num == Eq_sym_num && t->varnum != TERM) {
/* (t1 = t2) or (t1 != t2) */
str[(*ip)++] = '(';
str_print_term(str, ip, t->farg->argval);
if (t->occ.lit != NULL && t->occ.lit->sign == 0) {
str_copy(" != ", str+*ip);
*ip += 4;
}
else {
str_copy(" = ", str+*ip);
*ip += 3;
}
str_print_term(str, ip, t->farg->narg->argval);
str[(*ip)++] = ')';
}
else if (Flags[BIRD_PRINT].val && is_symbol(t, "a", 2) && 0)
/* bird_print(fp, t) */ ;
else {
s2 = sn_to_str(t->sym_num);
str_copy(s2, str+*ip);
*ip += strlen(s2);
str[(*ip)++] = '(';
r = t->farg;
while(r != NULL) {
str_print_term(str, ip, r->argval);
r = r->narg;
if(r != NULL)
str[(*ip)++] = ',';
}
str[(*ip)++] = ')';
}
}
} /* str_print_term */
/*************
*
* int sprint_term(s, t) -- return length of s.
*
*************/
int sprint_term(s, t)
char *s;
struct term *t;
{
int i;
i = 0;
str_print_term(s, &i, t);
s[i] = '\0';
return(i);
} /* sprint_term */
/*************
*
* p_term(term) -- print_term to the standard output.
*
*************/
void p_term(t)
struct term *t;
{
print_term(Fdout, t);
} /* p_term */
/*************
*
* print_term_nl(fp, term) -- print_term followed by newline
*
*************/
void print_term_nl(fp, t)
FILE *fp;
struct term *t;
{
print_term(fp, t);
fprintf(fp,"\n");
} /* print_term_nl */
/*************
*
* int proper_list(t)
*
*************/
int proper_list(t)
struct term *t;
{
if (t->type == VARIABLE)
return(0);
else if (t->type == NAME)
return(t->sym_num == Nil_sym_num);
else if (t->sym_num != Cons_sym_num)
return(0);
else
return(proper_list(t->farg->narg->argval));
} /* proper_list */
/*************
*
* int str_to_sn(string, arity, sts)
* Return a symbol number for string/arity.
*
* If the given string/arity is already in the global symbol table,
* then return symbol number; else, create a new symbol table entry and
* return a new symbol number
*
* Penguin: it returns TROUBLE/NO_TROUBLE and the symbol number through
* the parameter sts.
*
*************/
int str_to_sn(s, arity, sts)
char *s;
int arity;
int *sts;
{
struct sym_ent *p, *r;
int i;
for (i = 0; i < SYM_TAB_SIZE; i++) {
p = Sym_tab[i];
#ifdef ROO
p = p->next; /* skip dummy node */
#endif
while (p != NULL) {
if (str_ident(s, p->name) == 0)
p = p->next;
else if (p->arity == arity)
{
*sts = p->sym_num;
return(NO_TROUBLE);
}
else if (Flags[CHECK_ARITY].val)
{
*sts = 0;
return(NO_TROUBLE);
}
else
p = p->next;
} /* end of while */
} /* end of for */
if (get_sym_ent(&r) == TROUBLE)
return(TROUBLE);
str_copy(s, r->name);
r->arity = arity;
#ifdef ROO
p4_lock(&(Glob->sym_tab_lock));
r->sym_num = new_sym_num();
i = r->sym_num % SYM_TAB_SIZE;
r->next = Sym_tab[i]->next;
Sym_tab[i]->next = r;
p4_unlock(&(Glob->sym_tab_lock));
#else
r->sym_num = new_sym_num();
i = r->sym_num % SYM_TAB_SIZE;
r->next = Sym_tab[i];
Sym_tab[i] = r;
#endif
*sts = r->sym_num;
return(NO_TROUBLE);
} /* str_to_sn */
/*************
*
* void mark_evaluable_symbols(reading)
* Go through symbol table, checking $ Symbols.
*
* Penguin adds the parameter reading.
*
*************/
void mark_evaluable_symbols(reading)
int reading;
/* reading == 1 if mark_evaluable_symbols() is called by read_all_input(), */
/* reading == 0 if mark_evaluable_symbols() is called by move_messages(): */
/* the call to mark_evaluable_symbols() in read_all_input() is executed by */
/* the Penguins which reads the input, while the call to mark_evaluable_ */
/* symbols() in move_messages() is executed by the Penguins which receive */
/* the input via messages. */
{
struct sym_ent *p;
int i, error;
char *n;
for (i = 0; i < SYM_TAB_SIZE; i++) {
p = Sym_tab[i];
#ifdef ROO
p = p->next; /* skip dummy node */
#endif
while (p != NULL) {
n = p->name;
if (n[0] == '$' && p->sym_num != Cons_sym_num &&
p->sym_num != Nil_sym_num &&
p->sym_num != Eq_sym_num &&
p->sym_num != Ignore_sym_num &&
p->sym_num != Conditional_demodulator_sym_num &&
p->sym_num != Chr_sym_num &&
initial_str("$ANS", n) == 0 &&
initial_str("$Ans", n) == 0 &&
initial_str("$ans", n) == 0 &&
str_ident(n, "$NUCLEUS") == 0 &&
str_ident(n, "$BOTH") == 0 &&
str_ident(n, "$LINK") == 0 &&
str_ident(n, "$SATELLITE") == 0) {
error = 0;
if (str_ident(n, "$SUM"))
p->eval_code = SUM_SYM;
else if (str_ident(n, "$PROD"))
p->eval_code = PROD_SYM;
else if (str_ident(n, "$DIFF"))
p->eval_code = DIFF_SYM;
else if (str_ident(n, "$DIV"))
p->eval_code = DIV_SYM;
else if (str_ident(n, "$MOD"))
p->eval_code = MOD_SYM;
else if (str_ident(n, "$EQ"))
p->eval_code = EQ_SYM;
else if (str_ident(n, "$NE"))
p->eval_code = NE_SYM;
else if (str_ident(n, "$LT"))
p->eval_code = LT_SYM;
else if (str_ident(n, "$LE"))
p->eval_code = LE_SYM;
else if (str_ident(n, "$GT"))
p->eval_code = GT_SYM;
else if (str_ident(n, "$GE"))
p->eval_code = GE_SYM;
else if (str_ident(n, "$AND"))
p->eval_code = AND_SYM;
else if (str_ident(n, "$OR"))
p->eval_code = OR_SYM;
else if (str_ident(n, "$NOT"))
p->eval_code = NOT_SYM;
else if (str_ident(n, "$IF"))
p->eval_code = IF_SYM;
else if (str_ident(n, "$LLT"))
p->eval_code = LLT_SYM;
else if (str_ident(n, "$LLE"))
p->eval_code = LLE_SYM;
else if (str_ident(n, "$LGT"))
p->eval_code = LGT_SYM;
else if (str_ident(n, "$LGE"))
p->eval_code = LGE_SYM;
else if (str_ident(n, "$ID"))
p->eval_code = ID_SYM;
else if (str_ident(n, "$LNE"))
p->eval_code = LNE_SYM;
else if (str_ident(n, "$T"))
p->eval_code = T_SYM;
else if (str_ident(n, "$F"))
p->eval_code = F_SYM;
else if (str_ident(n, "$NEXT_CL_NUM"))
p->eval_code = NEXT_CL_NUM_SYM;
else if (str_ident(n, "$ATOMIC"))
p->eval_code = ATOMIC_SYM;
else if (str_ident(n, "$NUMBER"))
p->eval_code = NUMBER_SYM;
else if (str_ident(n, "$VAR"))
p->eval_code = VAR_SYM;
else if (str_ident(n, "$GROUND"))
p->eval_code = GROUND_SYM;
else if (str_ident(n, "$TRUE"))
p->eval_code = TRUE_SYM;
else if (str_ident(n, "$OUT"))
p->eval_code = OUT_SYM;
else if (str_ident(n, "$BIT_AND"))
p->eval_code = BIT_AND_SYM;
else if (str_ident(n, "$BIT_OR"))
p->eval_code = BIT_OR_SYM;
else if (str_ident(n, "$BIT_XOR"))
p->eval_code = BIT_XOR_SYM;
else if (str_ident(n, "$BIT_NOT"))
p->eval_code = BIT_NOT_SYM;
else if (str_ident(n, "$SHIFT_LEFT"))
p->eval_code = SHIFT_LEFT_SYM;
else if (str_ident(n, "$SHIFT_RIGHT"))
p->eval_code = SHIFT_RIGHT_SYM;
else if (!p->skolem) {
if (reading)
{
Stats[INPUT_ERRORS]++;
fprintf(Fdout,"ERROR, unrecognized $ symbol: %s, arity %d, somewhere in the input.\n",n,p->arity);
}
else /* receiving from Penguin which read the input */
p->skolem = 1;
}
switch (p->eval_code) {
case SUM_SYM:
case PROD_SYM:
case DIFF_SYM:
case DIV_SYM:
case MOD_SYM:
case EQ_SYM:
case NE_SYM:
case LT_SYM:
case LE_SYM:
case GT_SYM:
case GE_SYM:
case AND_SYM:
case LLT_SYM:
case LLE_SYM:
case LGT_SYM:
case LGE_SYM:
case ID_SYM:
case LNE_SYM:
case BIT_AND_SYM:
case BIT_OR_SYM:
case BIT_XOR_SYM:
case SHIFT_LEFT_SYM:
case SHIFT_RIGHT_SYM:
case OR_SYM : error = (p->arity != 2); break;
case TRUE_SYM :
case BIT_NOT_SYM:
case NOT_SYM : error = (p->arity != 1); break;
case IF_SYM : error = (p->arity != 3); break;
case T_SYM :
case F_SYM :
case NEXT_CL_NUM_SYM : error = (p->arity != 0); break;
case ATOMIC_SYM :
case NUMBER_SYM :
case VAR_SYM : error = (p->arity != 1); break;
case GROUND_SYM : error = (p->arity != 1); break;
case OUT_SYM : error = (p->arity != 1); break;
}
if (error) {
Stats[INPUT_ERRORS]++;
fprintf(Fdout,"ERROR, $ symbol: %s, has wrong arity: %d, somewhere in the input.\n", n, p->arity);
}
else if (p->eval_code != 0)
Internal_flags[DOLLAR_PRESENT] = 1;
}
p = p->next;
}
}
} /* mark_evaluable_symbols */
/*************
*
* print_syms(file_ptr) -- Display the symbol list.
*
*************/
void print_syms(fp)
FILE *fp;
{
struct sym_ent *p;
int i;
for (i = 0; i < SYM_TAB_SIZE; i++) {
p = Sym_tab[i];
#ifdef ROO
p = p->next; /* skip dummy node */
#endif
while (p != NULL) {
fprintf(fp, "%d %s/%d, lex_val=%d\n", p->sym_num, p->name, p->arity, p->lex_val);
p = p->next;
}
}
} /* print_syms */
/*************
*
* p_syms()
*
*************/
void p_syms()
{
print_syms(Fdout);
} /* p_syms */
/*************
*
* free_sym_tab() -- free all symbols in the symbol table
*
* Note for ROO: dummy nodes are freed as well.
*
*************/
void free_sym_tab()
{
struct sym_ent *p1, *p2;
int i;
for (i = 0; i < SYM_TAB_SIZE; i++) {
p1 = Sym_tab[i];
while (p1 != NULL) {
p2 = p1;
p1 = p1->next;
free_sym_ent(p2);
}
Sym_tab[i] = NULL;
}
} /* free_sym_tab */
/*************
*
* char *sn_to_str(sym_num) -- given a symbol number, return the name
*
*************/
char *sn_to_str(sym_num)
int sym_num;
{
struct sym_ent *p;
p = Sym_tab[sym_num % SYM_TAB_SIZE];
#ifdef ROO
p = p->next; /* skip dummy node */
#endif
while (p != NULL && p->sym_num != sym_num)
p = p->next;
if (p == NULL)
return("");
else
return(p->name);
} /* sn_to_str */
/*************
*
* int sn_to_arity(sym_num) -- given a symbol number, return the arity
*
*************/
int sn_to_arity(sym_num)
int sym_num;
{
struct sym_ent *p;
p = Sym_tab[sym_num % SYM_TAB_SIZE];
#ifdef ROO
p = p->next; /* skip dummy node */
#endif
while (p != NULL && p->sym_num != sym_num)
p = p->next;
if (p == NULL)
return(-1);
else
return(p->arity);
} /* sn_to_arity */
/*************
*
* int sn_to_ec(sym_num) - given a symbol number, return the evaluation code
*
*************/
int sn_to_ec(sym_num)
int sym_num;
{
struct sym_ent *p;
p = Sym_tab[sym_num % SYM_TAB_SIZE];
#ifdef ROO
p = p->next; /* skip dummy node */
#endif
while (p != NULL && p->sym_num != sym_num)
p = p->next;
if (p == NULL)
return(-1);
else
return(p->eval_code);
} /* sn_to_ec */
/*************
*
* int set_to_predicate(sym_num) Penguin
*
* Given a symbol number, turns its predicate field in Sym_tab on
*
*************/
int set_to_predicate(sym_num)
int sym_num;
{
struct sym_ent *p;
p = Sym_tab[sym_num % SYM_TAB_SIZE];
#ifdef ROO
p = p->next; /* skip dummy node */
#endif
while (p != NULL && p->sym_num != sym_num)
p = p->next;
if (p == NULL)
return(-1);
else
{
p->predicate = 1;
return(1);
}
} /* set_to_predicate */
/*************
*
* int sn_to_node(sym_num)
* Given a symbol number, return the symbol table node
*
*************/
struct sym_ent *sn_to_node(sym_num)
int sym_num;
{
struct sym_ent *p;
p = Sym_tab[sym_num % SYM_TAB_SIZE];
#ifdef ROO
p = p->next; /* skip dummy node */
#endif
while (p != NULL && p->sym_num != sym_num)
p = p->next;
return(p); /* possibly NULL */
} /* sn_to_node */
/*************
*
* int in_sym_tab(s) -- is s in the symbol table?
*
*************/
int in_sym_tab(s)
char *s;
{
struct sym_ent *p;
int i;
for (i = 0; i < SYM_TAB_SIZE; i++) {
p = Sym_tab[i];
#ifdef ROO
p = p->next; /* skip dummy node */
#endif
while (p != NULL) {
if (str_ident(p->name, s))
return(1);
p = p->next;
}
}
return(0);
} /* in_sym_tab */
/*************
*
* int mark_as_skolem(sym_num)
*
* void in Otter, int in Penguin, as it returns TROUBLE/NO_TROUBLE.
*
*************/
int mark_as_skolem(sym_num)
int sym_num;
{
struct sym_ent *se;
se = sn_to_node(sym_num);
if (se == NULL) {
output_stats(Fdout, 4);
fprintf(Fderr, "ABEND, mark_as_skolem, no symbol for %d.\007\n",sym_num);
fprintf(Fdout, "ABEND, mark_as_skolem, no symbol for %d.\n",sym_num);
return(TROUBLE);
}
else
se->skolem = 1;
return(NO_TROUBLE);
} /* mark_as_skolem */
/*************
*
* int is_skolem(sym_num,is)
*
* Penguin: it returns TROUBLE/NO_TROUBLE and 0/1 through the
* parameter is.
*
*************/
int is_skolem(sym_num,is)
int sym_num;
int *is;
{
struct sym_ent *se;
*is = 0; /* default */
se = sn_to_node(sym_num);
if (se == NULL) {
output_stats(Fdout, 4);
fprintf(Fderr, "ABEND, is_skolem, no symbol for %d.\007\n",sym_num);
fprintf(Fdout, "ABEND, is_skolem, no symbol for %d.\n",sym_num);
return(TROUBLE);
}
else
{
*is = se->skolem;
return(NO_TROUBLE);
}
} /* is_skolem */
/*************
*
* str_copy(s, t) -- Copy a string.
*
*************/
void str_copy(s, t)
char *s;
char *t;
{
while (*t++ = *s++);
} /* str_copy */
/*************
*
* int str_ident(s, t) -- Identity of strings
*
*************/
int str_ident(s, t)
char *s;
char *t;
{
for ( ; *s == *t; s++, t++)
if (*s == '\0') return(1);
return(0);
} /* str_ident */
/*************
*
* int initial_str(s, t) -- Is s an initial substring of t?
*
*************/
int initial_str(s, t)
char *s;
char *t;
{
for ( ; *s == *t; s++, t++)
if (*s == '\0') return(1);
return(*s == '\0');
} /* initial_str */
/*************
*
* int read_buf(file_ptr, buffer)
*
* Read characters into buffer until one of the following:
* 1. '.' is reached ('.' goes into the buffer)
* 2. EOF is reached: buf[0] = '\0' (an error occurs if
* any nonwhite space precedes EOF)
* 3. MAX_BUF - 2 characters have been read (an error occurs)
*
* If error occurs, return(0), else return(1).
*
*************/
int read_buf(fp, buf)
FILE *fp;
char buf[];
{
int c, i, j;
i = 0;
c = getc(fp);
while (c != '.' && c != EOF && i < MAX_BUF - 2) {
if (c == '\n' || c == '\t')
c = ' ';
if (c == '%') { /* comment--flush rest of line */
c = getc(fp);
while (c != '\n' && c != EOF)
c = getc(fp);
c = ' ';
}
buf[i++] = c;
c = getc(fp);
}
if (c == '.') {
buf[i++] = '.';
buf[i] = '\0';
return(1);
}
else if (c == EOF) {
j = 0;
buf[i] = '\0';
skip_white(buf, &j);
if (i != j) {
fprintf(Fdout, "ERROR, text after last period: %s\n", buf);
buf[0] = '\0';
return(0);
}
else {
buf[0] = '\0';
return(1);
}
}
else {
buf[i] = '\0';
fprintf(Fdout, "ERROR, input string more than %d characters, increase MAX_BUF : %s\n", MAX_BUF, buf);
/* now flush and discard */
c = getc(fp);
while (c != EOF && c != '.')
c = getc(fp);
return(0);
}
} /* read_buf */
/*************
*
* skip_white(buffer, position)
*
* Advance the buffer to the next nonwhite position.
*
*************/
void skip_white(buf, bufp)
char buf[];
int *bufp;
{
char c;
c = buf[*bufp];
while (c == ' ' || c == '\t' || c == '\n')
c = buf[++(*bufp)];
} /* skip_white */
/*************
*
* int is_delim(c)
*
*************/
int is_delim(c)
char c;
{
return(c == '(' || c == ',' || c == ')' || c == '.' ||
c == '|' ||
c == ' ' || c == '\t' ||
c == '[' || c == ']' ||
c == '\n');
}
/*************
*
* get_word(buffer, position, word)
*
*************/
void get_word(buf, bufp, word)
char buf[];
int *bufp;
char word[];
{
int i;
char c;
i = 0;
skip_white(buf, bufp);
c = buf[*bufp];
while (i < MAX_NAME-1 && is_delim(c) == 0) {
word[i++] = c;
c = buf[++(*bufp)];
}
word[i] = '\0';
if (is_delim(c))
skip_white(buf, bufp);
else {
fprintf(Fdout, "ERROR, word too big, max is %d; ", MAX_NAME-1);
word[0] = '\0';
}
} /* get_word */
/*************
*
* int str_term(buffer, position, st) -- parse buffer and build term
*
* If a syntax error is found, print message and return(NULL).
*
* struct term * in Otter, int in Penguin, as it returns TROUBLE/
* NO_TROUBLE. It returns the pointer to struct term through the
* parameter st.
*
*************/
int str_term(buf, bufp, st)
char buf[];
int *bufp;
struct term **st;
{
struct term *t1, *t2, *t3;
struct rel *r1, *r2;
char word[MAX_NAME];
int i, save_pos;
int tempint;
struct term *tempterm;
*st = NULL; /* default */
get_word(buf, bufp, word);
if (word[0] == '\0') {
if (buf[*bufp] == '[') { /* list notation */
(*bufp)++; /* skip past '[' */
if (buf[(*bufp)] == ']') {
if (get_term(&t1) == TROUBLE)
return(TROUBLE);
t1->type = NAME;
t1->sym_num = Nil_sym_num;
(*bufp)++; /* skip "]" */
skip_white(buf,bufp);
*st = t1;
return(NO_TROUBLE);
}
else {
if (str_term(buf, bufp, &t1) == TROUBLE)
return(TROUBLE);
if (t1 == NULL)
return(NO_TROUBLE);
else {
if (buf[*bufp] == '|') { /* [t1|t2] */
(*bufp)++; /* skip past '|' */
skip_white(buf,bufp);
if (str_term(buf, bufp, &t2) == TROUBLE)
return(TROUBLE);
if (t2 == NULL)
return(NO_TROUBLE);
else if (buf[*bufp] != ']') {
fprintf(Fdout, "ERROR, bad list:\n");
print_error(Fdout, buf, *bufp);
return(NO_TROUBLE);
}
else {
if (get_term(&t3) == TROUBLE)
return(TROUBLE);
if (get_rel(&r1) == TROUBLE)
return(TROUBLE);
if (get_rel(&r2) == TROUBLE)
return(TROUBLE);
t3->farg = r1;
r1->narg = r2;
r1->argval = t1;
r2->argval = t2;
t3->sym_num = Cons_sym_num;
t3->type = COMPLEX;
(*bufp)++; /* skip past ']' */
skip_white(buf, bufp);
*st = t3;
return(NO_TROUBLE);
}
}
else if (buf[*bufp] == ',' || buf[*bufp] == ']')
{ /* [t1,t2,...,tn] */
if (get_term(&t3) == TROUBLE)
return(TROUBLE);
t3->sym_num = Cons_sym_num;
t3->type = COMPLEX;
if (get_rel(&r1) == TROUBLE)
return(TROUBLE);
if (get_rel(&r2) == TROUBLE)
return(TROUBLE);
t3->farg = r1;
r1->narg = r2;
r1->argval = t1;
if (get_term(&t2) == TROUBLE)
return(TROUBLE);
r2->argval = t2;
while (buf[*bufp] == ',') {
(*bufp)++;
if (str_term(buf, bufp, &t1) == TROUBLE)
return(TROUBLE);
if (t1 == NULL)
return(NO_TROUBLE);
else {
t2->type = COMPLEX;
t2->sym_num = Cons_sym_num;
if (get_rel(&r1) == TROUBLE)
return(TROUBLE);
if (get_rel(&r2) == TROUBLE)
return(TROUBLE);
t2->farg = r1;
r1->narg = r2;
r1->argval = t1;
if (get_term(&tempterm) == TROUBLE)
return(TROUBLE);
r2->argval = tempterm;
t2 = r2->argval;
}
}
if (buf[*bufp] != ']') {
fprintf(Fdout, "ERROR, bad list:\n");
print_error(Fdout, buf, *bufp);
return(NO_TROUBLE);
}
else {
t2->type = NAME;
t2->sym_num = Nil_sym_num;
(*bufp)++; /* skip past ']' */
skip_white(buf, bufp);
*st = t3;
return(NO_TROUBLE);
}
}
else {
fprintf(Fdout, "ERROR, bad list:\n");
print_error(Fdout, buf, *bufp);
return(NO_TROUBLE);
}
}
}
} /* list notation */
else {
fprintf(Fdout, "ERROR, bad word:\n");
print_error(Fdout, buf, *bufp);
return(NO_TROUBLE);
}
}
else {
if (get_term(&t1) == TROUBLE)
return(TROUBLE);
if (buf[*bufp] != '(') {
t1->type = NAME; /* decide later if variable */
if (str_to_sn(word, 0, &tempint) == TROUBLE)
return(TROUBLE);
t1->sym_num = tempint;
if (t1->sym_num == 0) {
fprintf(Fdout, "ERROR, multiple arities :%s:\n", word);
print_error(Fdout, buf, *bufp);
return(NO_TROUBLE);
}
else
{
*st = t1;
return(NO_TROUBLE);
}
}
else {
t1->type = COMPLEX;
r1 = NULL;
i = 0; /* count subterms to get arity */
save_pos = *bufp; /* in case of error */
while (buf[*bufp] != ')') {
i++;
(*bufp)++; /* skip past comma or open paren */
if (str_term(buf, bufp, &t2) == TROUBLE)
return(TROUBLE);
if (t2 == NULL)
return(NO_TROUBLE);
else if (buf[*bufp] != ',' && buf[*bufp] != ')') {
fprintf(Fdout, "ERROR, comma or ) expected:\n");
print_error(Fdout, buf, *bufp);
return(NO_TROUBLE);
}
else {
if (get_rel(&r2) == TROUBLE)
return(TROUBLE);
r2->argval = t2;
if (r1 == NULL)
t1->farg = r2;
else
r1->narg = r2;
r1 = r2;
}
}
(*bufp)++; /* skip past close paren */
skip_white(buf, bufp);
if (str_to_sn(word, i, &tempint) == TROUBLE) /* functor */
return(TROUBLE);
t1->sym_num = tempint;
if (t1->sym_num == 0) {
fprintf(Fdout, "ERROR, multiple arities :%s:\n", word);
print_error(Fdout, buf, save_pos);
return(NO_TROUBLE);
}
else
{
*st = t1;
return(NO_TROUBLE);
}
}
}
} /* str_term */
/*************
*
* int str_atom(buf, bufp, signp, sa)
*
* struct term * in Otter, int in Penguin, as it returns TROUBLE/
* NO_TROUBLE. It returns the pointer to struct term through the
* parameter sa.
*
*************/
int str_atom(buf, bufp, signp, sa)
char buf[];
int *bufp;
int *signp;
struct term **sa;
{
struct term *t, *t1, *t2;
struct rel *r1, *r2;
char *s;
int save_pos;
struct term *temp;
*sa = NULL; /* default */
skip_white(buf, bufp);
if (buf[*bufp] != '(') {
*signp = 1;
if (str_term(buf, bufp, &temp) == TROUBLE)
return(TROUBLE);
*sa = temp;
return(NO_TROUBLE);
}
else {
(*bufp)++; /* skip past open paren */
save_pos = *bufp; /* in case of error */
if (str_term(buf, bufp, &t1) == TROUBLE)
return(TROUBLE);
if (t1 == NULL)
return(NO_TROUBLE); /* an error has already been handled */
else {
skip_white(buf, bufp);
if (buf[*bufp] == ')') {
fprintf(Fdout, "ERROR, '=' or '!=' expected:\n");
print_error(Fdout, buf, *bufp);
return(NO_TROUBLE);
}
else {
if (str_term(buf, bufp, &t2) == TROUBLE)
return(TROUBLE);
if (t2 == NULL)
return(NO_TROUBLE);
else {
s = sn_to_str(t2->sym_num);
*signp = -1;
if (str_ident(s, "="))
*signp = 1;
else if (str_ident(s, "!="))
*signp = 0;
if (*signp == -1 || t2->type != NAME) {
fprintf(Fdout, "ERROR, '=' or '!=' expected:\n");
print_error(Fdout, buf, *bufp);
return(NO_TROUBLE);
}
else {
free_term(t2);
if (buf[*bufp] == ')') {
fprintf(Fdout, "ERROR, bad equality:\n");
print_error(Fdout, buf, save_pos);
return(NO_TROUBLE);
}
else {
if (str_term(buf, bufp, &t2) == TROUBLE)
return(TROUBLE);
if (t2 == NULL)
return(NO_TROUBLE);
else if (buf[*bufp] != ')') {
fprintf(Fdout, "ERROR, bad equality:\n");
print_error(Fdout, buf, save_pos);
return(NO_TROUBLE);
}
else {
(*bufp)++; /* skip past ')' */
skip_white(buf, bufp);
if (get_term(&t) == TROUBLE)
return(TROUBLE);
t->type = COMPLEX;
t->sym_num = Eq_sym_num;
if (get_rel(&r1) == TROUBLE)
return(TROUBLE);
if (get_rel(&r2) == TROUBLE)
return(TROUBLE);
t->farg = r1;
r1->narg = r2;
r1->argval = t1;
r2->argval = t2;
*sa = t;
return(NO_TROUBLE);
}
}
}
}
}
}
}
} /* str_atom */
/*************
*
* int set_vars(term)
*
* Decide which of the names are really variables, and make
* into variables. (This routine is used only on input terms.)
* Preserve the user's variable names by keeping the pointer into
* the symbol list.
*
* If too many variabls, return(0); else return(1).
*
*************/
int set_vars(t)
struct term *t;
{
char *varnames[MAX_VARS];
int i;
for (i=0; i<MAX_VARS; i++)
varnames[i] = NULL;
return(set_vars_term(t, varnames));
} /* set_vars */
/*************
*
* int set_vars_term(term, varnames)
*
*************/
int set_vars_term(t, varnames)
struct term *t;
char *varnames[];
{
struct rel *r;
int i, rc;
if (t->type == COMPLEX) {
r = t->farg;
rc = 1;
while (rc && r != NULL) {
rc = set_vars_term(r->argval, varnames);
r = r->narg;
}
return(rc);
}
else if (var_name(sn_to_str(t->sym_num)) == 0)
return(1);
else {
i = 0;
t->type = VARIABLE;
while (i < MAX_VARS && varnames[i] != NULL &&
varnames[i] != sn_to_str(t->sym_num))
i++;
if (i == MAX_VARS)
return(0);
else {
if (varnames[i] == NULL)
varnames[i] = sn_to_str(t->sym_num);
t->varnum = i;
return(1);
/* t->sym_num = 0; include this to destroy input variable names */
}
}
} /* set_vars_term */
/*************
*
* int var_name(string) -- Decide if a string represents a variable.
*
* return("string is a variable")
*
* Modified by Penguin to recognize that the special strings
* HALT, TROUBLE and E_STOP are not variables in
* Prolog style.
*
*************/
int var_name(s)
char *s;
{
if (Flags[PROLOG_STYLE_VARIABLES].val)
{
if ((*s >= 'A' && *s <= 'Z') || *s == '_')
if (str_ident(s,"HALT"))
return(0);
else if (str_ident(s,"TROUBLE"))
return(0);
else if (str_ident(s,"E_STOP"))
return(0);
else return(1);
else return(0);
}
else
return(*s >= 'u' && *s <= 'z');
} /* var_name() */
/*************
*
* int read_term(file_ptr, retcd_ptr, rt) -- Read and return then next term.
*
* It is assumed that the next term in the file is terminated
* with a period. NULL is returned if EOF is reached first.
*
* If an error is found, return(0); else return(1).
*
* struct term * in Otter, int in Penguin, as it returns TROUBLE/
* NO_TROUBLE. It returns the pointer to struct term through the
* parameter rt.
*
*************/
int read_term(fp, rcp, rt)
FILE *fp;
int *rcp;
struct term **rt;
{
char buf[MAX_BUF];
int p, rc;
struct term *t;
*rt = NULL; /* default */
rc = read_buf(fp, buf);
if (rc == 0) { /* error */
*rcp = 0;
*rt = NULL;
return(NO_TROUBLE);
}
else if (buf[0] == '\0') { /* ok. EOF */
*rcp = 1;
*rt = NULL;
return(NO_TROUBLE);
}
else {
p = 0;
if (str_term(buf, &p, &t) == TROUBLE)
return(TROUBLE);
if (t == NULL) {
*rcp = 0;
*rt = NULL;
return(NO_TROUBLE);
}
else {
skip_white(buf, &p);
if (buf[p] != '.') {
fprintf(Fdout, "ERROR, text after term:\n");
print_error(Fdout, buf, p);
*rcp = 0;
*rt = NULL;
return(NO_TROUBLE);
}
else {
if (set_vars(t)) {
*rcp = 1;
*rt = t;
return(NO_TROUBLE);
}
else {
fprintf(Fdout, "ERROR, too many variables, max is %d:\n%s\n",
MAX_VARS, buf);
*rcp = 0;
*rt = NULL;
return(NO_TROUBLE);
}
}
}
}
} /* read_term */
/*************
*
* int read_list(file_ptr, errors_ptr, integrate, rl)
*
* Read and return a list of terms.
*
* The list must be terminated either with the term `end_of_list.'
* or with an actual EOF.
* Set errors_ptr to point to the number of errors found.
*
* struct term_ptr * in Otter, int in Penguin, as it returns TROUBLE/
* NO_TROUBLE. It returns the pointer to struct term_ptr through the
* parameter rl.
*
*************/
int read_list(fp, ep, integrate, rl)
FILE *fp;
int *ep;
int integrate;
struct term_ptr **rl;
{
struct term_ptr *p1, *p2, *p3;
struct term *t;
int rc;
struct term *temp;
*rl = NULL; /* default */
*ep = 0;
p3 = NULL;
p2 = NULL;
if (read_term(fp, &rc, &t) == TROUBLE)
return(TROUBLE);
while (rc == 0) {
(*ep)++;
if (read_term(fp, &rc, &t) == TROUBLE)
return(TROUBLE);
}
/* keep going until t == NULL || t is end marker */
while (t != NULL && (t->type != NAME ||
str_ident(sn_to_str(t->sym_num), "end_of_list") == 0)) {
if (integrate)
{
if (integrate_term(t, &temp) == TROUBLE)
return(TROUBLE);
t = temp;
}
if (get_term_ptr(&p1) == TROUBLE)
return(TROUBLE);
p1->term = t;
if (p2 == NULL)
p3 = p1;
else
p2->next = p1;
p2 = p1;
if (read_term(fp, &rc, &t) == TROUBLE)
return(TROUBLE);
while (rc == 0) {
(*ep)++;
if (read_term(fp, &rc, &t) == TROUBLE)
return(TROUBLE);
}
}
if (t == NULL)
{
*rl = p3;
return(NO_TROUBLE);
}
else {
zap_term(t);
*rl = p3;
return(NO_TROUBLE);
}
} /* read_list */
/*************
*
* print_list(file_ptr, term_ptr) -- Print a list of terms.
*
* The list is printed with periods after each term, and
* the list is terminated with `end_of_list.' so that it can
* be read with read_list.
*
*************/
void print_list(fp, p)
FILE *fp;
struct term_ptr *p;
{
while (p != NULL) {
print_term(fp, p->term); fprintf(fp, ".\n");
p = p->next;
}
fprintf(fp, "end_of_list.\n");
} /* print_list */
/*************
*
* print_error(fp, buf, pos)
*
*************/
void print_error(fp, buf, pos)
FILE *fp;
char buf[];
int pos;
{
int i;
fprintf(fp, "%s\n", buf);
for (i = 0; i < pos; i++)
fprintf(fp, "-");
fprintf(fp, "^\n");
} /* print_error */
/*************
*
* int is_symbol(t, str, arity) -- Does t have leading function symbol str with arity.
*
*************/
int is_symbol(t, str, arity)
struct term *t;
char *str;
int arity;
{
return((t->type == COMPLEX || t->type == NAME) &&
sn_to_arity(t->sym_num) == arity &&
str_ident(sn_to_str(t->sym_num), str));
} /* arity */
/*************
*
* bird_print(fp, t)
*
*************/
void bird_print(fp, t)
FILE *fp;
struct term *t;
{
struct rel *r;
if (t == NULL)
fprintf(fp, "(nil)");
else if (is_symbol(t, "a", 2) == 0) {
/* t is not of the form a(_,_), so print in prefix */
if (t->type == NAME) /* name */
fprintf(fp, "%s", sn_to_str(t->sym_num));
else if (t->type == VARIABLE) /* variable */
print_variable(fp, t);
else { /* complex */
fprintf(fp, "%s", sn_to_str(t->sym_num));
fprintf(fp, "(");
r = t->farg;
while(r != NULL) {
bird_print(fp, r->argval);
r = r->narg;
if(r != NULL)
fprintf(fp, ",");
}
fprintf(fp, ")");
}
}
else { /* t has form a(_,_), so print in bird notation */
if (is_symbol(t->farg->narg->argval, "a", 2)) {
bird_print(fp, t->farg->argval);
fprintf(fp, " (");
bird_print(fp, t->farg->narg->argval);
fprintf(fp, ")");
}
else {
bird_print(fp, t->farg->argval);
fprintf(fp, " ");
bird_print(fp, t->farg->narg->argval);
}
}
} /* bird_print */
/*************
*
* int str_int(string, int_ptr) -- Translate a string to an integer.
*
* String has optional '+' or '-' as first character.
* Return(1) iff success.
*
*************/
int str_int(s, np)
char s[];
int *np;
{
int i, sign, n;
i = 0;
sign = 1;
if (s[0] == '+' || s[0] == '-') {
if (s[0] == '-')
sign = -1;
i = 1;
}
if (s[i] == '\0')
return(0);
else {
n = 0;
for( ; s[i] >= '0' && s[i] <= '9'; i++)
n = n * 10 + s[i] - '0';
*np = n * sign;
return(s[i] == '\0');
}
} /* str_int */
/*************
*
* int str_long(string, long_ptr) -- Translate a string to a long.
*
* String has optional '+' or '-' as first character.
* Return(1) iff success.
*
*************/
int str_long(s, np)
char s[];
long *np;
{
int i, sign;
long n;
i = 0;
sign = 1;
if (s[0] == '+' || s[0] == '-') {
if (s[0] == '-')
sign = -1;
i = 1;
}
if (s[i] == '\0')
return(0);
else {
n = 0;
for( ; s[i] >= '0' && s[i] <= '9'; i++)
n = n * 10 + s[i] - '0';
*np = n * sign;
return(s[i] == '\0');
}
} /* str_long */
/*************
*
* int_str(int, str) -- translate an integer to a string
*
*************/
void int_str(i, s)
int i;
char s[];
{
int j, sign;
if ((sign = i) < 0)
i = -i;
j = 0;
if (i == 0)
s[j++] = '0';
else {
while (i > 0) {
s[j++] = i % 10 + '0';
i = i / 10;
}
}
if (sign < 0)
s[j++] = '-';
s[j] = '\0';
reverse(s);
} /* int_str */
/*************
*
* long_str(int, str) -- translate a long to a string
*
*************/
void long_str(i, s)
long i;
char s[];
{
int j;
long sign;
if ((sign = i) < 0)
i = -i;
j = 0;
if (i == 0)
s[j++] = '0';
else {
while (i > 0) {
s[j++] = i % 10 + '0';
i = i / 10;
}
}
if (sign < 0)
s[j++] = '-';
s[j] = '\0';
reverse(s);
} /* long_str */
/*************
*
* reverse(s) -- reverse a string
*
*************/
void reverse(s)
char s[];
{
int i, j;
char temp;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
} /* reverse */
/*************
*
* cat_str(s1, s2, s3, lim)
*
* Penguin adds the parameter lim and modifies the function to check
* array boundaries.
*
*************/
void cat_str(s1,s2,s3,lim)
char *s1;
char *s2;
char *s3;
int lim;
{
int i, j;
for (i = 0, j = 0; i < lim - 1 && j < lim && s1[j] != '\0'; j++, i++)
s3[i] = s1[j];
for (j = 0; i < lim - 1 && j < lim && s2[j] != '\0'; j++, i++)
s3[i] = s2[j];
s3[i] = '\0';
} /* cat_str */
/*****************
*
* void check_beq_lex_val() Penguin
*
* It checks whether any predicate symbol in the symbol table has
* been given a lex_value different from the default MAX_INT.
* If that is the case, it sets the lex_val of buil-in equality
* Eq_sym_num to the smallest lex_val among the predicates.
* It is called by read_all_input() after having checked that
* Eq_sym_num has not been given a lex_val different from MAX_INT
* by the user.
*
********************/
void check_beq_lex_val()
{
struct sym_ent *p, *beqp;
int i, min_pred_lex_val;
min_pred_lex_val = MAX_INT;
for (i = 0; i < SYM_TAB_SIZE; i++)
{
p = Sym_tab[i];
while (p != NULL)
{
if (p->predicate == 1 && p->lex_val < min_pred_lex_val)
min_pred_lex_val = p->lex_val;
p = p->next;
} /* end of while */
} /* end of for */
if (min_pred_lex_val != MAX_INT)
{
beqp = sn_to_node(Eq_sym_num);
beqp->lex_val = min_pred_lex_val;
for (i = 0; i < SYM_TAB_SIZE; i++)
{
p = Sym_tab[i];
while (p != NULL)
{
if (p->predicate == 1 && p->lex_val < MAX_INT && p != beqp)
p->lex_val++;
/* It increases because equality has been inserted at the bottom of the */
/* precedence among predicates. */
p = p->next;
} /* end of while */
} /* end of for */
} /* end of if */
} /* check_beq_lex_val */
|
C
|
int gcd(int a, int b){
while (b > 0) {
int c = a;
a = b;
b = c % b;
}
return a;
}
bool hasGroupsSizeX(int*deck, int deckSz){
int f[10001] = {0};
for(int z=0;z<deckSz;z++){int d = deck[z];
f[d]++;
}
int g = 0;
for(int z=0; z<10001; z++){int v = f[z];
g = gcd(g, v);
}
return g != 1;
}
|
C
|
#pragma once
#pragma pack(push, 1)
struct RGBColor {
unsigned char blue;
unsigned char green;
unsigned char red;
RGBColor() : blue(0), green(0), red(0) {}
RGBColor(unsigned char red, unsigned char green, unsigned char blue)
: blue(blue), green(green), red(red) {}
};
#pragma pack(pop)
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#define DEVICE_NAME "/dev/debug_driver_device"
int main(int argc, char **argv){
int ret, fd, read_length;
read_length = atoi(argv[2]);
char *message = malloc(sizeof(char)*read_length);
if (argc < 2){
printf("Usage: %s [message to write] [read length]\n",argv[0]);
return -1;
}
fd = open(DEVICE_NAME,O_RDWR);
if (fd < 0){
printf("[debug_driver main] Failed to open device [%s]\n",DEVICE_NAME);
return -1;
}
ret = write(fd,argv[1],strlen(argv[1]));
if (ret < 0){
printf("[debug_driver main] Failed to write to device [%s]\n",DEVICE_NAME);
return -1;
}
ret = read(fd,message,read_length);
if (ret < 0){
printf("[debug_driver main] reading from the device [%s]\n",DEVICE_NAME);
return -1;
}
printf("[debug_driver] read message from device ['%s']\n",message);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* list2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: najlee <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/08 13:41:11 by najlee #+# #+# */
/* Updated: 2021/07/08 13:41:12 by najlee ### ########.fr */
/* */
/* ************************************************************************** */
#include "builtin.h"
int add_list_sort(t_dummy *dummy, char *val)
{
t_list *tmp;
t_list *new_node;
tmp = dummy->head;
while (tmp->right->db != -1
&& m_strncmp(tmp->right->val, val, find_equal(val)) < 0)
tmp = tmp->right;
if (m_strncmp(tmp->right->val, val, find_equal(val)) == 0)
{
if (find_equal(val) != m_strlen(val))
m_strlcpy(tmp->right->val, val, m_strlen(val) + 1);
}
else
{
new_node = new_list(val, 0);
if (!new_node)
return (FALSE);
++dummy->head->db;
new_node->right = tmp->right;
tmp->right->left = new_node;
tmp->right = new_node;
new_node->left = tmp;
}
return (TRUE);
}
char **make_envp(t_dummy *dummy)
{
char **ret;
t_list *cur_node;
int size;
int i;
i = -1;
cur_node = dummy->head->right;
size = dummy->head->db + 1;
ret = malloc(sizeof(char *) * (size + 1));
while (++i < size)
{
ret[i] = m_strdup(cur_node->val);
cur_node = cur_node->right;
}
ret[size] = 0;
return (ret);
}
int search_list(t_dummy *dummy, char *val)
{
t_list *tmp;
tmp = dummy->head->right;
while (tmp->db != -1)
{
if (!m_strncmp(tmp->val, val, find_equal(tmp->val)))
return (TRUE);
tmp = tmp->right;
}
return (FALSE);
}
char *m_find_env_list(t_dummy *dummy, char *val)
{
char *ret;
t_list *tmp;
tmp = dummy->head->right;
while (tmp->db != -1)
{
if (!m_strncmp(tmp->val, val, find_equal(tmp->val)))
{
ret = m_strdup(&tmp->val[find_equal(tmp->val) + 1]);
return (ret);
}
tmp = tmp->right;
}
return (NULL);
}
int delete_list(t_dummy *dummy, char *val)
{
t_list *tmp;
t_list *del_node;
tmp = dummy->head;
while (tmp->right->db != -1)
{
if (m_strncmp(tmp->right->val, val, find_equal(val)) >= 0)
break ;
tmp = tmp->right;
}
if (m_strncmp(tmp->right->val, val, find_equal(val)) == 0)
{
--dummy->head->db;
del_node = tmp->right;
tmp->right = tmp->right->right;
tmp->right->left = tmp;
free(del_node);
del_node = 0;
}
return (TRUE);
}
|
C
|
/*
basic prototype for data definition structual organization and operations on the network datatype
Custom defined datatype with structures which allows us to do the following:
1. have a structure for storing data as well as the node information
2. have a way to add new node with connection which we can define as initialization/declaration or later
3. Have a way bring a full network into the older ones by assigning the head node which might belong to an existing network
4. Way to traverse the network
5. have a way to manage memory upon creation, while growing and upo deletion
6. generate some key network based statistics for the type
** in some ways we are almost going to recreate some sort of of tree like form which might be the purpose then
we are adding on some basic analysis in the term of network typologies and methods which eventually will
help us understand it better.
*/
#include<stdio.h>
/*
Na ---> Nb --> Nb1
--> Nb2
*/
// type definition
typedef struct nodeA{
nodeData data;
int* nodeIdentifier;
} node ;
|
C
|
#include "holberton.h"
/**
* puts_half - prints half of a string
*
* @str: pointer parameter
*
* Return: void
*/
void puts_half(char *str)
{
long length_st;
int second_half = 0;
int second_half2 = 0;
length_st = 0;
while (*(str + length_st) != '\0')
{
length_st++;
}
if (length_st % 2 == 0)
{
second_half = length_st / 2;
while (*(str + second_half) != '\0')
{
_putchar(*(str + second_half));
second_half++;
}
_putchar('\n');
}
else
{
second_half2 = ((length_st - 1) / 2) + 1;
while (*(str + second_half2) != '\0')
{
_putchar(*(str + second_half2));
second_half2++;
}
_putchar('\n');
}
}
|
C
|
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <conio.h>
#define MAX_BUF_SIZE 4000
char Buffer[MAX_BUF_SIZE];
void main(void){
unsigned short port = 5000;
int socket_type = SOCK_STREAM;
struct sockaddr_in server;
int ret,retval=0,temp =0;
const char serverip[] = "192.168.1.5";
unsigned int rd = 0;
WSADATA wsaData;
SOCKET conn_socket;
memset(&server,0,sizeof(server));
server.sin_addr.s_addr=inet_addr(serverip);
server.sin_family = AF_INET;
server.sin_port = htons(port);
if (WSAStartup(0x202,&wsaData) == SOCKET_ERROR){
printf("\nWSAStartup failed with error %d",WSAGetLastError());
WSACleanup();
exit(1);
}
conn_socket = socket(AF_INET,socket_type,0);
if (conn_socket <0 ){
printf("\nClient: Error Opening socket: Error %d\n",WSAGetLastError());
WSACleanup();
exit(1);
}
if (connect(conn_socket,(struct sockaddr*)&server,sizeof(server))== SOCKET_ERROR) {
printf("\nConnect() failed: %d",WSAGetLastError());
WSACleanup();
exit(1);
}
printf("Type x to exit\n");
while(1){
printf("\n:");
gets(Buffer);
if(Buffer[0] == 'x')break;
strcat(Buffer,"\r\n");
retval = send(conn_socket,Buffer,strlen(Buffer),0);
if (retval == SOCKET_ERROR){
fprintf(stderr,"send() failed: error %d\n",WSAGetLastError());
WSACleanup();
exit(1);
}
retval = recv(conn_socket,Buffer,MAX_BUF_SIZE,0);
if (retval == SOCKET_ERROR){
fprintf(stderr,"send() failed: error %d\n",WSAGetLastError());
WSACleanup();
exit(1);
}
Buffer[retval-1]=0;
printf("%d>%s",retval,Buffer);
};//end while 1
closesocket(conn_socket);
}//end main
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
int N, M;
pthread_mutex_t *mutexes;
pthread_barrier_t barrier;
void *f(void *a) {
int j = *((int*)a);
int i;
printf("Thread %d is waiting...\n", j);
pthread_barrier_wait(&barrier);
for (i = 0; i < M; i++) {
pthread_mutex_lock(&mutexes[i]);
printf("Thread %d has entered checkpoint %d\n", j, i);
int n = (random() % 101 + 100) * 1000;
usleep(n);
pthread_mutex_unlock(&mutexes[i]);
}
printf("Thread %d finished\n", j);
return NULL;
}
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Please provide 2 arguments!\n");
exit(1);
}
int *a = malloc(sizeof(int) * N);
N = atoi(argv[1]);
M = atoi(argv[2]);
pthread_t *t = malloc(sizeof(pthread_t) * N);
mutexes = malloc(sizeof(pthread_mutex_t) * M);
if (0 > pthread_barrier_init(&barrier, NULL, N)) {
free(t);
free(mutexes);
exit(1);
}
int i;
for (i = 0; i < M; i++) {
if(0 > pthread_mutex_init(&mutexes[i], NULL)) {
int j;
for(j=0;j<i;j++)
pthread_mutex_destroy(&mutexes[j]);
pthread_barrier_destroy(&barrier);
free(t);
free(mutexes);
exit(1);
}
}
srandom(time(NULL));
for (i = 0; i < N; i++) {
a[i] = i;
if(0 > pthread_create(&t[i], NULL, f, (void *)&a[i])) {
perror("Error on create thread");
//wait_threads(T, i);
//pthread_barrier_destroy(&barrier);
//destroy_mutexes(mutexes, M);
//cleanup(T, args, mutexes);
exit(1);
}
}
for(i=0;i<N;i++)
pthread_join(t[i], NULL);
pthread_barrier_destroy(&barrier);
for(i=0;i<M;i++)
pthread_mutex_destroy(&mutexes[i]);
free(t);
free(mutexes);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
//function to print RGB and alpha of a given 32bit color value
void printEachColor(uint32_t colorInt){
uint8_t Red,Green,Blue,Alpha;
Alpha=(uint8_t)colorInt&255;colorInt>>=8;
Blue=(uint8_t)colorInt&255;colorInt>>=8;
Green=(uint8_t)colorInt&255;colorInt>>=8;
Red=(uint8_t)colorInt&255;
printf("Red: %u\nGreen: %u\nBlue: %u\nAlpha: %u\n",Red,Green,Blue,Alpha);
}
//function to synthesize a 32bit color value from RGB and alpha
uint32_t getColor(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha){
uint32_t color=0;
color +=red;//add color red
color<<=8;//shift to left 8 bits
color +=green;//add color green
color<<=8;
color +=blue;//add color blue
color<<=8;
color +=alpha;//add alpha
return color;
}
int main() {
//initialize color values for testing
uint8_t red=25, green=100, blue=50, alpha=255;
uint32_t colorInt;
//synthesizing the color value from RGB values
colorInt=getColor(red,green,blue,alpha);
puts("Color created from RGB values");
//Performing the reverse operation
//extracting and printing RGB values of the color
printEachColor(colorInt);
return 0;
}
|
C
|
// RUN: %clang_cc1 -fsyntax-only -verify %s
#if !__has_extension(pragma_clang_attribute_namespaces)
#error
#endif
#pragma clang attribute MyNamespace.push (__attribute__((annotate)), apply_to=function) // expected-error 2 {{'annotate' attribute}}
int some_func(); // expected-note{{when applied to this declaration}}
#pragma clang attribute pop // expected-error{{'#pragma clang attribute pop' with no matching '#pragma clang attribute push'}}
#pragma clang attribute NotMyNamespace.pop // expected-error{{'#pragma clang attribute NotMyNamespace.pop' with no matching '#pragma clang attribute NotMyNamespace.push'}}
#pragma clang attribute MyOtherNamespace.push (__attribute__((annotate)), apply_to=function) // expected-error 2 {{'annotate' attribute}}
int some_other_func(); // expected-note 2 {{when applied to this declaration}}
// Out of order!
#pragma clang attribute MyNamespace.pop
int some_other_other_func(); // expected-note 1 {{when applied to this declaration}}
#pragma clang attribute MyOtherNamespace.pop
#pragma clang attribute Misc. () // expected-error{{namespace can only apply to 'push' or 'pop' directives}} expected-note {{omit the namespace to add attributes to the most-recently pushed attribute group}}
#pragma clang attribute Misc push // expected-error{{expected '.' after pragma attribute namespace 'Misc'}}
// Test how pushes with namespaces interact with pushes without namespaces.
#pragma clang attribute Merp.push (__attribute__((annotate)), apply_to=function) // expected-error{{'annotate' attribute}}
#pragma clang attribute push (__attribute__((annotate)), apply_to=function) // expected-warning {{unused attribute}}
#pragma clang attribute pop // expected-note{{ends here}}
int test(); // expected-note{{when applied to this declaration}}
#pragma clang attribute Merp.pop
#pragma clang attribute push (__attribute__((annotate)), apply_to=function) // expected-warning {{unused attribute}}
#pragma clang attribute Merp.push (__attribute__((annotate)), apply_to=function) // expected-error{{'annotate' attribute}}
#pragma clang attribute pop // expected-note{{ends here}}
int test2(); // expected-note{{when applied to this declaration}}
#pragma clang attribute Merp.pop
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
pid_t pid;
int mypipefd[2];
int ret;
char buf[20];
ret = pipe(mypipefd);
if(ret==-1){
perror("pipe");
exit(1);
}
pid = fork();
if(pid==0){
/*chiled process*/
printf("child process \n");
write(mypipefd[1],"Hello there!",12);
}
else{
/*parent process*/
printf("parent process \n");
read(mypipefd[0],buf,15);
printf("buf: %s\n", buf);
}
return 0;
}
|
C
|
// ڷκ Է¹ 2 Ͽ
#pragma warning (disable : 4996)
#include <stdio.h>
int main(void) {
//
int x, y, sum;
// ϳ Է¹ x
printf("ù° ڸ ԷϽÿ:");
scanf("%d", &x);
// ϳ Է¹ y
printf("ι° ڸ ԷϽÿ:");
scanf("%d", &y);
//
sum = x + y;
printf(" : %d", sum);
return 0;
}
|
C
|
unsigned char degerler[5]= {0};
void dht_start(){
output_float(PIN_A0);
restart_wdt();
delay_ms(1000);
}
unsigned char get_byte(){
unsigned char s = 0;
unsigned char value = 0;
for(s = 0; s < 8; s += 1)
{
value <<= 1;
restart_wdt();
while(!input(PIN_A0));
restart_wdt();
delay_us(30);
if(input(PIN_A0))
{
value |= 1;
}
while(input(PIN_A0));
}
return value;
}
unsigned char take_data(){
short chk = 0;
unsigned char s = 0;
output_high(PIN_A0);
output_low(PIN_A0);
delay_ms(18);
output_high(PIN_A0);
delay_us(26);
chk = input(PIN_A0);
if(chk)
{
return 1;
}
restart_wdt();
delay_us(80);
chk = input(PIN_A0);
if(!chk)
{
return 2;
}
delay_us(80);
restart_wdt();
for(s = 0; s <= 4; s += 1)
{
degerler[s] = get_byte();
}
output_high(PIN_A0);
}
unsigned char check_sum(){
unsigned char sum = 0;
for(int i=0; i<=3; i++){
sum += degerler[i];
}
if(sum == degerler[4]){
return 1;}
else{
return 0;}
}
|
C
|
#include "mymath.h"
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
void v3d_set(v3d *v, double x, double y, double z) {
assert(v != NULL);
v->x = x;
v->y = y;
v->z = z;
}
void v3d_minus(v3d *a, v3d *b, v3d *res) {
assert(a != NULL);
assert(b != NULL);
assert(res != NULL);
res->x = a->x - b->x; res->y = a->y - b->y;
res->z = a->z - b->z;
}
double v3d_length(v3d *v) {
assert(v != NULL);
return sqrt(
(v->x * v->x) +
(v->y * v->y) +
(v->z * v->z));
}
void v3d_copy(v3d *res, v3d *a) {
assert(res != NULL);
assert(a != NULL);
v3d_set(res, a->x, a->y, a->z);
}
void v3d_cross(v3d *a, v3d *b, v3d *res) {
#ifdef DEBUG
assert(a != NULL);
assert(b != NULL);
assert(res != NULL);
#endif
res->x = a->y * b->z - a->z * b->y;
res->y = a->z * b->x - a->x * b->z;
res->z = a->x * b->y - a->y * b->x;
}
void v3d_print(v3d *v) {
assert(v != NULL);
printf("(%lf, %lf, %lf)", v->x, v->y, v->z);
}
double v3d_dot(v3d *a, v3d *b) {
#ifdef DEBUG
assert(a != NULL);
assert(b != NULL);
#endif
return (
a->x * b->x +
a->y * b->y +
a->z * b->z);
}
void v3d_normalize(v3d *a) {
double mod;
assert(a != NULL);
mod = v3d_length(a);
assert(fabs(mod) >= 1e-10);
a->x /= mod;
a->y /= mod;
a->z /= mod;
}
|
C
|
/*
* example.c - readline example
*/
#include "readline.h"
void example () {
int fp;
int l;
char buf [255];
fp = open ("pipe", O_RDONLY);
l = readline(fp, buf, 244);
printf("read\n\t %s\n", buf);
close(fp);
return;
}
int main(int argc, char **argv)
{
example();
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int i, limit, sum = 0, x, c = 0, time_quantum;
int wait_time = 0, tat = 0, a_time[10], b_time[10], temp[10];
float average_wait_time, average_tat;
printf("Enter Total Number of Processes:");
scanf("%d", &limit);
x = limit;
for(i = 0; i < limit; i++)
{
printf("\nEnter Details of Process[%d]\n", i + 1);
printf("Arrival Time:");
scanf("%d", &a_time[i]);
printf("Burst Time:");
scanf("%d", &b_time[i]);
temp[i] = b_time[i];
}
printf("\nEnter Time Quantum:");
scanf("%d", &time_quantum);
printf("\nProcess ID\t\tBurst Time\t Turnaround Time\t Waiting Time");
for(sum = 0, i = 0; x != 0;)
{
if(temp[i] <= time_quantum && temp[i] > 0)
{
sum = sum + temp[i];
temp[i] = 0;
c = 1;
}
else if(temp[i] > 0)
{
temp[i] = temp[i] - time_quantum;
sum = sum + time_quantum;
}
if(temp[i] == 0 && c == 1)
{
x--;
printf("\nProcess[%d]\t\t%d\t\t %d\t\t\t %d", i + 1, b_time[i], sum - a_time[i], sum - a_time[i] - b_time[i]);
wait_time = wait_time + sum - a_time[i] - b_time[i];
tat = tat + sum - a_time[i];
c = 0;
}
if(i == limit - 1)
{
i = 0;
}
else if(a_time[i + 1] <= sum)
{
i++;
}
else
{
i = 0;
}
}
average_wait_time = wait_time * 1.0 / limit;
average_tat = tat * 1.0 / limit;
printf("\nAverage Waiting Time:%f", average_wait_time);
printf("\nAvg Turnaround Time:%f", average_tat);
return 0;
}
|
C
|
/* Game Tentang Agmal dan Iraj */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SISOP B10
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
int WakeUp_Status=0;
int Spirit_Status=100;
int p_agmal=0, p_iraj=0; // inisialisasi nilai awal
int flag=0;
int count_WakeUp=0;
int count_Spirit=0;
void *kegiatan_agmal (void *argv);
void *kegiatan_iraj (void *argv);
void *WakeUp_Agmal (void *argv);
void *Spirit_Iraj (void *argv);
int main(){
pthread_t tid[4];
pthread_create(&(tid[0]),NULL,kegiatan_agmal,NULL);
pthread_create(&(tid[1]),NULL,kegiatan_iraj,NULL);
while(flag==0) {
char perintah[50];
gets(perintah);
if (strcmp(perintah,"All Status") == 0) {
printf("Agmal WakeUp_Status = %d\n", WakeUp_Status);
printf("Iraj Spirit_Status = %d\n", Spirit_Status);
}
else if (strcmp(perintah, "Agmal Ayo Bangun") == 0){
if(p_agmal == 1) printf("Fitur Agmal Ayo Bangun disabled 10s\n");
else {
pthread_create(&(tid[2]), NULL, WakeUp_Agmal, NULL);
pthread_join(tid[2], NULL); // memastikan thread selesai mengubah flag, karena main dan thread jalan sendiri2
}
}
else if (strcmp(perintah,"Iraj Ayo Tidur")==0){
if(p_iraj == 1) printf("Fitur Iraj Ayo Tidur disabled 10s\n");
else {
pthread_create(&(tid[3]), NULL, Spirit_Iraj, NULL);
pthread_join(tid[3], NULL); // memastikan thread selesai mengubah flag, karena main dan thread jalan sendiri2
}
}
}
printf("Selesai!\n");
return 0;
}
void *kegiatan_agmal (void *argv) {
while(1){
if(count_Spirit == 3){
p_agmal=1;
sleep(10);
p_agmal=0;
count_Spirit=0;
}
}
}
void *kegiatan_iraj (void *argv) {
while(1){
if(count_WakeUp == 3){
p_iraj=1;
sleep(10);
p_iraj=0;
count_WakeUp=0;
}
}
}
void *WakeUp_Agmal (void *argv) {
WakeUp_Status+=15;
count_WakeUp++;
if(WakeUp_Status >= 100){
printf("Agmal Terbangun, mereka bangun pagi dan berolahraga\n\n");
flag=1;
}
}
void *Spirit_Iraj (void *argv) {
Spirit_Status-=20;
count_Spirit++;
if(Spirit_Status <= 0){
printf("Iraj ikut tidur, dan bangun kesiangan bersama Agmal\n\n");
flag=1;
}
}
/* SISOP B10 */
|
C
|
#include<stdio.h>
int main()
{
int n;
int num[100];
int l;
int desnum[100],k;
int i,j,temp;
printf("Enter the total number of marks to be entered: ");
scanf("%d",&n);
for(l=0;l<n;l++)
{
printf("Enter the marks of student %d: ", l+1);
scanf("%d",&num[l]);
}
for(k=0;k<n;k++)
desnum[k] = num[k];
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(desnum[i] < desnum[j])
{
temp= desnum[i];
desnum[i] = desnum[j];
desnum[j] = temp;
}
}
}
for(i=0;i<n;i++)
printf("\n Number at [%d] is %d", i, desnum[i]);
return 0;
}
|
C
|
#ifndef ENTERED_HERE
#define ENTERED_HERE
#pragma once
#include "expDefines.h"
#define MAXIMCHAR 28
struct Num
{
int leftOE;
int rightOE;
};
struct Modul
{
int poz;
int dest;
};
extern CString Valide;
extern Modul m_moduli[101];
//search the character c within the string str. if str=valide, it searches whether the character is number,
//operator, etc.
inline int SearchGroup(const CString& str, WCHAR c)
{
for (int i=0; i<str.GetLength(); i++)
if (str[i]==c)
{
if (i>=0 && i<=5) return SHGROUP_OPERATOR;//for valide: operators
if (i>=6 && i<=14) return SHGROUP_PARANTHESIS;//for valide: paranthesis
if (i==15) return SHGROUP_COMMA;//for valide: comma (,)
if (i==16) return SHGROUP_EQUAL;//for valide: equal
if (i>=17 && i<=27) return SHGROUP_NUMBER;//for valide: number (including ".")
if (i==28) return SHGROUP_SPACE; //space (" ")
}
return SHGROUP_NOGROUP;//unknowngroup
}
//searches the character in the string, from the position From until To and returns the position where
//it was found; -1 if not found
// int Search(const CString&, char, int From = 0, int To = MAXIMCHAR);//26=MAXCHAR
inline int Search(const CString& str, WCHAR c, int From = 0, int To = MAXIMCHAR)
{
if (From>To) return -1;
for (int i=From; i<=To; i++)
if (str[i]==c) return i;
return -1;
}
//checks to see if str is a constant/function/modulo or 0 if other
// int FoundFunction(const CString& str);
inline int FoundFunction(const CString& str)
{
if (!str.CompareNoCase(L"E")) return 1;
else
if (!str.CompareNoCase(L"PI")) return 2;
else
if (!str.CompareNoCase(L"RAD")) return 10;
else
if (!str.CompareNoCase(L"LOG")) return 11;
else
if (!str.CompareNoCase(L"LN")) return 12;
else
if (!str.CompareNoCase(L"LG")) return 13;
else
if (!str.CompareNoCase(L"CMMDC")) return 20;
else
if (!str.CompareNoCase(L"CMMMC")) return 21;
else
if (!str.CompareNoCase(L"MIN")) return 30;
else
if (!str.CompareNoCase(L"MAX")) return 31;
else
if (!str.CompareNoCase(L"P")) return 40;
else
if (!str.CompareNoCase(L"A")) return 41;
else
if (!str.CompareNoCase(L"C")) return 42;
else
if (!str.CompareNoCase(L"MOD")) return 50;
else return 0;
}
//gets the substring from the string, between positions x and y
// CString GetFunction(const CString& m_strExpression, int x, int y);
inline CString GetFunction(const CString& m_strExpression, int x, int y)
{
CString str;
if (x<0 || y>m_strExpression.GetLength()-1) return _T("");
for (int i=x; i<=y; i++) str+=m_strExpression[i];
return str;
}
//gets the number of module paranthesis and finds the position of each.
// int GetNrM(const CString& m_strExpression, int From, int To);
inline int GetNrM(const CString& m_strExpression, int From, int To)
{
int nrM = 0;
for (int i=From; i<=To; i++) if (m_strExpression[i]=='|')
{
nrM++;
m_moduli[nrM].poz = i;
}
return nrM;
}
//gets the name NAME_ of the element starting at the position from in the string, and returns its margins
// int GetName(const CString& m_strExpression, int From, int& left, int& right);
inline int GetName(const CString& m_strExpression, int From, int &left, int &right)
{
if (From<0 || From>m_strExpression.GetLength()-1)
{
left = -1;
right = -1;
return NAME_ERROR;//0;
}
int x = SearchGroup(Valide, m_strExpression[From]);
int y = Search(Valide, m_strExpression[From]);
//Numar
if (x==SHGROUP_NUMBER)
{
left = From;
while (x==SHGROUP_NUMBER)
{
From++;
x = SearchGroup(Valide, m_strExpression[From]);
}
right = --From;
return NAME_NUMBER;//1;
}
//Functie
if (x==SHGROUP_NOGROUP)
{
left = From;
while (x==SHGROUP_NOGROUP)
{
From++;
x = SearchGroup(Valide, m_strExpression[From]);
}
right = --From;
return NAME_FUNCTION;//3;
}
left = right = From;
if (x==SHGROUP_OPERATOR) return NAME_OPERATOR;//4;
if (x==SHGROUP_PARANTHESIS) return NAME_PARANTHESIS;//2;
if (x==SHGROUP_EQUAL) return NAME_EQUAL;//5;
return NAME_ERROR;
}
//gets the CHARTYPE_ of the char
// int GetCharType(char c);
inline int GetCharType(WCHAR c)
{
if (c=='+' || c=='-') return CHARTYPE_ADDITION;//1;
if (c=='*' || c=='/' || c=='^') return CHARTYPE_MULTIPLICATION;//2;
if (c=='!') return CHARTYPE_FACTORIAL;//3;
if (c=='(' || c=='[' || c=='{' || c=='<' || c=='|') return CHARTYPE_OPENEDPARANTHESIS;//4;
if (c==')' || c==']' || c=='}' || c=='>') return CHARTYPE_CLOSEDPARANTHESIS;//5;
if (c==',') return CHARTYPE_COMMA;//7;
if (c=='=') return CHARTYPE_EQUAL;//8;
if (c==' ') return CHARTYPE_SPACE;//10;
if (SearchGroup(Valide, c)==SHGROUP_NUMBER) return CHARTYPE_NUMBER;//9;
return CHARTYPE_OTHER;//0;
}
//checks if the expression that begins from the character From, within the string, is a function
// BOOL IsFunction(const CString& m_strExpression, int From);
inline BOOL IsFunction(const CString& m_strExpression, int From)
{
int left, right, x;
GetName(m_strExpression, From, left, right);
x = FoundFunction(GetFunction(m_strExpression, left, right));
if (x>9 && x<50) return TRUE;
return FALSE;
}
//checks if the character starting from the position From is an operator
// BOOL IsOperator(const CString& m_strExpression, int From);
inline BOOL IsOperator(const CString& m_strExpression, int From)
{
if (SearchGroup(Valide, m_strExpression[From])==1)
return TRUE;
int left, right;
GetName(m_strExpression, From, left, right);
if (FoundFunction(GetFunction(m_strExpression, left, right))==50) return TRUE;
return FALSE;
}
//
// int GetBkName(const CString& m_strExpression, int End, int &left, int &right);
inline int GetBkName(const CString& m_strExpression, int End, int &left, int &right)
{
if (End<0 || End>m_strExpression.GetLength()-1)
{
left = -1;
right = -1;
return NAME_ERROR;
}
int x = SearchGroup(Valide, m_strExpression[End]);
int y = Search(Valide, m_strExpression[End]);
//Numar
if (x==SHGROUP_NUMBER)
{
right = End;
while (x==SHGROUP_NUMBER && End>=0)
{
End--;
if (End>=0) x = SearchGroup(Valide, m_strExpression[End]);
}
left = ++End;
return NAME_NUMBER;//1
}
//Functie
if (x==SHGROUP_NOGROUP)
{
right = End;
while (x==SHGROUP_NOGROUP && End>=0)
{
End--;
if (End>=0) x = SearchGroup(Valide, m_strExpression[End]);
}
left = ++End;
return NAME_FUNCTION;//3;
}
left = right = End;
if (x==SHGROUP_OPERATOR) return NAME_OPERATOR;//4;
if (x==SHGROUP_PARANTHESIS) return NAME_PARANTHESIS;//2;
if (x==SHGROUP_EQUAL) return NAME_EQUAL;//5;
return NAME_ERROR;//0;
}
inline int GetNrNrs(CString& m_strExpression, int From, int To)
{
int nr(0), left, right;
if (From<0 || From>m_strExpression.GetLength()-1 || From>To)
return 0;
while (From<=To)
{
int Name = GetName(m_strExpression, From, left, right);
int func = FoundFunction(GetFunction(m_strExpression, left, right));
if (Name ==1 || Name ==3 && func<9 && func>0)
{
nr++;
From= right+1;
}
else From++;
}
return nr;
}
inline BOOL GetNextNumber(const CString& m_strExpression, int From, BOOL Forward, double &nr)
{
if (From<0 || From>m_strExpression.GetLength()-1)
{
nr = 0;
return FALSE;
}
int x, left, right, poz(From);
BOOL neg(FALSE);
if (Forward) //* 543
{
if (m_strExpression[From]==' ') poz++;
if (GetCharType(m_strExpression[From])==CHARTYPE_OPENEDPARANTHESIS) //lg[-10]=...
{
poz++;
if (m_strExpression[From+1]=='+') poz++;
else if (m_strExpression[From+1]=='-')
{
poz++;
neg = TRUE;
}
}
else
if ((m_strExpression[poz]=='-' || m_strExpression[poz]=='+') /*&&
(poz==0 || GetCharType(m_strExpression[poz-1])==4 || m_strExpression[poz-1]==','))*/)
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
{
if (m_strExpression[poz]=='-') neg = TRUE;
poz++;
}
x = GetName(m_strExpression, poz, left, right);
if (x==1) nr =_wtof(GetFunction(m_strExpression, left, right));
else if (x==3)
{
x = FoundFunction(GetFunction(m_strExpression, left, right));
if (x==1) nr = M_E;
else if (x==2) nr = M_PI;
else return FALSE;
}
else return FALSE;
}
else
{
if (m_strExpression[From]==' ') poz--;
if (m_strExpression[From]==')') poz--;
x = GetBkName(m_strExpression, poz, left, right);
if (x==1) nr = _wtof(GetFunction(m_strExpression, left, right));
else if (x==3)
{
x = FoundFunction(GetFunction(m_strExpression, left, right));
if (x==1) nr = M_E;
else if (x==2) nr = M_PI;
else return FALSE;
}
else return FALSE;
if (left-1>=0 && m_strExpression[left-1]=='-' && (left-2>=0 && m_strExpression[left-2]=='(' || left-1==0)) neg = TRUE;
}
if (neg) nr = -nr;
return TRUE;
}
#endif
|
C
|
#include <stdio.h>
#include <string.h>
#define NEW_NULL '\0'
#define LENGTH 100
// Declarar las funciones
char *new_strncpy(char *string, char *stringt, int n);
char *new_strncat(char *string, char *stringt, int n);
int new_strncmp(char *string, char *stringt, int n);
int main()
{
// Declarar cadenas de caracteres
char string1[LENGTH] = "Hola";
char string2[LENGTH] = "Hola";
char stringt[LENGTH] = "programaresmipasionxd";
// Copiar los primeros 3 caracteres de string1 a stringt
new_strncpy(string1, stringt, 3);
printf("Resultado de la copia: %s\n", string1);
// Concatenar 4 caracteres de stringt en string1
new_strncat(string2, stringt, 4);
printf("Resultado de la concatenación: %s\n", string2);
// Comparar los primeros 4 caracteres de string1 y string
printf("Resultado de la comparación: %d\n", new_strncmp(string1, string2, 1));
}
/*
Copiar máximo n caracteres del stringt a string
Regresa un apuntador al string
*/
char *new_strncpy(char *string, char *stringt, int n)
{
// Copiar cada elemento de stringt en string
for (int i = 0; i < n; i += 1)
{
*string++ = *stringt++;
}
// Verificar si stringt sea menor que n
if (strlen(stringt) < n)
{
while (1)
{
// Eliminar los caracteres que sobrepasen a n
if (!(*string++ = NEW_NULL))
{
break;
}
}
}
return string;
}
/*
Concatena máximo n caracteres de stringt a string
Regresa un apuntador al string
*/
char *new_strncat(char *string, char *stringt, int n)
{
// Ir al final de string
while (*string)
{
string += 1;
}
// Copiar stringt en string con la función ya creada
return new_strncpy(string, stringt, n);
}
/*
Compara máximo n caracteres de string y stringt
Regresa -1 si hay una diferencia
Regresa 0 si son iguales
*/
int new_strncmp(char *string, char *stringt, int n)
{
// Comparar los caracteres en un rango n
for (int i = 0; i < n; i += 1)
{
// Verificar que los caracteres sean iguales
if (*string != *stringt)
{
return -1;
}
string += 1;
stringt += 1;
}
return 0;
}
|
C
|
#include "codegen.h"
#include "parser.h"
#include "ast.h"
#include "lexer.h"
// functions to add, remove, modify entries in code table and
// to write codetable to MIPS output file
static void generate_table_start(FILE *out); //hard code start part
static void print_table_row(FILE *out, table_row *table_row);//print each row of the table
static void print_table(FILE *out);
static void destroy_table_row(table_row *table);
static char *reg_strings[] = { "$t0","$t1","$t2","$t3","$t4","$t5","$t6","$t7",
"$t8","$t9","$s0","$s1","$s2","$s3","$s4","arg_start","$a0","$a1","$a2","$a3","$v0",
"$v1","$ra","$0","endreg"};
static char *instr_strings[] = { "add","sub","mult","div",
"mflo","mfhi","addi","move","li","la","lw","sw","syscall","j","jal","jr","beq","bne",
"blt","bgt","ble","bge","slt" };
void add_row(table_row *row) {
table[table_count] = row;
table_count++;
}
void generate_from_codetable(FILE *out) {
generate_table_start(out);
print_table(out);
}
void destroy_table() {
int i;
for (i = 0; i < table_count; i++) {
destroy_table_row(table[i]);
}
}
static void destroy_table_row(table_row *table_row) {
if (table_row != NULL) {
free(table_row);
}
}
static void generate_table_start(FILE *out) {
fprintf(out, "%*s\n", ALIGN_WIDTH, ".data");
fprintf(out, "_newline_:%*s", ALIGN_WIDTH, ".ascii \" \\n\" \n");
fprintf(out, "%*s\n",ALIGN_WIDTH,".align 2");
fprintf(out, "%*s\n", ALIGN_WIDTH, ".text");
fprintf(out, "%s: \n", "main");
}
static void print_table(FILE *out) {
int i;
for (i = 0; i < table_count; i++) {
if (table[i] != NULL) {
print_table_row(out, table[i]);
}
}
}
static void print_table_row(FILE *out, table_row *row) {
if(row -> instruction != NIL){
char *instr = instr_strings[row->instruction - INSTRUCTION_START -1];
fprintf(out, "%*s", -ALIGN_WIDTH / 3, instr);
}
if (row -> r0 != NIL) {
if (row->r0 >= STARTREG && row->r0 <= ENDREG) {
char *r0_string = reg_strings[row->r0 - STARTREG - 1];
fprintf(out, "%s", r0_string);
}
else {
fprintf(out, "%d", row->r0);
}
}
if (row->r1 != NIL) {
if (row->r1 >= STARTREG && row->r1 <= ENDREG) {
char *r1_string = reg_strings[row->r1 - STARTREG - 1];
fprintf(out, ",%s", r1_string);
}
else {
fprintf(out, ",%d", row->r1);
}
}
if (row->r2 != NIL) {
if (row->r2 >= STARTREG && row->r2 <= ENDREG) {
char *r2_string = reg_strings[row->r2 - STARTREG - 1];
fprintf(out, ",%s", r2_string);
}
else {
fprintf(out, ",%d", row->r2);
}
}
if (row->label[0] != '\0') {
if (row->instruction == NIL && row->r0 == NIL && row->r1 == NIL &&
row->r2 == NIL) {
fprintf(out, "\n%s:", row->label);
}
else if (row->instruction != NIL && row->r0 == NIL && row->r1 == NIL
&&row->r2 == NIL) {
fprintf(out, "%s", row->label);
}
else {
fprintf(out, ",%s", row->label);
}
}
fprintf(out, "\n");
}
|
C
|
/*=========================================================================
* ode78_cr3bp.c mex file to generate
* a Runge-Kutta 7/8 integrator of the CR3BP vector field.
*
* author: BLB
* year: 2015
* version: 1.0
*=======================================================================*/
//-------------------------------------------------------------------------
// Headers
//-------------------------------------------------------------------------
//Mex
#include "mex.h"
//Custom
#include "C/ode78.h"
//-------------------------------------------------------------------------
// The gateway function.
// The input must bet, in that order:
// 1. [t0, tf] the time span
// 2. double y0[6 or 42], the initial state
// 3. double mu, the cr3bp mass ratio
//-------------------------------------------------------------------------
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
//---------------------------------------------------------------------
// Check for proper number of arguments
//---------------------------------------------------------------------
if(nrhs!=3) {
mexErrMsgIdAndTxt("custom:ode78_cr3bp:nrhs","3 inputs required.");
}
if(!(nlhs == 2 || nlhs == 4)) {
mexErrMsgIdAndTxt("custom:ode78_cr3bp:nlhs",
"2 or 4 outputs required: 2 if only the final state is desired, 4 if the state on a given time grid is also desired.");
}
//---------------------------------------------------------------------
// Retrieve the variables:
// 1. [t0, tf] the time span
// 2. double y0[6 or 42], the initial state
// 3. double mu, the cr3bp mass ratio
//---------------------------------------------------------------------
double *ts = mxGetPr(prhs[0]);
int nts = mxGetN(prhs[0]);
double *y0 = mxGetPr(prhs[1]);
int nvar = mxGetN(prhs[1]);
int mvar = mxGetM(prhs[1]);
double mu = mxGetScalar(prhs[2]);
//---------------------------------------------------------------------
// Set the size of the state as the max(nvar, mvar);
//---------------------------------------------------------------------
nvar = nvar > mvar? nvar:mvar;
//---------------------------------------------------------------------
// Do some checks on the inputs
//---------------------------------------------------------------------
if(nts!=2) {
mexErrMsgIdAndTxt("custom:ode78_bcp:nts","The time vector (first input) must be of size 2: [t0 tf]");
}
if(nvar!=6 && nvar!=42)
{
mexErrMsgIdAndTxt("custom:ode78_bcp:nts","The state vector (second input) must be of size either 6 or 42.");
}
//---------------------------------------------------------------------
// Build the times
//---------------------------------------------------------------------
double t0 = ts[0];
double tf = ts[1];
//---------------------------------------------------------------------
// Integration, for 2 outputs
//---------------------------------------------------------------------
double **yv, *tv, t, y[nvar];
int nGrid = 1000, nV;
if(nlhs == 2)
{
ode78_cr3bp(&t, y, y0, t0, tf, nvar, &mu);
}
else if(nlhs == 4)
{
//-----------------------------------------------------------------
// Integration, for 4 outputs
//-----------------------------------------------------------------
do{
//-------------------------------------------------------------
// State will be stored on a given grid, if necessary
//-------------------------------------------------------------
//Event states
yv = (double **) calloc(nvar, sizeof(double*));
for(int n = 0; n < nvar; n++) yv[n] = (double*) calloc(nGrid+1, sizeof(double));
//Event time
tv = (double*) calloc(nGrid+1, sizeof(double));
//-------------------------------------------------------------
// Integration
//-------------------------------------------------------------
nV = ode78_cr3bp_vec_var(&t, y, tv, yv, nGrid, y0, t0, tf, nvar, &mu);
//-------------------------------------------------------------
// Check that the grid is not overflowed
//-------------------------------------------------------------
if(nV < nGrid)
{
nGrid = nV;
break;
}
else
{
free(tv);
for (int i=0; i<=nvar; i++) free(yv[i]); free(yv);
nGrid *= 2;
}
}while(nGrid < 5e6);
}
if(nGrid >= 5e6)
{
mexErrMsgIdAndTxt("custom:ode78_cr3bp_events:maxCapacity","Maximum capacity reached. Try with a smaller integration time.");
}
//Old version with fixed grid
//if(nlhs == 4) ode78_cr3bp_vec(&t, y, tv, yv, nGrid, y0, t0, tf, nvar, &mu);
//---------------------------------------------------------------------
// Output: the final state
//---------------------------------------------------------------------
//Create the output matrices
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL); //t
plhs[1] = mxCreateDoubleMatrix(1, nvar, mxREAL); //y
//Get a pointer to the real data in the output
double *tout = mxGetPr(plhs[0]);
double *yout = mxGetPr(plhs[1]);
//Store the final state
for(int i = 0; i < nvar; i++) yout[i] = y[i];
tout[0] = t;
//---------------------------------------------------------------------
// Output: the state on a time grid, if necessary
//---------------------------------------------------------------------
if(nlhs == 4)
{
//Create the output matrices
plhs[2] = mxCreateDoubleMatrix(nGrid+1, 1, mxREAL); //tv
plhs[3] = mxCreateDoubleMatrix(nGrid+1, nvar, mxREAL); //yv
//Get a pointer to the real data in the output
double *tvout = mxGetPr(plhs[2]);
double *yvout = mxGetPr(plhs[3]);
//Store the state on the grid [0,..., nGrid]
int indix = 0;
for(int i = 0; i < nvar; i++)
{
for(int k = 0; k <= nGrid; k++)
{
yvout[indix++] = yv[i][k];
}
}
for(int k = 0; k <= nGrid; k++) tvout[k] = tv[k];
}
//---------------------------------------------------------------------
// Free memory
//---------------------------------------------------------------------
if(nlhs == 4)
{
free(tv);
for (int i=0; i<=nvar; i++) free(yv[i]); free(yv);
}
}
|
C
|
#include<stdio.h>
#define MONTHS 12
#define YEARS 5
void qb(int a,int b,float ar[a][b]);
void bf(float ar2[][MONTHS],int a);
int main(void)
{
float rain[YEARS][MONTHS]={
{4.3,4.3,4.3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6},
{8.5,8.2,1.2,1.6,2.4,0.0,5.2,0.9,0.3,0.9,1.4,7.3},
{9.1,8.5,6.7,4.3,2.1,0.8,0.2,0.2,1.1,2.3,6.1,8.4},
{7.2,9.9,8.4,3.3,1.2,0.8,0.4,0.0,0.6,1.7,4.3,6.2},
{7.6,5.6,3.8,2.8,3.8,0.2,0.0,0.0,0.0,1.3,2.6,5.2}
};
printf(" YEAR RAINFALL(inches)\n");
qb(YEARS,MONTHS,rain);
printf("MONTHLY AVERAGES:\n\n");
bf(rain,YEARS);
return 0;
}
void qb(int a,int b,float ar[a][b])
{
float subtot;
float total=0;
int m,n;
for(m=0;m<a;m++){
subtot=0;
for(n=0;n<b;n++)
subtot+=ar[m][n];
printf("%5d %15.1f\n",2000+m,subtot);
total+=subtot;
}
printf("\nThe yearly average is %.1f inches.\n\n",total/a);
}
void bf(float ar2[][MONTHS],int a)
{
float total;
int m,n;
printf("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec\n");
for(m=0;m<MONTHS;m++){
for(n=0,total=0;n<a;n++)
total+=ar2[n][m];
printf("%.1f ",total/a);
}
putchar('\n');
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void cesar_cifrado(char cipher[], int shift);
void cesar_descifrado(char cipher[], int shift);
int main () {
char *buffer;
size_t bufsize = 256;
size_t n;
buffer = (char *)malloc(bufsize * sizeof(char));
if( buffer == NULL)
{
perror("ERROR: no se puede asignar memoria");
exit(1);
}
char cipher[50];
int shift;
printf("Texto a cifrar (solo mayusculas): ");
//scanf("%s", cipher);
n=getline(&buffer,&bufsize,stdin);
buffer[n-1]='\0';
printf("Usted digito: %s\nEn total %d caracteres \n",buffer,n);
strcpy(cipher,buffer);
printf("Ingresar el corrimiento: ");
scanf("%d", &shift);
cesar_cifrado(cipher, shift);
cesar_descifrado(cipher, shift);
return 0;
}
void cesar_cifrado(char cipher[], int shift)
{
for(int i=0; cipher[i] != '\0'; i++)
cipher[i] = 65 + (cipher[i]-65+shift)%26;
printf("Texto cifrado: %s\n", cipher);
}
void cesar_descifrado(char cipher[], int shift) {
for(int i=0; cipher[i] != '\0'; i++)
cipher[i] = 65 + (cipher[i]-65-shift)%26;
printf("Texto descifrado: %s\n", cipher);
}
|
C
|
//Pesquisa e Classificação de Dados - Atividade Semi-Presencial 03 - 21/05/18
// Jiovana Sousa Gomes - [email protected]
//
#include <stdio.h>
#include <stdlib.h>
#include "aluno.h"
int main() {
Lista *lst = criarLista();
int opt;
do{
printf("Escolha opcao:\n0- Sair\n1-\n2- Inserir Aluno\n3- Inserir Entradas Aleatorias\n4- Excluir Aluno\n5- Busca Sequencial\n6- Busca Binaria\n7- Imprimir\n");
scanf("%d", &opt);
switch (opt){
case 2:;
lst = inserirLista(lst);
break;
case 3:
inserirRandom(lst);
break;
case 4:
lst = excluirAluno(lst);
break;
case 5:
buscaSequencial(lst);
break;
case 6:
buscaBinaria(lst,0,lst->qtd);
break;
case 7:
imprimirLista(lst);
break;
case 0:
liberarMem(lst);
}
}while (opt!=0);
return 0;
}
|
C
|
/*
Astrid Moore (Bruce Maxwell)
Fall 2014
Example of a 3D scene model
Draws a city with 3 different kinds of buildings
*/
#include "graphics.h"
#include <time.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
// initialize fields
const int rows = 500*2;
const int cols = 550*2;
Lighting *light;
Image *src;
Module *b;
Module *city, *terrain;
View3D view;
Matrix vtm, gtm;
DrawState *ds;
srand(time(NULL));
char command[256];
float alpha;
// set up color palette
Color Grey = {{0.5, 0.5, 0.5}};
Color ltGrey = {{0.7, 0.7, 0.7}};
Color blueGrey = {{29/255.0, 30/255.0, 25/255.0}};
Color brown = {{72/255.0, 57/255.0, 42/255.0}};
Color wBrown = {{50/255.0, 31/255.0, 12/255.0}};
Color sandyBrown = {{87/255.0, 68/255.0, 44/255.0}};
Color ltBrown = {{147/255.0, 106/255.0, 57/255.0}};
city = module_create();
terrain = module_create();
// grab command line argument to determine viewpoint
// and set up the view structure
if( argc > 1 ) {
alpha = atof( argv[1] );
if( alpha < 0.0 || alpha > 1.0 )
alpha = 0.0;
point_set3D( &(view.vrp), 120*alpha, 80*alpha, -80*alpha - (1.0-cos(alpha)*80) );
} else {
point_set3D( &(view.vrp), 40, 0, -110 );
}
// set up the view
vector_set( &(view.vpn), -view.vrp.val[0], -view.vrp.val[1],
-view.vrp.val[2] );
vector_set( &(view.vup), 0, 1, 0 );
view.d = 5;
view.du = 6;
view.f = 1;
view.b = 200;
view.screenx = cols;
view.screeny = rows;
printf("set up view\n");
matrix_setView3D( &vtm, &view );
matrix_identity( >m );
// buildings
b = module_create();
module_scale( b, 4, 20, 4);
module_translate( b, -60, 18, 15);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube(b, 1);
module_module(city, b);
b = module_create();
module_scale( b, 7, 2, 3);
module_translate( b, -60, 0, -5);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube(b, 1);
module_module(city, b);
b = module_create();
module_scale( b, 5, 15, 5);
module_translate( b, -60, 12.5, 30);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube( b, 1 );
module_module(city, b);
b = module_create();
module_scale( b, 7, 10, 5);
module_translate( b, -40, 7.5, 5);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube(b, 1);
module_module(city, b);
b = module_create();
module_scale( b, 5, 20, 7);
module_translate( b, -40, 16.5, 30);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube(b, 1);
module_module(city, b);
b = module_create();
module_scale( b, 5, 25, 7);
module_translate( b, -20, 21, 15);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube(b, 1);
module_module(city, b);
b = module_create();
module_scale( b, 5, 20, 7);
module_translate( b, -20, 16, -5);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube(b, 1);
module_module(city, b);
b = module_create();
module_scale( b, 5, 30, 7);
module_translate( b, -20, 26.5, 30);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube(b, 1);
module_module(city, b);
b = module_create();
module_scale( b, 5, 30, 7);
module_translate( b, 0, 26.5, 15);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube(b, 1);
module_module(city, b);
b = module_create();
module_scale( b, 2, 3, 2);
module_translate( b, 0, 0, -7.5);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube(b, 1);
module_module(city, b);
b = module_create();
module_scale( b, 2, 3, 2);
module_translate( b, 0, 0, 0);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube(b, 1);
module_module(city, b);
b = module_create();
module_scale( b, 4, 20, 4);
module_translate( b, 0, 18, 30);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube(b, 1);
module_module(city, b);
b = module_create();
module_scale( b, 5, 15, 6);
module_translate( b, 20, 12, 30);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube(b, 1);
module_module(city, b);
b = module_create();
module_scale( b, 5, 15, 5);
module_translate( b, 20, 12.5, 15);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube( b, 1);
module_module(city, b);
b = module_create();
module_scale( b, 7, 2, 3);
module_translate( b, 20, 0, 0);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube(b, 1);
module_module(city, b);
b = module_create();
module_scale( b, 7, 2, 3);
module_translate( b, 40, 0, 0);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube(b, 1);
module_module(city, b);
b = module_create();
module_scale( b, 4, 5, 6);
module_translate( b, 40, 2, 15);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube(b, 1);
module_module(city, b);
b = module_create();
module_scale( b, 7, 10, 5);
module_translate( b, 40, 7.5, 30);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube(b, 1);
module_module(city, b);
b = module_create();
module_scale( b, 2, 5, 2);
module_translate( b, 60, 4, 30);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube(b, 1);
module_module(city, b);
b = module_create();
module_scale( b, 8, 4, 3);
module_translate( b, 60, 2.5, 10);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube(b, 1);
module_module(city, b);
b = module_create();
module_scale( b, 7, 2, 3);
module_translate( b, 70, 0, 0);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube(b, 1);
module_module(city, b);
b = module_create();
module_scale( b, 7, 10, 5);
module_translate( b, 70, 7.5, 20);
module_bodyColor(b, &Grey);
module_surfaceColor(b, <Grey);
module_cube(b, 1);
module_module(city, b);
// so our city isn't floating in space...
// keep ground matt for contrast by withholding surface color
b = module_create();
module_scale(b, 77, 1, 26);
module_translate(b, 0, -2.5, 13);
module_bodyColor(b, &blueGrey);
module_cube(b, 1);
module_module(terrain, b);
b = module_create();
module_scale(b, 77, 1.5, 26);
module_translate(b, 0, -6, 13);
module_bodyColor(b, &brown);
module_cube(b, 1);
module_module(terrain, b);
b = module_create();
module_scale(b, 77, 2, 26);
module_translate(b, 0, -10, 13);
module_bodyColor(b, &wBrown);
module_cube(b, 1);
module_module(terrain, b);
b = module_create();
module_scale(b, 77, 0.5, 26);
module_translate(b, 0, -13, 13);
module_bodyColor(b, <Brown);
module_cube(b, 1);
module_module(terrain, b);
b = module_create();
module_scale(b, 77, 1, 26);
module_translate(b, 0, -15, 13);
module_bodyColor(b, &sandyBrown);
module_cube(b, 1);
module_module(terrain, b);
// create the image and drawstate
src = image_create( rows, cols );
ds = drawstate_create();
printf("created the image and drawstate\n");
// make sure the light source is the same as the viewer
point_copy(&(ds->viewer), &(view.vrp));
ds->shade = ShadeGouraud;
// make two lights: point for contrast, ambient for general brightness
light = lighting_create();
light->light[0].type = LightPoint;
light->light[1].type = LightAmbient;
light->light[0].position.val[0] = view.vrp.val[0];
light->light[0].position.val[1] = view.vrp.val[1];
light->light[0].position.val[2] = view.vrp.val[2];
light->light[1].position.val[0] = view.vrp.val[0];
light->light[1].position.val[1] = view.vrp.val[1];
light->light[1].position.val[2] = view.vrp.val[2];
light->light[0].color.c[0] = 1;
light->light[0].color.c[1] = 1;
light->light[0].color.c[2] = 1;
light->light[1].color.c[0] = 1;
light->light[1].color.c[1] = 1;
light->light[1].color.c[2] = 1;
light->nLights = 2;
// draw scene
module_draw(terrain, &vtm, >m, ds, light, src);
module_draw(city, &vtm, >m, ds, light, src );
printf("drew the scene\n");
// write out the scene
printf("Writing image\n");
image_write( src, "city.ppm" );
sprintf(command, "convert -scale %03dx%03d city.ppm city.ppm", cols/2, rows/2);
system(command);
// free the modules
module_delete( city );
module_delete( terrain );
printf("modules freed\n");
// free drawstate
free(ds);
printf("drawstate freed\n");
// free image
image_free( src );
printf("image freed\n");
return(0);
}
|
C
|
#include "../include/skip_segment.h"
void skip_segment(uint32_t *cpt, FILE *movie)
{
uint16_t size = read_block_size(cpt,movie);
skip_size(size-2,cpt,movie);
uint8_t oct = read_byte(cpt,movie);
assert(oct == 0xff);
}
/*
void skip_segment(uint32_t *cpt, FILE *movie)
{
uint32_t oct = read_byte(cpt,movie);
while (oct != 0xff) {
oct = read_byte(cpt,movie);
}
assert(oct == 0xff);
}
*/
/*
void skip_segment(FILE *movie)
{
uint32_t cpt = 0;
uint32_t oct = read_byte(&cpt,movie);
while (oct != 0xff) {
oct = read_byte(&cpt,movie);
}
}
*/
|
C
|
/*
问题1:实现pow(int x, int y) ,即x的y次方
x的y次方就是有y个x连续乘机,代码如下:
*/
#include <stdio.h>
#include <stdlib.h>
int my_pow(int x,int y){
if(x==0) return 0;
int ret=x,i=1;
for(;i<y;i++){
ret=ret*x;
printf("y=%d;ret=%d\n",i+1,ret);
}
return ret;
}
int main(){
int tmp = my_pow(2,10);
printf("====%d\n",tmp);
return 0;
}
/*
结果
复制代码
[root@admin Desktop]# ./a.out
y=2;ret=4
y=3;ret=8
y=4;ret=16
y=5;ret=32
y=6;ret=64
y=7;ret=128
y=8;ret=256
y=9;ret=512
y=10;ret=1024
====1024
[root@admin Desktop]#
复制代码
改进:
1.我们发现上面的方法,如果y=100,则乘法计算要进行100次,复杂度较高;
2.我们能否利用上次的计算结果,来简化计算?
比如2^4,用2*2*2*2=4*2*2=8*2=16;
上式中共进行了三次乘法;
把所有重复计算剔除:2^4=2^2*2^2=4*4=16,该过程共计算两次乘法2^2,4*4;
乘法次数由3次降为2次;
3.幂运算往往容易越界,比如int最大能表示2147483647,如果算出结果超出这个范围就出错了。
1.对越界做判断和检查;
2.用合适的数据类型表示结果,貌似C里最大的整形数应该是long double;
以下通过递归方式实现以上思想:
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
long double fun(long double x,long double y)
{
printf("ret is x=%Lf ; y=%Lf\n",x,y);//long double输出用%Lf
assert(x != 0 && y >= 0);
if(0 == y) return 1;
if(1 == y) return x;
if(2 == y) return x*x;
long double tmp = 0;
if(y/2 != 0) tmp = x*fun(x,y-1);
else tmp = fun(x*x,y/2);
if(tmp>0){ //如果越界可能出现负数,至于如何更合理判断越界情况,现在还没想好
printf("TMP > 0 IS: %Lf\n",tmp);
return tmp;
}
else{
printf("TMP < 0 IS: %Lf\n",tmp);
return 0;
}
}
int main(){
long double ret = fun(10,30);
printf("result = %Lf\n",ret);
return 0;
}
/*
看看洋气的输出结果:
复制代码
[root@admin Desktop]# ./a.out
ret is x=10.000000 ; y=30.000000
ret is x=10.000000 ; y=29.000000
ret is x=10.000000 ; y=28.000000
ret is x=10.000000 ; y=27.000000
ret is x=10.000000 ; y=26.000000
ret is x=10.000000 ; y=25.000000
ret is x=10.000000 ; y=24.000000
ret is x=10.000000 ; y=23.000000
ret is x=10.000000 ; y=22.000000
ret is x=10.000000 ; y=21.000000
ret is x=10.000000 ; y=20.000000
ret is x=10.000000 ; y=19.000000
ret is x=10.000000 ; y=18.000000
ret is x=10.000000 ; y=17.000000
ret is x=10.000000 ; y=16.000000
ret is x=10.000000 ; y=15.000000
ret is x=10.000000 ; y=14.000000
ret is x=10.000000 ; y=13.000000
ret is x=10.000000 ; y=12.000000
ret is x=10.000000 ; y=11.000000
ret is x=10.000000 ; y=10.000000
ret is x=10.000000 ; y=9.000000
ret is x=10.000000 ; y=8.000000
ret is x=10.000000 ; y=7.000000
ret is x=10.000000 ; y=6.000000
ret is x=10.000000 ; y=5.000000
ret is x=10.000000 ; y=4.000000
ret is x=10.000000 ; y=3.000000
ret is x=10.000000 ; y=2.000000
TMP > 0 IS: 1000.000000
TMP > 0 IS: 10000.000000
TMP > 0 IS: 100000.000000
TMP > 0 IS: 1000000.000000
TMP > 0 IS: 10000000.000000
TMP > 0 IS: 100000000.000000
TMP > 0 IS: 1000000000.000000
TMP > 0 IS: 10000000000.000000
TMP > 0 IS: 100000000000.000000
TMP > 0 IS: 1000000000000.000000
TMP > 0 IS: 10000000000000.000000
TMP > 0 IS: 100000000000000.000000
TMP > 0 IS: 1000000000000000.000000
TMP > 0 IS: 10000000000000000.000000
TMP > 0 IS: 100000000000000000.000000
TMP > 0 IS: 1000000000000000000.000000
TMP > 0 IS: 10000000000000000000.000000
TMP > 0 IS: 100000000000000000000.000000
TMP > 0 IS: 1000000000000000000000.000000
TMP > 0 IS: 10000000000000000000000.000000
TMP > 0 IS: 100000000000000000000000.000000
TMP > 0 IS: 1000000000000000000000000.000000
TMP > 0 IS: 10000000000000000000000000.000000
TMP > 0 IS: 100000000000000000000000000.000000
TMP > 0 IS: 1000000000000000000000000000.000000
TMP > 0 IS: 9999999999999999999731564544.000000
TMP > 0 IS: 99999999999999999997315645440.000000
TMP > 0 IS: 999999999999999999955976585216.000000
result = 999999999999999999955976585216.000000
[root@admin Desktop]#
复制代码
显然后面的结果不对,但是没有出现负数的情况。疑惑,烦请高人指点一二。
*/
|
C
|
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
pthread_mutex_t lock;
int j;
//Funktio jonka kukin thread suorittaa funktion parametrina thread saa pakattavan tiedoston nimen.
void *do_process(void* file)
{
char *filename = file;
FILE *fp = fopen(filename, "r");
if(fp==NULL){
printf("pzip: cannot open file\n");
exit(1);
}
//Luodaa kaksi dynaamista listaa, joihin tallennetaan pakattavien merkkien toistomäärät ja itse merkit
int* intList;
char* charList;
intList = malloc(sizeof(int));
charList = malloc(sizeof(char));
if (intList == NULL || charList == NULL) {
printf("Memory allocation failed");
exit(1);
}
int position = 0;
char curCh, preCh;
int count = 1;
preCh = getc(fp);
//Käytetään my-zipin pakkauslogiikkaa ja tallennetaan tulokset listoihin.
while((curCh = getc(fp)) != EOF)
{
if(preCh == curCh) {
count = count + 1;
}
else {
intList = realloc(intList, sizeof(int) * (position + 1));
charList = realloc(charList, sizeof(char)* (position + 1));
if (intList == NULL || charList == NULL) {
printf("Memory allocation failed");
exit(1);
}
intList[position] = count;
charList[position] = preCh;
position = position + 1;
count = 1;
}
preCh = curCh;
}
//Lukitaan thread sen ajaksi, kun pakattu lopputulos tulostetaan stdout:iin
pthread_mutex_lock(&lock);
for(int i = 0; i < position; i++){
fwrite(&intList[i], sizeof(int), 1, stdout);
fwrite(&charList[i], sizeof(char), 1, stdout);
}
fclose(fp);
free(intList);
free(charList);
pthread_mutex_unlock(&lock);
return NULL;
}
//Luodaan oma thread jokaiselle parametrina annetulle tiedostolle
int main(int argc, char *argv[])
{
if (pthread_mutex_init(&lock, NULL) != 0)
{
printf("Mutex initialization failed.\n");
return 1;
}
for(int i = 1; i < argc; i++){
pthread_t thread;
pthread_create(&thread, NULL, do_process, argv[i]);
pthread_join(thread, NULL);
}
return 0;
}
//Lähteet:
//https://dev.to/quantumsheep/basics-of-multithreading-in-c-4pam
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char** argv[]){
int i,x,fat, flag = 0;
while (flag == 0){
printf ("Insira o numero: ");
scanf("%d", &x);
system("cls");
if (x<0){
}else{
printf ("\n%d! => ", x);
i=1;
fat = 1;
while (i<=x){
fat = fat*(x-i+1);
printf("%d ", (x-i+1));
i++;
}
flag =1;
}
}
printf("= %d", fat);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* put_t_x.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: okherson <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/04/11 09:39:07 by okherson #+# #+# */
/* Updated: 2019/04/19 12:25:35 by okherson ### ########.fr */
/* */
/* ************************************************************************** */
#include "../ft_printf.h"
static char *add_pref(char *sn)
{
int len;
char *fr;
int n;
int m;
n = 2;
m = 0;
len = ft_strlen(sn);
fr = malloc((len + 3) * sizeof(char));
fr[0] = '0';
fr[1] = 'x';
while (sn[m])
{
fr[n] = sn[m];
n++;
m++;
}
fr[n] = '\0';
return (fr);
}
static void put_t_x_3(t_t *t, char *sn)
{
int l;
l = 0;
if (t->f.type == 'X')
while (sn[l])
{
if ((sn[l] >= 'a' && sn[l] <= 'f') || sn[l] == 'x')
sn[l] = sn[l] - 32;
l++;
}
add_str_to_b(t, sn);
}
static void put_t_x_2(t_t *t, long long int num, char *sn, char *fr)
{
int flag_pref;
flag_pref = 0;
if (t->f.grill == 1 && num != 0 && ((t->f.o != 1) || (t->f.accuracy != 0)))
{
fr = sn;
sn = add_pref(sn);
ft_strdel(&fr);
flag_pref = 1;
}
if (t->f.width > (int)ft_strlen(sn))
{
fr = sn;
sn = add_w_x(t, sn, flag_pref);
ft_strdel(&fr);
}
if (t->f.grill == 1 && num != 0 && t->f.o == 1 && flag_pref != 1)
{
fr = sn;
sn = add_pref(sn);
ft_strdel(&fr);
}
put_t_x_3(t, sn);
}
void put_t_x(t_t *t, long long int num)
{
char *fr;
char *sn;
sn = ft_itoa_base(num, 16);
if (t->f.accuracy < 0 && num == 0 && t->f.width == 0)
{
fr = sn;
sn = ft_strdup("");
ft_strdel(&fr);
}
if (t->f.accuracy > (int)ft_strlen(sn))
{
fr = sn;
sn = put_accuracy(t, sn);
ft_strdel(&fr);
}
put_t_x_2(t, num, sn, fr);
}
|
C
|
/*
Test that the proper error is triggered when we initialize
a global with another non-const global's rvalue.
Using gcc_jit_global_set_initializer_rvalue()
*/
#include <stdlib.h>
#include <stdio.h>
#include "libgccjit.h"
#include "harness.h"
void
create_code (gcc_jit_context *ctxt, void *user_data)
{
gcc_jit_type *int_type = gcc_jit_context_get_type (ctxt,
GCC_JIT_TYPE_INT);
gcc_jit_lvalue *foo;
{ /* int bar; */
foo = gcc_jit_context_new_global (
ctxt, NULL,
GCC_JIT_GLOBAL_EXPORTED,
int_type,
"global_lvalueinit_int1");
gcc_jit_rvalue *rval = gcc_jit_context_new_rvalue_from_int (
ctxt, int_type, 3);
gcc_jit_global_set_initializer_rvalue (foo,
rval);
}
{ /* int foo = bar; */
gcc_jit_lvalue *bar = gcc_jit_context_new_global (
ctxt, NULL,
GCC_JIT_GLOBAL_EXPORTED,
int_type,
"global_lvalueinit_int2");
gcc_jit_global_set_initializer_rvalue (bar,
gcc_jit_lvalue_as_rvalue (foo));
}
}
void
verify_code (gcc_jit_context *ctxt, gcc_jit_result *result)
{
/* Ensure that the bad API usage prevents the API giving a bogus
result back. */
CHECK_VALUE (result, NULL);
/* Verify that the correct error message was emitted. */
CHECK_STRING_VALUE (gcc_jit_context_get_first_error (ctxt),
"unable to convert initial value for the global variable"
" global_lvalueinit_int2 to a compile-time constant");
CHECK_STRING_VALUE (gcc_jit_context_get_last_error (ctxt),
"unable to convert initial value for the global variable"
" global_lvalueinit_int2 to a compile-time constant");
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
int findPeakElement(int* nums, int numsSize) {
int start = 1;
if(numsSize == 1){
return 0;
}else if(numsSize == 2){
if(nums[0]>nums[1]){
return 0;
}else{
return 1;
}
}
else{
if(nums[0]>nums[1]){
return 0;
}else if(nums[numsSize-1] > nums[numsSize-2]){
return numsSize-1;
}else{
for(start = 1;start <= numsSize -2;start++){
if(nums[start]>nums[start-1] && nums[start]>nums[start+1]){
return start;
}
}
}
}
return -INT_MIN;
}
int main(){
int num[7] = {1,2,1,3,5,6,4};
printf("we have found that index %d \n",findPeakElement(num,7));
}
|
C
|
#include<stdio.h>
#include<string.h>
int isnum(char str[32])
{
int l,i,flag=0;
l=strlen(str);
for(i=0;i<=l;i++)
{
if((str[i]>='A'&&str[i]<='Z')||(str[i]>='a'&&str[i]<='z'))
{
return 0;
flag=1;
}
}
if(flag==0)
{
return 1;
}
}
int main()
{
char str[10][32]={"a","b","32","a2","b4"},res[10][32];
int i,j=0;
for(i=0;i<=4;i++)
{
if(!isnum(str[i]))
{
strcpy(res[j],str[i]);
j++;
}
}
for(i=0;i<j;i++)
{
printf("\n%s",res[i]);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char S1[10050];
char S2[10050];
char ans[10050];
int main(){
int t,i,n,j;
char tmp;
int carry=0;
int sum;
scanf("%d",&t);
for(i=0;i<t;i++){
scanf("%d",&n);
tmp=getchar();
for(j=0;j<n;j++){
tmp=getchar();
S1[j]=tmp;
}
tmp=getchar();
for(j=0;j<n;j++){
tmp=getchar();
S2[j]=tmp;
}
carry=0;
for(j=n-1;j>=0;j--){
sum=carry+(int)S1[j]+(int)S2[j]-(((int)'0')*2);
//printf("yayayay %d\n",sum);
if(sum>=2){
sum=sum-2;
carry=1;
ans[j]=(char)(sum+((int)'0'));
}else{
ans[j]=(char)(sum+((int)'0'));
carry=0;
}
}
ans[n]='\0';
printf("%s\n",ans);
}
return 0;
}
|
C
|
//
// File: config.h
// Description: This file contains configurations that a user
// can change, such as colors for objects, number of mines, etc.
// After making changes, it is necessary to recompile the program.
//
#ifndef CONFIG_H
#define CONFIG_H
#include <SFML/Graphics.hpp>
//
// Base Color configurations
//
const sf::Color COLOR_GREY = sf::Color(150, 150, 150);
const sf::Color COLOR_RED = sf::Color(250, 0, 0);
const sf::Color COLOR_BLACK = sf::Color( 30, 30, 30);
const sf::Color COLOR_SILVER = sf::Color( 70, 70, 70);
const sf::Color COLOR_LGHT_SLVR = sf::Color(230, 230, 230);
const sf::Color COLOR_LGT_BLUE = sf::Color(100, 100, 255);
const sf::Color COLOR_BLUE = sf::Color( 50, 50, 255);
//
// Objects' color configurations
//
const sf::Color CELL_COLOR = COLOR_GREY;
const sf::Color FLAG_COLOR = COLOR_RED;
const sf::Color BOMB_COLOR = COLOR_BLACK;
const sf::Color BGRND_COLOR = COLOR_BLACK;
const sf::Color COLOR_CLR_RCTNGL = COLOR_SILVER;
//
// Sizes and dimensions
//
const float CELL_WIDTH = 30.0f;
const float CELL_HEIGHT = 30.0f;
const float CELL_SPACING = 5.0f;
const int CELL_RADIUS = 15;
const int BOMB_RADIUS = 15;
const int NUM_ROWS = 15;
const int NUM_COLS = 15;
//
// Game Performance
//
const int GAME_FRAMERATE = 60;
const int GAME_CELLTOMINERATIO = 10;
#endif // CONFIG_H
|
C
|
#include <stdio.h>
#define LIMIT 1000000
#define QUANT 78498
void main() {
int i, j, k, max, sum, nums[LIMIT]={0}, primes[QUANT]={0};
//add 2 to the array, since the loop will not
nums[1]=2;
//fill the array with numbers of the form 3+2n
for (i=3; i<LIMIT; i+=2) {
nums[i]=i;
}
//remove composite numbers from the array
for (i=3; i<LIMIT; i++) {
if (nums[i] != 0) {
for (j=3; j*i < LIMIT; j++) {
nums[i*j] = 0;
}
}
}
//create an array with only primes
j=0;
for (i=0; i<LIMIT; i++) {
if (nums[i] > 0) {
primes[j] = nums[i];
j++;
//printf("%d \n", primes[j-1]);
}
}
//add sequence of primes, which decreases in length, and end when found
for (i=550; i > 0; i--) {
for (j=0; j<=QUANT-i; j++) {
sum = 0;
for (k=j; k<j+i; k++) {
sum += primes[k];
if (sum > LIMIT ) {
sum=0;
break;
}
}
if ((sum != 0) && (isPrime(sum) == 1)) {
printf("%d \n", sum);
max=i;
break;
}
}
if ((sum != 0) && (isPrime(sum) == 1)) {
break;
}
}
printf("The answer is %d \n", max);
}
//determine if val is prime, 1 if yes, 0 if no
isPrime(int val) {
int i, prime=1;
for (i=2; i < val / 2; i++) {
if (val % i == 0) {
prime=0;
break;
}
}
return prime;
}
|
C
|
#include<stdio.h>
main()
{
int n,i,cpt=0,som1=0,som2=0;
float moy;
puts("entrer un nombre entier positif");
scanf("%d",&n);
if(n<=0)
do
{
puts("entrer une valeur positif");
scanf("%d",&n);
}while(n<=0);
for(i=1;i<=2*n;i++)
{
if(i%2==0)
som1=som1+i;
else
{
som2=som2+i;
cpt=cpt+1;
moy=som2/cpt;
}
}
printf("la somme des %d premier nombres paires est %d\n",n,som1);
printf("la moyenne des %d premier nombres impaires est %f\n",n,moy);
}
|
C
|
/*********************************************
Name : Mohamed Rafat Mohamed
E-Mail : [email protected]
PH : +201014859309
Facebook : www.facebook.com/MohamedRafat29
********************************************/
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int i = 4;
double d = 4.0;
char s[] = "HackerRank ";
// Declare second integer, double, and String variables.
int ii;
double dd;
char s2[70];
char s3;
// Read and save an integer, double, and String to your variables.
scanf("%d", &ii);
scanf("%lf", &dd);
scanf("%c", &s3);
fgets(s2, 70, stdin);
// Print the sum of both integer variables on a new line.
printf("%d\n", i + ii);
// Print the sum of the double variables on a new line.
printf("%.1lf\n", d + dd);
// Concatenate and print the String variables on a new line
// The 's' variable above should be printed first.
printf("%s%s\n", s, s2);
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//<>: ϵͳĿ¼
//"": ӵǰĿ¼ңûҵٴϵͳĿ¼Ѱ
#include "cfg.h"
#define CFGNAME "./mycfg.ini"
void MyMenu()
{
printf("================================\n");
printf("1 дļ\n");
printf("2 ļ\n");
printf("3 \n");
printf("4 ˳\n");
printf("================================\n");
}
void MyWrite()
{
int ret = 0;
char key[512] = { 0 };
char value[512] = { 0 };
printf("\nkey: ");
scanf("%s", key);
printf("\nvalue: ");
scanf("%s", value);
ret = WriteCfgFile(CFGNAME, key, value, strlen(value));
if (ret != 0) //ʧ
{
printf("WriteCfgFile err: %d\n", ret);
return;
}
printf("\nдݣ%s = %s\n\n", key, value);
}
void MyRead()
{
int ret = 0;
char key[512] = { 0 };
char value[512] = { 0 };
int len = 0;
printf("\nkey: ");
scanf("%s", key);
ret = ReadCfgFile(CFGNAME, key, value, &len);
if (ret != 0) //ʧ
{
printf("ReadCfgFile err: %d\n", ret);
return;
}
printf("\n %sӦvalueΪ%s, Ϊ%d\n\n", key, value, len);
}
int main()
{
int cmd;
while (1)
{
MyMenu();
printf("cmd:");
scanf("%d", &cmd);
switch (cmd)
{
case 1:
MyWrite();
break;
case 2:
MyRead();
break;
case 3:
system("cls");
break;
default:
exit(0);
}
}
printf("\n");
system("pause");
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int n,i,j,temp,min=0,max=0,minsum=0,maxsum=0;
int a[100];
scanf("%d", &n);
for(i=0;i<n;i++)
{
scanf("%d\t",&a[i]);
}
min=a[0];
for(i=0;i<n;i++)
{
if(a[i]<min)
{
min=a[i];
}
}
max=a[0];
for(i=0;i<n;i++)
{
if(a[i]>max)
{
max=a[i];
}
}
for(i=0;i<n;i++)
{
if(a[i]!=max)
{
minsum=minsum+a[i];
}
if(a[i]!=min)
{
maxsum=maxsum+a[i];
}
}
printf("%d %d",minsum,maxsum);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
int x = 0, e, j, d, k, space = 0;
char a[50], b[15][20], c[15][20];
printf("Read a string:\n");
fflush(stdin);
scanf("%[^\n]s", a);
for (x=0;a[x]!='\0';x++){
if (a[x] == ' '){
space++;
}
}
x = 0;
for(j=0;j<(space + 1);x++,j++){
k=0;
while(a[x] != '\0'){
if(a[x] == ' '){
break;
}else{
b[j][k++] = a[x];
x++;
}
}
b[j][k] = '\0';
}
x = 0;
strcpy(c[x], b[x]);
for(e=1;e<=j;e++){
for(d=0; d<=x;d++){
if(strcmp(c[x], b[e]) == 0){
break;
}else{
x++;
strcpy(c[x], b[e]);
break;
}
}
}
printf("Number of unique words in \'%s\' are: %d", a, x);
return 0;
}
|
C
|
/*
** ptr_cmd_move.c for PSU_2016_zappy in /home/kleinh/Documents/PSU_2016_zappy/server/src/ptr_cmd_move.c
**
** Made by Arthur Klein
** Login <[email protected]>
**
** Started on Fri Jun 23 14:37:54 2017 Arthur Klein
** Last update Sun Jul 2 17:48:49 2017 yan
*/
#include <stdbool.h>
#include "zappy_server.h"
void update_on_map(t_server *server, t_player *player, t_pos pos)
{
t_tile *tile;
t_tile *new_tile;
t_list_player *tmp;
t_list_player *before;
tile = &server->map[player->pos.y][player->pos.x];
new_tile = &server->map[pos.y][pos.x];
tmp = tile->player_list;
before = NULL;
while (tmp && tmp->player != player)
{
before = tmp;
tmp = tmp->next;
}
if (tmp != NULL)
{
if (before == NULL)
tile->player_list = tmp->next;
else
before->next = tmp->next;
add_list_player(&new_tile->player_list, tmp);
}
}
bool forward(t_server *server, char *line, t_player *player)
{
bool ret;
t_pos new_pos;
char msg[MSG_LENGTH];
(void)line;
new_pos.x = player->pos.x;
new_pos.y = player->pos.y;
update_new_pos(player->dir, &new_pos, server->info);
update_on_map(server, player, new_pos);
set_position(server, player, new_pos.x, new_pos.y);
sprintf(msg, "ppo %d %d %d %d", player->id, player->pos.x,
player->pos.y, player->dir);
if (send_graphical(server, msg) == false)
return (false);
ret = send_message(player->fd, "ok");
return (ret);
}
bool left(t_server *server, char *line, t_player *player)
{
bool ret;
char msg[MSG_LENGTH];
(void)server;
(void)line;
if (player->dir == UP)
player->dir = LEFT;
else if (player->dir == RIGHT)
player->dir = UP;
else if (player->dir == LEFT)
player->dir = DOWN;
else
player->dir = RIGHT;
sprintf(msg, "ppo %d %d %d %d", player->id, player->pos.x,
player->pos.y, player->dir);
if (send_graphical(server, msg) == false)
return (false);
ret = send_message(player->fd, "ok");
return (ret);
}
bool right(t_server *server, char *line, t_player *player)
{
bool ret;
char msg[MSG_LENGTH];
(void)server;
(void)line;
if (player->dir == UP)
player->dir = RIGHT;
else if (player->dir == RIGHT)
player->dir = DOWN;
else if (player->dir == LEFT)
player->dir = UP;
else
player->dir = LEFT;
sprintf(msg, "ppo %d %d %d %d", player->id, player->pos.x,
player->pos.y, player->dir);
if (send_graphical(server, msg) == false)
return (false);
ret = send_message(player->fd, "ok");
return (ret);
}
bool look(t_server *server, char *line, t_player *player)
{
int ret;
char *looked;
(void)line;
if (player->dir == UP)
looked = look_top(player, server);
else if (player->dir == RIGHT)
looked = look_right(player, server);
else if (player->dir == LEFT)
looked = look_left(player, server);
else
looked = look_bottom(player, server);
ret = send_message(player->fd, looked);
free(looked);
return (ret);
}
|
C
|
/**
* @file list.h List API
* @ingroup core
*/
/*
* Hamlog
*
* Copyright (C) 2011, Jan Kaluza <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA
*/
#ifndef _HAMLOG_LIST_H
#define _HAMLOG_LIST_H
#ifdef __cplusplus
extern "C" {
#endif
typedef void (*HAMListItemDataFree) (void *data);
typedef struct _HAMListItem {
void *data;
struct _HAMListItem *lptr;
struct _HAMListItem *rptr;
} HAMListItem;
typedef struct _HAMList {
HAMListItem *first;
HAMListItem *last;
HAMListItemDataFree free_func;
} HAMList;
/**
* Creates new empy list.
* @return Empty list which has to be destroyed by ham_list_destroy() method.
*/
HAMList *ham_list_new();
/**
* Destroys the list and also frees the data.
* @param list List.
*/
void ham_list_destroy(HAMList *list);
void ham_list_set_free_func(HAMList *list, HAMListItemDataFree func);
/**
* Inserts new data as first element in list.
* @param list List.
* @param data Data.
*/
void ham_list_insert_first(HAMList *list, void *data);
/**
* Inserts new data as last element in list.
* @param list List.
* @param data Data.
*/
void ham_list_insert_last(HAMList *list, void *data);
/**
* Removes data, but does not free it.
* @param list List.
* @param data Data.
*/
void ham_list_remove(HAMList *list, void *data);
/**
* Returns data of first element in list.
* @param list List.
* @return Data.
*/
void *ham_list_get_first(HAMList *list);
HAMListItem *ham_list_get_first_item(HAMList *list);
HAMListItem *ham_list_get_next_item(HAMListItem *item);
void *ham_list_item_get_data(HAMListItem *item);
/**
* Returns data of free element in list and removes it from list.
* @param list List.
* @return Data.
*/
void *ham_list_pop_first(HAMList *list);
/**
* Returns data of last element in list.
* @param list List.
* @return Data.
*/
void *ham_list_get_last(HAMList *list);
#ifdef __cplusplus
}
#endif
#endif
|
C
|
/*
* Test the ANSI terminal
*
* 15/4/2000 Stefano Bodrato
*
* Compile with zcc +zxansi ansitest.c
*/
// t for text s for screen
#include "stdio.h"
main()
{
int x;
/*
A stupid CSI escape code test
(normally no use uses CSI)
CSI n J
Clears part of the screen. If n is zero (or missing), clear from cursor to end of screen.
If n is one, clear from cursor to beginning of the screen.
If n is two, clear entire screen (and moves cursor to upper left on DOS
*/
printf ("If you can read this, CSI is not working.\n");
printf ("%c2J",155);
printf ("If this the firSt thing you can read, CSI is OK.\n");
/*
Set Graphic Rendition test
*/
printf ("%c[1mBold Text\n",27);
printf ("%c[2mDim text\n",27);
printf ("%c[4mUnderlined Text\n",27);
printf ("%c[24mUn-underlined text\n",27);
printf ("%c[7mReverse Text\n",27);
printf ("%c[27mUn-reverse text\n",27);
/*
Restore default text attributes
*/
printf ("%c[m",27);
/*
Cursor Position test
"Draw" an X
*/
for (x=0; x<11; x++)
{
printf ("%c[%u;%uH*\n",27,10+x,25+x);
printf ("%c[%u;%uH*\n",27,20-x,25+x);
}
}
|
C
|
#include <stdio.h>
#include<stdlib.h>
int main(){
int num1,num2;
num1 = 540;
num2 = 243;
if (num1 > num2)
printf("\n The greater number is: %d", num1);
else
printf("\n The greater number is: %d", num2);
return 0;
}
|
C
|
/*
name: Alex Austin
Lab Section: 03
Student ID: 001424250
Lab: 3
Question: 1
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *my_strcat( const char * const str1, const char * const str2);
int main(void)
{
printf ( "%s\n", my_strcat( "HELOOO", "WERLDF" ));
return 0;
}
char *my_strcat( const char * const str1, const char * const str2)
{
int strlen1, strlen2, totlen, i = 0,j = 0;
char *p = NULL;//sets pointer
strlen1 = strlen(str1);//gets the length of the strings
strlen2 = strlen(str2);
totlen = strlen1 + strlen2 + 1;//gets the total length
p = malloc(totlen*sizeof(char));//allocates memory based on the total size needed
for ( i; i < strlen1; i++)//copies the first string into the array
p[i]=str1[i];
for ( j; j <= strlen2; i++,j++)//copies second string including the null character into the rest of the memory
p[i]=str2[j];
return p;
}
|
C
|
/*
** EPITECH PROJECT, 2019
** my_printf
** File description:
** Unit tests for printing strings
*/
#include <stddef.h>
#include <criterion/criterion.h>
#include <criterion/redirect.h>
#include "my.h"
Test(my_arg_to_str, basic_usage, .init = cr_redirect_stdout)
{
char *str = "escape from reality";
char expected[] = "escape from reality";
my_printf("%s", str);
cr_assert_stdout_eq_str(expected);
}
Test(my_arg_to_str, with_static_str, .init = cr_redirect_stdout)
{
char *str = "escape from reality";
char expected[] = "mama i just wanna escape from reality";
my_printf("mama i just wanna %s", str);
cr_assert_stdout_eq_str(expected);
}
|
C
|
/* SPDX-License-Identifier: BSD-2-Clause */
/***********************************************************************
* Copyright (c) 2017-2018, Intel Corporation
*
* All rights reserved.
***********************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <inttypes.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <setjmp.h>
#include <cmocka.h>
#include "tss2_tpm2_types.h"
#include "util/io.h"
#define LOGMODULE test
#include "util/log.h"
int
__wrap_socket (
int domain,
int type,
int protocol)
{
errno = mock_type (int);
return mock_type (int);
}
int
__wrap_connect (
int sockfd,
const struct sockaddr *addr,
socklen_t addrlen)
{
errno = mock_type (int);
return mock_type (int);
}
/*
* Wrap the 'recv' system call. The mock queue for this function must have an
* integer return value (the number of byts recv'd), as well as a pointer to
* a buffer to copy data from to return to the caller.
*/
ssize_t
__wrap_read (int fd, void *buffer, size_t count)
{
LOG_DEBUG ("%s: reading %zu bytes from fd: %d to buffer at 0x%" PRIxPTR,
__func__, count, fd, (uintptr_t)buffer);
int r = mock_type (ssize_t);
if (r > 0)
memset(buffer, 0x66, r);
return r;
}
ssize_t
__wrap_write (int fd, const void *buffer, size_t buffer_size)
{
LOG_DEBUG ("writing %zd bytes from 0x%" PRIxPTR " to fd: %d",
buffer_size, (uintptr_t)buffer, fd);
return mock_type (ssize_t);
}
/*
* A test case for a successful call to the receive function. This requires
* that the context and the command buffer be valid (including the size
* field being set appropriately). The result should be an RC indicating
* success and the size parameter be updated to reflect the size of the
* data received.
*/
static void
write_all_simple_success_test (void **state)
{
ssize_t ret;
uint8_t buf [10];
will_return (__wrap_write, sizeof (buf));
ret = write_all (99, buf, sizeof (buf));
assert_int_equal(ret, sizeof (buf));
}
/*
* This test causes the underlying 'read' operation to return '0' bytes
* indicating EOF.
*/
static void
read_all_eof_test (void **state)
{
ssize_t ret;
uint8_t buf [10];
will_return (__wrap_read, 0);
ret = read_all (10, buf, sizeof (buf));
assert_int_equal (ret, 0);
}
/*
* This test is a minor variation on the 'read_all_eof_test'. We still get
* an EOF from the underlying read but only after we get a good read, but one
* that's less than what was requested.
*/
static void
read_all_twice_eof (void **state)
{
ssize_t ret;
uint8_t buf [10];
will_return (__wrap_read, 5);
will_return (__wrap_read, 0);
ret = read_all (10, buf, 10);
assert_int_equal (ret, 5);
}
/* When passed all NULL values ensure that we get back the expected RC. */
static void
socket_connect_test (void **state)
{
TSS2_RC rc;
SOCKET sock;
int ctrl;
for (ctrl = 0; ctrl < 2; ctrl++) {
will_return (__wrap_socket, 0);
will_return (__wrap_socket, 1);
will_return (__wrap_connect, 0);
will_return (__wrap_connect, 1);
rc = socket_connect ("127.0.0.1", 666, ctrl, &sock);
assert_int_equal (rc, TSS2_RC_SUCCESS);
}
}
static void
socket_connect_socket_fail_test (void **state)
{
TSS2_RC rc;
SOCKET sock;
will_return (__wrap_socket, EINVAL);
will_return (__wrap_socket, -1);
rc = socket_connect ("127.0.0.1", 555, 0, &sock);
assert_int_equal (rc, TSS2_TCTI_RC_IO_ERROR);
}
static void
socket_connect_connect_fail_test (void **state)
{
TSS2_RC rc;
SOCKET sock;
will_return (__wrap_socket, 0);
will_return (__wrap_socket, 1);
will_return (__wrap_connect, ENOTSOCK);
will_return (__wrap_connect, -1);
rc = socket_connect ("127.0.0.1", 444, 0, &sock);
assert_int_equal (rc, TSS2_TCTI_RC_IO_ERROR);
}
/* When passed all NULL values ensure that we get back the expected RC. */
static void
socket_ipv6_connect_test (void **state)
{
TSS2_RC rc;
SOCKET sock;
int ctrl;
for (ctrl = 0; ctrl < 2; ctrl++) {
will_return (__wrap_socket, 0);
will_return (__wrap_socket, 1);
will_return (__wrap_connect, 0);
will_return (__wrap_connect, 1);
rc = socket_connect ("::1", 666, ctrl, &sock);
assert_int_equal (rc, TSS2_RC_SUCCESS);
}
}
static void
socket_ipv6_connect_socket_fail_test (void **state)
{
TSS2_RC rc;
SOCKET sock;
will_return (__wrap_socket, EINVAL);
will_return (__wrap_socket, -1);
rc = socket_connect ("::1", 555, 0, &sock);
assert_int_equal (rc, TSS2_TCTI_RC_IO_ERROR);
}
static void
socket_ipv6_connect_connect_fail_test (void **state)
{
TSS2_RC rc;
SOCKET sock;
will_return (__wrap_socket, 0);
will_return (__wrap_socket, 1);
will_return (__wrap_connect, ENOTSOCK);
will_return (__wrap_connect, -1);
rc = socket_connect ("::1", 444, 0, &sock);
assert_int_equal (rc, TSS2_TCTI_RC_IO_ERROR);
}
#ifdef _WIN32
static void
socket_connect_unix_win32_fail_test (void **state)
{
TSS2_RC rc;
SOCKET sock;
rc = socket_connect_unix ("/some/path", 0, &sock);
assert_int_equal (rc, TSS2_RC_BAD_REFERENCE);
}
#else
static void
socket_connect_unix_test (void **state)
{
TSS2_RC rc;
SOCKET sock;
int ctrl;
for (ctrl = 0; ctrl < 2; ctrl++) {
will_return (__wrap_socket, 0);
will_return (__wrap_socket, 1);
will_return (__wrap_connect, 0);
will_return (__wrap_connect, 1);
rc = socket_connect_unix ("/some/path", ctrl, &sock);
assert_int_equal (rc, TSS2_RC_SUCCESS);
}
}
static void
socket_connect_unix_socket_fail_test (void **state)
{
TSS2_RC rc;
SOCKET sock;
will_return (__wrap_socket, EINVAL);
will_return (__wrap_socket, -1);
rc = socket_connect_unix ("/some/path", 0, &sock);
assert_int_equal (rc, TSS2_TCTI_RC_IO_ERROR);
}
static void
socket_connect_unix_connect_fail_test (void **state)
{
TSS2_RC rc;
SOCKET sock;
will_return (__wrap_socket, 0);
will_return (__wrap_socket, 1);
will_return (__wrap_connect, ENOTSOCK);
will_return (__wrap_connect, -1);
rc = socket_connect_unix ("/some/path", 0, &sock);
assert_int_equal (rc, TSS2_TCTI_RC_IO_ERROR);
}
#endif
static void
socket_connect_null_test (void **state)
{
TSS2_RC rc;
SOCKET sock;
rc = socket_connect (NULL, 444, 0, &sock);
assert_int_equal (rc, TSS2_TCTI_RC_BAD_REFERENCE);
}
int
main (int argc,
char *argv[])
{
const struct CMUnitTest tests[] = {
cmocka_unit_test (write_all_simple_success_test),
cmocka_unit_test (read_all_eof_test),
cmocka_unit_test (read_all_twice_eof),
cmocka_unit_test (socket_connect_test),
cmocka_unit_test (socket_connect_null_test),
cmocka_unit_test (socket_connect_socket_fail_test),
cmocka_unit_test (socket_connect_connect_fail_test),
cmocka_unit_test (socket_ipv6_connect_test),
cmocka_unit_test (socket_ipv6_connect_socket_fail_test),
cmocka_unit_test (socket_ipv6_connect_connect_fail_test),
cmocka_unit_test (socket_connect_unix_test),
cmocka_unit_test (socket_connect_unix_socket_fail_test),
cmocka_unit_test (socket_connect_unix_connect_fail_test),
};
return cmocka_run_group_tests (tests, NULL, NULL);
}
|
C
|
/*
* Example of do while loop
*/
/*
* while (condition)
* {
* do something;
* }
*
* do
* {
* something
* }
* while(condition);
*/
#include <stdio.h>
int main()
{
int num;
// user input
printf("Enter a number:");
scanf("%i", &num);
do
//while(num > 0)
{
printf("%i\n", num);
num -= 1; // num = num - 1
}
while(num > 0);
return 0;
}
|
C
|
enum { __FILE_NUM__ = 0 };
#include "app_queue.h"
void AppQueueIn(QUEUE_P QueuePtr, void *pQueueElement)
{
ELEMENT_P QueueElementPtr = (ELEMENT_P)pQueueElement;
ELEMENT_P LastPtr;
if ((LastPtr = QueuePtr->Last) == (ELEMENT_P)0) /* if queue is empty, */
QueuePtr->First = QueueElementPtr; /* q->first = q->last = new entry */
else /* if it is not empty, new entry */
LastPtr->Next = QueueElementPtr; /* is next from last entry */
QueuePtr->Last = QueueElementPtr;
QueueElementPtr->Next = (ELEMENT_P)0;
QueuePtr->ElementCount++; /* increment element count */
}
void *AppQueueOut(QUEUE_P QueuePtr)
{
ELEMENT_P FirstPtr;
if ((FirstPtr = QueuePtr->First) != (ELEMENT_P)0)
{
/* if queue not empty and */
/* it is the last entry */
if ((QueuePtr->First = FirstPtr->Next) == (ELEMENT_P)0)
QueuePtr->Last = (ELEMENT_P)0; /* set queue empty */
QueuePtr->ElementCount--; /* decrement element count */
}
return (FirstPtr);
}
void AppQueueInsert(QUEUE_P QueuePtr, void *pQueueElement, void *pNewQueueElement)
{
ELEMENT_P QueueElementPtr = (ELEMENT_P)pQueueElement;
ELEMENT_P NewQueueElementPtr = (ELEMENT_P)pNewQueueElement;
ELEMENT_P NextPtr;
if (QueueElementPtr == (ELEMENT_P)0) /* insert first element */
{
NextPtr = QueuePtr->First;
QueuePtr->First = NewQueueElementPtr;
NewQueueElementPtr->Next = NextPtr;
if (QueuePtr->Last == (ELEMENT_P)0) /* queue is empty ? */
QueuePtr->Last = NewQueueElementPtr;
QueuePtr->ElementCount++; /* increment element count */
return;
}
/* if ele is last ele -> new ele is last ele */
if (QueueElementPtr->Next == (ELEMENT_P)0)
{
AppQueueIn(QueuePtr, NewQueueElementPtr);
return;
}
NextPtr = QueueElementPtr->Next;
QueueElementPtr->Next = NewQueueElementPtr;
NewQueueElementPtr->Next = NextPtr;
QueuePtr->ElementCount++; /* increment element count */
return;
}
void AppQueueDelete(QUEUE_P QueuePtr, void *pQueueElement)
{
ELEMENT_P QueueElementPtr = (ELEMENT_P)pQueueElement;
ELEMENT_P NextElementPtr;
ELEMENT_P NextPtr;
if ((NextElementPtr = QueuePtr->First) == (ELEMENT_P)0)
return; /* queue is empty */
if (NextElementPtr == QueueElementPtr) /* if first is the elem to be */
{
/* deleted set first to next */
/* only one element ? */
if ((QueuePtr->First = NextElementPtr->Next) == (ELEMENT_P)0)
QueuePtr->Last = (ELEMENT_P)0; /* set queue empty */
QueuePtr->ElementCount--; /* decrement element count */
return;
}
while ((NextPtr = NextElementPtr->Next) != (ELEMENT_P)0 &&
NextPtr != QueueElementPtr)
NextElementPtr = NextPtr;
if (NextPtr == (ELEMENT_P)0)
{
return; /* not found */
}
NextElementPtr->Next = NextPtr->Next;
if (NextElementPtr->Next == (ELEMENT_P)0)
QueuePtr->Last = NextElementPtr;
QueuePtr->ElementCount--; /* decrement element count */
return;
}
|
C
|
int findMaxConsecutiveOnes(int* nums, int numsSize) {
int count = 0, max = 0;
for (int i = 0; i < numsSize; ++i) {
if (nums[i] & 1) count++;
else count = 0;
if (max < count) max = count;
}
return max;
}
|
C
|
// Author:Zheng Jun
// Date:2018/1/10
// E-mail:[email protected]
#include <stdio.h>
#include <memory.h>
#define NAME "NAME:ZHENGJUN'S Inc."
#define ADDRESS "ADDRESS:101 MEGABUCK PLAZA"
#define MOBILE "MOBILE:17131420668"
#define WIDTH 70
#define SPACE ' '
void show_n_char(char, int);//函数原型声明时可以省略形式参数的名称,只写参数类型
void lh2(){
int spaces;
show_n_char('*',WIDTH);
putchar('\n');
show_n_char(SPACE,(WIDTH-strlen(NAME))/2);
printf("%s\n",NAME);
spaces=(WIDTH-strlen(ADDRESS))/2;
show_n_char(SPACE,spaces);
printf("%s\n",ADDRESS);
show_n_char(SPACE,(WIDTH-strlen(MOBILE))/2);
printf("%s\n",MOBILE);
show_n_char('*',WIDTH);
putchar('\n');
}
void show_n_char(char ch, int count) {
for (int i = 0; i < count; ++i) {
putchar(ch);
}
}
//**********************************************************************
// NAME:ZHENGJUN'S Inc.
// ADDRESS:101 MEGABUCK PLAZA
// MOBILE:17131420668
//**********************************************************************
|
C
|
//Struct of Runways
struct outerNode
{
int value;
int numChildren;
struct outerNode* next;
struct innerNode* child;
};
//Taking Off Aircraft
struct innerNode
{
int value;
int flightNo;
struct innerNode* next;
};
//Incomming Aircraft
struct incomingNode
{
int fuel;
int time;
int wait;
int flightNo;
int runway;
int passengerNo;
struct incomingNode* next;
};
struct outerNode* createOuterList();
struct outerNode* createOuterNode(int value, struct innerNode* child);
struct innerNode* createInnerList(struct outerNode** list);
struct innerNode* createInnerNode(int value, int flightNo);
void addOuterNode(struct outerNode** list, int value, struct innerNode* child);
void printOuterList(struct outerNode* list);
void increment(struct outerNode* l);
void addToNthList(struct outerNode* list, int n, int value, int flightNo);
void addInnerNode(struct outerNode* list, int value, int flightNo);
void printInnerList(struct innerNode* list);
void incrementTime(struct innerNode* l);
int lowestOccupiedRunway(struct outerNode* list, int index);
void removeFromRunway(struct outerNode* oList);
int getNumChildren(struct outerNode* list, int index);
|
C
|
#include <stdio.h>
#include<math.h>
long long s1(int n){
long long sum=0;
int i=0;
while(i<n){
sum=sum+pow(10, i);
i++;
}
return sum;
}
int main() {
int a,b,i1=0,i2=0;
long long c,d,sum;
scanf("%lld%d%lld%d",&c,&a,&d,&b);
while(c>0){
if(c%10==a){
i1++;
}
c=c/10;
}
while(d>0){
if(d%10==b){
i2++;
}
d=d/10;
}
printf("%lld",s1(i1)*a+s1(i2)*b);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <syslog.h>
#include "xmalloc.h"
#include "unix.h"
#define DEFAULT_TCP_BUFLEN (1024 * 8)
int write_loop(int fd, char *buf, size_t size)
{
char *p;
int n;
p = buf;
while (p - buf < size) {
n = write(fd, p, size - (p - buf));
if (n == -1) {
if (errno == EINTR)
continue;
else
break;
}
p += n;
}
return p - buf;
}
int lockfile(int fd)
{
struct flock fl;
fl.l_type = F_WRLCK;
fl.l_start = 0;
fl.l_whence = SEEK_SET;
fl.l_len = 0;
return fcntl(fd, F_SETLK, &fl);
}
int daemonize(const char *cmd)
{
int i, fd0, fd1, fd2;
pid_t pid;
struct rlimit rl;
struct sigaction sa;
umask(0);
if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
return -EIO;
/* become a session leader to lose controlling TTY */
if ((pid = fork()) < 0)
return -EFAULT;
else if (pid > 0)
exit(0);
setsid();
/* ensure future opens won't allocate controlling TTYs */
sa.sa_handler = SIG_IGN;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
if (sigaction(SIGHUP, &sa, NULL) < 0)
return -EIO;
if ((pid = fork()) < 0)
return -EFAULT;
else if (pid > 0)
exit(0);
/* we won't prevent file system from being unmounted */
if (chdir("/") < 0)
return -EFAULT;
if (rl.rlim_max == RLIM_INFINITY)
rl.rlim_max = 1024;
for (i = 0; i < rl.rlim_max; i++)
close(i);
fd0 = open("/dev/null", O_RDWR);
fd1 = dup(0);
fd2 = dup(0);
openlog(cmd, LOG_CONS, LOG_DAEMON);
if (fd0 != 0 || fd1 != 1 || fd2 != 2) {
syslog(LOG_ERR, "unexpected file descriptors %d %d %d", fd0, fd1, fd2);
return -EFAULT;
}
return 0;
}
/*
* Split a command line into an array suitable for handing to execv.
*
* A note on syntax: words are split on whitespace and '\' escapes characters.
* '\\' will show up as '\' and '\ ' will leave a space, combining two
* words. Examples:
* "ncat\ experiment -l -k" will be parsed as the following tokens:
* "ncat experiment", "-l", "-k".
* "ncat\\ -l -k" will be parsed as "ncat\", "-l", "-k"
* See the test program, test/test-cmdline-split to see additional cases.
*/
char **cmdline_split(const char *cmdexec, int *cmd_argv)
{
const char *ptr;
char *cur_arg, **cmd_args;
int max_tokens = 0, arg_idx = 0, ptr_idx = 0;
/* Figure out the maximum number of tokens needed */
ptr = cmdexec;
while (*ptr) {
/* Find the start of the token */
while (*ptr && isspace((int)(unsigned char)*ptr))
ptr++;
if (!*ptr)
break;
max_tokens++;
/* Find the start of the whitespace again */
while (*ptr && !isspace((int)(unsigned char)*ptr))
ptr++;
}
/* The line is not empty so we've got something to deal with */
cmd_args = (char **)xmalloc(sizeof(char *) * (max_tokens + 1));
cur_arg = (char *)calloc(sizeof(char), strlen(cmdexec));
/* Get and copy the tokens */
ptr = cmdexec;
while (*ptr) {
while (*ptr && isspace((int)(unsigned char)*ptr))
ptr++;
if (!*ptr)
break;
while (*ptr && !isspace((int)(unsigned char)*ptr)) {
if (*ptr == '\\') {
ptr++;
if (!*ptr)
break;
cur_arg[ptr_idx] = *ptr;
ptr_idx++;
ptr++;
if (*(ptr - 1) != '\\') {
while (*ptr && isspace((int)(unsigned char)*ptr))
ptr++;
}
} else {
cur_arg[ptr_idx] = *ptr;
ptr_idx++;
ptr++;
}
}
cur_arg[ptr_idx] = '\0';
cmd_args[arg_idx] = strdup(cur_arg);
cur_arg[0] = '\0';
ptr_idx = 0;
arg_idx++;
}
cmd_args[arg_idx] = NULL;
if (cmd_argv)
*cmd_argv = arg_idx;
/* Clean up */
free(cur_arg);
return cmd_args;
}
void free_cmd_argv(char *cmd_argv[])
{
int i;
if (cmd_argv == NULL)
return;
for (i = 0; cmd_argv[i]; i++)
free(cmd_argv[i]);
free(cmd_argv);
}
int netexec(int fd, const char *cmdexec)
{
int child_stdin[2];
int child_stdout[2];
int pid;
char buffer[DEFAULT_TCP_BUFLEN];
int maxfd;
if (pipe(child_stdin) == -1 || pipe(child_stdout) == -1)
return -1;
pid = fork();
if (pid == -1)
return -1;
if (pid == 0) {
/* child */
char **cmdargs;
close(child_stdin[1]);
close(child_stdout[0]);
signal(SIGPIPE, SIG_DFL);
dup2(child_stdin[0], STDIN_FILENO);
dup2(child_stdout[1], STDOUT_FILENO);
cmdargs = cmdline_split(cmdexec, NULL);
execv(cmdargs[0], cmdargs);
return -1;
}
/* parent */
close(child_stdin[0]);
close(child_stdout[1]);
maxfd = child_stdout[0];
if (fd > maxfd)
maxfd = fd;
while (1) {
fd_set fds;
int n;
FD_ZERO(&fds);
FD_SET(fd, &fds);
FD_SET(child_stdout[0], &fds);
n = select(maxfd + 1, &fds, NULL, NULL, NULL);
if (n == -1) {
if (errno == EINTR)
continue;
else
break;
}
if (FD_ISSET(fd, &fds)) {
n = recv(fd, buffer, sizeof(buffer), 0);
if (n <= 0)
break;
write_loop(child_stdin[1], buffer, n);
}
if (FD_ISSET(child_stdout[0], &fds)) {
n = read(child_stdout[0], buffer, sizeof(buffer));
if (n <= 0)
break;
send(fd, buffer, n, 0);
}
}
close(fd);
exit(0);
return 0;
}
int netrun(int fd, const char *cmdexec)
{
int pid;
pid = fork();
if (pid == 0)
netexec(fd, cmdexec);
close(fd);
return pid;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_TERMS 10
typedef struct {
int row; // 행의 정보
int col; // 열의 정보
int value; // 행렬의 값
}term;
int shape;
typedef struct {
term data[MAX_TERMS];
int rows; // 행의 개수
int cols; // 열의 개수
int terms; // 항의 개수
}SparseMatrix;
SparseMatrix add_sparse(SparseMatrix a, SparseMatrix b){
SparseMatrix c = {0};
int ca = 0, cb = 0, cc = 0; //각 배열의 항목을 가리키는 인덱스
c.rows = a.rows;
c.cols = a.cols;
while (ca < a.terms && cb < b.terms){
// 각 항목의 실제 행렬에서의 순차적 번호 계산
int a_idx = a.data[ca].row * a.cols + a.data[ca].col;
int b_idx = b.data[cb].row * b.cols + b.data[cb].col;
if (a_idx < b_idx){ // a의 항목이 앞서는 경우
c.data[cc++] = a.data[ca++]; // a의 항목 추가
}else if (a_idx == b_idx){ // a와 b가 동일 위치에 있는 경우
if((a.data[ca].value + b.data[cb].value)!=0){ //0이 아닌 값만 저장하며 0인 경우 다음으로 넘어감
c.data[cc].row = a.data[ca].row;
c.data[cc].col = a.data[ca].col;
c.data[cc++].value = a.data[ca++].value + b.data[cb++].value;
}else {
ca++;
cb++;
}
}else c.data[cc++] = b.data[cb++]; // b의 항목이 앞서는 경우 b의 항목 추가
}
for (;ca < a.terms;) // 각 배열에 남아있는 항들을 결과 행렬에 추가
c.data[cc++] = a.data[ca++];
for (;cb < b.terms;)
c.data[cc++] = b.data[cb++];
c.terms = cc; // 결과 행렬의 항의 개수 저장
return c;
}
SparseMatrix sort_matrix(SparseMatrix c){
term temp;
for (int i = 0; i< c.terms; i++){
for (int j = 0; j < c.terms - 1 - i; j++){
if (c.data[j].row * c.cols + c.data[j].col > c.data[j+1].row * c.cols + c.data[j+1].col){
temp = c.data[j];
c.data[j] = c.data[j+1];
c.data[j+1] = temp;
}
}
}
return c;
}
SparseMatrix multiply_sparse(SparseMatrix a, SparseMatrix b){
SparseMatrix c={0};
int ca = 0, cb = 0, cc = 0, a_idx, b_idx, b_start, b_end;
c.rows = a.rows;
c.cols = a.cols;
for (int i = 0; i < a.terms; i++){
a_idx = a.data[i].row * a.cols + a.data[i].col; // a 항목의 실제 행렬에서의 순차적 번호 계산
cb = 0; //b의 희소행렬 인덱스 초기화
for (int j = cb; j < b.terms; j++){
b_idx = b.data[cb].row * b.cols + b.data[cb].col; // b 항목의 실제 행렬에서의 순차적 번호 계산
b_start = (a_idx % shape) * shape; //a의 항이 행렬 곱셈 수행 시 곱해지는 b의 범위 지정
b_end = b_start + shape - 1;
if (b_start <= b_idx && b_idx <= b_end){ //b 항목이 범위 안에 있을 경우
c.data[cc].row = a.data[ca].row; //결과 행렬 항목의 행은 a와 같음
c.data[cc].col = b.data[cb].col; //결과 행렬 항목의 열은 b와 같음
c.data[cc++].value += a.data[ca].value * b.data[cb++].value; //a항목의 값과 b항목의 곱한 값을 결과행렬의 값으로 넣고, b희소행렬의 인덱스 증가
}else if (b_idx < b_start){ //b 항목이 범위보다 전에 있을 경우 다음 항목으로 넘어감
cb++;
continue;
}else break; //b 항목이 범위를 벗어나면 다음 a항목으로 넘어감
}
ca++;
}
c.terms = cc;
c = sort_matrix(c);
return c;
}
void print_matrix(SparseMatrix m){
for (int i =0 ;i<m.terms;i++){
printf("%d %d %d\n", m.data[i].row, m.data[i].col, m.data[i].value);
}
}
int main(){
SparseMatrix m1, m2, m3, m4; // 행렬 구조체 선언
printf("행렬의 규격을 입력하세요. "); // 행렬의 규격 입력 후 전역변수에 저장
scanf(" %d", &shape);
m1.rows = shape; // 구조체의 값 일부 초기화, terms에 쓰레기 값이 들어가는 경우가 있어 초기화 필요
m1.cols = shape;
m1.terms = 0;
m2.rows = shape;
m2.cols = shape;
m2.terms = 0;
m3.rows = shape;
m3.cols = shape;
m3.terms = 0;
m4.rows = shape;
m4.cols = shape;
m4.terms = 0;
char input[(shape*shape)*2]; // 띄어쓰기 포함하여 행렬의 값을 입력받는 문자열 형성
printf("행렬 1의 데이터를 입력하세요. ");
scanf(" %[^\n]", input);
int r = 0, c = 0, data_idx = 0; // 저장에 필요한 행, 열, 인덱스 변수 선언
char* temp = strtok(input, " "); // 공백을 기준으로 분할하여 저장
if (atoi(temp) != 0){
m1.data[data_idx].row = r; // 행의 정보 저장
m1.data[data_idx].col = c; // 열의 정보 저장
m1.data[data_idx].value = atoi(temp); //항의 값 저장
m1.terms++; // 항의 개수 저장
data_idx++; // 다음 인덱스로
}
c++; // 다음 열로
if (c == shape){ // 열이 규격에 달하면 다음 행으로
c=0;
r++;
}
temp = strtok(NULL, " ");
}
r = 0;
c = 0;
data_idx = 0; // 저장에 필요한 행, 열, 인덱스 변수 초기화
printf("행렬 2의 데이터를 입력하세요. ");
scanf(" %[^\n]", input);
temp = strtok(input, " "); // 공백을 기준으로 분할하여 저장
while (temp != NULL){
if (atoi(temp) != 0){
m2.data[data_idx].row = r; // 행의 정보 저장
m2.data[data_idx].col = c; // 열의 정보 저장
m2.data[data_idx].value = atoi(temp); // 항의 값 저장
m2.terms++; // 항의 개수 저장
data_idx++; // 다음 인덱스로
}
c++;
if (c == shape){ // 다음 열로
c=0; // 열이 규격에 달하면 다음 행으로
r++;
}
temp = strtok(NULL, " ");
}
//행렬의 크기가 같은지 확인
if (m1.rows != m2.rows || m1.cols != m2.cols){
fprintf(stderr, "희소행렬 크기 에러\n");
exit(1);
}
m3 = add_sparse(m1, m2);
m4 = multiply_sparse(m1, m2);
printf("\n방식2:\n");
printf("\n행렬3 (%d개)\n", m1.terms*3);
print_matrix(m1);
printf("\n행렬4 (%d개)\n", m2.terms*3);
print_matrix(m2);
printf("\n행렬3+4 (%d개)\n", m3.terms*3);
print_matrix(m3);
printf("\n행렬3*4 (%d개)\n", m4.terms*3);
print_matrix(m4);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int i,num;
while(scanf("%d",&num)!=EOF)
{
if(num==2)
printf("prime number\n");
else
{
for(i=2; i<=num-1; i++)
{
if(num%i==0)
break;
}
if(num==i)
printf("prime number\n");
else
printf("not prime\n");
}
}
}
|
C
|
#include "stdio.h"
int main() {
char s[] = "Anurag Saraswat";
int i = 0;
int temp;
while (s[i] != '\0') {
temp = s[i];
if (temp >= 'A' && temp < 'a') {
s[i] = s[i] - 'A' + 'a';
}
else if (temp >= 'a' && temp <= 'z') {
s[i] = s[i] + 'A' - 'a';
}
i++;
}
puts(s);
return 0;
}
|
C
|
#ifdef _WIN32_
#include <windows.h>
#include "win_semaphor_thread.h"
#endif
#include "pthread.h"
#include "../locker_pthread.h"
#include "stdlib.h"
#include "string.h"
#include "../Locker.h"
#include "../nested_locker.h"
#include "../dlist.h"
//#include "log.h"
dlist list = NULL;
int eq(void* data1,void* data2)
{
int* dat1 = (int*)data1;
int* dat2 = (int*)data2;
if(*dat1>*dat2)
{
return *dat1-*dat2;
}
else
{
return *dat2-*dat1;
}
}
int print(void* data)
{
printf("%d,",*(int*)data);
}
/*
void thread_proc1( void *pParam )
{
int sleeptime = 0;
printf( "%s created.\n", pParam );
while(1)
{
void* data1 = NULL;
sleeptime = 1+(int)(10.0*rand()/(RAND_MAX+1.0));
data1 = malloc(sizeof(int));
*(int*)data1 = (int)(10.0*rand()/(RAND_MAX+1.0));
add(list,data1);
printf("Thread1 Add %d to the list.\n",*(int*)data1);
printf("The all data of the list printed by thread1.\n");
foreach(list,print,NULL);
printf("Thread1 sleep for %d time.\n",sleeptime);
Sleep(1000*sleeptime);
}
}
void thread_proc2( void *pParam )
{
int sleeptime = 0;
printf( "%s created.\n", pParam );
while(1)
{
void* data1 = NULL;
sleeptime = 1+(int)(10.0*rand()/(RAND_MAX+1.0));
data1 = malloc(sizeof(int));
*(int*)data1 = (int)(10.0*rand()/(RAND_MAX+1.0));
delNode(list,data1,eq);
printf("Thread2 Delete data %d from the list.\n",*(int*)data1);
printf("The all data of the list printed by thread2.\n");
foreach(list,print,NULL);
printf("Thread2 sleep for %d time.\n",sleeptime);
Sleep(1000*sleeptime);
}
}
*/
void* ThreadAProc()
{
int sleeptime = 0;
printf( "Thread A created.\n");
while(1)
{
void* data1 = NULL;
sleeptime = 1+(int)(10.0*rand()/(RAND_MAX+1.0));
data1 = malloc(sizeof(int));
*(int*)data1 = (int)(10.0*rand()/(RAND_MAX+1.0));
add(list,data1);
printf("Thread1 Add %d to the list.\n",*(int*)data1);
printf("The all data of the list printed by thread1.\n");
foreach(list,print,NULL);
printf("Thread1 sleep for %d time.\n",sleeptime);
sleep(1*sleeptime);
}
}
void* ThreadBProc()
{
int sleeptime = 0;
printf( "Thread B created.\n");
while(1)
{
void* data1 = NULL;
sleeptime = 1+(int)(10.0*rand()/(RAND_MAX+1.0));
data1 = malloc(sizeof(int));
*(int*)data1 = (int)(10.0*rand()/(RAND_MAX+1.0));
delNode(list,data1,eq);
printf("Thread2 Delete data %d from the list.\n",*(int*)data1);
printf("The all data of the list printed by thread2.\n");
foreach(list,print,NULL);
printf("Thread2 sleep for %d time.\n",sleeptime);
sleep(1*sleeptime);
}
}
int main(int argc,char** argv)
{
int k = 0;
pthread_t thread1;
pthread_t thread2;
int ret1;
int ret2;
Locker* locker = locker_pthread_create();
Locker* nest_locker = locker_nest_create(locker, (TaskSelfFunc)pthread_self);
init(&list,nest_locker);
ret1 = pthread_create(&thread1,NULL,&ThreadAProc,NULL);
ret2 = pthread_create(&thread2,NULL,&ThreadBProc,NULL);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
//Locker* locker = locker_win_create();
//Locker* nest_locker = locker_nest_create(locker, (TaskSelfFunc)GetCurrentThreadId);
//init(&list,nest_locker);
//_beginthread( thread_proc1, 4096,"Thread 1");
//_beginthread( thread_proc2, 4096,"Thread 2");
/*
Logger* log = NULL;
log = create_log("D:\\log.log",nest_locker,6);
log->debug(log,"Test the var list First: %d and second :%d\n",1,2);
*/
getchar();
return 0;
}
|
C
|
#ifndef TRAJECTORY_H
#define TRAJECTORY_H
#include "../../common/2d/2d.h"
#include "../../common/io/outputStream.h"
#include "../../device/device.h"
#define TRAJECTORY_THRESHOLD_NOTIFY_DEFAULT_VALUE true
// 5 cm of threshold
#define TRAJECTORY_THRESHOLD_DISTANCE_MM_DEFAULT_VALUE 50.0f
// About 10 degree
#define TRAJECTORY_THRESHOLD_ANGLE_RADIAN_DEFAULT_VALUE 0.174533f
/**
* Structure to store all informations linked to the follow of trajectory.
*/
typedef struct {
/** The current position with angle and initial Orientation */
Position position;
// Last left coder value
float lastLeft;
// Last right coder value
float lastRight;
// Last angle
float lastAngle;
/** The last time when we have notified */
float lastPidTimeInSeconds;
/** The last speed */
float lastSpeed;
// NOTIFY CHANGE SYSTEM
/** If we activate the notification on trajectory change */
bool notifyChange;
/** The last notified current Position with angle and initial Orientation*/
Position lastNotificationPosition;
/** The threshold in terms of distance (mm) to notify the new position */
float thresholdDistance;
/** The threshold in terms of angle (radian) to notify the new position */
float thresholdAngleRadian;
} TrajectoryInfo;
/**
* Returns all data about the follow of the trajectory.
*/
TrajectoryInfo* getTrajectory(void);
/**
* Initializes the trajectory computer and sets the current
* position to (0, 0) with an orientation angle of 0.
*/
void initializeTrajectory(void);
/**
* Clears the current trajectory informations and sets the
* current position to (0, 0) with the orientation 0.
*/
void clearTrajectory(void);
// POSITION
/**
* Returns the current absolute position.
* @return the structure representing the current position
*/
Position* getPosition(void);
/**
* Sets the absolute position.
* @param x the x coordinate in true length
* @param y the y coordinate in true length
* @param orientation the orientation angle
*/
void setPosition(float x, float y, float orientation);
/**
* Adjust the X Position, with a threshold to avoid that if we are blocked, we increase the error instead
* to decrease them.
*/
bool adjustXPosition(float x, float thresholdDistance);
/**
* Adjust the Y Position, with a threshold to avoid that if we are blocked, we increase the error instead
* to decrease them.
* @param y
*/
bool adjustYPosition(float y, float thresholdDistance);
/**
* Adjust the angle with a threshold to avoid that if we are blocked, we increase the error instead
* to decrease them.
* We do not provide the angle but we consider that we use always a value close to
* 0 / 90 / 180 / 270 degree
*/
bool adjustAngle(float thresholdAngle);
/**
* Update the information for the trajectory.
* Please note that the trajectory can differed from the reality
* because of threshold
*/
void updateTrajectory(void);
/**
* Update the information for the trajectory, but does not
* use Threshold.
*/
void updateTrajectoryWithNoThreshold(void);
/**
* Update the information for the trajectory and store to avoid
* lost of information, and clear Coders.
*/
void updateTrajectoryAndClearCoders(void);
// NOTIFICATION & TRAJECTORY_TYPE
enum TrajectoryType computeTrajectoryType(float distanceSinceLastNotification, float angleRadianSinceLastNotification);
float getDistanceBetweenLastNotificationAndCurrentRobotPosition(void);
float getAverageSpeedSinceLastNotification(float distance);
float getAbsoluteAngleRadianBetweenLastNotificationAndCurrentRobotPosition(void);
void clearLastNotificationData(void);
#endif
|
C
|
/**
* @file lv_style.c
*
*/
/*********************
* INCLUDES
*********************/
#include "lv_obj.h"
#include "../lv_misc/lv_mem.h"
#include "../lv_misc/lv_anim.h"
/*********************
* DEFINES
*********************/
#define STYLE_MIX_MAX 256
#define STYLE_MIX_SHIFT 8 /*log2(STYLE_MIX_MAX)*/
#define VAL_PROP(v1, v2, r) v1 + (((v2 - v1) * r) >> STYLE_MIX_SHIFT)
#define STYLE_ATTR_MIX(attr, r) \
if(start->attr != end->attr) { \
res->attr = VAL_PROP(start->attr, end->attr, r); \
} else { \
res->attr = start->attr; \
}
#define LV_STYLE_PROP_TO_ID(prop) (prop & 0xFF);
#define LV_STYLE_PROP_GET_TYPE(prop) ((prop >> 8) & 0xFF);
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
LV_ATTRIBUTE_FAST_MEM static inline int32_t get_property_index(const lv_style_t * style, lv_style_property_t prop);
static lv_style_t * get_alloc_local_style(lv_style_list_t * list);
static inline void style_resize(lv_style_t * style, size_t sz);
static inline lv_style_property_t get_style_prop(const lv_style_t * style, size_t idx);
static inline uint8_t get_style_prop_id(const lv_style_t * style, size_t idx);
static inline uint8_t get_style_prop_attr(const lv_style_t * style, size_t idx);
static inline size_t get_prop_size(uint8_t prop_id);
static inline size_t get_next_prop_index(uint8_t prop_id, size_t id);
/**********************
* GLOABAL VARIABLES
**********************/
/**********************
* STATIC VARIABLES
**********************/
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
/**
* Initialize a style
* @param style pointer to a style to initialize
*/
void lv_style_init(lv_style_t * style)
{
_lv_memset_00(style, sizeof(lv_style_t));
#if LV_USE_ASSERT_STYLE
style->sentinel = LV_DEBUG_STYLE_SENTINEL_VALUE;
#endif
}
/**
* Copy a style with all its properties
* @param style_dest pointer to the destination style. (Should be initialized with `lv_style_init()`)
* @param style_src pointer to the source (to copy )style
*/
void lv_style_copy(lv_style_t * style_dest, const lv_style_t * style_src)
{
if(style_src == NULL) return;
LV_ASSERT_STYLE(style_dest);
LV_ASSERT_STYLE(style_src);
if(style_src->map == NULL) return;
uint16_t size = _lv_style_get_mem_size(style_src);
style_dest->map = lv_mem_alloc(size);
_lv_memcpy(style_dest->map, style_src->map, size);
}
/**
* Remove a property from a style
* @param style pointer to a style
* @param prop a style property ORed with a state.
* E.g. `LV_STYLE_BORDER_WIDTH | (LV_STATE_PRESSED << LV_STYLE_STATE_POS)`
* @return true: the property was found and removed; false: the property wasn't found
*/
bool lv_style_remove_prop(lv_style_t * style, lv_style_property_t prop)
{
if(style == NULL) return false;
LV_ASSERT_STYLE(style);
int32_t id = get_property_index(style, prop);
/*The property exists but not sure it's state is the same*/
if(id >= 0) {
lv_style_attr_t attr_found;
lv_style_attr_t attr_goal;
attr_found = get_style_prop_attr(style, id);
attr_goal = (prop >> 8) & 0xFFU;
if(LV_STYLE_ATTR_GET_STATE(attr_found) == LV_STYLE_ATTR_GET_STATE(attr_goal)) {
uint32_t map_size = _lv_style_get_mem_size(style);
uint8_t prop_size = get_prop_size(prop);
/*Move the props to fill the space of the property to delete*/
uint32_t i;
for(i = id; i < map_size - prop_size; i++) {
style->map[i] = style->map[i + prop_size];
}
style_resize(style, map_size - prop_size);
return true;
}
}
return false;
}
/**
* Initialize a style list
* @param list a style list to initialize
*/
void lv_style_list_init(lv_style_list_t * list)
{
_lv_memset_00(list, sizeof(lv_style_list_t));
#if LV_USE_ASSERT_STYLE
list->sentinel = LV_DEBUG_STYLE_LIST_SENTINEL_VALUE;
#endif
}
/**
* Copy a style list with all its styles and local style properties
* @param list_dest pointer to the destination style list. (should be initialized with `lv_style_list_init()`)
* @param list_src pointer to the source (to copy) style list.
*/
void lv_style_list_copy(lv_style_list_t * list_dest, const lv_style_list_t * list_src)
{
LV_ASSERT_STYLE_LIST(list_dest);
LV_ASSERT_STYLE_LIST(list_src);
_lv_style_list_reset(list_dest);
if(list_src->style_list == NULL) return;
/*Copy the styles but skip the transitions*/
if(list_src->has_local == 0) {
if(list_src->has_trans) {
list_dest->style_list = lv_mem_alloc((list_src->style_cnt - 1) * sizeof(lv_style_t *));
_lv_memcpy(list_dest->style_list, list_src->style_list + 1, (list_src->style_cnt - 1) * sizeof(lv_style_t *));
list_dest->style_cnt = list_src->style_cnt - 1;
}
else {
list_dest->style_list = lv_mem_alloc(list_src->style_cnt * sizeof(lv_style_t *));
_lv_memcpy(list_dest->style_list, list_src->style_list, list_src->style_cnt * sizeof(lv_style_t *));
list_dest->style_cnt = list_src->style_cnt;
}
}
else {
if(list_src->has_trans) {
list_dest->style_list = lv_mem_alloc((list_src->style_cnt - 2) * sizeof(lv_style_t *));
_lv_memcpy(list_dest->style_list, list_src->style_list + 2, (list_src->style_cnt - 2) * sizeof(lv_style_t *));
list_dest->style_cnt = list_src->style_cnt - 2;
}
else {
list_dest->style_list = lv_mem_alloc((list_src->style_cnt - 1) * sizeof(lv_style_t *));
_lv_memcpy(list_dest->style_list, list_src->style_list + 1, (list_src->style_cnt - 1) * sizeof(lv_style_t *));
list_dest->style_cnt = list_src->style_cnt - 1;
}
lv_style_t * local_style = get_alloc_local_style(list_dest);
lv_style_copy(local_style, get_alloc_local_style((lv_style_list_t *)list_src));
}
}
/**
* Add a style to a style list.
* Only the the style pointer will be saved so the shouldn't be a local variable.
* (It should be static, global or dynamically allocated)
* @param list pointer to a style list
* @param style pointer to a style to add
*/
void _lv_style_list_add_style(lv_style_list_t * list, lv_style_t * style)
{
LV_ASSERT_STYLE_LIST(list);
LV_ASSERT_STYLE(style);
if(list == NULL) return;
/*Remove the style first if already exists*/
_lv_style_list_remove_style(list, style);
lv_style_t ** new_classes;
if(list->style_cnt == 0) new_classes = lv_mem_alloc(sizeof(lv_style_t *));
else new_classes = lv_mem_realloc(list->style_list, sizeof(lv_style_t *) * (list->style_cnt + 1));
LV_ASSERT_MEM(new_classes);
if(new_classes == NULL) {
LV_LOG_WARN("lv_style_list_add_style: couldn't add the class");
return;
}
/*Make space for the new style at the beginning. Leave local and trans style if exists*/
uint8_t i;
uint8_t first_style = 0;
if(list->has_trans) first_style++;
if(list->has_local) first_style++;
for(i = list->style_cnt; i > first_style; i--) {
new_classes[i] = new_classes[i - 1];
}
new_classes[first_style] = style;
list->style_cnt++;
list->style_list = new_classes;
}
/**
* Remove a style from a style list
* @param style_list pointer to a style list
* @param style pointer to a style to remove
*/
void _lv_style_list_remove_style(lv_style_list_t * list, lv_style_t * style)
{
LV_ASSERT_STYLE_LIST(list);
LV_ASSERT_STYLE(style);
if(list->style_cnt == 0) return;
/*Check if the style really exists here*/
uint8_t i;
bool found = false;
for(i = 0; i < list->style_cnt; i++) {
if(list->style_list[i] == style) {
found = true;
break;
}
}
if(found == false) return;
if(list->style_cnt == 1) {
lv_mem_free(list->style_list);
list->style_list = NULL;
list->style_cnt = 0;
list->has_local = 0;
return;
}
lv_style_t ** new_classes = lv_mem_alloc(sizeof(lv_style_t *) * (list->style_cnt - 1));
LV_ASSERT_MEM(new_classes);
if(new_classes == NULL) {
LV_LOG_WARN("lv_style_list_remove_style: couldn't reallocate class list");
return;
}
uint8_t j;
for(i = 0, j = 0; i < list->style_cnt; i++) {
if(list->style_list[i] == style) continue;
new_classes[j] = list->style_list[i];
j++;
}
lv_mem_free(list->style_list);
list->style_cnt--;
list->style_list = new_classes;
}
/**
* Remove all styles added from style list, clear the local style, transition style and free all allocated memories.
* Leave `ignore_trans` flag as it is.
* @param list pointer to a style list.
*/
void _lv_style_list_reset(lv_style_list_t * list)
{
LV_ASSERT_STYLE_LIST(list);
if(list == NULL) return;
if(list->has_local) {
lv_style_t * local = lv_style_list_get_local_style(list);
if(local) {
lv_style_reset(local);
lv_mem_free(local);
}
}
if(list->has_trans) {
lv_style_t * trans = _lv_style_list_get_transition_style(list);
if(trans) {
lv_style_reset(trans);
lv_mem_free(trans);
}
}
if(list->style_cnt > 0) lv_mem_free(list->style_list);
list->style_list = NULL;
list->style_cnt = 0;
list->has_local = 0;
list->has_trans = 0;
list->skip_trans = 0;
/* Intentionally leave `ignore_trans` as it is,
* because it's independent from the styles in the list*/
}
/**
* Clear all properties from a style and all allocated memories.
* @param style pointer to a style
*/
void lv_style_reset(lv_style_t * style)
{
LV_ASSERT_STYLE(style);
lv_mem_free(style->map);
style->map = NULL;
}
/**
* Get the size of the properties in a style in bytes
* @param style pointer to a style
* @return size of the properties in bytes
*/
uint16_t _lv_style_get_mem_size(const lv_style_t * style)
{
LV_ASSERT_STYLE(style);
if(style->map == NULL) return 0;
size_t i = 0;
uint8_t prop_id;
while((prop_id = get_style_prop_id(style, i)) != _LV_STYLE_CLOSEING_PROP) {
i = get_next_prop_index(prop_id, i);
}
return i + sizeof(lv_style_property_t);
}
/**
* Set an integer typed property in a style.
* @param style pointer to a style where the property should be set
* @param prop a style property ORed with a state.
* E.g. `LV_STYLE_BORDER_WIDTH | (LV_STATE_PRESSED << LV_STYLE_STATE_POS)`
* @param value the value to set
* @note shouldn't be used directly. Use the specific property set functions instead.
* For example: `lv_style_set_border_width()`
* @note for performance reasons it's not checked if the property really has integer type
*/
void _lv_style_set_int(lv_style_t * style, lv_style_property_t prop, lv_style_int_t value)
{
LV_ASSERT_STYLE(style);
int32_t id = get_property_index(style, prop);
/*The property already exists but not sure it's state is the same*/
if(id >= 0) {
lv_style_attr_t attr_found;
lv_style_attr_t attr_goal;
attr_found = get_style_prop_attr(style, id);
attr_goal = (prop >> 8) & 0xFFU;
if(LV_STYLE_ATTR_GET_STATE(attr_found) == LV_STYLE_ATTR_GET_STATE(attr_goal)) {
_lv_memcpy_small(style->map + id + sizeof(lv_style_property_t), &value, sizeof(lv_style_int_t));
return;
}
}
/*Add new property if not exists yet*/
uint8_t new_prop_size = (sizeof(lv_style_property_t) + sizeof(lv_style_int_t));
lv_style_property_t end_mark = _LV_STYLE_CLOSEING_PROP;
uint8_t end_mark_size = sizeof(end_mark);
uint16_t size = _lv_style_get_mem_size(style);
if(size == 0) size += end_mark_size;
size += sizeof(lv_style_property_t) + sizeof(lv_style_int_t);
style_resize(style, size);
LV_ASSERT_MEM(style->map);
if(style == NULL) return;
_lv_memcpy_small(style->map + size - new_prop_size - end_mark_size, &prop, sizeof(lv_style_property_t));
_lv_memcpy_small(style->map + size - sizeof(lv_style_int_t) - end_mark_size, &value, sizeof(lv_style_int_t));
_lv_memcpy_small(style->map + size - end_mark_size, &end_mark, sizeof(end_mark));
}
/**
* Set a color typed property in a style.
* @param style pointer to a style where the property should be set
* @param prop a style property ORed with a state.
* E.g. `LV_STYLE_BORDER_COLOR | (LV_STATE_PRESSED << LV_STYLE_STATE_POS)`
* @param value the value to set
* @note shouldn't be used directly. Use the specific property set functions instead.
* For example: `lv_style_set_border_color()`
* @note for performance reasons it's not checked if the property really has color type
*/
void _lv_style_set_color(lv_style_t * style, lv_style_property_t prop, lv_color_t color)
{
LV_ASSERT_STYLE(style);
int32_t id = get_property_index(style, prop);
/*The property already exists but not sure it's state is the same*/
if(id >= 0) {
lv_style_attr_t attr_found;
lv_style_attr_t attr_goal;
attr_found = get_style_prop_attr(style, id);
attr_goal = (prop >> 8) & 0xFFU;
if(LV_STYLE_ATTR_GET_STATE(attr_found) == LV_STYLE_ATTR_GET_STATE(attr_goal)) {
_lv_memcpy_small(style->map + id + sizeof(lv_style_property_t), &color, sizeof(lv_color_t));
return;
}
}
/*Add new property if not exists yet*/
uint8_t new_prop_size = (sizeof(lv_style_property_t) + sizeof(lv_color_t));
lv_style_property_t end_mark = _LV_STYLE_CLOSEING_PROP;
uint8_t end_mark_size = sizeof(end_mark);
uint16_t size = _lv_style_get_mem_size(style);
if(size == 0) size += end_mark_size;
size += sizeof(lv_style_property_t) + sizeof(lv_color_t);
style_resize(style, size);
LV_ASSERT_MEM(style->map);
if(style == NULL) return;
_lv_memcpy_small(style->map + size - new_prop_size - end_mark_size, &prop, sizeof(lv_style_property_t));
_lv_memcpy_small(style->map + size - sizeof(lv_color_t) - end_mark_size, &color, sizeof(lv_color_t));
_lv_memcpy_small(style->map + size - end_mark_size, &end_mark, sizeof(end_mark));
}
/**
* Set an opacity typed property in a style.
* @param style pointer to a style where the property should be set
* @param prop a style property ORed with a state.
* E.g. `LV_STYLE_BORDER_OPA | (LV_STATE_PRESSED << LV_STYLE_STATE_POS)`
* @param value the value to set
* @note shouldn't be used directly. Use the specific property set functions instead.
* For example: `lv_style_set_border_opa()`
* @note for performance reasons it's not checked if the property really has opacity type
*/
void _lv_style_set_opa(lv_style_t * style, lv_style_property_t prop, lv_opa_t opa)
{
LV_ASSERT_STYLE(style);
int32_t id = get_property_index(style, prop);
/*The property already exists but not sure it's state is the same*/
if(id >= 0) {
lv_style_attr_t attr_found;
lv_style_attr_t attr_goal;
attr_found = get_style_prop_attr(style, id);
attr_goal = (prop >> 8) & 0xFFU;
if(LV_STYLE_ATTR_GET_STATE(attr_found) == LV_STYLE_ATTR_GET_STATE(attr_goal)) {
_lv_memcpy_small(style->map + id + sizeof(lv_style_property_t), &opa, sizeof(lv_opa_t));
return;
}
}
/*Add new property if not exists yet*/
uint8_t new_prop_size = (sizeof(lv_style_property_t) + sizeof(lv_opa_t));
lv_style_property_t end_mark = _LV_STYLE_CLOSEING_PROP;
uint8_t end_mark_size = sizeof(end_mark);
uint16_t size = _lv_style_get_mem_size(style);
if(size == 0) size += end_mark_size;
size += sizeof(lv_style_property_t) + sizeof(lv_opa_t);
style_resize(style, size);
LV_ASSERT_MEM(style->map);
if(style == NULL) return;
_lv_memcpy_small(style->map + size - new_prop_size - end_mark_size, &prop, sizeof(lv_style_property_t));
_lv_memcpy_small(style->map + size - sizeof(lv_opa_t) - end_mark_size, &opa, sizeof(lv_opa_t));
_lv_memcpy_small(style->map + size - end_mark_size, &end_mark, sizeof(end_mark));
}
/**
* Set a pointer typed property in a style.
* @param style pointer to a style where the property should be set
* @param prop a style property ORed with a state.
* E.g. `LV_STYLE_TEXT_POINTER | (LV_STATE_PRESSED << LV_STYLE_STATE_POS)`
* @param value the value to set
* @note shouldn't be used directly. Use the specific property set functions instead.
* For example: `lv_style_set_border_width()`
* @note for performance reasons it's not checked if the property is really has pointer type
*/
void _lv_style_set_ptr(lv_style_t * style, lv_style_property_t prop, const void * p)
{
LV_ASSERT_STYLE(style);
int32_t id = get_property_index(style, prop);
/*The property already exists but not sure it's state is the same*/
if(id >= 0) {
lv_style_attr_t attr_found;
lv_style_attr_t attr_goal;
attr_found = get_style_prop_attr(style, id);
attr_goal = (prop >> 8) & 0xFFU;
if(LV_STYLE_ATTR_GET_STATE(attr_found) == LV_STYLE_ATTR_GET_STATE(attr_goal)) {
_lv_memcpy_small(style->map + id + sizeof(lv_style_property_t), &p, sizeof(const void *));
return;
}
}
/*Add new property if not exists yet*/
uint8_t new_prop_size = (sizeof(lv_style_property_t) + sizeof(const void *));
lv_style_property_t end_mark = _LV_STYLE_CLOSEING_PROP;
uint8_t end_mark_size = sizeof(end_mark);
uint16_t size = _lv_style_get_mem_size(style);
if(size == 0) size += end_mark_size;
size += sizeof(lv_style_property_t) + sizeof(const void *);
style_resize(style, size);
LV_ASSERT_MEM(style->map);
if(style == NULL) return;
_lv_memcpy_small(style->map + size - new_prop_size - end_mark_size, &prop, sizeof(lv_style_property_t));
_lv_memcpy_small(style->map + size - sizeof(const void *) - end_mark_size, &p, sizeof(const void *));
_lv_memcpy_small(style->map + size - end_mark_size, &end_mark, sizeof(end_mark));
}
/**
* Get the a property from a style.
* Take into account the style state and return the property which matches the best.
* @param style pointer to a style where to search
* @param prop the property, might contain ORed style states too
* @param res buffer to store the result
* @return the weight of the found property (how well it fits to the style state).
* Higher number is means better fit
* -1 if the not found (`res` will be undefined)
*/
int16_t _lv_style_get_int(const lv_style_t * style, lv_style_property_t prop, void * v_res)
{
lv_style_int_t * res = (lv_style_int_t *)v_res;
LV_ASSERT_STYLE(style);
if(style == NULL) return -1;
if(style->map == NULL) return -1;
int32_t id = get_property_index(style, prop);
if(id < 0) {
return -1;
}
else {
_lv_memcpy_small(res, &style->map[id + sizeof(lv_style_property_t)], sizeof(lv_style_int_t));
lv_style_attr_t attr_act;
attr_act = get_style_prop_attr(style, id);
lv_style_attr_t attr_goal;
attr_goal = (prop >> 8) & 0xFF;
return LV_STYLE_ATTR_GET_STATE(attr_act) & LV_STYLE_ATTR_GET_STATE(attr_goal);
}
}
/**
* Get an opacity typed property from a style.
* @param style pointer to a style from where the property should be get
* @param prop a style property ORed with a state.
* E.g. `LV_STYLE_BORDER_OPA | (LV_STATE_PRESSED << LV_STYLE_STATE_POS)`
* @param res pointer to a buffer to store the result value
* @return -1: the property wasn't found in the style.
* The matching state bits of the desired state (in `prop`) and the best matching property's state
* Higher value means match in higher precedence state.
* @note shouldn't be used directly. Use the specific property get functions instead.
* For example: `lv_style_get_border_opa()`
* @note for performance reasons it's not checked if the property really has opacity type
*/
int16_t _lv_style_get_opa(const lv_style_t * style, lv_style_property_t prop, void * v_res)
{
lv_opa_t * res = (lv_opa_t *)v_res;
LV_ASSERT_STYLE(style);
if(style == NULL) return -1;
if(style->map == NULL) return -1;
int32_t id = get_property_index(style, prop);
if(id < 0) {
return -1;
}
else {
_lv_memcpy_small(res, &style->map[id + sizeof(lv_style_property_t)], sizeof(lv_opa_t));
lv_style_attr_t attr_act;
attr_act = get_style_prop_attr(style, id);
lv_style_attr_t attr_goal;
attr_goal = (prop >> 8) & 0xFF;
return LV_STYLE_ATTR_GET_STATE(attr_act) & LV_STYLE_ATTR_GET_STATE(attr_goal);
}
}
/**
* Get a color typed property from a style.
* @param style pointer to a style from where the property should be get
* @param prop a style property ORed with a state.
* E.g. `LV_STYLE_BORDER_COLOR | (LV_STATE_PRESSED << LV_STYLE_STATE_POS)`
* @param res pointer to a buffer to store the result value
* @return -1: the property wasn't found in the style.
* The matching state bits of the desired state (in `prop`) and the best matching property's state
* Higher value means match in higher precedence state.
* @note shouldn't be used directly. Use the specific property get functions instead.
* For example: `lv_style_get_border_color()`
* @note for performance reasons it's not checked if the property really has color type
*/
int16_t _lv_style_get_color(const lv_style_t * style, lv_style_property_t prop, void * v_res)
{
lv_color_t * res = (lv_color_t *)v_res;
if(style == NULL) return -1;
if(style->map == NULL) return -1;
int32_t id = get_property_index(style, prop);
if(id < 0) {
return -1;
}
else {
_lv_memcpy_small(res, &style->map[id + sizeof(lv_style_property_t)], sizeof(lv_color_t));
lv_style_attr_t attr_act;
attr_act = get_style_prop_attr(style, id);
lv_style_attr_t attr_goal;
attr_goal = (prop >> 8) & 0xFF;
return LV_STYLE_ATTR_GET_STATE(attr_act) & LV_STYLE_ATTR_GET_STATE(attr_goal);
}
}
/**
* Get a pointer typed property from a style.
* @param style pointer to a style from where the property should be get
* @param prop a style property ORed with a state.
* E.g. `LV_STYLE_TEXT_FONT | (LV_STATE_PRESSED << LV_STYLE_STATE_POS)`
* @param res pointer to a buffer to store the result value
* @return -1: the property wasn't found in the style.
* The matching state bits of the desired state (in `prop`) and the best matching property's state
* Higher value means match in higher precedence state.
* @note shouldn't be used directly. Use the specific property get functions instead.
* For example: `lv_style_get_text_font()`
* @note for performance reasons it's not checked if the property really has pointer type
*/
int16_t _lv_style_get_ptr(const lv_style_t * style, lv_style_property_t prop, void * v_res)
{
const void ** res = (const void **)v_res;
if(style == NULL) return -1;
if(style->map == NULL) return -1;
int32_t id = get_property_index(style, prop);
if(id < 0) {
return -1;
}
else {
_lv_memcpy_small(res, &style->map[id + sizeof(lv_style_property_t)], sizeof(const void *));
lv_style_attr_t attr_act;
attr_act = get_style_prop_attr(style, id);
lv_style_attr_t attr_goal;
attr_goal = (prop >> 8) & 0xFF;
return LV_STYLE_ATTR_GET_STATE(attr_act) & LV_STYLE_ATTR_GET_STATE(attr_goal);
}
}
/**
* Get the local style of a style list
* @param list pointer to a style list where the local property should be set
* @return pointer to the local style if exists else `NULL`.
*/
lv_style_t * lv_style_list_get_local_style(lv_style_list_t * list)
{
LV_ASSERT_STYLE_LIST(list);
if(!list->has_local) return NULL;
if(list->has_trans) return list->style_list[1];
else return list->style_list[0];
}
/**
* Get the transition style of a style list
* @param list pointer to a style list where the local property should be set
* @return pointer to the transition style if exists else `NULL`.
*/
lv_style_t * _lv_style_list_get_transition_style(lv_style_list_t * list)
{
LV_ASSERT_STYLE_LIST(list);
if(!list->has_trans) return NULL;
return list->style_list[0];
}
/**
* Allocate the transition style in a style list. If already exists simply return it.
* @param list pointer to a style list
* @return the transition style of a style list
*/
lv_style_t * _lv_style_list_add_trans_style(lv_style_list_t * list)
{
LV_ASSERT_STYLE_LIST(list);
if(list->has_trans) return _lv_style_list_get_transition_style(list);
lv_style_t * trans_style = lv_mem_alloc(sizeof(lv_style_t));
LV_ASSERT_MEM(trans_style);
if(trans_style == NULL) {
LV_LOG_WARN("lv_style_list_add_trans_style: couldn't create transition style");
return NULL;
}
lv_style_init(trans_style);
_lv_style_list_add_style(list, trans_style);
list->has_trans = 1;
/*If the list has local style trans was added after it. But trans should be the first so swap them*/
if(list->has_local) {
lv_style_t * tmp = list->style_list[0];
list->style_list[0] = list->style_list[1];
list->style_list[1] = tmp;
}
return trans_style;
}
/**
* Set a local integer typed property in a style list.
* @param list pointer to a style list where the local property should be set
* @param prop a style property ORed with a state.
* E.g. `LV_STYLE_BORDER_WIDTH | (LV_STATE_PRESSED << LV_STYLE_STATE_POS)`
* @param value the value to set
* @note for performance reasons it's not checked if the property really has integer type
*/
void _lv_style_list_set_local_int(lv_style_list_t * list, lv_style_property_t prop, lv_style_int_t value)
{
LV_ASSERT_STYLE_LIST(list);
lv_style_t * local = get_alloc_local_style(list);
_lv_style_set_int(local, prop, value);
}
/**
* Set a local opacity typed property in a style list.
* @param list pointer to a style list where the local property should be set
* @param prop a style property ORed with a state.
* E.g. `LV_STYLE_BORDER_OPA | (LV_STATE_PRESSED << LV_STYLE_STATE_POS)`
* @param value the value to set
* @note for performance reasons it's not checked if the property really has opacity type
*/
void _lv_style_list_set_local_opa(lv_style_list_t * list, lv_style_property_t prop, lv_opa_t value)
{
LV_ASSERT_STYLE_LIST(list);
lv_style_t * local = get_alloc_local_style(list);
_lv_style_set_opa(local, prop, value);
}
/**
* Set a local color typed property in a style list.
* @param list pointer to a style list where the local property should be set
* @param prop a style property ORed with a state.
* E.g. `LV_STYLE_BORDER_COLOR | (LV_STATE_PRESSED << LV_STYLE_STATE_POS)`
* @param value the value to set
* @note for performance reasons it's not checked if the property really has color type
*/
void _lv_style_list_set_local_color(lv_style_list_t * list, lv_style_property_t prop, lv_color_t value)
{
LV_ASSERT_STYLE_LIST(list);
lv_style_t * local = get_alloc_local_style(list);
_lv_style_set_color(local, prop, value);
}
/**
* Set a local pointer typed property in a style list.
* @param list pointer to a style list where the local property should be set
* @param prop a style property ORed with a state.
* E.g. `LV_STYLE_TEXT_FONT | (LV_STATE_PRESSED << LV_STYLE_STATE_POS)`
* @param value the value to set
* @note for performance reasons it's not checked if the property really has pointer type
*/
void _lv_style_list_set_local_ptr(lv_style_list_t * list, lv_style_property_t prop, const void * value)
{
LV_ASSERT_STYLE_LIST(list);
lv_style_t * local = get_alloc_local_style(list);
_lv_style_set_ptr(local, prop, value);
}
/**
* Get an integer typed property from a style list.
* It will return the property which match best with given state.
* @param list pointer to a style list from where the property should be get
* @param prop a style property ORed with a state.
* E.g. `LV_STYLE_BORDER_WIDTH | (LV_STATE_PRESSED << LV_STYLE_STATE_POS)`
* @param res pointer to a buffer to store the result
* @return LV_RES_OK: there was a matching property in the list
* LV_RES_INV: there was NO matching property in the list
* @note for performance reasons it's not checked if the property really has integer type
*/
lv_res_t _lv_style_list_get_int(lv_style_list_t * list, lv_style_property_t prop, lv_style_int_t * res)
{
LV_ASSERT_STYLE_LIST(list);
if(list == NULL) return LV_RES_INV;
if(list->style_list == NULL) return LV_RES_INV;
lv_style_attr_t attr;
attr = prop >> 8;
int16_t weight_goal = attr;
int16_t weight = -1;
lv_style_int_t value_act = 0;
int16_t ci;
for(ci = 0; ci < list->style_cnt; ci++) {
/* changed class to _class to allow compilation as c++ */
lv_style_t * _class = lv_style_list_get_style(list, ci);
int16_t weight_act = _lv_style_get_int(_class, prop, &value_act);
/*On perfect match return the value immediately*/
if(weight_act == weight_goal) {
*res = value_act;
return LV_RES_OK;
}
else if(list->has_trans && weight_act >= 0 && ci == 0 && !list->skip_trans) {
*res = value_act;
return LV_RES_OK;
}
/*If the found ID is better the current candidate then use it*/
else if(weight_act > weight) {
weight = weight_act;
*res = value_act;
}
}
if(weight >= 0) return LV_RES_OK;
else return LV_RES_INV;
}
/**
* Get a color typed property from a style list.
* It will return the property which match best with given state.
* @param list pointer to a style list from where the property should be get
* @param prop a style property ORed with a state.
* E.g. `LV_STYLE_BORDER_COLOR | (LV_STATE_PRESSED << LV_STYLE_STATE_POS)`
* @param res pointer to a buffer to store the result
* @return LV_RES_OK: there was a matching property in the list
* LV_RES_INV: there was NO matching property in the list
* @note for performance reasons it's not checked if the property really has color type
*/
lv_res_t _lv_style_list_get_color(lv_style_list_t * list, lv_style_property_t prop, lv_color_t * res)
{
LV_ASSERT_STYLE_LIST(list);
if(list == NULL) return LV_RES_INV;
if(list->style_list == NULL) return LV_RES_INV;
lv_style_attr_t attr;
attr = prop >> 8;
int16_t weight_goal = attr;
int16_t weight = -1;
lv_color_t value_act;
value_act.full = 0;
int16_t ci;
for(ci = 0; ci < list->style_cnt; ci++) {
lv_style_t * _class = lv_style_list_get_style(list, ci);
int16_t weight_act = _lv_style_get_color(_class, prop, &value_act);
/*On perfect match return the value immediately*/
if(weight_act == weight_goal) {
*res = value_act;
return LV_RES_OK;
}
else if(list->has_trans && weight_act >= 0 && ci == 0 && !list->skip_trans) {
*res = value_act;
return LV_RES_OK;
}
/*If the found ID is better the current candidate then use it*/
else if(weight_act > weight) {
weight = weight_act;
*res = value_act;
}
}
if(weight >= 0) return LV_RES_OK;
else return LV_RES_INV;
}
/**
* Get an opacity typed property from a style list.
* It will return the property which match best with given state.
* @param list pointer to a style list from where the property should be get
* @param prop a style property ORed with a state.
* E.g. `LV_STYLE_BORDER_OPA| (LV_STATE_PRESSED << LV_STYLE_STATE_POS)`
* @param res pointer to a buffer to store the result
* @return LV_RES_OK: there was a matching property in the list
* LV_RES_INV: there was NO matching property in the list
* @note for performance reasons it's not checked if the property really has opacity type
*/
lv_res_t _lv_style_list_get_opa(lv_style_list_t * list, lv_style_property_t prop, lv_opa_t * res)
{
LV_ASSERT_STYLE_LIST(list);
if(list == NULL) return LV_RES_INV;
if(list->style_list == NULL) return LV_RES_INV;
lv_style_attr_t attr;
attr = prop >> 8;
int16_t weight_goal = attr;
int16_t weight = -1;
lv_opa_t value_act = LV_OPA_TRANSP;
int16_t ci;
for(ci = 0; ci < list->style_cnt; ci++) {
lv_style_t * _class = lv_style_list_get_style(list, ci);
int16_t weight_act = _lv_style_get_opa(_class, prop, &value_act);
/*On perfect match return the value immediately*/
if(weight_act == weight_goal) {
*res = value_act;
return LV_RES_OK;
}
else if(list->has_trans && weight_act >= 0 && ci == 0 && !list->skip_trans) {
*res = value_act;
return LV_RES_OK;
}
/*If the found ID is better the current candidate then use it*/
else if(weight_act > weight) {
weight = weight_act;
*res = value_act;
}
}
if(weight >= 0) return LV_RES_OK;
else return LV_RES_INV;
}
/**
* Get a pointer typed property from a style list.
* It will return the property which match best with given state.
* @param list pointer to a style list from where the property should be get
* @param prop a style property ORed with a state.
* E.g. `LV_STYLE_TEXT_FONT | (LV_STATE_PRESSED << LV_STYLE_STATE_POS)`
* @param res pointer to a buffer to store the result
* @return LV_RES_OK: there was a matching property in the list
* LV_RES_INV: there was NO matching property in the list
* @note for performance reasons it's not checked if the property really has pointer type
*/
lv_res_t _lv_style_list_get_ptr(lv_style_list_t * list, lv_style_property_t prop, const void ** res)
{
LV_ASSERT_STYLE_LIST(list);
if(list == NULL) return LV_RES_INV;
if(list->style_list == NULL) return LV_RES_INV;
lv_style_attr_t attr;
attr = prop >> 8;
int16_t weight_goal = attr;
int16_t weight = -1;
const void * value_act;
int16_t ci;
for(ci = 0; ci < list->style_cnt; ci++) {
lv_style_t * _class = lv_style_list_get_style(list, ci);
int16_t weight_act = _lv_style_get_ptr(_class, prop, &value_act);
/*On perfect match return the value immediately*/
if(weight_act == weight_goal) {
*res = value_act;
return LV_RES_OK;
}
else if(list->has_trans && weight_act >= 0 && ci == 0 && !list->skip_trans) {
*res = value_act;
return LV_RES_OK;
}
/*If the found ID is better the current candidate then use it*/
else if(weight_act > weight) {
weight = weight_act;
*res = value_act;
}
}
if(weight >= 0) return LV_RES_OK;
else return LV_RES_INV;
}
/**
* Check whether a style is valid (initialized correctly)
* @param style pointer to a style
* @return true: valid
*/
bool lv_debug_check_style(const lv_style_t * style)
{
if(style == NULL) return true; /*NULL style is still valid*/
#if LV_USE_ASSERT_STYLE
if(style->sentinel != LV_DEBUG_STYLE_SENTINEL_VALUE) {
LV_LOG_WARN("Invalid style (local variable or not initialized?)");
return false;
}
#endif
return true;
}
/**
* Check whether a style list is valid (initialized correctly)
* @param style pointer to a style
* @return true: valid
*/
bool lv_debug_check_style_list(const lv_style_list_t * list)
{
if(list == NULL) return true; /*NULL list is still valid*/
#if LV_USE_ASSERT_STYLE
if(list->sentinel != LV_DEBUG_STYLE_LIST_SENTINEL_VALUE) {
LV_LOG_WARN("Invalid style (local variable or not initialized?)");
return false;
}
#endif
return true;
}
/**********************
* STATIC FUNCTIONS
**********************/
/**
* Get a property's index (byte index in `style->map`) from a style.
* Return best matching property's index considering the state of `prop`
* @param style pointer to a style
* @param prop a style property ORed with a state.
* E.g. `LV_STYLE_TEXT_FONT | (LV_STATE_PRESSED << LV_STYLE_STATE_POS)`
* @return
*/
LV_ATTRIBUTE_FAST_MEM static inline int32_t get_property_index(const lv_style_t * style, lv_style_property_t prop)
{
LV_ASSERT_STYLE(style);
if(style->map == NULL) return -1;
uint8_t id_to_find = prop & 0xFF;
lv_style_attr_t attr;
attr = (prop >> 8) & 0xFF;
int16_t weight = -1;
int16_t id_guess = -1;
size_t i = 0;
uint8_t prop_id;
while((prop_id = get_style_prop_id(style, i)) != _LV_STYLE_CLOSEING_PROP) {
if(prop_id == id_to_find) {
lv_style_attr_t attr_i;
attr_i = get_style_prop_attr(style, i);
/*If the state perfectly matches return this property*/
if(LV_STYLE_ATTR_GET_STATE(attr_i) == LV_STYLE_ATTR_GET_STATE(attr)) {
return i;
}
/* Be sure the property not specifies other state than the requested.
* E.g. For HOVER+PRESS, HOVER only is OK, but HOVER+FOCUS not*/
else if((LV_STYLE_ATTR_GET_STATE(attr_i) & (~LV_STYLE_ATTR_GET_STATE(attr))) == 0) {
/* Use this property if it describes better the requested state than the current candidate.
* E.g. for HOVER+FOCUS+PRESS prefer HOVER+FOCUS over FOCUS*/
if(LV_STYLE_ATTR_GET_STATE(attr_i) > weight) {
weight = LV_STYLE_ATTR_GET_STATE(attr_i);
id_guess = i;
}
}
}
i = get_next_prop_index(prop_id, i);
}
return id_guess;
}
/**
* Get he local style from a style list. Allocate it if not exists yet.
* @param list pointer to a style list
* @return pointer to the local style
*/
static lv_style_t * get_alloc_local_style(lv_style_list_t * list)
{
LV_ASSERT_STYLE_LIST(list);
if(list->has_local) return lv_style_list_get_style(list, list->has_trans ? 1 : 0);
lv_style_t * local_style = lv_mem_alloc(sizeof(lv_style_t));
LV_ASSERT_MEM(local_style);
if(local_style == NULL) {
LV_LOG_WARN("get_local_style: couldn't create local style");
return NULL;
}
lv_style_init(local_style);
/*Add the local style to the first place*/
_lv_style_list_add_style(list, local_style);
list->has_local = 1;
return local_style;
}
/**
* Resizes a style map. Useful entry point for debugging.
* @param style pointer to the style to be resized.
* @param size new size
*/
static inline void style_resize(lv_style_t * style, size_t sz)
{
style->map = lv_mem_realloc(style->map, sz);
}
/**
* Get style property in index.
* @param style pointer to style.
* @param idx index of the style in style->map
* @return property in style->map + idx
*/
static inline lv_style_property_t get_style_prop(const lv_style_t * style, size_t idx)
{
lv_style_property_t prop;
uint8_t * prop_p = (uint8_t *)∝
prop_p[0] = style->map[idx];
prop_p[1] = style->map[idx + 1];
return prop;
}
/**
* Get style property id in index.
* @param style pointer to style.
* @param idx index of the style in style->map
* @return id of property in style->map + idx
*/
static inline uint8_t get_style_prop_id(const lv_style_t * style, size_t idx)
{
return get_style_prop(style, idx) & 0xFF;
}
/**
* Get style property attributes for index.
* @param style pointer to style.
* @param idx index of the style in style->map
* @return attribute of property in style->map + idx
*/
static inline uint8_t get_style_prop_attr(const lv_style_t * style, size_t idx)
{
return ((get_style_prop(style, idx) >> 8) & 0xFFU);
}
/**
* Get property size.
* @param prop_id property id.
* @param idx index of the style in style->map
* @return attribute of property in style->map + idx
*/
static inline size_t get_prop_size(uint8_t prop_id)
{
prop_id &= 0xF;
size_t size = sizeof(lv_style_property_t);
if(prop_id < LV_STYLE_ID_COLOR) size += sizeof(lv_style_int_t);
else if(prop_id < LV_STYLE_ID_OPA) size += sizeof(lv_color_t);
else if(prop_id < LV_STYLE_ID_PTR) size += sizeof(lv_opa_t);
else size += sizeof(const void *);
return size;
}
/**
* Get next property index, given current property and index.
* @param prop_id property id.
* @param idx index of the style in style->map
* @return index of next property in style->map
*/
static inline size_t get_next_prop_index(uint8_t prop_id, size_t idx)
{
return idx + get_prop_size(prop_id);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//行列を出力
void disp(double **a,double *b,int N){
int i,j;
printf("A,b=\n");
for (i=0;i<N;i++){
for (j=0;j<N;j++){
printf("%7.2f ",a[i][j]);
}
printf("| %6.2f\n",b[i]);
}
}
//ガウスの消去法
void gdeletion(double **a, double *b,int N){
int i,j,k;
double r;
//前進消去
for (k=0;k<N-1;k++){
disp(a,b,N);
for (i=k+1;i<N;i++){
r=a[i][k]/a[k][k];
for (j=k;j<N;j++){
a[i][j]-=a[k][j]*r;
}
b[i]-=b[k]*r;
}
}
//後退代入
for (i=N-1;i>=0;i--){
disp(a,b,N);
for (j=i+1;j<N;j++){
b[i]-=a[i][j]*b[j];
}
b[i]/=a[i][i];
}
disp(a,b,N);
}
int main(void){
int N,i,j;
double **a,*b;
printf("N=");
scanf("%d",&N);
//メモリの確保
a=(double **)malloc(sizeof(double *)*(N+1));
if (a==NULL){
printf("error");
exit(1);
}
for (i=0;i<N;i++){
a[i]=(double *)malloc(sizeof(double)*(N+1));
if (a[i]==NULL){
printf("error");
exit(1);
}
}
b=(double *)malloc(sizeof(double *)*(N+1));
if (b==NULL){
printf("error");
exit(1);
}
//数値代入
double d;
for (i=0;i<N;i++){
for (j=0;j<N;j++){
printf("A[%d][%d]=",i,j);
scanf("%lf",&d);
a[i][j]=d;
}
}
for (i=0;i<N;i++){
printf("b[%d]=",i);
scanf("%lf",&d);
b[i]=d;
}
//計算
gdeletion(a,b,N);
return 0;
}
|
C
|
/** \brief Apertura del archivo y llamado a funcion parser.
*
* \param path char* Ruta del archivo.
* \param pArrayListEmployee LinkedList*
* \return int 1 apertura y carga correcta, 0 error.
*
*/
int controller_loadFromText(char* path , LinkedList* pArrayListEmployee);
/** \brief Apertura del archivo y llamado a funcion parser.
*
* \param path char* Ruta del archivo.
* \param pArrayListEmployee LinkedList*
* \return int int 1 apertura y carga correcta, 0 error.
*
*/
int controller_loadFromBinary(char* path , LinkedList* pArrayListEmployee);
/** \brief Agrega un empleado a la LinkedList.
*
* \param pArrayListEmployee LinkedList*
* \return int 1 empleado agregado correctamente, 0 no se pudo agregar al empleado.
*
*/
int controller_addEmployee(LinkedList* pArrayListEmployee);
/** \brief Edita un empleado de la LinkedList.
*
* \param pArrayListEmployee LinkedList*
* \return int 1 empleado editado correctamente, 0 no se pudo editar el empleado.
*
*/
int controller_editEmployee(LinkedList* pArrayListEmployee);
/** \brief Elimina un empleado de la LinkedList.
*
* \param pArrayListEmployee LinkedList*
* \return int 1 empleado eliminado correctamente, 0 no se pudo eliminar el empleado.
*
*/
int controller_removeEmployee(LinkedList* pArrayListEmployee);
/** \brief Lista los empleados cargados en la LinkedList.
*
* \param pArrayListEmployee LinkedList*
* \return int 1 listado correcto.
*
*/
int controller_ListEmployee(LinkedList* pArrayListEmployee);
/** \brief Menu para elegir el criterio de ordenamiento.
*
* \param pArrayListEmployee LinkedList*
* \return int 1 ordenamiento correcto.
*
*/
int controller_sortEmployee(LinkedList* pArrayListEmployee);
/** \brief Guarda lo cargado en la LinkedList separado por coma.
*
* \param path char* Ruta del archivo
* \param pArrayListEmployee LinkedList*
* \return int 1 carga correcta, 0 no se pudo cargar.
*
*/
int controller_saveAsText(char* path , LinkedList* pArrayListEmployee);
/** \brief Guarda lo cargado en la LinkedList en formato binario.
*
* \param path char* Ruta del archivo.
* \param pArrayListEmployee LinkedList*
* \return int int 1 carga correcta, 0 no se pudo cargar.
*/
int controller_saveAsBinary(char* path , LinkedList* pArrayListEmployee);
/** \brief Muestra un meno para modificar un empleado.
*
* \param listaEmpleados LinkedList* LinkedList.
* \param empleado void* Puntero a empleado.
* \param index int Indice donde se encuentra el empleado en la LinkedList.
* \return int 1 modificacion correcta, 0 no se pudo modificar
*
*/
int menuModificaciones(LinkedList* listaEmpleados,void* empleado,int index);
|
C
|
/*****************************************************************************************
* Author: Jacob Karcz
* Date: 5.29.2017
* Course: CS372-400: Intro to Computer Networks
* Program 2: ftserver.c - file transfer servce application
* Description: This is the server for a file transfer service application.
* Runs a server process that waits for clients to request files or directory contents.
* Spins a new thread for each connecting client, services its directory change,
* file transfer, or directory listing request through the client's data port (when
* approproate), and then closes the data connection.
* Able to transfer binary files including large files (tested to 950MB)
* Note: username & password for verification are admin/password
******************************************************************************************/
/* headers
------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <pthread.h>
#include <dirent.h>
#include <fcntl.h>
#include <errno.h>
#include <assert.h>
#include <signal.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
/* constants
------------*/
#define BUFFER_SIZE 2000
#define DEBUG 0
/* Functions
----------------------------*/
void exitError(const char *msg);
void error(const char *msg);
int serverHandshake(int connectionFD, char* clientProcess, char* serverProcess);
int startup (int socketFD);
int openDataSocket (int dataPort, char* host);
void* ftpFunk(void*);
void ls(int dataSocket, char* host);
void sendFile(int dataPort, char* fileName, char* host);
int authenticate(char* authentication);
/*******************************************************************************************
* Function: int main(int argc, char *argv[])
* Description: main function of the file transfer service server, allows clients to
* connect and services their requests on separate threads.
* Parameters: argv[0] is the program's name
* argv[1] is the server's port number
* Pre-Conditions: none
* Post-Conditions: The server will run until closed with SIGINT, servicing clients requests.
********************************************************************************************/
int main(int argc, char *argv[]) {
//variables
int serverPort,
serverSocket,
clientSocket;
char host[1024],
service[20];
struct sockaddr_in serverAddress,
clientAddress;
socklen_t sizeOfClientInfo;
pthread_t clienThread;
//check usage & args
if (argc != 2) { fprintf(stderr,"USAGE: %s <port>\n", argv[0]); exit(1); }
//set up listening socket
serverPort = atoi(argv[1]);
serverSocket = startup (serverPort);
printf("File Transfer Server open on port %d\n", serverPort);
listen(serverSocket, 5); // Flip the socket on - it can now receive up to 5 connections
sizeOfClientInfo = sizeof(clientAddress); // Get the size of the address for the client
//wait for clients
while(1) {
clientSocket = accept(serverSocket, (struct sockaddr *)&clientAddress, &sizeOfClientInfo); // Accept
getnameinfo(&clientAddress, sizeof(clientAddress), host, sizeof(host), service, sizeof(service), 0);
printf("connection received from %s\n", host);
if (clientSocket < 0) error("ERROR on accept");
if (pthread_create(&clienThread, NULL, ftpFunk, (void*)&clientSocket) < 0) //threadz! :)
error("ERROR on thread creation"); //no threads :(
}
close(serverSocket); // Close the listening socket
return 0;
}
/*******************************************************************************************
* Function: int startup( int serverPort)
* Description: Function to set up the server's listening (control) socket
* Parameters: The port number where the server will service clients
* Pre-Conditions: None
* Post-Conditions: The server's control socket is initialized and ready to start listening.
* Returns: The server socket, properly initialized.
*******************************************************************************************/
int startup( int serverPort) {
struct sockaddr_in serverAddress;
int listenSocketFD;
// Set up the address struct for this process (the server)
memset((char *)&serverAddress, '\0', sizeof(serverAddress)); // Clear out the address struct
serverAddress.sin_family = AF_INET; // Create a network-capable socket
serverAddress.sin_port = htons(serverPort); // Store the port number
serverAddress.sin_addr.s_addr = INADDR_ANY; // Any address is allowed for connection to this process
// Set up the socket
listenSocketFD = socket(AF_INET, SOCK_STREAM, 0); // Create the socket
if (listenSocketFD < 0) exitError("ERROR opening control/listening socket");
//Bind the socket
if (bind(listenSocketFD, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0) // Connect socket to port or bust
exitError("ERROR on binding control/listening socket");
return listenSocketFD;
}
/*******************************************************************************************
* Function: int openDataSocket(int dataPort, char* host)
* Description: Function to set up the server's data transfer socket
* Parameters: The client's hostname and data transfer port
* Pre-Conditions: The server and client are ready to exchange data through the socket
* Post-Conditions: The server's data transfer socket is initialized and connected to the client
* Returns: The data socket, connected to the client process.
********************************************************************************************/
int openDataSocket(int dataPort, char* host) {
struct sockaddr_in serverAddress;
struct hostent *serverHost;
int dataSocketFD;
//prep for data socket
memset((char *)&serverAddress, '\0', sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(dataPort);
serverHost = gethostbyname(host);
memcpy((char*)&serverAddress.sin_addr.s_addr, (char*)serverHost->h_addr, serverHost->h_length);
// Set up data socket
sleep(1); //bc python is slow
dataSocketFD = socket(AF_INET, SOCK_STREAM, 0);
if (dataSocketFD < 0) error("ERROR opening data socket");
// Connect data socket
if (connect(dataSocketFD, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) != 0)
error("ERROR on connecting data socket");
return dataSocketFD;
}
/*******************************************************************************************
* Function: void* ftpFunk(void* FD)
* Description: The thread's main (logic) function that handles client commands/requests
* Parameters: The sockaddr_in struct for the server/client control connection
* Pre-Conditions: The client and server are connected and FD properly intitialized
* Post-Conditions: The client has been serviced or turned away, when the function terminates
* so does the thread.
********************************************************************************************/
void* ftpFunk(void* FD) {
//variables
int i,
serverSocket,
controlSocket,
dataSocketFT,
serverPort,
dataPort,
charsRead,
terminalLocation,
homeDir,
verifyConnect;
char buffer[BUFFER_SIZE],
commandLine[BUFFER_SIZE],
newDir[200],
fileName[200],
client[50],
clientIP[20];
char* token = NULL; //bc evil strtok works...
struct sockaddr_in serverAddress,
clientAddress;
struct stat findFile;
//clear buffers
memset(commandLine, '\0', sizeof(commandLine));
memset(newDir, '\0', sizeof(newDir));
memset(buffer, '\0', sizeof(buffer));
memset(fileName, '\0', sizeof(fileName));
memset(client, '\0', sizeof(client));
memset(clientIP, '\0', sizeof(clientIP));
//fix the socket
controlSocket = *(int*)FD;
//get client data
charsRead = recv(controlSocket, buffer, sizeof(buffer)-1, 0);
if (charsRead == 0) {printf("No data received, closing connection.\n"); return NULL;}
if (charsRead < 0) {printf("ERROR: failed to receive client data\n"); return NULL;}
//authenticate client
if (authenticate(buffer)) {
memset(buffer, '\0', sizeof(buffer));
sprintf(buffer, "Authentication verified... Access granted");
send(controlSocket, buffer, strlen(buffer), 0);
}
else {
memset(buffer, '\0', sizeof(buffer));
sprintf(buffer, "Verification failed: user name or password are incorrect");
send(controlSocket, buffer, strlen(buffer), 0);
return NULL;
}
memset(buffer, '\0', sizeof(buffer));
charsRead = recv(controlSocket, buffer, sizeof(buffer)-1, 0);
if (charsRead == 0) {printf("No data received, closing connection.\n"); return NULL;}
if (charsRead < 0) {printf("ERROR: failed to receive client data\n"); return NULL;}
//parse out commandline
strcpy(commandLine, buffer);
token = strtok(commandLine, " \n\0");
strcpy(client, token);
token = strtok(NULL, " \n\0");
strcpy(clientIP, token);
printf("Servicing client %s\n", clientIP);
token = strtok(NULL, " \n\0");
if (strncmp(token, "cd", 2) == 0) { //chdir
token = strtok(NULL, " \n\0");
//getcwd()?
//if (token == NULL) { homeDir = getenv("HOME"); }
strcpy(newDir, token);
printf("Server directory change to \"%s\" requested\n", newDir);
int movDir = chdir(newDir);
if (movDir == -1) {
perror("chdir error");
memset(buffer, '\0', sizeof(buffer));
sprintf(buffer, "ERROR: directory change failure");
write(controlSocket, buffer, strlen(buffer));
}
else {
printf("Directory changed successfully\n");
memset(buffer, '\0', sizeof(buffer));
sprintf(buffer, "Success! current directory: %s", newDir);
write(controlSocket, buffer, strlen(buffer));
}
}
else if (strcmp(token, "-l") == 0) { //ls
token = strtok(NULL, " \n\0");
dataPort = atoi(token);
printf("List directory requested on port %d\n", dataPort);
ls(dataPort, clientIP);
}
else if (strcmp(token, "-g") == 0) { //getFile
token = strtok(NULL, " \n\0");
strcpy(fileName, token);
token = strtok(NULL, " \n\0");
dataPort = atoi(token);
printf("File \"%s\" requested on port %d\n", fileName, dataPort);
if (stat(fileName, &findFile) < 0) {
printf("failed to open/locate file, sending error message to %s:%d\n", clientIP, dataPort);
memset(buffer, '\0', sizeof(buffer));
sprintf(buffer, "ERROR: file not found, unable to open \"%s\"", fileName);
send(controlSocket, buffer, strlen(buffer), 0);
//write(controlSocket, buffer, strlen(buffer));
}
else {
memset(buffer, '\0', sizeof(buffer));
sprintf(buffer, "Transfering \"%s\"", fileName);
write(controlSocket, buffer, strlen(buffer));
sendFile(dataPort, fileName, clientIP);
}
}
return NULL;
}
/*******************************************************************************************
* Function: void ls(int dataPort, char* host)
* Description: Function to send current directory contents to the client
* Parameters: The client's hostname and data transfer port
* Pre-Conditions: The client is ready to receive the directory through the data socket
* Post-Conditions: The server sent the requested directory contents to the client
* and closes out the the data socket (created within this function)
********************************************************************************************/
void ls(int dataPort, char* host) {
int dataSocket,
bytesSent;
char sendBuffer[BUFFER_SIZE];
memset(sendBuffer, '\0', sizeof(sendBuffer));
DIR* dir;
struct dirent *dirContent;
fflush(stdout);
printf("Sending directory contents to %s:%d\n", host, dataPort);
fflush(stdout);
dataSocket = openDataSocket(dataPort, host);
dir = opendir(".");
if (dir != NULL) {
while (dirContent = readdir(dir)) {
strcat(sendBuffer, dirContent->d_name);
strcat(sendBuffer, " ");
}
bytesSent = send(dataSocket, sendBuffer, strlen(sendBuffer), 0);
if (bytesSent < 0) error("ERROR writing to socket");
if (bytesSent < strlen(sendBuffer)) {
send(dataSocket, &sendBuffer[bytesSent], strlen(sendBuffer) - bytesSent, 0);
}
}
else error("ERROR: unable to open directory.");
//close out
closedir(dir);
close(dataSocket);
}
/*******************************************************************************************
* Function: void sendFile(int dataPort, char* fileName, char* host)
* Description: Function to send the requested file to the client
* Parameters: The client's hostname, data transfer port, and file name of wanted file
* Pre-Conditions: The client is ready to receive the file through the data socket
* Post-Conditions: The server sent the requested file to the client and closes out the
* the data socket (created within this function)
********************************************************************************************/
void sendFile(int dataPort, char* fileName, char* host) {
int dataSocket,
fileSize,
bytesRead,
bytesWritten,
bytesSent;
int fileFD;
char sendBuffer[BUFFER_SIZE];
memset(sendBuffer, '\0', sizeof(sendBuffer));
fflush(stdout);
printf("Sending \"%s\" to %s:%d\n", fileName, host, dataPort);
fflush(stdout);
dataSocket = openDataSocket(dataPort, host);
//open the file & copy it to buffer
fileFD = open(fileName, O_RDONLY);
if (fileFD < 1) {
fprintf(stderr, "error opening %s\n", fileName);
bytesWritten = send(dataSocket, "error, file not found or could not be opened\n", 45, 0);
if (bytesWritten < 0) error("ERROR writing to socket");
return;
}
fileSize = lseek(fileFD, 0, SEEK_END);
if(DEBUG) { printf("file size: %d bytes\n", fileSize); }
int pos = lseek(fileFD, 0, SEEK_SET);
//"small" files to 1 MB
if (fileSize < 1000000) {
char fileBuffer[fileSize + 1];
memset(fileBuffer, '\0', sizeof(fileBuffer));
bytesRead = read(fileFD, fileBuffer, sizeof(fileBuffer)-1);
if(DEBUG) { printf("file bytes read: %d bytes\n", bytesRead); }
//send the file contents (using memcpy instead of strcpy so it can send binary)
bytesSent = 0;
if (fileSize < BUFFER_SIZE) {
bytesWritten = send(dataSocket, fileBuffer, fileSize, 0);
if (bytesWritten < 0) { error("ERROR writing to socket"); }
}
else {
while (bytesSent <= fileSize){
if ((fileSize - bytesSent) < BUFFER_SIZE) {
memset(sendBuffer, '\0', sizeof(sendBuffer));
memcpy(sendBuffer, &fileBuffer[bytesSent], fileSize - bytesSent);
bytesWritten = send(dataSocket, sendBuffer, fileSize - bytesSent, 0);
if (bytesWritten < 0) { error("ERROR writing to socket"); break; }
bytesSent += bytesWritten;
if(DEBUG){
printf("bytes sent(now): %d\nbytes sent(total): %d\n", bytesWritten, bytesSent);
}
break;
}
//part out the fileBuffer
memset(sendBuffer, '\0', sizeof(sendBuffer));
memcpy(sendBuffer, &fileBuffer[bytesSent], BUFFER_SIZE-1);
//send
bytesWritten = send(dataSocket, sendBuffer, BUFFER_SIZE-1, 0);
if (bytesWritten < 0) { error("ERROR writing to socket"); break; }
bytesSent += bytesWritten;
//bytesSent += (BUFFER_SIZE - 1);
if(DEBUG){
printf("bytes sent(now): %d\nbytes sent(total): %d\n", bytesWritten, bytesSent);
}
}
}
close(fileFD);
}
//"big" files to ?
else {
close(fileFD);
size_t fileBytes;
ssize_t chunkSize;
char* fileChunk = NULL;
FILE* file = fopen(fileName, "r");
while ((chunkSize = getline(&fileChunk, &fileBytes, file)) != -1) {
bytesSent = send(dataSocket, fileChunk, chunkSize, 0);
if (bytesSent < 0) { error("ERROR writing to socket"); break; }
}
free(fileChunk);
fclose(file);
}
close(dataSocket);
}
/*******************************************************************************************
* Function: int authenticate(char* authentication)
* Description: Function to verify the connecting client
* Parameters: A string containing the user name and password as a single string
* (no extra chars or white space between the user name and password)
* Pre-Conditions: The string received should match the string bellow (in function)
* Post-Conditions: Returns true (1) if the strings match, otherwise returns false (0)
********************************************************************************************/
int authenticate(char* authentication) {
printf("Authenticating user... ");
//authentication(username+password) must match the string bellow!
if (strcmp(authentication, "adminpassword") != 0) {
printf("\n... authentication failed.\n");
return 0;
}
else {
printf("\n... authentication verified.\n");
return 1;
}
}
/****************************************************
* process connection verification function
***************************************************/
int serverHandshake(int connectionFD, char* clientProcess, char* serverProcess) {
//variables
int charsRead;
char buffer[128];
memset(buffer, '\0', sizeof(buffer));
//read client ID
charsRead = recv(connectionFD, buffer, sizeof(buffer)-1, 0);
if (charsRead < 0) { error("error reading client ID, terminating connection."); return 2;}
//send server ID
send(connectionFD, serverProcess, strlen(serverProcess), 0);
//verify ID
if(strncmp(buffer, clientProcess, charsRead) == 0) {
return 0; //ID verified
}
else {
return 1; //wrong ID
}
}
/****************************************************
* SIGCHILD signal handler function
***************************************************/
void zombies() {
int exitStat;
pid_t zombieChild;
zombieChild = waitpid(-1, &exitStat, WNOHANG);
}
/************************************************************
* Error Reporting Functions
************************************************************/
void exitError(const char *msg) { perror(msg); exit(1); }
void error(const char *msg) { perror(msg); }
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
// Rozważamy wyrażenia arytmetyczne zbudowane z liczb rzeczywistych, operatorów dodawania (+),
// odejmowania (-), mnożenia (*) i dzielenia (/) oraz nawiasów. Operatory są lewostronnie łączne,
// a mnożenie i dzielenie mają wyższy priorytet niż dodawanie i odejmowanie. Takie wyrażenia
// mogą być reprezentowane przez drzewa wyrażenia, gdzie w liściach są liczby, a w węzłach pośrednich
// operatory. Napisać funkcję, która czyta wyrażenie zakończone znakiem średnika i tworzy dla niego
// drzewo wyrażenia. Drzewo powinno być zbudowane z węzłów dynamicznie tworzonych w stercie.
// Druga funkcja powinna wypisywać drzewo wyrażenia na standardowym wyjściu w postaci prefiksowej,
// czyli najpierw operator, a później jego argumenty. Na przykład wyrażenie ((2)+3)*(7-(5));
// powinno zostać wypisane jako (* (+ 2 3) (- 7 5)). Program główny powinien czytać ciągi
// wyrażeń i wypisywać je w postaci prefiksowej.
typedef struct tree_node {
union {
int operation;
double number;
} value;
bool is_number;
struct tree_node * left_node;
struct tree_node * right_node;
} Node;
Node * node_init(bool is_number);
void terminate(char * error);
int char_buffer_pop();
void char_buffer_push(int chr);
void printf_tree(Node * tree);
Node * read_number();
Node * part_of_multiplication();
Node * part_of_sum();
Node * read_and_calculate_expression();
void set_as_negative(Node ** tree);
Node * node_init(bool is_number) {
Node * new_node;
new_node = malloc(sizeof(Node));
new_node->left_node = NULL;
new_node->right_node = NULL;
new_node->is_number = is_number;
return new_node;
}
void terminate(char * error) {
printf("ERROR: %s\n", error);
exit(1);
}
int char_buffer_pop() {
int chr;
while ((chr=getchar()) != EOF && isspace(chr));
return chr;
}
void char_buffer_push(int chr) {
ungetc(chr, stdin);
}
void printf_tree(Node * tree) {
if (tree->is_number) {
printf(" %.2lf", tree->value.number);
} else {
printf(" (%c", tree->value.operation);
printf_tree(tree->left_node);
printf_tree(tree->right_node);
printf(")");
}
}
void set_as_negative(Node ** tree_ptr) {
Node * tree = *tree_ptr;
Node * temp;
if (tree->is_number) {
tree->value.number = -(tree->value.number);
} else {
temp = tree;
tree = node_init(false);
tree->value.operation = '-';
tree->left_node = node_init(true);
tree->left_node->value.number = 0;
tree->right_node = temp;
*tree_ptr = tree;
}
}
Node * read_number() {
int chr;
Node * number_node = node_init(true);
double number = 0.0;
double shift = 1.0;
while ((chr = getchar()) != EOF && isdigit(chr))
number = 10.0 * number + (chr - '0');
if (chr == '.') {
while ((chr = getchar()) != EOF && isdigit(chr)) {
number = 10.0 * number + (chr - '0');
shift *= 10.0;
}
}
char_buffer_push(chr);
number_node->value.number = (number / shift);
return number_node;
}
Node * part_of_multiplication() {
int chr;
Node * result;
bool negative = false;
if ((chr = char_buffer_pop()) == '-')
negative = true;
else
char_buffer_push(chr);
chr = char_buffer_pop();
if (isdigit(chr)) {
char_buffer_push(chr);
result = read_number();
} else if (chr == '(') {
result = read_and_calculate_expression();
if ((chr = char_buffer_pop()) != ')') {
terminate("Illegar char; expected ')'.");
}
} else {
terminate("Illegal char; expected '(' or digit.");
}
if (negative) set_as_negative(&result);
return result;
}
Node * part_of_sum() {
int chr;
Node * tree;
Node * right;
Node * temp;
tree = part_of_multiplication();
while ((chr = char_buffer_pop()) == '*' || chr == '/') {
right = part_of_multiplication();
temp = tree;
tree = node_init(false);
tree->value.operation = chr;
tree->left_node = temp;
tree->right_node = right;
}
char_buffer_push(chr);
return tree;
}
Node * read_and_calculate_expression() {
Node * tree;
Node * right;
Node * temp;
int chr;
tree = part_of_sum();
while ((chr = char_buffer_pop()) == '+' || chr == '-') {
right = part_of_sum();
temp = tree;
tree = node_init(false);
tree->value.operation = chr;
tree->left_node = temp;
tree->right_node = right;
}
char_buffer_push(chr);
return tree;
}
int main() {
int chr;
Node * tree = NULL;
while ((chr = char_buffer_pop()) != EOF) {
char_buffer_push(chr);
tree = read_and_calculate_expression();
if ((chr = char_buffer_pop()) == ';') {
printf_tree(tree);
} else {
terminate("Illegal char.");
}
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#define INITSTRLEN 50
#define ERROR 0
#define OK 1
typedef struct{
char * ch;
int length;
int strsize;
}HString;
typedef int Status;
int replace = 0;
Status StrInit(HString * s)
{
s->ch = (char*)malloc(INITSTRLEN * sizeof(char));
if(!s->ch)
return ERROR;
s->ch[0] = '\0';
s->length = 0;
s->strsize = INITSTRLEN;
return OK;
}
Status CreateStr(HString * s)
{
char c;
int i = 0;
if(StrInit(s))
{
while((c = getchar()) != ' ' && c != '\n')
{
s->ch[i] = c;
i++;
s->length++;
}
}
}
void Replace(HString *a, HString *m, HString *n)
{
int i=0, j=0;
int state = 1;
while(i <= a->length - m->length)
{
j = 0;
if(a->ch[i] == m->ch[j])
{
for(j=0; j<m->length; j++)
{
if(a->ch[i+j] == m->ch[j])
state = 0;
else{
state = 1;
break;
}
}
if(state == 0)
{
for(j=0; j<n->length; j++)
{
a->ch[i] = n->ch[j];
}
a->length = a->length + n->length - m->length;
for(j=i+n->length; j<a->length; j++)
{
a->ch[j] = a->ch[j+m->length-n->length];
}
}
}
if(state == 0)
{
i = i+m->length;
replace = 1;
}else
i = i+1;
}
}
int main()
{
HString *a, *m, *n;
int i = 0;
a = (HString*)malloc(sizeof(HString));
m = (HString*)malloc(sizeof(HString));
n = (HString*)malloc(sizeof(HString));
int lengthA = 0, lengthM = 0, lengthN = 0;
CreateStr(a);
CreateStr(m);
CreateStr(n);
Replace(a, m, n);
if(replace == 1)
for(i=0; i<a->length; i++)
{
printf("%c", a->ch[i]);
}
return 0;
}
|
C
|
/*
* mcu-threads: threading library for embedded systems.
*
* Copyright (C) 2014 Vladislav Levenetz - [email protected]
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <common.h>
#include <platform.h>
#include <arch_api.h>
/* This always points to the currently running thread */
thread_t *current;
/* List of all running threads */
thread_t *running;
/* Initial thread */
static thread_t thread0;
/**
* Checks if this thread is last on the list
*
* @tr: thread to check
*/
#define thr_lonely(tr) ((tr)->next == (tr))
/**
* Adds the very first thread
*
* @tr: pointer to static thread
*/
#define add_first_thread(tr) \
do { \
(tr)->next = (tr); \
(tr)->prev = (tr); \
running = (tr); \
} while (0)
/**
* Inserts a new thread after another thread
*
* @where: pointer to a thread from where to start
* @tr: pointer to the new thread. It will be
* added after @where
*/
#define add_thread_after(where, tr) __add_thread((where), (tr))
/**
* Inserts a new thread before another thread
*
* @where: pointer to a thread from where to start
* @tr: pointer to the new thread. It will be
* added before @where
*/
#define add_thread_before(where, tr) __add_thread((where)->prev, (tr))
/**
* The same as add_thread_after()
*/
static inline void __add_thread(thread_t *where, thread_t *t)
{
thread_t *next;
next = where->next;
where->next = t;
t->prev = where;
t->next = next;
next->prev = t;
}
/**
* Unlinks a thread from the list of running threads.
*
* @t: thread to delete
*
* @notice: t->next, and t->prev are left untouched
* and still points to valid threads
*/
static inline void del_thread(thread_t *t)
{
thread_t *prev, *next;
prev = t->prev;
next = t->next;
prev->next = next;
next->prev = prev;
/* fix the list head pointer */
if (running == t)
running = next;
}
/**
* Puts a thread to sleep.
*
* @wq: wait queue to sleep on
* @t: thread to put to sleep
*
* Move the thread from the list of running threads
* to a defined wait queue. The CPU is given to the
* next thread after this.
*
* @notice: Undefined behaviour if @wq is not initialized.
*/
void thread_sleep(thread_wait_queue *wq, thread_t *t)
{
thread_t *l;
thr_lock();
del_thread(t);
if (!*wq) {
t->prev = t;
*wq = t;
goto sched;
}
l = (*wq)->prev;
(*wq)->prev = t;
l->next = t;
t->prev = l;
sched:
thr_unlock();
thr_sched();
}
/**
* Wakes up all threads in the wait queue.
*
* @wq: wait queue holding sleeping threads.
*
* Appends all threads from the wait queue at the end of
* the list of running threads.
* No context switch will occur after this call.
*/
void thread_wakeup(thread_wait_queue *wq)
{
thread_t *rlast, *slast;
thr_lock();
if (!*wq)
goto exit;
rlast = running->prev;
slast = (*wq)->prev;
rlast->next = (*wq);
(*wq)->prev = rlast;
slast->next = running;
running->prev = slast;
*wq = (void *)0;
exit:
thr_unlock();
}
/**
* Wakes up all threads in the wait queue.
*
* @wq: wait queue holding sleeping threads.
*
* Appends all threads from the wait queue right after
* current and gives the CPU to the first thread immediately.
* No context switch will occur if the wait queue is empty.
*/
void thread_wakeup_now(thread_wait_queue *wq)
{
thread_t *rnext, *slast;
thr_lock();
if (!*wq)
goto exit;
rnext = current->next;
slast = (*wq)->prev;
current->next = *wq;
(*wq)->prev = current;
slast->next = rnext;
rnext->prev = slast;
*wq = (void *)0;
thr_unlock();
thr_sched();
return;
exit:
thr_unlock();
}
/**
* Setups and adds a newly created thread.
*
* @t: new thread to add
* @fn: thread function to execute
*
* The new thread is added at the end of the
* list of running threads.
* No context switch will occur after this call.
*
* @notice: this is called with threads locked.
* @notice: arch should setup the new thread's stack
*/
static inline void add_thread(thread_t *t, void *fn)
{
thr_prepare(t, fn);
add_thread_before(running, t);
}
/**
* Creates a new thread.
*
* @t: new thread to create
* @fn: thread function to execute
*/
void thread_create(thread_t *t, void *fn)
{
thr_lock();
add_thread(t, fn);
thr_unlock();
}
/**
* Terminates a thread.
*
* Permanently unlinks the current thread from
* the list of running threads.
* CPU is given to the next thread in the list.
*/
void thread_exit(void)
{
thr_lock();
if (thr_lonely(current))
while (1); // the only thing we can do is spin
del_thread(current);
thr_unlock();
thr_sched();
}
/**
* Initializes the thread library.
*
* @fn: pointer to thread main function.
*
* The caller must supply a new 'main' function
* which will be executed in threading context.
* This function is the thread function of the
* static thread 0.
*/
void threads_init(void (*fn)(void))
{
thr_disable_interrupts();
add_first_thread(&thread0);
current = &thread0;
thr_init();
thr_enable_interrupts();
/* Enter thread 0 immediately before first timer tick! */
(*fn)();
}
|
C
|
#include "I2C_devices.h"
const char currDate[7] = { 0x00, // 00 Seconds
0x20, // 28 Minutes
0x02, // 24 hour mode, set to 5:00
0x01, // Sunday
0x026, // 4th
0x02, // February
0x18 // 2018
};
void RTC_setTime(void) {
I2C_Master_Start(); // Start condition
I2C_Master_Write(0b11010000); //7 bit RTC address + Write
I2C_Master_Write(0x00); // Set memory pointer to seconds
/* Write array. */
for(char i=0; i<7; i++){
I2C_Master_Write(currDate[i]);
}
I2C_Master_Stop(); //Stop condition
}
void Arduino_command(unsigned char command) {
I2C_Master_Start();
I2C_Master_Write(0b00010000);
I2C_Master_Write(command);
I2C_Master_Stop();
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_putnbr_base.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: clbrunet <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/08/09 17:51:11 by clbrunet #+# #+# */
/* Updated: 2020/08/09 20:49:44 by clbrunet ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
void ft_putchar(char c)
{
write(1, &c, 1);
}
int ft_strlen(char *str)
{
int i;
i = 0;
while (str[i])
i++;
return (i);
}
int ft_valid_base(char *base, int base_len)
{
char current;
int i;
int j;
if (base_len < 2)
return (0);
i = 0;
while (base[i])
{
current = base[i];
if (current == '+' || current == '-')
return (0);
j = i + 1;
while (base[j])
{
if (base[j] == current)
return (0);
j++;
}
i++;
}
return (1);
}
void ft_putnbr_base(int nbr, char *base)
{
long int long_nbr;
int base_len;
base_len = ft_strlen(base);
if (!ft_valid_base(base, base_len))
return ;
long_nbr = nbr;
if (long_nbr < 0)
{
ft_putchar('-');
long_nbr *= -1;
}
if (long_nbr >= base_len)
ft_putnbr_base(long_nbr / base_len, base);
ft_putchar(base[long_nbr % base_len]);
}
|
C
|
/**
* vigenere.c
*
* Deep Chaudhary
* [email protected]
*
* Encrypts messages using Vigenere’s cipher.
*/
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, string argv[])
{
// ensure proper usage
if (argc != 2)
{
printf("Usage: ./vigenere <keyword>\n");
return 1;
}
int m = strlen(argv[1]);
// check if one command-line argument contains any non-alphabetical character
for (int i = 0; i < m; i++)
{
if (isalpha( argv[1][i]) == false)
{
printf("Keyword must only contain letters A-Z and a-z\n");
return 1;
}
}
// get the message from the user
string text = GetString();
for (int i = 0, j = 0, result = 0, n = strlen(text); i < n; i++)
{
char letter = text[i];
// if the letter proves to be a non-alphabetical character, wait to apply that jth character
// of key to the next alphabetical character in text not yet advance to the next character in key
char key = argv[1][(j) % m];
// as for the characters in key, treat A and a as 0, B and b as 1, … , and Z and z as 25
if (isupper(key))
{
key -= 65;
}
else if (islower(key))
{
key -= 97;
}
if (isupper(letter))
{
result = (letter + key - 65) % 26 + 65;
j++;
}
else if (islower(letter))
{
result = (letter + key - 97) % 26 + 97;
j++;
}
// if the character in text is not a letter, output this character unchanged
else
{
result = letter;
}
printf("%c", result);
}
printf("\n");
}
|
C
|
#include<stdio.h>
#include<string.h>
int main()
{
int n, i, j, tam, valido, a;
char linha[128], pilha[128];
scanf("%d", &n);
char vetor[n];
for(i=0; i<n; i++)
{
scanf("%s", linha);
tam = strlen(linha);
a=0;
valido=1;
for(j=0; j<tam&&valido; j++)
{
if(linha[j]=='(' || linha[j]=='[')
{
pilha[a] = linha[j];
a++;
}
else
{
switch(linha[j])
{
case ')':
{
if(a>0 && pilha[a-1]=='(')
{
a--;
}
else
{
valido = 0;
}
}break;
case ']':
{
if(a>0 && pilha[a-1]=='[')
{
a--;
}
else
{
valido = 0;
}
}break;
}
}
}
if(valido && a==0)
{
vetor[i] = 1;
}
else
{
vetor[i] = 0;
}
}
for(i=0; i<n; i++)
{
if(vetor[i]==1)
{
puts("Yes");
}
else
{
puts("No");
}
}
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int n, i, a[10000], x, j, m;
scanf("%d", &n);
for(i=1; i<=n; i++)
scanf("%d", &a[i]);
scanf("%d", &x);
j=0; m=0;
for(i=1; i<=n; i++)
if(j<x)
{
m++;
if(a[i]%2==0)
j++;
}
for(i=1; i<=m; i++)
printf("%d", a[i]);
}
|
C
|
/*
* Turing Machine prototype
* Main source file
*
* format:
* '<name>:<input><output><+/-/N><next>,<input><out(...)\n'
*
*
* Copyright Tiago Teixeira, 2017
*/
#include "fileio.h"
char* do_state(struct state s,char*input,int*next)
{
int act = 0;
while(*(s.ins+act)!=0)
{
if(*(s.ins+act)==*input)
{
// cool
*input=*(s.ins+act+1);
sscanf(s.ins+act+3,"%d",next);
if(*(s.ins+act+2)=='+')
return ++input;
else if(*(s.ins+act+2)=='-')
return --input;
else
return NULL;
}
char*ph = strchr(s.ins+act,',');
if(ph==NULL)
return NULL;
act+=(ph-(s.ins+act))+1;
}
return NULL;
}
void print_actual(char*input,char*act,int state_value)
{
printf("(%d,",state_value);
for(int i=0;*(input+i)!=0;i++)
{
if((input+i)==act)
putchar('|');
putchar(*(input+i));
if((input+i)==act)
putchar('|');
}
printf(")\n");
}
int main(int argc,char**argv)
{
struct state* states = NULL,ns;
int len;
if(argc!=3)
{
fprintf(stderr,"Error: usage: %s <fname> <input_string>\n",*argv);
return 1;
}
states=read_states(argv[1],&len);
if(states==NULL)
return 2;
char *act = argv[2];
int next = states[0].value;
while(act!=NULL)
{
ns = get_state(states,len,next);
print_actual(argv[2],act,ns.value);
if(ns.ins==NULL)
{
fprintf(stderr,"Error: state: state non-existent\n");
free_states(states,len);
return 3;
}
act = do_state(ns,act,&next);
}
free_states(states,len);
return 0;
}
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
static void handler(int signo){
printf("Child %d sending signal to parent\n", getpid());
kill(getppid(), SIGRTMIN + rand()%(SIGRTMAX - SIGRTMIN));
}
int main(){
signal(SIGUSR1, handler);
sigset_t mask;
sigfillset(&mask);
sigdelset(&mask, SIGUSR1);
srand(getpid());
int sleeptime = rand()%11;
printf("I am child with pid: %d, sleeping for %d sek:)\n", getpid(), sleeptime);
sleep(sleeptime);
printf("Child %d sending SIGUSR1 to parent:)\n", getpid());
kill(getppid(),SIGUSR1);
sigsuspend(&mask);
return sleeptime;
}
|
C
|
/*
* lzw15v.c
*
* The LZW algorithm.
*
* Referencias:
*
* T. A. Welch, IEEE Computer, Vol. 17, pp 8-19. 1984.
* M. Nelson and J.-L. Gailly, The Data Compression Book. 1995.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "bitio.h"
/*
* Nmero mximo de bits de un cdigo de compresin "w".
*/
#define MAX_CODE_SIZE_IN_BITS 15
/*
* Valor mximo que puede tomar un cdigo de compresin.
*/
#define MAX_CODE ((1<<MAX_CODE_SIZE_IN_BITS)-1)
/*
* Define el tamao del diccionario. Como se utiliza hashing y cuando
* aparece una colisin se utiliza una bsqueda secuencial, interesa
* utilizar un nmero primo suficientemente grande. A continuacin se
* muestran algunas sugerencias prximas a potencias de dos:
* 4999, 8999, 17989, 35023, 69997, 139999.
*/
#define TABLE_SIZE 35023L
/*
* Indica el fin de la compresin.
*/
#define END_OF_STREAM 256
/*
* Indica ...
*/
#define BUMP_CODE 257
/*
* Indica un vaciado del diccionario.
*/
#define FLUSH_CODE 258
/*
* Primera entrada en el diccionario que almacena una cadena.
*/
#define FIRST_CODE 259
/*
* Entrada vaca.
*/
#define UNUSED -1
/*
* La siguiente estructura de datos declara (de forma esttica) el
* diccionario. Como puede apreciarse, se trata de una tabla de ternas
* "code_value", "parent_code" y "character", donde cada terna
* especifica una cadena diferente. El campo "code_value" es el cdigo
* de compresin asociado a la cadena "parent_code""character", es
* decir, el ndice de la cadena "parent_code""character" en el
* diccionario. Recuerdese adems que "code_value"s menores que 256
* codifican smbolos (races).
*/
struct dictionary {
int code_value;
int parent_code;
char k;
} dict[TABLE_SIZE];
/*
* Contiene la cadena "w" descodificada.
*/
char decode_stack[TABLE_SIZE];
/*
* Siguiente cdigo insertado en el diccionario.
*/
unsigned int next_w;
/*
* Tamao actual del cdigo de compresin.
*/
int current_code_bits;
/*
* Cdigo de compresin que incrementar el tamao del cdigo de
* compresin.
*/
unsigned int next_bump_code;
/*
* Inicializa el diccionario y otras variables globales.
*/
void InitializeDictionary()
{
unsigned int i;
for ( i = 0 ; i < TABLE_SIZE ; i++ )
dict[ i ].code_value = UNUSED;
next_w = FIRST_CODE;
current_code_bits = 9;
next_bump_code = 511;
}
/*
* Busca en el diccionario la cadena "wk". Se utiliza una funcin hash
* que depende "w" y de "k", que se relacionan mediante la operacin
* XOR. En caso de aparecer una colisin se busca, tantas veces como
* sea necesario, en la entrada "index*2 mod TABLE_SIZE", donde
* "index" el la posicin esperrada de la cadena "wk" en el
* diccionario.
*/
unsigned int find_child_node(int parent_code, int child_k) {
unsigned int index;
unsigned int offset;
index = ( child_k << ( MAX_CODE_SIZE_IN_BITS - 8 ) ) ^ parent_code;
if ( index == 0 )
offset = 1;
else
offset = TABLE_SIZE - index;
for ( ; ; ) {
if ( dict[ index ].code_value == UNUSED )
/* Entrada vaca. */
return index;
if ( dict[ index ].parent_code == parent_code &&
dict[ index ].k == (char) child_k )
/* Cadena encontrada. */
return index;
/* Colisin. */
if ( (int) index >= offset )
index -= offset;
else
index += TABLE_SIZE - offset;
}
}
/*
* This routine decodes a string from the dictionary, and stores it
* in the decode_stack data structure. It returns a count to the
* calling program of how many characters were placed in the stack.
*/
unsigned int string(unsigned int count, unsigned int w) {
while ( w > 255 ) {
decode_stack[ count++ ] = dict[ w ].k;
w = dict[ w ].parent_code;
}
decode_stack[ count++ ] = (char) w;
return( count );
}
/*
* The compressor is short and simple. It reads in new symbols one
* at a time from the input file. It then checks to see if the
* combination of the current symbol and the current code are already
* defined in the dictionary. If they are not, they are added to the
* dictionary, and we start over with a new one symbol code. If they
* are, the code for the combination of the code and character becomes
* our new code. Note that in this enhanced version of LZW, the
* encoder needs to check the codes for boundary conditions.
*/
void encode_stream(int argc, char *argv[]) {
int k;
int w;
unsigned int index;
InitializeDictionary();
if ((w=getchar())==EOF)
/* Fichero de entrada vaco! */
w = END_OF_STREAM;
while ((k=getchar())!=EOF) {
/* Buscamos "wk" en el diccionario. */
index = find_child_node(w, k);
if ( dict[ index ].code_value != - 1 )
/* "wk" est en el diccionario. */
/* w <- direccin de "wk". */
w = dict[ index ].code_value;
else {
/* "wk" no est en el diccionario. */
/* Escribimos "w" a la salida. */
put_bits(w, current_code_bits);
/* Insertamos "wk" en el diccionario. */
dict[ index ].code_value = next_w++;
dict[ index ].parent_code = w;
dict[ index ].k = (char) k;
/* w <- k. */
w = k;
if (next_w > MAX_CODE) {
/* Vaciamos el diccionario. */
put_bits(FLUSH_CODE, current_code_bits);
InitializeDictionary();
} else if (next_w > next_bump_code) {
/* Aumentamos el tamao del cdigo en 1 bit. */
put_bits(BUMP_CODE, current_code_bits);
current_code_bits++;
next_bump_code <<= 1;
next_bump_code |= 1;
}
}
}
/* EOS. */
put_bits(w, current_code_bits);
put_bits(END_OF_STREAM, current_code_bits);
flush();
}
/*
* The file expander operates much like the encoder. It has to
* read in codes, the convert the codes to a string of characters.
* The only catch in the whole operation occurs when the encoder
* encounters a CHAR+STRING+CHAR+STRING+CHAR sequence. When this
* occurs, the encoder outputs a code that is not presently defined
* in the table. This is handled as an exception. All of the special
* input codes are handled in various ways.
*/
void decode_stream(int argc, char *argv[]) {
unsigned int w;
unsigned int prev_w;
int k;
unsigned int count;
for ( ; ; ) {
InitializeDictionary();
/* prev_w <- primer cdigo de entrada. */
prev_w = get_bits(current_code_bits);
if ( prev_w == END_OF_STREAM )
return;
/* Escribimos prev_w a la salida. */
putchar(prev_w);
/* k <- prev_w. */
k = prev_w;
for ( ; ; ) {
/* w <- siguiente cdido de entrada. */
w = get_bits(current_code_bits);
/* Mientras existan cdigos de entrada. */
if ( w == END_OF_STREAM )
return;
if ( w == FLUSH_CODE )
break;
if ( w == BUMP_CODE ) {
current_code_bits++;
continue;
}
if ( w >= next_w ) {
/* Si w no est en el diccionario. */
/* Escribir string(w)+k a la salida. */
decode_stack[ 0 ] = (char) k;
count = string( 1, prev_w );
}
else
/* Si w est en el diccionario. */
/* Escribir string(w) a la salida. */
count = string( 0, w );
/* k <- primer smbolo emitido en la salida anterior. */
k = decode_stack[ count - 1 ];
while ( count > 0 )
putchar(decode_stack[--count]);
/* Insertar wk en el diccionario. */
dict[ next_w ].parent_code = prev_w;
dict[ next_w ].k = (char) k;
next_w++;
/* prev_w <- w. */
prev_w = w;
}
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char encrypt(char );
int main()
{
char text[100];
scanf("%[^\n]s", text);
int i;
for (i = 0; i < strlen(text); i++)
{
putchar(encrypt(text[i]));
}
putchar('\n');
return 0;
}
char encrypt(char t)
{
const char *uppercase = "IWGZVFUTHSOJLKDECNMRQPYXBA";
const char *lowercase = "iwgzvfuthsojlkdecnmrqpyxba";
int i;
if (isupper(t))
{
for (i = 0; i < strlen(uppercase); i++)
{
if (uppercase[i] == t)
{
return uppercase[(i + 5) % 26];
}
}
}
else if (islower(t))
{
for (i = 0; i < strlen(lowercase); i++)
{
if (lowercase[i] == t)
{
return lowercase[(i + 5) % 26];
}
}
}
else
{
return t;
}
}
|
C
|
#include "my.h"
#include <setjmp.h>
static jmp_buf g_stack_env;
static void fun1(void);
static void fun2(void);
int main(void)
{
if(0==setjmp(g_stack_env))
{
printf("Normal flow\n");
fun1();
}
else{
printf("long jump flow\n");
}
return 0;
}
static void fun1(void)
{
printf("enter fun1\n");
fun2();
}
static void fun2(void)
{
printf("enter fun2\n");
longjmp(g_stack_env,1);
printf("leave fun2\n");
}
|
C
|
#include <stdio.h>
#include <string.h>
int main() {
int A;
int B;
int C;
scanf("%d %d %d",&A, &B, &C);
int array[4];
int temp;
array[0] = A;
array[1] = B;
array[2] = C;
int i,j;
for (i = 0; i < 2; ++i) {
for (j = i + 1; j < 3; ++j) {
if (array[i] < array[j]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
int output = 10*array[0] + array[1] +array[2];
printf("%d\n",output);
return 0;
} ./Main.c: In function main:
./Main.c:7:3: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result]
scanf("%d %d %d",&A, &B, &C);
^
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* damier.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsourd-b <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/12/20 11:21:22 by bsourd-b #+# #+# */
/* Updated: 2015/12/20 11:21:25 by bsourd-b ### ########.fr */
/* */
/* ************************************************************************** */
#include <rt.h>
static void put_color(t_pix *vec_dir, t_color color)
{
vec_dir->color->b = color.b;
vec_dir->color->g = color.g;
vec_dir->color->r = color.r;
}
static void check(t_pix *vec_dir, int a, int b)
{
int l;
int a1;
int b1;
l = vec_dir->cur_obj->damier.l;
if (a < 0)
a = abs(a - l);
if (b < 0)
b = abs(b - l);
a1 = (int)(a % (2 * l));
b1 = (int)(b % (2 * l));
if ((a1 < l && b1 < l) || (a1 > l && b1 > l))
put_color(vec_dir, vec_dir->cur_obj->damier.color);
else
put_color(vec_dir, vec_dir->cur_obj->color);
}
void damier(t_pix *vec_dir)
{
t_vec normale;
double u;
double v;
if (vec_dir->cur_obj->perlin != 0)
perlin(vec_dir);
else if (vec_dir->cur_obj->type == PLANE)
{
vec_dir->normale = get_normale(vec_dir, vec_dir->inter);
if (fabs(vec_dir->normale.x) != 0.0)
check(vec_dir, (int)vec_dir->inter.y, (int)vec_dir->inter.z);
else if (fabs(vec_dir->normale.y) != 0.0)
check(vec_dir, (int)vec_dir->inter.x, (int)vec_dir->inter.z);
else
check(vec_dir, (int)vec_dir->inter.y, (int)vec_dir->inter.x);
}
else if (vec_dir->cur_obj->type == SPHERE)
{
normale = normalize(make_vec(vec_dir->inter, vec_dir->cur_obj->coord));
u = 0.5 - (atan2((-normale.x), (-normale.y)) / (2.0 * M_PI));
v = 0.5 + 2.0 * (asin((normale.z)) / (2.0 * M_PI));
u *= 4000;
v *= 4000;
check(vec_dir, u, v);
}
}
|
C
|
#include "Stack.c"
/*-----------------------------------------------------------------------------
* Driver Program
*-----------------------------------------------------------------------------*/
int main()
{
DLL* miLista = DLL_Create ();
int tablero[TAM][TAM];
int Conjunto_x[TAM]={-1,0,1,0}; //Representa los movimientos de derecha a izquierda
int Conjunto_y[TAM] = {0,1,0,-1}; //Representa los movimientos arriba y abajo
printf("\n\t*****************LABERINTO**************************\n");
printf("\nPor favor ingrese las coordenadas del laberinto a resolver...");
printf("\n0---Paredes");
printf("\n1---Libre");
printf("\n2---Entrada");
printf("\n3---Salida\n");
for (int i = 0; i< TAM; i++)
{
for(int j = 0; j < TAM; j++)
{
printf("\nPosicion <%d %d>:",i+1,j+1);
scanf("%d", &tablero[i][j]);
}
}
if (laberinto(miLista,Conjunto_x,Conjunto_y,tablero,TAM) == TRUE)
{
printf("\n\tHubo solucion al laberinto\n");
}
else
{
printf("\n\tNO hubo solucion al laberinto\n");
if(DLL_Empty(miLista) == TRUE)
{
printf("\n\t No hay elementos en la pila\n");
}
}
DLL_Destroy (miLista); //Devuelve memoria pedida al sistema
return 0;
}
|
C
|
#include "common.h"
#include <ctype.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <libgen.h>
#include <stdlib.h>
pid_t safe_fork(void)
{
pid_t pid = fork();
assert(pid != -1);
return pid;
}
int safe_creat(const char *pathname, mode_t mode)
{
int fd = creat(pathname, mode);
assert(fd != -1);
return fd;
}
int safe_open(const char *pathname, int flags)
{
int fd = open(pathname, flags);
assert(fd != -1);
return fd;
}
void safe_read(int fd, void *buf, size_t count)
{
assert(read(fd, buf, count) == count);
}
void *safe_calloc(size_t size, size_t cnt)
{
void *buf = calloc(size, cnt);
assert(buf != NULL);
return buf;
}
void *safe_malloc(size_t size)
{
void *buf = malloc(size);
assert(buf != NULL);
return buf;
}
void safe_free(void *buf)
{
assert(buf != NULL);
free(buf);
}
void safe_write(int fd, const void *buf, size_t count)
{
assert(write(fd, buf, count) == count);
}
void safe_close(int fd)
{
assert(close(fd) == 0);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.