file
stringlengths 18
26
| data
stringlengths 2
1.05M
|
---|---|
the_stack_data/86902.c |
/* arm_init.c - NEON optimised filter functions
*
* Copyright (c) 2014,2016 Glenn Randers-Pehrson
* Written by Mans Rullgard, 2011.
* Last changed in libpng 1.6.22 [May 26, 2016]
*
* This code is released under the libpng license.
* For conditions of distribution and use, see the disclaimer
* and license in png.h
*/
/* Below, after checking __linux__, various non-C90 POSIX 1003.1 functions are
* called.
*/
#if defined(__arm64__) || defined(__arm64) || defined(__aarch64__) || defined(__arm__) || defined(__arm) || defined(ARM) || defined(_ARM_) || defined(__ARM__) || defined(_M_ARM)
#define _POSIX_SOURCE 1
#include "../pngpriv.h"
#ifdef PNG_READ_SUPPORTED
#if PNG_ARM_NEON_OPT > 0
#ifdef PNG_ARM_NEON_CHECK_SUPPORTED /* Do run-time checks */
/* WARNING: it is strongly recommended that you do not build libpng with
* run-time checks for CPU features if at all possible. In the case of the ARM
* NEON instructions there is no processor-specific way of detecting the
* presence of the required support, therefore run-time detection is extremely
* OS specific.
*
* You may set the macro PNG_ARM_NEON_FILE to the file name of file containing
* a fragment of C source code which defines the png_have_neon function. There
* are a number of implementations in contrib/arm-neon, but the only one that
* has partial support is contrib/arm-neon/linux.c - a generic Linux
* implementation which reads /proc/cpufino.
*/
#ifndef PNG_ARM_NEON_FILE
# ifdef __linux__
# define PNG_ARM_NEON_FILE "../contrib/arm-neon/linux.c"
# endif
#endif
#ifdef PNG_ARM_NEON_FILE
#include <signal.h> /* for sig_atomic_t */
static int png_have_neon(png_structp png_ptr);
#include PNG_ARM_NEON_FILE
#else /* PNG_ARM_NEON_FILE */
# error "PNG_ARM_NEON_FILE undefined: no support for run-time ARM NEON checks"
#endif /* PNG_ARM_NEON_FILE */
#endif /* PNG_ARM_NEON_CHECK_SUPPORTED */
#ifndef PNG_ALIGNED_MEMORY_SUPPORTED
# error "ALIGNED_MEMORY is required; set: -DPNG_ALIGNED_MEMORY_SUPPORTED"
#endif
void
png_init_filter_functions_neon(png_structp pp, unsigned int bpp)
{
/* The switch statement is compiled in for ARM_NEON_API, the call to
* png_have_neon is compiled in for ARM_NEON_CHECK. If both are defined
* the check is only performed if the API has not set the NEON option on
* or off explicitly. In this case the check controls what happens.
*
* If the CHECK is not compiled in and the option is UNSET the behavior prior
* to 1.6.7 was to use the NEON code - this was a bug caused by having the
* wrong order of the 'ON' and 'default' cases. UNSET now defaults to OFF,
* as documented in png.h
*/
png_debug(1, "in png_init_filter_functions_neon");
#ifdef PNG_ARM_NEON_API_SUPPORTED
switch ((pp->options >> PNG_ARM_NEON) & 3)
{
case PNG_OPTION_UNSET:
/* Allow the run-time check to execute if it has been enabled -
* thus both API and CHECK can be turned on. If it isn't supported
* this case will fall through to the 'default' below, which just
* returns.
*/
#endif /* PNG_ARM_NEON_API_SUPPORTED */
#ifdef PNG_ARM_NEON_CHECK_SUPPORTED
{
static volatile sig_atomic_t no_neon = -1; /* not checked */
if (no_neon < 0)
no_neon = !png_have_neon(pp);
if (no_neon)
return;
}
#ifdef PNG_ARM_NEON_API_SUPPORTED
break;
#endif
#endif /* PNG_ARM_NEON_CHECK_SUPPORTED */
#ifdef PNG_ARM_NEON_API_SUPPORTED
default: /* OFF or INVALID */
return;
case PNG_OPTION_ON:
/* Option turned on */
break;
}
#endif
/* IMPORTANT: any new external functions used here must be declared using
* PNG_INTERNAL_FUNCTION in ../pngpriv.h. This is required so that the
* 'prefix' option to configure works:
*
* ./configure --with-libpng-prefix=foobar_
*
* Verify you have got this right by running the above command, doing a build
* and examining pngprefix.h; it must contain a #define for every external
* function you add. (Notice that this happens automatically for the
* initialization function.)
*/
pp->read_filter[PNG_FILTER_VALUE_UP-1] = png_read_filter_row_up_neon;
if (bpp == 3)
{
pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub3_neon;
pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg3_neon;
pp->read_filter[PNG_FILTER_VALUE_PAETH-1] =
png_read_filter_row_paeth3_neon;
}
else if (bpp == 4)
{
pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub4_neon;
pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg4_neon;
pp->read_filter[PNG_FILTER_VALUE_PAETH-1] =
png_read_filter_row_paeth4_neon;
}
}
#endif /* PNG_ARM_NEON_OPT > 0 */
#endif /* READ */
#endif
|
the_stack_data/248581629.c | /* Copyright (C) 1992,93,96,97,98,2001 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <termios.h>
#include <errno.h>
#include <stddef.h>
struct speed_struct
{
speed_t value;
speed_t internal;
};
static const struct speed_struct speeds[] =
{
#ifdef B0
{ 0, B0 },
#endif
#ifdef B50
{ 50, B50 },
#endif
#ifdef B75
{ 75, B75 },
#endif
#ifdef B110
{ 110, B110 },
#endif
#ifdef B134
{ 134, B134 },
#endif
#ifdef B150
{ 150, B150 },
#endif
#ifdef B200
{ 200, B200 },
#endif
#ifdef B300
{ 300, B300 },
#endif
#ifdef B600
{ 600, B600 },
#endif
#ifdef B1200
{ 1200, B1200 },
#endif
#ifdef B1200
{ 1200, B1200 },
#endif
#ifdef B1800
{ 1800, B1800 },
#endif
#ifdef B2400
{ 2400, B2400 },
#endif
#ifdef B4800
{ 4800, B4800 },
#endif
#ifdef B9600
{ 9600, B9600 },
#endif
#ifdef B19200
{ 19200, B19200 },
#endif
#ifdef B38400
{ 38400, B38400 },
#endif
#ifdef B57600
{ 57600, B57600 },
#endif
#ifdef B76800
{ 76800, B76800 },
#endif
#ifdef B115200
{ 115200, B115200 },
#endif
#ifdef B153600
{ 153600, B153600 },
#endif
#ifdef B230400
{ 230400, B230400 },
#endif
#ifdef B307200
{ 307200, B307200 },
#endif
#ifdef B460800
{ 460800, B460800 },
#endif
#ifdef B500000
{ 500000, B500000 },
#endif
#ifdef B576000
{ 576000, B576000 },
#endif
#ifdef B921600
{ 921600, B921600 },
#endif
#ifdef B1000000
{ 1000000, B1000000 },
#endif
#ifdef B1152000
{ 1152000, B1152000 },
#endif
#ifdef B1500000
{ 1500000, B1500000 },
#endif
#ifdef B2000000
{ 2000000, B2000000 },
#endif
#ifdef B2500000
{ 2500000, B2500000 },
#endif
#ifdef B3000000
{ 3000000, B3000000 },
#endif
#ifdef B3500000
{ 3500000, B3500000 },
#endif
#ifdef B4000000
{ 4000000, B4000000 },
#endif
};
/* Set both the input and output baud rates stored in *TERMIOS_P to SPEED. */
int
cfsetspeed (struct termios *termios_p, speed_t speed)
{
size_t cnt;
for (cnt = 0; cnt < sizeof (speeds) / sizeof (speeds[0]); ++cnt)
if (speed == speeds[cnt].internal)
{
cfsetispeed (termios_p, speed);
cfsetospeed (termios_p, speed);
return 0;
}
else if (speed == speeds[cnt].value)
{
cfsetispeed (termios_p, speeds[cnt].internal);
cfsetospeed (termios_p, speeds[cnt].internal);
return 0;
}
__set_errno (EINVAL);
return -1;
}
|
the_stack_data/89914.c |
int main()
{
int n;
int c[n];
#pragma scop
{
int c1;
if (n >= 1) {
for (c1 = 1; c1 <= n; c1++) {{
// A C++ comment.
c[c1] = 0;
}
}
}
}
/* Another comment in the scop. */
#pragma endscop
}
|
the_stack_data/408874.c | #include <unistd.h>
#include <stdio.h>
#define BUF_SZ 128
char echobuf[128];
int main(int argc, char* argv[])
{
argc--;
argv++;
while (argc-- > 0) {
printf("%s ", *argv++);
}
printf("\n");
return 0;
}
|
the_stack_data/61074952.c | #include<stdio.h>
int main()
{
//Q12.WAP input a no and check whether that no is perfect or not
int n=0,i=1;
printf("Enter a number to check for perfectness: ");
scanf("%d",&n);
int sum = 0;
for(;i<n;i++)if(n%i==0)sum+=i;
if (sum == n && n != 1)printf("Perfect.");
else printf("Not perfect.");
return 0;
} |
the_stack_data/26156.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
int TAM = 50, letraA = 0;
char palavra[TAM];
printf("Digite a palavra: ");
scanf("%[^\n]", palavra);
for(int i = 0; i < TAM; i++){
if(palavra[i] == '\0'){
break;
}
if(palavra[i] == 'a' || palavra[i] == 'A' ){
letraA++;
}
}
printf("Palavra: %s\nLetra A: %d", palavra, letraA);
} |
the_stack_data/607722.c | extern int __VERIFIER_nondet_int();
extern void __VERIFIER_error() __attribute__ ((__noreturn__));
#include <stdlib.h>
#include <limits.h>
#define APPEND(l,i) {i->next=l; l=i;}
typedef struct node {
struct node *next;
int val;
} Node;
int main() {
Node *l = NULL;
int min = INT_MAX, max = -INT_MAX;
while (__VERIFIER_nondet_int()) {
Node *p = malloc(sizeof(*p));
p->val = __VERIFIER_nondet_int();
APPEND(l, p)
if (min > p->val) {
min = p->val;
}
if (max < p->val) {
max = p->val;
}
}
Node *i = l;
while (i != NULL) {
if (i->val < min)
__VERIFIER_error();
if (i->val > max)
__VERIFIER_error();
i = i->next;
}
}
|
the_stack_data/108029.c | #include <math.h>
#include <stdio.h>
int main() {
double pi = 4 * atan(1);
/*Pi / 4 is 45 degrees. All answers should be the same.*/
double radians = pi / 4;
double degrees = 45.0;
double temp;
/*sine*/
printf("%f %f\n", sin(radians), sin(degrees * pi / 180));
/*cosine*/
printf("%f %f\n", cos(radians), cos(degrees * pi / 180));
/*tangent*/
printf("%f %f\n", tan(radians), tan(degrees * pi / 180));
/*arcsine*/
temp = asin(sin(radians));
printf("%f %f\n", temp, temp * 180 / pi);
/*arccosine*/
temp = acos(cos(radians));
printf("%f %f\n", temp, temp * 180 / pi);
/*arctangent*/
temp = atan(tan(radians));
printf("%f %f\n", temp, temp * 180 / pi);
return 0;
}
|
the_stack_data/1177070.c | //*****************************************************************
//EDGARDO ADRIÁN FRANCO MARTÍNEZ
//(C) Agosto 2010 Versión 1.5
//Lectura, escritura y tratamiento de imagenes BMP
//Compilación: "gcc BMP.c -o BMP"
//Ejecución: "./BMP imagen.bmp"
//Observaciones "imagen.bmp" es un BMP de 24 bits
//*****************************************************************
//*****************************************************************
//LIBRERIAS INCLUIDAS
//*****************************************************************
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//*****************************************************************
//DEFINICION DE CONSTANTES DEL PROGRAMA
//*****************************************************************
#define IMAGEN_TRATADA "tratada.bmp" //Ruta y nombre del archivo de la imagen de salida BMP
//********************************************************************************
//DECLARACION DE ESTRUCTURAS
//********************************************************************************
//Estructura para almacenar la cabecera de la imagen BMP y un apuntador a la matriz de pixeles
typedef struct BMP
{
char bm[2]; //(2 Bytes) BM (Tipo de archivo)
int tamano; //(4 Bytes) Tamaño del archivo en bytes
int reservado; //(4 Bytes) Reservado
int offset; //(4 Bytes) offset, distancia en bytes entre la img y los píxeles
int tamanoMetadatos; //(4 Bytes) Tamaño de Metadatos (tamaño de esta estructura = 40)
int alto; //(4 Bytes) Ancho (numero de píxeles horizontales)
int ancho; //(4 Bytes) Alto (numero de pixeles verticales)
short int numeroPlanos; //(2 Bytes) Numero de planos de color
short int profundidadColor; //(2 Bytes) Profundidad de color (debe ser 24 para nuestro caso)
int tipoCompresion; //(4 Bytes) Tipo de compresión (Vale 0, ya que el bmp es descomprimido)
int tamanoEstructura; //(4 Bytes) Tamaño de la estructura Imagen (Paleta)
int pxmh; //(4 Bytes) Píxeles por metro horizontal
int pxmv; //(4 Bytes) Píxeles por metro vertical
int coloresUsados; //(4 Bytes) Cantidad de colores usados
int coloresImportantes; //(4 Bytes) Cantidad de colores importantes
unsigned char **pixel; //Puntero a una tabla dinamica de caracteres de 2 dimensiones almacenara el valor del pixel en escala de gris (0-255)
}BMP;
//*****************************************************************
//DECLARACIÓN DE FUNCIONES
//*****************************************************************
void abrir_imagen(BMP *imagen, char ruta[]); //Función para abrir la imagen BMP
void crear_imagen(BMP *imagen, char ruta[]); //Función para crear una imagen BMP
/*********************************************************************************************************
//PROGRAMA PRINCIPAL
//*********************************************************************************************************/
int main (int argc, char* argv[])
{
int i,j; //Variables auxiliares para loops
BMP img; //Estructura de tipo imágen
char IMAGEN[45]; //Almacenará la ruta de la imagen
//******************************************************************
//Si no se introdujo la ruta de la imagen BMP
//******************************************************************
//Si no se introduce una ruta de imágen
if (argc!=2)
{
printf("\nIndique el nombre del archivo a codificar - Ejemplo: [user@equipo]$ %s imagen.bmp\n",argv[0]);
exit(1);
}
//Almacenar la ruta de la imágen
strcpy(IMAGEN,argv[1]);
//***************************************************************************************************************************
//0 Abrir la imágen BMP de 24 bits, almacenar su cabecera en la estructura img y colocar sus pixeles en el arreglo img.pixel[][]
//***************************************************************************************************************************
abrir_imagen(&img,IMAGEN);
printf("\n*************************************************************************");
printf("\nIMAGEN: %s",IMAGEN);
printf("\n*************************************************************************");
printf("\nDimensiones de la imágen:\tAlto=%d\tAncho=%d\n",img.alto,img.ancho);
//*************************************************************
//1 Tratamiento de los pixeles
//*************************************************************
//Imprimir el valor de los pixeles
for (i=0;i<img.alto;i++)
for (j=0;j<img.ancho;j++)
img.pixel[i][j]=img.pixel[i][j]-10;
//printf("%c\t",img.pixel[i][j]);
//***************************************************************************************************************************
//2 Crear la imágen BMP a partir del arreglo img.pixel[][]
//***************************************************************************************************************************
crear_imagen(&img,IMAGEN_TRATADA);
printf("\nImágen BMP tratada en el archivo: %s\n",IMAGEN_TRATADA);
//Terminar programa normalmente
exit (0);
}
//************************************************************************
//FUNCIONES
//************************************************************************
//*************************************************************************************************************************************************
//Función para abrir la imagen, colocarla en escala de grisis en la estructura imagen imagen (Arreglo de bytes de alto*ancho --- 1 Byte por pixel 0-255)
//Parametros de entrada: Referencia a un BMP (Estructura BMP), Referencia a la cadena ruta char ruta[]=char *ruta
//Parametro que devuelve: Ninguno
//*************************************************************************************************************************************************
void abrir_imagen(BMP *imagen, char *ruta)
{
FILE *archivo; //Puntero FILE para el archivo de imágen a abrir
int i,j;
//Abrir el archivo de imágen
archivo = fopen( ruta, "rb+" );
if(!archivo)
{
//Si la imágen no se encuentra en la ruta dada
printf( "La imágen %s no se encontro\n",ruta);
exit(1);
}
//Leer la cabecera de la imagen y almacenarla en la estructura a la que apunta imagen
fseek( archivo,0, SEEK_SET);
fread(&imagen->bm,sizeof(char),2, archivo);
fread(&imagen->tamano,sizeof(int),1, archivo);
fread(&imagen->reservado,sizeof(int),1, archivo);
fread(&imagen->offset,sizeof(int),1, archivo);
fread(&imagen->tamanoMetadatos,sizeof(int),1, archivo);
fread(&imagen->alto,sizeof(int),1, archivo);
fread(&imagen->ancho,sizeof(int),1, archivo);
fread(&imagen->numeroPlanos,sizeof(short int),1, archivo);
fread(&imagen->profundidadColor,sizeof(short int),1, archivo);
fread(&imagen->tipoCompresion,sizeof(int),1, archivo);
fread(&imagen->tamanoEstructura,sizeof(int),1, archivo);
fread(&imagen->pxmh,sizeof(int),1, archivo);
fread(&imagen->pxmv,sizeof(int),1, archivo);
fread(&imagen->coloresUsados,sizeof(int),1, archivo);
fread(&imagen->coloresImportantes,sizeof(int),1, archivo);
//Validar ciertos datos de la cabecera de la imágen
if (imagen->bm[0]!='B'||imagen->bm[1]!='M')
{
printf ("La imagen debe ser un bitmap.\n");
exit(1);
}
if (imagen->profundidadColor!= 24)
{
printf ("La imagen debe ser de 24 bits.\n");
exit(1);
}
//Reservar memoria para el arreglo que tendra la imágen en escala de grises (Arreglo de tamaño "img.ancho X img.alto")
imagen->pixel=malloc (imagen->alto* sizeof(char *));
for( i=0; i<imagen->alto; i++)
imagen->pixel[i]=malloc (imagen->ancho* sizeof(char));
//Pasar la imágen a el arreglo reservado en escala de grises
unsigned char R,B,G;
for (i=0;i<imagen->alto;i++)
{
for (j=0;j<imagen->ancho;j++)
{
fread(&B,sizeof(char),1, archivo); //Byte Blue del pixel
fread(&G,sizeof(char),1, archivo); //Byte Green del pixel
fread(&R,sizeof(char),1, archivo); //Byte Red del pixel
//Conversión a escala de grises
imagen->pixel[i][j]=(unsigned char)((R*0.3)+(G*0.59)+ (B*0.11)); //Formula correcta
//imagen->pixel[i][j]=(B+G+R)/3; //Forma simple (Promedio)
}
}
//Cerrrar el archivo
fclose(archivo);
}
//****************************************************************************************************************************************************
//Función para crear una imagen BMP, a partir de la estructura imagen imagen (Arreglo de bytes de alto*ancho --- 1 Byte por pixel 0-255)
//Parametros de entrada: Referencia a un BMP (Estructura BMP), Referencia a la cadena ruta char ruta[]=char *ruta
//Parametro que devuelve: Ninguno
//****************************************************************************************************************************************************
void crear_imagen(BMP *imagen, char ruta[])
{
FILE *archivo; //Puntero FILE para el archivo de imágen a abrir
int i,j;
//Abrir el archivo de imágen
archivo = fopen( ruta, "wb+" );
if(!archivo)
{
//Si la imágen no se encuentra en la ruta dada
printf( "La imágen %s no se pudo crear\n",ruta);
exit(1);
}
//Escribir la cabecera de la imagen en el archivo
fseek( archivo,0, SEEK_SET);
fwrite(&imagen->bm,sizeof(char),2, archivo);
fwrite(&imagen->tamano,sizeof(int),1, archivo);
fwrite(&imagen->reservado,sizeof(int),1, archivo);
fwrite(&imagen->offset,sizeof(int),1, archivo);
fwrite(&imagen->tamanoMetadatos,sizeof(int),1, archivo);
fwrite(&imagen->alto,sizeof(int),1, archivo);
fwrite(&imagen->ancho,sizeof(int),1, archivo);
fwrite(&imagen->numeroPlanos,sizeof(short int),1, archivo);
fwrite(&imagen->profundidadColor,sizeof(short int),1, archivo);
fwrite(&imagen->tipoCompresion,sizeof(int),1, archivo);
fwrite(&imagen->tamanoEstructura,sizeof(int),1, archivo);
fwrite(&imagen->pxmh,sizeof(int),1, archivo);
fwrite(&imagen->pxmv,sizeof(int),1, archivo);
fwrite(&imagen->coloresUsados,sizeof(int),1, archivo);
fwrite(&imagen->coloresImportantes,sizeof(int),1, archivo);
//Pasar la imágen del arreglo reservado en escala de grises a el archivo (Deben escribirse los valores BGR)
for (i=0;i<imagen->alto;i++)
{
for (j=0;j<imagen->ancho;j++)
{
//Ecribir los 3 bytes BGR al archivo BMP, en este caso todos se igualan al mismo valor (Valor del pixel en la matriz de la estructura imagen)
fwrite(&imagen->pixel[i][j],sizeof(char),1, archivo); //Escribir el Byte Blue del pixel
fwrite(&imagen->pixel[i][j],sizeof(char),1, archivo); //Escribir el Byte Green del pixel
fwrite(&imagen->pixel[i][j],sizeof(char),1, archivo); //Escribir el Byte Red del pixel
}
}
//Cerrrar el archivo
fclose(archivo);
}
|
the_stack_data/173577485.c | #if ENABLE_FEATURE_GPT_LABEL
/*
* Copyright (C) 2010 Kevin Cernekee <[email protected]>
*
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
#define GPT_MAGIC 0x5452415020494645ULL
enum {
LEGACY_GPT_TYPE = 0xee,
GPT_MAX_PARTS = 256,
GPT_MAX_PART_ENTRY_LEN = 4096,
GUID_LEN = 16,
};
typedef struct {
uint64_t magic;
uint32_t revision;
uint32_t hdr_size;
uint32_t hdr_crc32;
uint32_t reserved;
uint64_t current_lba;
uint64_t backup_lba;
uint64_t first_usable_lba;
uint64_t last_usable_lba;
uint8_t disk_guid[GUID_LEN];
uint64_t first_part_lba;
uint32_t n_parts;
uint32_t part_entry_len;
uint32_t part_array_crc32;
} gpt_header;
typedef struct {
uint8_t type_guid[GUID_LEN];
uint8_t part_guid[GUID_LEN];
uint64_t lba_start;
uint64_t lba_end;
uint64_t flags;
uint16_t name36[36];
} gpt_partition;
static gpt_header *gpt_hdr;
static char *part_array;
static unsigned int n_parts;
static unsigned int part_entry_len;
static inline gpt_partition *
gpt_part(int i)
{
if (i >= n_parts) {
return NULL;
}
return (gpt_partition *)&part_array[i * part_entry_len];
}
static uint32_t
gpt_crc32(void *buf, int len)
{
return ~crc32_block_endian0(0xffffffff, buf, len, global_crc32_table);
}
static void
gpt_print_guid(uint8_t *buf)
{
printf(
"%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
buf[3], buf[2], buf[1], buf[0],
buf[5], buf[4],
buf[7], buf[6],
buf[8], buf[9],
buf[10], buf[11], buf[12], buf[13], buf[14], buf[15]);
}
static void
gpt_print_wide36(uint16_t *s)
{
#if ENABLE_UNICODE_SUPPORT
char buf[37 * 4];
wchar_t wc[37];
int i = 0;
while (i < ARRAY_SIZE(wc)-1) {
if (s[i] == 0)
break;
wc[i] = s[i];
i++;
}
wc[i] = 0;
if (wcstombs(buf, wc, sizeof(buf)) <= sizeof(buf)-1)
fputs(printable_string(NULL, buf), stdout);
#else
char buf[37];
int i = 0;
while (i < ARRAY_SIZE(buf)-1) {
if (s[i] == 0)
break;
buf[i] = (0x20 <= s[i] && s[i] < 0x7f) ? s[i] : '?';
i++;
}
buf[i] = '\0';
fputs(buf, stdout);
#endif
}
static void
gpt_list_table(int xtra UNUSED_PARAM)
{
int i;
char numstr6[6];
smart_ulltoa5(total_number_of_sectors * sector_size, numstr6, " KMGTPEZY")[0] = '\0';
printf("Disk %s: %llu sectors, %s\n", disk_device,
(unsigned long long)total_number_of_sectors,
numstr6);
printf("Logical sector size: %u\n", sector_size);
printf("Disk identifier (GUID): ");
gpt_print_guid(gpt_hdr->disk_guid);
printf("\nPartition table holds up to %u entries\n",
(int)SWAP_LE32(gpt_hdr->n_parts));
printf("First usable sector is %llu, last usable sector is %llu\n\n",
(unsigned long long)SWAP_LE64(gpt_hdr->first_usable_lba),
(unsigned long long)SWAP_LE64(gpt_hdr->last_usable_lba));
/* "GPT fdisk" has a concept of 16-bit extension of the original MBR 8-bit type codes,
* which it displays here: its output columns are ... Size Code Name
* They are their own invention and are not stored on disk.
* Looks like they use them to support "hybrid" GPT: for example, they have
* AddType(0x8307, "69DAD710-2CE4-4E3C-B16C-21A1D49ABED3", "Linux ARM32 root (/)");
* and then (code>>8) matches what you need to put into MBR's type field for such a partition.
* To print those codes, we'd need a GUID lookup table. Lets just drop the "Code" column instead:
*/
puts("Number Start (sector) End (sector) Size Name");
// 123456 123456789012345 123456789012345 12345 abc
for (i = 0; i < n_parts; i++) {
gpt_partition *p = gpt_part(i);
if (p->lba_start) {
smart_ulltoa5((1 + SWAP_LE64(p->lba_end) - SWAP_LE64(p->lba_start)) * sector_size,
numstr6, " KMGTPEZY")[0] = '\0';
printf("%6u %15llu %15llu %s ",
i + 1,
(unsigned long long)SWAP_LE64(p->lba_start),
(unsigned long long)SWAP_LE64(p->lba_end),
numstr6
);
gpt_print_wide36(p->name36);
bb_putchar('\n');
}
}
}
static int
check_gpt_label(void)
{
unsigned part_array_len;
struct partition *first = pt_offset(MBRbuffer, 0);
struct pte pe;
uint32_t crc;
/* LBA 0 contains the legacy MBR */
if (!valid_part_table_flag(MBRbuffer)
|| first->sys_ind != LEGACY_GPT_TYPE
) {
current_label_type = 0;
return 0;
}
/* LBA 1 contains the GPT header */
read_pte(&pe, 1);
gpt_hdr = (void *)pe.sectorbuffer;
if (gpt_hdr->magic != SWAP_LE64(GPT_MAGIC)) {
current_label_type = 0;
return 0;
}
init_unicode();
if (!global_crc32_table) {
global_crc32_new_table_le();
}
crc = SWAP_LE32(gpt_hdr->hdr_crc32);
gpt_hdr->hdr_crc32 = 0;
if (gpt_crc32(gpt_hdr, SWAP_LE32(gpt_hdr->hdr_size)) != crc) {
/* FIXME: read the backup table */
puts("\nwarning: GPT header CRC is invalid\n");
}
n_parts = SWAP_LE32(gpt_hdr->n_parts);
part_entry_len = SWAP_LE32(gpt_hdr->part_entry_len);
if (n_parts > GPT_MAX_PARTS
|| part_entry_len > GPT_MAX_PART_ENTRY_LEN
|| SWAP_LE32(gpt_hdr->hdr_size) > sector_size
) {
puts("\nwarning: unable to parse GPT disklabel\n");
current_label_type = 0;
return 0;
}
part_array_len = n_parts * part_entry_len;
part_array = xmalloc(part_array_len);
seek_sector(SWAP_LE64(gpt_hdr->first_part_lba));
if (full_read(dev_fd, part_array, part_array_len) != part_array_len) {
fdisk_fatal(unable_to_read);
}
if (gpt_crc32(part_array, part_array_len) != gpt_hdr->part_array_crc32) {
/* FIXME: read the backup table */
puts("\nwarning: GPT array CRC is invalid\n");
}
puts("Found valid GPT with protective MBR; using GPT\n");
current_label_type = LABEL_GPT;
return 1;
}
#endif /* GPT_LABEL */
|
the_stack_data/25137244.c | #include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
int main(int argc, char **argv)
{
int fd[2],fi,r,w;
char buf[512];
pid_t pid1, pid2;
if(argc<5){ //ERROR
fprintf(stderr, "Format: ./exe pr1 arg1 arg2 filename\n");
return 1;
}
if(pipe(fd) < 0) //ERROR
{
perror("pipe");
return 1;
}
pid1 = fork();
if(pid1<0) //ERROR
{
perror("fork");
return 1;
}
else if(pid1 == 0)
{
//1st SON
dup2(fd[1], 1); //stdout(1) is now fd[1]
close(fd[0]);
close(fd[1]);
execlp(argv[1], argv[1], argv[2], argv[3], NULL);
fprintf(stderr, "Can't run %s\n", argv[1]);
return 1;
}
pid2 = fork();
if(pid2<0)
{
perror("fork");
return 1;
}
else if(pid2==0)
{
//2nd SON
dup2(fd[0], 0); //stdin(0) is now fd[0]
close(fd[0]);
close(fd[1]);
fi = open(argv[4], O_WRONLY | O_CREAT, 0644);
if(fi == -1)
{
fprintf(stderr,"Can't open or create file %s\n", argv[4]);
return 1;
}
while((r=read(0, buf, 512)) > 0)
w = write(fi, buf, r);
return 0;
}
close(fd[0]);
close(fd[1]);
// wait(NULL);
// wait(NULL);
return 0;
}
|
the_stack_data/23575410.c |
#include <locale.h>
int main(int argc, char **argv) {
struct lconv *cur_locale = localeconv();
if (atoi(argv[1]))
{
printf("%s\n", cur_locale->decimal_point);
}
}
|
the_stack_data/577087.c | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct list_node list_node;
struct list_node
{
list_node* next;
list_node* prev;
int data;
};
typedef struct
{
list_node* head;
list_node* tail;
} list;
void list_append (list* list, int data) {
list_node* new_node = malloc( sizeof(list_node) );
new_node->data = data;
new_node->next = new_node->prev = NULL;
if (list->tail == NULL) {
list->head = list->tail = new_node;
} else {
list->tail->next = new_node;
new_node->prev = list->tail;
list->tail = new_node;
}
}
void show_items (list* list) {
list_node* tmp = list->head;
int i = 0;
while (tmp != NULL) {
printf("item %d = %d\n", i, tmp->data);
tmp = tmp->next;
i++;
}
}
int main()
{
list* list = malloc (sizeof(list));
list_append(list, 20);
list_append(list, 15);
list_append(list, 5);
list_append(list, 10);
list_append(list, 1);
show_items(list);
} |
the_stack_data/96858.c | /*
* libc/stdio/snprintf.c
*/
#include <stdio.h>
int snprintf(char * buf, size_t n, const char * fmt, ...)
{
va_list ap;
int rv;
va_start(ap, fmt);
rv = vsnprintf(buf, n, fmt, ap);
va_end(ap);
return rv;
}
EXPORT_SYMBOL(snprintf);
|
the_stack_data/212642537.c | #include <stdio.h>
#include <stdlib.h>
#define SUCESSO 0
#define LISTA_VAZIA 1
#define FALTOU_MEMORIA 2
#define CODIGO_INEXISTENTE 3
// Structs
typedef struct {
int cod;
float sal;
} Dado;
typedef struct nodo Nodo;
struct nodo {
Dado info;
Nodo *prox;
Nodo *ant;
};
typedef struct {
Nodo *inicio;
Nodo *fim;
int n;
} ListaDE;
// Funções
void criaLista(ListaDE *lt){
lt->inicio = NULL;
lt->fim = NULL;
lt->n = 0;
}
void exibe(ListaDE lt){
Nodo *pAux;
pAux = lt.inicio;
printf("* * * * * INICIO EXIBE* * * * *\n");
printf("Inicio: %p\n",lt.inicio);
while(pAux !=NULL){
printf("Ant: %p | Cod: %d | End: %p | Sal: %f | Prox: %p |\n",pAux->ant,pAux->info.cod,pAux,pAux->info.sal,pAux->prox);
pAux = pAux->prox;
}
printf("Fim: %p\n",lt.fim);
}
int estaVazia(ListaDE lt){
if(lt.n == 0){
return 1;
}else{
return 0;
}
}
int incluiNoFim(ListaDE * lt, Dado d){
Nodo *pNodo;
pNodo = (Nodo*) malloc (sizeof(Nodo));
if(pNodo == NULL){
return FALTOU_MEMORIA;
}else {
if(lt->inicio==NULL && lt->fim==NULL){ // Lista Vazia
pNodo->info = d;
pNodo->ant = NULL;
pNodo->prox = NULL;
lt->inicio = pNodo;
lt->fim= pNodo;
lt->n++;
return SUCESSO;
}else { // Quando Já tem Elementos
pNodo->info = d;
pNodo->prox = NULL;
pNodo->ant= lt->fim;
lt->fim->prox= pNodo;// mudo para aonde o ultimo elemento estava apontando
lt->fim= pNodo;
lt->n++;
return SUCESSO;
}
}
}
int existe (ListaDE lt, int cod){
Nodo *pAux;
pAux = lt.inicio;
while (pAux!=NULL){
if(pAux->info.cod == cod){
return 1;
}
pAux=pAux->prox;
}
return 0;
}
int incluiDepois(ListaDE *lt, int cd, Dado d){
Nodo *pAux,*pNodo;
pNodo = (Nodo *) malloc (sizeof (Nodo));
if (pNodo == NULL){
return FALTOU_MEMORIA;
}else {
pAux = lt->inicio;
while(pAux!=NULL){
if(pAux->info.cod == cd){
if(pAux->prox == NULL){ // Para o ultimo elemento
pNodo->info = d;
pNodo->ant=lt->fim;
pNodo->prox=pAux->prox;
pAux->prox = pNodo;
lt->fim=pNodo;
}else {
pNodo->info = d;
pNodo->prox = pAux->prox;
pNodo->ant = pAux;
pAux->prox = pNodo;
}
lt->n++;
return SUCESSO;
}
pAux = pAux->prox;
}
return CODIGO_INEXISTENTE;
}
}
int incluiNoInicio(ListaDE *lt, Dado d){
Nodo *pNodo;
pNodo = (Nodo *) malloc (sizeof (Nodo));
if(pNodo == NULL){
return FALTOU_MEMORIA;
}else{
if(lt->n == 0){
pNodo->info=d;
pNodo->ant=NULL;
pNodo->prox=NULL;
lt->inicio = pNodo;
lt->fim = pNodo;
}else {
pNodo->info=d;
pNodo->ant=NULL;
pNodo->prox=lt->inicio;
lt->inicio = pNodo;
}
lt->n++;
return SUCESSO;
}
}
int quantidadeDeNodos(ListaDE lt){
return lt.n;
}
int excluiDoInicio(ListaDE *lt, Dado *d){
if(lt->n ==0){
return LISTA_VAZIA;
}else {
Nodo *pAux;
pAux=lt->inicio;
*d= lt->inicio->info;
lt->inicio=lt->inicio->prox;
if(lt->n ==1){ // Aqui se só tiver um
lt->fim = NULL;
}else{ // Quando tem mais de um
lt->inicio->ant = NULL;
}
lt->n--;
free(pAux);
return SUCESSO;
}
}
int excluiDoFim(ListaDE *lt, Dado *d){
if(lt->n ==0){
return LISTA_VAZIA;
}else {
Nodo *pAux;
pAux=lt->fim;
*d= lt->inicio->info;
//lt->inicio=lt->inicio->prox;
if(lt->n ==1){ // Aqui se só tiver um
lt->inicio = NULL;
lt->fim = NULL;
}else{ // Quando tem mais de um
lt->fim->ant->prox=NULL;
lt->fim = lt->fim->ant;
}
lt->n--;
free(pAux);
return SUCESSO;
}
}
int consultaPorCodigo(ListaDE lt, int cd, Dado *d){
Nodo *pAux;
pAux= lt.inicio;
while(pAux!=NULL){
if(pAux->info.cod == cd){
*d=pAux->info;
return SUCESSO;
}
pAux = pAux->prox;
}
return CODIGO_INEXISTENTE;
}
int excluiNodo(ListaDE *lt, int cd, Dado *d){
Nodo *pAux;
pAux= lt->inicio;
while (pAux != NULL){
if(pAux->info.cod==cd){
if(pAux->prox == NULL && lt->n ==1){ // Aqui só tem um elemento
*d=pAux->info;
free(pAux);
lt->inicio=NULL;
lt->fim=NULL;
lt->n--;
printf("1");
return SUCESSO;
}else if( lt->n >1 && pAux->prox == NULL){ // Aqui tenho 2 ou mais e quero excluir o ultimo
*d=pAux->info;
pAux->ant->prox = NULL; // lt->fim->ant->prox
lt->fim = pAux->ant; // lt->fim-ant;
free(pAux);
lt->n--;
printf("2");
return SUCESSO;
//pAux->prox!=NULL && lt->inicio == pAux
}else if(lt->n > 1 && lt->inicio == pAux){ // // Aqui tenho 2 ou mais e quero excluir o Primeiro
*d = lt->inicio->info;
lt->inicio = lt->inicio->prox;
pAux->prox->ant = NULL;
lt->n--;
free(pAux);
printf("3");
return SUCESSO;
}else { // Excluir do meio
*d=pAux->info;
pAux->ant->prox = pAux->prox;
pAux->prox->ant = pAux->ant;
lt->n--;
free(pAux);
printf("4");
return SUCESSO;
}
}
pAux = pAux->prox;
}
}
int main(){
ListaDE lt;
Dado dad;
criaLista(<);
int op,ret,cod;
do{
printf("0 -Fim\n");
printf("1 -Inclui no fim\n");
printf("2 -Exibe na lista\n");
printf("3 -Quantidade de nodos\n");
printf("4 -Exclui do fim\n");
printf("5 -Inclui no inicio\n");
printf("6 -Exclui do inicio\n");
printf("7 -Consulta por codigo\n");
printf("8 -Verifica existencia\n");
printf("9 -Inclui Depois\n");
printf("10-Exclui nodo\n");
printf("11-Esta Vazia\n");
scanf("%d",&op);
if(op>=0 && op<=11){
switch(op){
case 0:
op=15; // Para Sair do Prog, seta op para 15
break;
case 1:
printf("Informe o Cod: ");
scanf("%d",&dad.cod);
printf("Informe o Sal: ");
scanf("%f",&dad.sal);
ret=incluiNoFim(<,dad);
if(ret==SUCESSO){
printf("Sucesso\n");
}else if(ret==FALTOU_MEMORIA){
printf("Erro MEMORIA CHEIA\n");
}
break;
case 2:
exibe(lt);
//printf("Sucesso\n");
break;
case 3:
ret=quantidadeDeNodos(lt);
printf("Quantidade de Nodos: %d\n",ret);
break;
case 4:
ret=excluiDoFim(<,&dad);
if(ret==SUCESSO){
printf("Dado Excluido\n");
printf("Cod: %d\n",dad.cod);
printf("Sal: %.2f\n",dad.sal);
printf("Sucesso\n");
}else if(ret==LISTA_VAZIA) {
printf("Lista Vazia\n ");
}
break;
case 5:
printf("Informe o Cod: ");
scanf("%d",&dad.cod);
printf("Informe o Sal: ");
scanf("%f",&dad.sal);
ret=incluiNoInicio(<,dad);
if(ret==SUCESSO){
printf("Sucesso\n");
}else if(ret==FALTOU_MEMORIA){
printf("\nErro FALTOU MEMORIA\n");
}
break;
case 6:
ret=excluiDoInicio(<,&dad);
if(ret==SUCESSO){
printf("Dado Excluido\n");
printf("Cod: %d\n",dad.cod);
printf("Sal: %.2f\n",dad.sal);
printf("Sucesso\n");
}else if(ret==LISTA_VAZIA) {
printf("Lista Vazia Sucesso\n ");
}
break;
case 7:
printf("Informe o Cod a Ser Pesquisado: ");
scanf("%d",&cod);
ret=consultaPorCodigo(lt,cod,&dad);
if(ret==SUCESSO){
printf("Sucesso\n");
printf("Cod: %d\n",dad.cod);
printf("Sal: %f\n",dad.sal);
}else if(ret==CODIGO_INEXISTENTE){
printf("CODIGO INEXISTENTE\n");
}
break;
case 8:
printf("Informe o Cod a Ser Pesquisado: ");
scanf("%d",&cod);
ret=existe(lt,cod);
if(ret==1){
printf("Existe Sucesso\n");
}else if(ret==0){
printf("NAO Existe\n");
}
break;
case 9:
printf("Informe o Cod: ");
scanf("%d",&dad.cod);
printf("Informe o Sal: ");
scanf("%f",&dad.sal);
printf("Informe a Posicao A Ser Inserido Igual ou Maior Q 1: ");
scanf("%d",&cod);
ret=incluiDepois(<,cod,dad);
if(ret==SUCESSO){
printf("Sucesso\n");
}else if(ret==FALTOU_MEMORIA){
printf("FALTOU MEMORIA\n");
}else if(ret==CODIGO_INEXISTENTE){
printf("Cod Nao Existe\n");
}
break;
case 10:
printf("Informe o Cod: ");
scanf("%d",&cod);
ret=excluiNodo(<,cod,&dad);
printf("Cod: %d\n",dad.cod);
printf("Sal: %.2f\n",dad.sal);
if(ret==SUCESSO){
printf("SUCESSO\n");
}else if(ret==CODIGO_INEXISTENTE){
printf("COD Inexistente\n");
}
break;
case 11:
ret=estaVazia(lt);
if(ret==0){
printf("Lista Nao Esta Vazia\n");
}else if(ret==LISTA_VAZIA){
printf("Lista Esta Vazia\n");
}
break;
}
exibe(lt);
}
}while (op>=0 && op<=11);
return 0;
}
|
the_stack_data/23574798.c | //===================
// Compile with -pthread
//===================
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <wait.h>
#include <sys/mman.h>
#include <time.h>
#include <sys/msg.h>
// The report Structure (Used when child process report to parent)
typedef struct {
int incomingPatients;
int vaccinatedPatients;
} Report;
// Message queue structure
struct messg {
long mtype; //this is a free value e.g for the address of the message
Report mrep; //this is the message itself
};
typedef struct messg Message;
/*Main program code*/
int msgid; /// the message ID of the communication
int file_descriptors[2]; /// the pipe that going to be used for communication between process children
int file_descriptors1[2]; /// pipe for the second child
/*Note: 2 pipes needed since 1 child will take the even processed data,
while the other will take the odd ones*/
/*
* SIGUSR1 signal handler
*/
void handle_signal(){
printf("1 child process begin\n");
return;
}
/**
* A full process incapsulated in a funciton. It reads data from a pipe (filled in the parent).
* And process the data. Finally return the processed data to the parent through a message queue
*/
void firstChild(){
kill(getppid(), SIGUSR1);
Report rep = {0,0}; // no incomiing and no vaccinated
/*recieving people data from the parent*/
/*closing first child discreptors*/
close(file_descriptors1[0]);
close(file_descriptors1[1]);
/*recieving people data from the parent*/
close(file_descriptors[1]);
int vaccine_shot;
while(read(file_descriptors[0], &vaccine_shot,sizeof(int)) > 0){
printf("recieved in Ursulu someone who needs: %d vaccine shots\n", vaccine_shot);
rep.incomingPatients++;
int chance = rand() % 100 + 1; // 1-100%
if(chance <= 50){ //sickness chance
rep.vaccinatedPatients++; // increasing the count of the vaccinated people
printf("Ursulu gave to patient all shots!\n");
} else{
printf("Ursulu DIDNOT vaccinate the patient!\n");
}
}
close(file_descriptors[0]);
printf("\n*** Ursulu vaccinated %d people!! ***\n", rep.vaccinatedPatients);
/*reporting data to teh parent*/
const Message m = { 5, {rep.incomingPatients, rep.vaccinatedPatients}};
int status = msgsnd( msgid, &m, sizeof(Message) , 0 );
if ( status < 0 ) perror("msgsnd error");
exit(0);
}
/**
* A full process incapsulated in a funciton. It reads data from a pipe (filled in the parent).
* And process the data. Finally return the processed data to the parent through a message queue
*/
void secondChild(){
sleep(1); // avoiding signal dropping
kill(getppid(), SIGUSR1);
Report rep = {0,0}; // no incomiing and no vaccinated
/*recieving people data from the parent*/
close(file_descriptors[0]); // closing first child discreptors
close(file_descriptors[1]);
close(file_descriptors1[1]);
int vaccine_shot;
while(read(file_descriptors1[0], &vaccine_shot,sizeof(int)) > 0){
printf("recieved in Beakmaster someone who needs: %d vaccine shots\n", vaccine_shot);
rep.incomingPatients++;
int chance = rand() % 100 + 1; // 1-100%
if(chance <= 50){
rep.vaccinatedPatients++; // increasing the count of the vaccinated people
printf("Beakmaster gave to patient all shots!\n");
} else{
printf("Beakmaster DIDNOT vaccinate the patient!\n");
}
}
close(file_descriptors1[0]);
printf("\n*** Beakmaster vaccinated %d people!! *** \n", rep.vaccinatedPatients);
/*reporting data to teh parent*/
const Message m = { 5, {rep.incomingPatients, rep.vaccinatedPatients}};
int status = msgsnd( msgid, &m, sizeof(Message) , 0 );
if ( status < 0 ) perror("msgsnd error");
exit(0);
}
/**
* Parent Process: It generates data and send them to the children through a pipe.
* After that it saves the reported back data from the children in a file
*/
void parent(int pid1, int pid2){
/*waiting for children process*/
pause();
pause();
/*Parent main job*/
int waitingPatients;
printf("\nHow many patients are there? : ");
scanf("%d", &waitingPatients);
printf("\n", waitingPatients);
/*writing data to a pipe*/
close(file_descriptors[0]);
close(file_descriptors1[0]);
for(int i = 0 ; i < waitingPatients; i++){
int vaccine_shot = 1; // 1 shot or 2 shots
if(i % 2 == 0) // even goes to ursulo
write(file_descriptors[1], &vaccine_shot, sizeof(int));
else// odd goes to beakmaster
write(file_descriptors1[1], &vaccine_shot, sizeof(int));
}
close(file_descriptors[1]);
close(file_descriptors1[1]);
/*terminating children*/
int returnStatus;
if(pid1 != -1) waitpid(pid1, &returnStatus, 0); /// waiting for the children processess to finish
if(pid2 != -1) waitpid(pid2, &returnStatus, 0); /// waiting for the children processess to finish
printf("\nChildren are dead!\n\n");
/*reading reports from message queue*/
Report finalrep = {0,0};
Message m;
int status = msgrcv(msgid, &m, sizeof(Message) , 5, 0 );
if ( status < 0 ) perror("msgsnd error");
else
{
finalrep.incomingPatients += m.mrep.incomingPatients;
finalrep.vaccinatedPatients += m.mrep.vaccinatedPatients;
printf("1 child report is:\n 1) total patients: %d\n 2) vaccinated patients: %d\n", m.mrep.incomingPatients, m.mrep.vaccinatedPatients);
}
status = msgrcv(msgid, &m, sizeof(Message) , 5, 0 );
if ( status < 0 ) perror("msgsnd error");
else
{
finalrep.incomingPatients += m.mrep.incomingPatients;
finalrep.vaccinatedPatients += m.mrep.vaccinatedPatients;
printf("1 child report is:\n 1) total patients: %d\n 2) vaccinated patients: %d\n", m.mrep.incomingPatients, m.mrep.vaccinatedPatients);
}
/*reporting to a file*/
char* dataFileName = "data.bin";
FILE* pDatabase = fopen(dataFileName, "wb");
if(!pDatabase){
fclose(pDatabase);
puts("Error with opening the file. Permission denied!");
return;
}
printf("Report with: %d total patients, and %d vaccinated patients, have been logged to data.bin file\n", finalrep.incomingPatients,finalrep.vaccinatedPatients);
fwrite( &finalrep , sizeof(Report), 1 , pDatabase); // writing the data to the file
fclose(pDatabase); // closing the reporting file
printf("\n\nDoctor closes the clinic!\n\n"); // closing the doctor
return;
}
//------------------------------ Main funciton -------------------------------
int main(int argc, char* argv[]){
// initializing area
srand(time(NULL)); // for how many shots of vaccine per patient
signal(SIGUSR1, handle_signal);
pipe(file_descriptors); // first child pipe
pipe(file_descriptors1); // second child pipe
key_t key = ftok(argv[0],1);
msgid = msgget( key, 0600 | IPC_CREAT );
if ( msgid < 0 ) { perror("msgget error"); return 1; }
int c1 = fork();
if(c1 == 0) firstChild();
else{
int c2 = fork();
if(c2 == 0) secondChild();
else {
parent(c1,c2);
if ( msgctl( msgid, IPC_RMID, NULL ) < 0 ) perror("msgctl error"); // destroying the message queue
return 0;
}
}
return 0;
} |
the_stack_data/150142530.c | /*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Chris Torek.
*
* %sccs.include.redist.c%
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)getchar.c 8.1 (Berkeley) 06/04/93";
#endif /* LIBC_SCCS and not lint */
/*
* A subroutine version of the macro getchar.
*/
#include <stdio.h>
#undef getchar
getchar()
{
return (getc(stdin));
}
|
the_stack_data/38392.c | #include <stdio.h>
#include <string.h>
#include <math.h>
main()
{
char a[21];
int i,j,n,sum;
while(scanf("%s",&a)!=EOF)
{
sum=0;
n=strlen(a);
for(i=0;i<n;i++)
{
if(a[i]>='a' && a[i]<='z')
{
sum+=a[i]-96;
}
if(a[i]>='A' && a[i]<='Z')
{
sum+=a[i]-38;
}
}
if(sum==1)
{
printf("It is a prime word.\n");
}
for(i=2;i<sum;i++)
{
if(sum % i == 0)
{
printf("It is not a prime word.\n");
break;
}
}
if(i==sum)
{
printf("It is a prime word.\n");
}
}
return 0;
}
|
the_stack_data/117165.c | /* Test TREE_CONSTANT VLA size: bug 27893. */
/* Origin: Joseph Myers <[email protected]> */
/* { dg-require-effective-target alloca } */
int a;
void g(void *);
void f(void) { int b[(__SIZE_TYPE__)&a]; g(b); }
|
the_stack_data/130623.c | #include "string.h"
void* memmove(void* dstptr, const void* srcptr, size_t size) {
unsigned char* dst = (unsigned char*) dstptr;
const unsigned char* src = (const unsigned char*) srcptr;
if (dst < src) {
for (size_t i = 0; i < size; i++)
dst[i] = src[i];
} else {
for (size_t i = size; i != 0; i--)
dst[i-1] = src[i-1];
}
return dstptr;
}
|
the_stack_data/655639.c | #include <sched.h>
#include "syscall.h"
int sched_yield()
{
return syscall(SYS_sched_yield);
}
|
the_stack_data/179831280.c | //@ #include "nat.gh"
/*@
lemma void induction(nat n, nat m)
requires true;
ensures true;
{
switch(n)
{
case succ(n0):
induction(n, m); //~
case zero:
}
}
@*/ |
the_stack_data/52483.c | #define MSIZE 256
double u[MSIZE][MSIZE], f[MSIZE][MSIZE];
int n, m;
void initialize ()
{
int i, j, xx;
n = MSIZE;
m = MSIZE;
double dx = 2.0 / (n - 1);
for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
{
xx = (int) (-1.0 + dx * (i - 1));
u[i][j] = 0.0;
f[i][j] = -1.0 * (1.0 - xx * xx);
}
}
|
the_stack_data/161081149.c | //diamond_1-2.c
int main(void) {
int x;
int y;
(x = 0);
assume(y >= 0);
while (x < 99) {
if (y % 2 == 0) {
x = x + 1;
} else {
x = x + 2;
}
}
assert((x % 2) == (y % 2));
}
|
the_stack_data/156393701.c | #include<stdio.h>
int main()
{
int a,b;
scanf("%d%d" , &a, &b);
int z=b%a;
int r=a-z;
printf("%d\n" ,r);
} |
the_stack_data/889066.c | /* 1009 说反话 (20 分)
解析:
1. scanf处理输入的空格。1. 分割字符串的技巧。
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){
// 处理输入
char string[80];
if(scanf("%[^\n]", string) != 1) return EXIT_FAILURE;
// 分割单词
int len = strlen(string);
char words[80][80];
int i = 0, j = 0;
for(int k=0; k<=len; k++){
if(string[k] != ' ' && string[k] !='\0'){
words[i][j] = string[k];
j++;
}else{
words[i][j] = '\0';
i++;
j = 0;
}
}
// 处理输出
while(--i >= 0){
printf("%s%s", words[i], i==0?"":" ");
}
return EXIT_SUCCESS;
}
|
the_stack_data/179830108.c | // this source is derived from CHILL AST originally from file 'peel5678.c' as parsed by frontend compiler rose
// example from the CHiLL manual page 13 (ALMOST)
void mm(float **A, float **B, float **C) {
int t6;
int t4;
int t2;
for (t2 = 0; t2 <= 7; t2 += 1)
for (t4 = 0; t4 <= 15; t4 += 1) {
C[t2][t4] = 0.0f;
C[t2][t4] += A[t2][0] * B[0][t4];
C[t2][t4] += A[t2][1] * B[1][t4];
C[t2][t4] += A[t2][2] * B[2][t4];
C[t2][t4] += A[t2][3] * B[3][t4];
for (t6 = 4; t6 <= 31; t6 += 1)
C[t2][t4] += A[t2][t6] * B[t6][t4];
}
}
|
the_stack_data/95683.c | const int size = 1000;
int main () {
int b[size];
int i = 0;
int j = 0;
l8787:
for (i=0; i < size; i++) {
b[i] = 0;
}
return b[size-1];
}
|
the_stack_data/68888387.c | #include <stdio.h>
char
decode_hex(char input) {
static char hex[] = "0123456789ABCDEF";
int i; // I hate you, C before C99.
for (i = 0; i < 16; ++i) {
if (input == hex[i]) {
return i;
}
}
return 0;
}
void
nginx_unescape(char* inp)
{
char* outp = inp;
while (*inp) {
if (*inp == '\\' && *(inp+1) == 'x') {
*outp++ = (decode_hex(*(inp+2)) << 4) + decode_hex(*(inp+3));
inp += 4;
} else {
*outp++ = *inp++;
}
}
*outp = 0;
} |
the_stack_data/150140863.c | #include <stdio.h>
int main(){
int num1, num2, smallest, i, largest, total;
total = 0;
printf("Enter the two numbers: ");
scanf("%d %d", &num1, &num2);
smallest = num1;
largest = num2;
if(num2<num1){
smallest = num2;
largest = num1;
}
printf("\n");
do{
printf("%-5d%-5d\n", smallest, largest);
if(smallest % 2 != 0){
total += largest;
}
smallest /= 2;
largest *= 2;
if(smallest == 1){
printf("%-5d%-5d\n", smallest, largest);
total += largest;
break;
}
}while(1);
printf("The total is %d!", total);
return 0;
}
|
the_stack_data/156392489.c | #include <math.h>
extern void __VERIFIER_error() __attribute__ ((__noreturn__));
void __VERIFIER_assert(int cond) { if (!(cond)) { ERROR: __VERIFIER_error(); } return; }
int main(void)
{
__VERIFIER_assert(fmin(2,1) == 1.f);
__VERIFIER_assert(fmin(-INFINITY,0) == -(1./0.0));
__VERIFIER_assert(fmin(NAN,-1) == -1.f);
__VERIFIER_assert(!(fmin(NAN,NAN) == NAN));
}
|
the_stack_data/61076401.c | /* Mixmaster version 3.1 -- (C) 1999 - 2016 Anonymizer Inc. and others.
Mixmaster may be redistributed and modified under certain conditions.
This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
ANY KIND, either express or implied. See the file COPYRIGHT for
details.
Menu-based user interface - nym management
$Id$ */
#ifdef NYMSUPPORT
#include "menu.h"
#include "mix3.h"
#include <string.h>
#include <stdlib.h>
#ifdef POSIX
#include <unistd.h>
#endif /* POSIX */
#ifdef USE_NCURSES
void menu_nym(char *nnym)
{
char nym[maxnym][LINELEN];
char pending[maxnym][LINELEN];
int c, i, num = 0, numpending = 0, select = -1;
int edit = 0;
BUFFER *nymlist;
int s;
int pass = 0;
char reliability[9]; /* When printing information about a chain,
this variable stores the reliability. */
nymlist = buf_new();
strcpy(nym[0], NONANON);
strcatn(nym[0], " (", sizeof(nym[0]));
strcatn(nym[0], NAME, sizeof(nym[0]));
strcatn(nym[0], ")", sizeof(nym[0]));
strcpy(nym[1], ANON);
num = 2;
if (nymlist_read(nymlist) == -1) {
user_delpass();
mix_status("");
} else
pass = 1;
while (nymlist_get(nymlist, nym[num], NULL, NULL, NULL, NULL, NULL, &s) >= 0) {
if (s == NYM_OK) {
if (num < maxnym)
num++;
} else if (s == NYM_WAITING) {
if (numpending < maxnym)
strncpy(pending[numpending++], nym[num], LINELEN);
}
}
buf_free(nymlist);
nymselect:
clear();
standout();
printw("Select nym:\n\n");
standend();
#ifdef USE_PGP
if (pass)
printw("c)reate new nym\ne)dit nym\nd)elete nym\n\n");
else
printw("[nym passphrase is invalid]\n\n");
#endif /* USE_PGP */
for (i = 0; i < num; i++)
printw("%d) %s\n", i, nym[i]);
if (numpending > 0) {
printw("\n\nWaiting for confirmation: ");
for (i = 0; i < numpending; i++)
printw("%s ", pending[i]);
printw("\n");
}
select:
if (select != -1)
printw("\r%d", select);
else
printw("\r \r");
refresh();
c = getch();
if (c == erasechar())
c = KEY_BACKSPACE;
if (c >= '0' && c <= '9') {
if (select == -1)
select = c - '0';
else
select = 10 * select + c - '0';
if (edit ? select == 0 || select >= num + numpending - 1 : select >= num) {
beep();
select = -1;
}
refresh();
goto select;
} else
switch (c) {
case KEY_BACKSPACE:
select /= 10;
if (select < 1)
select = -1;
goto select;
case 'q':
if (edit) {
edit = 0;
select = -1;
goto nymselect;
}
break;
#ifdef USE_PGP
case 'e':
if (pass) {
if (edit || num + numpending < 3) {
edit = 0;
select = -1;
goto nymselect;
} else {
clear();
standout();
printw("Edit nym:\n\n");
standend();
for (i = 2; i < num + numpending; i++)
printw("%d) %s\n", i - 1, i < num ? nym[i] : pending[i - num]);
printw("\n");
select = -1;
edit = NYM_MODIFY;
goto select;
}
}
break;
case 'd':
if (pass) {
if (edit || num + numpending < 3) {
edit = 0;
select = -1;
goto nymselect;
} else {
clear();
standout();
printw("Delete nym:\n\n");
standend();
for (i = 2; i < num + numpending; i++)
printw("%d) %s\n", i - 1, i < num ? nym[i] : pending[i - num]);
printw("\n");
select = -1;
edit = NYM_DELETE;
goto select;
}
}
break;
case '\r':
case '\n':
if (select == -1 || (edit && select == 0)) {
beep();
edit = 0;
select = -1;
goto nymselect;
}
if (!edit) {
strncpy(nnym, nym[select], LINELEN);
return;
}
/* fallthru */
case 'c':
if (pass) {
char nymserv[LINELEN] = "*";
char replyblock[5][CHAINMAX], dest[10][LINELEN];
int latent[5], desttype[5];
char mdest[LINELEN], pdest[LINELEN] = "alt.anonymous.messages",
psub[LINELEN] = "";
int deflatent = 0, defdesttype = MSG_MAIL;
char alias[LINELEN] = "";
BUFFER *name, *opt;
char sendchain[CHAINMAX];
int sendnumcopies = 1, rnum = 1;
int i;
char line[LINELEN];
int acksend = 0, signsend = 0, fixedsize = 0, disable = 0,
fingerkey = 1;
name = buf_new();
opt = buf_new();
strncpy(sendchain, CHAIN, CHAINMAX);
strncpy(mdest, ADDRESS, LINELEN);
if (edit)
strncpy(alias, select + 1 < num ? nym[select + 1] :
pending[select + 1 - num], LINELEN);
if (edit == NYM_MODIFY) {
nymlist_getnym(alias, NULL, NULL, opt, name, NULL);
acksend = bufifind(opt, "+acksend");
signsend = bufifind(opt, "+signsend");
fixedsize = bufifind(opt, "+fixedsize");
disable = bufifind(opt, "+disable");
fingerkey = bufifind(opt, "+fingerkey");
rnum = -1;
}
newnym:
if (!edit) {
clear();
standout();
printw("Create a nym:");
standend();
mvprintw(3, 0, "Alias address: ");
echo();
wgetnstr(stdscr, alias, LINELEN);
noecho();
if (alias[0] == '\0')
goto end;
for (i = 0; alias[i] > ' ' && alias[i] != '@'; i++) ;
alias[i] = '\0';
if (i == 0)
goto newnym;
mvprintw(4, 0, "Pseudonym: ");
echo();
wgetnstr(stdscr, line, LINELEN);
noecho();
buf_sets(name, line);
menu_chain(nymserv, 2, 0);
}
if (edit != NYM_DELETE) {
for (i = 0; i < 5; i++) {
desttype[i] = defdesttype;
latent[i] = deflatent;
dest[i][0] = '\0';
strcpy(replyblock[i], "*,*,*,*");
}
if (rnum != -1) {
menu_replychain(&defdesttype, &deflatent, mdest, pdest, psub,
replyblock[0]);
desttype[0] = defdesttype;
latent[0] = deflatent;
strncpy(dest[0], desttype[0] == MSG_POST ? pdest : mdest,
LINELEN);
}
}
redraw:
clear();
standout();
switch (edit) {
case NYM_DELETE:
printw("Delete nym:");
break;
case NYM_MODIFY:
printw("Edit nym:");
break;
default:
printw("Create a nym:");
break;
}
standend();
loop:
{
if (!edit) {
cl(2, 0);
printw("Nym: a)lias address: %s", alias);
cl(3, 0);
printw(" nym s)erver: %s", nymserv);
}
if (edit != NYM_DELETE) {
cl(4, 0);
printw(" p)seudonym: %s", name->data);
if (edit)
mvprintw(6, 0, "Nym modification:");
else
mvprintw(6, 0, "Nym creation:");
}
cl(7, 0);
chain_reliability(sendchain, 0, reliability); /* chaintype 0=mix */
printw(" c)hain to nym server: %-30s (reliability: %s)", sendchain, reliability);
cl(8, 0);
printw(" n)umber of redundant copies: %d", sendnumcopies);
if (edit != NYM_DELETE) {
mvprintw(10, 0, "Configuration:\n");
printw(" A)cknowledge sending: %s\n", acksend ? "yes" : "no");
printw(" S)erver signatures: %s\n", signsend ? "yes" : "no");
printw(" F)ixed size replies: %s\n", fixedsize ? "yes" :
"no");
printw(" D)isable: %s\n", disable ? "yes" : "no");
printw(" Finger K)ey: %s\n", fingerkey ? "yes" : "no");
mvprintw(17, 0, "Reply chains:");
cl(18, 0);
if (rnum == -1)
printw(" create new r)eply block");
else {
printw(" number of r)eply chains: %2d reliability", rnum);
for (i = 0; i < rnum; i++) {
cl(i + 19, 0);
chain_reliability(replyblock[i], 1, reliability); /* 1=ek */
printw(" %d) %30s %-31s [%s]", i + 1,
desttype[i] == MSG_NULL ?
"(cover traffic)" : dest[i], replyblock[i],
reliability);
}
}
}
move(LINES - 1, COLS - 1);
refresh();
c = getch();
if (edit != NYM_DELETE && c >= '1' && c <= '9' && c - '1' < rnum) {
menu_replychain(&defdesttype, &deflatent, mdest, pdest, psub,
replyblock[c - '1']);
desttype[c - '1'] = defdesttype;
latent[c - '1'] = deflatent;
strncpy(dest[c - '1'],
desttype[c - '1'] == MSG_POST ? pdest : mdest, LINELEN);
goto redraw;
}
switch (c) {
case 'A':
acksend = !acksend;
goto redraw;
case 'S':
signsend = !signsend;
goto redraw;
case 'F':
fixedsize = !fixedsize;
goto redraw;
case 'D':
disable = !disable;
goto redraw;
case 'K':
fingerkey = !fingerkey;
goto redraw;
case 'q':
edit = 0;
select = -1;
goto nymselect;
case '\014':
goto redraw;
case 'a':
cl(2, 0);
printw("Nym: a)lias address: ");
echo();
wgetnstr(stdscr, alias, LINELEN);
noecho();
for (i = 0; alias[i] > ' ' && alias[i] != '@'; i++) ;
alias[i] = '\0';
if (i == 0)
goto nymselect;
goto redraw;
case 'p':
cl(4, 0);
printw(" p)seudonym: ");
echo();
wgetnstr(stdscr, line, LINELEN);
noecho();
if (line[0] != '\0')
buf_sets(name, line);
goto redraw;
case 'c':
menu_chain(sendchain, 0, 0);
goto redraw;
case 'n':
cl(8, 0);
printw(" n)umber of redundant copies: ");
echo();
wgetnstr(stdscr, line, LINELEN);
noecho();
sendnumcopies = strtol(line, NULL, 10);
if (sendnumcopies < 1 || sendnumcopies > 10)
sendnumcopies = 1;
goto redraw;
case 'r':
cl(18, 0);
printw(" number of r)eply chains: ");
echo();
wgetnstr(stdscr, line, LINELEN);
noecho();
i = rnum;
rnum = strtol(line, NULL, 10);
if (rnum < 1)
rnum = 1;
if (rnum > 5)
rnum = 5;
for (; i < rnum; i++)
if (dest[i][0] == '\0') {
desttype[i] = defdesttype;
latent[i] = deflatent;
strncpy(dest[i], defdesttype == MSG_POST ? pdest :
mdest, LINELEN);
}
goto redraw;
case 's':
menu_chain(nymserv, 2, 0);
goto redraw;
case '\n':
case '\r':
{
BUFFER *chains;
int err;
if (rnum == -1)
chains = NULL;
else {
chains = buf_new();
for (i = 0; i < rnum; i++)
if (replyblock[i][0] != '\0') {
if (desttype[i] == MSG_POST)
buf_appendf(chains, "Subject: %s\n", psub);
if (desttype[i] == MSG_MAIL)
buf_appends(chains, "To: ");
else if (desttype[i] == MSG_POST)
buf_appends(chains, "Newsgroups: ");
else
buf_appends(chains, "Null:");
buf_appendf(chains, "%s\n", dest[i]);
buf_appendf(chains, "Chain: %s\n", replyblock[i]);
buf_appendf(chains, "Latency: %d\n\n", latent[i]);
}
}
create:
clear();
buf_setf(opt,
" %cacksend %csignsend +cryptrecv %cfixedsize %cdisable %cfingerkey",
acksend ? '+' : '-',
signsend ? '+' : '-',
fixedsize ? '+' : '-',
disable ? '+' : '-',
fingerkey ? '+' : '-');
if (edit) {
mix_status("Preparing nymserver configuration message...");
err = nym_config(edit, alias, NULL,
name, sendchain, sendnumcopies,
chains, opt);
} else {
mix_status("Preparing nym creation request...");
err = nym_config(edit, alias, nymserv, name,
sendchain, sendnumcopies, chains,
opt);
}
if (err == -3) {
beep();
mix_status("Bad passphrase!");
getch();
goto create;
}
if (err != 0) {
mix_genericerror();
beep();
refresh();
} else {
if (edit)
mix_status("Nymserver configuration message completed.");
else
mix_status("Nym creation request completed.");
}
if (chains)
buf_free(chains);
goto end;
}
default:
beep();
goto loop;
}
}
end:
buf_free(name);
buf_free(opt);
return;
}
#endif /* USE_PGP */
default:
beep();
goto select;
}
}
#endif /* USE_NCURSES */
#endif /* NYMSUPPORT */
|
the_stack_data/117328693.c | #include <stdio.h>
main(){
int c;
while((c=getchar()) != EOF){
if(c == '\t'){
putchar('\\');
putchar('t');
}else if(c == '\b'){
putchar('\\');
putchar('b');
}else if(c =='\\'){
putchar('\\');
putchar('\\');
}else{
putchar(c);
}
}
}
|
the_stack_data/764046.c | #include <stdio.h>
#define SIZE 4
int main(void){
int no_data[SIZE];
int i;
printf("%2s%14s\n", "i", "no_data[i]");
for ( i = 0; i < SIZE; i++)
printf("%2d%14d\n", i, no_data[i]);
return 0;
} |
the_stack_data/26700068.c | extern void __VERIFIER_error();
extern void __VERIFIER_assume();
extern int __VERIFIER_nondet_int();
extern _Bool __VERIFIER_nondet_bool();
void __VERIFIER_assert(int cond) {
if (!cond) __VERIFIER_error();
}
int main() {
int x = __VERIFIER_nondet_int();
__VERIFIER_assume(x >= 0);
while (x > 0) {
_Bool b = __VERIFIER_nondet_bool();
if (b)
x = x - 1;
else
x = x + 1;
}
__VERIFIER_assert(x >= 0);
return 0;
}
|
the_stack_data/67324412.c | #include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <setjmp.h>
#include <stdlib.h>
#define MAXLINE 4096
static void sig_alrm(int);
static jmp_buf env_alrm;
int main(void) {
int n;
char line[MAXLINE];
if (signal(SIGALRM, sig_alrm) == SIG_ERR) {
perror("Error");
exit(1);
}
if (setjmp(env_alrm) != 0) {
perror("Error");
exit(1);
}
alarm(10);
if ((n = read(STDIN_FILENO, line, MAXLINE)) < 0) {
perror("Error");
exit(1);
}
alarm(0);
write(STDOUT_FILENO, line, n);
exit(0);
}
static void sig_alrm(int signo) {
longjmp(env_alrm, 1);
} |
the_stack_data/15764125.c | /*******************************************************************************
*
* Program: Sleep
*
* Description: Example of using sleep functions in C.
*
* YouTube Lesson: https://www.youtube.com/watch?v=SjOPUr7Bkmo
*
* Author: Kevin Browne @ https://portfoliocourses.com
*
*******************************************************************************/
#include <stdio.h>
#include <unistd.h>
int main(void)
{
// printf before and after sleep functions to see the sleep time
printf("before\n");
// usleep will sleep for the number of microseconds given, a very small unit
// of time... the below will sleep for 0.75 seconds
usleep(750000);
// will sleep for 5 seconds
// sleep(5);
printf("after\n");
return 0;
}
|
the_stack_data/108162.c | //Anthony Lemmon (eu6623)
//CSC4421
//Lab 8
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <signal.h>
//Function prototypes
int readFile();
void writeFile(int x);
//For usage with signal
void action(int input){
sleep(1);}
int main(){
int pid;
int x = 19530;
writeFile(x);
printf("x = %d\n", x);
pid = fork();
if (pid == -1){ //Fork error
perror("Error with fork");
exit(1);}
else if(pid > 0){ //Parent, x-=5
sleep(1);
for(int i = 1; i <= 5; i++){
printf("\nITERATION %d\n", i);
x = readFile();
x -= 5;
printf("Parent: %d\n", x);
writeFile(x);
kill(pid, SIGUSR1);
signal(SIGUSR1, action);
pause();}}
else if(pid == 0){ //Child, x/=5
for(int i = 1; i <= 5; i++){
signal(SIGUSR1, action);
pause();
x = readFile();
x /= 5;
printf("Child: %d\n", x);
writeFile(x);
kill(getppid(), SIGUSR1);}}
return 0;}
int readFile() //Read value from testfile.txt
{
char buffer[10];
int fd;
if((fd = open("testfile.txt", O_RDONLY )) == -1){
perror("Error opening file");
exit(2);}
if(read(fd, buffer, 10) == -1){
perror("Error reading file");
exit(3);}
close(fd);
return atoi(buffer);
}
void writeFile(int writeFile) //Write value to testfile.txt
{
char buffer[10];
int fd;
int xBytes;
if ( (fd = open("testfile.txt", O_CREAT | O_TRUNC | O_WRONLY, 0644 )) == -1 ){
perror("Error opening file");
exit(4);}
xBytes = sprintf(buffer, "%d", writeFile);
if ( write(fd, buffer, xBytes) == -1 )
{
perror("Error writing to file");
exit(5);}
close(fd);
return;
}
|
the_stack_data/27395.c | // Protocoale de comunicatii
// Laborator 9 - DNS
// dns.c
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
int usage(char* name)
{
printf("Usage:\n\t%s -n <NAME>\n\t%s -a <IP>\n", name, name);
return 1;
}
// Receives a name and prints IP addresses
void get_ip(char* name)
{
int ret;
struct addrinfo hints, *result, *p;
char res[2048];
// TODO: set hints
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
// TODO: get addresses
getaddrinfo(name, "http", &hints, &result);
// TODO: iterate through addresses and print them
p = result;
while(p != NULL) {
inet_ntop(p -> ai_family, &(((struct sockaddr_in *) (p -> ai_addr)) -> sin_addr), res, sizeof(res));
printf("%s\n", res);
p = p -> ai_next;
}
// TODO: free allocated data
freeaddrinfo(result);
}
// Receives an address and prints the associated name and service
void get_name(char* ip)
{
int ret;
struct sockaddr_in addr;
char host[1024];
char service[20];
// TODO: fill in address data
addr.sin_family = AF_INET;
addr.sin_port = htons(80);
ret = inet_aton(ip, &addr.sin_addr);
// TODO: get name and service
getnameinfo((struct sockaddr*) &addr, sizeof(addr), host, sizeof(host), service, sizeof(service), 0);
// TODO: print name and service
printf("host: %s\n", host);
printf("service: %s\n", service);
}
int main(int argc, char **argv)
{
if (argc < 3) {
return usage(argv[0]);
}
if (strncmp(argv[1], "-n", 2) == 0) {
get_ip(argv[2]);
} else if (strncmp(argv[1], "-a", 2) == 0) {
get_name(argv[2]);
} else {
return usage(argv[0]);
}
return 0;
}
|
the_stack_data/175142894.c | // RUN: %clang_cc1 -triple powerpc64-unknown-aix -emit-llvm %s -o - | FileCheck %s
// RUN: %clang_cc1 -triple powerpc64-unknown-unknown -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,PPC64
static unsigned char dwarf_reg_size_table[1024];
int test() {
__builtin_init_dwarf_reg_size_table(dwarf_reg_size_table);
return __builtin_dwarf_sp_column();
}
// CHECK-LABEL: define signext i32 @test()
// CHECK: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 0), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 1), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 2), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 3), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 4), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 5), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 6), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 7), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 8), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 9), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 10), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 11), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 12), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 13), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 14), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 15), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 16), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 17), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 18), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 19), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 20), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 21), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 22), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 23), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 24), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 25), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 26), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 27), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 28), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 29), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 30), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 31), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 32), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 33), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 34), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 35), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 36), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 37), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 38), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 39), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 40), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 41), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 42), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 43), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 44), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 45), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 46), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 47), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 48), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 49), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 50), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 51), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 52), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 53), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 54), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 55), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 56), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 57), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 58), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 59), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 60), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 61), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 62), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 63), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 64), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 65), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 66), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 67), align 1
// CHECK-NEXT: store i8 4, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 68), align 1
// CHECK-NEXT: store i8 4, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 69), align 1
// CHECK-NEXT: store i8 4, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 70), align 1
// CHECK-NEXT: store i8 4, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 71), align 1
// CHECK-NEXT: store i8 4, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 72), align 1
// CHECK-NEXT: store i8 4, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 73), align 1
// CHECK-NEXT: store i8 4, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 74), align 1
// CHECK-NEXT: store i8 4, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 75), align 1
// CHECK-NEXT: store i8 4, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 76), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 77), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 78), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 79), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 80), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 81), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 82), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 83), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 84), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 85), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 86), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 87), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 88), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 89), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 90), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 91), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 92), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 93), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 94), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 95), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 96), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 97), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 98), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 99), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 100), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 101), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 102), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 103), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 104), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 105), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 106), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 107), align 1
// CHECK-NEXT: store i8 16, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 108), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 109), align 1
// CHECK-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 110), align 1
// PPC64-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 111), align 1
// PPC64-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 112), align 1
// PPC64-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 113), align 1
// PPC64-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 114), align 1
// PPC64-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 115), align 1
// PPC64-NEXT: store i8 8, i8* getelementptr inbounds ([1024 x i8], [1024 x i8]* @dwarf_reg_size_table, i64 0, i64 116), align 1
// CHECK-NEXT: ret i32 1
|
the_stack_data/237642893.c | #define _XOPEN_SOURCE 700
#include <signal.h>
#include <unistd.h>
int main()
{
sigset_t set;
int status;
if (getpid() != 1) return 1;
sigfillset(&set);
sigprocmask(SIG_BLOCK, &set, 0);
if (fork()) for (;;) wait(&status);
sigprocmask(SIG_UNBLOCK, &set, 0);
setsid();
setpgid(0, 0);
return execve("/etc/rc", (char *[]){ "rc", 0 }, (char *[]){ 0 });
}
|
the_stack_data/86075115.c | // Copyright 2020, Brian Swetland <[email protected]>
// Licensed under the Apache License, Version 2.0.
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdbool.h>
#include <strings.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#define nil 0
void error(const char *fmt, ...);
typedef uint32_t u32;
typedef int32_t i32;
typedef uint8_t u8;
enum { FNMAXARGS = 8, };
// token classes (tok & tcMASK)
enum {
tcRELOP = 0x08, tcADDOP = 0x10, tcMULOP = 0x18,
tcAEQOP = 0x20, tcMEQOP = 0x28, tcMASK = 0xF8,
};
typedef enum {
// EndMarks, Braces, Brackets Parens
tEOF, tEOL, tOBRACE, tCBRACE, tOBRACK, tCBRACK, tOPAREN, tCPAREN,
// RelOps (do not reorder)
tEQ, tNE, tLT, tLE, tGT, tGE, tx0E, tx0F,
// AddOps (do not reorder)
tPLUS, tMINUS, tPIPE, tCARET, tx14, tx15, tx16, tx17,
// MulOps (do not reorder)
tSTAR, tSLASH, tPERCENT, tAMP, tANDNOT, tLEFT, tRIGHT, tx1F,
// AsnOps (do not reorder)
tADDEQ, tSUBEQ, tOREQ, tXOREQ, tx24, tx25, tx26, tx27,
tMULEQ, tDIVEQ, tMODEQ, tANDEQ, tANNEQ, tLSEQ, tRSEQ, t2F,
// Various, UnaryNot, LogicalOps,
tSEMI, tCOLON, tDOT, tCOMMA, tNOT, tAND, tOR, tBANG,
tASSIGN, tINC, tDEC, tHASH, tARROW,
// Keywords
tTYPEDEF, tSTRUCT, tVAR, tENUM,
tIF, tELSE, tWHILE,
tBREAK, tCONTINUE, tRETURN,
tFOR, tSWITCH, tCASE,
tTRUE, tFALSE, tNIL,
tIDN, tNUM, tSTR, tTYPE,
// used internal to the lexer but never returned
tSPC, tINV, tDQT, tSQT, tMSC, tTAB
} token_t;
char *tnames[] = {
"<EOF>", "<EOL>", "{", "}", "[", "]", "(", ")",
"==", "!=", "<", "<=", ">", ">=", "", "",
"+", "-", "|", "^", "", "", "", "",
"*", "/", "%", "&", "&~", "<<", ">>", "",
"+=", "-=", "|=", "^=", "", "", "", "",
"*=", "/=", "%=", "&=", "&~=", "<<=", ">>=", "",
";", ":", ".", ",", "~", "&&", "||", "!",
"=", "++", "--", "#", "->",
"typedef", "struct", "var", "enum",
"if", "else", "while",
"break", "continue", "return",
"for", "switch", "case",
"true", "false", "nil",
"<ID>", "<NUM>", "<STR>", "<TYPE>",
"<SPC>", "<INV>", "<DQT>", "<SQT>", "<MSC>", "<TAB>"
};
u8 lextab[256] = {
tEOF, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tTAB, tEOL, tSPC, tINV, tSPC, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tSPC, tBANG, tDQT, tHASH, tMSC, tPERCENT, tAMP, tSQT,
tOPAREN, tCPAREN, tSTAR, tPLUS, tCOMMA, tMINUS, tDOT, tSLASH,
tNUM, tNUM, tNUM, tNUM, tNUM, tNUM, tNUM, tNUM,
tNUM, tNUM, tCOLON, tSEMI, tLT, tASSIGN, tGT, tMSC,
tMSC, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN,
tIDN, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN,
tIDN, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN,
tIDN, tIDN, tIDN, tOBRACK, tMSC, tCBRACK, tCARET, tIDN,
tMSC, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN,
tIDN, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN,
tIDN, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN,
tIDN, tIDN, tIDN, tOBRACE, tPIPE, tCBRACE, tNOT, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
};
typedef struct StringRec* String;
typedef struct StringRec StringRec;
struct StringRec {
String next;
u32 len;
u32 kind;
char text[0];
};
#define KindNone 0
#define KindType 1
#define KindKeyword 2
// ------------------------------------------------------------------
struct CtxRec {
const char* filename; // filename of active source
int fd;
u8 iobuffer[1024]; // scanner file io buffer
u32 ionext;
u32 iolast;
u32 linenumber; // line number of most recent line
u32 lineoffset; // position of start of most recent line
u32 byteoffset; // position of the most recent character
u32 flags;
u32 cc; // scanner: next character
token_t tok; // most recent token
u32 num; // used for tNUM
char tmp[256]; // used for tIDN, tSTR;
String ident; // used for tIDN
String strtab; // TODO: hashtable
};
struct CtxRec ctx;
String make_string(const char* text, u32 len, u32 kind) {
// OPT obviously this wants to be a hash table
String str = ctx.strtab;
while (str != nil) {
if ((str->len == len) && (memcmp(text, str->text, len) == 0)) {
if ((str->kind != kind) && (kind != tIDN)) {
error("string '%s' already kind %u\n", str->text, str->kind);
}
return str;
}
str = str->next;
}
str = malloc(sizeof(StringRec) + len + 1);
str->len = len;
str->kind = kind;
memcpy(str->text, text, len);
str->text[len] = 0;
str->next = ctx.strtab;
ctx.strtab = str;
return str;
}
void make_keyword(const char* text, u32 tok) {
make_string(text, strlen(text), tok);
}
void make_type(const char* text) {
make_string(text, strlen(text), tTYPE);
}
int is_type(String str) {
return str->kind == 0x1000;
}
void init_ctx() {
memset(&ctx, 0, sizeof(ctx));
make_type("u8");
make_type("u32");
make_type("i32");
make_type("void");
make_type("str");
make_type("strptr");
make_type("bool");
make_type("token_t");
// pre-intern keywords
make_keyword("if", tIF);
//make_keyword("for", tFOR);
make_keyword("nil", tNIL);
make_keyword("else", tELSE);
make_keyword("enum", tENUM);
make_keyword("true", tTRUE);
make_keyword("false", tFALSE);
make_keyword("typedef", tTYPEDEF);
make_keyword("break", tBREAK);
make_keyword("while", tWHILE);
make_keyword("struct", tSTRUCT);
make_keyword("return", tRETURN);
make_keyword("continue", tCONTINUE);
}
void dump_file_line(const char* fn, u32 offset) {
int fd = open(fn, O_RDONLY);
if (fd < 0) {
return;
}
if (lseek(fd, offset, SEEK_SET) != offset) {
close(fd);
return;
}
char line[256];
int r = read(fd, line, 255);
if (r > 0) {
line[r] = 0;
int n = 0;
while (n < r) {
if (line[n] == '\n') {
line[n] = 0;
break;
}
n++;
}
fprintf(stderr, "\n%s", line);
}
close(fd);
}
void error(const char *fmt, ...) {
va_list ap;
fprintf(stderr,"\n\n%s:%d: ", ctx.filename, ctx.linenumber);
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
if (ctx.linenumber > 0) {
dump_file_line(ctx.filename, ctx.lineoffset);
}
fprintf(stderr, "\n\n");
exit(1);
}
void load(const char* filename) {
ctx.filename = filename;
ctx.linenumber = 0;
if (ctx.fd >= 0) {
close(ctx.fd);
}
ctx.fd = open(filename, O_RDONLY);
if (ctx.fd < 0) {
error("cannot open file '%s'", filename);
}
ctx.ionext = 0;
ctx.iolast = 0;
ctx.linenumber = 1;
ctx.lineoffset = 0;
ctx.byteoffset = 0;
}
int unhex(u32 ch) {
if ((ch >= '0') && (ch <= '9')) {
return ch - '0';
}
if ((ch >= 'a') && (ch <= 'f')) {
return ch - 'a' + 10;
}
if ((ch >= 'A') && (ch <= 'F')) {
return ch - 'A' + 10;
}
return -1;
}
u32 scan() {
while (ctx.ionext == ctx.iolast) {
if (ctx.fd < 0) {
ctx.cc = 0;
return ctx.cc;
}
int r = read(ctx.fd, ctx.iobuffer, sizeof(ctx.iobuffer));
if (r <= 0) {
ctx.fd = -1;
} else {
ctx.iolast = r;
ctx.ionext = 0;
}
}
ctx.cc = ctx.iobuffer[ctx.ionext];
ctx.ionext++;
ctx.byteoffset++;
return ctx.cc;
}
u32 unescape(u32 n) {
if (n == 'n') {
return 10;
} else if (n == 'r') {
return 13;
} else if (n == 't') {
return 9;
} else if (n == '"') {
return '"';
} else if (n == '\'') {
return '\'';
} else if (n == '\\') {
return '\\';
} else if (n == 'x') {
int x0 = unhex(scan());
int x1 = unhex(scan());
if ((x0 < 0) || (x1 < 0)) {
error("invalid hex escape");
}
return (x0 << 4) | x1;
} else {
error("invalid escape 0x%02x", n);
return 0;
}
}
token_t scan_string(u32 cc, u32 nc) {
u32 n = 0;
while (true) {
if (nc == '"') {
nc = scan();
break;
} else if (nc == 0) {
error("unterminated string");
} else if (nc == '\\') {
ctx.tmp[n] = unescape(scan());
} else {
ctx.tmp[n] = nc;
}
nc = scan();
n++;
if (n == 255) {
ctx.tmp[n] = 0;
error("constant string too large '%s'", ctx.tmp);
}
}
ctx.tmp[n] = 0;
return tSTR;
}
token_t scan_keyword(u32 len) {
ctx.tmp[len] = 0;
String idn = make_string(ctx.tmp, len, tIDN);
ctx.ident = idn;
return idn->kind;
}
token_t scan_number(u32 cc, u32 nc) {
u32 n = 1;
u32 val = cc - '0';
if ((cc == '0') && (nc == 'b')) { // binary
nc = scan();
while ((nc == '0') || (nc == '1')) {
val = (val << 1) | (nc - '0');
nc = scan();
n++;
if (n == 34) {
error("binary constant too large");
}
}
} else if ((cc == '0') && (nc == 'x')) { // hex
nc = scan();
while (true) {
int tmp = unhex(nc);
if (tmp == -1) {
break;
}
val = (val << 4) | tmp;
nc = scan();
n++;
if (n == 10) {
error("hex constant too large");
}
}
} else { // decimal
while (lextab[nc] == tNUM) {
u32 tmp = (val * 10) + (nc - '0');
if (tmp <= val) {
error("decimal constant too large");
}
val = tmp;
nc = scan();
n++;
}
}
ctx.num = val;
return tNUM;
}
token_t scan_ident(u32 cc, u32 nc) {
ctx.tmp[0] = cc;
u32 n = 1;
while (true) {
u32 tok = lextab[nc];
if ((tok == tIDN) || (tok == tNUM)) {
ctx.tmp[n] = nc;
n++;
if (n == 32) { error("identifier too large"); }
nc = scan();
} else {
break;
}
}
return scan_keyword(n);
}
token_t _next(int ws) {
u8 nc = ctx.cc;
while (true) {
u8 cc = nc;
nc = scan();
u32 tok = lextab[cc];
if (tok == tNUM) { // 0..9
return scan_number(cc, nc);
} else if (tok == tIDN) { // _ A..Z a..z
return scan_ident(cc, nc);
} else if (tok == tDQT) { // "
return scan_string(cc, nc);
} else if (tok == tSQT) { // '
ctx.num = nc;
if (nc == '\\') {
ctx.num = unescape(scan());
}
nc = scan();
if (nc != '\'') {
error("unterminated character constant");
}
nc = scan();
return tNUM;
} else if (tok == tPLUS) {
if (nc == '+') { tok = tINC; nc = scan(); }
} else if (tok == tMINUS) {
if (nc == '-') { tok = tDEC; nc = scan(); }
else if (nc == '>') { tok = tARROW; nc = scan(); }
} else if (tok == tAMP) {
if (nc == '&') { tok = tAND; nc = scan(); }
else if (nc == '~') { tok = tANDNOT; nc = scan(); }
} else if (tok == tPIPE) {
if (nc == '|') { tok = tOR; nc = scan(); }
} else if (tok == tGT) {
if (nc == '=') { tok = tGE; nc = scan(); }
else if (nc == '>') { tok = tRIGHT; nc = scan(); }
} else if (tok == tLT) {
if (nc == '=') { tok = tLE; nc = scan(); }
else if (nc == '<') { tok = tLEFT; nc = scan(); }
} else if (tok == tASSIGN) {
if (nc == '=') { tok = tEQ; nc = scan(); }
} else if (tok == tBANG) {
if (nc == '=') { tok = tNE; nc = scan(); }
} else if (tok == tSLASH) {
if (nc == '/') {
if (ws) printf("/");
// comment -- consume until EOL or EOF
while ((nc != '\n') && (nc != 0)) {
if (ws) printf("%c", nc);
nc = scan();
}
continue;
}
} else if (tok == tHASH) {
while ((nc != '\n') && (nc != 0)) {
nc = scan();
}
continue;
} else if (tok == tEOL) {
ctx.linenumber++;
ctx.lineoffset = ctx.byteoffset;
//ctx.xref[ctx.pc / 4] = ctx.linenumber;
//if (ctx.flags & cfVisibleEOL) {
// return tEOL;
//}
if (ws) printf("\n");
continue;
} else if (tok == tSPC) {
if (ws) printf(" ");
continue;
} else if (tok == tTAB) {
if (ws) printf("\t");
continue;
} else if ((tok == tMSC) || (tok == tINV)) {
error("unknown character 0x%02x", cc);
}
// if we're an AddOp or MulOp, followed by an '='
if (((tok & 0xF0) == 0x20) && (nc == '=')) {
nc = scan();
// transform us to a XEQ operation
tok = tok + 0x10;
}
return tok;
}
}
token_t next() {
return (ctx.tok = _next(1));
}
token_t nextq() {
return (ctx.tok = _next(0));
}
void printstr() {
u32 n = 0;
printf("\"");
while (n < 256) {
u32 ch = ctx.tmp[n];
if (ch == 0) {
break;
} else if ((ch < ' ') || (ch > '~')) {
printf("\\x%02x", ch);
} else if ((ch == '"') || (ch == '\\')) {
printf("\\%c", ch);
} else {
printf("%c", ch);
}
n++;
}
printf("\"");
}
void print() {
if (ctx.tok == tNUM) {
printf("%u ", ctx.num);
} else if (ctx.tok == tIDN) {
printf("@%s ", ctx.tmp);
} else if (ctx.tok == tTYPE) {
printf("@@%s ", ctx.tmp);
} else if (ctx.tok == tEOL) {
printf("\n");
} else if (ctx.tok == tSTR) {
printstr();
} else {
printf("%s ", tnames[ctx.tok]);
}
}
void emit() {
if (ctx.tok == tNUM) {
printf("%u", ctx.num);
} else if (ctx.tok == tIDN) {
printf("%s", ctx.tmp);
} else if (ctx.tok == tTYPE) {
printf("%s", ctx.tmp);
} else if (ctx.tok == tSTR) {
printstr();
} else {
printf("%s", tnames[ctx.tok]);
}
}
void expected(const char* what) {
error("expected %s, found %s", what, tnames[ctx.tok]);
}
void expect(token_t tok) {
if (ctx.tok != tok) {
error("expected %s, found %s", tnames[tok], tnames[ctx.tok]);
}
}
void require(token_t tok) {
expect(tok);
emit();
next();
}
void requireq(token_t tok) {
expect(tok);
nextq();
}
void parse_enum() {
printf("enum ");
require(tOBRACE);
while (ctx.tok != tCBRACE) {
emit();
next();
}
require(tCBRACE);
require(tSEMI);
}
void parse_expr() {
while (ctx.tok != tCPAREN) {
if (ctx.tok == tOPAREN) {
printf("(");
next();
parse_expr();
} else {
emit();
next();
}
}
require(tCPAREN);
printf(")");
}
void parse_block() {
unsigned start = 1;
while (ctx.tok != tCBRACE) {
if (start) {
start = 0;
}
if (ctx.tok == tOPAREN) {
printf("(");
next();
parse_expr();
} else if (ctx.tok == tOBRACE) {
printf("{");
next();
parse_block();
start = 1;
} else if (ctx.tok == tSEMI) {
printf(";");
next();
start = 1;
} else {
emit();
next();
}
}
require(tCBRACE);
}
void parse_func(String type, String name) {
printf("func %s(", name->text);
while (ctx.tok != tCPAREN) {
String pt = ctx.ident;
nextq();
String pn = ctx.ident;
nextq();
printf("%s %s", pn->text, pt->text);
if (ctx.tok == tCOMMA) {
printf(",");
next();
}
}
require(tCPAREN);
if (ctx.tok == tSEMI) {
printf(" %s;", type->text);
next();
return;
}
printf("%s ", type->text);
require(tOBRACE);
parse_block();
}
void parse_array(String type, String name) {
u32 n = ctx.num;
if (ctx.tok == tCBRACK) {
next();
printf("var %s []%s", name->text, type->text);
} else {
requireq(tNUM);
requireq(tCBRACK);
printf("var %s [%u]%s", name->text, n, type->text);
}
if (ctx.tok == tSEMI) {
printf(";");
next();
} else if (ctx.tok == tASSIGN) {
printf(" =");
next();
require(tOBRACE);
while (ctx.tok != tCBRACE) {
emit();
next();
}
require(tCBRACE);
require(tSEMI);
} else {
error("LOST");
}
}
void parse_program() {
next();
for (;;) {
if (ctx.tok == tENUM) {
nextq();
parse_enum();
} else if (ctx.tok == tTYPE) {
String type = ctx.ident;
requireq(tTYPE);
String ident = ctx.ident;
requireq(tIDN);
if (ctx.tok == tOBRACK) { // array
next();
parse_array(type, ident);
} else if(ctx.tok == tOPAREN) { // func
next();
parse_func(type, ident);
} else { // global var
printf("var %s %s", ident->text, type->text);
while (ctx.tok != tSEMI) {
emit();
next();
}
require(tSEMI);
}
} else if (ctx.tok == tTYPEDEF) {
nextq();
requireq(tSTRUCT);
String t1 = ctx.ident;
nextq();
if (ctx.tok == tSTAR) {
nextq();
String t2 = ctx.ident;
next();
t2->kind = tTYPE;
printf("type %s *%s", t2->text, t1->text);
} else {
next();
t1->kind = tTYPE;
printf("type %s", t1->text);
}
require(tSEMI);
} else if (ctx.tok == tSTRUCT) {
nextq();
String n = ctx.ident;
nextq();
n->kind = tTYPE;
printf("type %s struct ", n->text);
require(tOBRACE);
while (ctx.tok != tCBRACE) {
emit();
next();
}
require(tCBRACE);
require(tSEMI);
} else if (ctx.tok == tEOF) {
return;
} else {
expected("top level entity");
}
}
}
// ================================================================
int main(int argc, char **argv) {
const char *outname = "out.c";
const char *srcname = nil;
bool dump = false;
bool scan_only = false;
init_ctx();
ctx.filename = "<commandline>";
while (argc > 1) {
if (!strcmp(argv[1],"-o")) {
if (argc < 2) {
error("option -o requires argument");
}
outname = argv[2];
argc--;
argv++;
} else if (!strcmp(argv[1], "-p")) {
dump = true;
} else if (!strcmp(argv[1], "-s")) {
scan_only = true;
} else if (argv[1][0] == '-') {
error("unknown option: %s", argv[1]);
} else {
if (srcname != nil) {
error("multiple source files disallowed");
} else {
srcname = argv[1];
}
}
argc--;
argv++;
}
if (srcname == nil) {
error("no file specified");
}
ctx.filename = srcname;
load(srcname);
ctx.linenumber = 1;
ctx.lineoffset = 0;
// prime the lexer
scan();
if (scan_only) {
ctx.flags |= 1;
while (true) {
next();
print();
if (ctx.tok == tEOF) {
return 0;
}
}
}
parse_program();
return 0;
}
|
the_stack_data/61074819.c | /*
Test that the function:
int sigaddset(sigset_t *, int);
is declared.
*/
#include <signal.h>
typedef int (*sigaddset_test) (sigset_t *, int);
int dummyfcn(void)
{
sigaddset_test dummyvar;
dummyvar = sigaddset;
return 0;
}
|
the_stack_data/184517190.c | #include <stdio.h>
int i;
void * thread_func(void * arg)
{
pthread_setcanceltype(NULL);
pthread_setcancelstate(NULL);
for(i=0; i<4; i++)
{
sleep(1);
printf("I am running verry important process %i ...\n", i+1);
}
pthread_testcancel();
printf("YOU WILL NOT STOP ME!!!\n");
}
int main(int argc, char * argv[])
{
while(i < 1) sleep(1);
thread_func(fread);
printf("Requsted to cancel the thread!\n");
pthread_join(fread);
printf("The thread is stopped!\n");
return 0;
}
|
the_stack_data/153268215.c | /**********************************************************
Automatically generated for Collective Knowledge Framework
http://github.com/ctuning/ck
(C)opyright 2016 by Grigori Fursin (cTuning foundation)
Released under the same license as OpenCL
(see include/CL/cl.h)
**********************************************************/
#include <CL/cl.h>
CL_API_ENTRY cl_int CL_API_CALL
clGetPlatformIDs(cl_uint num_entries ,
cl_platform_id * platforms ,
cl_uint * num_platforms ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clGetPlatformInfo(cl_platform_id platform ,
cl_platform_info param_name ,
size_t param_value_size ,
void * param_value ,
size_t * param_value_size_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clGetDeviceIDs(cl_platform_id platform ,
cl_device_type device_type ,
cl_uint num_entries ,
cl_device_id * devices ,
cl_uint * num_devices ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clGetDeviceInfo(cl_device_id device ,
cl_device_info param_name ,
size_t param_value_size ,
void * param_value ,
size_t * param_value_size_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clCreateSubDevices(cl_device_id in_device ,
const cl_device_partition_property * properties ,
cl_uint num_devices ,
cl_device_id * out_devices ,
cl_uint * num_devices_ret ) CL_API_SUFFIX__VERSION_1_2
{}
CL_API_ENTRY cl_int CL_API_CALL
clRetainDevice(cl_device_id device ) CL_API_SUFFIX__VERSION_1_2
{}
CL_API_ENTRY cl_int CL_API_CALL
clReleaseDevice(cl_device_id device ) CL_API_SUFFIX__VERSION_1_2
{}
CL_API_ENTRY cl_context CL_API_CALL
clCreateContext(const cl_context_properties * properties ,
cl_uint num_devices ,
const cl_device_id * devices ,
void (CL_CALLBACK * pfn_notify )(const char *, const void *, size_t, void *),
void * user_data ,
cl_int * errcode_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_context CL_API_CALL
clCreateContextFromType(const cl_context_properties * properties ,
cl_device_type device_type ,
void (CL_CALLBACK * pfn_notif )(const char *, const void *, size_t, void *),
void * user_data ,
cl_int * errcode_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clRetainContext(cl_context context ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clReleaseContext(cl_context context ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clGetContextInfo(cl_context context ,
cl_context_info param_name ,
size_t param_value_size ,
void * param_value ,
size_t * param_value_size_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_command_queue CL_API_CALL
clCreateCommandQueue(cl_context context ,
cl_device_id device ,
cl_command_queue_properties properties ,
cl_int * errcode_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clRetainCommandQueue(cl_command_queue command_queue ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clReleaseCommandQueue(cl_command_queue command_queue ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clGetCommandQueueInfo(cl_command_queue command_queue ,
cl_command_queue_info param_name ,
size_t param_value_size ,
void * param_value ,
size_t * param_value_size_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_mem CL_API_CALL
clCreateBuffer(cl_context context ,
cl_mem_flags flags ,
size_t size ,
void * host_ptr ,
cl_int * errcode_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_mem CL_API_CALL
clCreateSubBuffer(cl_mem buffer ,
cl_mem_flags flags ,
cl_buffer_create_type buffer_create_type ,
const void * buffer_create_info ,
cl_int * errcode_ret ) CL_API_SUFFIX__VERSION_1_1
{}
CL_API_ENTRY cl_mem CL_API_CALL
clCreateImage(cl_context context ,
cl_mem_flags flags ,
const cl_image_format * image_format ,
const cl_image_desc * image_desc ,
void * host_ptr ,
cl_int * errcode_ret ) CL_API_SUFFIX__VERSION_1_2
{}
CL_API_ENTRY cl_int CL_API_CALL
clRetainMemObject(cl_mem memobj ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clReleaseMemObject(cl_mem memobj ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clGetSupportedImageFormats(cl_context context ,
cl_mem_flags flags ,
cl_mem_object_type image_type ,
cl_uint num_entries ,
cl_image_format * image_formats ,
cl_uint * num_image_formats ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clGetMemObjectInfo(cl_mem memobj ,
cl_mem_info param_name ,
size_t param_value_size ,
void * param_value ,
size_t * param_value_size_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clGetImageInfo(cl_mem image ,
cl_image_info param_name ,
size_t param_value_size ,
void * param_value ,
size_t * param_value_size_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clSetMemObjectDestructorCallback( cl_mem memobj ,
void (CL_CALLBACK * pfn_notif )( cl_mem /* memobj */, void* /*user_data*/),
void * user_data ) CL_API_SUFFIX__VERSION_1_1;
/* Sampler APIs */
extern CL_API_ENTRY cl_sampler CL_API_CALL
clCreateSampler(cl_context context ,
cl_bool normalized_coords ,
cl_addressing_mode addressing_mode ,
cl_filter_mode filter_mode ,
cl_int * errcode_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clRetainSampler(cl_sampler sampler ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clReleaseSampler(cl_sampler sampler ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clGetSamplerInfo(cl_sampler sampler ,
cl_sampler_info param_name ,
size_t param_value_size ,
void * param_value ,
size_t * param_value_size_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_program CL_API_CALL
clCreateProgramWithSource(cl_context context ,
cl_uint count ,
const char ** strings ,
const size_t * lengths ,
cl_int * errcode_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_program CL_API_CALL
clCreateProgramWithBinary(cl_context context ,
cl_uint num_devices ,
const cl_device_id * device_list ,
const size_t * lengths ,
const unsigned char ** binaries ,
cl_int * binary_status ,
cl_int * errcode_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_program CL_API_CALL
clCreateProgramWithBuiltInKernels(cl_context context ,
cl_uint num_devices ,
const cl_device_id * device_list ,
const char * kernel_names ,
cl_int * errcode_ret ) CL_API_SUFFIX__VERSION_1_2
{}
CL_API_ENTRY cl_int CL_API_CALL
clRetainProgram(cl_program program ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clReleaseProgram(cl_program program ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clBuildProgram(cl_program program ,
cl_uint num_devices ,
const cl_device_id * device_list ,
const char * options ,
void (CL_CALLBACK * pfn_notify )(cl_program /* program */, void * /* user_data */),
void * user_data ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clCompileProgram(cl_program program ,
cl_uint num_devices ,
const cl_device_id * device_list ,
const char * options ,
cl_uint num_input_headers ,
const cl_program * input_headers ,
const char ** header_include_names ,
void (CL_CALLBACK * pfn_notify )(cl_program /* program */, void * /* user_data */),
void * user_data ) CL_API_SUFFIX__VERSION_1_2
{}
CL_API_ENTRY cl_program CL_API_CALL
clLinkProgram(cl_context context ,
cl_uint num_devices ,
const cl_device_id * device_list ,
const char * options ,
cl_uint num_input_programs ,
const cl_program * input_programs ,
void (CL_CALLBACK * pfn_notify )(cl_program /* program */, void * /* user_data */),
void * user_data ,
cl_int * errcode_ret ) CL_API_SUFFIX__VERSION_1_2
{}
CL_API_ENTRY cl_int CL_API_CALL
clUnloadPlatformCompiler(cl_platform_id platform ) CL_API_SUFFIX__VERSION_1_2
{}
CL_API_ENTRY cl_int CL_API_CALL
clGetProgramInfo(cl_program program ,
cl_program_info param_name ,
size_t param_value_size ,
void * param_value ,
size_t * param_value_size_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clGetProgramBuildInfo(cl_program program ,
cl_device_id device ,
cl_program_build_info param_name ,
size_t param_value_size ,
void * param_value ,
size_t * param_value_size_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_kernel CL_API_CALL
clCreateKernel(cl_program program ,
const char * kernel_name ,
cl_int * errcode_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clCreateKernelsInProgram(cl_program program ,
cl_uint num_kernels ,
cl_kernel * kernels ,
cl_uint * num_kernels_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clRetainKernel(cl_kernel kernel ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clReleaseKernel(cl_kernel kernel ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clSetKernelArg(cl_kernel kernel ,
cl_uint arg_index ,
size_t arg_size ,
const void * arg_value ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clGetKernelInfo(cl_kernel kernel ,
cl_kernel_info param_name ,
size_t param_value_size ,
void * param_value ,
size_t * param_value_size_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clGetKernelArgInfo(cl_kernel kernel ,
cl_uint arg_indx ,
cl_kernel_arg_info param_name ,
size_t param_value_size ,
void * param_value ,
size_t * param_value_size_ret ) CL_API_SUFFIX__VERSION_1_2
{}
CL_API_ENTRY cl_int CL_API_CALL
clGetKernelWorkGroupInfo(cl_kernel kernel ,
cl_device_id device ,
cl_kernel_work_group_info param_name ,
size_t param_value_size ,
void * param_value ,
size_t * param_value_size_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clWaitForEvents(cl_uint num_events ,
const cl_event * event_list ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clGetEventInfo(cl_event event ,
cl_event_info param_name ,
size_t param_value_size ,
void * param_value ,
size_t * param_value_size_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_event CL_API_CALL
clCreateUserEvent(cl_context context ,
cl_int * errcode_ret ) CL_API_SUFFIX__VERSION_1_1;
extern CL_API_ENTRY cl_int CL_API_CALL
clRetainEvent(cl_event event ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clReleaseEvent(cl_event event ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clSetUserEventStatus(cl_event event ,
cl_int execution_status ) CL_API_SUFFIX__VERSION_1_1
{}
CL_API_ENTRY cl_int CL_API_CALL
clSetEventCallback( cl_event event ,
cl_int command_exec_callback_type ,
void (CL_CALLBACK * pfn_notify )(cl_event, cl_int, void *),
void * user_data ) CL_API_SUFFIX__VERSION_1_1
{}
CL_API_ENTRY cl_int CL_API_CALL
clGetEventProfilingInfo(cl_event event ,
cl_profiling_info param_name ,
size_t param_value_size ,
void * param_value ,
size_t * param_value_size_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clFlush(cl_command_queue command_queue ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clFinish(cl_command_queue command_queue ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clEnqueueReadBuffer(cl_command_queue command_queue ,
cl_mem buffer ,
cl_bool blocking_read ,
size_t offset ,
size_t size ,
void * ptr ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clEnqueueReadBufferRect(cl_command_queue command_queue ,
cl_mem buffer ,
cl_bool blocking_read ,
const size_t * buffer_offset ,
const size_t * host_offset ,
const size_t * region ,
size_t buffer_row_pitch ,
size_t buffer_slice_pitch ,
size_t host_row_pitch ,
size_t host_slice_pitch ,
void * ptr ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ) CL_API_SUFFIX__VERSION_1_1
{}
CL_API_ENTRY cl_int CL_API_CALL
clEnqueueWriteBuffer(cl_command_queue command_queue ,
cl_mem buffer ,
cl_bool blocking_write ,
size_t offset ,
size_t size ,
const void * ptr ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clEnqueueWriteBufferRect(cl_command_queue command_queue ,
cl_mem buffer ,
cl_bool blocking_write ,
const size_t * buffer_offset ,
const size_t * host_offset ,
const size_t * region ,
size_t buffer_row_pitch ,
size_t buffer_slice_pitch ,
size_t host_row_pitch ,
size_t host_slice_pitch ,
const void * ptr ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ) CL_API_SUFFIX__VERSION_1_1
{}
CL_API_ENTRY cl_int CL_API_CALL
clEnqueueFillBuffer(cl_command_queue command_queue ,
cl_mem buffer ,
const void * pattern ,
size_t pattern_size ,
size_t offset ,
size_t size ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ) CL_API_SUFFIX__VERSION_1_2
{}
CL_API_ENTRY cl_int CL_API_CALL
clEnqueueCopyBuffer(cl_command_queue command_queue ,
cl_mem src_buffer ,
cl_mem dst_buffer ,
size_t src_offset ,
size_t dst_offset ,
size_t size ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clEnqueueCopyBufferRect(cl_command_queue command_queue ,
cl_mem src_buffer ,
cl_mem dst_buffer ,
const size_t * src_origin ,
const size_t * dst_origin ,
const size_t * region ,
size_t src_row_pitch ,
size_t src_slice_pitch ,
size_t dst_row_pitch ,
size_t dst_slice_pitch ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ) CL_API_SUFFIX__VERSION_1_1
{}
CL_API_ENTRY cl_int CL_API_CALL
clEnqueueReadImage(cl_command_queue command_queue ,
cl_mem image ,
cl_bool blocking_read ,
const size_t * origin ,
const size_t * region ,
size_t row_pitch ,
size_t slice_pitch ,
void * ptr ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clEnqueueWriteImage(cl_command_queue command_queue ,
cl_mem image ,
cl_bool blocking_write ,
const size_t * origin ,
const size_t * region ,
size_t input_row_pitch ,
size_t input_slice_pitch ,
const void * ptr ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clEnqueueFillImage(cl_command_queue command_queue ,
cl_mem image ,
const void * fill_color ,
const size_t * origin ,
const size_t * region ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ) CL_API_SUFFIX__VERSION_1_2
{}
CL_API_ENTRY cl_int CL_API_CALL
clEnqueueCopyImage(cl_command_queue command_queue ,
cl_mem src_image ,
cl_mem dst_image ,
const size_t * src_origin ,
const size_t * dst_origin ,
const size_t * region ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clEnqueueCopyImageToBuffer(cl_command_queue command_queue ,
cl_mem src_image ,
cl_mem dst_buffer ,
const size_t * src_origin ,
const size_t * region ,
size_t dst_offset ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clEnqueueCopyBufferToImage(cl_command_queue command_queue ,
cl_mem src_buffer ,
cl_mem dst_image ,
size_t src_offset ,
const size_t * dst_origin ,
const size_t * region ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY void * CL_API_CALL
clEnqueueMapBuffer(cl_command_queue command_queue ,
cl_mem buffer ,
cl_bool blocking_map ,
cl_map_flags map_flags ,
size_t offset ,
size_t size ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ,
cl_int * errcode_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY void * CL_API_CALL
clEnqueueMapImage(cl_command_queue command_queue ,
cl_mem image ,
cl_bool blocking_map ,
cl_map_flags map_flags ,
const size_t * origin ,
const size_t * region ,
size_t * image_row_pitch ,
size_t * image_slice_pitch ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ,
cl_int * errcode_ret ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clEnqueueUnmapMemObject(cl_command_queue command_queue ,
cl_mem memobj ,
void * mapped_ptr ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clEnqueueMigrateMemObjects(cl_command_queue command_queue ,
cl_uint num_mem_objects ,
const cl_mem * mem_objects ,
cl_mem_migration_flags flags ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ) CL_API_SUFFIX__VERSION_1_2
{}
CL_API_ENTRY cl_int CL_API_CALL
clEnqueueNDRangeKernel(cl_command_queue command_queue ,
cl_kernel kernel ,
cl_uint work_dim ,
const size_t * global_work_offset ,
const size_t * global_work_size ,
const size_t * local_work_size ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clEnqueueTask(cl_command_queue command_queue ,
cl_kernel kernel ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clEnqueueNativeKernel(cl_command_queue command_queue ,
void (CL_CALLBACK * user_fun )(void *),
void * args ,
size_t cb_args ,
cl_uint num_mem_objects ,
const cl_mem * mem_list ,
const void ** args_mem_loc ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ) CL_API_SUFFIX__VERSION_1_0
{}
CL_API_ENTRY cl_int CL_API_CALL
clEnqueueMarkerWithWaitList(cl_command_queue command_queue ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ) CL_API_SUFFIX__VERSION_1_2
{}
CL_API_ENTRY cl_int CL_API_CALL
clEnqueueBarrierWithWaitList(cl_command_queue command_queue ,
cl_uint num_events_in_wait_list ,
const cl_event * event_wait_list ,
cl_event * event ) CL_API_SUFFIX__VERSION_1_2
{}
CL_API_ENTRY void * CL_API_CALL
clGetExtensionFunctionAddressForPlatform(cl_platform_id platform ,
const char * func_name ) CL_API_SUFFIX__VERSION_1_2
{}
|
the_stack_data/248581762.c | #include <yaml.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct fruit {
char *name;
char *color;
int count;
};
struct fruit data[] = {
{"apple", "red", 12},
{"orange", "orange", 3},
{"banana", "yellow", 4},
{"mango", "green", 1},
{NULL, NULL, 0}
};
int main(void)
{
yaml_emitter_t emitter;
yaml_event_t event;
struct fruit *f;
char buffer[64];
yaml_emitter_initialize(&emitter);
yaml_emitter_set_output_file(&emitter, stdout);
yaml_stream_start_event_initialize(&event, YAML_UTF8_ENCODING);
if (!yaml_emitter_emit(&emitter, &event)) goto error;
yaml_document_start_event_initialize(&event, NULL, NULL, NULL, 0);
if (!yaml_emitter_emit(&emitter, &event)) goto error;
yaml_mapping_start_event_initialize(&event, NULL, (yaml_char_t *)YAML_MAP_TAG,
1, YAML_ANY_MAPPING_STYLE);
if (!yaml_emitter_emit(&emitter, &event)) goto error;
yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *)"fruit", strlen("fruit"), 1, 0, YAML_PLAIN_SCALAR_STYLE);
if (!yaml_emitter_emit(&emitter, &event)) goto error;
yaml_sequence_start_event_initialize(&event, NULL, (yaml_char_t *)YAML_SEQ_TAG,
1, YAML_ANY_SEQUENCE_STYLE);
if (!yaml_emitter_emit(&emitter, &event)) goto error;
for (f = data; f->name; f++) {
yaml_mapping_start_event_initialize(&event, NULL, (yaml_char_t *)YAML_MAP_TAG,
1, YAML_ANY_MAPPING_STYLE);
if (!yaml_emitter_emit(&emitter, &event)) goto error;
yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *)"name", strlen("name"), 1, 0, YAML_PLAIN_SCALAR_STYLE);
if (!yaml_emitter_emit(&emitter, &event)) goto error;
yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *)f->name, strlen(f->name), 1, 0, YAML_PLAIN_SCALAR_STYLE);
if (!yaml_emitter_emit(&emitter, &event)) goto error;
yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *)"color", strlen("color"), 1, 0, YAML_PLAIN_SCALAR_STYLE);
if (!yaml_emitter_emit(&emitter, &event)) goto error;
yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *)f->color, strlen(f->color), 1, 0, YAML_PLAIN_SCALAR_STYLE);
if (!yaml_emitter_emit(&emitter, &event)) goto error;
yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *)"count", strlen("count"), 1, 0, YAML_PLAIN_SCALAR_STYLE);
if (!yaml_emitter_emit(&emitter, &event)) goto error;
sprintf(buffer, "%d", f->count);
yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_INT_TAG,
(yaml_char_t *)buffer, strlen(buffer), 1, 0, YAML_PLAIN_SCALAR_STYLE);
if (!yaml_emitter_emit(&emitter, &event)) goto error;
yaml_mapping_end_event_initialize(&event);
if (!yaml_emitter_emit(&emitter, &event)) goto error;
}
yaml_sequence_end_event_initialize(&event);
if (!yaml_emitter_emit(&emitter, &event)) goto error;
yaml_mapping_end_event_initialize(&event);
if (!yaml_emitter_emit(&emitter, &event)) goto error;
yaml_document_end_event_initialize(&event, 0);
if (!yaml_emitter_emit(&emitter, &event)) goto error;
yaml_stream_end_event_initialize(&event);
if (!yaml_emitter_emit(&emitter, &event)) goto error;
yaml_emitter_delete(&emitter);
return 0;
error:
fprintf(stderr, "Failed to emit event %d: %s\n", event.type, emitter.problem);
yaml_emitter_delete(&emitter);
return 1;
}
|
the_stack_data/130768.c | #include <math.h>
#include <stdio.h>
#include <ctype.h>
/* Copyright 2021 Melwyn Francis Carlo */
int main()
{
FILE *fp;
char* filename = "problems/042/p042_words.txt";
fp = fopen(filename, "r");
char ch;
int count = 0;
int index = -1;
int word_val = 0;
int is_incremented = 0;
fseek(fp, 1, SEEK_SET);
while((ch = fgetc(fp)) != EOF)
{
if (isalpha(ch))
{
is_incremented = 0;
word_val += ch - 64;
index++;
}
else
{
if (!is_incremented)
{
index = 0;
is_incremented = 1;
float sqrt_term = sqrt(1 + (8 * word_val));
word_val = 0;
if (sqrt_term != (int)sqrt_term)
continue;
float n_term = (sqrt_term - 1) / 2;
if (n_term != (int)n_term)
continue;
count++;
}
}
}
fclose(fp);
printf("%d\n", count);
return 0;
}
|
the_stack_data/7949624.c | #include <stdio.h>
#define MAX 8
int main(void) {
char hex[MAX + 1];
printf("Upisite niz > ");
fgets(hex, MAX + 1, stdin);
printf("Niz: %s\n", hex);
int i;
for (i = 0; i <= MAX; i++) {
if (!((hex[i] >= '0' && hex[i] <= '9') ||
(hex[i] >= 'A' && hex[i] <= 'Z'))) {
break;
}
}
int dekadski;
if (hex[i] !=
((hex[i] >= '0' && hex[i] <= '9') || (hex[i] >= 'A' && hex[i] <= 'Z'))) {
printf("Neispravan znak %c na poziciji %d", hex[i], i + 1);
} else {
for (i = 0; i <= MAX; i++) {
if (hex[i] >= '0' && hex[i] <= '9') {
dekadski = dekadski * 16 + hex[i] - '0';
} else {
dekadski = dekadski * 16 + hex[i] - 'A' + 10;
}
}
printf("Dekadski: %u", dekadski);
}
return 0;
} |
the_stack_data/40762211.c | #include <stdio.h>
#include <stdlib.h>
struct Aresta {
int origem, destino;
};
typedef struct Aresta aresta;
struct Grafo {
int V; // Numero de vertices
int E; // Numero de arestas
// O grafo eh representado por um vetor de arestas
aresta* VetorDeArestas;
};
typedef struct Grafo grafo;
grafo* criarGrafo(int V, int E) {
grafo* g = (grafo*) malloc( sizeof(grafo) );
g->V = V;
g->E = E;
g->VetorDeArestas = (aresta*) malloc(g->E * sizeof(aresta) );
return g;
}
// Funcao que procura o representante do elemento i
int Find_Set(int pai[], int i) {
if (pai[i] == i)
return i;
return Find_Set(pai, pai[i]);
}
// Funcao que junta os conjuntos de x e y.
void Union(int pai[], int x, int y) {
int rx = Find_Set(pai, x);
int ry = Find_Set(pai, y);
pai[rx] = ry;
}
// Funcao utilizada para verificar se o grafo tem ou nao ciclo
int temCiclo( grafo* g ) {
int i, j;
int pai[g->V];
for (i=0; i<g->V; i++)
pai[i] = i;
for(j=0; j<g->E; j++) {
int rx = Find_Set(pai, g->VetorDeArestas[j].origem);
int ry = Find_Set(pai, g->VetorDeArestas[j].destino);
if (rx==ry)
return 1;
Union(pai, rx, ry);
}
return 0;
}
int main()
{
int nV, nE, k;
scanf("%d", &nV);
scanf("%d", &nE);
grafo* g = criarGrafo(nV, nE);
for(k=0; k<g->E; k++) {
int p, q;
scanf("%d", &p);
scanf("%d", &q);
g->VetorDeArestas[k].origem = p;
g->VetorDeArestas[k].destino = q;
}
if (temCiclo(g))
printf("\nGrafo contem ciclo\n");
else
printf("\nGrafo nao contem ciclo\n");
}
|
the_stack_data/39151.c | /*
* Copyright (C) 2003 - 2006 Tomasz Kojm <[email protected]>
*
* Number encoding rutines are based on yyyRSA by Erik Thiele
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif
#ifdef HAVE_GMP
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <gmp.h>
#include "clamav.h"
#include "others.h"
#include "dsig.h"
#include "str.h"
#define CLI_NSTR "118640995551645342603070001658453189751527774412027743746599405743243142607464144767361060640655844749760788890022283424922762488917565551002467771109669598189410434699034532232228621591089508178591428456220796841621637175567590476666928698770143328137383952820383197532047771780196576957695822641224262693037"
#define CLI_ESTR "100001027"
static unsigned char cli_ndecode(unsigned char value)
{
unsigned int i;
char ncodec[] = {
'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',
'+', '/'
};
for(i = 0; i < 64; i++)
if(ncodec[i] == value)
return i;
cli_errmsg("cli_ndecode: value out of range\n");
return -1;
}
unsigned char *cli_decodesig(const char *sig, unsigned int plen, mpz_t e, mpz_t n)
{
int i, slen = strlen(sig), dec;
unsigned char *plain;
mpz_t r, p, c;
mpz_init(r);
mpz_init(c);
for(i = 0; i < slen; i++) {
if((dec = cli_ndecode(sig[i])) < 0) {
mpz_clear(r);
mpz_clear(c);
return NULL;
}
mpz_set_ui(r, dec);
mpz_mul_2exp(r, r, 6 * i);
mpz_add(c, c, r);
}
plain = (unsigned char *) cli_calloc(plen + 1, sizeof(unsigned char));
if(!plain) {
cli_errmsg("cli_decodesig: Can't allocate memory for 'plain'\n");
mpz_clear(r);
mpz_clear(c);
return NULL;
}
mpz_init(p);
mpz_powm(p, c, e, n); /* plain = cipher^e mod n */
mpz_clear(c);
for(i = plen - 1; i >= 0; i--) { /* reverse */
mpz_tdiv_qr_ui(p, r, p, 256);
plain[i] = mpz_get_ui(r);
}
mpz_clear(p);
mpz_clear(r);
return plain;
}
int cli_versig(const char *md5, const char *dsig)
{
mpz_t n, e;
char *pt, *pt2;
if(strlen(md5) != 32 || !isalnum(md5[0])) {
/* someone is trying to fool us with empty/malformed MD5 ? */
cli_errmsg("SECURITY WARNING: MD5 basic test failure.\n");
return CL_EMD5;
}
mpz_init_set_str(n, CLI_NSTR, 10);
mpz_init_set_str(e, CLI_ESTR, 10);
if(!(pt = (char *) cli_decodesig(dsig, 16, e, n))) {
mpz_clear(n);
mpz_clear(e);
return CL_EDSIG;
}
pt2 = cli_str2hex(pt, 16);
free(pt);
cli_dbgmsg("cli_versig: Decoded signature: %s\n", pt2);
if(strncmp(md5, pt2, 32)) {
cli_dbgmsg("cli_versig: Signature doesn't match.\n");
free(pt2);
mpz_clear(n);
mpz_clear(e);
return CL_EDSIG;
}
free(pt2);
mpz_clear(n);
mpz_clear(e);
cli_dbgmsg("cli_versig: Digital signature is correct.\n");
return CL_SUCCESS;
}
#endif
|
the_stack_data/96913.c | /* Extract X.509 certificate in DER form from PKCS#11 or PEM.
*
* Copyright © 2014-2015 Red Hat, Inc. All Rights Reserved.
* Copyright © 2015 Intel Corporation.
*
* Authors: David Howells <[email protected]>
* David Woodhouse <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the licence, or (at your option) any later version.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <err.h>
#include <openssl/bio.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/engine.h>
#define PKEY_ID_PKCS7 2
static __attribute__((noreturn))
void format(void)
{
fprintf(stderr,
"Usage: scripts/extract-cert <source> <dest>\n");
exit(2);
}
static void display_openssl_errors(int l)
{
const char *file;
char buf[120];
int e, line;
if (ERR_peek_error() == 0)
return;
fprintf(stderr, "At main.c:%d:\n", l);
while ((e = ERR_get_error_line(&file, &line))) {
ERR_error_string(e, buf);
fprintf(stderr, "- SSL %s: %s:%d\n", buf, file, line);
}
}
static void drain_openssl_errors(void)
{
const char *file;
int line;
if (ERR_peek_error() == 0)
return;
while (ERR_get_error_line(&file, &line)) {}
}
#define ERR(cond, fmt, ...) \
do { \
bool __cond = (cond); \
display_openssl_errors(__LINE__); \
if (__cond) { \
err(1, fmt, ## __VA_ARGS__); \
} \
} while(0)
static const char *key_pass;
static BIO *wb;
static char *cert_dst;
int kbuild_verbose;
static void write_cert(X509 *x509)
{
char buf[200];
if (!wb) {
wb = BIO_new_file(cert_dst, "wb");
ERR(!wb, "%s", cert_dst);
}
X509_NAME_oneline(X509_get_subject_name(x509), buf, sizeof(buf));
ERR(!i2d_X509_bio(wb, x509), "%s", cert_dst);
if (kbuild_verbose)
fprintf(stderr, "Extracted cert: %s\n", buf);
}
int main(int argc, char **argv)
{
char *cert_src;
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
ERR_clear_error();
kbuild_verbose = atoi(getenv("KBUILD_VERBOSE")?:"0");
key_pass = getenv("KBUILD_SIGN_PIN");
if (argc != 3)
format();
cert_src = argv[1];
cert_dst = argv[2];
if (!cert_src[0]) {
/* Invoked with no input; create empty file */
FILE *f = fopen(cert_dst, "wb");
ERR(!f, "%s", cert_dst);
fclose(f);
exit(0);
} else if (!strncmp(cert_src, "pkcs11:", 7)) {
ENGINE *e;
struct {
const char *cert_id;
X509 *cert;
} parms;
parms.cert_id = cert_src;
parms.cert = NULL;
ENGINE_load_builtin_engines();
drain_openssl_errors();
e = ENGINE_by_id("pkcs11");
ERR(!e, "Load PKCS#11 ENGINE");
if (ENGINE_init(e))
drain_openssl_errors();
else
ERR(1, "ENGINE_init");
if (key_pass)
ERR(!ENGINE_ctrl_cmd_string(e, "PIN", key_pass, 0), "Set PKCS#11 PIN");
ENGINE_ctrl_cmd(e, "LOAD_CERT_CTRL", 0, &parms, NULL, 1);
ERR(!parms.cert, "Get X.509 from PKCS#11");
write_cert(parms.cert);
} else {
BIO *b;
X509 *x509;
b = BIO_new_file(cert_src, "rb");
ERR(!b, "%s", cert_src);
while (1) {
x509 = PEM_read_bio_X509(b, NULL, NULL, NULL);
if (wb && !x509) {
unsigned long err = ERR_peek_last_error();
if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
ERR_clear_error();
break;
}
}
ERR(!x509, "%s", cert_src);
write_cert(x509);
}
}
BIO_free(wb);
return 0;
}
|
the_stack_data/40763199.c |
/* A trivial test case we will use to generate data16. */
int testfunction(void)
{
int ivar = 12;
long lvar = -3;
return ivar + lvar;
}
|
the_stack_data/167331804.c | /**
* @file
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
return EXIT_SUCCESS;
}
|
the_stack_data/150140928.c | // Cálculo da razão áurea (phi)
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
void golden(double *phi, unsigned int *iter);
int main() {
double phi = 3;
unsigned int iter = 0;
golden(&phi, &iter);
printf("%u iterações: ϕ = %1.15f\n",iter,phi);
return EXIT_SUCCESS;
}
void golden(double *phi, unsigned int *iter) {
double tmp = -1;
while (fabs(*phi - tmp) > DBL_EPSILON) {
tmp = *phi;
*phi = sqrt(*phi + 1);
(*iter)++;
}
}
|
the_stack_data/179830043.c | /* Copyright 2012 The Emscripten Authors. All rights reserved.
* Emscripten is available under two separate licenses, the MIT license and the
* University of Illinois/NCSA Open Source License. Both these licenses can be
* found in the LICENSE file.
*/
#include <stdio.h>
int main() {
FILE* file = fopen("tests/hello_world_file.txt", "rb");
if (!file) {
printf("cannot open file\n");
return 1;
}
while (!feof(file)) {
char c = fgetc(file);
if (c != EOF) {
putchar(c);
}
}
fclose(file);
return 0;
}
|
the_stack_data/74106.c | #include <stdio.h>
void lonesome_cowboy()
{
int i,j,n=12;
int a[n][n];
for(i=0;i<n;i++)
for(j=0;j<n;j++)
a[i][j]=0;
for(i=1;i<n-1;i++)
isolate:
for(j=1;j<n;j++)
{
if(j<10&&j>=2) a[i][j]=1;
}
/* compute trace */
for(i=0,j=0;i<n;i++)
j+=a[i][i];
printf("%d",j);
}
int main(int argv, char *argc[])
{
lonesome_cowboy();
return 0;
}
|
the_stack_data/947358.c | #include <stdio.h>
#include <unistd.h>
int main(){
printf("sension id of A %d " ,getsid(0));
return 0;
}
|
the_stack_data/53640.c | #include <stdio.h>
int ft_str_is_lowercase(char *str);
int main(void)
{
char str1[] = "asd";
printf("%d\n", ft_str_is_lowercase(str1));
char str2[] = "aTsd";
printf("%d\n", ft_str_is_lowercase(str2));
char str3[] = "";
printf("%d\n", ft_str_is_lowercase(str3));
return (0);
}
|
the_stack_data/87636867.c | int x;
long y;
extern unsigned long foo (int x);
extern int main ();
unsigned long foo (int x) {
unsigned long i;
i = (unsigned long) x;
return (x);
}
main ()
{
int i;
switch (i) {
case 2: foo (i); break;
case 3: foo (i); break;
case 5: foo (i); break;
case 7: foo (i); break;
default: foo (i*2);
}
}
|
the_stack_data/68889144.c | #include <stdio.h>
int main() {
printf("Hello C!\n\a\a\a\a\a\a");
return 0;
}
|
the_stack_data/94440.c | #include <stdio.h>
int main()
{
int n, m;
double s = 0.0;
scanf("%d%d", &n, &m);
for (int i = n; i <= m; i++)
{
s += (double)1 / i / i;
}
printf("%.5lf\n", s);
return 0;
}
|
the_stack_data/161081002.c | #include <stdio.h>
#include <stdlib.h>
int* preecheMatriz(int n);
int* preecheMatriz(int n){
int* p = malloc(sizeof(int) * n * n), l = 0, c = 0;
for(int x = 0; x < n * n; x++){
if(c == n){
l += 1;
c = 0;
}
if(l == c){
*(p + x) = 0;
}else if(l > c){
*(p + x) = -1;
}else{
*(p + x) = 1;
}
c += 1;
}
return p;
}
int main(int argc, char const *argv[]){
int n, *prtMatriz = NULL;
scanf("%d", &n);
prtMatriz = preecheMatriz(n);
for(int x = 0; x < n * n; x++){
printf("%d ", *(prtMatriz + x));
if((x + 1) % n == 0){
printf("\n");
}
}
return 0;
} |
the_stack_data/655772.c | const int r=33;
void f(void){
return;
}
int main(void) {
char a = 6;
const char o=a;
const char e=o;
char t;
int s=3;
{
int a = 5;
int y = e + 1; // 6
const int v=666;
s = y + 1; // 7
}
s = a + 1; // 4
return 0;
} |
the_stack_data/851261.c | #include <stdio.h>
#define SPACE ' '
int main(void) {
char ch;;
while ((ch = getchar()) != '\n') {
printf("%d \n", ch);
if (SPACE == ch) {
putchar(ch);
} else {
putchar(ch + 1);
}
}
putchar(ch);
return 0;
} |
the_stack_data/67324559.c | /*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2013 Intel Corporation. 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. Redistributions
in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution. Neither the name of
the Intel Corporation nor the names of its contributors may be used to
endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR
ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
END_LEGAL */
// This little application is used to test calling application functions.
//
#include <stdio.h>
#if defined (TARGET_WINDOWS)
#define EXPORT_SYM __declspec( dllexport )
#else
#define EXPORT_SYM extern
#include <stdlib.h>
#endif
EXPORT_SYM long Original1( long param1, long param2 );
EXPORT_SYM long Original2( long param1, long param2 );
int main()
{
long res;
int i;
for (i=0; i<10; i++)
{
res = Original1(3, 4);
}
if ((unsigned int)res != (unsigned int)9207)
{
printf ("***ERROR res %ld is unexpected\n", res);
exit (-1);
}
return 0;
}
|
the_stack_data/117329450.c | #include <stdio.h>
#include <unistd.h>
int main(){
int duration = 15 * 1000 * 1000;
printf("usleep(%d)\n", duration);
usleep(duration);
return 0;
}
|
the_stack_data/165769167.c | #include <stdio.h>
#include <stdlib.h>
struct {
unsigned int
i : 4; // 0 to 15 : used value 1 to 11
} cpt; // compteur
int main(void)
{
printf("Table de multiplication de 7\n");
for (cpt.i=1;cpt.i<11;cpt.i++)
printf("7 x %d = %d\n",cpt.i,cpt.i*7);
return EXIT_SUCCESS;
}
|
the_stack_data/26700123.c | #include<stdio.h>
int main()
{
int queue[20],n,head,i,j,k,seek=0,max,diff;
float avg;
printf("Enter the max range of disk\n");
scanf("%d",&max);
printf("Enter the size of queue request\n");
scanf("%d",&n);
printf("Enter the queue of disk positions to be read\n");
for(i=1;i<=n;i++)
scanf("%d",&queue[i]);
printf("Enter the initial head position\n");
scanf("%d",&head);
queue[0]=head;
for(j=0;j<=n-1;j++)
{
diff=abs(queue[j+1]-queue[j]);
seek+=diff;
printf("Disk head moves from %d to %d with seek %d\n",queue[j],queue[j+1],diff);
}
printf("Total seek time is %d\n",seek);
return 0;
}
|
the_stack_data/45450890.c | /*Reverse the word of String without using string function*/
#include<stdio.h>
int length(char *a)
{
int i;
for(i = 0;a[i];i++);
return i;
}
char *Reverse(char *a)
{
int i,j;
char t;
for(i = 0,j = length(a)-1;i<j;i++,j--)
{
t = a[i];
a[i] = a[j];
a[j] = t;
}
return a;
}
char *wordReverse(char *s)
{
int i,j,k;
char temp;
for(i = 0,j = 0,k = 0;s[i];i++)
{
if(s[i] ==' '||s[i+1] =='\0')
{
for(k=(s[i]==' '?i-1:i);j<k;j++,k--)
{
temp = s[j];
s[j] = s[k];
s[k] = temp;
}
j = i+1;
}
}
return s;
}
int main()
{
char str[] = "how are you";
printf("%s",wordReverse(Reverse(str)));
}
|
the_stack_data/145135.c | /* f2c.h -- Standard Fortran to C header file */
/** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed."
- From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */
#ifndef F2C_INCLUDE
#define F2C_INCLUDE
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <complex.h>
#ifdef complex
#undef complex
#endif
#ifdef I
#undef I
#endif
#if defined(_WIN64)
typedef long long BLASLONG;
typedef unsigned long long BLASULONG;
#else
typedef long BLASLONG;
typedef unsigned long BLASULONG;
#endif
#ifdef LAPACK_ILP64
typedef BLASLONG blasint;
#if defined(_WIN64)
#define blasabs(x) llabs(x)
#else
#define blasabs(x) labs(x)
#endif
#else
typedef int blasint;
#define blasabs(x) abs(x)
#endif
typedef blasint integer;
typedef unsigned int uinteger;
typedef char *address;
typedef short int shortint;
typedef float real;
typedef double doublereal;
typedef struct { real r, i; } complex;
typedef struct { doublereal r, i; } doublecomplex;
static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;}
static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;}
#define pCf(z) (*_pCf(z))
#define pCd(z) (*_pCd(z))
typedef int logical;
typedef short int shortlogical;
typedef char logical1;
typedef char integer1;
#define TRUE_ (1)
#define FALSE_ (0)
/* Extern is for use with -E */
#ifndef Extern
#define Extern extern
#endif
/* I/O stuff */
typedef int flag;
typedef int ftnlen;
typedef int ftnint;
/*external read, write*/
typedef struct
{ flag cierr;
ftnint ciunit;
flag ciend;
char *cifmt;
ftnint cirec;
} cilist;
/*internal read, write*/
typedef struct
{ flag icierr;
char *iciunit;
flag iciend;
char *icifmt;
ftnint icirlen;
ftnint icirnum;
} icilist;
/*open*/
typedef struct
{ flag oerr;
ftnint ounit;
char *ofnm;
ftnlen ofnmlen;
char *osta;
char *oacc;
char *ofm;
ftnint orl;
char *oblnk;
} olist;
/*close*/
typedef struct
{ flag cerr;
ftnint cunit;
char *csta;
} cllist;
/*rewind, backspace, endfile*/
typedef struct
{ flag aerr;
ftnint aunit;
} alist;
/* inquire */
typedef struct
{ flag inerr;
ftnint inunit;
char *infile;
ftnlen infilen;
ftnint *inex; /*parameters in standard's order*/
ftnint *inopen;
ftnint *innum;
ftnint *innamed;
char *inname;
ftnlen innamlen;
char *inacc;
ftnlen inacclen;
char *inseq;
ftnlen inseqlen;
char *indir;
ftnlen indirlen;
char *infmt;
ftnlen infmtlen;
char *inform;
ftnint informlen;
char *inunf;
ftnlen inunflen;
ftnint *inrecl;
ftnint *innrec;
char *inblank;
ftnlen inblanklen;
} inlist;
#define VOID void
union Multitype { /* for multiple entry points */
integer1 g;
shortint h;
integer i;
/* longint j; */
real r;
doublereal d;
complex c;
doublecomplex z;
};
typedef union Multitype Multitype;
struct Vardesc { /* for Namelist */
char *name;
char *addr;
ftnlen *dims;
int type;
};
typedef struct Vardesc Vardesc;
struct Namelist {
char *name;
Vardesc **vars;
int nvars;
};
typedef struct Namelist Namelist;
#define abs(x) ((x) >= 0 ? (x) : -(x))
#define dabs(x) (fabs(x))
#define f2cmin(a,b) ((a) <= (b) ? (a) : (b))
#define f2cmax(a,b) ((a) >= (b) ? (a) : (b))
#define dmin(a,b) (f2cmin(a,b))
#define dmax(a,b) (f2cmax(a,b))
#define bit_test(a,b) ((a) >> (b) & 1)
#define bit_clear(a,b) ((a) & ~((uinteger)1 << (b)))
#define bit_set(a,b) ((a) | ((uinteger)1 << (b)))
#define abort_() { sig_die("Fortran abort routine called", 1); }
#define c_abs(z) (cabsf(Cf(z)))
#define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); }
#define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);}
#define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);}
#define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));}
#define c_log(R, Z) {pCf(R) = clogf(Cf(Z));}
#define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));}
//#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));}
#define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));}
#define d_abs(x) (fabs(*(x)))
#define d_acos(x) (acos(*(x)))
#define d_asin(x) (asin(*(x)))
#define d_atan(x) (atan(*(x)))
#define d_atn2(x, y) (atan2(*(x),*(y)))
#define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); }
#define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); }
#define d_cos(x) (cos(*(x)))
#define d_cosh(x) (cosh(*(x)))
#define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 )
#define d_exp(x) (exp(*(x)))
#define d_imag(z) (cimag(Cd(z)))
#define r_imag(z) (cimag(Cf(z)))
#define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define d_log(x) (log(*(x)))
#define d_mod(x, y) (fmod(*(x), *(y)))
#define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x)))
#define d_nint(x) u_nint(*(x))
#define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a)))
#define d_sign(a,b) u_sign(*(a),*(b))
#define r_sign(a,b) u_sign(*(a),*(b))
#define d_sin(x) (sin(*(x)))
#define d_sinh(x) (sinh(*(x)))
#define d_sqrt(x) (sqrt(*(x)))
#define d_tan(x) (tan(*(x)))
#define d_tanh(x) (tanh(*(x)))
#define i_abs(x) abs(*(x))
#define i_dnnt(x) ((integer)u_nint(*(x)))
#define i_len(s, n) (n)
#define i_nint(x) ((integer)u_nint(*(x)))
#define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b)))
#define pow_dd(ap, bp) ( pow(*(ap), *(bp)))
#define pow_si(B,E) spow_ui(*(B),*(E))
#define pow_ri(B,E) spow_ui(*(B),*(E))
#define pow_di(B,E) dpow_ui(*(B),*(E))
#define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));}
#define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));}
#define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));}
#define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; }
#define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d))))
#define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; }
#define sig_die(s, kill) { exit(1); }
#define s_stop(s, n) {exit(0);}
static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n";
#define z_abs(z) (cabs(Cd(z)))
#define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));}
#define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));}
#define myexit_() break;
#define mycycle() continue;
#define myceiling(w) {ceil(w)}
#define myhuge(w) {HUGE_VAL}
//#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);}
#define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)}
/* procedure parameter types for -A and -C++ */
#define F2C_proc_par_types 1
#ifdef __cplusplus
typedef logical (*L_fp)(...);
#else
typedef logical (*L_fp)();
#endif
static float spow_ui(float x, integer n) {
float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static double dpow_ui(double x, integer n) {
double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static _Complex float cpow_ui(_Complex float x, integer n) {
_Complex float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static _Complex double zpow_ui(_Complex double x, integer n) {
_Complex double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer pow_ii(integer x, integer n) {
integer pow; unsigned long int u;
if (n <= 0) {
if (n == 0 || x == 1) pow = 1;
else if (x != -1) pow = x == 0 ? 1/x : 0;
else n = -n;
}
if ((n > 0) || !(n == 0 || x == 1 || x != -1)) {
u = n;
for(pow = 1; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer dmaxloc_(double *w, integer s, integer e, integer *n)
{
double m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static integer smaxloc_(float *w, integer s, integer e, integer *n)
{
float m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i])) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i])) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i]) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i]) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
/* -- translated by f2c (version 20000121).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
/* > \brief \b CLAGS2 */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download CLAGS2 + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/clags2.
f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/clags2.
f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/clags2.
f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE CLAGS2( UPPER, A1, A2, A3, B1, B2, B3, CSU, SNU, CSV, */
/* SNV, CSQ, SNQ ) */
/* LOGICAL UPPER */
/* REAL A1, A3, B1, B3, CSQ, CSU, CSV */
/* COMPLEX A2, B2, SNQ, SNU, SNV */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > CLAGS2 computes 2-by-2 unitary matrices U, V and Q, such */
/* > that if ( UPPER ) then */
/* > */
/* > U**H *A*Q = U**H *( A1 A2 )*Q = ( x 0 ) */
/* > ( 0 A3 ) ( x x ) */
/* > and */
/* > V**H*B*Q = V**H *( B1 B2 )*Q = ( x 0 ) */
/* > ( 0 B3 ) ( x x ) */
/* > */
/* > or if ( .NOT.UPPER ) then */
/* > */
/* > U**H *A*Q = U**H *( A1 0 )*Q = ( x x ) */
/* > ( A2 A3 ) ( 0 x ) */
/* > and */
/* > V**H *B*Q = V**H *( B1 0 )*Q = ( x x ) */
/* > ( B2 B3 ) ( 0 x ) */
/* > where */
/* > */
/* > U = ( CSU SNU ), V = ( CSV SNV ), */
/* > ( -SNU**H CSU ) ( -SNV**H CSV ) */
/* > */
/* > Q = ( CSQ SNQ ) */
/* > ( -SNQ**H CSQ ) */
/* > */
/* > The rows of the transformed A and B are parallel. Moreover, if the */
/* > input 2-by-2 matrix A is not zero, then the transformed (1,1) entry */
/* > of A is not zero. If the input matrices A and B are both not zero, */
/* > then the transformed (2,2) element of B is not zero, except when the */
/* > first rows of input A and B are parallel and the second rows are */
/* > zero. */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] UPPER */
/* > \verbatim */
/* > UPPER is LOGICAL */
/* > = .TRUE.: the input matrices A and B are upper triangular. */
/* > = .FALSE.: the input matrices A and B are lower triangular. */
/* > \endverbatim */
/* > */
/* > \param[in] A1 */
/* > \verbatim */
/* > A1 is REAL */
/* > \endverbatim */
/* > */
/* > \param[in] A2 */
/* > \verbatim */
/* > A2 is COMPLEX */
/* > \endverbatim */
/* > */
/* > \param[in] A3 */
/* > \verbatim */
/* > A3 is REAL */
/* > On entry, A1, A2 and A3 are elements of the input 2-by-2 */
/* > upper (lower) triangular matrix A. */
/* > \endverbatim */
/* > */
/* > \param[in] B1 */
/* > \verbatim */
/* > B1 is REAL */
/* > \endverbatim */
/* > */
/* > \param[in] B2 */
/* > \verbatim */
/* > B2 is COMPLEX */
/* > \endverbatim */
/* > */
/* > \param[in] B3 */
/* > \verbatim */
/* > B3 is REAL */
/* > On entry, B1, B2 and B3 are elements of the input 2-by-2 */
/* > upper (lower) triangular matrix B. */
/* > \endverbatim */
/* > */
/* > \param[out] CSU */
/* > \verbatim */
/* > CSU is REAL */
/* > \endverbatim */
/* > */
/* > \param[out] SNU */
/* > \verbatim */
/* > SNU is COMPLEX */
/* > The desired unitary matrix U. */
/* > \endverbatim */
/* > */
/* > \param[out] CSV */
/* > \verbatim */
/* > CSV is REAL */
/* > \endverbatim */
/* > */
/* > \param[out] SNV */
/* > \verbatim */
/* > SNV is COMPLEX */
/* > The desired unitary matrix V. */
/* > \endverbatim */
/* > */
/* > \param[out] CSQ */
/* > \verbatim */
/* > CSQ is REAL */
/* > \endverbatim */
/* > */
/* > \param[out] SNQ */
/* > \verbatim */
/* > SNQ is COMPLEX */
/* > The desired unitary matrix Q. */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date December 2016 */
/* > \ingroup complexOTHERauxiliary */
/* ===================================================================== */
/* Subroutine */ int clags2_(logical *upper, real *a1, complex *a2, real *a3,
real *b1, complex *b2, real *b3, real *csu, complex *snu, real *csv,
complex *snv, real *csq, complex *snq)
{
/* System generated locals */
real r__1, r__2, r__3, r__4, r__5, r__6, r__7, r__8;
complex q__1, q__2, q__3, q__4, q__5;
/* Local variables */
real aua11, aua12, aua21, aua22, avb11, avb12, avb21, avb22, ua11r, ua22r,
vb11r, vb22r, a;
complex b, c__;
real d__;
complex r__, d1;
real s1, s2, fb, fc;
extern /* Subroutine */ int slasv2_(real *, real *, real *, real *, real *
, real *, real *, real *, real *), clartg_(complex *, complex *,
real *, complex *, complex *);
complex ua11, ua12, ua21, ua22, vb11, vb12, vb21, vb22;
real csl, csr, snl, snr;
/* -- LAPACK auxiliary routine (version 3.7.0) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* December 2016 */
/* ===================================================================== */
if (*upper) {
/* Input matrices A and B are upper triangular matrices */
/* Form matrix C = A*adj(B) = ( a b ) */
/* ( 0 d ) */
a = *a1 * *b3;
d__ = *a3 * *b1;
q__2.r = *b1 * a2->r, q__2.i = *b1 * a2->i;
q__3.r = *a1 * b2->r, q__3.i = *a1 * b2->i;
q__1.r = q__2.r - q__3.r, q__1.i = q__2.i - q__3.i;
b.r = q__1.r, b.i = q__1.i;
fb = c_abs(&b);
/* Transform complex 2-by-2 matrix C to real matrix by unitary */
/* diagonal matrix diag(1,D1). */
d1.r = 1.f, d1.i = 0.f;
if (fb != 0.f) {
q__1.r = b.r / fb, q__1.i = b.i / fb;
d1.r = q__1.r, d1.i = q__1.i;
}
/* The SVD of real 2 by 2 triangular C */
/* ( CSL -SNL )*( A B )*( CSR SNR ) = ( R 0 ) */
/* ( SNL CSL ) ( 0 D ) ( -SNR CSR ) ( 0 T ) */
slasv2_(&a, &fb, &d__, &s1, &s2, &snr, &csr, &snl, &csl);
if (abs(csl) >= abs(snl) || abs(csr) >= abs(snr)) {
/* Compute the (1,1) and (1,2) elements of U**H *A and V**H *B, */
/* and (1,2) element of |U|**H *|A| and |V|**H *|B|. */
ua11r = csl * *a1;
q__2.r = csl * a2->r, q__2.i = csl * a2->i;
q__4.r = snl * d1.r, q__4.i = snl * d1.i;
q__3.r = *a3 * q__4.r, q__3.i = *a3 * q__4.i;
q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i;
ua12.r = q__1.r, ua12.i = q__1.i;
vb11r = csr * *b1;
q__2.r = csr * b2->r, q__2.i = csr * b2->i;
q__4.r = snr * d1.r, q__4.i = snr * d1.i;
q__3.r = *b3 * q__4.r, q__3.i = *b3 * q__4.i;
q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i;
vb12.r = q__1.r, vb12.i = q__1.i;
aua12 = abs(csl) * ((r__1 = a2->r, abs(r__1)) + (r__2 = r_imag(a2)
, abs(r__2))) + abs(snl) * abs(*a3);
avb12 = abs(csr) * ((r__1 = b2->r, abs(r__1)) + (r__2 = r_imag(b2)
, abs(r__2))) + abs(snr) * abs(*b3);
/* zero (1,2) elements of U**H *A and V**H *B */
if (abs(ua11r) + ((r__1 = ua12.r, abs(r__1)) + (r__2 = r_imag(&
ua12), abs(r__2))) == 0.f) {
q__2.r = vb11r, q__2.i = 0.f;
q__1.r = -q__2.r, q__1.i = -q__2.i;
r_cnjg(&q__3, &vb12);
clartg_(&q__1, &q__3, csq, snq, &r__);
} else if (abs(vb11r) + ((r__1 = vb12.r, abs(r__1)) + (r__2 =
r_imag(&vb12), abs(r__2))) == 0.f) {
q__2.r = ua11r, q__2.i = 0.f;
q__1.r = -q__2.r, q__1.i = -q__2.i;
r_cnjg(&q__3, &ua12);
clartg_(&q__1, &q__3, csq, snq, &r__);
} else if (aua12 / (abs(ua11r) + ((r__1 = ua12.r, abs(r__1)) + (
r__2 = r_imag(&ua12), abs(r__2)))) <= avb12 / (abs(vb11r)
+ ((r__3 = vb12.r, abs(r__3)) + (r__4 = r_imag(&vb12),
abs(r__4))))) {
q__2.r = ua11r, q__2.i = 0.f;
q__1.r = -q__2.r, q__1.i = -q__2.i;
r_cnjg(&q__3, &ua12);
clartg_(&q__1, &q__3, csq, snq, &r__);
} else {
q__2.r = vb11r, q__2.i = 0.f;
q__1.r = -q__2.r, q__1.i = -q__2.i;
r_cnjg(&q__3, &vb12);
clartg_(&q__1, &q__3, csq, snq, &r__);
}
*csu = csl;
q__2.r = -d1.r, q__2.i = -d1.i;
q__1.r = snl * q__2.r, q__1.i = snl * q__2.i;
snu->r = q__1.r, snu->i = q__1.i;
*csv = csr;
q__2.r = -d1.r, q__2.i = -d1.i;
q__1.r = snr * q__2.r, q__1.i = snr * q__2.i;
snv->r = q__1.r, snv->i = q__1.i;
} else {
/* Compute the (2,1) and (2,2) elements of U**H *A and V**H *B, */
/* and (2,2) element of |U|**H *|A| and |V|**H *|B|. */
r_cnjg(&q__4, &d1);
q__3.r = -q__4.r, q__3.i = -q__4.i;
q__2.r = snl * q__3.r, q__2.i = snl * q__3.i;
q__1.r = *a1 * q__2.r, q__1.i = *a1 * q__2.i;
ua21.r = q__1.r, ua21.i = q__1.i;
r_cnjg(&q__5, &d1);
q__4.r = -q__5.r, q__4.i = -q__5.i;
q__3.r = snl * q__4.r, q__3.i = snl * q__4.i;
q__2.r = q__3.r * a2->r - q__3.i * a2->i, q__2.i = q__3.r * a2->i
+ q__3.i * a2->r;
r__1 = csl * *a3;
q__1.r = q__2.r + r__1, q__1.i = q__2.i;
ua22.r = q__1.r, ua22.i = q__1.i;
r_cnjg(&q__4, &d1);
q__3.r = -q__4.r, q__3.i = -q__4.i;
q__2.r = snr * q__3.r, q__2.i = snr * q__3.i;
q__1.r = *b1 * q__2.r, q__1.i = *b1 * q__2.i;
vb21.r = q__1.r, vb21.i = q__1.i;
r_cnjg(&q__5, &d1);
q__4.r = -q__5.r, q__4.i = -q__5.i;
q__3.r = snr * q__4.r, q__3.i = snr * q__4.i;
q__2.r = q__3.r * b2->r - q__3.i * b2->i, q__2.i = q__3.r * b2->i
+ q__3.i * b2->r;
r__1 = csr * *b3;
q__1.r = q__2.r + r__1, q__1.i = q__2.i;
vb22.r = q__1.r, vb22.i = q__1.i;
aua22 = abs(snl) * ((r__1 = a2->r, abs(r__1)) + (r__2 = r_imag(a2)
, abs(r__2))) + abs(csl) * abs(*a3);
avb22 = abs(snr) * ((r__1 = b2->r, abs(r__1)) + (r__2 = r_imag(b2)
, abs(r__2))) + abs(csr) * abs(*b3);
/* zero (2,2) elements of U**H *A and V**H *B, and then swap. */
if ((r__1 = ua21.r, abs(r__1)) + (r__2 = r_imag(&ua21), abs(r__2))
+ ((r__3 = ua22.r, abs(r__3)) + (r__4 = r_imag(&ua22),
abs(r__4))) == 0.f) {
r_cnjg(&q__2, &vb21);
q__1.r = -q__2.r, q__1.i = -q__2.i;
r_cnjg(&q__3, &vb22);
clartg_(&q__1, &q__3, csq, snq, &r__);
} else if ((r__1 = vb21.r, abs(r__1)) + (r__2 = r_imag(&vb21),
abs(r__2)) + c_abs(&vb22) == 0.f) {
r_cnjg(&q__2, &ua21);
q__1.r = -q__2.r, q__1.i = -q__2.i;
r_cnjg(&q__3, &ua22);
clartg_(&q__1, &q__3, csq, snq, &r__);
} else if (aua22 / ((r__1 = ua21.r, abs(r__1)) + (r__2 = r_imag(&
ua21), abs(r__2)) + ((r__3 = ua22.r, abs(r__3)) + (r__4 =
r_imag(&ua22), abs(r__4)))) <= avb22 / ((r__5 = vb21.r,
abs(r__5)) + (r__6 = r_imag(&vb21), abs(r__6)) + ((r__7 =
vb22.r, abs(r__7)) + (r__8 = r_imag(&vb22), abs(r__8)))))
{
r_cnjg(&q__2, &ua21);
q__1.r = -q__2.r, q__1.i = -q__2.i;
r_cnjg(&q__3, &ua22);
clartg_(&q__1, &q__3, csq, snq, &r__);
} else {
r_cnjg(&q__2, &vb21);
q__1.r = -q__2.r, q__1.i = -q__2.i;
r_cnjg(&q__3, &vb22);
clartg_(&q__1, &q__3, csq, snq, &r__);
}
*csu = snl;
q__1.r = csl * d1.r, q__1.i = csl * d1.i;
snu->r = q__1.r, snu->i = q__1.i;
*csv = snr;
q__1.r = csr * d1.r, q__1.i = csr * d1.i;
snv->r = q__1.r, snv->i = q__1.i;
}
} else {
/* Input matrices A and B are lower triangular matrices */
/* Form matrix C = A*adj(B) = ( a 0 ) */
/* ( c d ) */
a = *a1 * *b3;
d__ = *a3 * *b1;
q__2.r = *b3 * a2->r, q__2.i = *b3 * a2->i;
q__3.r = *a3 * b2->r, q__3.i = *a3 * b2->i;
q__1.r = q__2.r - q__3.r, q__1.i = q__2.i - q__3.i;
c__.r = q__1.r, c__.i = q__1.i;
fc = c_abs(&c__);
/* Transform complex 2-by-2 matrix C to real matrix by unitary */
/* diagonal matrix diag(d1,1). */
d1.r = 1.f, d1.i = 0.f;
if (fc != 0.f) {
q__1.r = c__.r / fc, q__1.i = c__.i / fc;
d1.r = q__1.r, d1.i = q__1.i;
}
/* The SVD of real 2 by 2 triangular C */
/* ( CSL -SNL )*( A 0 )*( CSR SNR ) = ( R 0 ) */
/* ( SNL CSL ) ( C D ) ( -SNR CSR ) ( 0 T ) */
slasv2_(&a, &fc, &d__, &s1, &s2, &snr, &csr, &snl, &csl);
if (abs(csr) >= abs(snr) || abs(csl) >= abs(snl)) {
/* Compute the (2,1) and (2,2) elements of U**H *A and V**H *B, */
/* and (2,1) element of |U|**H *|A| and |V|**H *|B|. */
q__4.r = -d1.r, q__4.i = -d1.i;
q__3.r = snr * q__4.r, q__3.i = snr * q__4.i;
q__2.r = *a1 * q__3.r, q__2.i = *a1 * q__3.i;
q__5.r = csr * a2->r, q__5.i = csr * a2->i;
q__1.r = q__2.r + q__5.r, q__1.i = q__2.i + q__5.i;
ua21.r = q__1.r, ua21.i = q__1.i;
ua22r = csr * *a3;
q__4.r = -d1.r, q__4.i = -d1.i;
q__3.r = snl * q__4.r, q__3.i = snl * q__4.i;
q__2.r = *b1 * q__3.r, q__2.i = *b1 * q__3.i;
q__5.r = csl * b2->r, q__5.i = csl * b2->i;
q__1.r = q__2.r + q__5.r, q__1.i = q__2.i + q__5.i;
vb21.r = q__1.r, vb21.i = q__1.i;
vb22r = csl * *b3;
aua21 = abs(snr) * abs(*a1) + abs(csr) * ((r__1 = a2->r, abs(r__1)
) + (r__2 = r_imag(a2), abs(r__2)));
avb21 = abs(snl) * abs(*b1) + abs(csl) * ((r__1 = b2->r, abs(r__1)
) + (r__2 = r_imag(b2), abs(r__2)));
/* zero (2,1) elements of U**H *A and V**H *B. */
if ((r__1 = ua21.r, abs(r__1)) + (r__2 = r_imag(&ua21), abs(r__2))
+ abs(ua22r) == 0.f) {
q__1.r = vb22r, q__1.i = 0.f;
clartg_(&q__1, &vb21, csq, snq, &r__);
} else if ((r__1 = vb21.r, abs(r__1)) + (r__2 = r_imag(&vb21),
abs(r__2)) + abs(vb22r) == 0.f) {
q__1.r = ua22r, q__1.i = 0.f;
clartg_(&q__1, &ua21, csq, snq, &r__);
} else if (aua21 / ((r__1 = ua21.r, abs(r__1)) + (r__2 = r_imag(&
ua21), abs(r__2)) + abs(ua22r)) <= avb21 / ((r__3 =
vb21.r, abs(r__3)) + (r__4 = r_imag(&vb21), abs(r__4)) +
abs(vb22r))) {
q__1.r = ua22r, q__1.i = 0.f;
clartg_(&q__1, &ua21, csq, snq, &r__);
} else {
q__1.r = vb22r, q__1.i = 0.f;
clartg_(&q__1, &vb21, csq, snq, &r__);
}
*csu = csr;
r_cnjg(&q__3, &d1);
q__2.r = -q__3.r, q__2.i = -q__3.i;
q__1.r = snr * q__2.r, q__1.i = snr * q__2.i;
snu->r = q__1.r, snu->i = q__1.i;
*csv = csl;
r_cnjg(&q__3, &d1);
q__2.r = -q__3.r, q__2.i = -q__3.i;
q__1.r = snl * q__2.r, q__1.i = snl * q__2.i;
snv->r = q__1.r, snv->i = q__1.i;
} else {
/* Compute the (1,1) and (1,2) elements of U**H *A and V**H *B, */
/* and (1,1) element of |U|**H *|A| and |V|**H *|B|. */
r__1 = csr * *a1;
r_cnjg(&q__4, &d1);
q__3.r = snr * q__4.r, q__3.i = snr * q__4.i;
q__2.r = q__3.r * a2->r - q__3.i * a2->i, q__2.i = q__3.r * a2->i
+ q__3.i * a2->r;
q__1.r = r__1 + q__2.r, q__1.i = q__2.i;
ua11.r = q__1.r, ua11.i = q__1.i;
r_cnjg(&q__3, &d1);
q__2.r = snr * q__3.r, q__2.i = snr * q__3.i;
q__1.r = *a3 * q__2.r, q__1.i = *a3 * q__2.i;
ua12.r = q__1.r, ua12.i = q__1.i;
r__1 = csl * *b1;
r_cnjg(&q__4, &d1);
q__3.r = snl * q__4.r, q__3.i = snl * q__4.i;
q__2.r = q__3.r * b2->r - q__3.i * b2->i, q__2.i = q__3.r * b2->i
+ q__3.i * b2->r;
q__1.r = r__1 + q__2.r, q__1.i = q__2.i;
vb11.r = q__1.r, vb11.i = q__1.i;
r_cnjg(&q__3, &d1);
q__2.r = snl * q__3.r, q__2.i = snl * q__3.i;
q__1.r = *b3 * q__2.r, q__1.i = *b3 * q__2.i;
vb12.r = q__1.r, vb12.i = q__1.i;
aua11 = abs(csr) * abs(*a1) + abs(snr) * ((r__1 = a2->r, abs(r__1)
) + (r__2 = r_imag(a2), abs(r__2)));
avb11 = abs(csl) * abs(*b1) + abs(snl) * ((r__1 = b2->r, abs(r__1)
) + (r__2 = r_imag(b2), abs(r__2)));
/* zero (1,1) elements of U**H *A and V**H *B, and then swap. */
if ((r__1 = ua11.r, abs(r__1)) + (r__2 = r_imag(&ua11), abs(r__2))
+ ((r__3 = ua12.r, abs(r__3)) + (r__4 = r_imag(&ua12),
abs(r__4))) == 0.f) {
clartg_(&vb12, &vb11, csq, snq, &r__);
} else if ((r__1 = vb11.r, abs(r__1)) + (r__2 = r_imag(&vb11),
abs(r__2)) + ((r__3 = vb12.r, abs(r__3)) + (r__4 = r_imag(
&vb12), abs(r__4))) == 0.f) {
clartg_(&ua12, &ua11, csq, snq, &r__);
} else if (aua11 / ((r__1 = ua11.r, abs(r__1)) + (r__2 = r_imag(&
ua11), abs(r__2)) + ((r__3 = ua12.r, abs(r__3)) + (r__4 =
r_imag(&ua12), abs(r__4)))) <= avb11 / ((r__5 = vb11.r,
abs(r__5)) + (r__6 = r_imag(&vb11), abs(r__6)) + ((r__7 =
vb12.r, abs(r__7)) + (r__8 = r_imag(&vb12), abs(r__8)))))
{
clartg_(&ua12, &ua11, csq, snq, &r__);
} else {
clartg_(&vb12, &vb11, csq, snq, &r__);
}
*csu = snr;
r_cnjg(&q__2, &d1);
q__1.r = csr * q__2.r, q__1.i = csr * q__2.i;
snu->r = q__1.r, snu->i = q__1.i;
*csv = snl;
r_cnjg(&q__2, &d1);
q__1.r = csl * q__2.r, q__1.i = csl * q__2.i;
snv->r = q__1.r, snv->i = q__1.i;
}
}
return 0;
/* End of CLAGS2 */
} /* clags2_ */
|
the_stack_data/203304.c | /*
* libc/stdio/fscanf.c
* ANSI-compliant C standard i/o library.
* fscanf()
* ANSI 4.9.6.2.
* Formatted input from FILE.
*/
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
int
fscanf(stream, format) FILE *stream; const char *format;
{
va_list args;
int count;
va_start(args, format);
count = _scanf(stream, format, args);
va_end(args);
return count;
}
/* end of libc/stdio/fscanf.c */
|
the_stack_data/42492.c | int fib(int n)
{
if (n <= 1)
{
return n;
}
return fib(n-1) + fib(n-2);
}
|
the_stack_data/990002.c | /* Disciplina: Computacao Concorrente */
/* Prof.: Silvana Rossetto */
/* Laboratório: 5 */
/* Codigo: Threads escrevem e leem uma variavel global: exemlo de programa com condicao de corrida */
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NTHREADS 3
int x = 0; //variavel compartilhada entre as threads
//funcao executada pela thread 1
void *t1 (void *threadid) {
int tid = *(int*) threadid;
printf("Thread : %d esta executando...\n", tid);
x = 1;
printf("Thread : %d terminou!\n", tid);
free(threadid);
pthread_exit(NULL);
}
//funcao executada pela thread 2
void *t2 (void *threadid) {
int tid = *(int*) threadid;
printf("Thread : %d esta executando...\n", tid);
x = 2;
printf("Thread : %d terminou!\n", (int) tid);
free(threadid);
pthread_exit(NULL);
}
//funcao executada pela thread 3
void *t3 (void *threadid) {
int y;
int tid = *(int*) threadid;
printf("Thread : %d esta executando...\n", tid);
y = x;
printf("Thread : %d terminou!\n", tid);
printf("Valor de y = %d\n", y);
free(threadid);
pthread_exit(NULL);
}
//thread principal
int main(int argc, char *argv[]) {
pthread_t tid[NTHREADS];
int *t;
//cria as 3 threads
t = malloc(sizeof(int)); if(t==NULL) return -1;
*t = 1;
if (pthread_create(&tid[0], NULL, t1, (void *)t)) {
printf("--ERRO: pthread_create()\n"); exit(-1); }
t = malloc(sizeof(int)); if(t==NULL) return -1;
*t = 2;
if (pthread_create(&tid[1], NULL, t2, (void *)t)) {
printf("--ERRO: pthread_create()\n"); exit(-1);}
t = malloc(sizeof(int)); if(t==NULL) return -1;
*t = 3;
if (pthread_create(&tid[2], NULL, t3, (void *)t)) {
printf("--ERRO: pthread_create()\n"); exit(-1); }
pthread_exit(NULL);
return 0;
}
|
the_stack_data/165766171.c | #include <stdio.h>
#include <math.h>
#include <stdbool.h>
# define PI 3.14159
# define loop_limit 90
//created by Justin M O'Dea
// Feb 20, 2016
bool done = false;
unsigned input;
enum menu_t {
Sine, Cosine, Tangent, QUIT
};
void list(void) // Prints menu
{
printf("Please choose an option: (0) Sine (1) Cosine (2) Tangent (3) QUIT\n");
printf("Enter your choice: ");
} // end menu method
int tally() // tallies sin, cos, tan, and terminates after three is typed.
{
while (!done) {
scanf("%u", &input);
switch (input) {
case Sine:
for (int i = 0; i <= loop_limit; i = i + 15) {
printf("\tsin(%d) = %2f\n", i, sin(PI * i / 180.0f)); // calculates sin
}
list();
break;
case Cosine:
for (int i = 0; i <= loop_limit; i = i + 15) {
printf("\tcos(%d) = %2f\n", i, cos(PI * i / 180.0f)); // calculates cos
}
list();
break;
case Tangent:
for (int i = 0; i <= loop_limit; i = i + 15) {
if (i == 90)
printf("\ttan(90) is UNDEFINED\n");
else
printf("\ttan(%d) = %2f\n", i,
tan(PI * i / 180.0f)); // calculates tan
}
list();
break;
case QUIT:
done = true;
printf("You chose QUIT. Thank you, come again!\n"); // quits and terminates
break;
default:
printf("%d is an invalid option. Please try again.\n",
input); // invalid option method
} // end switch
} // end while
} // end calculate method
int main() // main method
{
list(); // Prints main menu.
while (!done)
{
tally(input); // Calculates and prints sin, cos, tan, and quit.
} // end while
return 0;
} // end main
|
the_stack_data/57949732.c | /* The Computer Language Benchmarks Game
* http://benchmarksgame.alioth.debian.org/
*
* contributed by Bob W
*/
#include <stdio.h>
#include <stdlib.h>
#include "time.h"
#define JBFSIZE 82 // line input buffer size
#define QBFSIZE 5200 // output buffer initial size
#define Z16 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
#define V32 "\0TVGH\0\0CD\0\0M\0KN\0\0\0YSA\0BW\0R\0\0\0\0\0\0"
#define VALL Z16 Z16 Z16 Z16 V32 V32 Z16 Z16 Z16 Z16 Z16 Z16 Z16 Z16
int errex(char *s, int n) { // error message+value, return 1
fprintf(stderr,"\n*** Error: %s [%d]!\n", s, n);
return 1;
}
int main () { // ***** main *****
char *pj, *pq, *pr; // buffer pointers: inp,out,/out
char *jjj = malloc(JBFSIZE); // allocate input line buffer
char *qqq = malloc(QBFSIZE); // output buffer (dyn. size)
char *pqstop = qqq+QBFSIZE; // end-of-buffer pointer
char xtab[256] = VALL; // char conversion table
clock_t t = clock();
if (!jjj || !qqq)
return errex("Buffer allocation", !jjj + !qqq);
pj = fgets(jjj,JBFSIZE,stdin); // fetch 1st line
if (!pj)
return errex("No input data",0);
if (*jjj != '>')
return errex("1st char not '>'", 0);
while (pj) { // MAIN LOOP: process data
fputs(jjj, stdout); // output ID line
for (pq=qqq+1, pr=pqstop; ; pq++) { // LOOP: fill output buffer
pj = fgets(jjj, JBFSIZE, stdin); // get line from stdin
if (!pj || (*jjj=='>')) break; // EOF or new ID line
if (pr <= (pq+61)) { // need to resize buffer
char *newstop = pqstop + 12777888;
char *newptr = realloc(qqq, newstop-qqq);
if (!newptr)
return errex("Out of memory", 0);
if (newptr != qqq) { // new base: adj. pointers
size_t x = newptr-qqq; // offset for pointer update
pq+=x; pr+=x; qqq+=x;
newstop+=x; pqstop+=x;
}
pr = __builtin_memmove(newstop-(pqstop-pr), pr, pqstop-pr);
pqstop = newstop; // buffer resize complete
}
while (*pj) { // LOOP: conv. & revert line
char c = xtab[(unsigned char)(*pj++)];
if (c) // conversion valid
*(--pr) = c;
}
}
for (pq = qqq; pr<pqstop; ) { // LOOP: format output
size_t x = (pqstop-pr)<60 ? pqstop-pr : 60;
__builtin_memmove(pq,pr,x); // move line to free space
pr+=x; pq+=x; *(pq++) = 0xA; // adjust pointers, add LF
}
fwrite(qqq, 1, pq-qqq, stdout); // output converted data
}
fprintf(stderr, "time(%.2f)\n", (float)(clock() - t)/CLOCKS_PER_SEC);
return 0;
}
|
the_stack_data/85692.c | #include <stdio.h>
/* This is a comment. */
int main(int argc, char *argv[])
{
int distance = 100;
// this is also a comment
printf("You are %d miles away.\n", distance);
return 0;
}
|
the_stack_data/70449235.c | int main() {
int a[6][6][6];
int b = 1;
int c = 2;
int d = 3;
a[b+3][c+2][d+1]= 94 + b + c + d;
return a[b+3][c+2][d+1];
} |
the_stack_data/970544.c | #include <stdio.h>
int sum;
int divisor;
int product;
int difference;
int remainder;
int main() {
sum = (1 + 2);
divisor = (4 / 2);
product = (3 * 3);
difference = (7 - 2);
remainder = (7 % 2);
printf("These are the values: %d %d %d %d %d", sum, divisor, product, difference, remainder);
}
|
the_stack_data/72013605.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <CL/cl.h>
unsigned char *read_buffer(char *file_name, size_t *size_ptr)
{
FILE *f;
unsigned char *buf;
size_t size;
/* Open file */
f = fopen(file_name, "rb");
if (!f)
return NULL;
/* Obtain file size */
fseek(f, 0, SEEK_END);
size = ftell(f);
fseek(f, 0, SEEK_SET);
/* Allocate and read buffer */
buf = malloc(size + 1);
fread(buf, 1, size, f);
buf[size] = '\0';
/* Return size of buffer */
if (size_ptr)
*size_ptr = size;
/* Return buffer */
return buf;
}
void write_buffer(char *file_name, const char *buffer, size_t buffer_size)
{
FILE *f;
/* Open file */
f = fopen(file_name, "w+");
/* Write buffer */
if(buffer)
fwrite(buffer, 1, buffer_size, f);
/* Close file */
fclose(f);
}
int main(int argc, char const *argv[])
{
/* Get platform */
cl_platform_id platform;
cl_uint num_platforms;
cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetPlatformIDs' failed\n");
exit(1);
}
printf("Number of platforms: %d\n", num_platforms);
printf("platform=%p\n", platform);
/* Get platform name */
char platform_name[100];
ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetPlatformInfo' failed\n");
exit(1);
}
printf("platform.name='%s'\n\n", platform_name);
/* Get device */
cl_device_id device;
cl_uint num_devices;
ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetDeviceIDs' failed\n");
exit(1);
}
printf("Number of devices: %d\n", num_devices);
printf("device=%p\n", device);
/* Get device name */
char device_name[100];
ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name),
device_name, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetDeviceInfo' failed\n");
exit(1);
}
printf("device.name='%s'\n", device_name);
printf("\n");
/* Create a Context Object */
cl_context context;
context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateContext' failed\n");
exit(1);
}
printf("context=%p\n", context);
/* Create a Command Queue Object*/
cl_command_queue command_queue;
command_queue = clCreateCommandQueue(context, device, 0, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateCommandQueue' failed\n");
exit(1);
}
printf("command_queue=%p\n", command_queue);
printf("\n");
/* Program source */
unsigned char *source_code;
size_t source_length;
/* Read program from 'relational_less_than_long8long8.cl' */
source_code = read_buffer("relational_less_than_long8long8.cl", &source_length);
/* Create a program */
cl_program program;
program = clCreateProgramWithSource(context, 1, (const char **)&source_code, &source_length, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateProgramWithSource' failed\n");
exit(1);
}
printf("program=%p\n", program);
/* Build program */
ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
if (ret != CL_SUCCESS )
{
size_t size;
char *log;
/* Get log size */
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size);
/* Allocate log and print */
log = malloc(size);
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL);
printf("error: call to 'clBuildProgram' failed:\n%s\n", log);
/* Free log and exit */
free(log);
exit(1);
}
printf("program built\n");
printf("\n");
/* Create a Kernel Object */
cl_kernel kernel;
kernel = clCreateKernel(program, "relational_less_than_long8long8", &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateKernel' failed\n");
exit(1);
}
/* Create and allocate host buffers */
size_t num_elem = 10;
/* Create and init host side src buffer 0 */
cl_long8 *src_0_host_buffer;
src_0_host_buffer = malloc(num_elem * sizeof(cl_long8));
for (int i = 0; i < num_elem; i++)
src_0_host_buffer[i] = (cl_long8){{2, 2, 2, 2, 2, 2, 2, 2}};
/* Create and init device side src buffer 0 */
cl_mem src_0_device_buffer;
src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_long8), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create source buffer\n");
exit(1);
}
ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_long8), src_0_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueWriteBuffer' failed\n");
exit(1);
}
/* Create and init host side src buffer 1 */
cl_long8 *src_1_host_buffer;
src_1_host_buffer = malloc(num_elem * sizeof(cl_long8));
for (int i = 0; i < num_elem; i++)
src_1_host_buffer[i] = (cl_long8){{2, 2, 2, 2, 2, 2, 2, 2}};
/* Create and init device side src buffer 1 */
cl_mem src_1_device_buffer;
src_1_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_long8), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create source buffer\n");
exit(1);
}
ret = clEnqueueWriteBuffer(command_queue, src_1_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_long8), src_1_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueWriteBuffer' failed\n");
exit(1);
}
/* Create host dst buffer */
cl_int8 *dst_host_buffer;
dst_host_buffer = malloc(num_elem * sizeof(cl_int8));
memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_int8));
/* Create device dst buffer */
cl_mem dst_device_buffer;
dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_int8), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create dst buffer\n");
exit(1);
}
/* Set kernel arguments */
ret = CL_SUCCESS;
ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer);
ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &src_1_device_buffer);
ret |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &dst_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clSetKernelArg' failed\n");
exit(1);
}
/* Launch the kernel */
size_t global_work_size = num_elem;
size_t local_work_size = num_elem;
ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueNDRangeKernel' failed\n");
exit(1);
}
/* Wait for it to finish */
clFinish(command_queue);
/* Read results from GPU */
ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_int8), dst_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueReadBuffer' failed\n");
exit(1);
}
/* Dump dst buffer to file */
char dump_file[100];
sprintf((char *)&dump_file, "%s.result", argv[0]);
write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_int8));
printf("Result dumped to %s\n", dump_file);
/* Free host dst buffer */
free(dst_host_buffer);
/* Free device dst buffer */
ret = clReleaseMemObject(dst_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Free host side src buffer 0 */
free(src_0_host_buffer);
/* Free device side src buffer 0 */
ret = clReleaseMemObject(src_0_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Free host side src buffer 1 */
free(src_1_host_buffer);
/* Free device side src buffer 1 */
ret = clReleaseMemObject(src_1_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Release kernel */
ret = clReleaseKernel(kernel);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseKernel' failed\n");
exit(1);
}
/* Release program */
ret = clReleaseProgram(program);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseProgram' failed\n");
exit(1);
}
/* Release command queue */
ret = clReleaseCommandQueue(command_queue);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseCommandQueue' failed\n");
exit(1);
}
/* Release context */
ret = clReleaseContext(context);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseContext' failed\n");
exit(1);
}
return 0;
} |
the_stack_data/6387989.c | #include<stdio.h>
#include<stdlib.h>
typedef struct Node {
int key, val;
struct Node *left;
struct Node *right;
struct Node *parent;
} Node;
Node* add_node_in_tree(int key, int val, Node *parent) {
Node* tmp = (Node*) malloc(sizeof(Node));
tmp->left = tmp->right = NULL;
tmp->key = key;
tmp->val = val;
tmp->parent = parent;
return tmp;
}
void insert(Node *head, int key, int val) {
Node *tmp = NULL;
if (head == NULL) {
head = add_node_in_tree(key, val, NULL);
return;
}
tmp = head;
while(tmp) {
if(val > tmp->val) {
if(tmp->right) {
tmp = tmp->right;
continue;
} else {
tmp->right = add_node_in_tree(key, val, tmp);
return;
}
} else if(val < tmp->val) {
if(tmp->left) {
tmp = tmp->left;
continue;
} else {
tmp->left = add_node_in_tree(key, val, tmp);
return;
}
} else {
return;
}
}
}
Node* get_node_key(Node *head, int key) {
if(head) {
if(head->right) {
if(head->key == key) {
return head;
} else {
Node *tmp = get_node_key(head->right, key);
if(tmp) {
return tmp;
}
}
}
if(head->left) {
if(head->key == key) {
return head;
} else {
Node *tmp = get_node_key(head->left, key);
if(tmp) {
return tmp;
}
}
}
}
return NULL;
}
int get_node_level_key(Node *head, int key, int level) {
if(head) {
if(head->right) {
if(head->key == key) {
return level;
} else {
int lvl = get_node_level_key(head->right, key, level + 1);
if(lvl) {
return lvl;
}
}
}
if(head->left) {
if(head->key == key) {
return level;
} else {
int lvl = get_node_level_key(head->left, key, level + 1);
if(lvl) {
return lvl;
}
}
}
}
return 0;
}
void print_tree(Node *head) {
if(head) {
print_tree(head->right);
printf("%d", head->val);
print_tree(head->left);
}
}
int main() {
int n;
scanf("%d", &n);
int key, val;
scanf("%d%d", &key, &val);
Node* head = add_node_in_tree(key, val, NULL);
for(int i = 1; i < n; i++) {
scanf("%d%d", &key, &val);
insert(head, key, val);
}
print_tree(head);
printf("\n");
}
|
the_stack_data/794511.c | #include <stdio.h>
int main(void){
int x,z,y,a1,a2,a,b,c,d,flag; //z=Unicode,x=variable for input,a-b-c-d=temporary variables for byte management
x=getchar();
while(x!=EOF){ //Don't stop until the end of the file
flag=0; //Indication if character is encoded in UTF-8
if (x<=0x7F){ //1-byte-encoded: 0xxxxxxx
flag=1;
z=x;
}
else if(x>=0xC0 && x<=0xDF){ //2-byte-encoded: 110xxxxx 10xxxxxx , where x are unicode bits
flag=1; //Always getting bytes form left to right...
a=x&31;
a<<=6;
x=getchar();
b=x&63;
z=a|b;
}
else if(x>=0xE0 && x<=0xEF){ //3-byte-encoded: 1110xxxx 10xxxxxx 10xxxxxx
flag=1;
a=x&15;
a<<=12;
x=getchar();
b=x&63;
b<<=6;
x=getchar();
c=x&63;
z=a|b|c;
}
else if(x>=0xF0 && x<=0xF7){ //4-byte-encoded: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
flag=1;
a=x&7;
a<<=18;
x=getchar();
b=x&0x3F;
b<<=12;
x=getchar();
c=x&63;
c<<=6;
x=getchar();
d=x&63;
z=a|b|c|d;
}
if(!flag){ //Error:false input text file
printf("\n TEXT NOT IN UTF-8");
break;
}
///////////////////////////////////////////Start of UTF-16 encoding///////////////////////////////////////////////////
if((z<=0xD7FF)||(z>=0xE000 && z<=0xFFFF)){//Encoding using 2 bytes,Unicode exists in [0x0000,0xD7FF] and [0xE000,0xFFFF].
putchar (z >> 8);
putchar (z & 255);
}
else if(z>=0x10000 && z<=0x10FFFF){ //Encoding using 4 bytes,Unicode exists in [0x010000,0x10FFFF].
z-=0x010000;
a1=(z>>10)+0xD800; //a1=high surrogate,exists in [0xD800,0xDBFF].
a2=(z&1023)+0xDC00; //a2=low surrogate,exists in [0xDC00,0xDFFF].
putchar(a1>>8); //Creating the surrogate pair...
putchar(a1&255);
putchar(a2>>8);
putchar(a2&255);
}
x=getchar(); //Moving to next character
}
return 0;
}
|
the_stack_data/4751.c | int main()
{
int a = 68;
return a-5+98;
} |
the_stack_data/11601.c | //Berechnung und Ausgabe der Levenshtein Distanz zwischen zwei Wörtern
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void printMatrix (int *matrix, int zeilen, int spalten);
void main () {
char wort1[49], wort2[49]; //2 Strings mit Platz für 49 Zeichen, da 49*2=98, letzte Mögl für 2 Stellen für Ausgabe Zahlen in der Matrix
int laenge1, laenge2, i, n, distanz;
printf("Eingabe des ersten Wortes: "); //Aufforderung zur Eingabe von Wörtern
scanf("%s", wort1);
printf("Eingabe des zeiten Wortes: ");
scanf("%s", wort2);
laenge1 = strlen(wort1) + 1; //Länge um 1 höher als Wort, da Levenshteinmatrix mit leerem Buchstaben beginnt
laenge2 = strlen(wort2) + 1;
int ergebnisMatrix[laenge1][laenge2]; //2D Array als Ergebnismatrix erstellen
memset (ergebnisMatrix, 0, sizeof(ergebnisMatrix)); //Array mit Nullen füllen
for (i = 0; i < laenge2; i++) { //Erste Zeile mit Zalen von 0 bis Länge des Zielwortes füllen (einfüge Operation beim Wortvergleich)
ergebnisMatrix[0][i] = i;
}
for (i = 1; i < laenge1; i++) { //Erste Spalte mit Zahlen von 0 bis Länge des Quellwortes füllen (löschen Operation beim Wortvergleich)
ergebnisMatrix[i][0] = i;
}
for (i = 1; i < laenge1; i++) { //Zusammensetzung der Matrix
for (n = 1; n < laenge2; n++) {
if (wort1[i - 1] == wort2[n - 1]) { //Wenn Buchstaben an Stelle gleich sind --> keine erhöhung der Levenshtein Distanz
ergebnisMatrix[i][n] = ergebnisMatrix[i - 1][n - 1];
}
else { //Wenn Buchstaben verschiden erhöhe um 1 von min(links daneben, darüber)
if (ergebnisMatrix[i][n - 1] > ergebnisMatrix[i - 1][n])
ergebnisMatrix[i][n] = ergebnisMatrix[i - 1][n] + 1;
else
ergebnisMatrix[i][n] = ergebnisMatrix[i][n - 1] + 1;
}
}
}
distanz = ergebnisMatrix[laenge1 - 1][laenge2 - 1]; //Levenshteindistanz = Element rechts unten
printMatrix (&ergebnisMatrix[0][0], laenge1, laenge2); //Funktionsaufruf die Ergebnismatrix auszugeben
printf("\nDie Levenshteindistanz zwischen '%s' und '%s' betraegt: %i", wort1, wort2, distanz); //Ausgabe der Levenshtein Distanz
getchar();
printf("\nContinue...");
getchar();
}
void printMatrix (int *matrix, int zeilen,int spalten) { //Funktion zur Ausgabe der Ergebnismatrix
int n, m;
printf("\n");
for (n = 0; n < zeilen; n++) { //Zeilen
for (m = 0; m < spalten; m++){ //Spalten
printf("%3i", *(matrix + n * spalten + m)); //Ausgabe der Zahlen in der Matrix
}
printf("\n"); //Zeilenumburch
}
} |
the_stack_data/99905.c | #include <stdio.h>
int inp(void);
int cal(int);
int main(void)
{
printf("%d", cal(inp()));
return 0;
}
int inp()
{
int intp;
scanf("%d", &intp);
return intp;
}
int cal(int stk)
{
int cnt = 1, n;
if(stk == 1){
return 1;
}
for (n = 1; ; n++){
cnt += n * 6;
if(cnt >= stk){
break;
}
}
return n + 1;
}
|
the_stack_data/36147.c | /*
This file is adapted from ref10/scalarmult.c:
The code for Mongomery ladder is replace by the ladder assembly function;
Inversion is done in the same way as amd64-51/.
(fe is first converted into fe51 after Mongomery ladder)
*/
#include <stddef.h>
#ifdef HAVE_AVX_ASM
#include "utils.h"
#include "curve25519_sandy2x.h"
#include "../scalarmult_curve25519.h"
#include "fe.h"
#include "fe51.h"
#include "ladder.h"
#define x1 var[0]
#define x2 var[1]
#define z2 var[2]
static int
crypto_scalarmult_curve25519_sandy2x(unsigned char *q, const unsigned char *n,
const unsigned char *p)
{
unsigned char *t = q;
fe var[3];
fe51 x_51;
fe51 z_51;
unsigned int i;
for (i = 0; i < 32; i++) {
t[i] = n[i];
}
t[0] &= 248;
t[31] &= 127;
t[31] |= 64;
fe_frombytes(x1, p);
ladder(var, t);
z_51.v[0] = (z2[1] << 26) + z2[0];
z_51.v[1] = (z2[3] << 26) + z2[2];
z_51.v[2] = (z2[5] << 26) + z2[4];
z_51.v[3] = (z2[7] << 26) + z2[6];
z_51.v[4] = (z2[9] << 26) + z2[8];
x_51.v[0] = (x2[1] << 26) + x2[0];
x_51.v[1] = (x2[3] << 26) + x2[2];
x_51.v[2] = (x2[5] << 26) + x2[4];
x_51.v[3] = (x2[7] << 26) + x2[6];
x_51.v[4] = (x2[9] << 26) + x2[8];
fe51_invert(&z_51, &z_51);
fe51_mul(&x_51, &x_51, &z_51);
fe51_pack(q, &x_51);
return 0;
}
struct crypto_scalarmult_curve25519_implementation
crypto_scalarmult_curve25519_sandy2x_implementation = {
SODIUM_C99(.mult = ) crypto_scalarmult_curve25519_sandy2x,
SODIUM_C99(.mult_base = ) NULL
};
#endif
|
the_stack_data/242331566.c | // a program on binary search
#include<stdio.h>
int main() {
int n, a[30], item, i, j, mid, top, bottom;
printf("Enter how many elements you want:\n");
scanf("%d", &n);
printf("Enter the %d elements in ascending order\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
printf("\nEnter the item to search\n");
scanf("%d", &item);
bottom = 1;
top = n;
do {
mid = (bottom + top) / 2;
if (item < a[mid])
top = mid - 1;
else if (item > a[mid])
bottom = mid + 1;
} while (item != a[mid] && bottom <= top);
if (item == a[mid]) {
printf("Binary search successfull!!\n");
printf("\n %d found in position: %d\n", item, mid + 1);
} else {
printf("\n Search failed\n %d not found\n", item);
}
return 0;
}
|
the_stack_data/140765345.c | // See ../getdents/getdents.go for some info on why
// this exists.
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <errno.h>
int main(int argc, char *argv[])
{
if(argc != 2) {
printf("Usage: %s PATH\n", argv[0]);
printf("Run getdents(2) on PATH in a 100ms loop\n");
exit(1);
}
const char *path = argv[1];
for (int i = 1 ; ; i ++ ) {
int fd = open(path, O_RDONLY);
if (fd == -1) {
perror("open");
exit(1);
}
char tmp[10000];
int sum = 0;
printf("%3d: getdents64: ", i);
for ( ; ; ) {
int n = syscall(SYS_getdents64, fd, tmp, sizeof(tmp));
printf("n=%d; ", n);
if (n <= 0) {
printf("errno=%d total %d bytes\n", errno, sum);
if (n < 0) {
exit(1);
}
break;
}
sum += n;
}
close(fd);
usleep(100000);
}
}
|
the_stack_data/118038.c | /* This testcase caused ICE because gcc was not able to add instructions
on edge from ENTRY block successor to itself. */
/* { dg-do compile } */
/* { dg-options "-O3 -fssa" } */
struct A { int a1; int a2; };
struct B { long int b[32]; };
extern int bar (struct B *, struct A *);
int
foo (struct B x)
{
struct A a, b;
struct B c;
int d;
while (1)
{
a.a1 = 0;
a.a2 = 0;
b = a;
c = x;
d = bar (&c, &b);
if (d >= 0)
return d;
}
return 0;
}
|
the_stack_data/617733.c | /*
Bilhetes Falsos
https://www.urionlinejudge.com.br/judge/pt/problems/view/1318
*/
#include <stdio.h>
#include <stdlib.h>
#define NUMERO_MAXIMO_DE_BILHETES 20000
int diff(const void *a, const void *b);
int main (void) {
int N, M,
BILHETES[NUMERO_MAXIMO_DE_BILHETES];
while (scanf("%d %d", &N, &M), N != 0 && M != 0) {
int i;
int quantidadeDeBilhetesRepetidos = 0;
for (i = 0; i < M; i++) {
scanf("%d", BILHETES + i);
}
qsort(BILHETES, M, sizeof(int), diff);
i = 0;
while (i < M) {
int bilhete = BILHETES[i++];
int repetiu = 0;
while (bilhete == BILHETES[i]) {
repetiu = 1;
i++;
}
if (repetiu) {
quantidadeDeBilhetesRepetidos++;
}
}
printf("%d\n", quantidadeDeBilhetesRepetidos);
}
return 0;
}
int diff(const void *a, const void *b) {
const int *ia = a;
const int *ib = b;
return *ia - *ib;
}
|
the_stack_data/10589.c | #ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/THTensorLapack.c"
#else
/*
Check if self is transpose of a contiguous matrix
*/
static int THTensor_(isTransposedContiguous)(THTensor *self)
{
return self->stride[0] == 1 && self->stride[1] == self->size[0];
}
/*
If a matrix is a regular contiguous matrix, make sure it is transposed
because this is what we return from Lapack calls.
*/
static void THTensor_(checkTransposed)(THTensor *self)
{
if(THTensor_(isContiguous)(self))
THTensor_(transpose)(self, NULL, 0, 1);
return;
}
/*
newContiguous followed by transpose
Similar to (newContiguous), but checks if the transpose of the matrix
is contiguous and also limited to 2D matrices.
*/
static THTensor *THTensor_(newTransposedContiguous)(THTensor *self)
{
THTensor *tensor;
if(THTensor_(isTransposedContiguous)(self))
{
THTensor_(retain)(self);
tensor = self;
}
else
{
tensor = THTensor_(newContiguous)(self);
THTensor_(transpose)(tensor, NULL, 0, 1);
}
return tensor;
}
/*
Given the result tensor and src tensor, decide if the lapack call should use the
provided result tensor or should allocate a new space to put the result in.
The returned tensor have to be freed by the calling function.
nrows is required, because some lapack calls, require output space smaller than
input space, like underdetermined gels.
*/
static THTensor *THTensor_(checkLapackClone)(THTensor *result, THTensor *src, int nrows)
{
/* check if user wants to reuse src and if it is correct shape/size */
if (src == result && THTensor_(isTransposedContiguous)(src) && src->size[1] == nrows)
THTensor_(retain)(result);
else if(src == result || result == NULL) /* in this case, user wants reuse of src, but its structure is not OK */
result = THTensor_(new)();
else
THTensor_(retain)(result);
return result;
}
/*
Same as cloneColumnMajor, but accepts nrows argument, because some lapack calls require
the resulting tensor to be larger than src.
*/
static THTensor *THTensor_(cloneColumnMajorNrows)(THTensor *self, THTensor *src, int nrows)
{
THTensor *result;
THTensor *view;
if (src == NULL)
src = self;
result = THTensor_(checkLapackClone)(self, src, nrows);
if (src == result)
return result;
THTensor_(resize2d)(result, src->size[1], nrows);
THTensor_(checkTransposed)(result);
if (src->size[0] == nrows)
THTensor_(copy)(result, src);
else
{
view = THTensor_(newNarrow)(result, 0, 0, src->size[0]);
THTensor_(copy)(view, src);
THTensor_(free)(view);
}
return result;
}
/*
Create a clone of src in self column major order for use with Lapack.
If src == self, a new tensor is allocated, in any case, the return tensor should be
freed by calling function.
*/
static THTensor *THTensor_(cloneColumnMajor)(THTensor *self, THTensor *src)
{
return THTensor_(cloneColumnMajorNrows)(self, src, src->size[0]);
}
void THTensor_(gesv)(THTensor *rb_, THTensor *ra_, THTensor *b, THTensor *a)
{
if (a == NULL) a = ra_;
if (b == NULL) b = rb_;
THArgCheck(a->nDimension == 2, 2, "A should be 2 dimensional");
THArgCheck(b->nDimension == 2, 1, "B should be 2 dimensional");
THArgCheck(a->size[0] == a->size[1], 2, "A should be square");
THArgCheck(a->size[0] == b->size[0], 2, "A,b size incompatible");
int n, nrhs, lda, ldb, info;
THIntTensor *ipiv;
THTensor *ra__; // working version of A matrix to be passed into lapack GELS
THTensor *rb__; // working version of B matrix to be passed into lapack GELS
ra__ = THTensor_(cloneColumnMajor)(ra_, a);
rb__ = THTensor_(cloneColumnMajor)(rb_, b);
n = (int)ra__->size[0];
nrhs = (int)rb__->size[1];
lda = n;
ldb = n;
ipiv = THIntTensor_newWithSize1d((long)n);
THLapack_(gesv)(n, nrhs,
THTensor_(data)(ra__), lda, THIntTensor_data(ipiv),
THTensor_(data)(rb__), ldb, &info);
THLapackCheck("Lapack Error in %s : U(%d,%d) is zero, singular U.", "gesv", info, info);
THTensor_(freeCopyTo)(ra__, ra_);
THTensor_(freeCopyTo)(rb__, rb_);
THIntTensor_free(ipiv);
}
void THTensor_(trtrs)(THTensor *rb_, THTensor *ra_, THTensor *b, THTensor *a,
const char *uplo, const char *trans, const char *diag)
{
if (a == NULL) a = ra_;
if (b == NULL) b = rb_;
THArgCheck(a->nDimension == 2, 2, "A should be 2 dimensional");
THArgCheck(b->nDimension == 2, 1, "A should be 2 dimensional");
THArgCheck(a->size[0] == a->size[1], 2, "A should be square");
THArgCheck(b->size[0] == a->size[0], 2, "A,b size incompatible");
int n, nrhs, lda, ldb, info;
THTensor *ra__; // working version of A matrix to be passed into lapack TRTRS
THTensor *rb__; // working version of B matrix to be passed into lapack TRTRS
ra__ = THTensor_(cloneColumnMajor)(ra_, a);
rb__ = THTensor_(cloneColumnMajor)(rb_, b);
n = (int)ra__->size[0];
nrhs = (int)rb__->size[1];
lda = n;
ldb = n;
THLapack_(trtrs)(uplo[0], trans[0], diag[0], n, nrhs,
THTensor_(data)(ra__), lda,
THTensor_(data)(rb__), ldb, &info);
THLapackCheck("Lapack Error in %s : A(%d,%d) is zero, singular A", "trtrs", info, info);
THTensor_(freeCopyTo)(ra__, ra_);
THTensor_(freeCopyTo)(rb__, rb_);
}
void THTensor_(gels)(THTensor *rb_, THTensor *ra_, THTensor *b, THTensor *a)
{
// Note that a = NULL is interpreted as a = ra_, and b = NULL as b = rb_.
if (a == NULL) a = ra_;
if (b == NULL) b = rb_;
THArgCheck(a->nDimension == 2, 2, "A should be 2 dimensional");
THArgCheck(b->nDimension == 2, 1, "B should be 2 dimensional");
THArgCheck(a->size[0] == b->size[0], 2, "size incompatible A,b");
int m, n, nrhs, lda, ldb, info, lwork;
THTensor *work = NULL;
real wkopt = 0;
THTensor *ra__ = NULL; // working version of A matrix to be passed into lapack GELS
THTensor *rb__ = NULL; // working version of B matrix to be passed into lapack GELS
ra__ = THTensor_(cloneColumnMajor)(ra_, a);
m = ra__->size[0];
n = ra__->size[1];
lda = m;
ldb = (m > n) ? m : n;
rb__ = THTensor_(cloneColumnMajorNrows)(rb_, b, ldb);
nrhs = rb__->size[1];
info = 0;
/* get optimal workspace size */
THLapack_(gels)('N', m, n, nrhs, THTensor_(data)(ra__), lda,
THTensor_(data)(rb__), ldb,
&wkopt, -1, &info);
lwork = (int)wkopt;
work = THTensor_(newWithSize1d)(lwork);
THLapack_(gels)('N', m, n, nrhs, THTensor_(data)(ra__), lda,
THTensor_(data)(rb__), ldb,
THTensor_(data)(work), lwork, &info);
THLapackCheck("Lapack Error in %s : The %d-th diagonal element of the triangular factor of A is zero", "gels", info);
/* rb__ is currently ldb by nrhs; resize it to n by nrhs */
rb__->size[0] = n;
if (rb__ != rb_)
THTensor_(resize2d)(rb_, n, nrhs);
THTensor_(freeCopyTo)(ra__, ra_);
THTensor_(freeCopyTo)(rb__, rb_);
THTensor_(free)(work);
}
void THTensor_(geev)(THTensor *re_, THTensor *rv_, THTensor *a_, const char *jobvr)
{
int n, lda, lwork, info, ldvr;
THTensor *work, *wi, *wr, *a;
real wkopt;
real *rv_data;
long i;
THTensor *re__ = NULL;
THTensor *rv__ = NULL;
THArgCheck(a_->nDimension == 2, 1, "A should be 2 dimensional");
THArgCheck(a_->size[0] == a_->size[1], 1,"A should be square");
/* we want to definitely clone a_ for geev*/
a = THTensor_(cloneColumnMajor)(NULL, a_);
n = a->size[0];
lda = n;
wi = THTensor_(newWithSize1d)(n);
wr = THTensor_(newWithSize1d)(n);
rv_data = NULL;
ldvr = 1;
if (*jobvr == 'V')
{
THTensor_(resize2d)(rv_,n,n);
/* guard against someone passing a correct size, but wrong stride */
rv__ = THTensor_(newTransposedContiguous)(rv_);
rv_data = THTensor_(data)(rv__);
ldvr = n;
}
THTensor_(resize2d)(re_,n,2);
re__ = THTensor_(newContiguous)(re_);
/* get optimal workspace size */
THLapack_(geev)('N', jobvr[0], n, THTensor_(data)(a), lda, THTensor_(data)(wr), THTensor_(data)(wi),
NULL, 1, rv_data, ldvr, &wkopt, -1, &info);
lwork = (int)wkopt;
work = THTensor_(newWithSize1d)(lwork);
THLapack_(geev)('N', jobvr[0], n, THTensor_(data)(a), lda, THTensor_(data)(wr), THTensor_(data)(wi),
NULL, 1, rv_data, ldvr, THTensor_(data)(work), lwork, &info);
THLapackCheck(" Lapack Error in %s : %d off-diagonal elements of an didn't converge to zero", "geev", info);
{
real *re_data = THTensor_(data)(re__);
real *wi_data = THTensor_(data)(wi);
real *wr_data = THTensor_(data)(wr);
for (i=0; i<n; i++)
{
re_data[2*i] = wr_data[i];
re_data[2*i+1] = wi_data[i];
}
}
if (*jobvr == 'V')
{
THTensor_(checkTransposed)(rv_);
THTensor_(freeCopyTo)(rv__, rv_);
}
THTensor_(freeCopyTo)(re__, re_);
THTensor_(free)(a);
THTensor_(free)(wi);
THTensor_(free)(wr);
THTensor_(free)(work);
}
void THTensor_(syev)(THTensor *re_, THTensor *rv_, THTensor *a, const char *jobz, const char *uplo)
{
if (a == NULL) a = rv_;
THArgCheck(a->nDimension == 2, 1, "A should be 2 dimensional");
int n, lda, lwork, info;
THTensor *work;
real wkopt;
THTensor *rv__ = NULL;
THTensor *re__ = NULL;
rv__ = THTensor_(cloneColumnMajor)(rv_, a);
n = rv__->size[0];
lda = n;
THTensor_(resize1d)(re_,n);
re__ = THTensor_(newContiguous)(re_);
/* get optimal workspace size */
THLapack_(syev)(jobz[0], uplo[0], n, THTensor_(data)(rv__), lda,
THTensor_(data)(re_), &wkopt, -1, &info);
lwork = (int)wkopt;
work = THTensor_(newWithSize1d)(lwork);
THLapack_(syev)(jobz[0], uplo[0], n, THTensor_(data)(rv__), lda,
THTensor_(data)(re_), THTensor_(data)(work), lwork, &info);
THLapackCheck("Lapack Error %s : %d off-diagonal elements didn't converge to zero", "syev", info);
THTensor_(freeCopyTo)(rv__, rv_);
THTensor_(freeCopyTo)(re__, re_);
THTensor_(free)(work);
}
void THTensor_(gesvd)(THTensor *ru_, THTensor *rs_, THTensor *rv_, THTensor *a, const char* jobu)
{
THTensor *ra_ = THTensor_(new)();
THTensor_(gesvd2)(ru_, rs_, rv_, ra_, a, jobu);
THTensor_(free)(ra_);
}
void THTensor_(gesvd2)(THTensor *ru_, THTensor *rs_, THTensor *rv_, THTensor *ra_, THTensor *a, const char* jobu)
{
if (a == NULL) a = ra_;
THArgCheck(a->nDimension == 2, 1, "A should be 2 dimensional");
int k,m, n, lda, ldu, ldvt, lwork, info;
THTensor *work;
real wkopt;
THTensor *ra__ = NULL;
THTensor *ru__ = NULL;
THTensor *rs__ = NULL;
THTensor *rv__ = NULL;
ra__ = THTensor_(cloneColumnMajor)(ra_, a);
m = ra__->size[0];
n = ra__->size[1];
k = (m < n ? m : n);
lda = m;
ldu = m;
ldvt = n;
THTensor_(resize1d)(rs_,k);
THTensor_(resize2d)(rv_,ldvt,n);
if (*jobu == 'A')
THTensor_(resize2d)(ru_,m,ldu);
else
THTensor_(resize2d)(ru_,k,ldu);
THTensor_(checkTransposed)(ru_);
/* guard against someone passing a correct size, but wrong stride */
ru__ = THTensor_(newTransposedContiguous)(ru_);
rs__ = THTensor_(newContiguous)(rs_);
rv__ = THTensor_(newContiguous)(rv_);
THLapack_(gesvd)(jobu[0],jobu[0],
m,n,THTensor_(data)(ra__),lda,
THTensor_(data)(rs__),
THTensor_(data)(ru__),
ldu,
THTensor_(data)(rv__), ldvt,
&wkopt, -1, &info);
lwork = (int)wkopt;
work = THTensor_(newWithSize1d)(lwork);
THLapack_(gesvd)(jobu[0],jobu[0],
m,n,THTensor_(data)(ra__),lda,
THTensor_(data)(rs__),
THTensor_(data)(ru__),
ldu,
THTensor_(data)(rv__), ldvt,
THTensor_(data)(work),lwork, &info);
THLapackCheck(" Lapack Error %s : %d superdiagonals failed to converge.", "gesvd", info);
THTensor_(freeCopyTo)(ru__, ru_);
THTensor_(freeCopyTo)(rs__, rs_);
THTensor_(freeCopyTo)(rv__, rv_);
THTensor_(freeCopyTo)(ra__, ra_);
THTensor_(free)(work);
}
void THTensor_(getri)(THTensor *ra_, THTensor *a)
{
if (a == NULL) a = ra_;
THArgCheck(a->nDimension == 2, 1, "A should be 2 dimensional");
THArgCheck(a->size[0] == a->size[1], 1, "A should be square");
int m, n, lda, info, lwork;
real wkopt;
THIntTensor *ipiv;
THTensor *work;
THTensor *ra__ = NULL;
ra__ = THTensor_(cloneColumnMajor)(ra_, a);
m = ra__->size[0];
n = ra__->size[1];
lda = m;
ipiv = THIntTensor_newWithSize1d((long)m);
/* Run LU */
THLapack_(getrf)(n, n, THTensor_(data)(ra__), lda, THIntTensor_data(ipiv), &info);
THLapackCheck("Lapack Error %s : U(%d,%d) is 0, U is singular","getrf", info, info);
/* Run inverse */
THLapack_(getri)(n, THTensor_(data)(ra__), lda, THIntTensor_data(ipiv), &wkopt, -1, &info);
lwork = (int)wkopt;
work = THTensor_(newWithSize1d)(lwork);
THLapack_(getri)(n, THTensor_(data)(ra__), lda, THIntTensor_data(ipiv), THTensor_(data)(work), lwork, &info);
THLapackCheck("Lapack Error %s : U(%d,%d) is 0, U is singular","getri", info, info);
THTensor_(freeCopyTo)(ra__, ra_);
THTensor_(free)(work);
THIntTensor_free(ipiv);
}
void THTensor_(potrf)(THTensor *ra_, THTensor *a)
{
if (a == NULL) a = ra_;
THArgCheck(a->nDimension == 2, 1, "A should be 2 dimensional");
THArgCheck(a->size[0] == a->size[1], 1, "A should be square");
int n, lda, info;
char uplo = 'U';
THTensor *ra__ = NULL;
ra__ = THTensor_(cloneColumnMajor)(ra_, a);
n = ra__->size[0];
lda = n;
/* Run Factorization */
THLapack_(potrf)(uplo, n, THTensor_(data)(ra__), lda, &info);
THLapackCheck("Lapack Error %s : A(%d,%d) is 0, A cannot be factorized", "potrf", info, info);
/* Build full upper-triangular matrix */
{
real *p = THTensor_(data)(ra__);
long i,j;
for (i=0; i<n; i++) {
for (j=i+1; j<n; j++) {
p[i*n+j] = 0;
}
}
}
THTensor_(freeCopyTo)(ra__, ra_);
}
void THTensor_(potri)(THTensor *ra_, THTensor *a)
{
if (a == NULL) a = ra_;
THArgCheck(a->nDimension == 2, 1, "A should be 2 dimensional");
THArgCheck(a->size[0] == a->size[1], 1, "A should be square");
int n, lda, info;
char uplo = 'U';
THTensor *ra__ = NULL;
ra__ = THTensor_(cloneColumnMajor)(ra_, a);
n = ra__->size[0];
lda = n;
/* Run Factorization */
THLapack_(potrf)(uplo, n, THTensor_(data)(ra__), lda, &info);
THLapackCheck("Lapack Error %s : A(%d,%d) is 0, A cannot be factorized", "potrf", info, info);
/* Run inverse */
THLapack_(potri)(uplo, n, THTensor_(data)(ra__), lda, &info);
THLapackCheck("Lapack Error %s : A(%d,%d) is 0, A cannot be factorized", "potri", info, info);
/* Build full matrix */
{
real *p = THTensor_(data)(ra__);
long i,j;
for (i=0; i<n; i++) {
for (j=i+1; j<n; j++) {
p[i*n+j] = p[j*n+i];
}
}
}
THTensor_(freeCopyTo)(ra__, ra_);
}
/*
Perform a QR decomposition of a matrix.
In LAPACK, two parts of the QR decomposition are implemented as two separate
functions: geqrf and orgqr. For flexibility and efficiency, these are wrapped
directly, below - but to make the common usage convenient, we also provide
this function, which calls them both and returns the results in a more
intuitive form.
Args:
* `rq_` - result Tensor in which to store the Q part of the decomposition.
* `rr_` - result Tensor in which to store the R part of the decomposition.
* `a` - input Tensor; the matrix to decompose.
*/
void THTensor_(qr)(THTensor *rq_, THTensor *rr_, THTensor *a)
{
int m = a->size[0];
int n = a->size[1];
int k = (m < n ? m : n);
THTensor *ra_ = THTensor_(new)();
THTensor *rtau_ = THTensor_(new)();
THTensor *rr__ = THTensor_(new)();
THTensor_(geqrf)(ra_, rtau_, a);
THTensor_(resize2d)(rr__, k, ra_->size[1]);
THTensor_(narrow)(rr__, ra_, 0, 0, k);
THTensor_(triu)(rr_, rr__, 0);
THTensor_(resize2d)(rq_, ra_->size[0], k);
THTensor_(orgqr)(rq_, ra_, rtau_);
THTensor_(narrow)(rq_, rq_, 1, 0, k);
THTensor_(free)(ra_);
THTensor_(free)(rtau_);
THTensor_(free)(rr__);
}
/*
The geqrf function does the main work of QR-decomposing a matrix.
However, rather than producing a Q matrix directly, it produces a sequence of
elementary reflectors which may later be composed to construct Q - for example
with the orgqr function, below.
Args:
* `ra_` - Result matrix which will contain:
i) The elements of R, on and above the diagonal.
ii) Directions of the reflectors implicitly defining Q.
* `rtau_` - Result tensor which will contain the magnitudes of the reflectors
implicitly defining Q.
* `a` - Input matrix, to decompose. If NULL, `ra_` is used as input.
For further details, please see the LAPACK documentation.
*/
void THTensor_(geqrf)(THTensor *ra_, THTensor *rtau_, THTensor *a)
{
if (a == NULL) ra_ = a;
THArgCheck(a->nDimension == 2, 1, "A should be 2 dimensional");
THTensor *ra__ = NULL;
/* Prepare the input for LAPACK, making a copy if necessary. */
ra__ = THTensor_(cloneColumnMajor)(ra_, a);
int m = ra__->size[0];
int n = ra__->size[1];
int k = (m < n ? m : n);
int lda = m;
THTensor_(resize1d)(rtau_, k);
/* Dry-run to query the suggested size of the workspace. */
int info = 0;
real wkopt = 0;
THLapack_(geqrf)(m, n, THTensor_(data)(ra__), lda,
THTensor_(data)(rtau_),
&wkopt, -1, &info);
/* Allocate the workspace and call LAPACK to do the real work. */
int lwork = (int)wkopt;
THTensor *work = THTensor_(newWithSize1d)(lwork);
THLapack_(geqrf)(m, n, THTensor_(data)(ra__), lda,
THTensor_(data)(rtau_),
THTensor_(data)(work), lwork, &info);
THLapackCheck("Lapack Error %s : unknown Lapack error. info = %i", "geqrf", info);
THTensor_(freeCopyTo)(ra__, ra_);
THTensor_(free)(work);
}
/*
The orgqr function allows reconstruction of a matrix Q with orthogonal
columns, from a sequence of elementary reflectors, such as is produced by the
geqrf function.
Args:
* `ra_` - result Tensor, which will contain the matrix Q.
* `a` - input Tensor, which should be a matrix with the directions of the
elementary reflectors below the diagonal. If NULL, `ra_` is used as
input.
* `tau` - input Tensor, containing the magnitudes of the elementary
reflectors.
For further details, please see the LAPACK documentation.
*/
void THTensor_(orgqr)(THTensor *ra_, THTensor *a, THTensor *tau)
{
if (a == NULL) a = ra_;
THArgCheck(a->nDimension == 2, 1, "A should be 2 dimensional");
THTensor *ra__ = NULL;
ra__ = THTensor_(cloneColumnMajor)(ra_, a);
int m = ra__->size[0];
int n = ra__->size[1];
int k = tau->size[0];
int lda = m;
/* Dry-run to query the suggested size of the workspace. */
int info = 0;
real wkopt = 0;
THLapack_(orgqr)(m, k, k, THTensor_(data)(ra__), lda,
THTensor_(data)(tau),
&wkopt, -1, &info);
/* Allocate the workspace and call LAPACK to do the real work. */
int lwork = (int)wkopt;
THTensor *work = THTensor_(newWithSize1d)(lwork);
THLapack_(orgqr)(m, k, k, THTensor_(data)(ra__), lda,
THTensor_(data)(tau),
THTensor_(data)(work), lwork, &info);
THLapackCheck(" Lapack Error %s : unknown Lapack error. info = %i", "orgqr", info);
THTensor_(freeCopyTo)(ra__, ra_);
THTensor_(free)(work);
}
#endif
|
the_stack_data/97012182.c | #include <stdio.h>
#include <unistd.h> // for usleep()
#include <stdlib.h> // for exit()
int main() {
system("setterm -cursor off"); // this is a linux command hides the block cursor as to not block the animation
char arr[5] = {'|','/','-','\\'}; // this is the array of characters that will be traversed to form a spinning circle.
for (int z = 0; z < 3; z++) { // this makes the actual loop spin more than once
for (int x = 0; x < 4; x++) { // this is the actual spinning animation loop
fflush(stdout); // clears at least that character space.
char y = arr[x]; // a new printable variable will cycle through all of the array characters
printf("\b%c", y); // clear, then print y's character every loop
usleep(200000); // milliseconds break so the characters can slowly appear to spin
}
}
printf("\n");
system("setterm -cursor on"); // turn cursor back on before quitting
exit(0);
}
|
the_stack_data/159516264.c | // This test shows how sanatization works. By placing
// #pragma leek sanatized before x+=5;, we are telling the
// IFC system that x is now trusted data.
// Normally, of course, sanitization would be on a
// function that would actually process the data in some way.
#include <stdio.h>
char newchar() {
char c = 0;
#pragma leek tainted
c = getchar();
return c;
}
int main() {
int x;
x=11;
x = newchar();
#pragma leek sanatized
x += 5;
#pragma leek trusted
return x;
}
|
the_stack_data/184518186.c | /*Exercise 2 - Selection
Write a program to calculate the amount to be paid for a rented vehicle.
• Input the distance the van has travelled
• The first 30 km is at a rate of 50/= per km.
• The remaining distance is calculated at the rate of 40/= per km.
e.g.
Distance -> 20
Amount = 20 x 50 = 1000
Distance -> 50
Amount = 30 x 50 + (50-30) x 40 = 2300*/
#include <stdio.h>
int main() {
float distance , Amount;
printf("Input the distance the van has travelled (km) : ");
scanf("%f" , &distance); //read distance
if(distance > 30)
{
Amount = 30 * 50 + (distance - 30) * 40; //calculate amount
printf("Amount : %.2f" , Amount);
}
else
{
Amount = distance * 50; //calculate amount
printf("Amount : %.2f" , Amount);
}
return 0;
}
|
the_stack_data/86849.c |
int main(void){
5 ? (void)5 : (signed char)6;
}
|
the_stack_data/111076906.c | /**
* @file sensor3.c
* @brief definition to function uses to manage sensor 0 packet that will be framed and send through UWB
* @note THIS FILE IS IMPLEMENTATION DEPENDANT, AND MUST MATCH SYSTEM, HW, ENVIRONMENT,ETC...
* @author [email protected]
* @date 24/02/2015
*/
/*
* Copyright (C) Bespoon 2014-2015. No Part of the source code shall be
* reproduced, transmitted, distributed, used nor modified in any way without
* the express prior written authorization of Bespoon.
*/
#ifdef CONFIG_RTLS_PROTOCOL
#include <ranging_data_payload.h>
/************************************** SENSOR 3 SPECIFIC IMPLEMENTATION *************/
OSAL_u8 s3_data[2]={'s','3'};
OSAL_void sensor3_payload_init()
{
//TODO: This is called at protocol start. It inits all about sensor 3
}
OSAL_void sensor3_payload_deinit()
{
//TODO: This is called at protocol stop. It deinits all about sensor 3
}
OSAL_void sensor3_payload_getData(OSAL_u8** data,OSAL_u16* dataSizeinBits)
{
//TODO
//This function MUST only return a buffer to stored data.
//This function can be called in order to get fixed size of Ext data
//sensor3_updateData will do the job to get the data
if(data) *data=&s3_data[0];
if(dataSizeinBits) *dataSizeinBits=16;
}
OSAL_void sensor3_payload_updateData()
{
//TODO. Store data of sensor 3 in memory. this function is called within the main loop
}
#endif /*#ifdef CONFIG_RTLS_PROTOCOL*/
|
the_stack_data/25139091.c | #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define oops(m,x) {perror(m); exit(x);}
int make_dgram_server_socket(int);
int get_internet_address(char *, int, int *, struct sockaddr_in *);
void say_who_called(struct sockaddr_in *);
int main(int ac, char **av) {
int port;
int sock;
char buf[BUFSIZ];
size_t msglen;
struct sockaddr_in saddr;
socklen_t saddrlen;
if (ac == 1 || (port = atoi(av[1])) <= 0) {
fprintf(stderr, "usage: dgrecv portnumber\n");
exit(1);
}
if ((sock = make_dgram_server_socket(port)) == -1)
oops("cannot make socket", 2);
saddrlen = sizeof(saddr);
while ((msglen = recvfrom(sock, buf, BUFSIZ, 0, &saddr, &saddrlen)) > 0) {
buf[msglen] = '\0';
printf("dgrecv: got a message: %s\n", buf);
say_who_called(&saddr);
}
return 0;
}
void say_who_called(struct sockaddr_in *addrp) {
char host[BUFSIZ];
int port;
get_internet_address(host, BUFSIZ, &port, addrp);
printf("from: %s:%d\n", host, port);
}
|
the_stack_data/813220.c | #include <stdio.h>
int main(int argc, char **argv)
{
printf("Hello World! NaNNaNaNaNa\n");
return 0;
}
|
the_stack_data/153267203.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char** argv)
{
if(argc < 3){
printf("Enough arguments not provided.\n");
exit (0);
}
int PORTN = atoi (argv[2]);
struct sockaddr_in address;
int n,sockfd;
int len;char buff[100];
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0){
printf("\nError in Socket");
exit(0);
}
else printf("Socket is Opened.\n");
bzero(&address,sizeof(address));
address.sin_family=AF_INET;
address.sin_port=htons(PORTN);
if(inet_pton(AF_INET, argv[1], &address.sin_addr) <= 0){
printf ("Invalid Address.\n");
return -1;
}
if(connect(sockfd,(struct sockaddr*)&address,sizeof(address))<0){
printf("\nError in connection failed");
exit(0);
}
else{
printf("Connected successfully.\n");
if(n=read(sockfd,buff,sizeof(buff))<0){
printf("\nError in Reading");
exit(0);
}
else{
printf("The local date and time is: %s", buff);
}
}
return 0;
}
/* Commands: gcc 190020020_time_client.c -o client
./client 192.168.29.165 500000020
Output:
Socket is Opened.
Connected successfully.
The local date and time is: Sun Mar 28 15:33:52 2021
*/
|
the_stack_data/25138319.c | #include<stdio.h>
#include<pthread.h>
// define the number of threads
#define NTHREADS 100
int vetor[NTHREADS];
// function that the thread will perform
void * task (void * arg) {
int ident = * (int *) arg;
vetor[ident] = ident + 1;
printf("I'm the thread %d!\n", ident + 1);
pthread_exit(NULL);
}
// main function
int main(void) {
// thread id
pthread_t tid[NTHREADS];
// local thread id
int ident[NTHREADS];
int i;
// create all threads
for(i = 0; i < NTHREADS; i++) {
ident[i] = i;
// create a new thread
if (pthread_create(&tid[i], NULL, task, (void *)&ident[i]))
printf("ERRO --pthread_create\n");
exit(-1);
}
// waits for all threads to finish
for(i = 0; i < NTHREADS; i++) {
if (pthread_join(tid[i], NULL))
printf("ERRO --pthread_join\n");
}
// send hello world message
printf("I'm the main thread!\n");
for(i = 0; i < NTHREADS; i++) {
printf("%d ", vetor[i]);
}
// disconnect the end of the mother from the end of the program
pthread_exit(NULL);
return 0;
} |
the_stack_data/28383.c | /*
** mmapdemo.c -- demonstrates memory mapped files lamely.
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <errno.h>
int main(int argc, char *argv[])
{
int fd, // id del archivo cargado en memoria
offset; // de donde vamos a empezar a leer el archivo (numero de char)
char *data;
struct stat sbuf;
if (argc != 2) {
fprintf(stderr, "usage: mmaptest offset\n");
exit(1);
}
// Cargamos archivo a memoria con syscall open()
if ((fd = open("mmaptest.c", O_RDONLY)) == -1) {
perror("open error");
exit(1);
}
// Saca estadisticas de archivo con stat() y la guardara a &sbuf
if (stat("mmaptest.c", &sbuf) == -1) {
perror("stat");
exit(1);
}
offset = atoi(argv[1]);
if (offset < 0 || offset > sbuf.st_size-1) {
fprintf(stderr, "mmaptest: offset must be in the range 0-%ld\n", sbuf.st_size-1);
exit(1);
}
// Funcion mmap() creara una direccion de memoria y la inicializara con el archivo
// Bandera MAP_SHARED especifica que sera un archivo compartido, solo habra un archivo
// fd (el archivo) se pone en la direccion de memoria
if ((data = mmap((caddr_t)0, sbuf.st_size, PROT_READ, MAP_SHARED, fd, 0)) == (caddr_t)(-1)) {
perror("mmap");
exit(1);
}
printf("byte at offset %d is '%c'\n", offset, data[offset]);
return 0;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.