language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
int edad=20;
int *pedad;
int nueva_edad;
pedad= &edad;//el puntero es igual a la memoria de edad osea 56789 en el ej
printf("el valor del puntero es : %d ",*pedad);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct NodoLista{
int dato;
struct NodoLista* sig;
}NodoLista;
NodoLista* crearNodo();
NodoLista* enlistar();
void eliminarElemento(NodoLista* );
void insertarElemento(NodoLista* );
void mostrar(NodoLista* );
void main(){
NodoLista* ini;
int op;
ini=enlistar();
do{
do{
printf("\nQu hacer ahora?:\n1.mostrar\n2.Eliminar un elemento\n3.Insertar al INICIO\n4.Insertar al Final\n5.Ordenar Lista\n6.Salir \nR: ");
scanf("%i",&op);
printf("\n\n");
}while(op<1 || op>=6);
switch(op){
case 1:
mostrar(ini);
break;
case 2:
eliminarElemento(ini);
break;
case 3:
insertarElemento(ini);
break;
case 4:
break;
case 5:
break;
case 6:
break;
}
}while(op!=6);
}
void insertarElemento(NodoLista* nodo){
int dato;
int pos;
NodoLista* aux;
printf("\ningrese el valor del dato que desea insertar: ");
scanf("%i",&dato);
if(nodo==NULL){
nodo->dato=dato;
}else{
}
}
NodoLista* enlistar(){
NodoLista* nuevo;
NodoLista* head;
NodoLista* aux;
int i;
int cant;
head=NULL;
i=0;
do{
printf("\nIngrese la cantidad de nodos que tendr a lista: ");
scanf("%i",&cant);
}while(cant<1);
do{
nuevo=crearNodo();
printf("\n Nodo nro %i: ",i+1);
scanf("%i",&nuevo->dato);
if(head==NULL){
head=nuevo;
aux=head;
}else{
aux->sig=nuevo;
aux=nuevo;
}
i++;
}while(i<cant);
nuevo=NULL;
aux=NULL;
return head;
}
NodoLista* crearNodo(){
NodoLista* nodo;
nodo=(NodoLista*)malloc(sizeof(NodoLista));
nodo->sig=NULL;
return nodo;
}
void eliminarElemento(NodoLista* nodo){
NodoLista* aux;
NodoLista* aux2;
NodoLista* aux3;
NodoLista* fin;
int enc;
int val;
printf("\nElemento a eliminar: ");
scanf("%i",&val);
enc=0;
aux=nodo;
aux2=nodo;
aux3=aux;
fin=nodo;
while(aux!=NULL && enc!=1){
if(aux->dato==val){
enc=1;
}else{
aux=aux->sig;
}
}
while(fin->sig!=NULL){
fin=fin->sig;
}
if(enc==0){
printf("\nEl elemento que se desea eliminar no existe");
}else{
if(aux==aux2){
if(aux==fin){
aux->sig=NULL;
free(aux);
aux=NULL;
}else{
aux2=aux->sig;
aux->sig=NULL;
free(aux);
aux=NULL;
}
}
if(aux==fin){
while(aux2->sig!=fin){
aux2=aux2->sig;
}
aux=aux2;
aux2->sig=NULL;
free(fin);
fin=NULL;
}else{
while(aux2->sig!=aux && aux3->sig!=aux){
aux2=aux2->sig;
aux3=aux3->sig;
}
aux2->sig=aux->sig;
aux2=aux2->sig;
aux3->sig=aux2;
aux->sig=NULL;
free(aux);
aux=NULL;
}
}
printf("\n\n");
}
void mostrar(NodoLista* nodo){
NodoLista* aux;
aux=nodo;
printf("\n");
do{
printf(" %i-->",aux->dato);
aux=aux->sig;
}while(aux!=NULL);
printf(" NULL\n\n");
}
|
C
|
#include "stm32f4xx.h"
unsigned short delay_c = 0;
unsigned short blink_delay = 500;
unsigned short light = 0x1000;
void SysTick_Handler(void){
if(delay_c > 0)
delay_c--;
}
void delay_ms(unsigned short delay_t){
delay_c = delay_t;
while(delay_c){};
}
void init(void){
SysTick_Config(SystemCoreClock/1000);
RCC->AHB1ENR |= RCC_AHB1ENR_GPIODEN;
GPIOD->MODER |= 0x55000000;
GPIOD->OTYPER = 0;
GPIOD->OSPEEDR = 0;
}
void main_loop(void) {
GPIOD->ODR = light;
delay_ms(blink_delay);
GPIOD->ODR = 0;
delay_ms(blink_delay);
if(light == 0x8000)
light = 0x1000;
else
light = light << 1;
}
int main(void) {
init();
while(1) {
main_loop();
}
}
|
C
|
#include <stdio.h>
int main()
{
int n, v, p;
scanf("%d", &n);
scanf("%d", &v);
if(v<0 || v>1) return 0;
else scanf("%d", &p);
if(p<0 || p>7) return 0;
else
{
if(v == 1)
{
n = (1 << p) | n;
}
if(v == 0)
{
n = (~(1 << p)) & n;
}
}
printf("\n %d \n", n);
return 0;
}
|
C
|
/*
* SPMiniMax.c
*
* Created on: May 31, 2017
* Author: sapir
*/
#include "SPMiniMax.h"
#include "SPFIARGame.h"
#include "SPMiniMaxNode.h"
#include <limits.h>
#include <stddef.h>
int spMinimaxSuggestMove(SPFiarGame* currentGame, unsigned int maxDepth) {
if ((currentGame == NULL) || (maxDepth <= 0)) {
return -1;
}
SPFiarGame* game_copy = spFiarGameCopy(currentGame);
if (game_copy != NULL) {
move_value best_move;
best_move = minimaxAlgo(game_copy, maxDepth);
spFiarGameDestroy(game_copy);
if (best_move.move != -1) {
return best_move.move;
} else {
/* no legal move - some problem occurred */
/* according to the return value we'll be able to who won / there was a tie */
return -3;
}
} else { /* memory problem */
return -2;
}
}
|
C
|
#include "my_put_string.h"
size_t my_put_string(const char *string)
{
size_t charCount = 0;
if (!string)
return 0;
while (*string++ != '\0')
charCount += my_put_char(*(string - 1));
return charCount;
}
|
C
|
#include <string.h>
#include <kogata/malloc.h>
#include <kogata/syscall.h>
#include <kogata/debug.h>
#include <kogata/region_alloc.h>
int main(int argc, char **argv) {
dbg_print("(BEGIN-USER-TEST malloc-test)\n");
dbg_print_region_info();
for (int iter = 0; iter < 4; iter++) {
dbg_printf("Doing malloc test #%d...\n", iter + 1);
const int m = 200;
uint16_t** ptr = malloc(m * sizeof(uint32_t));
for (int i = 0; i < m; i++) {
size_t s = 1 << ((i * 7) % 11 + 2);
ptr[i] = (uint16_t*)malloc(s);
ASSERT((size_t)ptr[i] >= 0x40000000 && (size_t)ptr[i] < 0xB0000000);
*ptr[i] = ((i * 211) % 1024);
}
dbg_printf("Fully allocated.\n");
dbg_print_region_info();
for (int i = 0; i < m; i++) {
for (int j = i; j < m; j++) {
ASSERT(*ptr[j] == (j * 211) % 1024);
}
free(ptr[i]);
}
free(ptr);
dbg_printf("malloc test OK.\n");
dbg_print_region_info();
}
dbg_printf("(TEST-OK)\n");
return 0;
}
/* vim: set ts=4 sw=4 tw=0 noet :*/
|
C
|
#include <stdio.h>
int main()
{
int n, op = 1;
float total = 0;
scanf("%d",&n);
for (int i = 1; i <= 2*n; i+=2){
if(op == 1){
total += 4.0/i;
op = 0;
}
else{
total -= 4.0/i;
op = 1;
}
}
printf("%f\n",total);
return 0;
}
|
C
|
#ifndef __BINARY_HEAP_STATIC_H__
#define __BINARY_HEAP_STATIC_H__
/*******************************************************************************************************************
* typedef *
*******************************************************************************************************************/
typedef enum HeapType_Tag
{
MIN_HEAP,
MAX_HEAP,
INVALID,
}HeapType;
typedef struct MyStaticBinaryHeap_Tag
{
void* TreeBuffer;
uint16_t ElementSize;
uint16_t BufferSize;
int16_t Head;
uint8_t HeapType;
}MyStaticBinaryHeap;
/*******************************************************************************************************************
* function declaration *
*******************************************************************************************************************/
/// <summary>
/// This function initializes the static binary heap
/// </summary>
/// <param name="MyBinaryHeap - base address of the heap structure"></param>
/// <param name="Buffer - binary heap buffer"></param>
/// <param name="ElementSize - heap elment size"></param>
/// <param name="BufferSize - heap buffer size"></param>
/// <param name="heapType - min or max heap"></param>
/// <returns>1-success, 0-failure</returns>
unsigned char MyStaticBinaryHeap_Create(MyStaticBinaryHeap* MyBinaryHeap, void * Buffer,
uint16_t ElementSize, uint16_t BufferSize, HeapType heapType);
/// <summary>
/// This function pushes the element to the heap
/// </summary>
/// <param name="MyBinaryHeap - base address of the heap structure"></param>
/// <param name="Element - pointer to the element to be pushed"></param>
/// <returns>1-success, 0-failure</returns>
unsigned char MyStaticBinaryHeap_Push(MyStaticBinaryHeap* MyBinaryHeap, void* Element);
/// <summary>
/// This function removes the elment from the heap
/// </summary>
/// <param name="MyBinaryHeap - base address of the heap structure"></param>
/// <param name="Element - pointer to the element to be pushed"></param>
/// <returns>1-success, 0-failure</returns>
unsigned char MyStaticBinaryHeap_Pop(MyStaticBinaryHeap* MyBinaryHeap, void* Element);
/// <summary>
/// This function heapifies the binary tree
/// </summary>
/// <param name="MyBinaryHeap - base address of the heap structure"></param>
/// <returns>1-success, 0-failure</returns>
unsigned char MyStaticBinaryHeap_Heapfy(MyStaticBinaryHeap* MyBinaryHeap);
/// <summary>
/// This function traverses the binary heap
/// </summary>
/// <param name="MyBinaryHeap - base address of the heap structure"></param>
void MyStaticBinaryHeap_Traverse(MyStaticBinaryHeap* MyBinaryHeap);
#endif //__BINARY_HEAP_STATIC_H__
|
C
|
#include <stdlib.h>
#include "point_array.h"
/* ALL THESE FUNCTIONS REQUIRE A VALID POINT_ARRAY_T POINTER AS THEIR
FIRST PARAMETER. THEY SHOULD FAIL ON ASSERTION IF THIS POINTER IS
NULL */
// Safely initalize an empty array structure.
void point_array_init( point_array_t* pa )
{
if (pa != NULL)
{
pa->len = 0;
pa->points = NULL;
}
}
// Resets the array to be empty, freeing any memory allocated if
// necessary.
void point_array_reset( point_array_t* pa )
{
pa->len = 0;
free(pa->points);
pa->points = NULL;
}
// Append a point to the end of an array. If successful, return 0,
// else return 1;
int point_array_append( point_array_t* pa, point_t* p )
{
(pa->len)++;
pa->points = realloc(pa->points, pa->len * sizeof(point_t));
if (pa->points == NULL)
{
(pa->len)--;
return 1;
}
pa->points[pa->len-1] = *p;
return 0;
}
// Remove the point at index i from the array, reducing the size of
// the array by one. The order of points in the array may change.
// Return 0 on success and 1 on failure.
int point_array_remove( point_array_t* pa, unsigned int i )
{
if (pa->len > 1 && pa->len > i)
{
(pa->len)--;
pa->points[i] = pa->points[pa->len];
pa->points = realloc(pa->points, pa->len * sizeof(point_t));
if (pa->points == NULL)
{
(pa->len)++;
return 1;
}
return 0;
}
else if (pa->len == 1 && pa->len > i)
{
pa->len = 0;
pa->reserved = 0;
free(pa->points);
pa->points = NULL;
return 0;
}
return 1;
}
|
C
|
/*
Name
GRfind_button_on_menu_bar
Description
This function will find a button on the menu bar which corresponds to
the specified command string. If the menu bar to search is not
specified by the caller, the routine will search for a displayed menu
bar, stopping on the first one found.
Synopsis
int GRfind_button_on_menu_bar(cmd_to_find, menu_bar_arg, button_label)
int () o TRUE => success, FALSE => failure
char *cmd_to_find i Command string/key to look for.
Form *menu_bar_arg i/o Menu bar id, if known. May be NULL, or
pointer initialized to NULL. If the
latter, the menu bar id will be returned.
int *button_label o The label of the button containing
cmd_to_find (-1 on failure).
Notes
The gadgets on the menu are checked sequentially until a
matching command is found. If a gadget label is invalid, the
search continues up to MAX_INDEX, rather than terminating the
search. This allows applications (especially those not using
menu builder and genmenu) to not have to worry about keeping
gadget labels in order.
History
mrm 09/04/91 creation
mrm 02/18/92 removed dependency on menu names
mrm 08/31/93 allow wildcard to ignore command prefix
*/
#include <alloca.h>
#include <FI.h>
#define TRUE 1
#define FALSE 0
#define NULL 0
/* gadget label range for the buttons on the menu bar */
#define FIRST_INDEX 11
#define MAX_INDEX 40
int GRfind_button_on_menu_bar(cmd_to_find, menu_bar_arg, button_label)
char *cmd_to_find;
Form *menu_bar_arg;
int *button_label;
{
int i, n, type, sts, valid = FALSE;
Form menu_bar, *forms;
char cmd[128];
*button_label = -1;
/* if the caller has not specified the menu bar id, find it */
if (menu_bar_arg == NULL || *menu_bar_arg == NULL)
{
menu_bar = NULL;
/* get a list of forms and menus */
FI_get_num_forms_menus(&n);
forms = (Form *)alloca(n * sizeof(Form));
FI_get_forms_menus(forms, &n);
for (i = 0; i < n; i++)
{
FI_get_form_menu_type(forms[i], &type);
if (type == FI_BAR_MENU_TYPE || type == FI_TEAR_OFF_BAR_MENU_TYPE)
{
/* make sure this is the active menu */
FIf_is_displayed(forms[i], &valid);
if (valid)
{
menu_bar = forms[i];
break;
}
}
}
if (menu_bar)
{
/* return the menu_bar if the caller requested it */
if (menu_bar_arg)
{
*menu_bar_arg = menu_bar;
}
}
else
{
#if DEBUG
printf("Failed to find menu bar (sts = %d)\n", sts);
#endif
return(FALSE);
}
}
else
{
menu_bar = *menu_bar_arg;
}
/* check for leading *'s in the target command; these may be used to
ignore leading characters, like the package prefix. This is to
accomodate apps which alias commands (eg GRDlE -> Z1DlE) */
for (n = 0; cmd_to_find[n] == '*'; n++)
;
/* find the button on the bar which corresponds to the command */
for (i = FIRST_INDEX; i < MAX_INDEX; i++)
{
sts = FIg_get_command(menu_bar, i, cmd);
if ((sts == FI_SUCCESS) && (strcmp(&cmd[n], &cmd_to_find[n]) == 0))
{
*button_label = i;
return(TRUE);
}
}
return(FALSE);
}
|
C
|
#include <stdio.h>
void swap(double *a, double *b) {
double buf = *a;
*a = *b;
*b = buf;
}
int main() {
double a = 1.3;
double b = 1.7;
printf("ٲٱ a, b : %.1lf %.1lf\n", a, b);
swap(&a, &b);
printf("ٲ a, b : %.1lf %.1lf\n", a, b);
}
|
C
|
// Vetor v = [20, 12, 28, 05, 10, 18]
#include <stdio.h>
#include <stdlib.h>
void mostra_vetor(int v[], int n)
{
int i;
printf("\n\nV =");
for (i = 0; i < n; i++)
{
if (i == n-1)
printf(" %d.", v[i]);
else
printf(" %d,", v[i]);
}
}
void troca(int *a, int *b)
{
int aux = *a;
*a = *b;
*b = aux;
}
void insert_sort (int v[], int n)
{
int i, j, aux, cont = 0;
for (i = 1; i < n; i++)
{
aux = v[i];
for (j = i-1; j >= 0 && aux < v[j]; j--)
v[j + 1] = v[j];
v[j + 1] = aux;
mostra_vetor(v,n);
printf("\tIteracao %d", ++cont);
}
}
void select_sort(int v[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
for (j = i + 1; j < n; j++)
if (v[j] < v[i])
troca(&v[j], &v[i]);
}
void bubble_sort(int v[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)
for (j = 0; j < n - i - 1; j++)
if(v[j] > v[j+1])
troca(&v[j+1], &v[j]);
}
int main()
{
int n = 6;
int v[6] = {20, 12, 28, 05, 10, 18};
mostra_vetor(v,n);
//insert_sort(v,n);
//select_sort(v,n);
bubble_sort(v,n);
mostra_vetor(v,n);
system("pause>>null");
}
|
C
|
#include "holberton.h"
#define USAGE ("Usage: cp file_from file_to\n")
#define SOURCE (argv[1])
#define DEST (argv[2])
#define NO_READ ("Error: Can't read from file %s\n")
#define NO_WRITE ("Error: Can't write to %s\n")
#define NO_CLOSE ("Error: Can't close fd %d\n")
/**
* main - program that copies the content of a file to another file
*
* @argc: arg count
* @argv: argument vector
*
* Return: int
*/
int main(int argc, char *argv[])
{
int source, dest, read_bytes, write_bytes;
char buf[1024];
if (argc != 3)
dprintf(STDERR_FILENO, USAGE), exit(97);
source = open(SOURCE, O_RDONLY);
if (source == -1)
dprintf(STDERR_FILENO, NO_READ, SOURCE), exit(98);
dest = open(DEST, O_CREAT | O_WRONLY | O_TRUNC, 0664);
while ((read_bytes = read(source, buf, 1024)) > 0)
write_bytes = write(dest, buf, read_bytes);
if (read_bytes == -1)
dprintf(STDERR_FILENO, NO_READ, SOURCE), exit(98);
if (write_bytes == -1 || dest == -1)
dprintf(STDERR_FILENO, NO_WRITE, DEST), exit(99);
if (close(source) == -1)
dprintf(STDERR_FILENO, NO_CLOSE, source), exit(100);
if (close(dest) == -1)
dprintf(STDERR_FILENO, NO_CLOSE, dest), exit(100);
return (0);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: anurgali <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/07 15:52:15 by anurgali #+# #+# */
/* Updated: 2019/10/07 15:52:19 by anurgali ### ########.fr */
/* */
/* ************************************************************************** */
#include "fractol.h"
void choose_fract(t_fract *set)
{
if (set->fract_num == 0)
exit(0);
else
thread(set);
mlx_put_image_to_window(set->mlx_ptr,set->win_ptr,set->img_ptr , 0, 0);
}
void make_col_arr(t_fract *set)
{
int c;
float r;
set->color_arr = (int *)malloc(sizeof(int) * set->max);
c = 0;
r = 0;
while (c++ < set->max)
{
set->rgb.r = (cos(r) + 1) * 127;
set->rgb.g = (sin(r) + 1) * 127;
set->rgb.b = (-cos(r) + 1) * 127;
set->color_arr[c] = set->rgb.b | set->rgb.g << 4 | set->rgb.r << 16;
r += M_PI / set->max;
}
}
int *make_col_arr2(void)
{
int *colARR = (int *)malloc(sizeof(int) * 16);
colARR[0] = 0x421E0F;
colARR[1] = 0x19071A;
colARR[2] = 0x09012F;
colARR[3] = 0x040449;
colARR[4] = 0x000764;
colARR[5] = 0x0C2C8A;
colARR[6] = 0x182C8A;
colARR[7] = 0x397DD1;
colARR[8] = 0x86B5E5;
colARR[9] = 0xD3ECF8;
colARR[10] = 0xF1E9BF;
colARR[11] = 0xF8C95F;
colARR[12] = 0xFFAA00;
colARR[13] = 0xCC8000;
colARR[14] = 0x995700;
colARR[15] = 0x6A3403;
return (colARR);
}
void inputchoise(char av, t_fract *set)
{
if (av == 'M')
{
set->fract_num = 1;
}
else if (av == 'J')
{
set->fract_num = 2;
}
else if (av == 'S')
{
set->fract_num = 3;
}
//else if (av == 'X')
// init_window_jx(set);
else
set->fract_num = 0;
}
void setup_env(t_fract *set)
{
set->zoom = .90;
set->move_x = 0;
set->move_y = 0;
set->max = 64;
set->flag = 0;
set->color_arr = make_col_arr2();
}
int main (int ac, char **av)
{
t_fract *set;
if (ac == 2)
{
if (!(set = ft_memalloc(sizeof(t_fract))))
return (0);
inputchoise(av[1][0], set);
if (!(set->fract_num))
ft_putendl("fractal not found");
set->mlx_ptr = mlx_init();
set->win_ptr = mlx_new_window(set->mlx_ptr, WIN_X, WIN_Y, "JULIA");
set->img_ptr = mlx_new_image(set->mlx_ptr, WIN_X, WIN_Y);
set->data = mlx_get_data_addr(set->img_ptr, &set->bpp, &set->size_line, &set->endian);
int i = 0;
while(set->data[i])
{
printf("i = %d\n", i);
i++;
}
setup_env(set);
choose_fract(set);
mlx_key_hook(set->win_ptr, deal_key, set);
mlx_mouse_hook(set->win_ptr, mouse_hooks, set);
mlx_hook(set->win_ptr, 6, 0, julia_mouse_hook, set);
mlx_loop(set->mlx_ptr);
}
else
ft_putendl("Gimme one fractal: M - Mandelbrot; J - Julia; S - BurningShip; JX = Julia Explorer.");
return (0);
}
|
C
|
#include"main.h"
int main()
{
pStu pHead=NULL;
pHead=create_node();
init(pHead);
menu(pHead);
return 0;
}
int menu(pStu pHead)
{
int function;
while(1)
{
printf("-----------------\n");
printf("| 1、插入 |\n");
printf("| 2、删除 |\n");
printf("| 3、查找 |\n");
printf("| 4、打印 |\n");
printf("| 5、保存 |\n");
printf("| 6、退出 |\n");
printf("-----------------\n");
printf(" 请选择功能:\n");
scanf("%d",&function);
if(-1==judge(function,pHead))
{
break;
}
}
return 0;
}
int judge(int function,pStu pHead)
{
switch(function)
{
case INSERT:
insert(pHead);
break;
case DEL:
del(pHead);
break;
case SEARCH:
search(pHead);
break;
case PRINT:
fun.pPrint(pHead);
break;
case SAVE:
save(pHead);
break;
case EXIT:
return -1;
break;
default:
printf("输入错误!\n");
break;
}
return 0;
}
|
C
|
#include <stdio.h>
int main ()
{
float nota [4][3], media, av1, av2, av3; /*numero de linhas antes do de colunas*/
int i, j, mat;
for (i=0; i<=3; i++)
{
for (j=0; j<=2; j++)
{
printf("\nEntre com a av%d do aluno %d:\n",j+1, i+1);
scanf("%f", ¬a[i][j]);
}
}
printf("\nResultado final:");
printf("\n---------------------------------------------------------------------------------------\n");
printf("\nNome \t\t\t Av1 \t\t Av2 \t\t Av3 ");
printf("\n---------------------------------------------------------------------------------------\n");
for(i=0; i<=3; i++)
{
printf("Aluno %d \t\t %.2f \t\t %.2f \t\t %2.f\n", i+1, nota[i][0], nota[i][1], nota[i][2]);
printf("\n---------------------------------------------------------------------------------------\n");
}
printf("\nResultado da AV1:");
printf("\n-----------------------------------------\n");
printf("\nNome \t\t\t Av1 ");
printf("\n-----------------------------------------\n");
for(i=0; i<=3; i++)
{
printf("Aluno %d \t\t %.2f \n", i+1, nota[i][0]);
printf("\n----------------------------------------\n");
}
printf("\nEntre com a matricula:");
scanf("%d",&mat);
printf("\nResultado final:");
printf("\n---------------------------------------------------------------------------------------\n");
printf("\nNome \t\t\t Av1 \t\t Av2 \t\t Av3 \t\t Resultado");
printf("\n---------------------------------------------------------------------------------------\n");
i = mat-1;
av1 = nota[i][0];
av2 = nota[i][1];
av3 = nota[i][2];
if(av1>=av2 && av1>=av3) //av1 é a maior
{
if(av2>av3)
{
media= (av1+av2)/2;
}
else
{
media= (av1+av3)/2;
}
}
else if(av2>av3) //av2 é a maior
{
if(av1>av3)
{
media = (av2+av1)/2;
}
else
{
media = (av2+av3)/2;
}
}
else if (av1>av2) //av3 é a maior
{
media = (av3+av1)/2;
}
else
{
media = (av3+av2)/2;
}
if (media>=6)
{
printf("Aluno %d \t\t %.2f \t\t %.2f \t\t %2.f \t\t Aprovado\n", mat, nota[i][0], nota[i][1], nota[i][2]);
}
else{
printf("Aluno %d \t\t %.2f \t\t %.2f \t\t %2.f \t\t Reprovado\n", mat, nota[i][0], nota[i][1], nota[i][2]);
}
printf("\n---------------------------------------------------------------------------------------\n");
return 0;
}
|
C
|
/*! \file FileManager.c
*/
#ifdef __cplusplus
extern "C" {
#endif
/*************************************************************************
* I N C L U D E
*************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "FileManager.h"
/*************************************************************************
* D E F I N E
*************************************************************************/
/*************************************************************************
* G L O B A L
*************************************************************************/
/*************************************************************************
* F O R W A R D D E C L A R A T I O N
*************************************************************************/
/************************************************************************
*/
/*! \fn int FileManager_MaxEntries(char* cFile)
* \brief open an file and return the number of entrys
*
* \return int --< number of entries or -1 in case of an error
*
*************************************************************************/
int FileManager_MaxEntries(char* cFile)
{
FILE *fpStation;
int iCurrentNumber, iEntrys = 0;
char cText[128];
char* pResult;
fpStation = fopen((const char*)cFile, "r+");
/* if seek failed return with an error */
if(fseek(fpStation, 0, SEEK_SET) < 0) return -1;
do
{
pResult = fgets(cText, 128, fpStation);
if(memcmp("ENTRY=", &cText[0], strlen("ENTRY=")) == 0)
{
sscanf(&cText[strlen("ENTRY=")], "%d", &iCurrentNumber);
iEntrys++;
if(!(iCurrentNumber == iEntrys))
{
fclose(fpStation);
return -1;
}
}
pResult = fgets(cText, 128, fpStation);
pResult = fgets(cText, 128, fpStation);
pResult = fgets(cText, 128, fpStation);
} while(pResult != 0);
fclose(fpStation);
return iEntrys;
}
/************************************************************************
*/
/*! \fn int FileManager_Read(STATION_ENTRY* StationEntry, int iNumber)
* \brief Read an entry selectet by number
*
* \return int --> 1 entrie is filed, or -1 entry not found or an error occure
*
*************************************************************************/
int FileManager_Read(char* cFile, STATION_ENTRY* StationEntry, int iNumber)
{
FILE *fpStation;
int iCurrentNumber = 0;
char* pResult;
char cText[128];
fpStation = fopen((const char*)cFile, "r+");
/* if seek failed return with an error */
if(fseek(fpStation, 0, SEEK_SET) < 0) return -1;
do
{
pResult = fgets(cText, 128, fpStation);
if(memcmp("ENTRY=", &cText[0], strlen("ENTRY=")) == 0)
{
sscanf(&cText[strlen("ENTRY=")], "%d", &iCurrentNumber);
}
if(iCurrentNumber == iNumber)
{
StationEntry->iNumber = iCurrentNumber;
pResult = fgets(cText, 128, fpStation);
if(memcmp("STATION=", &cText[0], strlen("ENTRY=")) == 0)
{
strcpy(StationEntry->cStation, &cText[strlen("STATION=")]);
}
pResult = fgets(cText, 128, fpStation);
if(memcmp("GENRE=", &cText[0], strlen("GENRE=")) == 0)
{
strcpy(StationEntry->cGenre, &cText[strlen("GENRE=")]);
}
pResult = fgets(cText, 128, fpStation);
if(memcmp("STREAM=", &cText[0], strlen("STREAM=")) == 0)
{
strcpy(StationEntry->cStream, &cText[strlen("STREAM=")]);
}
fclose(fpStation);
return iCurrentNumber;
}
else
{
pResult = fgets(cText, 128, fpStation);
pResult = fgets(cText, 128, fpStation);
pResult = fgets(cText, 128, fpStation);
}
} while(pResult != 0);
fclose(fpStation);
return -1;
}
/************************************************************************
*/
/*! \fn int FileManager_Write(STATION_ENTRY* StationEntry, int iNumber)
* \brief Read an entry selectet by number
*
* \return int --> 1 entrie is filed, or -1 entry not found or an error occure
*
*************************************************************************/
int FileManager_Write(char* cFile, STATION_ENTRY* StationEntry, int iNumber)
{
FILE *fpStation;
return -1;
}
/************************************************************************
*/
/*! \fn int FileManager_Append(STATION_ENTRY* StationEntry, int iNumber)
* \brief Append an return the position in the file
*
* \return int --> nummber of entry in file, or -1 entry not found or an error occure
*
*************************************************************************/
int FileManager_Append(char* cFile, STATION_ENTRY StationEntry)
{
FILE *fpStation;
int iMaxEntrys;
char* pResult;
char cText[128];
iMaxEntrys = FileManager_MaxEntries(cFile);
iMaxEntrys++;
fpStation = fopen((const char*)cFile, "a");
if(fpStation < 0) return -1;
sprintf(cText, "ENTRY=%d\r", iMaxEntrys);
fputs (cText,fpStation);
sprintf(cText, "STATION=%s", StationEntry.cStation);
fputs (cText,fpStation);
sprintf(cText, "GENRE=%s", StationEntry.cGenre);
fputs (cText,fpStation);
sprintf(cText, "STREAM=%s", StationEntry.cStream);
fputs (cText,fpStation);
fclose(fpStation);
return iMaxEntrys;
}
#ifdef __cplusplus
}
#endif
|
C
|
//
// Created by Luca Barco on 10/12/2017.
//
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "atlList.h"
#define MAXC 26
struct nodo_s{
atleta val;
link_atleta next;
link_piano head_piano;
link_piano tail_piano;
};
struct tabAtleti_s{
int nAtleti;
link_atleta head;
link_atleta tail;
};
tabAtleti nuovaTabAt(){
tabAtleti a=malloc(sizeof(*a));
a->head=NULL;
a->tail=NULL;
return a;
}
tabAtleti leggiFile_atleta(tabAtleti atleti){
FILE *fp;
int i=0;
atleta temp;
fp=fopen("atleti.txt","r");
if(fp==NULL){
printf("Errore nell'apertura del file 'atleti'!\n");
return NULL;
}
fscanf(fp,"%d\n",&(atleti->nAtleti));
temp=atletaScan(fp);
while(atletaEq((temp),atletaVoid())!=1 && i<atleti->nAtleti){
atleti->head=InserimentoCoda(atleti,temp);
i++;
temp=atletaScan(fp);
}
fclose(fp);
return atleti;
}
link_atleta nuovoNodo(link_atleta next,atleta val){
link_atleta x=malloc(sizeof(*x));
if(x==NULL)
return NULL;
x->val=val;
x->next=next;
x->head_piano=NULL;
x->tail_piano=NULL;
return x;
}
link_atleta InserimentoCoda(tabAtleti atleti,atleta val){
link_atleta x;
if(atleti->head==NULL) {
x = nuovoNodo(NULL, val);
atleti->tail = x;
return x;
}
for(x=atleti->head;x->next!=NULL;x=x->next);
x->next=nuovoNodo(NULL,val);
atleti->tail=x->next;
return atleti->head;
}
tabAtleti rimuoviNodo(tabAtleti atleti,char *k){
link_atleta x,p;
if(atleti->head==NULL) {
return NULL;
}
for(x=atleti->head,p=NULL;x!=NULL;p=x,x=x->next){
if(strcmp(x->val.codice,k)==0){
if(x==atleti->head)
atleti->head=x->next;
else
p->next=x->next;
free(x);
break;
}
}
return atleti;
}
link_atleta ricercaCodice(tabAtleti atleti,char *chiave){
link_atleta i;
link_atleta h=atleti->head;
for(i=h;i!=NULL;i=i->next){
if(strcmp(chiave,i->val.codice)==0)
return i;
}
return NULL;
}
link_atleta ricercaCognome(tabAtleti atleti,char *chiave){
link_atleta i;
link_atleta h=atleti->head;
int ls,k,trovato=0;
char cognome_temp[MAXC];
ls=strlen(chiave);
for(k=0;k<=ls;k++){
chiave[k]=toupper(chiave[k]);
}
for(i=h;i!=NULL;i=i->next) {
strcpy(cognome_temp, i->val.cognome);
for (k = 0; k <= strlen(cognome_temp); k++) {
cognome_temp[k] = toupper(cognome_temp[k]);
}
if (strncmp(chiave, cognome_temp,ls) == 0) {
trovato=1;
printf("%s %s %s %s %s %d\n", i->val.codice, i->val.nome, i->val.cognome, i->val.data, i->val.categoria, i->val.ore);
}
}
if(trovato==0)
printf("-----Nessuna corrispondenza trovata!-----\n");
return NULL;
}
tabAtleti aggiungiAtleta(tabAtleti atleti){
char i_codice[6];
char i_nome[MAXC];
char i_cognome[MAXC];
char i_categoria[MAXC];
char i_data[11];
int i_ore_allenamento;
atleta temp;
printf("Inserisci i dati dell'atleta\n\tCodice:");
scanf("%s",i_codice);
printf("Nome:");
scanf("%s",i_nome);
printf("Cognome:");
scanf("%s",i_cognome);
printf("Data di nascita:");
scanf("%s",i_data);
printf("Categoria Sportiva:");
scanf("%s",i_categoria);
printf("Ore di allenamento settimanali:");
scanf("%d",&i_ore_allenamento);
temp.codice=malloc(6*sizeof(char));
strcpy(temp.codice,i_codice);
temp.data=malloc(11*sizeof(char));
strcpy(temp.data,i_data);
temp.n_nome=strlen(i_nome);
temp.nome=malloc((temp.n_nome+1)*sizeof(char));
strcpy(temp.nome,i_nome);
temp.n_cognome=strlen(i_cognome);
temp.cognome=malloc((temp.n_cognome+1)*sizeof(char));
strcpy(temp.cognome,i_cognome);
temp.n_categoria=strlen(i_categoria);
temp.categoria=malloc((temp.n_categoria+1)*sizeof(char));
strcpy(temp.categoria,i_categoria);
temp.ore=i_ore_allenamento;
atleti->head= InserimentoCoda(atleti,temp);
printf("-----Atleta aggiunto correttamente!-----\n");
return atleti;
}
tabAtleti cancellaAtleta(tabAtleti atleti){
char codice[6];
printf("Inserire il codice dell'atleta da eliminare!\n");
scanf("%s",codice);
atleti= rimuoviNodo(atleti,codice);
printf("-----Cancellazione riuscita!-----\n");
return atleti;
}
void stampaAtleta(tabAtleti atleti,char *chiave){
link_atleta i;
link_piano j;
i=ricercaCodice(atleti,chiave);
if(i!=NULL){
printf("---------------Ricerca terminata!---------------\n");
atletaPrint(i->val,stdout);
if(i->head_piano!=NULL){
printf("\n-----> Piano di allenamento:\n");
for(j=i->head_piano;j!=NULL;j=nextEser(j)){
stampaEserPiano(j,stdout);
}
}
else{
printf("-----> Piano relativo all'atleta non trovato!\n");
}
}
else{
printf("---------------Atleta non trovato!---------------\n");
}
}
void aggiornaOre(tabAtleti atleti){
char codice[6];
int nuove_ore;
link_atleta i;
printf("Inserisci il codice dell'atleta di cui aggiornare le ore di allenamento seguito dal nuovo numero di ore");
scanf("%s %d",codice,&nuove_ore);
i=ricercaCodice(atleti,codice);
i->val.ore=nuove_ore;
printf("---------- Aggiornamento riuscito!----------\n");
printf("%s %s %s %s %s %d\n", i->val.codice, i->val.nome, i->val.cognome, i->val.data, i->val.categoria,
i->val.ore);
return;
}
link_atleta trovaCodice(tabAtleti atleti,char *cognome,char *nome){
char cognome_temp[MAXC],nome_temp[MAXC];
link_atleta i,l;
int k,trovato=0,esci=0,scelta;
for(k=0;k<=strlen(cognome);k++){
cognome[k]=toupper(cognome[k]);
}
for(k=0;k<=strlen(nome);k++){
nome[k]=toupper(nome[k]);
}
for(i=atleti->head;i!=NULL&&trovato==0&&esci==0;i=i->next) {
trovato=0;
strcpy(cognome_temp, i->val.cognome);
for (k = 0; k <= strlen(cognome_temp); k++) {
cognome_temp[k] = toupper(cognome_temp[k]);
}
if (strncmp(cognome, cognome_temp,strlen(cognome_temp)) == 0) {
strcpy(nome_temp, i->val.nome);
for (k = 0; k <= strlen(nome_temp); k++) {
nome_temp[k] = toupper(nome_temp[k]);
}
if(strncmp(nome,nome_temp,strlen(nome_temp))==0){
trovato=1;
printf("Atleta: %s %s \tCodice: %s\n\tPremere 1 per confermare,0 per cercare altri omonimi\n",i->val.nome,i->val.cognome,i->val.codice);
scanf("%d",&scelta);
if(scelta==1) {
l = i;
esci = 1;
}
return l;
}
}
}
if(trovato==0) {
printf("-----Nessuna corrispondenza trovata!-----\n");
l=NULL;
return l;
}
}
tabAtleti leggiFile_piano(tabAtleti atleti,char *codice,tabEser vett){
char nomefile[10];
link_atleta i;
link_piano head=newPointPiano();
link_piano tail=newPointPiano();
link_piano temp;
int k,trovato=0;
FILE *fp;
i=ricercaCodice(atleti,codice);
if(i!=NULL) {
if (i->head_piano == NULL) {
sprintf(nomefile, "%s.txt", codice);
fp = fopen(nomefile, "r");
if (fp == NULL) {
printf("----> Errore nell'apertura del piano. File non presente!\n");
return NULL;
}
head = NULL;
while ((temp = eserScanPiano(fp)) != NULL) {
head = InserimentoCoda_piano(head, &tail, temp);
tail = associaEser(tail, vett);
}
i->head_piano = head;
i->tail_piano = tail;
fclose(fp);
return atleti;
} else {
printf("-----------Piano gia' caricato per questo utente!-----------\n");
return atleti;
}
}
else{
printf("---------------File piano non presente per questo atleta!---------------\n");
return atleti;
}
}
tabAtleti rimuoviEser(tabAtleti atleti,char *codice,char *k){
link_atleta i=ricercaCodice(atleti,codice);
i->head_piano=rimuoviEserNodo(i->head_piano,k);
return atleti;
}
tabAtleti nuovoEser(tabAtleti atleti,char *codice,char *nomees,int set,int rip,tabEser vett){
link_atleta i=ricercaCodice(atleti,codice);
link_atleta j;
int trovato=0;
link_piano val=newEser(nomees,set,rip,vett);
val=associaEser(val,vett);
i->head_piano=InserimentoCoda_piano(i->head_piano,&(i->tail_piano),val);
for(j=atleti->head;j!=NULL && trovato==0;j=j->next){
if(strcmp(j->val.codice,codice)==0){
j->head_piano=i->head_piano;
trovato=1;
}
}
return atleti;
}
tabAtleti modificaEsAtl(tabAtleti atleti,char *codice_chiave, char *nomees_chiave,int n_set,int n_rip,tabEser vett){
link_atleta i;
i=ricercaCodice(atleti,codice_chiave);
if(i!=NULL){
i->head_piano=modificaEs(i->head_piano,nomees_chiave,n_rip,n_set,vett);
}
else{
printf("---------------Atleta non trovato!---------------\n");
}
return atleti;
}
atleta extractVal(link_atleta i){
return i->val;
}
int extractRip(link_atleta i,char *nomees,tabEser vett){
link_piano j;
for(j=i->head_piano;j!=NULL;j=nextEser(j)){
if(strcmp(getEserPianoNome(j,vett),nomees)==0){
return estraiRip(j);
}
}
}
int extractSet(link_atleta i,char *nomees,tabEser vett){
link_piano j;
for(j=i->head_piano;j!=NULL;j=nextEser(j)){
if(strcmp(getEserPianoNome(j,vett),nomees)==0){
return estraiSet(j);
}
}
}
char *extractCode(link_atleta i){
return i->val.codice;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include <errno.h>
#include "note.h"
#include "x_lib.h"
int blank_note(struct statistics* stats, char* buffer, int offset, bool arg, int mask);
int single_note(struct statistics* stats, char* buffer, int offset, bool arg, int mask);
int multi_note(struct statistics* stats, char* buffer, int offset, bool arg, int mask);
int code_note(struct statistics* stats, char* buffer, int offset, bool arg, int mask);
struct note_choice choices[] =
{
{0, blank_note},
{1, single_note},
{2, multi_note},
{3, code_note},
};
int blank_note(struct statistics* stats, char* buffer, int offset, bool arg, int mask)
{
fputs(buffer, stats->wrfp);
if(mask&0x3)
{
stats->note +=mask&0x1;
stats->combine+=(mask&0x2)>>1;
}
else
{
stats->count++;
stats->blank++;
}
}
int code_note(struct statistics* stats, char* buffer, int offset, bool arg, int mask)
{
fputs(buffer, stats->wrfp);
if(mask&0x3)
{
stats->combine++;
}
else
{
stats->count++;
stats->code ++;
}
}
int single_note(struct statistics* stats, char* buffer, int offset, bool arg, int mask)
{
bool front = x_ispair(buffer, offset, '\"');
bool behind = x_ispair(buffer+offset, strlen(buffer)-offset, '\"');
if((!front)&&(!behind))
{
fputs(buffer, stats->wrfp);
return 0;
}
if(!(mask&0x3)/*mask == 0*/)
{
stats->count++;
if(arg)
{
buffer[offset] = '\n';
buffer[offset+1] = '\0';
fputs(buffer, stats->wrfp);
stats->combine++;
}
else
{
stats->note++;
}
return 0;
}
//mask != 0
if(arg)
{
buffer[offset] = '\n';
buffer[offset+1] = '\0';
fputs(buffer, stats->wrfp);
stats->combine++;
}
else
{
stats->note +=mask&0x1;
stats->combine+=(mask&0x2)>>1;
}
return 0;
}
int multi_note_tail(char* buffer)
{
int offset;
for(offset = 0; offset < strlen(buffer); offset++)
{
if((buffer[offset] == '*') && (buffer[offset+1] == '/'))
{
break;
}
}
return offset;
}
int multi_note(struct statistics* stats, char* buffer, int offset, bool arg, int mask)
{
if(!(mask&0x3))
{
stats->count++;
}
if(arg)
{
fwrite(buffer, offset, 1, stats->wrfp);
mask=(0x1<<1);
}
else
{
if(mask == 0)
mask = (0x1<<0);
}
//
char* s = buffer + offset + 2;
do{
s += multi_note_tail(s);
if(s[0] != '\0')
{
goto find;
}
s = buffer;
fgets(s, 1024, stats->rdfp);
if(feof(stats->rdfp))
{
break;
}
mask=(0x1<<0);
stats->note ++;
stats->count++;
}while(!feof(stats->rdfp));
return -1;
find:
s += 2;
uint8_t flag = 0;
int offset2 = check_note(s, strlen(s), &flag);
int type = flag&0x03;
bool arg2 = (flag&0x04) >> 2;
if(choices[type].handle(stats, s, offset2, arg2, mask) == -1)
{
return -1;
}
return 0;
}
int trim_buf(char* buffer)
{
char* p = buffer;
while(*p == ' ' || *p == '\t')
p++;
return p - buffer;
}
int check_note(char* buffer, int len, uint8_t* flag)
{
//
int i = trim_buf(buffer);
//
if(buffer[i] == '\n')
{
//blank line.
*flag |= 0x00;
return i;
}
//
if(buffer[i] != '/')
{
*flag |= 0x04;
}
//
for(; i < len; i++)
{
if(buffer[i] == '/')
{
if(buffer[i+1] == '/')
{
//single line note.
*flag |= 0x01;
return i;
}
else if(buffer[i+1] == '*')
{
//multi line note.
*flag |= 0x02;
return i;
}
}
}
//code line.
*flag |= 0x03;
return i;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 5
int again(int s[SIZE]){
int i;
int k;
for(i = 0; i < SIZE; i++){
for(k = i + 1; k < SIZE; k++){
if(s[i] == s[k]){
printf("틀린답 입니다.\n");
return 0;
}
}
}
printf("정답 입니다\n");
return 0;
}
int main(){
int i;
int scores[SIZE];
srand(time(NULL));
for(i = 0; i < SIZE; i++){
scores[i] = (rand() % 100) + 1;
}
for(i = 0; i < SIZE; i++){
printf("score[%d] = %d\n", i, scores[i]);
}
again(scores);
return 0;
}
|
C
|
#include<stdio.h>
void main()
{
int i,f[20],n[50],div[50],j,temp,quotient[20],z[10];
printf("enter the number\n");
for(i=0;i<6;i++)
{
scanf("%d",&n[i]);
}
printf("enter the polynomial\n");
for(i=0;i<4;i++)
{
scanf("%d",&div[i]);
}
for(i=8;i<12;i++)
{
n[i]=0;
}
for(i=0;i<8;i++)
{
temp=i;
if(n[i]==1)
{
for (j=0;j<4;j++)
{
if (n[temp]==div[j])
{n[temp]=0;
f[j]=0;}
else
{n[temp]=1;
f[j]=1;}
temp=temp+1;
}
quotient[i]=1;
}
else
quotient[i]=0;
}
printf("\nthe quotient is \n");
for(i=0;i<8;i++)
printf("%d",quotient[i]);
printf("\n CRC is \n ");
for(j=0;j<4;j++)
printf("%d",f[j]);
}
|
C
|
//
// main.c
// Chapter 10: Structs
//
// Created by Kathy Lin on 11/5/17.
// Copyright © 2017 Kathy Lin. All rights reserved.
//
// typedef defines an alias for a type declaration and allows one to use it more like the usual data types. You can pass it to another function
#include <stdio.h>
#include <time.h>
typedef struct {
float heightInMeters;
int weightInKilos;
} Person;
float bodyMassIndex(Person p) {
return p.weightInKilos / (p.heightInMeters * p.heightInMeters);
}
int main(int argc, const char * argv[]) {
// struct Person person (if no typedef)
Person person;
person.weightInKilos = 96;
person.heightInMeters = 1.8;
printf("person weighs %i kilograms.\n", person.weightInKilos);
printf("person is %.2f meters tall.\n", person.heightInMeters);
// calculate bmi
printf("person has a BMI of %.2f.\n", bodyMassIndex(person));
// challenge: write a program that will tell you what the date (4-30-2015 format is fine) will be in 4 million seconds.
long secondsSince1970 = time(NULL);
struct tm now;
localtime_r(&secondsSince1970, &now);
printf("The time is %d:%d:%d\n", now.tm_hour, now.tm_min, now.tm_sec);
long inFourMillionSeconds = secondsSince1970 + 4000000;
struct tm time;
localtime_r(&inFourMillionSeconds, &time);
printf("The date in 4 million seconds is %d-%d-%d\n", time.tm_mon+1, time.tm_mday, time.tm_year+1900);
return 0;
}
|
C
|
/*
cc rbt_test.c rbt.c
*/
#include "rbt.h"
#include <stdio.h>
#include <string.h>
int main()
{
RBT t = Initialize_rbt();
/*
10(B)
/ \
5(B) 15(B)
/ \
/ \
13(R) 20(R)
*/
const int ITEM_1 = 10;
t->key = 10;
const int ITEM_2 = 5;
Rbt_insert(t, ITEM_2);
const int ITEM_3 = 15;
Rbt_insert(t, ITEM_3);
const int ITEM_4 = 13;
Rbt_insert(t, ITEM_4);
const int ITEM_5 = 20;
Rbt_insert(t, ITEM_5);
printf("In order print of t:\n");
Rbt_inorder_print(t);
printf("\n");
struct rbt_node* n = Rbt_search(t, ITEM_3);
if (!n)
{
printf("Rbt_search failed\n");
}
else
{
Rbt_delete(t, n);
printf("After delete %d:\n", ITEM_3);
Rbt_inorder_print(t);
printf("\n");
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
char buf[100];
int n;
if((n=readlink("ep",buf,sizeof(buf)))==-1){
perror("readlink");
return -1;
}
buf[n]=0;//'\0'
puts(buf);
unlink("ep");
}
|
C
|
/* login : g.isaac@groupecerco.com */
#include <stdio.h>
#include <stdlib.h>
char *ft_strncpy(char *dest, char *src, unsigned int n);
char *ft_strncpy(char *dest, char *src, unsigned int n)
{
unsigned int i;
i = 0;
while (i++ < n && src[i - 1])
dest[i - 1] = src[i - 1];
while (i++ < n)
dest[i - 2] = '\0';
return (dest);
}
void main(void)
{
char text[20];
int n;
ft_strncpy(text, "God will make a way for me.", 3);
printf("Text: %s", text);
return (0);
}
|
C
|
#pragma once
#include <stdint.h>
#include <stdbool.h>
// Addresses here are already pre-shifted
typedef enum
{
BMA400_I2C__0X28 = 0x28,
BMA400_I2C__0X2A = 0x2A
} bma400_i2c__address;
typedef struct
{
int16_t x, y, z;
} bma400_i2c__axes_raw_s;
typedef struct
{
float x, y, z;
} bma400_i2c__axes_mps2_s;
/**
* Initialize bma400
**/
bool bma400_i2c__init(bma400_i2c__address bma400_address);
/**
* Get BMA400 chip id
* @return bma400 chip id
**/
uint8_t bma400_i2c__get_chip_id(bma400_i2c__address bma400_address);
/**
* Get raw x, y, and z values
* @return raw data of x, y, and z axes from bma400
**/
bma400_i2c__axes_raw_s bma400_i2c__get_acceleration_raw(bma400_i2c__address bma400_address);
/**
* Get x, y, and z values in meters per second squared (m/s^2 or mps2)
* @return x, y, and z data in meters per second squared
**/
bma400_i2c__axes_mps2_s bma400_i2c__get_acceleration_mps2(bma400_i2c__address bma400_address);
/**
* Check if new data is ready
* @return true of new data is available
**/
bool bma400_i2c__data_ready(bma400_i2c__address bma400_address);
/**
* Get raw x value
* @return raw x value
**/
int16_t bma400_i2c__get_x_raw(bma400_i2c__address bma400_address);
/**
* Get raw y value
* @return raw y value
**/
int16_t bma400_i2c__get_y_raw(bma400_i2c__address bma400_address);
/**
* Get raw z value
* @return raw z value
**/
int16_t bma400_i2c__get_z_raw(bma400_i2c__address bma400_address);
/**
* Get x value in meters per second squared
* @return x value in mps2
**/
float bma400_i2c__get_x_mps2(bma400_i2c__address bma400_address);
/**
* Get y value in meters per second squared
* @return y value in mps2
**/
float bma400_i2c__get_y_mps2(bma400_i2c__address bma400_address);
/**
* Get z value in meters per second squared
* @return z value in mps2
**/
float bma400_i2c__get_z_mps2(bma400_i2c__address bma400_address);
|
C
|
#ifndef __TREE_H__
#define __TREE_H__
#include <stdio.h>
#include <stdlib.h>
typedef void *Object;
typedef struct node
{
Object value;
struct node *left;
struct node *right;
} Node;
typedef Node *Node_ptr;
typedef struct
{
Node_ptr root;
} Tree;
typedef Tree *Tree_ptr;
typedef enum
{
False,
True
} Bool;
typedef enum
{
Lesser,
Greater,
Equal
} Cmp_Status;
typedef Bool (*Predicate)(Object, Object);
typedef Cmp_Status (*Compare)(Object, Object);
typedef void (*Change_Node)(Node_ptr);
Node_ptr create_node(Object);
Tree_ptr create_tree(void);
void insert_node(Tree_ptr, Object, Predicate);
Bool search(Tree_ptr, Object, Compare);
#endif
|
C
|
#include<stdio.h>
void main()
{
int i,n,result=0;
printf("enter n value:\t");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
result=result+i;
}
printf("%d",result);
}
|
C
|
#include<stdio.h>
typedef long long ll;
ll gcd(ll a, ll b) {
while (b > 0) {
ll t = b;
b = a % b;
a = t;
}
return a;
}
int main(){
ll N, cd;
scanf("%ld", &N);
scanf("%ld", &cd);
for (ll i = 1; i < N; i++) {
ll n;
scanf("%ld", &n);
cd = gcd(cd, n);
}
ll n = 1;
ll cnt = 1;
while (cd % 2 == 0) {
cnt++;
cd /= 2;
}
n *= cnt;
for (ll i = 3; i <= cd; i+=2) {
cnt = 1;
while (cd % i == 0) {
cnt++;
cd /= i;
}
n *= cnt;
}
printf("%ld\n", n);
}
|
C
|
/*Problema 1: Comprobar a traves de un programa si un alumno
aprobo o no un examen (Aprubea si su nota es mayor a 10.5) */
#include <stdio.h>
int main(){
float examen;
printf("Digite la nota del examen: "); scanf("%f", &examen);
if( examen > 10.5){
printf("\nEl alumno esta aprobado");
// puts("El alumno esta aprobado"); Solo imprime dentro de un condicional
}
return 0;
}
|
C
|
// htab_clear.c
// Řešení IJC-DU2, příklad 2), 28.4
// Autor: Andrej Dzilský, FIT
// Přeloženo: gcc 5.3.1
#include <stdlib.h>
#include "libtable.h"
void htab_clear(htab_t *t)
{
htab_listitem *item;
/* cyklus v poli ukazatelov na zaznamy */
for (unsigned i = 0; i < t->htab_size; ++i)
{
/* nastavenie na prvy prvok v poli zaznamov */
item = t->list[i];
/* cyklus pre vsetky polozky v jednotlivych poliach zaznamov */
while (item != NULL)
{
htab_remove(t,item->key);
item = item->next;
}
}
}
|
C
|
// Author: Abs_;
/* Problem:
Given the values of three variables a, b and c, write a program to compute and display the value
of x, where x = a /(b - c) , use the values (a) a = 250, b = 85, c= 25 (b) a = 300, b = 70, c = 70 Comment on the output in each case.*/
// **Note: a / 0 = NAN, so if b - c = 0 then the program doesn't give any output.
#include<stdio.h>
void main()
{
int a, b, c;
float x;
printf("\nEnter the values of a , b , c : ");
scanf("%d %d %d", &a, &b, &c);
x = a /(b - c);
printf("\nIf a = %d, b = %d, c = %d then x = %f", a, b, c, x);
}
|
C
|
#include <stdio.h>
int main (void)
{
int a;
printf("Enter the number ");
scanf("%d", &a);
printf("Ur number %d\r\n", a);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
void main(int argc,char*argv[])
{
int sid,sid1,rval,itr,i;// sid is half association. sid1 is full association
struct sockaddr_in s,c;
char buffer[20];
int clen; //accept() uses value-result parameter
system("clear");
if(argc<3)
{
printf("\nUSAGE : %s IP_ADDRESS PORT#\n",argv[0]);
exit(0);
}
printf("\nEnter the number of clients to serve/ server iterations : ");
scanf("%d",&itr);
sid=socket(AF_INET,SOCK_STREAM,6);//3rd parameter can also be 0
if(sid==-1)
{
perror("SOCK-CRE-ERR:");
exit(1);
}
/*DEFINING NAME OF THE SERVICE*/
s.sin_family=AF_INET;
s.sin_port=htons(atoi(argv[2]));
s.sin_addr.s_addr=inet_addr(argv[1]);
/*BIND SOCKET- indicates the process that is listening*/
rval=bind(sid,(struct sockaddr*)&s,sizeof(s));
if(rval==-1)
{
perror("BIND-ERR:");
close(sid);
exit(1);
}
rval=listen(sid,5);//range : 1-5
if(rval==-1)
{
perror("LISTEN-ERR:");
close(sid);
exit(1);
}
for(i=1;i<=itr;i++)
{
clen=sizeof(c);
sid1=accept(sid,(struct sockaddr*)&c,&clen);
rval=recv(sid1,buffer,sizeof(buffer),0);
if(rval==-1)
{
perror("MSG-RCV-ERR:");
}
else
{
printf("\nClient request is %s\n",buffer);
}
rval=send(sid1,buffer,sizeof(buffer),0);
if(rval==-1)
{
perror("MSG-SND-ERR:");
}
else
{
printf("\nResponse sent\n");
}
close(sid1);//closing the serving socket
}
close(sid);//closing the listening socket
}
|
C
|
/*
* @lc app=leetcode.cn id=1518 lang=c
*
* [1518] 换酒问题
*
* https://leetcode-cn.com/problems/water-bottles/description/
*
* algorithms
* Easy (69.17%)
* Likes: 20
* Dislikes: 0
* Total Accepted: 9.9K
* Total Submissions: 14.3K
* Testcase Example: '9\n3'
*
* 小区便利店正在促销,用 numExchange 个空酒瓶可以兑换一瓶新酒。你购入了 numBottles 瓶酒。
*
* 如果喝掉了酒瓶中的酒,那么酒瓶就会变成空的。
*
* 请你计算 最多 能喝到多少瓶酒。
*
*
*
* 示例 1:
*
*
*
* 输入:numBottles = 9, numExchange = 3
* 输出:13
* 解释:你可以用 3 个空酒瓶兑换 1 瓶酒。
* 所以最多能喝到 9 + 3 + 1 = 13 瓶酒。
*
*
* 示例 2:
*
*
*
* 输入:numBottles = 15, numExchange = 4
* 输出:19
* 解释:你可以用 4 个空酒瓶兑换 1 瓶酒。
* 所以最多能喝到 15 + 3 + 1 = 19 瓶酒。
*
*
* 示例 3:
*
* 输入:numBottles = 5, numExchange = 5
* 输出:6
*
*
* 示例 4:
*
* 输入:numBottles = 2, numExchange = 3
* 输出:2
*
*
*
*
* 提示:
*
*
* 1 <= numBottles <= 100
* 2 <= numExchange <= 100
*
*
*/
// @lc code=start
int numWaterBottles(int numBottles, int numExchange){
}
// @lc code=end
|
C
|
#include<stdio.h>
struct rankList{
int id;
int M;
int E;
};
bool operator < (rankList a, rankList b){
if(a.M > b.M)return true;
else if(a.M == b.M && a.E > b.E) return true;
else return false;
}
int main(){
ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
rankList rl;
int n;
//cin>>n;
scanf("%d", &n)
vector<rankList> vec;
for(int i=1; i<=n; i++){
//cin>>rl.id>>rl.M>>rl.E;
scanf("%d %d %d", &rl.id, &rl.M, &rl.E);
vec.push_back(rl);
}
sort(vec.begin(), vec.end());
cout<<endl;
for(int i=0; i<vec.size(); i++){
cout<<vec[i].id<<" "<<vec[i].M<<" "<<vec[i].E<<endl;
}
return 0;
}
|
C
|
#include <stdio.h>
/*ハブデータ
* スポーク計算に必要なデータを記載
* 重量も記載している
* 1、ハブの名称
* 2、PCD
* 3、エンド幅(ロックナット間距離OLD)
* 5、ロックナット-フランジ間距離(右)
* 6、ロックナット-フランジ間距離(左)
* 7、ハブ重量
*
*/
struct front_hub
{
char *name;
double pcd;
double old;
double range;
double weight;
};
struct rear_hub
{
char *name;
double pcd;
double old;
double range_r;
double range_l;
double weight;
};
struct front_hub Evolution_light = {
.name = "Evolution_light_front",
.pcd = 30,
.old = 100,
.range = 17.5,
.weight = 60,
};
struct front_hub HB2200 = {
.name = "HB-2200_front",
.pcd = 37,
.old = 100,
.range = 16,
.weight = 60,
};
|
C
|
/****************************************************************************
* FreeRTOS data race example / JPP 22032017
*
*
****************************************************************************/
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include <stdio.h>
/* FreeRTOS include files are located in FreeRTOS/sources/include, which must be set as an additional
include path in project */
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
// in FreeRTOS, higher priority value means higher priority
#define WRITER_TASK_PRIORITY ( tskIDLE_PRIORITY + 2 )
#define READER_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 )
static void vWriterTask( void *pvParameters );
static void vReaderTask( void *pvParameters );
SemaphoreHandle_t xSemaphore;
int main( void )
{
// create tasks and start scheduler
xTaskCreate( vWriterTask, ( const char * ) "T1", 255, (void *)('1'), WRITER_TASK_PRIORITY, NULL );
xTaskCreate( vReaderTask, ( const char * ) "T2", 255, (void *)('2'), READER_TASK_PRIORITY, NULL );
xSemaphore = xSemaphoreCreateBinary();
xSemaphoreGive(xSemaphore);
vTaskStartScheduler();
return 0;
}
volatile int shared;
static void vWriterTask( void *pvParameters )
{
( void ) pvParameters;
while(1)
{
if (xSemaphore != NULL) {
if (xSemaphoreTake(xSemaphore, (TickType_t) 10 ) == pdTRUE)
{
shared=0x0000;
shared=0xFFFF;
xSemaphoreGive(xSemaphore);
}
}
vTaskDelay( 1 );
}
}
static void vReaderTask( void *pvParameters )
{
( void ) pvParameters;
DDRD |= 0x80;
while(1)
{
if (xSemaphore != NULL) {
if (xSemaphoreTake(xSemaphore, (TickType_t) 10 ) == pdTRUE)
{
switch(shared)
{
//variable should be either 0x0000 or 0xFFFF
case 0x0000:
case 0xFFFF:
//OK
PORTD = 0x00;
break;
//but, catch the following failure with breakpoint:
default:
PORTD = 0x80;
break;
}
xSemaphoreGive(xSemaphore);
}
}
}
}
|
C
|
#include "lists.h"
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
/**
* print_list - prints the string
* in each node in the linked list
*
* @h: pointer to struct
*
* Return: count (success) 1 (fail)
*/
size_t print_list(const list_t *h)
{
/* set counter */
unsigned int count = 0;
/* set HEAD to front of list */
const list_t *head = h;
/* loop through list */
while (head != NULL)
{
if (head->str == NULL)
{
printf("[%d] %s\n", 0, "(nil)");
}
else
{
printf("[%d] %s\n", head->len, head->str);
}
count++;
head = head->next;
}
return (count);
}
|
C
|
#include "base64.h"
uint8_t base64Encode(uint8_t byte) {
static uint8_t map[] = {
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',
'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/'
};
return map[byte & 0x3F];
}
uint8_t base64Decode(uint8_t ch) {
return (ch >= 'A' && ch <= 'Z') ? ch - 'A' :
(ch >= 'a' && ch <= 'z') ? (ch - 'a') + 26 :
(ch >= '0' && ch <= '9') ? (ch - '0') + 52 :
(ch == '+') ? 62 :
(ch == '/') ? 63 :
0xFF;
}
|
C
|
/*
Enumeraciones
Una enumeracin (palabra reservada enum),
es un conjunto de constantes de enumeracin enteras representadas por identificadores.
Los valores de una enumeracin comienzan con 0, a menos que se especifique lo contrario, y se incrementan en 1.
*/
#include <stdio.h>
//Las siguientes constantes de enumeracin representan los meses del ao
enum meses {
ENE = 1, FEB, MAR, ABR, MAY, JUN, JUL, AGO, SEP, OCT, NOV, DIC
};
int main(void) {
//inicializar array de punteros
//Dejamos el primer elemento sin definir, ya que el primer valor de la enumeracin empieza en 1
const char *nombreMes[] = { "", "Enero", "Febrero", "Marzo",
"Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre",
"Noviembre", "Diciembre" };
//Bucle a travs de meses
for (enum meses mes = ENE; mes <= DIC; ++mes) {
printf("%2d%11s\n", mes, nombreMes[mes]);
}
}
|
C
|
/**
* @file lv_area.h
*
*/
#ifndef LV_AREA_H
#define LV_AREA_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../lv_conf_internal.h"
#include <string.h>
#include <stdbool.h>
#include <stdint.h>
#include "lv_mem.h"
/*********************
* DEFINES
*********************/
/*To avoid overflow don't let the max ranges (reduce with 1000) */
#define LV_COORD_MAX ((lv_coord_t)((uint32_t)((uint32_t)1 << (8 * sizeof(lv_coord_t) - 1)) - 1000))
#define LV_COORD_MIN (-LV_COORD_MAX)
LV_EXPORT_CONST_INT(LV_COORD_MAX);
LV_EXPORT_CONST_INT(LV_COORD_MIN);
/**********************
* TYPEDEFS
**********************/
/**
* Represents a point on the screen.
*/
typedef struct {
lv_coord_t x;
lv_coord_t y;
} lv_point_t;
/** Represents an area of the screen. */
typedef struct {
lv_coord_t x1;
lv_coord_t y1;
lv_coord_t x2;
lv_coord_t y2;
} lv_area_t;
/** Alignments */
enum {
LV_ALIGN_CENTER = 0,
LV_ALIGN_IN_TOP_LEFT,
LV_ALIGN_IN_TOP_MID,
LV_ALIGN_IN_TOP_RIGHT,
LV_ALIGN_IN_BOTTOM_LEFT,
LV_ALIGN_IN_BOTTOM_MID,
LV_ALIGN_IN_BOTTOM_RIGHT,
LV_ALIGN_IN_LEFT_MID,
LV_ALIGN_IN_RIGHT_MID,
LV_ALIGN_OUT_TOP_LEFT,
LV_ALIGN_OUT_TOP_MID,
LV_ALIGN_OUT_TOP_RIGHT,
LV_ALIGN_OUT_BOTTOM_LEFT,
LV_ALIGN_OUT_BOTTOM_MID,
LV_ALIGN_OUT_BOTTOM_RIGHT,
LV_ALIGN_OUT_LEFT_TOP,
LV_ALIGN_OUT_LEFT_MID,
LV_ALIGN_OUT_LEFT_BOTTOM,
LV_ALIGN_OUT_RIGHT_TOP,
LV_ALIGN_OUT_RIGHT_MID,
LV_ALIGN_OUT_RIGHT_BOTTOM,
};
typedef uint8_t lv_align_t;
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Initialize an area
* @param area_p pointer to an area
* @param x1 left coordinate of the area
* @param y1 top coordinate of the area
* @param x2 right coordinate of the area
* @param y2 bottom coordinate of the area
*/
void lv_area_set(lv_area_t * area_p, lv_coord_t x1, lv_coord_t y1, lv_coord_t x2, lv_coord_t y2);
/**
* Copy an area
* @param dest pointer to the destination area
* @param src pointer to the source area
*/
inline static void lv_area_copy(lv_area_t * dest, const lv_area_t * src)
{
_lv_memcpy_small(dest, src, sizeof(lv_area_t));
}
/**
* Get the width of an area
* @param area_p pointer to an area
* @return the width of the area (if x1 == x2 -> width = 1)
*/
static inline lv_coord_t lv_area_get_width(const lv_area_t * area_p)
{
return (lv_coord_t)(area_p->x2 - area_p->x1 + 1);
}
/**
* Get the height of an area
* @param area_p pointer to an area
* @return the height of the area (if y1 == y2 -> height = 1)
*/
static inline lv_coord_t lv_area_get_height(const lv_area_t * area_p)
{
return (lv_coord_t)(area_p->y2 - area_p->y1 + 1);
}
/**
* Set the width of an area
* @param area_p pointer to an area
* @param w the new width of the area (w == 1 makes x1 == x2)
*/
void lv_area_set_width(lv_area_t * area_p, lv_coord_t w);
/**
* Set the height of an area
* @param area_p pointer to an area
* @param h the new height of the area (h == 1 makes y1 == y2)
*/
void lv_area_set_height(lv_area_t * area_p, lv_coord_t h);
/**
* Set the position of an area (width and height will be kept)
* @param area_p pointer to an area
* @param x the new x coordinate of the area
* @param y the new y coordinate of the area
*/
void _lv_area_set_pos(lv_area_t * area_p, lv_coord_t x, lv_coord_t y);
/**
* Return with area of an area (x * y)
* @param area_p pointer to an area
* @return size of area
*/
uint32_t lv_area_get_size(const lv_area_t * area_p);
/**
* Get the common parts of two areas
* @param res_p pointer to an area, the result will be stored her
* @param a1_p pointer to the first area
* @param a2_p pointer to the second area
* @return false: the two area has NO common parts, res_p is invalid
*/
bool _lv_area_intersect(lv_area_t * res_p, const lv_area_t * a1_p, const lv_area_t * a2_p);
/**
* Join two areas into a third which involves the other two
* @param res_p pointer to an area, the result will be stored here
* @param a1_p pointer to the first area
* @param a2_p pointer to the second area
*/
void _lv_area_join(lv_area_t * a_res_p, const lv_area_t * a1_p, const lv_area_t * a2_p);
/**
* Check if a point is on an area
* @param a_p pointer to an area
* @param p_p pointer to a point
* @param radius radius of area (e.g. for rounded rectangle)
* @return false:the point is out of the area
*/
bool _lv_area_is_point_on(const lv_area_t * a_p, const lv_point_t * p_p, lv_coord_t radius);
/**
* Check if two area has common parts
* @param a1_p pointer to an area.
* @param a2_p pointer to an other area
* @return false: a1_p and a2_p has no common parts
*/
bool _lv_area_is_on(const lv_area_t * a1_p, const lv_area_t * a2_p);
/**
* Check if an area is fully on an other
* @param ain_p pointer to an area which could be in 'aholder_p'
* @param aholder_p pointer to an area which could involve 'ain_p'
* @param radius radius of `aholder_p` (e.g. for rounded rectangle)
* @return true: `ain_p` is fully inside `aholder_p`
*/
bool _lv_area_is_in(const lv_area_t * ain_p, const lv_area_t * aholder_p, lv_coord_t radius);
/**
* Align an area to an other
* @param base an are where the other will be aligned
* @param to_align the area to align
* @param align `LV_ALIGN_...`
* @param res x/y coordinates where `to_align` align area should be placed
*/
void _lv_area_align(const lv_area_t * base, const lv_area_t * to_align, lv_align_t align, lv_point_t * res);
/**********************
* MACROS
**********************/
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#define BLOCK_SIZE 512
typedef uint8_t byte;
// typedef uint8_t byte;
int checkSignature(FILE *diskImage, long *start);
void copyBytes(FILE *output, FILE *diskImage, long *start, long offset);
int main(int argc, char *argv[])
{
// ensure correct usage
if (argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
// open the image file passed in by argv[1] for reading, twice for a read ahead
FILE *img = fopen(argv[1], "r");
FILE *imgReadAhead = fopen(argv[1], "r");
// error reading the file
if (!img)
{
printf("Cannot open file %s\n", argv[1]);
return 1;
}
// Business Logic of the analytics tool
int counter = 0;
char fileName[8];
long startByte = 0;
long offsetBlocks = 0;
do
{
// Read ahead and extract start + offset of valid jpg
offsetBlocks = checkSignature(imgReadAhead, &startByte);
if (offsetBlocks == 0)
{
break;
}
// only prepare files if we find traces of jpg
// compile the file name for each jpg
sprintf(fileName, "%03i.jpg", counter);
// create a new file and fill it with bytes from img
FILE *file = fopen((const char *)fileName, "w");
copyBytes(file, img, &startByte, offsetBlocks);
// prepare for next file
counter++;
startByte += offsetBlocks * BLOCK_SIZE;
// clean up after ourselves
fclose(file);
}
while (!feof(imgReadAhead)); // Halt at end of readahead
// clean up after ourselves
fclose(img);
fclose(imgReadAhead);
}
int checkSignature(FILE *diskImage, long *pstart)
{
/*
* Checks for JPEG signature at the first four bytes of a block
* until it either finds another signature or the end of the disk image
*/
long offset = 0;
long start = *pstart;
long end = 0;
byte tmp[BLOCK_SIZE];
do
{
fread(tmp, BLOCK_SIZE, 1, diskImage);
// JPG Magic Bytes
if (tmp[0] == 0xff && tmp[1] == 0xd8 && tmp[2] == 0xff && (tmp[3] >= 0xe0 && tmp[3] <= 0xef))
{
if (start == 0) // Find first start of jpg
{
start = ftell(diskImage) - BLOCK_SIZE; // we've read over the current block, set start back 1 block to include the magic bytes
*pstart = start;
}
else
{
end = ftell(diskImage) - BLOCK_SIZE;
}
}
if (feof(diskImage)) // Halt at end of diskImage
{
if (start == 0) // no jpg found
{
return 0;
}
end = ftell(diskImage);
break;
}
}
while (start >= end); // read bytes until we find another jpg header after our starting point
offset = (end - start) / BLOCK_SIZE;
return offset;
}
void copyBytes(FILE *output, FILE *diskImage, long *pstart, long offset)
{
/*
* Write offset bytes from *pstart in FILE* output
* Reads and writes in chunks to be more efficient
*/
char *tmp;
tmp = malloc(offset * BLOCK_SIZE);
fseek(diskImage, *pstart, SEEK_SET);
fread(tmp, offset * BLOCK_SIZE, 1, diskImage);
fwrite(tmp, BLOCK_SIZE, offset, output);
// clean up after ourselves
free(tmp);
return;
}
|
C
|
/*
* main.c
* Copyleft (ɔ) 2021 greennewbie <adsl53102@gmail.com>
*
* Distributed under terms of the MIT license.
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/wait.h>
#define MIN_PID 300
#define MAX_PID 5000
#define NUM 10
pthread_mutex_t mutex;
int *pidArray = NULL;
int allocate_map(void)
{
pthread_mutex_lock(&mutex);
if (pidArray)
return -1;
int size = MAX_PID - MIN_PID;
pidArray = (int*) calloc(size, sizeof(int));
int i = 0;
while (i < size)
{
pidArray[i++] = 0;
}
pthread_mutex_unlock(&mutex);
return 1;
}
int allocate_pid(void){
int i,flag=1;
for(i=0; i<MAX_PID-MIN_PID; i++){
if(pidArray[i]==0){
pidArray[i]=1;
flag=0;
break;
}
}
return flag?-1:i + MIN_PID;
}
/*
int allocate_pid(void)
{
int size = MAX_PID - MIN_PID;
int i = 0;
while (i < size)
{
if (!pidArray[i])
{
pidArray[i] = 1;
return i + MIN_PID;
}
}
return 1;
}
*/
void release_pid(int pid)
{
int p = pid - MIN_PID;
pidArray[p] = 0;
}
void* threadHelper(void* argv)
{
int thread_id = *((int*)argv);
//printf("here\n");
int pid = allocate_pid();
if (pid == -1)
printf("allocated_pid error\n");
else
{
printf("Thread %d allocated pid %d\n", thread_id, pid);
int sleepNum = 1 + rand() % 16;
sleep(sleepNum);
printf("Thread %d released pid %d after sleeping %d\n", thread_id, pid, sleepNum);
release_pid(pid);
}
pthread_exit(NULL);
}
int main(int argc, char* argv[])
{
int i = 0;
if (allocate_map() == -1)
printf("allocate_map error\n");
srand(time(NULL));
pthread_mutex_init(&mutex, NULL);
pthread_t threads[NUM];
for (i = 0; i < NUM; i++) {
pthread_create(&threads[i], NULL, threadHelper, (void*) &i);
} /* for (i = 0; i < NUM; i++) */
for (i = 0; i < NUM; ++i) {
pthread_join(threads[i], NULL);
}
pthread_mutex_destroy(&mutex);
free(pidArray);
return 0;
}
|
C
|
#include "holberton.h"
#include <stdlib.h>
/**
* malloc_checked - function that adds 2 integers
* @b: is one of the integers added together
*
*
* Description: function allocates memory with malloc_check
* Return: if malloc fails we use exit(98)
*/
void *malloc_checked(unsigned int b)
{
int *pointer;
pointer = malloc(b);
if (pointer == NULL)
exit(98);
return (pointer);
}
|
C
|
#include <stdio.h>
#include "variables.h"
void GeneralRound ( i, f )
int i;
void f ( int, int );
{
int N, S, W, E;
N = ( i - cx ) >= 0;
S = ( i + cx ) < MatrixSize;
W = i % cx;
E = ( i + 1 ) % cx;
if ( N ) f ( i - cx, i );
if ( S ) f ( i + cx, i );
if ( W ) f ( i - 1, i );
if ( E ) f ( i + 1, i );
if ( N && W ) f ( i - cx - 1, i );
if ( N && E ) f ( i - cx + 1, i );
if ( S && W ) f ( i + cx - 1, i );
if ( S && E ) f ( i + cx + 1, i );
}
void ShowRealMatrix ()
{
int i;
for ( i = 0; i < MatrixSize; i++ )
{
if ( (i % cx) == 0 ) printf ("\n");
printf ( "%d", realMatrix[i]);
}
printf ( "\n" );
}
|
C
|
#include <stdio.h>
#include "stdtypes.h"
typedef union
{
struct
{
uint_8 B0 : 1;
uint_8 B1 : 1;
uint_8 B2 : 1;
uint_8 B3 : 1;
uint_8 B4 : 1;
uint_8 B5 : 1;
uint_8 B6 : 1;
uint_8 B7 : 1;
} bits;
uint_8 byte;
} Register;
int main(void) {
Register x;
x.bits.B2 = 1;
printf("Register = %d\n", x.byte);
return 0;
}
|
C
|
// Funcion Mosaico con SSE2+THREADS
#include <stdio.h>
#include <stdlib.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <emmintrin.h>
// Aqui para SSE2 se define el tipo de dato __m128i y las funciones
// _mm_load_si128 y _mm_store_si128
#include <time.h>
#include <pthread.h> /* POSIX Threads */
#define NTHREADS 4 // Vamos a usar 4 threads
// Definicion de las variables locales aquí:
#define ALTO 16
#define ANCHO 16
void copiarBloque(int i, int j, IplImage *imagenOrigen, int k, int l, IplImage *imagenDestino); // En C tenemos que declararlo aquí.
int compararBloque(int filaBloque1, int colBloque1, IplImage *imagen1, int filaBloque2, int colBloque2, IplImage *imagen2);
void mosaico_thread(void *ptr); // Metodo
int main(int argc, char** argv) {
struct timespec start, finish;
float elapsed;
clock_gettime(CLOCK_MONOTONIC, &start);
// A partir de aquí metemos el código del cual queremos
//calcular el tiempo que tarda en ejecutarse.
if (argc != 3) {
printf("Usage: %s image_file_name\n", argv[0]);
return EXIT_FAILURE;
}
//CV_LOAD_IMAGE_COLOR = 1 forces the resultant IplImage to be colour.
//CV_LOAD_IMAGE_GRAYSCALE = 0 forces a greyscale IplImage.
//CV_LOAD_IMAGE_UNCHANGED = -1
IplImage* Img1 = cvLoadImage(argv[1], CV_LOAD_IMAGE_UNCHANGED);
IplImage* Img2 = cvLoadImage(argv[2], CV_LOAD_IMAGE_UNCHANGED);
// Always check if the program can find a file
if (!Img1) {
printf("Error: fichero %s no leido\n", argv[1]);
return EXIT_FAILURE;
}
if (!Img2) {
printf("Error: fichero %s no leido\n", argv[2]);
return EXIT_FAILURE;
}
// a visualization window is created with title 'image'
cvNamedWindow(argv[1], CV_WINDOW_AUTOSIZE);
// img is shown in 'image' window
cvShowImage(argv[1], Img1);
cvWaitKey(0);
// a visualization window is created with title 'image'
cvNamedWindow(argv[2], CV_WINDOW_AUTOSIZE);
// img is shown in 'image' window
cvShowImage(argv[2], Img2);
cvWaitKey(0);
IplImage *ImgNueva = cvCreateImage(cvSize(Img1->width, Img1->height), IPL_DEPTH_8U, 3);
//copiarBloque(4,4, Img1, 700, 900, ImgNueva);
int fila1, columna1,filamin,columnamin;
for (fila1 = 0; fila1 < Img1->height; fila1 = fila1 + ALTO) {
for (columna1 = 0; columna1 < Img1->width; columna1 = columna1 + ANCHO) {
int fila2, columna2;
int minimo = INT_MAX;
int valor = 0;
int filamin, columnamin;
for (fila2 = 0; fila2 < Img2->height; fila2 = fila2 + ALTO) {
for (columna2 = 0; columna2 < Img2->width; columna2 = columna2 + ANCHO) {
valor = compararBloque(fila1, columna1, Img1, fila2, columna2, Img2);
if (valor < minimo) {
minimo = valor;
filamin = fila2;
columnamin = columna2;
}
}
}
copiarBloque(filamin, columnamin, Img2, fila1, columna1, ImgNueva);
}
}
// a visualization window is created with title 'image'
cvNamedWindow("Img Nueva", CV_WINDOW_AUTOSIZE);
// img is shown in 'image' window
cvShowImage("Img Nueva", ImgNueva);
cvWaitKey(0);
// memory release for img before exiting the application
cvReleaseImage(&Img1);
cvReleaseImage(&Img2);
cvReleaseImage(&ImgNueva);
// Self-explanatory
cvDestroyWindow(argv[1]);
cvDestroyWindow(argv[2]);
cvDestroyWindow("Img Nueva");
clock_gettime(CLOCK_MONOTONIC, &finish); // Aqui finaliza el bloque
// de código que queremos comprobar
elapsed = (finish.tv_sec - start.tv_sec);
elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0;
printf("Tiempo transcurrido: %f", elapsed);
return EXIT_SUCCESS;
}
void mosaico_thread(void *ptr) {
//ptr apunta a un entero que indica el mutiplo de la fila a sustituir
int *fila = (int *) ptr;
int fila,columna;
}
void copiarBloque(int i, int j, IplImage *imagenOrigen, int k, int l, IplImage *imagenDestino) {
int fila, columna;
for (fila = 0; fila < ALTO ; fila++) {
unsigned char *pimagenOrigen = (unsigned char *)( imagenOrigen->imageData + ((i+fila) * imagenOrigen->widthStep) + j*3); //Esos 3 son bytes
unsigned char *pimagenDestino = (unsigned char *) imagenDestino->imageData + ((k+fila) * imagenDestino->widthStep) + l*3;
for (columna = 0; columna < ANCHO; columna++) {
*pimagenDestino++ = *pimagenOrigen++;
*pimagenDestino++ = *pimagenOrigen++;
*pimagenDestino++ = *pimagenOrigen++;
}
}
}
/*
int compararBloque(int filaBloque1, int colBloque1, IplImage *imagen1, int filaBloque2, int colBloque2, IplImage *imagen2) {
int fila, columna, valor = 0;
for (fila = filaBloque1; fila < ALTO + filaBloque1; fila++) {
unsigned char *pimagen1 = (unsigned char *) imagen1->imageData + fila * imagen1->widthStep + colBloque1 * 3;
unsigned char *pimagen2 = (unsigned char *) imagen2->imageData + filaBloque2 * imagen2->widthStep + colBloque2 * 3;
for (columna = 0; columna < ANCHO; columna++) {
valor = valor + abs(*pimagen1++ - *pimagen2++) + abs(*pimagen1++ - *pimagen2++) + abs(*pimagen1++ - *pimagen2++);
}
filaBloque2++;
}
return valor;
}
*/
// CON SSE2:
int compararBloque(int filaBloque1, int colBloque1, IplImage *imagen1, int filaBloque2, int colBloque2, IplImage *imagen2) {
int fila, columna= 0;
__m128i A, B, C, D, E;
int sad;
int total = 0;
for (fila = filaBloque1; fila < ALTO + filaBloque1; fila++) {
__m128i *pimagen1 = (__m128i *) (imagen1->imageData + (fila * imagen1->widthStep) + (colBloque1*3));
__m128i *pimagen2 = (__m128i *) (imagen2->imageData + (filaBloque2 * imagen2->widthStep) + (colBloque2*3));
for (columna = colBloque1; columna < ANCHO*3 + colBloque1; columna= columna + 16) {
A = _mm_load_si128(pimagen1);
B = _mm_load_si128(pimagen2);
C = _mm_sad_epu8(A, B);
D = _mm_srli_si128(C, 8);
E = _mm_add_epi32(C, D);
sad = _mm_cvtsi128_si32(E);
*pimagen1++;
*pimagen2++;
total = total + sad;
}
filaBloque2=filaBloque2+1;
}
return total;
}
|
C
|
#ifndef INC_DEBUGPRINT_H
#define INC_DEBUGPRINT_H
#define DEBUGPRINT_LVL_NONE 0
#define DEBUGPRINT_LVL_FEW 1
#define DEBUGPRINT_LVL_MANY 2
#define DEBUGPRINT_LVL_ALL 3
extern int global_debug_print_level;
#ifdef DEBUG
#define USE_DEBUG_PRINTING 1
#else
#define USE_DEBUG_PRINTING 0
#endif
#define debug_print(lvl, msg) \
if(USE_DEBUG_PRINTING) if(lvl <= global_debug_print_level) Serial.println(msg)
#endif /* INC_DEBUGPRINT_H */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct data
{
int num;
struct data *next;
} Data;
Data *insert(int n, Data *start)
{
Data *new = malloc(sizeof(Data));
new->num = n;
new->next = start;
return new;
}
int ave(Data *start)
{
int ave = 0, total = 0;
while (start != NULL)
{
total++;
ave = (ave * (total - 1) + start->num) / total;
start = start->next;
}
return ave;
}
int main()
{
Data *start = NULL;
char line[100];
int number;
while (fgets(line, 100, stdin) != NULL)
{
number = atoi(line);
start = insert(number, start);
}
printf("%d\n", ave(start));
return 0;
}
|
C
|
//
// Created by Sujay Bhowmick on 9/17/21.
//
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "employee.h"
Employee *createEmployee(char name[], unsigned char age) {
Employee *e1 = (Employee *) malloc(sizeof(Employee));
strcpy(e1->name, name);
e1->age = age;
return e1;
}
void freeEmployee(Employee *e) {
free(e);
}
int compareEmployee(Employee *e1, Employee *e2) {
return strcmp(e1->name, e2->name);
}
void displayEmployee(Employee *employee) {
printf("%s", employee->name);
for (int i = 0; i < (55 - strlen(employee->name)); i++) {
printf("%s", " ");
}
printf("%d\n", employee->age);
}
|
C
|
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<errno.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
typedef struct {//super block utilization-1023 bytes
unsigned int isize;
unsigned int fsize;
unsigned int nfree;
unsigned int free[150];
unsigned int ninode;
unsigned int inode[100];
char flock;
char ilock;
char fmod;
unsigned short time[2];
}superblock;
typedef struct {//inode size-64bytes
unsigned short flags;
unsigned short nlinks;
unsigned short uid;
unsigned short gid;
unsigned short size0; // -2 bytes of size
unsigned short size1;//-2 bytes of size-toatal 4 bytes,makes max 4gb file possible
unsigned int addr[12]; //one level of triple indirect block can support 4gb.
unsigned short actime;
unsigned short modtime[2];
}inode;
typedef struct {
unsigned short inode_number;//inode which is allocated to the directory
char name[14];//name corresponding to the directory
}directory;
//free array structure for chaining the blocks
typedef struct {
unsigned int nfree;
unsigned int free[150];
}freeArray;
int initfs(int fd,unsigned short num_blck,unsigned short num_of_inodes ){
superblock super;
//setting fsize;
super.fsize=num_blck;
int number_of_blocks=num_blck;
int inodesize=64;
int inode_mem=num_of_inodes*inodesize;
int blocksize=1024;
int blocks_into_freearray;
int inodes_into_inodearray;
//calculating iszie
if(inode_mem%blocksize==0){
super.isize=inode_mem/blocksize;
}
else{
super.isize=inode_mem/blocksize+1;
}
/*isize number of blocks to inodes,1st two blocks are bootloader and superblock
and the 1st data block is allocated to the contents of root dierctory*/
int filled_blocks=3+super.isize;
int remaining_blocks=num_blck-filled_blocks;
/*setting free array and nfree*/
super.nfree=150;//setting nfree as 150
//free blocks are less than 150
if(remaining_blocks<150){
//setting nfree
blocks_into_freearray=remaining_blocks;
remaining_blocks=0;
}
//free blocks are more than 150
else if(remaining_blocks>150){
blocks_into_freearray=150;
remaining_blocks=remaining_blocks-150;
}
for(int i=0;i<blocks_into_freearray;i++){
super.free[i]=filled_blocks+i;
}
/*setting nionode and inode array*/
super.ninode=100;//number of free inodes in the list of inodes
int first_free_inode_number=2;//inode 1 will be allocated during the initialization of the root directory
if(num_of_inodes<=100){
inodes_into_inodearray=num_of_inodes-1;
}
else if(num_of_inodes>100){
inodes_into_inodearray=100;
}
super.ninode=inodes_into_inodearray;
for(int j=0;j<inodes_into_inodearray;j++){
super.inode[j]=first_free_inode_number+j;
}
super.fmod = 'N';
super.flock = 'Y';
super.ilock='N';
lseek(fd,1024,SEEK_SET);//moving to the superblock in the file
write(fd, &super, 1024);//write the superblock in the next 1024 bytes of the file which will be the superblock
superblock s2;
lseek(fd,1024,SEEK_SET);
read(fd,&s2,1024);
printf("s2 components: isize = %d, fsize = %d,nfree= %d,ninode= %d\n",s2.isize, s2.fsize,s2.nfree,s2.ninode);//printing the initialized components
printf("printing superblock free array\n");
for(int i=0;i<150;i++){
printf("%d",s2.free[i]);//printing free array
printf(", ");
}
printf("\n");
/*initialize inode 1 with root directory information*/
initialize_rootdir(fd,filled_blocks);
/*link the free array for chaining free data blocks*/
chainfreearray(fd,remaining_blocks,filled_blocks);
/*testing chaining of free blocks*/
print_next_set_of_chainedblocks(fd,filled_blocks,remaining_blocks);//to test if chaining is correct
return 1;
}
void print_next_set_of_chainedblocks(int fd, int filled_blocks,int remaining_blocks){
int to_add_to_free_array;
while(remaining_blocks>0){
if(remaining_blocks<150){
to_add_to_free_array=remaining_blocks;
remaining_blocks=0;
}
else{
to_add_to_free_array=150;
remaining_blocks=remaining_blocks-150;
}
lseek(fd,filled_blocks*1024,SEEK_SET);//move to first data block which conatins the list of next set of free datablocks
freeArray f1;
read(fd,&f1,604);
printf("chained free array\n");
printf("nfree value: %d\n",f1.nfree);
for(int i=0;i<to_add_to_free_array;i++){
printf("%d",f1.free[i]);
printf(", ");
}
printf("\n");
filled_blocks=filled_blocks+150;
}
}
//link the free array for chaining free data blocks
void chainfreearray(int fd,int remaining_blocks,int filled_blocks)
{
freeArray freearr;
int to_add_data_blocks;// number of datablocks to be added to freelist
while(remaining_blocks>0){//whenever data blocks remain
lseek(fd,(filled_blocks*1024),SEEK_SET);//move pointer to the first available data block
filled_blocks+=150;//increment the freeblocks by the freearray size
if(remaining_blocks<150){
to_add_data_blocks=remaining_blocks;
freearr.nfree = remaining_blocks;
remaining_blocks = 0;
}
else{
to_add_data_blocks=150;
freearr.nfree =150;
remaining_blocks =remaining_blocks-150;
}
for(int k=0;k<to_add_data_blocks;k++){
freearr.free[k]=filled_blocks+k;
}
/*printf("set of chained logical blocks");
for(int i=0;i<to_add_data_blocks;i++){
printf("%d\n",freearr.free[i]);
}*/
write(fd, &freearr,604);
}
}
void initialize_rootdir(int fd,int filled_blocks){
inode inodestr;//instance of inode struct
//setting inode flags
inodestr.flags=140777;//1-inode is allocated,4-directory,0-userid and groupid on execution not provided,each 7-r,w,execute to ownwner,group,others
inodestr.nlinks = '2';
inodestr.uid = '0';
inodestr.gid = '0';
inodestr.size0 = '0';
inodestr.size1 = 0;
inodestr.addr[0] = filled_blocks-1;//alloting first data block to inode 1's addr[] array.
inodestr.actime = 0;
inodestr.modtime[0] = 0;
inodestr.modtime[1] = 0;
lseek(fd, 2*1024,SEEK_SET);//going to the first inode block position
write(fd, &inodestr,64);//writing the root directory information into the inode1 which is the first 64 bytes
//init root directory's data block
directory dir;
dir.inode_number = 1;//setting inode number for the root to be 1
strncpy(dir.name, ".", 14);//cpying '.' in the name field of the directory
int logical_datablockstomove=filled_blocks-1;//first datablock which corresponds to the root
int totalbytes=logical_datablockstomove*1024;
lseek(fd,totalbytes,SEEK_SET);//moving to the first datablock which corresponds to root directory
write(fd, &dir, 16);//writing the directory structure there
directory dir2;
lseek(fd,totalbytes,SEEK_SET);
read(fd,&dir2,16);
printf("priniting root directory data\n");//verifying root directory information by read from file
printf("name: %s\n",dir2.name);
printf("inode_number: %d\n",dir2.inode_number);
strncpy(dir.name, "..", 14);//setting parent directory name
int to_seek=totalbytes+16;
lseek(fd,to_seek,SEEK_SET);
write(fd, &dir, 16);//writing the directory again
directory dir3;
lseek(fd,to_seek,SEEK_SET);
read(fd,&dir3,16);//verifying root info by reading from file
printf("priniting parent of root directory data\n");
printf("name: %s\n",dir3.name);
printf("inode_number: %d\n",dir3.inode_number);
}
#define TOKEN " "
int main(int args, char *arg[]){
char input[512];
char *input_command;
char *filepath;
char *a, *b, *c;
printf("Enter a command\n");
while( 1 )
{
scanf(" %[^\n]s", input);
input_command = strtok(input," ");
if(strcmp(input_command, "initfs")==0)
{
a = strtok(NULL, TOKEN);
b = strtok(NULL, TOKEN);
c = strtok(NULL, TOKEN);
if (!a | !b | !c)
{
printf("enter proper arguments");
continue;
}
else{
filepath = a;
int num_blck = atoi(b);
int number_of_inodes = atoi(c);
if( access(filepath, F_OK) == -1){
int fd = open(filepath, O_RDWR | O_CREAT , 0777);
if(fd < 0)
{
printf("please enter proper path");
continue;
}
else{
printf("initialized new file system that supports files upto 4GB\n");
initfs(fd, num_blck, number_of_inodes);
}
}
}
}
else if(strcmp(input_command, "q")==0){
printf("saving and exiting\n");
exit(0);
}
}
}
|
C
|
#include "common.h"
TCPSocket* tcpsock_setup(const char* host, int port){
TCPSocket* conn = calloc(sizeof(TCPSocket), 1);
memcpy(conn->host, host, strlen(host));
conn->port = port;
conn->sock = -1;
conn->handle.sin_family = PF_INET;
conn->handle.sin_addr.s_addr = inet_addr(host);
conn->handle.sin_port = htons(port);
conn->sock = socket(PF_INET, SOCK_STREAM, 0);
conn->closed = 0;
return conn;
}
void tcpsock_destroy(TCPSocket* conn){
tcp_close(conn);
free(conn);
}
int tcp_server(TCPSocket* conn){
bind(conn->sock, (struct sockaddr*)(&conn->handle), sizeof(conn->handle));
return listen(conn->sock, 100);
}
int tcp_client(TCPSocket* conn){
if(conn->closed) {
conn->sock = socket(PF_INET, SOCK_STREAM, 0);
conn->closed = 0;
}
return connect(conn->sock, (struct sockaddr*)&(conn->handle), sizeof(conn->handle));
}
TCPSocket* tcp_accept(TCPSocket* serv){
TCPSocket* client = calloc(sizeof(TCPSocket), 1);
unsigned size = sizeof(client->handle);
client->sock = accept(serv->sock, (struct sockaddr*)&(client->handle), &size);
client->port = ntohs(client->handle.sin_port);
memcpy(client->host, inet_ntoa(client->handle.sin_addr), sizeof(client->handle.sin_addr.s_addr));
return client;
}
int tcp_read(TCPSocket* sock, char* buf, int buf_size){
return recv(sock->sock, buf, buf_size, 0);
}
int tcp_write(TCPSocket* sock, char* buf, int buf_size){
return send(sock->sock, buf, buf_size, 0);
}
int tcp_close(TCPSocket* sock){
sock->closed = 1;
return close(sock->sock);
}
|
C
|
//ͷļ
#include "usually.h"
#include "usart.h"
//´,֧printf,Ҫѡuse MicroLIB
#if 1
#pragma import(__use_no_semihosting)
//Ҫֺ֧
struct __FILE
{
int handle;
/* Whatever you require here. If the only file you are using is */
/* standard output using printf() for debugging, no file handling */
/* is required. */
};
/* FILE is typedef d in stdio.h. */
FILE __stdout;
//_sys_exit()Աʹðģʽ
_sys_exit(int x)
{
x = x;
}
//ضfputc
int fputc(int Data, FILE *f)
{
while(!USART_GetFlagStatus(USART1,USART_FLAG_TXE)); //USART_GetFlagStatusõ״̬λ
//USART_FLAG_TXE:ͼĴΪ 1Ϊգ0æ״̬
USART_SendData(USART1,Data); //һַ
while(!USART_GetFlagStatus(USART2,USART_FLAG_TXE)); //USART_GetFlagStatusõ״̬λ
//USART_FLAG_TXE:ͼĴΪ 1Ϊգ0æ״̬
USART_SendData(USART2,Data); //һַ
return Data; //һֵ
}
#endif
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
** : USART1_Send_Byte
** : ڷһַ
** Data Ҫ͵
** : Dream
** ա : 2011620
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
void USART1_Send_Byte(uint16_t Data)
{
while(!USART_GetFlagStatus(USART1,USART_FLAG_TXE)); //USART_GetFlagStatusõ״̬λ
//USART_FLAG_TXE:ͼĴΪ 1Ϊգ0æ״̬
USART_SendData(USART1,Data); //һַ
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
** : USART2_Send_Byte
** : ڷһַ
** Data Ҫ͵
** : Dream
** ա : 2011620
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
void USART2_Send_Byte(uint16_t Data)
{
while(!USART_GetFlagStatus(USART2,USART_FLAG_TXE)); //USART_GetFlagStatusõ״̬λ
//USART_FLAG_TXE:ͼĴΪ 1Ϊգ0æ״̬
USART_SendData(USART2,Data); //һַ
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
** : USART1_Receive_Byte
** : ڽһַ
**
** : Dream
** ա : 2011620
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
uint8_t USART1_Receive_Byte(void)
{
while(!(USART_GetFlagStatus(USART1,USART_FLAG_RXNE))); //USART_GetFlagStatusõ״̬λ
//USART_FLAG_RXNE:ݼĴǿձ־λ
//1æ״̬ 0(ûյݣȴ)
return USART_ReceiveData(USART1); //һַ
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
** : USART2_Receive_Byte
** : ڽһַ
**
** : Dream
** ա : 2011620
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
uint8_t USART2_Receive_Byte(void)
{
while(!(USART_GetFlagStatus(USART2,USART_FLAG_RXNE))); //USART_GetFlagStatusõ״̬λ
//USART_FLAG_RXNE:ݼĴǿձ־λ
//1æ״̬ 0(ûյݣȴ)
return USART_ReceiveData(USART2); //һַ
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
** : Usart_Init1
** : ųʼ
** :
** : Dream
** ա : 2011620
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
void Init_Usart1(void)
{
GPIO_InitTypeDef GPIO_InitStructure; //һGPIOṹ
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_USART1,ENABLE);
//ʹܸ˿ʱӣҪ
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //ôڽն˿ڹҽӵ9˿
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //ù©
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //ö˿ٶΪ50M
GPIO_Init(GPIOA, &GPIO_InitStructure); //ݲʼGPIOAĴ
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //(λ״̬);
GPIO_Init(GPIOA, &GPIO_InitStructure); //ݲʼGPIOAĴ
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
** : Usart_Init2
** : ųʼ
** :
** : Dream
** ա : 2011620
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
void Init_Usart2(void)
{
GPIO_InitTypeDef GPIO_InitStructure; //һGPIOṹ
RCC_APB1PeriphClockCmd(RCC_APB2Periph_GPIOA |RCC_APB1Periph_USART2,ENABLE);
//ʹܸ˿ʱӣҪ
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; //ôڽն˿ڹҽӵ9˿
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //ù©
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //ö˿ٶΪ50M
GPIO_Init(GPIOA, &GPIO_InitStructure); //ݲʼGPIOAĴ
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //(λ״̬);
GPIO_Init(GPIOA, &GPIO_InitStructure); //ݲʼGPIOAĴ
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
** : Usart1_Configuration
** : ú
** : BaudRateò
** : Dream
** ա : 2011620
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
void Usart1_Configuration(uint32_t BaudRate)
{
USART_InitTypeDef USART_InitStructure; //һڽṹ
USART_InitStructure.USART_BaudRate =BaudRate ; //115200
USART_InitStructure.USART_WordLength = USART_WordLength_8b; //ʹ8λ
USART_InitStructure.USART_StopBits = USART_StopBits_1; //֡β1λֹͣλ
USART_InitStructure.USART_Parity = USART_Parity_No ; //żʧ
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//Ӳʧ
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //պͷģʽ
USART_Init(USART1, &USART_InitStructure); //ݲʼڼĴ
USART_ITConfig(USART1,USART_IT_RXNE,ENABLE); //ʹܴжϽ
USART_Cmd(USART1, ENABLE); //ʹܴ
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
** : Usart2_Configuration
** : ú
** : BaudRateò
** : Dream
** ա : 2011620
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
void Usart2_Configuration(uint32_t BaudRate)
{
USART_InitTypeDef USART_InitStructure; //һڽṹ
USART_InitStructure.USART_BaudRate =BaudRate ; //115200
USART_InitStructure.USART_WordLength = USART_WordLength_8b; //ʹ8λ
USART_InitStructure.USART_StopBits = USART_StopBits_1; //֡β1λֹͣλ
USART_InitStructure.USART_Parity = USART_Parity_No ; //żʧ
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//Ӳʧ
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //պͷģʽ
USART_Init(USART2, &USART_InitStructure); //ݲʼڼĴ
USART_ITConfig(USART2,USART_IT_RXNE,ENABLE); //ʹܴжϽ
USART_Cmd(USART2, ENABLE); //ʹܴ
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
** : USART1_IRQHandler
** : жϺ
** :
** : Dream
** ա : 2011620
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
void USART1_IRQHandler()
{
uint8_t ReceiveDate; //һŽյ
if(!(USART_GetITStatus(USART1,USART_IT_RXNE))); //ȡжϱ־λUSART_IT_RXNE
//USART_FLAG_RXNE:ݼĴǿձ־λ
//1æ״̬ 0(ûյݣȴ)
{
USART_ClearITPendingBit(USART1,USART_IT_RXNE); //жϱ־λ
ReceiveDate=USART_ReceiveData(USART1); //ַ
// printf("%d",(char*)ReceiveDate); //ʮֵ,ǿԿеļֵӦʮ
//"1"Ӧ49 "A" ӦֵΪ65
printf("\n\r"); //ö
USART1_Send_Byte(ReceiveDate);
}
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
** : USART2_IRQHandler
** : жϺ
** :
** : Dream
** ա : 2011620
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
void USART2_IRQHandler()
{
uint8_t ReceiveDate1; //һŽյ
if(!(USART_GetITStatus(USART2,USART_IT_RXNE))); //ȡжϱ־λUSART_IT_RXNE
//USART_FLAG_RXNE:ݼĴǿձ־λ
//1æ״̬ 0(ûյݣȴ)
{
USART_ClearITPendingBit(USART2,USART_IT_RXNE); //жϱ־λ
ReceiveDate1=USART_ReceiveData(USART2); //ַ
// printf("%d",(char*)ReceiveDate); //ʮֵ,ǿԿеļֵӦʮ
//"1"Ӧ49 "A" ӦֵΪ65
printf("\n\r"); //ö
USART1_Send_Byte(ReceiveDate1);
}
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
End:-D:-D:-D:-D:-D:-D:-D:-D:-D:-D:-D:-D:-D:-D:-D:-D:-D:-D:-D:-D
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
|
C
|
#include <stdio.h>
typedef struct s {
char c[9];
int i[10];
double d[10]
} s_t;
int main() {
printf("size of struct is : %d \n", sizeof(s_t));
return 0;
}
// 9+7 + 40 + 80 = 136, but the real output is 132, very weird. hmm...
// update: since the maximum padding is on the basis of highest size of bus size and maximum member size
// For 32 Bit - Max alignment is 4 Bytes
// For 64 Bit - Max alignment is 8 Bytes
|
C
|
/* LTAGLT.C - Convert all voxels of specified value in a lattice to an
ignore_tag.
Author: Mike Wall
Date: 5/5/95
Version: 1.
*/
#include<mwmask.h>
int ltaglt(LAT3D *lat)
{
size_t
i,
j,
k,
r,
index = 0;
for(k = 0; k < lat->zvoxels; k++) {
for(j = 0; j < lat->yvoxels; j++) {
for (i = 0; i < lat->xvoxels; i++) {
if (lat->lattice[index] == lat->rfile[0]) {
lat->lattice[index] = lat->rfile[1];
}
index++;
}
}
}
}
|
C
|
/* ************************************************************************** */
/* LE - / */
/* / */
/* signal.c .:: .:/ . .:: */
/* +:+:+ +: +: +:+:+ */
/* By: dzonda <marvin@le-101.fr> +:+ +: +: +:+ */
/* #+# #+ #+ #+# */
/* Created: 2018/06/06 02:24:12 by dzonda #+# ## ## #+# */
/* Updated: 2018/10/07 08:56:57 by dzonda ### #+. /#+ ###.fr */
/* / */
/* / */
/* ************************************************************************** */
#include "ft_select.h"
static void ft_handle_signal_quit(int signo)
{
t_select *select;
(void)signo;
ft_select_save(&select, 1);
ft_disable_raw(select->termios);
exit(EXIT_FAILURE);
}
static void ft_handle_signal_tstp(int signo)
{
t_select *select;
(void)signo;
ft_select_save(&select, 1);
signal(SIGTSTP, SIG_DFL);
ioctl(STDIN_FILENO, TIOCSTI, "\x1A");
ft_disable_raw(select->termios);
}
static void ft_handle_signal_resize(int signo)
{
t_select *select;
ft_select_save(&select, 1);
ft_tcaps_exec("ho");
ft_tcaps_exec("cd");
if (signo == SIGCONT)
{
ft_enable_raw(&(select->termios));
signal(SIGTSTP, ft_handle_signal_tstp);
}
select->map = ft_select_get_map(select);
if (select->map.screen_height > 2)
ft_select_print(select);
}
void ft_handle_signal(void)
{
unsigned int signo;
signo = 0;
while (++signo < 32)
{
if (signo == SIGINT || signo == SIGQUIT || signo == SIGTERM)
signal(signo, ft_handle_signal_quit);
if (signo == SIGTSTP)
signal(signo, ft_handle_signal_tstp);
if (signo == SIGCONT || signo == SIGWINCH)
signal(signo, ft_handle_signal_resize);
}
}
|
C
|
/*
** EPITECH PROJECT, 2020
** matchstick
** File description:
** print map functions
*/
#include <unistd.h>
#include "header.h"
void print_map(char **map, int line, int game_status)
{
int x = 0;
for (int y = 0; y != line + 2; y++) {
for (; x != line * 2 + 1; x++) {
my_putchar(map[y][x]);
}
my_putchar('\n');
x = 0;
}
if (game_status == 0)
my_putchar('\n');
}
void print_removed_match(linematch_t lm)
{
my_putstr("Player removed ");
my_putnbr(my_atoi(lm.match));
my_putstr(" match(es) from line ");
my_putnbr(my_atoi(lm.line));
my_putchar('\n');
}
int player_turn(int size, int const max, char **map, int *turn)
{
linematch_t lm = {NULL, NULL};
size_t sizeuh;
if (*turn == 1)
my_putstr("Your turn:\n");
my_putstr("Line: ");
if (getline(&lm.line, &sizeuh, stdin) == -1)
return (84);
if (invalid_line(max, size, map, lm) == 1) {
*turn = -1;
return (1);
}
my_putstr("Matches: ");
if (getline(&lm.match, &sizeuh, stdin) == -1)
return (84);
if (invalid_match(max, size, map, lm) == 1) {
*turn = -1;
return (1);
}
print_removed_match(lm);
remove_match(map, my_atoi(lm.line), my_atoi(lm.match));
*turn = 2;
return (0);
}
|
C
|
#include "logger.h"
extern int errno;
LOGGER_BOOL log_init(logger *l){
/*fname is ignored if mode is MODE_CONS or MODE_SYSLOG
* priority cant be greater than 7
* log.priority=log.priority & 0x07
*/
switch(l->mode){
case MODE_CONS:
break;
case MODE_SYSLOG:
/*open syslog : ident,log_opt,fac*/
openlog(l->prog_name,LOGGER_OPT,LOGGER_FAC);
break;
case MODE_FILE:
/*try to open file*/
if((l->fp=fopen(l->fname,"a+b"))==NULL){
fprintf(stderr,"Error in creating file: \n");
perror(l->prog_name);
return FALSE;
}
break;
default :
/*if an invalid mode then use syslog*/
l->mode=MODE_SYSLOG;
break;
}
/*only extrem case of error such as direcory or file not writeble will be reported as FATAL
* and log_init() will fail
*/
return TRUE;
}
void log_msg(logger l,const char*msg){
/*ready the output string */
time_t the_time;
char time_buff[256],hostname[256];
int len=0;
gethostname(hostname,256);
(void) time(&the_time);
strncpy(time_buff,ctime(&the_time),255);
/*overwrite the newline marker attached with ctime() returnred string */
len=strlen(time_buff);
time_buff[len-1]='\0';
switch(l.mode){
case MODE_CONS:
fprintf(stderr,"%s %s[%d] @ %s: %s\n",time_buff,l.prog_name,l.pid,hostname,msg);
break;
case MODE_FILE:
fprintf(l.fp,"%s %s[%d] @ %s: %s\n",time_buff,l.prog_name,l.pid,hostname,msg);
break;
default:
/*default is MODE_SYSLOG*/
syslog(l.priority,"%s:",msg);
break;
}
}
void close_log(logger l){
switch(l.mode){
case MODE_CONS:
/*nothing special but we dont use closelog() in this mode so special case -not same as of MODE_SYSLOG*/
break;
case MODE_FILE:
/*close file descriptor*/
fclose(l.fp);
break;
default:
/*MODE_SYSLOG is handled here */
closelog();
break;
}
}
int main(){
logger log;
strcpy(log.prog_name,"logger_test");
log.mode=MODE_FILE;
log.priority=LOG_INFO; /*any one out of seven*/
strcpy(log.fname,"test.log");
log.pid=getpid();
if(log_init(&log)==FALSE){
sdebug("log_init:FAILED");
return EXIT_FAILURE;
}
log_msg(log,"starting up");
close_log(log);
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
//int M, N;
int K;
typedef struct
{
int sx;
int sy;
int ex;
int ey;
}BUS;
BUS bus[5000];
int chk[5000];
int sx, sy, ex, ey;
typedef struct
{
int bus_n;
int cnt;
}QUEUE;
QUEUE queue[5000];
int wp, rp;
#define Enqueue(X) (queue[wp++] = (X))
#define Dequeue(X) ((X) = queue[rp++])
#define QueueNotEmpty (wp > rp)
void Input_Data(void)
{
int i,m, n;
scanf("%d %d",&m,&n);
scanf("%d",&K);
for (i = 0; i < K;i++)
{
scanf("%d %d %d %d %d", &m, &bus[i].sx, &bus[i].sy,
&bus[i].ex, &bus[i].ey);
// 가로
if (bus[i].sx == bus[i].ex)
{
if (bus[i].sy > bus[i].ey)
{
int temp;
temp = bus[i].sy;
bus[i].sy = bus[i].ey;
bus[i].ey = temp;
}
}
// 세로
else if (bus[i].sy == bus[i].ey)
{
if (bus[i].sx > bus[i].ex)
{
int temp;
temp = bus[i].sx;
bus[i].sx = bus[i].ex;
bus[i].ex = temp;
}
}
}
scanf("%d %d %d %d", &sx, &sy, &ex, &ey);
}
int BFS(void)
{
QUEUE data, ndata;
int i;
for (i = 0; i < K; i++)
{
if ((bus[i].sx <= sx) && (sx <= bus[i].ex) &&
(bus[i].sy <= sy) && (sy <= bus[i].ey))
{
data.bus_n = i;
data.cnt = 1;
Enqueue(data);
chk[i] = 1;
}
}
while (QueueNotEmpty)
{
Dequeue(data);
if ((bus[data.bus_n].sx <= ex) && (ex <= bus[data.bus_n].ex) &&
(bus[data.bus_n].sy <= ey) && (ey <= bus[data.bus_n].ey))
{
return data.cnt;
}
for (i = 0; i < K; i++)
{
if (chk[i]) continue;
if (!((bus[i].sx <= bus[data.bus_n].sx && bus[data.bus_n].sx <= bus[i].ex)
|| (bus[data.bus_n].sx <= bus[i].sx && bus[i].sx <= bus[data.bus_n].ex)))
continue;
if (!((bus[i].sy <= bus[data.bus_n].sy && bus[data.bus_n].sy <= bus[i].ey)
|| (bus[data.bus_n].sy <= bus[i].sy && bus[i].sy <= bus[data.bus_n].ey)))
continue;
ndata.bus_n = i;
ndata.cnt = data.cnt + 1;
Enqueue(ndata);
chk[i] = 1;
}
}
return -1;
}
int main(void)
{
Input_Data();
printf("%d\n", BFS());
return 0;
}
|
C
|
int num(int m, int n)
{
if(m <= 1) return 1;
if(n == 1) return 1;
int sum = 0, i;
for(i = 1; i <= n; i++)
{
if(i > m) break;
sum += num(m - i, i);
}
return sum;
}
int main()
{
int n, i;
scanf("%d", &n);
for(i = 0; i < n; i++)
{
int M, N;
scanf("%d%d", &M, &N);
int r = num(M, N);
printf("%d\n", r);
}
return 0;
}
|
C
|
#include "helpers.h"
#include "math.h"
#include "stdlib.h"
#include "stdio.h"
// Convert image to grayscale
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
//accessing all the pixels
for (int i = 0 ; i < height ; i++)
{
for (int j = 0; j < width; j++)
{
// taking the average of r,g,b
float averagecolor = ((float) image[i][j].rgbtRed + (float) image[i][j].rgbtGreen + (float) image[i][j].rgbtBlue) / 3;
//printf("%f,%f",averagecolor, round(averagecolor));
//changing with new values
image[i][j].rgbtRed = round(averagecolor);
image[i][j].rgbtGreen = round(averagecolor);
image[i][j].rgbtBlue = round(averagecolor);
}
}
return;
}
// Convert image to sepia
void sepia(int height, int width, RGBTRIPLE image[height][width])
{
//usual accesing all the pixels
for (int i = 0 ; i < height ; i++)
{
for (int j = 0 ; j < width ; j++)
{
// sapia effect
float sapiared = (((float) image[i][j].rgbtRed * 393 / 1000) + ((float) image[i][j].rgbtGreen * 769 / 1000) +
((float) image[i][j].rgbtBlue * 189 / 1000));
float sapiagreen = (((float) image[i][j].rgbtRed * 349 / 1000) + ((float) image[i][j].rgbtGreen * 686 /1000) +
((float) image[i][j].rgbtBlue * 168 / 1000));
float sapiablue = (((float) image[i][j].rgbtRed * 272 / 1000) + ((float) image[i][j].rgbtGreen * 534 / 1000) +
((float) image[i][j].rgbtBlue * 131 / 1000));
// These if's for preventing not the exceed unsigned chars byte limit
if (sapiared > 255)
{
image[i][j].rgbtRed = 255;
}
else
{
image[i][j].rgbtRed = round(sapiared);
}
if (sapiagreen > 255)
{
image[i][j].rgbtGreen = 255;
}
else
{
image[i][j].rgbtGreen = round(sapiagreen);
}
if (sapiablue > 255)
{
image[i][j].rgbtBlue = 255;
}
else
{
image[i][j].rgbtBlue = round(sapiablue);
}
}
}
return;
}
// Reflect image horizontally
void reflect(int height, int width, RGBTRIPLE image[height][width])
{
RGBTRIPLE emptyglass[height][width];
for (int i = 0 ; i < height ; i++)
{
for (int j = 0; j < width; j++)
{
emptyglass[i][j].rgbtRed = image[i][width - 1 - j].rgbtRed;
emptyglass[i][j].rgbtGreen = image[i][width - 1 - j].rgbtGreen;
emptyglass[i][j].rgbtBlue = image[i][width - 1 - j].rgbtBlue;
//image[i][j].rgbtRed = image[i][width - 1].rgbtRed;
//image[i][j].rgbtGreen = image[i][width - 1].rgbtGreen;
//image[i][j].rgbtBlue = image[i][width - 1].rgbtBlue;
}
for (int j = 0; j < width ; j++)
{
image[i][j].rgbtRed = emptyglass[i][j].rgbtRed;
image[i][j].rgbtGreen = emptyglass[i][j].rgbtGreen;
image[i][j].rgbtBlue = emptyglass[i][j].rgbtBlue;
}
}
return;
}
// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{
for (int i = 1; i < height - 1 ; i++)
{
for (int j = 1 ; j < width - 1 ; j++)
{
if (i < 1 || j < 1 || i + 1 == width || j + 1 == height)
{
continue;
}
float a = ((float)image[i][j].rgbtRed +
(float) image[i][j + 1].rgbtRed +
(float) image[i][j - 1].rgbtRed +
(float) image[i + 1][j].rgbtRed +
(float) image[i - 1][j].rgbtRed +
(float) image[i - 1][j - 1].rgbtRed +
(float) image[i + 1][j + 1].rgbtRed +
(float) image[i - 1][j + 1].rgbtRed +
(float) image[i + 1][j - 1].rgbtRed) / 9;
float b = ((float) image[i][j].rgbtBlue +
(float) image[i][j + 1].rgbtBlue +
(float) image[i][j - 1].rgbtBlue +
(float) image[i + 1][j].rgbtBlue +
(float) image[i - 1][j].rgbtBlue +
(float) image[i - 1][j - 1].rgbtBlue +
(float) image[i + 1][j + 1].rgbtBlue +
(float) image[i - 1][j + 1].rgbtBlue +
(float) image[i + 1][j - 1].rgbtBlue) / 9;
float c = ((float) image[i][j].rgbtGreen +
(float) image[i][j + 1].rgbtGreen +
(float) image[i][j - 1].rgbtGreen +
(float) image[i + 1][j].rgbtGreen +
(float) image[i - 1][j].rgbtGreen +
(float) image[i - 1][j - 1].rgbtGreen +
(float) image[i + 1][j + 1].rgbtGreen +
(float) image[i - 1][j + 1].rgbtGreen +
(float) image[i + 1][j - 1].rgbtGreen) / 9;
image[i][j].rgbtRed = round(a);
image[i][j].rgbtBlue = round(b);
image[i][j].rgbtGreen = round(c);
}
}
return;
}
|
C
|
/*
** vm_calc_instructions.c for src in /home/chapea_o/travail/corewar/git_corewar/corewar/vm/src
**
** Made by olivier chapeau
** Login <chapea_o@epitech.net>
**
** Started on Tue Dec 11 15:57:52 2012 olivier chapeau
** Last update Sun Dec 16 15:29:06 2012 olivier chapeau
*/
#include "vm.h"
#include "vm_processes.h"
void add(t_vm *vm, int id)
{
unsigned char encoding_byte;
char params[3];
t_processus *processus;
if ((processus = get_processus_by_id(vm, id)) == NULL)
return ;
encoding_byte = vm->memory[++processus->pc];
if ((encoding_byte & PARAM1) != 0x40
|| (encoding_byte & PARAM2) != 0x10
|| (encoding_byte & PARAM3) != 0x04)
{
processus->carry = 0;
return ;
}
params[0] = processus->registers[vm->memory[++processus->pc]];
params[1] = processus->registers[vm->memory[++processus->pc]];
params[2] = vm->memory[++processus->pc];
processus->registers[params[2]] = params[0] + params[1];
processus->carry = 1;
}
void sub(t_vm *vm, int id)
{
unsigned char encoding_byte;
char params[3];
t_processus *processus;
if ((processus = get_processus_by_id(vm, id)) == NULL)
return ;
encoding_byte = vm->memory[++processus->pc];
if ((encoding_byte & PARAM1) != 0x40
|| (encoding_byte & PARAM2) != 0x10
|| (encoding_byte & PARAM3) != 0x04)
{
processus->carry = 0;
return ;
}
params[0] = processus->registers[vm->memory[++processus->pc]];
params[1] = processus->registers[vm->memory[++processus->pc]];
params[2] = vm->memory[++processus->pc];
processus->registers[params[2]] = params[0] - params[1];
processus->carry = 1;
}
|
C
|
/*
* File: FSM_Server.h
* Author: Grupo1
*
* Created on March 24, 2018
*/
#ifndef FSM_SERVER_H
#define FSM_SERVER_H
/*******************************************************************************
CONSTANT AND MACRO DEFINITIONS USING #DEFINE
******************************************************************************/
#define SIZEEVENTQUEUE 100 //Size of event queue
/*******************************************************************************
ENUMS, STRUCTS Y TYPEDEFS
******************************************************************************/
typedef enum { END_OF_TABLE, MOVE, ACK, TIME_OUT ,
TIME_OUT_2, QUIT, ERROR1 ,GARBAGE , RESET , I_AM_READY,
INVALID_ACKCODE,VALID_ACKCODE, START_COMMUNICATION } event_t;
typedef enum { CLEAR, FETCH }mode_t;//typedef for the function get_ev
/*
EVENT TABLE
MOVE_RECEIVED:'b'
MOVE_SENT: 'c'
ACK: 'd'
TIME_OUT: 'e'
TIME_OUT_2: 'f'
QUIT: 'g'
ERROR:'h'
GARBAGE: 'i'
RESET: 'j'
I_AM_READY: 'k'
INVALID_ACKCODE: 'm'
VALID_ACKCODE: 'o'
END_COMMUNICATION: 'n'
*/
/* CONNECTION PROTOCOL EVENTS:
- MOVE_RECEIVED: The machine picks up a MOVE event from the other computer. We decide we have to make a difference between an incoming
MOVE and an outgoing one beacuse the latter will have to wait for the ACK of their pair and in the case of the former
the machine itself will send the ACK.
- MOVE_SENT: The machine sends a MOVE event to the other computer.
- ACK: The computer flags the success in the communication of a package.
- INVALID_ACK: The devide receives an ACK that doesnt match with the ID of the MOVE sent.
- VALID_ACK: The device recieves an ACK that does match with the ID of the MOVE sent. It becomes available again for a new interaction.
- TIMEOUT: A previously defined time pass without receiving the ACK attach to a certain package already sent. The program proceeds
to resent the MOVE package.
- TIMEOUT_2: A previously defined time that flags that is occurring a problem in the conncection between the devices.
- QUIT: A device consciously want to end the connection between the pair, so it sends this particular message.
- GARBAGE: Some undetermined message is received, the connection is not working properly.
- RESET: The user wants to restart de protocol communication between the devices.
- I_AM_READY_SERVER: The server starts the protocol communication updating its status to ready.
- I_AM_READY_CLIENT: The client device acknowledges that its also ready to start the information exchange.
- END_COMMUNICATION: Both devices agreed to finish the connection between them.
*/
typedef enum { OFF, ON } switch_t;
typedef unsigned int uint;
/*****************************************************
* DEFINITION OF EDGE
* **************************************************/
typedef struct edge edge_t;
struct edge
{
event_t event;
edge_t *nextstate;
void(*fun_trans)(void);
};
/*******************************************************************************
FSM STATES
******************************************************************************/
//Every state is represent by an array
extern edge_t Initiating_state[];
extern edge_t Waiting_for_ClientOK_state[];
extern edge_t Finishing_configuration[];
extern edge_t Looping_state[];
extern edge_t Waiting_to_send_ACK_state[];
extern edge_t Waiting_for_ACK_state[];
extern edge_t Resending_MOVE[];
extern edge_t Analyzing_ACK[];
extern edge_t Sending_ERROR[];
#endif /* FSM_H */
|
C
|
#include <stdio.h>
#include <string.h>
#define ARRAY_LEN 4096
double x[ ARRAY_LEN ];
double y[ ARRAY_LEN ];
int main( int argc, char **argv )
{
const double alpha = 2.1;
for ( int i = 0; i < ARRAY_LEN; ++i )
{
y[ i ] = 0.0;
x[ i ] = 1.0;
}
#pragma omp simd
for ( int i = 0; i < ARRAY_LEN; ++i )
{
y[ i ] += alpha * x[ i ];
}
#if 0
_Pragma( "omp simd" )
for ( int i = 0; i < ARRAY_LEN; ++i )
{
x[ i ] += alpha * y[ i ];
}
#endif
return 0;
}
|
C
|
#ifndef JOYSTICK_H
#define JOYSTICK_H
// Button mappings
#define BTN_INCSPEED 10
#define BTN_DECSPEED 13
#define BTN_TURNLEFT -1
#define BTN_TURNRIGHT -2
#define BTN_ASCEND 6
#define BTN_DESCEND 7
#define BTN_EMERGSTOP -3
#define BTN_ZEROSPEED 2
#define BTN_ARM_TORPEDO 1
#define BTN_ARM_MARKER 3
#define BTN_FIRE 0
#define AXIS_TSPEED 0
#define AXIS_SPEED 1
#define AXIS_YAW 2
#define AXIS_THROTTLE 3
int scaleAxis(int val, int negRange, int posRange, int offset, int outRange)
{
val += offset;
if(val < 0) /* Forward, range up to 15677 */
val = outRange * val / negRange;
else
val = outRange * val / posRange;
if(val > outRange)
val = outRange;
if(val < -outRange)
val = -outRange;
return val;
}
#define SCALE_SPEED(val) \
scaleAxis(val, -14000, -15000, 6811, SPEED_RANGE)
#define SCALE_YAW(val) \
scaleAxis(val, 18504, 18504, 4498, YAW_RANGE)
#define SCALE_TSPEED(val) \
scaleAxis(val, 15934, 17476, 10152, TSPEED_RANGE)
#define SCALE_THROTTLE(val) \
scaleAxis(val, -19789, -19789, 8867, SPEED_RANGE)
#include "joystick.h"
#define INFO_MESSAGE \
"Using Saitek mapping\n\tThumb L-Ascend\n\tThumb R-Descend\n\tPOV Hat - Fwd/Back, Turn\n\tZ trigger- Emergency stop\n\tButton under POV Hat - zer speed to 0\n"
#endif // JOYSTICK_H
|
C
|
#include "linkedList.h"
Node *head = NULL;
void print_list(){
Node *list = head;
while(list != NULL){
printf("%d\t", list->value);
list= list->next;
}
printf("\n");
}
void push(int value){
Node *list = (Node*) malloc(sizeof(Node));
list->value = value;
list->next = head;
head= list;
}
void insert_last(int value){
Node *current = head;
while(current->next != NULL){
current= current->next;
}
current->next = (Node*) malloc(sizeof(Node));
current->next->value = value;
current->next->next = NULL;
}
Node* pop(){
Node *tempList = head;
head= head->next;
return tempList; // Return the deleted link
}
Node* delete_last(){
Node *current = head;
if(head->next == NULL){
head= head->next;
return current;
}
while(current->next->next != NULL)
current = current->next;
Node *temp = current->next;
current->next= current->next->next;
return temp;
}
bool isEmpty(){
return head == NULL;
}
int length(){
int length= 0;
Node *current = (Node*) malloc(sizeof(Node));
for(current= head; current != NULL; current= current->next){
length++;
}
return length;
}
Node* find(int value){
Node *current= head;
if(head == NULL)
return NULL;
while(current->value != value){
if(current->next == NULL)
return NULL;
else
current = current->next;
}
return current;
}
Node* delete(int value){
Node *current = head;
Node *previous = NULL;
if(head == NULL)
return NULL;
while(current->value != value){
if(current->next == NULL)
return NULL;
else{
previous = current;
current = current->next;
}
}
if(current == head)
head = head->next;
else
previous->next = current->next;
return current;
}
void sort(){
int i, j, k, tempValue;
Node *current = (Node*) malloc(sizeof(Node));
Node *next = (Node*) malloc(sizeof(Node));
int size = length();
k= size;
for(i= 0; i<size -1; i++){
current = head;
next = head->next;
for(j= 1; j<k; j++){
if(current->value > next->value){
tempValue = current->value;
current->value = next->value;
next->value = tempValue;
}
current = current->next;
next = next->next;
}
}
}
void reverse(Node **head){
Node *prev = NULL;
Node *current = *head;
Node *next;
while(current != NULL){
next= current->next;
current->next= prev;
prev= current;
current= next;
}
*head= prev;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
float average;
int arr[50],source[50],sum=0,i,N;
printf("Nhap so phan tu cho chuoi : ");
scanf("%d",&N);
for(i=0;i<N;i++)
{
printf("Nhap vao phan tu thu %d cho chuoi : ",i+1);
scanf("%d",&arr[i]);
}
for(i=0;i<N;i++)
{
sum=sum+arr[i];
}
average= sum/N;
for (i=0;i<N;i++)
{
if (arr[i]<=average)
{
source[i]=average-arr[i];
}
else
{
source[i]=arr[i]-average;
}
}
for(i=0;i<N;i++)
{
printf("%d",source[i]);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>
#include "estructuraUno.h"
#include "estructuraDos.h"
#include "funcionesGenericas.h"
#include "menu.h"
#include "hardcode.h"
#include "validaciones.h"
int menuPrincipal()
{
int opcion;
opcion = getInt("=====================================================================\n"
"|| MENU: ||\n"
"|| 1. Alta ||\n"
"|| ||\n"
"|| 2. Listar ||\n"
"|| ||\n"
"|| 3. Baja ||\n"
"|| ||\n"
"|| 4. Modificar ||\n"
"|| ||\n"
//"5. Baja director\n"
//"6. Mostrar\n"
"|| 5. Salir ||\n"
"|| ||\n"
"=====================================================================\n"
"Ingrese una opcion: ");
while((opcion < 0 && opcion != 777) || (opcion > 5 && opcion != 777))
{
printf("Ingrese una opcion valida\n");
system("pause");
system("cls");
opcion = getInt("=====================================================================\n"
"|| MENU: ||\n"
"|| 1. Alta ||\n"
"|| ||\n"
"|| 2. Listar ||\n"
"|| ||\n"
"|| 3. Baja ||\n"
"|| ||\n"
"|| 4. Modificar ||\n"
"|| ||\n"
//"|| 5. Baja director\n"
//"6. Mostrar\n"
"|| 5. Salir ||\n"
"|| ||\n"
"=====================================================================\n"
"Ingrese una opcion: ");
}
return opcion;
}
int subMenuAltas()
{
int opcion;
opcion = getInt(" 1. Agregar datos a Cosas Uno\n"
" 2. Agregar datos a Cosas Dos\n");
while(opcion < 0 || opcion > 2)
{
opcion = getInt("Por favor, ingrese una opcion valida\n"
" 1. Agregar datos a Cosas Uno\n"
" 2. Agregar datos a Cosas Dos\n");
}
return opcion;
// switch(opcion)
// {
// case 1:
// agregarDato(arrayCosasUno, LIMITE);
// break;
// case 2:
// agregarDatoDos(arrayCosasDos, LIMITE);
// break;
// }
}
int subMenuListar()
{
int opcion;
opcion = getInt(" 1. Mostrar datos de Cosas Uno\n"
" 2. Mostrar datos de Cosas Dos\n");
while(opcion < 0 || opcion > 2)
{
opcion = getInt("Por favor, ingrese una opcion valida\n"
" 1. Mostrar datos de Cosas Uno\n"
" 2. Mostrar datos de Cosas Dos\n");
}
return opcion;
}
int subMenuBaja()
{
int opcion;
opcion = getInt(" 1. Dar de baja elemento de Cosas Uno\n"
" 2. Dar de baja elemento de Cosas Dos\n");
while(opcion < 0 || opcion > 2)
{
opcion = getInt("Por favor, ingrese una opcion valida\n"
" 1. Dar de baja elemento de Cosas Uno\n"
" 2. Dar de baja elemento de Cosas Dos\n");
}
return opcion;
}
int subMenuModificar()
{
int opcion;
opcion = getInt(" 1. Modificar elemento de Cosas Uno\n"
" 2. Modificar elemento de Cosas Dos\n");
while(opcion < 0 || opcion > 2)
{
opcion = getInt("Por favor, ingrese una opcion valida\n"
" 1. Modificar elemento de Cosas Uno\n"
" 2. Modificar elemento de Cosas Dos\n");
}
return opcion;
}
int subMenuModificarUno()
{
int opcion;
opcion = getInt("1. Int\n"
"2. String\n"
"3. Char\n"
"4. Float\n"
"Ingrese una opcion: ");
while(opcion < 0 || opcion > 4)
{
opcion = getInt("Por favor, ingrese una opcion valida\n"
"1. Int\n"
"2. String\n"
"3. Char\n"
"4. Float\n"
"Ingrese una opcion: ");
}
return opcion;
}
int subMenuModificarDos()
{
int opcion;
opcion = getInt("1. Int\n"
"2. String\n"
"3. Char\n"
"4. Float\n"
"Ingrese una opcion: ");
while(opcion < 0 || opcion > 4)
{
opcion = getInt("Por favor, ingrese una opcion valida\n"
"1. Int\n"
"2. String\n"
"3. Char\n"
"4. Float\n"
"Ingrese una opcion: ");
}
return opcion;
}
|
C
|
#include<stdio.h>
int main()
{
float radius,area,*rad=&radius,*ar=&area;
printf("Enter the radius of circle : ");
scanf("%f",&radius);
*ar=(22/7)**rad**rad;
printf("\nArea = %f",*ar);
return 0;
}
|
C
|
/* ͷļ *****************************************************************/
#include "I2C.h"
void I2C_GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
__HAL_RCC_GPIOA_CLK_ENABLE();
// RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.Pull = GPIO_PULLUP;
GPIO_InitStructure.Speed=GPIO_SPEED_FREQ_VERY_HIGH;
// /* Configure I2C2 pins: SCL and SDA -------------------*/
GPIO_InitStructure.Pin = SCL | SDA;
GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_OD; // óɿ©GPIOģI2C
HAL_GPIO_Init(GPIOA, &GPIO_InitStructure);
}
void I2C_GPIO_DeInit(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
__HAL_RCC_GPIOA_CLK_DISABLE();
// RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.Pull = GPIO_NOPULL;
GPIO_InitStructure.Speed=GPIO_SPEED_FREQ_VERY_HIGH;
// /* Configure I2C2 pins: SCL and SDA -------------------*/
GPIO_InitStructure.Pin = SCL | SDA;
GPIO_InitStructure.Mode = GPIO_MODE_ANALOG; // óɿ©GPIOģI2C
HAL_GPIO_Init(GPIOA, &GPIO_InitStructure);
}
void I2C_delay(void)
{
u8 i = I2C_DELAY; // 72MHzƵ£͵2д
while(i) i--;
}
Bool I2C_Start(void)
{
SDA_H; SCL_H;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
SDA_L;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
SCL_L;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
return TRUE;
}
void I2C_Stop(void)
{
SCL_L;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
SDA_L;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
SCL_H;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
SDA_H;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
}
void I2C_Ack(void)
{
SCL_L;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
SDA_L;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
SCL_H;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
SCL_L;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
}
void I2C_NoAck(void)
{
SCL_L;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
SDA_H;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
SCL_H;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
SCL_L;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
}
Bool I2C_WaitAck(void) // Ϊ1ACKΪ0ACK
{
SCL_L;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
SDA_H;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
SCL_H;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
SCL_L;
if(SDA_read) return FALSE;
else return TRUE;
}
u8 I2C_ReceiveByte(void) // ݴӸλλ
{
u8 i=8, ReceiveByte=0;
SDA_H;
while(i--)
{
ReceiveByte <<= 1;
SCL_L;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
SCL_H;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
if(SDA_read) ReceiveByte|=0x01;
}
SCL_L;
return ReceiveByte;
}
void I2C_SendByte(u8 SendByte) // ݴӸλλ
{
u8 i=8;
while(i--)
{
SCL_L;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
if(SendByte & 0x80) SDA_H;
else SDA_L;
SendByte <<= 1;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
SCL_H;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
}
SCL_L;
}
u8 ReadI2C(u8 address, u8 WriteAddress) // 1
{
u8 ch; // 洢ݵʱ;
I2C_Start(); // ߣʼ;
I2C_SendByte(WriteAddress);
I2C_WaitAck(); // ʹӲַ;
I2C_SendByte(address);
I2C_WaitAck(); // ʹڲݴ洢ĵַ;
I2C_Start(); // ߣʼ;
I2C_SendByte(WriteAddress+1);
I2C_WaitAck(); // ʹڲݴ洢ĵַ;
ch = I2C_ReceiveByte();
I2C_NoAck(); // һֽݴʱͷӦλ;
I2C_Stop(); // ֹͣźţͷ·;
return(ch);
}
void WriteI2C(u8 ch, u8 address, u8 WriteAddress)
{
I2C_Start(); // ߣʼ;
I2C_SendByte(WriteAddress); I2C_WaitAck();
//while(TestAck()); // ʹӲַ;
I2C_SendByte(address); I2C_WaitAck();
//while(TestAck()); // ʹ洢ֽڵַ;
I2C_SendByte(ch); I2C_WaitAck();
//while(TestAck()); // ;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
I2C_Stop(); // ֹͣλݽ;
#if ENABLE_I2C_DELAY
I2C_delay();
#endif
}
///*******************************************************************************
//* Function Name : I2C_EE_BufferRead
//* Description : Reads a block of data from the EEPROM.
//* Input : - pBuffer : pointer to the buffer that receives the data read
//* from the EEPROM.
//* - ReadAddr : EEPROM's internal address to read from.
//* - NumByteToRead : number of bytes to read from the EEPROM.
//* Output : None
//* Return : None
//*******************************************************************************/
//void I2C_BufferRead(u8* pBuffer, u8 HARD_ADDRESS, u8 ReadAddr, u16 NumByteToRead)
//{
// /* Send START condition */
// I2C_GenerateSTART(I2C2, ENABLE);
//
// /* Test on EV5 and clear it */
// //while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_MODE_SELECT));
//#if ENABLE_I2C_DELAY
// I2C_delay();
//#endif
// /* Send Hardware address for write */
// I2C_Send7bitAddress(I2C2, HARD_ADDRESS, I2C_Direction_Transmitter);
// /* Test on EV6 and clear it */
// while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED));
//
// /* Clear EV6 by setting again the PE bit */
// I2C_Cmd(I2C2, ENABLE);
// /* Send the Hardware's internal address to write to */
// I2C_SendData(I2C2, ReadAddr);
// /* Test on EV8 and clear it */
// while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_BYTE_TRANSMITTED));
//
// /* Send STRAT condition a second time */
// I2C_GenerateSTART(I2C2, ENABLE);
//
// /* Test on EV5 and clear it */
// while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_MODE_SELECT));
//
// /* Send Hardware address for read */
// I2C_Send7bitAddress(I2C2, HARD_ADDRESS, I2C_Direction_Receiver);
//
// /* Test on EV6 and clear it */
// while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED));
//
// /* While there is data to be read */
// while(NumByteToRead)
// {
// if(NumByteToRead == 1)
// {
// /* Disable Acknowledgement */
// I2C_AcknowledgeConfig(I2C2, DISABLE);
//
// /* Send STOP Condition */
// I2C_GenerateSTOP(I2C2, ENABLE);
// }
// /* Test on EV7 and clear it */
// if(I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_BYTE_RECEIVED))
// {
// /* Read a byte from the Hardware */
// *pBuffer = I2C_ReceiveData(I2C2);
// /* Point to the next location where the byte read will be saved */
// pBuffer++;
//
// /* Decrement the read bytes counter */
// NumByteToRead--;
// }
// }
// /* Enable Acknowledgement to be ready for another reception */
// I2C_AcknowledgeConfig(I2C2, ENABLE);
//}
///*******************************************************************************
//* Function Name : I2C_EE_ByteWrite
//* Description : Writes one byte to the I2C EEPROM.
//* Input : - pBuffer : pointer to the buffer containing the data to be
//* written to the EEPROM.
//* - WriteAddr : EEPROM's internal address to write to.
//* Output : None
//* Return : None
//*******************************************************************************/
//void I2C_ByteWrite(u8* pBuffer, u8 HARD_ADDRESS, u8 WriteAddr)
//{
// /* Send STRAT condition */
// I2C_GenerateSTART(I2C2, ENABLE);
// /* Test on EV5 and clear it */
// //while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_MODE_SELECT));
//#if ENABLE_I2C_DELAY
// I2C_delay();
//#endif
// /* Send Hardware address for write */
// I2C_Send7bitAddress(I2C2, HARD_ADDRESS, I2C_Direction_Transmitter);
//
// /* Test on EV6 and clear it */
// while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED));
//
// /* Send the Hardware's internal address to write to */
// I2C_SendData(I2C2, WriteAddr);
//
// /* Test on EV8 and clear it */
// while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_BYTE_TRANSMITTED));
// /* Send the byte to be written */
// I2C_SendData(I2C2, *pBuffer);
//
// /* Test on EV8 and clear it */
// while(!I2C_CheckEvent(I2C2, I2C_EVENT_MASTER_BYTE_TRANSMITTED));
//
// /* Send STOP condition */
// I2C_GenerateSTOP(I2C2, ENABLE);
//}
/************************************ļ*********************************/
|
C
|
#include "validar.h"
#include "cJSON.h"
#include "mysql_connect.h"
#define query_select_user "SELECT * FROM users WHERE username = '%s' AND password = '%s'"
#define query_select_id "SELECT * FROM dispositivo WHERE id = %s"
#define query_select_tipo_medicion \
"SELECT tm.id as tipo_medicion_id,tm.codigo FROM dispositivo d join " \
"dispositivo_tipo_medicion dtm ON dtm.dispositivo_id = d.id join " \
"tipo_medicion tm ON tm.id = dtm.tipo_medicion_id where d.id = %s"
#define query_insert_medicion "INSERT INTO medicion VALUES(NULL,'%s','%s')"
#define query_insert_medicion_valor \
"INSERT INTO medicion_valor VALUES(NULL,'%d','%s',%f)"
#define query_insert_medicion_particular \
"INSERT INTO medicion VALUES(NULL,FROM_UNIXTIME(%f),'%s')"
bool validar_usuario(char *user, char *password) {
MYSQL *con = init_connection();
MYSQL_RES *res;
char query[150];
memset(query, 0, sizeof query);
snprintf(query, sizeof query, query_select_user, user, password);
if (mysql_query(con, query)) {
finish_with_error(con);
return false;
}
res = mysql_store_result(con);
if (res->row_count == 0) {
printf("Registro de usuario no entontrado.\n");
close_connection(con);
return false;
}
return true;
}
bool validar_dispositivo(char *payload) {
cJSON *json = cJSON_Parse(payload);
if (json == NULL) {
const char *error_ptr = cJSON_GetErrorPtr();
if (error_ptr != NULL) {
fprintf(stderr, "Error before: %s\n", error_ptr);
}
return false;
}
cJSON *device_id = cJSON_GetObjectItemCaseSensitive(json, "device_id");
if (device_id->type == cJSON_String || device_id->type == cJSON_Raw) {
MYSQL *con = init_connection();
MYSQL_RES *res;
MYSQL_ROW row;
MYSQL_FIELD *field;
char query[150];
memset(query, 0, sizeof query);
snprintf(query, sizeof query, query_select_id, device_id->valuestring);
if (mysql_query(con, query)) {
finish_with_error(con);
}
res = mysql_store_result(con);
if (res->row_count == 0) {
printf("No se encontraron resultados.\n");
close_connection(con);
if (json != NULL) {
cJSON_Delete(json);
}
return false;
}
int num_fields = mysql_num_fields(res);
while ((row = mysql_fetch_row(res))) {
for (int i = 0; i < num_fields; i++) {
if (row[i] != NULL) {
field = mysql_fetch_field_direct(res, i);
printf("%s: %s, ", field->name, row[i]);
}
}
printf("\n");
}
if (res != NULL) mysql_free_result(res);
close_connection(con);
if (json != NULL) {
cJSON_Delete(json);
}
return true;
}
if (json != NULL) {
cJSON_Delete(json);
}
return false;
}
bool validar_payload(char *payload) {
cJSON *json = cJSON_Parse(payload);
if (json == NULL) {
const char *error_ptr = cJSON_GetErrorPtr();
if (error_ptr != NULL) {
fprintf(stderr, "Error before: %s\n", error_ptr);
}
return false;
}
cJSON *device_id = cJSON_GetObjectItemCaseSensitive(json, "device_id");
if (device_id->type == cJSON_String || device_id->type == cJSON_Raw) {
MYSQL *con = init_connection();
MYSQL_RES *res;
MYSQL_ROW row;
MYSQL_FIELD *field;
char query[300];
memset(query, 0, sizeof query);
snprintf(query, sizeof query, query_select_tipo_medicion, device_id->valuestring);
if (mysql_query(con, query)) {
finish_with_error(con);
}
res = mysql_store_result(con);
if (res->row_count == 0) {
printf("No se encontraron resultados.\n");
close_connection(con);
if (json != NULL) {
cJSON_Delete(json);
}
return false;
}
cJSON *sensors_data = cJSON_GetObjectItemCaseSensitive(json, "sensors");
cJSON *value = NULL;
char *sensor_name[10];
float sensor_value[10];
char datetime[20];
memset(datetime, 0, sizeof datetime);
int idx = 0;
cJSON_ArrayForEach(value, sensors_data) {
if (strcmp("datetime", value->string) == 0) {
sensor_name[idx] = value->string;
sensor_value[idx] = 0;
strcpy(datetime, value->valuestring);
} else {
sensor_name[idx] = value->string;
sensor_value[idx] = value->valuedouble;
}
idx++;
}
char query_medicion[100];
memset(query_medicion, 0, sizeof query_medicion);
if (datetime != NULL) {
snprintf(query_medicion, sizeof query_medicion,
query_insert_medicion, datetime, device_id->valuestring);
}
if (mysql_query(con, query_medicion)) {
printf("No se logro insertar medicion.\n");
close_connection(con);
if (json != NULL) {
cJSON_Delete(json);
}
return false;
}
int medicion_id = mysql_insert_id(con);
if (medicion_id == 0) {
printf("Registro de medicion_id incorrecto.\n");
close_connection(con);
if (json != NULL) {
cJSON_Delete(json);
}
return false;
}
char query_medicion_valor[100];
int num_fields = mysql_num_fields(res);
while ((row = mysql_fetch_row(res))) {
for (int i = 0; i < num_fields; i++) {
if (row[i] == NULL) {
continue;
}
field = mysql_fetch_field_direct(res, i);
if (strcmp(field->name, "codigo") != 0) {
continue;
}
for (int j = 0; j < idx; j++) {
if (strcmp(row[1], sensor_name[j]) != 0) {
continue;
}
memset(query_medicion_valor, 0, sizeof query_medicion_valor);
snprintf(query_medicion_valor, sizeof query_medicion_valor, query_insert_medicion_valor, medicion_id, row[0], sensor_value[j]);
if (mysql_query(con, query_medicion_valor)) {
printf( "No se logro insertar medicion_valor.\n");
close_connection(con);
if (json != NULL) {
cJSON_Delete(json);
}
return false;
}
}
}
}
printf("medicion_id -> %d insertada correctamente\n", medicion_id);
if (res != NULL) mysql_free_result(res);
close_connection(con);
if (json != NULL) {
cJSON_Delete(json);
}
return true;
}
if (json != NULL) {
cJSON_Delete(json);
}
return false;
}
bool validar_dispositivo_generico(char *payload, char *device_id) {
if (strcmp(device_id, "") == 0) {
printf("Dispositivo no válido.\n");
return false;
}
cJSON *json = cJSON_Parse(payload);
if (json == NULL) {
const char *error_ptr = cJSON_GetErrorPtr();
if (error_ptr != NULL) {
fprintf(stderr, "Error before: %s\n", error_ptr);
}
return false;
}
MYSQL *con = init_connection();
MYSQL_RES *res;
MYSQL_ROW row;
MYSQL_FIELD *field;
char query[300];
memset(query, 0, sizeof query);
snprintf(query, sizeof query, query_select_tipo_medicion, device_id);
if (mysql_query(con, query)) {
finish_with_error(con);
}
res = mysql_store_result(con);
if (res->row_count == 0) {
printf("No se encontraron resultados.\n");
close_connection(con);
if (json != NULL) {
cJSON_Delete(json);
}
return false;
}
char *sensor_name[10];
float sensor_value[10];
int idx = 0;
cJSON *longitude = cJSON_GetObjectItemCaseSensitive(json, "longitude");
sensor_name[0] = "longitude";
sensor_value[0] = longitude->valuedouble;
idx++;
cJSON *latitude = cJSON_GetObjectItemCaseSensitive(json, "latitude");
sensor_name[1] = "latitude";
sensor_value[1] = latitude->valuedouble;
idx++;
cJSON *altitude = cJSON_GetObjectItemCaseSensitive(json, "altitude");
sensor_name[2] = "altitude";
sensor_value[2] = altitude->valuedouble;
idx++;
cJSON *gps_accuracy = cJSON_GetObjectItemCaseSensitive(json, "gps_accuracy");
sensor_name[3] = "gps_accuracy";
sensor_value[3] = gps_accuracy->valuedouble;
idx++;
cJSON *tst = cJSON_GetObjectItemCaseSensitive(json, "tst");
sensor_name[4] = "tst";
sensor_value[4] = tst->valuedouble;
char query_medicion[100];
memset(query_medicion, 0, sizeof query_medicion);
snprintf(query_medicion, sizeof query_medicion, query_insert_medicion_particular, tst->valuedouble, device_id);
if (mysql_query(con, query_medicion)) {
printf("No se logro insertar medicion.\n");
close_connection(con);
if (json != NULL) {
cJSON_Delete(json);
}
return false;
}
int medicion_id = mysql_insert_id(con);
if (medicion_id == 0) {
printf("Registro de medicion_id incorrecto.\n");
close_connection(con);
if (json != NULL) {
cJSON_Delete(json);
}
return false;
}
char query_medicion_valor[100];
int num_fields = mysql_num_fields(res);
while ((row = mysql_fetch_row(res))) {
for (int i = 0; i < num_fields; i++) {
if (row[i] == NULL) {
continue;
}
field = mysql_fetch_field_direct(res, i);
if (strcmp(field->name, "codigo") != 0) {
continue;
}
for (int j = 0; j < idx; j++) {
if (strcmp(row[1], sensor_name[j]) != 0) {
continue;
}
memset(query_medicion_valor, 0, sizeof query_medicion_valor);
snprintf(query_medicion_valor, sizeof query_medicion_valor, query_insert_medicion_valor, medicion_id, row[0], sensor_value[j]);
if (mysql_query(con, query_medicion_valor)) {
printf( "No se logro insertar medicion_valor.\n");
close_connection(con);
if (json != NULL) {
cJSON_Delete(json);
}
return false;
}
}
}
}
printf("medicion_id -> %d insertada correctamente\n", medicion_id);
if (res != NULL) mysql_free_result(res);
close_connection(con);
if (json != NULL) {
cJSON_Delete(json);
}
return true;
}
|
C
|
#include "loli_core_types.h"
#include "loli_generic_pool.h"
#include "loli_symtab.h"
#include "loli_type_maker.h"
#include "loli_alloc.h"
loli_generic_pool *loli_new_generic_pool(void)
{
loli_generic_pool *gp = loli_malloc(sizeof(*gp));
loli_class **cache_generics = loli_malloc(4 * sizeof(*cache_generics));
loli_class **scope_generics = loli_malloc(4 * sizeof(*scope_generics));
gp->cache_generics = cache_generics;
gp->cache_size = 4;
int i;
for (i = 0;i < 4;i++)
cache_generics[i] = NULL;
gp->scope_generics = scope_generics;
gp->scope_start = 0;
gp->scope_end = 0;
gp->scope_size = 4;
return gp;
}
void loli_free_generic_pool(loli_generic_pool *gp)
{
int i;
for (i = 0;i < gp->cache_size;i++) {
loli_class *c = gp->cache_generics[i];
if (c == NULL)
break;
loli_free(c->self_type);
loli_free(c->name);
loli_free(c);
}
loli_free(gp->cache_generics);
loli_free(gp->scope_generics);
loli_free(gp);
}
static loli_class *find_in_cache(loli_generic_pool *gp, const char *name,
int generic_pos, int *next_pos)
{
int i = 0;
loli_class *c = gp->cache_generics[i];
while (c) {
if (c->name[0] == name[0])
return c;
i++;
c = gp->cache_generics[i];
}
*next_pos = i;
return NULL;
}
void loli_gp_push(loli_generic_pool *gp, const char *name, int generic_pos)
{
int i;
loli_class *result = find_in_cache(gp, name, generic_pos, &i);
if (result == NULL) {
loli_class *new_generic = loli_new_raw_class(name);
loli_type *t = loli_new_raw_type(new_generic);
t->flags |= TYPE_IS_UNRESOLVED;
t->generic_pos = generic_pos;
new_generic->id = LOLI_ID_GENERIC;
new_generic->self_type = t;
new_generic->all_subtypes = t;
result = new_generic;
gp->cache_generics[i] = new_generic;
if (i + 1 == gp->cache_size) {
gp->cache_size *= 2;
loli_class **new_cache = loli_realloc(gp->cache_generics,
gp->cache_size * sizeof(*new_cache));
for (i = i + 1;i < gp->cache_size;i++)
new_cache[i] = NULL;
gp->cache_generics = new_cache;
}
}
if (gp->scope_end == gp->scope_size) {
gp->scope_size *= 2;
loli_class **new_scope = loli_realloc(gp->scope_generics,
gp->scope_size * sizeof(*new_scope));
gp->scope_generics = new_scope;
}
gp->scope_generics[gp->scope_end] = result;
gp->scope_end++;
}
loli_class *loli_gp_find(loli_generic_pool *gp, const char *name)
{
char ch = name[0];
int i;
for (i = gp->scope_start;i < gp->scope_end;i++) {
loli_class *c = gp->scope_generics[i];
if (c->name[0] == ch)
return c;
}
return NULL;
}
int loli_gp_num_in_scope(loli_generic_pool *gp)
{
return gp->scope_end - gp->scope_start;
}
uint16_t loli_gp_save(loli_generic_pool *gp)
{
return gp->scope_end;
}
void loli_gp_restore(loli_generic_pool *gp, uint16_t old_end)
{
gp->scope_end = old_end;
}
uint16_t loli_gp_save_and_hide(loli_generic_pool *gp)
{
uint16_t result = gp->scope_start;
gp->scope_start = gp->scope_end;
return result;
}
void loli_gp_restore_and_unhide(loli_generic_pool *gp, uint16_t old_start)
{
gp->scope_end = gp->scope_start;
gp->scope_start = old_start;
}
|
C
|
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
#include "lists.h"
/**
* delete_nodeint_at_index - function that ideletes the node
* at index index of a listint_t linked list.
* @head: listint_t pointer to a list node.
* @index: the index of the node.
* Return: a pointer to the indexed node.
*/
int delete_nodeint_at_index(listint_t **head, unsigned int index)
{
listint_t *temp, *store_next;
unsigned int i;
/**
* ***tests:****
* 1- not a NULL node (you have nothing to delete)
* 2- delete node at the beginning
* 3- delete node at the end
* 4- delete node in the middle
*/
/* If linked list is empty */
if (*head == NULL)
return (-1);
/* Store head node */
temp = *head;
/* If head needs to be removed */
if (index == 0)
{
*head = temp->next; /* Change head */
free(temp); /* free old head */
return (1);
}
/* Find previous node of the node to be deleted*/
for (i = 0; ((temp != NULL) && (i < (index - 1))); i++)
temp = temp->next;
/* If position is more than number of nodes*/
if ((temp == NULL) || (temp->next == NULL))
return (-1);
/* Node temp->next (that temp-> pointes to)is the node to be deleted */
/* Store pointer to the next of node to be deleted (so we do not loose the link to the rest of the node)*/
store_next = (temp->next)->next;
/* Unlink the node from linked list */
free(temp->next); /* Free memory */
temp->next = store_next; /* Unlink the deleted node from list = link the previous with the next node*/
return (1);
}
|
C
|
#include "bricks.h"
SDL_Rect** initialize_brick_array(SDL_Window* p_window, Uint16 nb_lines, Uint16 bricks_per_lines){
SDL_Rect** bricks_array = malloc(sizeof(SDL_Rect) * bricks_per_lines * nb_lines);
// Define the offset between each bricks
int offset = 10;
// Get the screen size, in order to manage the size & position of each bricks dynamicly
int screen_width = 0;
int screen_height = 0;
SDL_GetWindowSize(p_window, &screen_width, &screen_height);
// Compute the size of one brick
int brick_w = (screen_width - (offset * (bricks_per_lines + 1))) / bricks_per_lines;
int brick_h = 10;
for(int i = 0; i < nb_lines; i++){
for(int j = 0; j < bricks_per_lines; j++){
SDL_Rect* p_new_brick = malloc(sizeof(SDL_Rect));
p_new_brick -> w = brick_w;
p_new_brick -> h = brick_h;
p_new_brick -> x = (offset * (j + 1)) + (brick_w * j);
p_new_brick -> y = (offset * (i + 1)) + (brick_h * i);
bricks_array[(i * bricks_per_lines) + j] = p_new_brick;
}
}
return bricks_array;
}
|
C
|
/*
Input:
3
There is nothing permanent except change
Output:
There is nothing change except permanent
Explanation: The last 3 words "permanent except change" are reversed and the remaining words are printed as it is
*/
#include<stdio.h>
#include <stdlib.h>
int main()
{
int n,i=0;
scanf("%d\n",&n);
char s[100][1001];
while(scanf("%s",&s[i])==1)
{
i++;
}
for(int j=0;j<i-n;j++)
{
printf("%s ",s[j]);
}
i=i-1;
while(n--)
{
printf("%s ",s[i--]);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void Prekopiraj (const int *izvor, int *odrediste, int n){
int i=0;
int* pomocni=odrediste;
for (i=0; i<n; i++){
*odrediste=*izvor;
izvor++;
odrediste++;
}
odrediste=pomocni;
}
int main()
{
printf("Hello. \n");
int niz[100];
int vel=0;
int i=0;
printf("\nEnter some numbers fam (-1 for end): ");
int broj;
for (i=0; i<100; i++){
scanf("%d", &broj);
if (broj==-1){
break;
}
niz[i]=broj;
vel++;
}
int* izvor=niz;
int niz2[100];
int* odrediste=niz2;
Prekopiraj(niz, niz2, vel);
int j=0;
while (j<vel){
printf("%d\n", *odrediste);
odrediste++;
j++;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int VerificarQuantidade(int refrigerante)
{
if(refrigerante == 0)
{
printf("\n Item esgotado! \n");
return refrigerante;
}
else
return refrigerante;
}
int ReceberDinheiro(float precoRefrigerante)
{
float dinheiro;
float troco;
float falta;
float dinheiroCaixa = 102.55;
printf("\n As entradas possiveis da maquina sao: \n 0.01, 0.05, 0.10, 0.25, 0.50, 1, 2, 5, 10, 20, 50 e 100 reais ");
printf("\n");
printf("\n Entre com o dinheiro: ");
scanf("%f", &dinheiro);
if(dinheiro == 0.01 || dinheiro == 0.05 || dinheiro == 0.10 || dinheiro == 0.25 || dinheiro == 0.50 ||
dinheiro == 1.00 || dinheiro == 2.00 || dinheiro == 5.00 || dinheiro == 10.00 || dinheiro == 20.00 ||
dinheiro == 50.00 || dinheiro == 100.00)
{
if(dinheiro < precoRefrigerante)
{
falta = precoRefrigerante - dinheiro;
printf("\n Dinheiro insuficiente! Faltam: %.2f \n", falta);
return -1;
}
else if(dinheiro == precoRefrigerante)
{
dinheiroCaixa += dinheiro;
printf("\n Retire seu Refrigerante!\n");
}
else if(dinheiro >= precoRefrigerante)
{
troco = dinheiro - precoRefrigerante;
if(dinheiroCaixa >= troco)
{
printf("\n Valor do troco: %.2f \n\n Retire seu Refrigerante e o troco! \n\n ", troco);
dinheiroCaixa += dinheiro;
dinheiroCaixa -= troco;
}
else
{
printf("\n Infelizmente estamos sem troco, receba seu dinheiro de volta ...\n ");
return -1;
}
return 1;
}
}
return -1;
}
int main(void)
{
int op;
int cocaCola = 20;
int pepsi = 20;
int fanta = 20;
int sprite = 20;
int antartica = 20;
int kuat = 20;
int cocaColaZero = 20;
int fantaUva = 20;
int spriteZero = 20;
int kuatZero = 20;
const float precoCocaCola = 2.45;
const float precoPepsi = 2.15;
const float precoFanta = 2.45;
const float precoSprite = 2.25;
const float precoAntartica = 2.35;
const float precoKuat = 2.15;
const float precoCocaColaZero = 2.35;
const float precoFantaUva = 2.45;
const float precoSpriteZero = 2.25;
const float precoKuatZero = 2.15;
do
{
fflush(stdin);
printf("\n MENU \n"
"----------------------------------------------------------\n"
" 0 - SAIR\n"
" 1 - COCA COLA 350 ML VALOR: R$ 2,45 %2.d UNIDADES\n"
" 2 - PEPSI 350 ML VALOR: R$ 2,15 %2.d UNIDADES\n"
" 3 - FANTA 350 ML VALOR: R$ 2,45 %2.d UNIDADES\n"
" 4 - SPRITE 350 ML VALOR: R$ 2,25 %2.d UNIDADES\n"
" 5 - ANTARTICA 350 ML VALOR: R$ 2,35 %2.d UNIDADES\n"
" 6 - KUAT 350 ML VALOR: R$ 2,15 %2.d UNIDADES\n"
" 7 - COCA COLA Zero 350 ML VALOR: R$ 2,35 %2.d UNIDADES\n"
" 8 - FANTA Uva 350 ML VALOR: R$ 2,45 %2.d UNIDADES\n"
" 9 - SPRITE Zero 350 ML VALOR: R$ 2,25 %2.d UNIDADES\n"
"10 - KUAT Zero 350 ML VALOR: R$ 2,15 %2.d UNIDADES"
"\n----------------------------------------------------------\n",
cocaCola, pepsi, fanta, sprite, antartica, kuat, cocaColaZero,
fantaUva, spriteZero,kuatZero);
printf(" opcao: ");
scanf("%d",&op);
switch (op)
{
case 1:
{
if(VerificarQuantidade(cocaCola) != 0)
{
if(ReceberDinheiro(precoCocaCola) != -1)
cocaCola--;
}
break;
}
case 2:
{
if(VerificarQuantidade(pepsi) != 0)
{
if(ReceberDinheiro(precoPepsi) != -1)
pepsi--;
}
break;
}
case 3:
{
if(VerificarQuantidade(fanta) != 0)
{
if(ReceberDinheiro(precoFanta) != -1)
fanta--;
}
break;
}
case 4:
{
if(VerificarQuantidade(sprite) != 0)
{
if(ReceberDinheiro(precoSprite) != -1)
sprite--;
}
break;
}
case 5:
{
if(VerificarQuantidade(antartica) != 0)
{
if(ReceberDinheiro(precoAntartica) != -1)
antartica--;
}
break;
}
case 6:
{
if(VerificarQuantidade(kuat) != 0)
{
if(ReceberDinheiro(precoKuat) != -1)
kuat--;
}
break;
}
case 7:
{
if(VerificarQuantidade(cocaColaZero)!= 0)
{
if(ReceberDinheiro(precoCocaColaZero)!= -1)
cocaColaZero--;
}
break;
}
case 8:
{
if(VerificarQuantidade(fantaUva)!= 0)
{
if(ReceberDinheiro(precoFantaUva) != -1)
fantaUva--;
}
break;
}
case 9:
{
if(VerificarQuantidade(spriteZero) != 0)
{
if(ReceberDinheiro(precoSpriteZero) != -1)
spriteZero--;
}
break;
}
case 10:
{
if(VerificarQuantidade(kuatZero) != 0)
{
if(ReceberDinheiro(precoKuatZero) != -1)
kuatZero--;
}
break;
}
}} while(op!=0);
printf("\nSaindo....\n");
return 0;
}
|
C
|
/*#include "stdio.h"
#include "stdlib.h"
void GameResult(int a[])
{
if (a[0]>=a[1]&&a[0]>=a[2])
{
printf("B");
}else if(a[1]>=a[0]&&a[1]>=a[2])
{
printf("C");
}else
{
printf("J");
}
}
void main()
{
int n;
int i;
char c;
char d;
int win[2]={0},lose[2]={0},pin[2]={0};
int a[3]={0};
int b[3]={0};
scanf("%d",&n);
//c=(char*)malloc(sizeof(char)*n);
//d=(char*)malloc(sizeof(char)*n);
for(i=0;i<n;i++)
{
getchar();
scanf("%c %c",&c,&d);
if (c==d)
{
pin[0]++;
pin[1]++;
}else if(c=='C'&&d=='J'
||c=='J'&&d=='B'
||c=='B'&&d=='C')
{
win[0]++;
lose[1]++;
if (c=='B')
{
a[0]++;
}else if (c=='C')
{
a[1]++;
}else
{
a[2]++;
}
}else
{
win[1]++;
lose[0]++;
if (d=='B')
{
b[0]++;
}else if (d=='C')
{
b[1]++;
}else
{
b[2]++;
}
}
}
printf("%d %d %d\n",win[0],pin[0],lose[0]);
printf("%d %d %d\n",win[1],pin[1],lose[1]);
GameResult(a);
printf(" ");
GameResult(b);
system("pause");
}
*/
|
C
|
/*
string_buffer.h
project: string_buffer
url: https://github.com/noporpoise/StringBuffer
author: Isaac Turner <turner.isaac@gmail.com>
Copyright (c) 2011, Isaac Turner
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef STRING_BUFFER_FILE_SEEN
#define STRING_BUFFER_FILE_SEEN
#include <zlib.h> // needed for gzFile
#include <stdarg.h> // required for va_list
typedef unsigned long t_buf_pos;
typedef struct STRING_BUFFER STRING_BUFFER;
struct STRING_BUFFER
{
char *buff;
t_buf_pos len; // length of the string
t_buf_pos size; // buffer size - includes '\0' (size >= len+1)
};
//
// Creation, reset, free and memory expansion
//
// Constructors
STRING_BUFFER* string_buff_init(const t_buf_pos size);
STRING_BUFFER* string_buff_create(const char* str);
// Destructors
void string_buff_free(STRING_BUFFER* sbuf);
// Free sbuf struct, but retain and return the char array
char* string_buff_free_get_str(STRING_BUFFER* sbuf);
// Clone a buffer (including content)
STRING_BUFFER* string_buff_clone(const STRING_BUFFER* sbuf);
// Get a copy of this STRING_BUFFER as a char array
// Returns NULL if not enough memory
char* string_buff_as_str(const STRING_BUFFER* sbuf);
// Clear the content of an existing STRING_BUFFER (sets size to 0)
void string_buff_reset(STRING_BUFFER* sbuf);
// Get size
inline t_buf_pos string_buff_strlen(const STRING_BUFFER* sbuf);
inline t_buf_pos string_buff_size(const STRING_BUFFER* sbuf);
//
// Resizing
//
// Ensure capacity for len characters plus '\0' character - exits on FAILURE
void string_buff_ensure_capacity(STRING_BUFFER *sbuf, const t_buf_pos len);
// reallocs to exact memory specified - return 1 on success 0 on failure
char string_buff_resize(STRING_BUFFER *sbuf, const t_buf_pos new_size);
// convenience function: prints error and exits with EXIT_FAILURE if it fails
void string_buff_resize_vital(STRING_BUFFER *sbuf, const t_buf_pos new_size);
// Shorten string without reallocating memory
void string_buff_shrink(STRING_BUFFER *sbuf, const t_buf_pos new_len);
//
// Useful String functions
//
// get/set chars
inline char string_buff_get_char(const STRING_BUFFER *sbuf,
const t_buf_pos index);
inline void string_buff_set_char(STRING_BUFFER *sbuf, const t_buf_pos index,
const char c);
// Add a character to the end of this STRING_BUFFER
void string_buff_append_char(STRING_BUFFER* sbuf, const char txt);
// Copy a STRING_BUFFER to the end of this STRING_BUFFER
void string_buff_append_buff(STRING_BUFFER* dst, STRING_BUFFER* src);
// Copy a character array to the end of this STRING_BUFFER
void string_buff_append_str(STRING_BUFFER* sbuf, const char* txt);
// Copy N characters from a character array to the end of this STRING_BUFFER
void string_buff_append_strn(STRING_BUFFER* sbuf, const char* txt,
const t_buf_pos len);
// Remove \r and \n characters from the end of this STRING_BUFFER
void string_buff_chomp(STRING_BUFFER *sbuf);
// Get a substring as a new null terminated char array
// (remember to free the returned char* after you're done with it!)
char* string_buff_substr(STRING_BUFFER *sbuf, const t_buf_pos start,
const t_buf_pos len);
// Change to upper or lower case
void string_buff_to_uppercase(STRING_BUFFER *sbuf);
void string_buff_to_lowercase(STRING_BUFFER *sbuf);
// Copy a string to this STRING_BUFFER, overwriting any existing characters
void string_buff_copy(STRING_BUFFER* dest, const t_buf_pos dest_pos,
const STRING_BUFFER* src, const t_buf_pos src_pos,
const t_buf_pos len);
void string_buff_str_copy(STRING_BUFFER* dst, const t_buf_pos dst_pos,
const char* src, const t_buf_pos len);
// Copy to a STRING_BUFFER, shifting any existing characters along
void string_buff_insert(STRING_BUFFER* dest, const t_buf_pos dest_pos,
const STRING_BUFFER* src, const t_buf_pos src_pos,
const t_buf_pos len);
void string_buff_str_insert(STRING_BUFFER* dst, const t_buf_pos dst_pos,
const char* src, const t_buf_pos len);
//
// sprintf
//
// sprintf to a STRING_BUFFER (adds string terminator after sprint)
void string_buff_sprintf(STRING_BUFFER *sbuf, const char* fmt, ...);
void string_buff_sprintf_at(STRING_BUFFER *sbuf, const t_buf_pos pos,
const char* fmt, ...);
void string_buff_vsprintf(STRING_BUFFER *sbuf, const t_buf_pos pos,
const char* fmt, va_list argptr);
// sprintf without terminating character
// Does not prematurely end the string if you sprintf within the string
// (terminates string if sprintf to the end)
void string_buff_sprintf_noterm(STRING_BUFFER *sbuf, const t_buf_pos pos,
const char* fmt, ...);
//
// Reading files
//
// Reading a FILE
t_buf_pos string_buff_reset_readline(STRING_BUFFER *sbuf, FILE *file);
t_buf_pos string_buff_readline(STRING_BUFFER *sbuf, FILE *gz_file);
// Reading a gzFile
t_buf_pos string_buff_reset_gzreadline(STRING_BUFFER *sbuf, gzFile gz_file);
t_buf_pos string_buff_gzreadline(STRING_BUFFER *sbuf, gzFile gz_file);
// Skip a line and return how many characters were skipped
t_buf_pos string_buff_skip_line(FILE *file);
t_buf_pos string_buff_gzskip_line(gzFile gz_file);
/**************************/
/* Other String functions */
/**************************/
char string_is_all_whitespace(const char* s);
char* string_next_nonwhitespace(const char* s);
char* string_trim(char* str);
size_t string_chomp(char* str);
size_t string_count_char(const char* str, const int c);
long string_split(const char* split, const char* txt, char*** result);
#endif
|
C
|
/*
Author: Anthony Bustamante
Date: 10Nov19
Description: Exercise 3-2 - Write a function escape(s,t) that converts charactgers like
newline and tab intro visible escape sewquences like \n and \t as it copies the string
t to s. Use a switch statement. Write a function for the other direction as well,
converting escape sequences into the real characters.
*/
#include <stdio.h>
#define MAXLINE 1000
int myGetline(char line[], int maxline);
void copy(char to[], char from[]);
void escape(char to[], char from[]);
void rescape(char to[], char from[]);
main()
{
//char input[MAXLINE];
//myGetline(input, MAXLINE);
char input1[MAXLINE] = "This is a test";
char input2[MAXLINE] = "This\nis\na\ntest";
char output1[MAXLINE];
char output2[MAXLINE];
escape(output1, input1);
printf("%s\n", output1);
rescape(output2, input2);
printf("%s", output2);
}
int myGetline(char s[], int lim)
{
int c, i;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}
void escape(char to[], char from[]){
int i, offset;
i = offset = 0;
while ((to[i + offset] = from[i]) != '\0') {
switch(from[i]) {
case '\n':
to[i + offset] = '\\';
to[i + 1 + offset] = 'n';
offset += 1;
break;
case '\t':
to[i + offset] = '\\';
to[i + 1 + offset] = 't';
offset += 1;
break;
default:
break;
}
++i;
}
}
void rescape(char to[], char from[]){
int i, offset;
i = offset = 0;
while ((to[i] = from[i + offset]) != '\0') {
if (from[i + offset] == '\\') {
switch (from[i + offset + 1]) {
case 'n':
to[i] = '\n';
++offset;
break;
case 't':
to[i] = '\t';
++offset;
break;
default:
break;
}
}
++i;
}
}
|
C
|
int a[25];
int n;
void main()
{
int i;
int max(int);
int num=0;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
num=max(i)>num?max(i):num;
printf("%d",num);
}
int max(int chu)
{
int z=1,tempj;
int i,j,k;
if(chu==n-1) z=1;
else{
for(j=chu+1;j<n;j++)
{
if(a[j]>a[chu]) continue;
tempj=1+max(j);
z=tempj>z?tempj:z;
tempj=0;
}
}
return z;
}
|
C
|
// ***
// *** You MUST modify this file.
// ***
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#ifdef TEST_COUNTINT
int countInt(char * filename)
{
// If fopen fails, return -1
FILE * fptr = fopen(filename,"r");
int sum = 0;
if (fptr == NULL)
{
return -1;
}
else
{
// count the number of integers in the file
// 124 378 -56
// There are three integers: 124, 378, -56
int val;
while (fscanf(fptr, "%d", &val) == 1)
{
sum++;
}
// remember to fclose if fopen succeeds
fclose(fptr);
}
return sum;
}
#endif
#ifdef TEST_READINT
bool readInt(char* filename, int * intArr, int size)
{
// if fopen fails, return false
FILE * fptr = fopen(filename,"r");
if (fptr == NULL)
{
return false;
}
else
{
// read integers from the file.
int val;
int sum = 0;
while (fscanf(fptr, "%d", &val) == 1)
{
sum++;
}
// if the number of integers is different from size (too
// few or too many) return false
if (sum != size)
{
return false;
}
int i = 0;
fseek(fptr, 0, SEEK_SET);
while (fscanf(fptr, "%d", &intArr[i]) == 1)
{
i++;
}
// if everything is fine, fclose and return true
fclose(fptr);
}
return true;
}
#endif
#ifdef TEST_COMPAREINT
int compareInt(const void *p1, const void *p2)
{
// needed by qsort
// return an integer less than, equal to, or greater than zero if
// the first argument is considered to be respectively less than,
// equal to, or greater than the second.
const int * ptr1 = (const int*)p1;
const int * ptr2 = (const int*)p2;
int val1 = * ptr1;
int val2 = * ptr2;
if (val1 < val2)
{
return -1;
}
if (val1 == val2)
{
return 0;
}
return 1;
}
#endif
#ifdef TEST_WRITEINT
bool writeInt(char* filename, int * intArr, int size)
{
// if fopen fails, return false
FILE * fptr = fopen(filename,"w");
if (fptr == NULL)
{
return false;
}
else
{
// write integers to the file.
// one integer per line
for(int i = 0; i < size; i++)
{
fprintf(fptr,"%d\n", intArr[i]);
}
// fclose and return true
fclose(fptr);
}
return true;
}
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int peso;
int contadorMax=0;
int contadorMin=0;
char seguir='s';
do
{
printf("Ingrese el peso del empleado: \n");
scanf("%d", &peso);
if(peso<=80)
{
contadorMin++;
}else
{
contadorMax++;
}
fflush(stdin);
printf("Desea continuar con la carga: s/n...\n");
scanf("%c", &seguir);
}while(seguir=='s');
printf("La cantidad de empleados que pesa hasta 80kg inclusive es: %d.\n", contadorMin);
printf("La cantidad de empleados que pesa mas de 80kg es: %d.\n", contadorMax);
return 0;
}
|
C
|
/*
* Write a function that takes 2 pointers and swaps the memory they point to.
* The function should also take the size of each memory piece and should work
* with any data type.
*/
#include <stdio.h>
#include <stdlib.h>
void swap(void *first, void *second, size_t size);
int main(int argc, char** argv) {
char letter = 'B', symbol = '+';
int a = 10, b = 6;
double d = 3.14, f = 1.23567;
swap(&letter, &symbol, sizeof(char));
printf("%c %c\n", letter, symbol);
swap(&a, &b, sizeof(int));
printf("%d %d\n", a, b);
swap(&d, &f, sizeof(double));
printf("%.2lf %.2lf\n", d, f);
return (EXIT_SUCCESS);
}
void swap(void *first, void *second, size_t size)
{
char *memoryFirstPtr = first;
char *memorySecondPtr = second;
int i;
for (i = 0; i < size; i++) {
char temp = memoryFirstPtr[i];
memoryFirstPtr[i] = memorySecondPtr[i];
memorySecondPtr[i] = temp;
}
}
|
C
|
/*Napisati funkciju koja e primiti cijeli broj vei od nule te odvojiti znamenke djeljive s 3 i
one koje to nisu u dva odvojena broja.
Primjer: broj 13597 treba pretvoriti u brojeve 157 i 39.
Funkcija brojeve treba vratiti glavnom programu koji ih onda ispisuje.*/
#include <stdio.h>
#include <math.h>
void funkcija_za_povrat_brojeva(int uneseni_broj, int *djeljiv, int *nije_djeljiv);
int main(void)
{
int uneseni_broj, djeljiv, nije_djeljiv;
printf("Unesite jedan cijeli broj: ");
scanf_s("%d", &uneseni_broj);
funkcija_za_povrat_brojeva(uneseni_broj, &djeljiv, &nije_djeljiv); /*funkciji proslijeujem uneseni broj i dva pointera*/
printf("%d %d", nije_djeljiv, djeljiv); /*itam to je funkcija zapisala na adresama pointera*/
getchar();
getchar();
return 0;
}
void funkcija_za_povrat_brojeva(int uneseni_broj, int *djeljiv, int *nije_djeljiv)
{
int znamenka, brojac, brojac_djeljiv = 0, brojac_nije_djeljiv = 0;
*djeljiv = 0, *nije_djeljiv = 0;
brojac = 0;
while (uneseni_broj)
{
znamenka = uneseni_broj % 10;
uneseni_broj /= 10;
if (znamenka % 3 == 0)
{
*djeljiv += (pow(10, brojac_djeljiv) * znamenka);
++brojac_djeljiv;
}
else
{
*nije_djeljiv += (pow(10, brojac_nije_djeljiv) * znamenka);
++brojac_nije_djeljiv;
}
++brojac;
}
return 0;
}
|
C
|
#include<lpc21xx.h>
void delay(unsigned int);
int main()
{ //basic gpio
/* IODIR0 = 0x00005500; //0x0000FF00; //set direction as o/p using masking
while(1)
{
IOSET0 = 0x00005500; //0x0000FF00; //reset
delay(100);
IOCLR0 = 0x00005500; //0x0000FF00; //set
delay(100);
} */
//odd evn gpio
/* IODIR1 = 0x01FE0000; //0x0000FF00; //set direction as o/p using masking
while(1)
{
IOSET1 = 0x01FE0000; //0x0000FF00; //reset
delay(300); //controller needs more delay
IOCLR1 = 0x01FE0000; //0x0000FF00; //set
delay(300);
} */
//led prgrm
/* IODIR1 = 0x01FE0000; //0x0000FF00; //set direction as o/p using masking
while(1)
{
int i;
for(i=17; i<=24; i++)
{
IOSET1 = (1<<i); //0x0000FF00; //reset
delay(300); //controller needs more delay
IOCLR1 = (1<<i);
delay(300);
}
for(i=24; i>=17; i--)
{
IOSET1 = (1<<i); //0x0000FF00; //reset
delay(300); //controller needs more delay
IOCLR1 = (1<<i);
delay(300);
}
} */
//led prgrm pattern
IODIR1 = 0x01FE0000; //0x0000FF00; //set direction as o/p using masking
while(1)
{
int i;
int ar[] = {0x81,0x42,0x24,0x18,0x24,0x42,0x81};
for(i=0; i<7; i++)
{
IOSET1 = (ar[i]<<17); //0x0000FF00; //reset
delay(300); //controller needs more delay
IOCLR1 = (ar[i]<<17);
delay(300);
}
}
}
void delay(unsigned int a) //delay(100)*6000
{
int i, j;
for(i=0;i<=a;i++)
for(j=0;j<6000;j++);
}
|
C
|
#include "Level.h"
_Tile *TileList=NULL;
int TileListCount=0;
_GlobalSectionEntry *GlobalSectionList=NULL;
int GlobalSectionListSize=0;
_SectionEntry *SectionList;
int SectionListCount;
int Level_BlockBaseHeight=64;
int Level_BlockWidth=64;
void Level_Init()
{
/* Create global section array */
/* Do this by looping over all files in the Maps directory */
struct dirent *Entry;
DIR *Dir=opendir("Maps");
char Filename[32];
FILE *File;
GlobalSectionListSize=0;
while((Entry=readdir(Dir))!=NULL)
if (Entry->d_name[0]!='.')
{
/* TODO: Check for null */
GlobalSectionList=realloc(GlobalSectionList, (GlobalSectionListSize+1)*sizeof(_GlobalSectionEntry));
sprintf(Filename,"Maps/%s", Entry->d_name);
File=fopen(Filename, "rb");
fread(&(GlobalSectionList[GlobalSectionListSize].Id), sizeof(int), 1, File);
fread(&(GlobalSectionList[GlobalSectionListSize].X1), sizeof(long long), 1, File);
fread(&(GlobalSectionList[GlobalSectionListSize].Y1), sizeof(long long), 1, File);
fread(&(GlobalSectionList[GlobalSectionListSize].X2), sizeof(long long), 1, File);
fread(&(GlobalSectionList[GlobalSectionListSize].Y2), sizeof(long long), 1, File);
fclose(File);
++GlobalSectionListSize;
}
closedir(Dir);
/* TileList */
File=fopen("Tiles/TileList", "rb");
char String[256], Char;
int Id;
TileListCount=0;
TileList=NULL;
while(fread(&Id, sizeof(int), 1, File))
{
/* TODO: Check for null */
++TileListCount;
TileList=realloc(TileList, TileListCount*sizeof(_Tile));
String[0]='\0';
do
{
fread(&Char, sizeof(char), 1, File);
String[strlen(String)+1]=0;
String[strlen(String)]=Char;
}
while(Char);
if (strlen(String)>0)
TileList[Id].Surface=IMG_Load(String);
else
TileList[Id].Surface=NULL;
fread(&(TileList[Id].Colour), sizeof(int), 1, File);
fread(&(TileList[Id].Height), sizeof(int), 1, File);
}
fclose(File);
}
void Level_Quit()
{
/* Free all loaded sections */
int I;
for(I=0;I<SectionListCount;++I)
{
free(SectionList[I].VisibleSections);
SectionList[I].VisibleSections=NULL;
}
free(SectionList);
SectionList=NULL;
SectionListCount=0;
/* Free tiles */
for(I=0;I<TileListCount;++I)
{
SDL_FreeSurface(TileList[I].Surface);
TileList[I].Surface=NULL;
}
free(TileList);
TileList=NULL;
TileListCount=0;
/* Free global list */
free(GlobalSectionList);
GlobalSectionList=NULL;
GlobalSectionListSize=0;
}
int Level_SpriteOnSquare(long long int X, long long int Y)
{
/* TODO: this */
return -1;
}
int Level_TileOnSquare(long long int X, long long int Y)
{
/* Find which section tile is in */
int SectionId=Level_XYToSectionId(X, Y);
if (SectionId==-1)
return -1;
/* Adjust X and Y to relative offset within section */
int Index=Level_SectionIdToIndex(SectionId);
X-=SectionList[Index].X1;
Y-=SectionList[Index].Y1;
/* Return the tile */
return SectionList[Index].Tiles[X][Y];
}
_Tile Level_GetTileById(int TId)
{
return TileList[TId];
}
void Level_UpdatePlayerPosition(double PlayerX, double PlayerY)
{
/* Find which section the player is in */
int SectionId=Level_XYToSectionId((int)PlayerX, (int)PlayerY);
if (SectionId==-1)
{
printf("Error: No section associated with (%f, %f).\n", PlayerX, PlayerY);
exit(0);
}
/* Firstly load the section itself */
Level_LoadSection(SectionId);
/* Set all sections as uneeded expect current section and ones visible */
int SectionIndex=Level_SectionIdToIndex(SectionId);
int I, J;
for(I=0;I<SectionListCount;++I)
{
if (I==SectionIndex)
continue;
SectionList[I].Needed=0;
for(J=0;SectionList[SectionIndex].VisibleSections[J]!=-1;++J)
if (SectionList[I].Id==SectionList[SectionIndex].VisibleSections[J])
SectionList[I].Needed=1;
}
/* Now load all sections which are visible from this one */
for(I=0;SectionList[SectionIndex].VisibleSections[I]!=-1;++I)
Level_LoadSection(SectionList[SectionIndex].VisibleSections[I]);
}
int Level_XYToSectionId(long long int X, long long int Y)
{
int I;
for(I=0;I<GlobalSectionListSize;++I)
if (X>=GlobalSectionList[I].X1 && Y>=GlobalSectionList[I].Y1 &&
X<GlobalSectionList[I].X2 && Y<GlobalSectionList[I].Y2)
return GlobalSectionList[I].Id;
return -1;
}
void Level_LoadSection(int SectionId)
{
/* Is struct already loaded? */
if (Level_SectionIdToIndex(SectionId)!=-1)
/* No point loading it again */
return;
/* Find somewhere to store the new section */
int Index, I;
for(Index=0;Index<SectionListCount;++Index)
if (!SectionList[Index].Needed)
{
/* Clean up malloc'ed stuff */
free(SectionList[Index].VisibleSections);
SectionList[Index].VisibleSections=NULL;
for(I=0;I<SectionList[Index].Height;++I)
free(SectionList[Index].Tiles[I]);
free(SectionList[Index].Tiles);
SectionList[Index].Tiles=NULL;
break;
}
if (Index==SectionListCount)
{
/* No space - must allocate more */
/* TODO: Check for nulls */
Index=SectionListCount++;
SectionList=realloc(SectionList, SectionListCount*sizeof(_SectionEntry));
}
/* Load the section from its file */
char Filename[32];
sprintf(Filename, "Maps/%i", SectionId);
FILE *File=fopen(Filename, "rb");
fread(&(SectionList[Index].Id), sizeof(int), 1, File);
fread(&(SectionList[Index].X1), sizeof(long long), 1, File);
fread(&(SectionList[Index].Y1), sizeof(long long), 1, File);
fread(&(SectionList[Index].X2), sizeof(long long), 1, File);
fread(&(SectionList[Index].Y2), sizeof(long long), 1, File);
SectionList[Index].Width=SectionList[Index].X2-SectionList[Index].X1;
SectionList[Index].Height=SectionList[Index].Y2-SectionList[Index].Y1;
I=-1;
SectionList[Index].VisibleSections=NULL;
do
{
++I;
SectionList[Index].VisibleSections=realloc(SectionList[Index].VisibleSections, (I+1)*sizeof(int));
fread(&(SectionList[Index].VisibleSections[I]), sizeof(int), 1, File);
}while(SectionList[Index].VisibleSections[I]!=-1);
SectionList[Index].Tiles=malloc(sizeof(int*)*SectionList[Index].Height);
for(I=0;I<SectionList[Index].Height;++I)
{
SectionList[Index].Tiles[I]=malloc(sizeof(int)*SectionList[Index].Width);
fread(SectionList[Index].Tiles[I], sizeof(int), SectionList[Index].Width, File);
}
SectionList[Index].Needed=1;
fclose(File);
}
int Level_SectionIdToIndex(int SectionId)
{
int I;
for(I=0;I<SectionListCount;++I)
if (SectionList[I].Id==SectionId)
return I;
return -1;
}
|
C
|
// Task: https://atcoder.jp/contests/abc114/tasks/abc114_b
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int i,j,ans=1000;
float n;
char s[20];
scanf("%s", s);
for (i=0;i<8;i++) {
for (j=n=0;j<3;j++) {
n=n*10+s[i+j]-48;
}
ans=fmin(ans, fabs(753-n));
}
printf("%d\n", ans);
}
|
C
|
#ifndef FOR_H
#define FOR_H
#include <stdio.h>
struct Lesson {
int position;
char name[255];
};
struct Section {
int position;
char title[255];
int reset_lesson_position;
int lessons_size;
/* For now, every section will have at most 2 lessons, the count above is the
actual number of lessons present.
I would normally do a larger power of two, maybe even 16 */
struct Lesson lessons[2];
};
static void display_sections(int sections_size, struct Section* sections)
{
const int last_section_index = sections_size - 1;
printf("[\n");
for (int i = 0; i < sections_size; i++)
{
struct Section* section = §ions[i];
printf("\t{\n\t\t\"title\": \"%s\",\n\t\t\"reset_lesson_position\": %s,\n\t\t\"position\": %i,\n",
section->title,
section->reset_lesson_position ? "true" : "false",
section->position);
printf("\t\t\"lessons\": [\n");
const int last_lesson_index = section->lessons_size - 1;
for (int li = 0; li < section->lessons_size; li++)
{
struct Lesson* lesson = §ion->lessons[li];
printf("\t\t\t{\n");
printf("\t\t\t\t\"name\": \"%s\",\n", lesson->name);
printf("\t\t\t\t\"position\": %i\n", lesson->position);
printf("\t\t\t}%s\n", li == last_lesson_index ? "" : ",");
}
printf("\t\t]\n");
printf("\t}%s\n", last_section_index == i ? "" : ",");
}
printf("]\n");
}
#endif
|
C
|
#include <stdio.h>
int main(){
int i, sc=0, sd=0;
float v[10], soma=0, psd;
printf("Digite o saldo dos 10 clientes: ");
for(i=0; i<10; i++){
scanf("%f", &v[i]);
soma+=v[i];
if(v[i]>0){
sc++;
}
else{
sd++;
}
}
psd = sd*10;
printf("Saldo medio = %.2f\n", soma/10);
printf("Porcentagem de clientes com saldo devedor = %.2f\n", psd);
printf("Numero de clientes com saldo credor = %d\n", sc);
return 0;
}
|
C
|
#include <stdio.h>
main(){
int n, k;
printf("Digite a quantidade de valores da lista: ");
scanf("%d", &n);
int array[n];
int *p = array;
printf("\nLista:\n");
for(int i = 0; i<n; i++){
printf("Digite o valor %d: ", i+1);
scanf("%d", (p+i));
}
printf("\nDigite a quantidade de valores por linha: ");
scanf("%d", &k);
printf("\n");
function(p,n,k);
}
int function(int *p, int n, int k){
int t=0,atual;
atual = *(p);
for(int i=0; i<n; i++){
printf("%d ", *(p+i));
if(*(p+i)>atual){
atual = *(p+i);
}
t++;
if(t==k){
printf("\n\n");
t=0;
}
}
return printf("Maior valor: %d\n", atual);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* load_scene_block.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cmelara- <cmelara-@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/02/26 16:52:43 by cmelara- #+# #+# */
/* Updated: 2019/02/26 18:47:38 by cmelara- ### ########.fr */
/* */
/* ************************************************************************** */
#include "scene_manager.h"
char *type_to_string(t_asset_type type)
{
if (type == SOUNDS)
return ("SOUNDS");
else if (type == MUSIC)
return ("MUSIC");
else if (type == TEXTURES)
return ("TEXTURES");
else if (type == SPRITES)
return ("SPRITES");
else if (type == FONTS)
return ("FONTS");
else if (type == MAPS)
return ("MAPS");
return (NULL);
}
void load_scene_block(t_vector *paths, t_asset_type type, char *scene_file)
{
int i;
int j;
char *block;
t_path *path;
int vars_count;
block = type_to_string(type);
i = go_to_block(scene_file, block);
j = 0;
vector_init(paths, 0);
vars_count = ini_count_vars(&scene_file[i]);
while (j < vars_count)
{
path = (t_path *)malloc(sizeof(t_path));
strcpy(path->name, ini_next_name(&scene_file[i], j == 0));
strcpy(path->path, ini_next_value(&scene_file[i], j == 0));
vector_push(paths, path);
j++;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * fp;
int c;
int i = 0;
long pos;
fp = fopen ("/dev/lprf", "r+");
printf ("Enter requested address (hex), 0 to cancel: ");
scanf ("%X",&i);
// while(i != 0)
// {
printf("fseek...\n");
fseek(fp, i, SEEK_SET); //calls kernel file_operations.llseek but also to file_operations.read
printf("fseek finished. ftell...\n");
pos = ftell(fp);
printf("ftell finished. fgetc...\n");
c = fgetc(fp);
printf("fgetc finished\n");
printf("pos=%ld \t c=%02X \t c=%d \n", pos, c, c);
// printf ("Enter requested address (hex), 0 to cancel: ");
// scanf ("%X",&i);
// }
fclose(fp);
return(0);
}
|
C
|
#include "config.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <orc/orcprogram.h>
#include <orc/orcdebug.h>
/**
* SECTION:orcexecutor
* @title: OrcExecutor
* @short_description: Running Orc programs
*/
#define CHUNK_SIZE 16
OrcExecutor *
orc_executor_new (OrcProgram *program)
{
OrcExecutor *ex;
ex = malloc(sizeof(OrcExecutor));
memset(ex,0,sizeof(OrcExecutor));
orc_executor_set_program (ex, program);
return ex;
}
void
orc_executor_free (OrcExecutor *ex)
{
free (ex);
}
void
orc_executor_run (OrcExecutor *ex)
{
void (*func) (OrcExecutor *);
if (ex->program) {
func = ex->program->code_exec;
} else {
OrcCode *code = (OrcCode *)ex->arrays[ORC_VAR_A2];
func = code->exec;
}
if (func) {
func (ex);
/* ORC_ERROR("counters %d %d %d", ex->counter1, ex->counter2, ex->counter3); */
} else {
orc_executor_emulate (ex);
}
}
void
orc_executor_run_backup (OrcExecutor *ex)
{
void (*func) (OrcExecutor *);
if (ex->program) {
func = ex->program->backup_func;
} else {
OrcCode *code = (OrcCode *)ex->arrays[ORC_VAR_A2];
func = code->exec;
}
if (func) {
func (ex);
/* ORC_ERROR("counters %d %d %d", ex->counter1, ex->counter2, ex->counter3); */
} else {
orc_executor_emulate (ex);
}
}
void
orc_executor_set_program (OrcExecutor *ex, OrcProgram *program)
{
ex->program = program;
if (program->code_exec) {
ex->arrays[ORC_VAR_A1] = (void *)program->code_exec;
} else {
ex->arrays[ORC_VAR_A1] = (void *)orc_executor_emulate;
}
ex->arrays[ORC_VAR_A2] = program->orccode;
}
void
orc_executor_set_array (OrcExecutor *ex, int var, void *ptr)
{
ex->arrays[var] = ptr;
}
void
orc_executor_set_stride (OrcExecutor *ex, int var, int stride)
{
ex->params[var] = stride;
}
void
orc_executor_set_array_str (OrcExecutor *ex, const char *name, void *ptr)
{
int var;
var = orc_program_find_var_by_name (ex->program, name);
if (var >= 0)
ex->arrays[var] = ptr;
}
void
orc_executor_set_param (OrcExecutor *ex, int var, int value)
{
ex->params[var] = value;
}
void
orc_executor_set_param_float (OrcExecutor *ex, int var, float value)
{
orc_union32 u;
u.f = value;
ex->params[var] = u.i;
}
void
orc_executor_set_param_int64 (OrcExecutor *ex, int var, orc_int64 value)
{
ex->params[var] = value & 0xffffffff;
ex->params[var + (ORC_VAR_T1-ORC_VAR_P1)] = (value >> 32) & 0xffffffff;
}
void
orc_executor_set_param_double (OrcExecutor *ex, int var, double value)
{
orc_union64 u;
u.f = value;
ex->params[var] = u.i & 0xffffffff;
ex->params[var + (ORC_VAR_T1-ORC_VAR_P1)] = (u.i >> 32) & 0xffffffff;
}
void
orc_executor_set_param_str (OrcExecutor *ex, const char *name, int value)
{
int var;
var = orc_program_find_var_by_name (ex->program, name);
if (var >= 0)
ex->params[var] = value;
}
int
orc_executor_get_accumulator (OrcExecutor *ex, int var)
{
return ex->accumulators[var - ORC_VAR_A1];
}
int
orc_executor_get_accumulator_str (OrcExecutor *ex, const char *name)
{
int var;
var = orc_program_find_var_by_name (ex->program, name);
if (var >= 0)
return ex->accumulators[var];
return -1;
}
void
orc_executor_set_n (OrcExecutor *ex, int n)
{
ex->n = n;
}
void
orc_executor_set_m (OrcExecutor *ex, int m)
{
ORC_EXECUTOR_M(ex) = m;
}
static void
load_constant (void *data, int size, orc_uint64 value)
{
switch (size) {
case 1:
{
int l;
orc_int8 *d = data;
for(l=0;l<CHUNK_SIZE;l++) {
d[l] = value;
}
}
break;
case 2:
{
int l;
orc_int16 *d = data;
for(l=0;l<CHUNK_SIZE;l++) {
d[l] = value;
}
}
break;
case 4:
{
int l;
orc_int32 *d = data;
for(l=0;l<CHUNK_SIZE;l++) {
d[l] = value;
}
}
break;
case 8:
{
int l;
orc_int64 *d = data;
for(l=0;l<CHUNK_SIZE;l++) {
d[l] = value;
}
}
break;
default:
ORC_ASSERT(0);
}
}
void
orc_executor_emulate (OrcExecutor *ex)
{
int i;
int j;
int k;
int m, m_index;
OrcCode *code;
OrcInstruction *insn;
OrcStaticOpcode *opcode;
OrcOpcodeExecutor *opcode_ex;
void *tmpspace[ORC_N_COMPILER_VARIABLES] = { 0 };
if (ex->program) {
code = ex->program->orccode;
} else {
code = (OrcCode *)ex->arrays[ORC_VAR_A2];
}
ex->accumulators[0] = 0;
ex->accumulators[1] = 0;
ex->accumulators[2] = 0;
ex->accumulators[3] = 0;
ORC_DEBUG("emulating");
memset (&opcode_ex, 0, sizeof(opcode_ex));
if (code == NULL) {
ORC_ERROR("attempt to run program that failed to compile");
ORC_ASSERT(0);
}
if (code->is_2d) {
m = ORC_EXECUTOR_M(ex);
} else {
m = 1;
}
for(i=0;i<ORC_N_COMPILER_VARIABLES;i++){
OrcCodeVariable *var = code->vars + i;
if (var->size) {
tmpspace[i] = malloc(ORC_MAX_VAR_SIZE * CHUNK_SIZE);
}
}
opcode_ex = malloc(sizeof(OrcOpcodeExecutor)*code->n_insns);
for(j=0;j<code->n_insns;j++){
insn = code->insns + j;
opcode = insn->opcode;
opcode_ex[j].emulateN = opcode->emulateN;
opcode_ex[j].shift = 0;
if (insn->flags & ORC_INSTRUCTION_FLAG_X2) {
opcode_ex[j].shift = 1;
} else if (insn->flags & ORC_INSTRUCTION_FLAG_X4) {
opcode_ex[j].shift = 2;
}
for(k=0;k<ORC_STATIC_OPCODE_N_SRC;k++) {
OrcCodeVariable *var = code->vars + insn->src_args[k];
if (opcode->src_size[k] == 0) continue;
if (var->vartype == ORC_VAR_TYPE_CONST) {
opcode_ex[j].src_ptrs[k] = tmpspace[insn->src_args[k]];
/* FIXME hack */
load_constant (tmpspace[insn->src_args[k]], 8,
var->value.i);
} else if (var->vartype == ORC_VAR_TYPE_PARAM) {
opcode_ex[j].src_ptrs[k] = tmpspace[insn->src_args[k]];
/* FIXME hack */
if (var->size == 8) {
load_constant (tmpspace[insn->src_args[k]], 8,
(orc_uint64)(orc_uint32)ex->params[insn->src_args[k]] |
(((orc_uint64)(orc_uint32)ex->params[insn->src_args[k] +
(ORC_VAR_T1 - ORC_VAR_P1)])<<32));
} else {
load_constant (tmpspace[insn->src_args[k]], 8,
ex->params[insn->src_args[k]]);
}
} else if (var->vartype == ORC_VAR_TYPE_TEMP) {
opcode_ex[j].src_ptrs[k] = tmpspace[insn->src_args[k]];
} else if (var->vartype == ORC_VAR_TYPE_SRC) {
if (ORC_PTR_TO_INT(ex->arrays[insn->src_args[k]]) & (var->size - 1)) {
ORC_ERROR("Unaligned array for src%d, program %s",
(insn->src_args[k]-ORC_VAR_S1), ex->program->name);
}
opcode_ex[j].src_ptrs[k] = ex->arrays[insn->src_args[k]];
} else if (var->vartype == ORC_VAR_TYPE_DEST) {
if (ORC_PTR_TO_INT(ex->arrays[insn->src_args[k]]) & (var->size - 1)) {
ORC_ERROR("Unaligned array for dest%d, program %s",
(insn->src_args[k]-ORC_VAR_D1), ex->program->name);
}
opcode_ex[j].src_ptrs[k] = ex->arrays[insn->src_args[k]];
}
}
for(k=0;k<ORC_STATIC_OPCODE_N_DEST;k++) {
OrcCodeVariable *var = code->vars + insn->dest_args[k];
if (opcode->dest_size[k] == 0) continue;
if (var->vartype == ORC_VAR_TYPE_TEMP) {
ORC_DEBUG("dest vartype tmp %d", insn->dest_args[k]);
opcode_ex[j].dest_ptrs[k] = tmpspace[insn->dest_args[k]];
} else if (var->vartype == ORC_VAR_TYPE_ACCUMULATOR) {
opcode_ex[j].dest_ptrs[k] =
&ex->accumulators[insn->dest_args[k] - ORC_VAR_A1];
} else if (var->vartype == ORC_VAR_TYPE_DEST) {
if (ORC_PTR_TO_INT(ex->arrays[insn->dest_args[k]]) & (var->size - 1)) {
ORC_ERROR("Unaligned array for dest%d, program %s",
(insn->dest_args[k]-ORC_VAR_D1), ex->program->name);
}
opcode_ex[j].dest_ptrs[k] = ex->arrays[insn->dest_args[k]];
}
}
ORC_DEBUG("opcode %s %p %p %p", opcode->name,
opcode_ex[j].dest_ptrs[0], opcode_ex[j].src_ptrs[0],
opcode_ex[j].src_ptrs[1]);
}
ORC_DEBUG("src ptr %p stride %d", ex->arrays[ORC_VAR_S1], ex->params[ORC_VAR_S1]);
for(m_index=0;m_index<m;m_index++){
ORC_DEBUG("m_index %d m %d", m_index, m);
for(j=0;j<code->n_insns;j++){
insn = code->insns + j;
opcode = insn->opcode;
for(k=0;k<ORC_STATIC_OPCODE_N_SRC;k++) {
OrcCodeVariable *var = code->vars + insn->src_args[k];
if (opcode->src_size[k] == 0) continue;
if (var->vartype == ORC_VAR_TYPE_SRC) {
opcode_ex[j].src_ptrs[k] =
ORC_PTR_OFFSET(ex->arrays[insn->src_args[k]],
ex->params[insn->src_args[k]]*m_index);
} else if (var->vartype == ORC_VAR_TYPE_DEST) {
opcode_ex[j].src_ptrs[k] =
ORC_PTR_OFFSET(ex->arrays[insn->src_args[k]],
ex->params[insn->src_args[k]]*m_index);
}
}
for(k=0;k<ORC_STATIC_OPCODE_N_DEST;k++) {
OrcCodeVariable *var = code->vars + insn->dest_args[k];
if (opcode->dest_size[k] == 0) continue;
if (var->vartype == ORC_VAR_TYPE_DEST) {
opcode_ex[j].dest_ptrs[k] =
ORC_PTR_OFFSET(ex->arrays[insn->dest_args[k]],
ex->params[insn->dest_args[k]]*m_index);
}
}
}
for(i=0;i<ex->n;i+=CHUNK_SIZE){
for(j=0;j<code->n_insns;j++){
if (ex->n - i >= CHUNK_SIZE) {
opcode_ex[j].emulateN (opcode_ex + j, i, CHUNK_SIZE << opcode_ex[j].shift);
} else {
opcode_ex[j].emulateN (opcode_ex + j, i, (ex->n - i) << opcode_ex[j].shift);
}
}
}
}
free (opcode_ex);
for(i=0;i<ORC_N_COMPILER_VARIABLES;i++){
if (tmpspace[i]) free (tmpspace[i]);
}
}
|
C
|
#include <stdio.h>
int main(void)
{
int n;
printf("Enter the n:");
scanf("%d", &n);
for(int i = 1; i * i <= n; i++)
{
if(i * i % 2 == 0) printf("%d\n", i * i);
}
return 0;
}
|
C
|
/**
* https://www.spoj.pl/problems/LATTICE/
* Schier Michael
*/
#include <stdio.h>
#include <math.h>
#define MAXN 5000
// calculate the number of connections of length sqrt(w^2+h^2) in a n^2 grid
long numConn(int n, int w, int h)
{
long result = (n-w) + (n-h) - 1;
return w==h || w==0 || h==0 ? result*2 : result*4;
}
/**
* extend lattice
* example: n=5, new is #
* #####
* #****
* #*---
* #*-;;
* #*-;.
*/
double calc(int n, double result)
{
int w,h;
for(w=0; w<n; w++)
for(h=w; h<n; h++)
{
if(h==0)
continue;
#ifdef DEBUG
printf("-> %ld x sqrt(%d)\n", numConn(n, w, h), w*w + h*h);
#endif
result += numConn(n, w, h) * sqrt(w*w + h*h);
}
return result;
}
int main()
{
long long int i;
double result = 0.0;
for(i=1; i<=MAXN; i++)
{
result = calc(i, result);
printf("%.2lf\n", 2*result / (i*i*i*i));
fprintf(stderr, "%d\n", i);
}
return 0;
}
|
C
|
#include<stdio.h>
void main(){
int a,b,sum;
a=214;
b=1014;
sum=a+b;
printf("%d\n",sum);
}
|
C
|
#include <stdio.h>
int main()
{
int age = 0;
float ageMinutes;
printf("请输入您的年龄:");
scanf("%d", &age);
ageMinutes = age * 3.156E7;
printf("年龄对应的秒数为:%f\n", ageMinutes);
printf("年龄对应的秒数为:%e\n", ageMinutes);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.