file
stringlengths 18
26
| data
stringlengths 2
1.05M
|
---|---|
the_stack_data/251324.c |
/*5) Ler um vetor V de 20 posições (aceitar somente números positivos). Escrever a seguir
o valor do maior elemento de V e a respectiva posição que ele ocupa no vetor.*/
#include <stdio.h>
#define TAM 20
int main()
{
float v[TAM], maior = -9999;
int i, a;
for (i = 0; i < TAM; i++)
{
printf("Digite o %dº valor: ", i+1);
scanf("%f", &v[i]);
if (v[i] > maior)
{
maior = v[i];
a = i;
}
}
printf("\nO maior numero é %g e está na %dº posição", maior, a+1);
return 0;
}
|
the_stack_data/118103.c | #include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <sys/types.h>
bool binary64_to_integer(uint64_t value, long long *n)
{
if (!(value << 1)) {
*n = 0;
return true;
}
if (value == 0xc3e0000000000000) {
*n = LLONG_MIN;
return true;
}
size_t bits = 8 * sizeof *n;
int exp = (int)(value >> 52 & 0x7ff) - 1023;
if (exp < 0 || exp >= bits - 1)
return false;
bool negative = value >> 63;
uint64_t mask = ~0ULL >> 12;
uint64_t significand = (value & mask) | 1ULL << 52;
if (exp >= 52) {
*n = significand << (exp - 52);
if (negative)
*n = -*n;
return true;
}
if ((value & (mask >> exp)) == 0) {
*n = significand >> (52 - exp);
if (negative)
*n = -*n;
return true;
}
return false;
}
bool binary64_to_unsigned(uint64_t value, unsigned long long *n)
{
if (!(value << 1)) {
*n = 0;
return true;
}
bool negative = value >> 63;
if (negative)
return false;
size_t bits = 8 * sizeof *n;
int exp = (int)(value >> 52 & 0x7ff) - 1023;
if (exp < 0 || exp >= bits)
return false;
uint64_t mask = ~0ULL >> 12;
uint64_t significand = (value & mask) | 1ULL << 52;
if (exp >= 52) {
*n = significand << (exp - 52);
return true;
}
if ((value & (mask >> exp)) == 0) {
*n = significand >> (52 - exp);
return true;
}
return false;
}
|
the_stack_data/358351.c | #include<stdio.h>
int main()
{
int n;
printf("Enter the size of the array: ");
scanf("%d",&n);
int array[n];
printf("Enter the %d numbers: ",n);
for(int i=0;i<n;i++)
{
scanf("%d",&array[i]);
}
printf("Entered numbers are: ");
for(int i=0;i<n;i++)
printf("%d\t",array[i]);
printf("\n");
return 0;
}
|
the_stack_data/150142540.c | #define PI 3.14159
#include <stdio.h>
int main() {
double A, B, C;
scanf("%lf %lf %lf", &A, &B, &C);
double tri_ret = (A * C) / 2;
double circ = PI * (C * C);
double trap = ((A + B) * C) / 2;
double quad = B * B;
double ret = A * B;
printf("TRIANGULO: %.3lf\n"
"CIRCULO: %.3lf\n"
"TRAPEZIO: %.3lf\n"
"QUADRADO: %.3lf\n"
"RETANGULO: %.3lf\n", tri_ret, circ, trap,
quad, ret);
return 0;
}
|
the_stack_data/212642547.c | #include<stdio.h>
#include<pthread.h>
void *hello_thread(void *arg)
{
printf("hello thread\n");
}
void *bye_thread(void *arg)
{
printf("bye thread\n");
}
void *greet_thread(void *arg)
{
printf("%s greet thread\n", arg);
}
int main(int argc, char const *argv[])
{
pthread_t helloID, byeID;
printf("Main thread: Before create hello thread\n");
pthread_create(&helloID, NULL, greet_thread, "hello");
pthread_create(&byeID, NULL, greet_thread, "bye");
pthread_join(helloID,NULL);
pthread_join(byeID, NULL);
printf("Main thread: After creating hello thread\n");
return 0;
} |
the_stack_data/279474.c | #include <stdio.h>
main ()
{
int num1, num2, num3;
char ch2;
num1 = 5;
num3 = 4;
printf("Please enter 1 number and 1 character: \n");
scanf("%d", &num2);
flushall();
scanf("%c", &ch2);
flushall();
printf("\nYou entered %d and %c\n", num2, ch2);
printf("The other numbers are %d, %d", num1, num3);
getchar();
} |
the_stack_data/130653.c | /*
* vtj1options.c - Set some terminal options on the VTJ-1 terminal.
* Probably not as portable as I'd like, but compiles and seems to run ok
* under both Linux and NetBSD 7.
*
* Copyright (c) 2017 Jeremy Dilatush
* 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.
*
* THIS SOFTWARE IS PROVIDED BY JEREMY DILATUSH 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 JEREMY DILATUSH 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
extern int vtj1check(int i, int o); /* in vtj1check.c */
static char *progname = "vtj1options";
static void
usage(void)
{
fprintf(stderr, "%s: sets VTJ-1 terminal specific options\n"
"USAGE: %s [OPTIONS]\n"
"OPTIONS for VTJ-1 specific modes:\n"
"\t-x/+x - don't/do show checkerboard glyph on some errors\n"
"\t-b/+b - don't/do show cursor as block instead of underline\n"
"\t-v/+v - don't/do flash screen to indicate bell\n"
"\t-a/+a - don't/do make sound to indicate bell\n"
"OPTIONS for modes defined by DEC historically:\n"
"\t-c/+c - disable/enable cursor keys mode (DECCKM)\n"
"\t-r/+r - disable/enable screenwise reverse video (DECSCNM)\n"
"\t-o/+o - disable/enable origin mode (DECOM)\n"
"\t-w/+w - disable/enable auto wrap mode (DECAWM)\n"
/* leaving out DECARM since it doesn't work on my keyboard */
"OPTIONS for modes defined by ANSI:\n"
"\t-l/+l - unlock/lock keyboard\n"
"\t-i/+i - disable/enable insert mode\n"
"\t-e/+e - disable/enable \"no local echo\" mode\n"
"\t-n/+n - disable/enable line feed / new line mode\n"
"\t +n - transmit both line feed and carriage return\n"
"\t -n - transmit only line feed or carriage return\n"
"OPTIONS to control %s operation:\n"
"\t-F - force operation, don't check for a VTJ-1 first\n"
"\t-D dev - use device 'dev' instead of NULL; example: /dev/ttyUSB1\n",
progname, progname, progname);
exit(1);
}
/* mode settings identified by +char or -char and sent to the terminal
* as ^[[...l (for -) or ^[[...h (for +).
*/
struct {
char ch;
char *seq;
int chosen; /* 0 if not chosen, '+' or '-' if chosen */
} modes1[] = {
{ 'x', "=1", 0 },
{ 'b', "=3", 0 },
{ 'v', "=4", 0 },
{ 'a', "=5", 0 },
{ 'c', "?1", 0 },
{ 'r', "?5", 0 },
{ 'o', "?6", 0 },
{ 'w', "?7", 0 },
{ 'l', "2", 0 },
{ 'i', "4", 0 },
{ 'e', "12", 0 },
{ 'n', "20", 0 },
{ -1, NULL, 0 }
};
static void dumb_putchar(int fd, int ch);
int
main(int argc, char **argv)
{
int i, j, a, ifd, ofd, none = 1;
int optff = 0;
char *optdd = NULL;
/* figure out what we're called */
if (argv && argv[0]) progname = argv[0];
/* process any command line arguments; not using getopt() due to
* the quirky +/- char syntax
*/
for (a = 1; a < argc; ++a) {
if (argv[a][0] == '-' && argv[a][1] == 'F' && argv[a][2] == '\0') {
optff = 1;
} else if (argv[a][0] == '-' && argv[a][1] == 'D' &&
argv[a][2] == '\0' && a + 1 < argc) {
a++;
optdd = argv[a];
} else if ((argv[a][0] == '+' || argv[a][0] == '-') &&
argv[a][1] != '\0' && argv[a][2] == '\0') {
for (i = 0; modes1[i].seq; ++i) {
if (modes1[i].ch == argv[a][1]) {
break;
}
}
if (modes1[i].seq) {
modes1[i].chosen = argv[a][0];
none = 0;
} else {
fprintf(stderr, "Unrecognized option character\r\n");
usage();
}
} else {
fprintf(stderr, "Unrecognized command line argument\r\n");
usage();
}
}
/* open the terminal */
if (optdd == NULL) {
ifd = STDIN_FILENO;
ofd = STDOUT_FILENO;
} else {
ifd = open(optdd, O_RDONLY);
if (ifd < 0) {
perror(optdd);
exit(1);
}
ofd = open(optdd, O_WRONLY);
if (ofd < 0) {
perror(optdd);
exit(1);
}
}
if (none) {
fprintf(stderr, "%s: not doing anything, no options specified\r\n",
progname);
usage();
}
/* check whether it's a VTJ-1, unless the user gave us -F */
if (!optff) {
if (!vtj1check(ifd, ofd)) {
fprintf(stderr, "\r\n"
"%s: Apparently terminal is not a VTJ-1; aborting\r\n"
"This check may be suppressed with the -F option\r\n",
progname);
exit(1);
}
}
/* issue the commands */
for (i = 0; modes1[i].seq; ++i) {
if (modes1[i].chosen) {
dumb_putchar(ofd, 27);
dumb_putchar(ofd, '[');
for (j = 0; modes1[i].seq[j]; ++j)
dumb_putchar(ofd, modes1[i].seq[j]);
dumb_putchar(ofd, (modes1[i].chosen == '+' ? 'h' : 'l'));
}
}
/* all done */
return(0);
}
/*
* dumb_putchar() - not very good but good enough for this purpose
*/
static void
dumb_putchar(int fd, int ch)
{
char buf[1];
int rv;
buf[0] = ch;
for (;;) {
rv = write(fd, buf, 1);
if (rv < 0) {
if (errno == EAGAIN || errno == EINTR) {
continue; /* retry */
} else {
return; /* fail */
}
} else {
return; /* succeed or fail, either way: done */
}
}
}
|
the_stack_data/1189782.c | #include <stdio.h>
#include <stdlib.h>
#define SWAP(a , b) do{int temp=a;a=b;b=temp;}while(0)
static void ssort(int *array , int n){
int i = 0,
j = 0,
pos = 0;
while(i<n){
pos = i;
j = i + 1;
while(j<n){
if(*(array + j) < *(array + pos)){
pos = j;
}
++j;
}
if(pos != i){
SWAP(*(array + i),
*(array + pos));
}
++i;
}
}
int main(int ac , char **av){
int n = ac - 1,
*arr = NULL,
*p = NULL;
if(!n){
printf("Usage: %s [NUMBERS.... ]\n" , *av);
return -1;
}
p = arr = calloc(n + 1 , sizeof(*arr));
++av;
while(*av){
*p++ = atoi(*av);
++av;
}
ssort(arr , n);
p = arr;
while(*p){
printf(" %d " , *p++);
}
putchar('\n');
free(arr);
return 0;
}
|
the_stack_data/117115.c | /*s: init9.c */
//@Scheck: def can actually be found initcode.c, but this file is in skip list
extern void startboot(char*, char**);
//@Scheck: entry point looked for by the linker 8l
void
_main(char *argv0)
{
startboot(argv0, &argv0);
}
/*e: init9.c */
|
the_stack_data/1249929.c | #include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
int horizontal = 0;
int depth = 0;
char buff[8];
int x_unites;
// forward X increases the horizontal position by X units.
// down X increases the depth by X units.
// up X decreases the depth by X units.
FILE *fp;
fp = fopen("input.txt", "r");
while(fscanf(fp, "%s %d", buff, &x_unites) != EOF){
//printf("%s %d\n", buff, x_unites);
//printf("Hoz: %d, Depth: %d\n", horizontal, depth);
if(strcmp(buff, "forward") == 0){
horizontal += x_unites;
//printf("horiz: %d\n", horizontal);
}
else if(strcmp(buff, "up") == 0){
depth -= x_unites;
//printf("Up: %d\n", depth);
}
else if(strcmp(buff, "down") == 0){
depth += x_unites;
//printf("Down: %d\n", depth);
}
}
printf("Horiz * Depth = %d\n", horizontal*depth);
fclose(fp);
return 0;
}
|
the_stack_data/23575460.c | /*
Raju and His Trip Problem Code: VALTRISolvedSubmit
Raju is planning to visit his favourite restaurant. He shall travel to it by bus. Only the buses whose numbers are divisible by 5 or by 6 shall take him to his destination. You are given a bus number N. Find if Raju can take the bus or not. Print YES if he can take the bus, otherwise print NO.
Input:
The first and only line of the input shall contain an integer N, denoting the bus number.
Output:
Print YES if Raju can take that bus, else print NO.
Constraints
1≤N≤106
Sample Input 1:
60
Sample Output 1:
YES
Sample Input 2:
16
Sample Output 2:
NO
Sample Input 3:
20
Sample Output 3:
YES
EXPLANATION:
In the first example, 60 is divisible by 5 and 6 both, so he can take the bus.
In the second example, 16 is divisible by neither 5 nor 6, so he can't take the bus.
In the third example, 20 is divisible by 5, so he can take the bus.
*/
#include <stdio.h>
int main(void) {
// your code goes here
int n;
scanf("%d", &n);
if(n%5==0 || n%6==0)
{
printf("YES");
}
else
{
printf("NO");
}
return 0;
}
|
the_stack_data/96828.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <CL/cl.h>
unsigned char *read_buffer(char *file_name, size_t *size_ptr)
{
FILE *f;
unsigned char *buf;
size_t size;
/* Open file */
f = fopen(file_name, "rb");
if (!f)
return NULL;
/* Obtain file size */
fseek(f, 0, SEEK_END);
size = ftell(f);
fseek(f, 0, SEEK_SET);
/* Allocate and read buffer */
buf = malloc(size + 1);
fread(buf, 1, size, f);
buf[size] = '\0';
/* Return size of buffer */
if (size_ptr)
*size_ptr = size;
/* Return buffer */
return buf;
}
void write_buffer(char *file_name, const char *buffer, size_t buffer_size)
{
FILE *f;
/* Open file */
f = fopen(file_name, "w+");
/* Write buffer */
if(buffer)
fwrite(buffer, 1, buffer_size, f);
/* Close file */
fclose(f);
}
int main(int argc, char const *argv[])
{
/* Get platform */
cl_platform_id platform;
cl_uint num_platforms;
cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetPlatformIDs' failed\n");
exit(1);
}
printf("Number of platforms: %d\n", num_platforms);
printf("platform=%p\n", platform);
/* Get platform name */
char platform_name[100];
ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetPlatformInfo' failed\n");
exit(1);
}
printf("platform.name='%s'\n\n", platform_name);
/* Get device */
cl_device_id device;
cl_uint num_devices;
ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetDeviceIDs' failed\n");
exit(1);
}
printf("Number of devices: %d\n", num_devices);
printf("device=%p\n", device);
/* Get device name */
char device_name[100];
ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name),
device_name, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetDeviceInfo' failed\n");
exit(1);
}
printf("device.name='%s'\n", device_name);
printf("\n");
/* Create a Context Object */
cl_context context;
context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateContext' failed\n");
exit(1);
}
printf("context=%p\n", context);
/* Create a Command Queue Object*/
cl_command_queue command_queue;
command_queue = clCreateCommandQueue(context, device, 0, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateCommandQueue' failed\n");
exit(1);
}
printf("command_queue=%p\n", command_queue);
printf("\n");
/* Program source */
unsigned char *source_code;
size_t source_length;
/* Read program from 'tgamma_float4.cl' */
source_code = read_buffer("tgamma_float4.cl", &source_length);
/* Create a program */
cl_program program;
program = clCreateProgramWithSource(context, 1, (const char **)&source_code, &source_length, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateProgramWithSource' failed\n");
exit(1);
}
printf("program=%p\n", program);
/* Build program */
ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
if (ret != CL_SUCCESS )
{
size_t size;
char *log;
/* Get log size */
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size);
/* Allocate log and print */
log = malloc(size);
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL);
printf("error: call to 'clBuildProgram' failed:\n%s\n", log);
/* Free log and exit */
free(log);
exit(1);
}
printf("program built\n");
printf("\n");
/* Create a Kernel Object */
cl_kernel kernel;
kernel = clCreateKernel(program, "tgamma_float4", &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateKernel' failed\n");
exit(1);
}
/* Create and allocate host buffers */
size_t num_elem = 10;
/* Create and init host side src buffer 0 */
cl_float4 *src_0_host_buffer;
src_0_host_buffer = malloc(num_elem * sizeof(cl_float4));
for (int i = 0; i < num_elem; i++)
src_0_host_buffer[i] = (cl_float4){{2.0, 2.0, 2.0, 2.0}};
/* Create and init device side src buffer 0 */
cl_mem src_0_device_buffer;
src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_float4), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create source buffer\n");
exit(1);
}
ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_float4), src_0_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueWriteBuffer' failed\n");
exit(1);
}
/* Create host dst buffer */
cl_float4 *dst_host_buffer;
dst_host_buffer = malloc(num_elem * sizeof(cl_float4));
memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_float4));
/* Create device dst buffer */
cl_mem dst_device_buffer;
dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_float4), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create dst buffer\n");
exit(1);
}
/* Set kernel arguments */
ret = CL_SUCCESS;
ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer);
ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &dst_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clSetKernelArg' failed\n");
exit(1);
}
/* Launch the kernel */
size_t global_work_size = num_elem;
size_t local_work_size = num_elem;
ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueNDRangeKernel' failed\n");
exit(1);
}
/* Wait for it to finish */
clFinish(command_queue);
/* Read results from GPU */
ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_float4), dst_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueReadBuffer' failed\n");
exit(1);
}
/* Dump dst buffer to file */
char dump_file[100];
sprintf((char *)&dump_file, "%s.result", argv[0]);
write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_float4));
printf("Result dumped to %s\n", dump_file);
/* Free host dst buffer */
free(dst_host_buffer);
/* Free device dst buffer */
ret = clReleaseMemObject(dst_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Free host side src buffer 0 */
free(src_0_host_buffer);
/* Free device side src buffer 0 */
ret = clReleaseMemObject(src_0_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Release kernel */
ret = clReleaseKernel(kernel);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseKernel' failed\n");
exit(1);
}
/* Release program */
ret = clReleaseProgram(program);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseProgram' failed\n");
exit(1);
}
/* Release command queue */
ret = clReleaseCommandQueue(command_queue);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseCommandQueue' failed\n");
exit(1);
}
/* Release context */
ret = clReleaseContext(context);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseContext' failed\n");
exit(1);
}
return 0;
} |
the_stack_data/1219561.c | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define bool int
#define true 1
#define false 0
//calculate the max length of intersection the suffix of a and the prefix of b
int computePrefixFunction(char *p) {
if(!p || !strlen(p) || strlen(p) == 1) return 0;
int i;
int result = 0;
char *p1 = p+1;
while(*p1 != '\0') {
char *p11 = p1;
char *p2 = p;
while(*p11 != '\0' && *(p2+1) != '\0') {
//printf("*p11=%c, *p2=%c\n", *p11, *p2);
if(*p11 == *p2) {
p11++;
p2++;
} else {
break;
}
}
if(*p11 == '\0') {
//printf("enter here\n");
result = p2 - p;
break;
}
p1++;
//printf("\n");
}
return result;
}
//return first displacement of the matching
//-1 means no matches
int regularKmpMatching(char *t, char *p) {
if(!t || !p || !*t || !*p || !strlen(t) || !strlen(p) || strlen(p) > strlen(t)) return -1;
char *ptHeader = t;
char *ptTail = t;
char *pp = p;
int result = -1;
while(*ptTail != '\0' && *pp != '\0') {
printf("%c, %c, %c\n", *ptHeader, *ptTail, *pp);
if(*ptTail == *pp) {
//pt++;
ptTail++;
pp++;
} else {
int i = pp - p - 1;
if(i < 0) {
ptHeader = ptHeader + 1;
} else {
char* cCopy = (char*)calloc(i+2, sizeof(char));
memcpy(cCopy, p, i+1);
*(cCopy+i+1) = '\0';
printf("%d, %s\n", i, cCopy);
int s = computePrefixFunction(cCopy);
printf("s=%d\n", s);
ptHeader = ptTail - s;
//ptTail = ptHeader;
pp = p;
}
ptTail = ptHeader;
}
}
if(*pp == '\0') {
printf("enter here\n");
printf("%c, %c\n", *ptHeader, *t);
result = ptHeader - t;
}
return result;
}
bool isMatch(char *s, char *p) {
char *ps = s;
char *pp = p;
while(*pp != '\0') {
pp++;
}
}
int main(void) {
char t[30], p[30];
printf("please input t: \n");
fgets(t, sizeof(t), stdin);
printf("please input p: \n");
fgets(p, sizeof(p), stdin);
char *tt = (char*)calloc(strlen(t)+1, sizeof(char));
char *pp = (char*)calloc(strlen(p)+1, sizeof(char));
strcpy(tt, t);
strcpy(pp, p);
char *tEnd = strchr(tt, '\n');
if(tEnd) {
*tEnd = '\0';
}
char *pEnd = strchr(pp, '\n');
if(pEnd) {
*pEnd = '\0';
}
// printf("tt=%s, pp=%s\n", tt, pp);
printf("s=%d\n", kmpMatching(tt, pp));
/**
char a[30];
printf("please input the pattern: \n");
fgets(a, sizeof(a), stdin);
char *aa = (char*)calloc(strlen(a)+1, sizeof(char));
strcpy(aa, a);
printf("a==%s\n", a);
printf("aa==%s\n", aa);
char *end = strchr(aa, '\n');
if(end) {
*end = '\0';
}
printf("%d\n", computePrefixFunction(aa));
**/
return 0;
}
|
the_stack_data/25137234.c | // RUN: %clang_cc1 -S -O3 -fno-builtin -o - %s | FileCheck %s
// RUN: %clang_cc1 -S -O3 -fno-builtin-ceil -fno-builtin-copysign -fno-builtin-cos \
// RUN: -fno-builtin-fabs -fno-builtin-floor -fno-builtin-strcat -fno-builtin-strncat \
// RUN: -fno-builtin-strchr -fno-builtin-strrchr -fno-builtin-strcmp -fno-builtin-strncmp \
// RUN: -fno-builtin-strcpy -fno-builtin-stpcpy -fno-builtin-strncpy -fno-builtin-strlen \
// RUN: -fno-builtin-strpbrk -fno-builtin-strspn -fno-builtin-strtod -fno-builtin-strtof \
// RUN: -fno-builtin-strtold -fno-builtin-strtol -fno-builtin-strtoll -fno-builtin-strtoul \
// RUN: -fno-builtin-strtoull -o - %s | FileCheck %s
// rdar://10551066
typedef __SIZE_TYPE__ size_t;
double ceil(double x);
double copysign(double,double);
double cos(double x);
double fabs(double x);
double floor(double x);
char *strcat(char *s1, const char *s2);
char *strncat(char *s1, const char *s2, size_t n);
char *strchr(const char *s, int c);
char *strrchr(const char *s, int c);
int strcmp(const char *s1, const char *s2);
int strncmp(const char *s1, const char *s2, size_t n);
char *strcpy(char *s1, const char *s2);
char *stpcpy(char *s1, const char *s2);
char *strncpy(char *s1, const char *s2, size_t n);
size_t strlen(const char *s);
char *strpbrk(const char *s1, const char *s2);
size_t strspn(const char *s1, const char *s2);
double strtod(const char *nptr, char **endptr);
float strtof(const char *nptr, char **endptr);
long double strtold(const char *nptr, char **endptr);
long int strtol(const char *nptr, char **endptr, int base);
long long int strtoll(const char *nptr, char **endptr, int base);
unsigned long int strtoul(const char *nptr, char **endptr, int base);
unsigned long long int strtoull(const char *nptr, char **endptr, int base);
double t1(double x) { return ceil(x); }
// CHECK: t1
// CHECK: ceil
double t2(double x, double y) { return copysign(x,y); }
// CHECK: t2
// CHECK: copysign
double t3(double x) { return cos(x); }
// CHECK: t3
// CHECK: cos
double t4(double x) { return fabs(x); }
// CHECK: t4
// CHECK: fabs
double t5(double x) { return floor(x); }
// CHECK: t5
// CHECK: floor
char *t6(char *x) { return strcat(x, ""); }
// CHECK: t6
// CHECK: strcat
char *t7(char *x) { return strncat(x, "", 1); }
// CHECK: t7
// CHECK: strncat
char *t8(void) { return strchr("hello, world", 'w'); }
// CHECK: t8
// CHECK: strchr
char *t9(void) { return strrchr("hello, world", 'w'); }
// CHECK: t9
// CHECK: strrchr
int t10(void) { return strcmp("foo", "bar"); }
// CHECK: t10
// CHECK: strcmp
int t11(void) { return strncmp("foo", "bar", 3); }
// CHECK: t11
// CHECK: strncmp
char *t12(char *x) { return strcpy(x, "foo"); }
// CHECK: t12
// CHECK: strcpy
char *t13(char *x) { return stpcpy(x, "foo"); }
// CHECK: t13
// CHECK: stpcpy
char *t14(char *x) { return strncpy(x, "foo", 3); }
// CHECK: t14
// CHECK: strncpy
size_t t15(void) { return strlen("foo"); }
// CHECK: t15
// CHECK: strlen
char *t16(char *x) { return strpbrk(x, ""); }
// CHECK: t16
// CHECK: strpbrk
size_t t17(char *x) { return strspn(x, ""); }
// CHECK: t17
// CHECK: strspn
double t18(char **x) { return strtod("123.4", x); }
// CHECK: t18
// CHECK: strtod
float t19(char **x) { return strtof("123.4", x); }
// CHECK: t19
// CHECK: strtof
long double t20(char **x) { return strtold("123.4", x); }
// CHECK: t20
// CHECK: strtold
long int t21(char **x) { return strtol("1234", x, 10); }
// CHECK: t21
// CHECK: strtol
long int t22(char **x) { return strtoll("1234", x, 10); }
// CHECK: t22
// CHECK: strtoll
long int t23(char **x) { return strtoul("1234", x, 10); }
// CHECK: t23
// CHECK: strtoul
long int t24(char **x) { return strtoull("1234", x, 10); }
// CHECK: t24
// CHECK: strtoull
|
the_stack_data/108059.c | #include <stdio.h>
int main(void)
{
for (int i = 0; i < 6; i++)
{
for (int j = 0; j <= i; j++)
printf("%c", 'F' - j);
printf("\n");
}
return 0;
}
|
the_stack_data/248581659.c | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
/*
* COPYRIGHT
*
* neckm.c
* Copyright (C) 2014 Exstrom Laboratories LLC
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* A copy of the GNU General Public License is available on the internet at:
* http://www.gnu.org/copyleft/gpl.html
*
* or you can write to:
*
* The Free Software Foundation, Inc.
* 675 Mass Ave
* Cambridge, MA 02139, USA
*
* Exstrom Laboratories LLC contact:
* stefan(AT)exstrom.com
*
* Exstrom Laboratories LLC
* Longmont, CO 80503, USA
*
*/
// Compile: gcc -lm -o neckm neckm.c
int n, n1;
int *b;
// k = length of necklace
// l = length of longest prefix that is a lyndon word
// m = number of parts (ones)
void neckbin(int k, int l, int m)
{
if(k > n){
if((n%l)==0 && m==n1){
for(k=1; k<n+1; ++k) printf("%d",b[k]);
printf("\n");}}
else{
b[k]=b[k-l];
if(b[k]==1){
neckbin(k+1,l,m+1);
b[k]=0;
neckbin(k+1,k,m);}
else
neckbin(k+1,l,m);}
}
/*******************************************************************/
int main( int argc, char *argv[] )
{
if(argc < 2)
{
printf("usage: %s n m\n", argv[0]);
printf(" Generates all binary necklaces of length n with m ones.\n");
exit(-1);
}
n = atoi(argv[1]);
n1 = atoi(argv[2]);
b = (int *)malloc((n+2)*sizeof(int));
b[0] = 1;
neckbin(1,1,0);
free(b);
return(0);
}
|
the_stack_data/89964.c | /*
* sigdemo1.c - shows how a signal handler works
* run this and press crtl-c a few times
*/
#include <stdio.h>
#include <signal.h>
main() {
void f(int); //declare the handler
int i;
signal(SIGINT, f); //istall the handler
for (int i = 0; i < 5; ++i) {
printf("hello\n");
sleep(1);
}
}
void f(int signum) {
printf("OUCH! \n");
} |
the_stack_data/26126.c | // Lista 02 Questões 02 e 03
#include <stdio.h>
/** EXERCICIO: - 02:
* Elabore um registro que contenha os seguintes campos: nome e nota.
* O campo nota deverá ser um vetor com 03 notas para registrar as
* notas AP1, AP2 e FINAL.
*/
struct Aluno
{
double nota[3];
char nome[20];
} typedef TAluno;
void MostreAlunos(TAluno *turma, int tamanho)
{
for (int i = 0; i < tamanho; i++)
{
printf("AP1: %.2lf;\tAP2: %.2lf;\tFINAL: %.2lf;\tAluno: %s;\n", turma[i].nota[0], turma[i].nota[1], turma[i].nota[2], turma[i].nome);
}
}
/** EXERCICIO: - 03:
* Considerando o registro da questão anterior, elabore um programa para armazenar o nome e
* nota de 5 alunos da disciplina Estruturas de Dados. O programa deverá mostrar os registros dos 5 alunos e notas.
*/
void AppAcademico()
{
// SETUP
TAluno turma[35] = {
{7.22, 7.22, 7.22, "Ubireudo"},
{8.22, 8.22, 8.22, "Notlina"},
{9.22, 9.22, 9.22, "Newt"}};
int numeroDeAlunos = 3;
char option = '1';
// APLICATION
do
{
Printf("\n\tApp Academico\n");
printf("- op%c%co:\n", 135, 198);
printf(" 1 - Mostrar lista de Alunos\n");
printf(" 2 - Inserir novo Aluno\n");
printf(" ----------------------\n");
printf(" 0 - Sair do Aplicativo\n");
printf("\n Escolha uma op%c%co: ", 135, 198);
fflush(stdin);
option = getchar();
if (option == '0')
{
printf("\n ** Fim do aplicativo **");
break;
}
switch (option)
{
case '1':
MostreAlunos(turma, numeroDeAlunos);
break;
case '2':
if (numeroDeAlunos < 35)
{
fflush(stdin);
scanf("\nDigite o nome: %s", &turma[numeroDeAlunos].nome);
fflush(stdin);
scanf("\nDigite a nota 1: %lf", &turma[numeroDeAlunos].nota[0]);
fflush(stdin);
scanf("\nDigite a nota 2: %lf", &turma[numeroDeAlunos].nota[1]);
fflush(stdin);
scanf("\nDigite a nota 3: %lf", &turma[numeroDeAlunos].nota[2]);
numeroDeAlunos++;
printf("\nAluno incluido");
}
else
{
printf("\nLista de Alunos completa!!");
}
break;
default:
Printf("op%c%co invalida!\n", 135, 198);
break;
}
} while (option != '0');
printf("\nAplicativo encerrado");
}
int main(int argc, char const *argv[])
{
printf("\n\tQuestão 02 e 03\n");
TAluno classe[3] = {
{7.22, 7.22, 7.22, "Ubireudo"},
{8.22, 8.22, 8.22, "Notlina"},
{9.22, 9.22, 9.22, "Newt"},
};
MostreAlunos(classe, sizeof(classe) / sizeof(classe[0]));
return 0;
} |
the_stack_data/61074922.c | // KASAN: use-after-free Read in ip6t_do_table
// https://syzkaller.appspot.com/bug?id=a7093f0aef8fbb70043daf3989e608acd4fd6c39
// status:open
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <dirent.h>
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <net/if.h>
#include <netinet/in.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/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <linux/genetlink.h>
#include <linux/if_addr.h>
#include <linux/if_link.h>
#include <linux/in6.h>
#include <linux/neighbour.h>
#include <linux/net.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/veth.h>
unsigned long long procid;
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;
}
struct nlmsg {
char* pos;
int nesting;
struct nlattr* nested[8];
char buf[1024];
};
static struct nlmsg nlmsg;
static void netlink_init(struct nlmsg* nlmsg, int typ, int flags,
const void* data, int size)
{
memset(nlmsg, 0, sizeof(*nlmsg));
struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf;
hdr->nlmsg_type = typ;
hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
memcpy(hdr + 1, data, size);
nlmsg->pos = (char*)(hdr + 1) + NLMSG_ALIGN(size);
}
static void netlink_attr(struct nlmsg* nlmsg, int typ, const void* data,
int size)
{
struct nlattr* attr = (struct nlattr*)nlmsg->pos;
attr->nla_len = sizeof(*attr) + size;
attr->nla_type = typ;
memcpy(attr + 1, data, size);
nlmsg->pos += NLMSG_ALIGN(attr->nla_len);
}
static int netlink_send_ext(struct nlmsg* nlmsg, int sock, uint16_t reply_type,
int* reply_len)
{
if (nlmsg->pos > nlmsg->buf + sizeof(nlmsg->buf) || nlmsg->nesting)
exit(1);
struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf;
hdr->nlmsg_len = nlmsg->pos - nlmsg->buf;
struct sockaddr_nl addr;
memset(&addr, 0, sizeof(addr));
addr.nl_family = AF_NETLINK;
unsigned n = sendto(sock, nlmsg->buf, hdr->nlmsg_len, 0,
(struct sockaddr*)&addr, sizeof(addr));
if (n != hdr->nlmsg_len)
exit(1);
n = recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0);
if (hdr->nlmsg_type == NLMSG_DONE) {
*reply_len = 0;
return 0;
}
if (n < sizeof(struct nlmsghdr))
exit(1);
if (reply_len && hdr->nlmsg_type == reply_type) {
*reply_len = n;
return 0;
}
if (n < sizeof(struct nlmsghdr) + sizeof(struct nlmsgerr))
exit(1);
if (hdr->nlmsg_type != NLMSG_ERROR)
exit(1);
return -((struct nlmsgerr*)(hdr + 1))->error;
}
static int netlink_send(struct nlmsg* nlmsg, int sock)
{
return netlink_send_ext(nlmsg, sock, 0, NULL);
}
static int netlink_next_msg(struct nlmsg* nlmsg, unsigned int offset,
unsigned int total_len)
{
struct nlmsghdr* hdr = (struct nlmsghdr*)(nlmsg->buf + offset);
if (offset == total_len || offset + hdr->nlmsg_len > total_len)
return -1;
return hdr->nlmsg_len;
}
static void netlink_device_change(struct nlmsg* nlmsg, int sock,
const char* name, bool up, const char* master,
const void* mac, int macsize,
const char* new_name)
{
struct ifinfomsg hdr;
memset(&hdr, 0, sizeof(hdr));
if (up)
hdr.ifi_flags = hdr.ifi_change = IFF_UP;
hdr.ifi_index = if_nametoindex(name);
netlink_init(nlmsg, RTM_NEWLINK, 0, &hdr, sizeof(hdr));
if (new_name)
netlink_attr(nlmsg, IFLA_IFNAME, new_name, strlen(new_name));
if (master) {
int ifindex = if_nametoindex(master);
netlink_attr(nlmsg, IFLA_MASTER, &ifindex, sizeof(ifindex));
}
if (macsize)
netlink_attr(nlmsg, IFLA_ADDRESS, mac, macsize);
int err = netlink_send(nlmsg, sock);
(void)err;
}
const int kInitNetNsFd = 239;
#define DEVLINK_FAMILY_NAME "devlink"
#define DEVLINK_CMD_PORT_GET 5
#define DEVLINK_CMD_RELOAD 37
#define DEVLINK_ATTR_BUS_NAME 1
#define DEVLINK_ATTR_DEV_NAME 2
#define DEVLINK_ATTR_NETDEV_NAME 7
#define DEVLINK_ATTR_NETNS_FD 137
static int netlink_devlink_id_get(struct nlmsg* nlmsg, int sock)
{
struct genlmsghdr genlhdr;
struct nlattr* attr;
int err, n;
uint16_t id = 0;
memset(&genlhdr, 0, sizeof(genlhdr));
genlhdr.cmd = CTRL_CMD_GETFAMILY;
netlink_init(nlmsg, GENL_ID_CTRL, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(nlmsg, CTRL_ATTR_FAMILY_NAME, DEVLINK_FAMILY_NAME,
strlen(DEVLINK_FAMILY_NAME) + 1);
err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n);
if (err) {
return -1;
}
attr = (struct nlattr*)(nlmsg->buf + NLMSG_HDRLEN +
NLMSG_ALIGN(sizeof(genlhdr)));
for (; (char*)attr < nlmsg->buf + n;
attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) {
if (attr->nla_type == CTRL_ATTR_FAMILY_ID) {
id = *(uint16_t*)(attr + 1);
break;
}
}
if (!id) {
return -1;
}
recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0); /* recv ack */
return id;
}
static void netlink_devlink_netns_move(const char* bus_name,
const char* dev_name, int netns_fd)
{
struct genlmsghdr genlhdr;
int sock;
int id;
sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);
if (sock == -1)
exit(1);
id = netlink_devlink_id_get(&nlmsg, sock);
if (id == -1)
goto error;
memset(&genlhdr, 0, sizeof(genlhdr));
genlhdr.cmd = DEVLINK_CMD_RELOAD;
netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, DEVLINK_ATTR_BUS_NAME, bus_name, strlen(bus_name) + 1);
netlink_attr(&nlmsg, DEVLINK_ATTR_DEV_NAME, dev_name, strlen(dev_name) + 1);
netlink_attr(&nlmsg, DEVLINK_ATTR_NETNS_FD, &netns_fd, sizeof(netns_fd));
netlink_send(&nlmsg, sock);
error:
close(sock);
}
static struct nlmsg nlmsg2;
static void initialize_devlink_ports(const char* bus_name, const char* dev_name,
const char* netdev_prefix)
{
struct genlmsghdr genlhdr;
int len, total_len, id, err, offset;
uint16_t netdev_index;
int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);
if (sock == -1)
exit(1);
int rtsock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (rtsock == -1)
exit(1);
id = netlink_devlink_id_get(&nlmsg, sock);
if (id == -1)
goto error;
memset(&genlhdr, 0, sizeof(genlhdr));
genlhdr.cmd = DEVLINK_CMD_PORT_GET;
netlink_init(&nlmsg, id, NLM_F_DUMP, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, DEVLINK_ATTR_BUS_NAME, bus_name, strlen(bus_name) + 1);
netlink_attr(&nlmsg, DEVLINK_ATTR_DEV_NAME, dev_name, strlen(dev_name) + 1);
err = netlink_send_ext(&nlmsg, sock, id, &total_len);
if (err) {
goto error;
}
offset = 0;
netdev_index = 0;
while ((len = netlink_next_msg(&nlmsg, offset, total_len)) != -1) {
struct nlattr* attr = (struct nlattr*)(nlmsg.buf + offset + NLMSG_HDRLEN +
NLMSG_ALIGN(sizeof(genlhdr)));
for (; (char*)attr < nlmsg.buf + offset + len;
attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) {
if (attr->nla_type == DEVLINK_ATTR_NETDEV_NAME) {
char* port_name;
char netdev_name[IFNAMSIZ];
port_name = (char*)(attr + 1);
snprintf(netdev_name, sizeof(netdev_name), "%s%d", netdev_prefix,
netdev_index);
netlink_device_change(&nlmsg2, rtsock, port_name, true, 0, 0, 0,
netdev_name);
break;
}
}
offset += len;
netdev_index++;
}
error:
close(rtsock);
close(sock);
}
static void initialize_devlink_pci(void)
{
int netns = open("/proc/self/ns/net", O_RDONLY);
if (netns == -1)
exit(1);
int ret = setns(kInitNetNsFd, 0);
if (ret == -1)
exit(1);
netlink_devlink_netns_move("pci", "0000:00:10.0", netns);
ret = setns(netns, 0);
if (ret == -1)
exit(1);
close(netns);
initialize_devlink_ports("pci", "0000:00:10.0", "netpci");
}
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");
}
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;
}
}
}
uint64_t r[5] = {0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff,
0x0, 0xffffffffffffffff};
void execute_one(void)
{
intptr_t res = 0;
res = syscall(__NR_socket, 0xaul, 2ul, 0);
if (res != -1)
r[0] = res;
res = syscall(__NR_socket, 0x11ul, 2ul, 0x300ul);
if (res != -1)
r[1] = res;
memcpy((void*)0x20000100, "/dev/net/tun\000", 13);
res = syscall(__NR_openat, 0xffffffffffffff9cul, 0x20000100ul, 0ul, 0ul);
if (res != -1)
r[2] = res;
memcpy((void*)0x200001c0, "veth0\000\000\000\000\000\000\000\000\000\000\000",
16);
*(uint16_t*)0x200001d0 = 0x201a;
syscall(__NR_ioctl, r[2], 0x400454caul, 0x200001c0ul);
memcpy((void*)0x20000140, "veth0\000\000\000\000\000\000\000\000\000\000\000",
16);
*(uint32_t*)0x20000150 = 0;
res = syscall(__NR_ioctl, r[1], 0x8933ul, 0x20000140ul);
if (res != -1)
r[3] = *(uint32_t*)0x20000150;
memcpy((void*)0x200000c0,
"\x48\x91\x92\x57\x2c\xa0\xae\xd6\xde\x1b\x4b\xc6\xda\x12\x57\x2c",
16);
*(uint32_t*)0x200000d0 = 0;
*(uint32_t*)0x200000d4 = r[3];
syscall(__NR_ioctl, r[0], 0x8916ul, 0x200000c0ul);
*(uint16_t*)0x20000040 = 0xa;
*(uint16_t*)0x20000042 = htobe16(0);
*(uint32_t*)0x20000044 = htobe32(0);
memcpy((void*)0x20000048,
"\xd2\x14\xc0\xe1\x2e\xb5\xe6\xea\x07\x6c\xca\x63\xe0\x53\x79\x07",
16);
*(uint32_t*)0x20000058 = 0;
syscall(__NR_connect, r[0], 0x20000040ul, 0x1cul);
syscall(__NR_sendmmsg, r[0], 0x2000ac80ul, 0x271ul, 0x8042ul);
res = syscall(__NR_socket, 0xaul, 2ul, 0);
if (res != -1)
r[4] = res;
syscall(__NR_dup3, r[4], r[2], 0ul);
*(uint64_t*)0x200056c0 = 0;
*(uint32_t*)0x200056c8 = 0;
*(uint64_t*)0x200056d0 = 0;
*(uint64_t*)0x200056d8 = 0;
*(uint64_t*)0x200056e0 = 0;
*(uint64_t*)0x200056e8 = 0;
*(uint32_t*)0x200056f0 = 0;
*(uint32_t*)0x200056f8 = 0;
syscall(__NR_sendmmsg, r[0], 0x200056c0ul, 1ul, 0ul);
}
int main(void)
{
syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 3ul, 0x32ul, -1, 0);
for (procid = 0; procid < 6; procid++) {
if (fork() == 0) {
loop();
}
}
sleep(1000000);
return 0;
}
|
the_stack_data/26700018.c | // keccak.c
// 19-Nov-11 Markku-Juhani O. Saarinen <[email protected]>
// A baseline Keccak (3rd round) implementation.
#include <stdint.h>
#include <memory.h>
#define HASH_DATA_AREA 136
#define KECCAK_ROUNDS 24
#ifndef ROTL64
#define ROTL64(x, y) (((x) << (y)) | ((x) >> (64 - (y))))
#endif
const uint64_t keccakf_rndc[24] =
{
0x0000000000000001, 0x0000000000008082, 0x800000000000808a,
0x8000000080008000, 0x000000000000808b, 0x0000000080000001,
0x8000000080008081, 0x8000000000008009, 0x000000000000008a,
0x0000000000000088, 0x0000000080008009, 0x000000008000000a,
0x000000008000808b, 0x800000000000008b, 0x8000000000008089,
0x8000000000008003, 0x8000000000008002, 0x8000000000000080,
0x000000000000800a, 0x800000008000000a, 0x8000000080008081,
0x8000000000008080, 0x0000000080000001, 0x8000000080008008
};
// update the state with given number of rounds
void keccakf(uint64_t st[25], int rounds)
{
int i, j, round;
uint64_t t, bc[5];
for (round = 0; round < rounds; ++round) {
// Theta
bc[0] = st[0] ^ st[5] ^ st[10] ^ st[15] ^ st[20];
bc[1] = st[1] ^ st[6] ^ st[11] ^ st[16] ^ st[21];
bc[2] = st[2] ^ st[7] ^ st[12] ^ st[17] ^ st[22];
bc[3] = st[3] ^ st[8] ^ st[13] ^ st[18] ^ st[23];
bc[4] = st[4] ^ st[9] ^ st[14] ^ st[19] ^ st[24];
for (i = 0; i < 5; ++i) {
t = bc[(i + 4) % 5] ^ ROTL64(bc[(i + 1) % 5], 1);
st[i ] ^= t;
st[i + 5] ^= t;
st[i + 10] ^= t;
st[i + 15] ^= t;
st[i + 20] ^= t;
}
// Rho Pi
t = st[1];
st[ 1] = ROTL64(st[ 6], 44);
st[ 6] = ROTL64(st[ 9], 20);
st[ 9] = ROTL64(st[22], 61);
st[22] = ROTL64(st[14], 39);
st[14] = ROTL64(st[20], 18);
st[20] = ROTL64(st[ 2], 62);
st[ 2] = ROTL64(st[12], 43);
st[12] = ROTL64(st[13], 25);
st[13] = ROTL64(st[19], 8);
st[19] = ROTL64(st[23], 56);
st[23] = ROTL64(st[15], 41);
st[15] = ROTL64(st[ 4], 27);
st[ 4] = ROTL64(st[24], 14);
st[24] = ROTL64(st[21], 2);
st[21] = ROTL64(st[ 8], 55);
st[ 8] = ROTL64(st[16], 45);
st[16] = ROTL64(st[ 5], 36);
st[ 5] = ROTL64(st[ 3], 28);
st[ 3] = ROTL64(st[18], 21);
st[18] = ROTL64(st[17], 15);
st[17] = ROTL64(st[11], 10);
st[11] = ROTL64(st[ 7], 6);
st[ 7] = ROTL64(st[10], 3);
st[10] = ROTL64(t, 1);
// Chi
// unrolled loop, where only last iteration is different
j = 0;
bc[0] = st[j ];
bc[1] = st[j + 1];
st[j ] ^= (~st[j + 1]) & st[j + 2];
st[j + 1] ^= (~st[j + 2]) & st[j + 3];
st[j + 2] ^= (~st[j + 3]) & st[j + 4];
st[j + 3] ^= (~st[j + 4]) & bc[0];
st[j + 4] ^= (~bc[0]) & bc[1];
j = 5;
bc[0] = st[j ];
bc[1] = st[j + 1];
st[j ] ^= (~st[j + 1]) & st[j + 2];
st[j + 1] ^= (~st[j + 2]) & st[j + 3];
st[j + 2] ^= (~st[j + 3]) & st[j + 4];
st[j + 3] ^= (~st[j + 4]) & bc[0];
st[j + 4] ^= (~bc[0]) & bc[1];
j = 10;
bc[0] = st[j ];
bc[1] = st[j + 1];
st[j ] ^= (~st[j + 1]) & st[j + 2];
st[j + 1] ^= (~st[j + 2]) & st[j + 3];
st[j + 2] ^= (~st[j + 3]) & st[j + 4];
st[j + 3] ^= (~st[j + 4]) & bc[0];
st[j + 4] ^= (~bc[0]) & bc[1];
j = 15;
bc[0] = st[j ];
bc[1] = st[j + 1];
st[j ] ^= (~st[j + 1]) & st[j + 2];
st[j + 1] ^= (~st[j + 2]) & st[j + 3];
st[j + 2] ^= (~st[j + 3]) & st[j + 4];
st[j + 3] ^= (~st[j + 4]) & bc[0];
st[j + 4] ^= (~bc[0]) & bc[1];
j = 20;
bc[0] = st[j ];
bc[1] = st[j + 1];
bc[2] = st[j + 2];
bc[3] = st[j + 3];
bc[4] = st[j + 4];
st[j ] ^= (~bc[1]) & bc[2];
st[j + 1] ^= (~bc[2]) & bc[3];
st[j + 2] ^= (~bc[3]) & bc[4];
st[j + 3] ^= (~bc[4]) & bc[0];
st[j + 4] ^= (~bc[0]) & bc[1];
// Iota
st[0] ^= keccakf_rndc[round];
}
}
// compute a keccak hash (md) of given byte length from "in"
typedef uint64_t state_t[25];
void keccak(const uint8_t *in, int inlen, uint8_t *md, int mdlen)
{
state_t st;
uint8_t temp[144];
int i, rsiz, rsizw;
rsiz = sizeof(state_t) == mdlen ? HASH_DATA_AREA : 200 - 2 * mdlen;
rsizw = rsiz / 8;
memset(st, 0, sizeof(st));
for ( ; inlen >= rsiz; inlen -= rsiz, in += rsiz) {
for (i = 0; i < rsizw; i++)
st[i] ^= ((uint64_t *) in)[i];
keccakf(st, KECCAK_ROUNDS);
}
// last block and padding
memcpy(temp, in, inlen);
temp[inlen++] = 1;
memset(temp + inlen, 0, rsiz - inlen);
temp[rsiz - 1] |= 0x80;
for (i = 0; i < rsizw; i++)
st[i] ^= ((uint64_t *) temp)[i];
keccakf(st, KECCAK_ROUNDS);
memcpy(md, st, mdlen);
}
void keccak1600(const uint8_t *in, int inlen, uint8_t *md)
{
keccak(in, inlen, md, sizeof(state_t));
} |
the_stack_data/144386.c | //Program to display ASCII value of each escape character in C
#include<stdio.h>
int main()
{
char c,d,e,f,g,h;
c='\n',d='\r',e='\t',f='\b',g='\v',h='\f';
printf("The ASCII value of \\n is %d\n",c);
printf("The ASCII value of \\r is %d\n",d);
printf("The ASCII value of \\t is %d\n",e);
printf("The ASCII value of \\b is %d\n",f);
printf("The ASCII value of \\v is %d\n",e);
printf("The ASCII value of \\f is %d",f);
return 0;
}
|
the_stack_data/15764155.c | int sum(int *a, int n) {
int i, s = 0;
for (i = 0; i < n; i++) {
s += a[i];
}
return s;
} |
the_stack_data/67324462.c | /*
* *****************************************************************************
*
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2018-2021 Gavin D. Howard and contributors.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
*
* *****************************************************************************
*
* The parser for bc.
*
*/
#if BC_ENABLED
#include <assert.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <setjmp.h>
#include <bc.h>
#include <num.h>
#include <vm.h>
// Before you embark on trying to understand this code, have you read the
// Development manual (manuals/development.md) and the comment in include/bc.h
// yet? No? Do that first. I'm serious.
//
// The reason is because this file holds the most sensitive and finicky code in
// the entire codebase. Even getting history to work on Windows was nothing
// compared to this. This is where dreams go to die, where dragons live, and
// from which Ken Thompson himself would flee.
static void bc_parse_else(BcParse *p);
static void bc_parse_stmt(BcParse *p);
static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags,
BcParseNext next);
static void bc_parse_expr_status(BcParse *p, uint8_t flags, BcParseNext next);
/**
* Returns true if an instruction could only have come from a "leaf" expression.
* For more on what leaf expressions are, read the comment for BC_PARSE_LEAF().
* @param t The instruction to test.
*/
static bool bc_parse_inst_isLeaf(BcInst t) {
return (t >= BC_INST_NUM && t <= BC_INST_MAXSCALE) ||
#if BC_ENABLE_EXTRA_MATH
t == BC_INST_TRUNC ||
#endif // BC_ENABLE_EXTRA_MATH
t <= BC_INST_DEC;
}
/**
* Returns true if the *previous* token was a delimiter. A delimiter is anything
* that can legally end a statement. In bc's case, it could be a newline, a
* semicolon, and a brace in certain cases.
* @param p The parser.
*/
static bool bc_parse_isDelimiter(const BcParse *p) {
BcLexType t = p->l.t;
bool good;
// If it's an obvious delimiter, say so.
if (BC_PARSE_DELIMITER(t)) return true;
good = false;
// If the current token is a keyword, then...beware. That means that we need
// to check for a "dangling" else, where there was no brace-delimited block
// on the previous if.
if (t == BC_LEX_KW_ELSE) {
size_t i;
uint16_t *fptr = NULL, flags = BC_PARSE_FLAG_ELSE;
// As long as going up the stack is valid for a dangling else, keep on.
for (i = 0; i < p->flags.len && BC_PARSE_BLOCK_STMT(flags); ++i) {
fptr = bc_vec_item_rev(&p->flags, i);
flags = *fptr;
// If we need a brace and don't have one, then we don't have a
// delimiter.
if ((flags & BC_PARSE_FLAG_BRACE) && p->l.last != BC_LEX_RBRACE)
return false;
}
// Oh, and we had also better have an if statement somewhere.
good = ((flags & BC_PARSE_FLAG_IF) != 0);
}
else if (t == BC_LEX_RBRACE) {
size_t i;
// Since we have a brace, we need to just check if a brace was needed.
for (i = 0; !good && i < p->flags.len; ++i) {
uint16_t *fptr = bc_vec_item_rev(&p->flags, i);
good = (((*fptr) & BC_PARSE_FLAG_BRACE) != 0);
}
}
return good;
}
/**
* Sets a previously defined exit label. What are labels? See the bc Parsing
* section of the Development manual (manuals/development.md).
* @param p The parser.
*/
static void bc_parse_setLabel(BcParse *p) {
BcFunc *func = p->func;
BcInstPtr *ip = bc_vec_top(&p->exits);
size_t *label;
assert(func == bc_vec_item(&p->prog->fns, p->fidx));
// Set the preallocated label to the correct index.
label = bc_vec_item(&func->labels, ip->idx);
*label = func->code.len;
// Now, we don't need the exit label; it is done.
bc_vec_pop(&p->exits);
}
/**
* Creates a label and sets it to idx. If this is an exit label, then idx is
* actually invalid, but it doesn't matter because it will be fixed by
* bc_parse_setLabel() later.
* @param p The parser.
* @param idx The index of the label.
*/
static void bc_parse_createLabel(BcParse *p, size_t idx) {
bc_vec_push(&p->func->labels, &idx);
}
/**
* Creates a conditional label. Unlike an exit label, this label is set at
* creation time because it comes *before* the code that will target it.
* @param p The parser.
* @param idx The index of the label.
*/
static void bc_parse_createCondLabel(BcParse *p, size_t idx) {
bc_parse_createLabel(p, p->func->code.len);
bc_vec_push(&p->conds, &idx);
}
/*
* Creates an exit label to be filled in later by bc_parse_setLabel(). Also, why
* create a label to be filled in later? Because exit labels are meant to be
* targeted by code that comes *before* the label. Since we have to parse that
* code first, and don't know how long it will be, we need to just make sure to
* reserve a slot to be filled in later when we know.
*
* By the way, this uses BcInstPtr because it was convenient. The field idx
* holds the index, and the field func holds the loop boolean.
*
* @param p The parser.
* @param idx The index of the label's position.
* @param loop True if the exit label is for a loop or not.
*/
static void bc_parse_createExitLabel(BcParse *p, size_t idx, bool loop) {
BcInstPtr ip;
assert(p->func == bc_vec_item(&p->prog->fns, p->fidx));
ip.func = loop;
ip.idx = idx;
ip.len = 0;
bc_vec_push(&p->exits, &ip);
bc_parse_createLabel(p, SIZE_MAX);
}
/**
* Pops the correct operators off of the operator stack based on the current
* operator. This is because of the Shunting-Yard algorithm. Lower prec means
* higher precedence.
* @param p The parser.
* @param type The operator.
* @param start The previous start of the operator stack. For more
* information, see the bc Parsing section of the Development
* manual (manuals/development.md).
* @param nexprs A pointer to the current number of expressions that have not
* been consumed yet. This is an IN and OUT parameter.
*/
static void bc_parse_operator(BcParse *p, BcLexType type,
size_t start, size_t *nexprs)
{
BcLexType t;
uchar l, r = BC_PARSE_OP_PREC(type);
uchar left = BC_PARSE_OP_LEFT(type);
// While we haven't hit the stop point yet.
while (p->ops.len > start) {
// Get the top operator.
t = BC_PARSE_TOP_OP(p);
// If it's a right paren, we have reached the end of whatever expression
// this is no matter what.
if (t == BC_LEX_LPAREN) break;
// Break for precedence. Precedence operates differently on left and
// right associativity, by the way. A left associative operator that
// matches the current precedence should take priority, but a right
// associative operator should not.
l = BC_PARSE_OP_PREC(t);
if (l >= r && (l != r || !left)) break;
// Do the housekeeping. In particular, make sure to note that one
// expression was consumed. (Two were, but another was added.)
bc_parse_push(p, BC_PARSE_TOKEN_INST(t));
bc_vec_pop(&p->ops);
*nexprs -= !BC_PARSE_OP_PREFIX(t);
}
bc_vec_push(&p->ops, &type);
}
/**
* Parses a right paren. In the Shunting-Yard algorithm, it needs to be put on
* the operator stack. But before that, it needs to consume whatever operators
* there are until it hits a left paren.
* @param p The parser.
* @param nexprs A pointer to the current number of expressions that have not
* been consumed yet. This is an IN and OUT parameter.
*/
static void bc_parse_rightParen(BcParse *p, size_t *nexprs) {
BcLexType top;
// Consume operators until a left paren.
while ((top = BC_PARSE_TOP_OP(p)) != BC_LEX_LPAREN) {
bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
bc_vec_pop(&p->ops);
*nexprs -= !BC_PARSE_OP_PREFIX(top);
}
// We need to pop the left paren as well.
bc_vec_pop(&p->ops);
// Oh, and we also want the next token.
bc_lex_next(&p->l);
}
/**
* Parses function arguments.
* @param p The parser.
* @param flags Flags restricting what kind of expressions the arguments can
* be.
*/
static void bc_parse_args(BcParse *p, uint8_t flags) {
bool comma = false;
size_t nargs;
bc_lex_next(&p->l);
// Print and comparison operators not allowed. Well, comparison operators
// only for POSIX. But we do allow arrays, and we *must* get a value.
flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
flags |= (BC_PARSE_ARRAY | BC_PARSE_NEEDVAL);
// Count the arguments and parse them.
for (nargs = 0; p->l.t != BC_LEX_RPAREN; ++nargs) {
bc_parse_expr_status(p, flags, bc_parse_next_arg);
comma = (p->l.t == BC_LEX_COMMA);
if (comma) bc_lex_next(&p->l);
}
// An ending comma is FAIL.
if (BC_ERR(comma)) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// Now do the call with the number of arguments.
bc_parse_push(p, BC_INST_CALL);
bc_parse_pushIndex(p, nargs);
}
/**
* Parses a function call.
* @param p The parser.
* @param flags Flags restricting what kind of expressions the arguments can
* be.
*/
static void bc_parse_call(BcParse *p, const char *name, uint8_t flags) {
size_t idx;
bc_parse_args(p, flags);
// We just assert this because bc_parse_args() should
// ensure that the next token is what it should be.
assert(p->l.t == BC_LEX_RPAREN);
// We cannot use bc_program_insertFunc() here
// because it will overwrite an existing function.
idx = bc_map_index(&p->prog->fn_map, name);
// The function does not exist yet. Create a space for it. If the user does
// not define it, it's a *runtime* error, not a parse error.
if (idx == BC_VEC_INVALID_IDX) {
BC_SIG_LOCK;
idx = bc_program_insertFunc(p->prog, name);
BC_SIG_UNLOCK;
assert(idx != BC_VEC_INVALID_IDX);
// Make sure that this pointer was not invalidated.
p->func = bc_vec_item(&p->prog->fns, p->fidx);
}
// The function exists, so set the right function index.
else idx = ((BcId*) bc_vec_item(&p->prog->fn_map, idx))->idx;
bc_parse_pushIndex(p, idx);
// Make sure to get the next token.
bc_lex_next(&p->l);
}
/**
* Parses a name/identifier-based expression. It could be a variable, an array
* element, an array itself (for function arguments), a function call, etc.
*
*/
static void bc_parse_name(BcParse *p, BcInst *type,
bool *can_assign, uint8_t flags)
{
char *name;
BC_SIG_LOCK;
// We want a copy of the name since the lexer might overwrite its copy.
name = bc_vm_strdup(p->l.str.v);
BC_SETJMP_LOCKED(err);
BC_SIG_UNLOCK;
// We need the next token to see if it's just a variable or something more.
bc_lex_next(&p->l);
// Array element or array.
if (p->l.t == BC_LEX_LBRACKET) {
bc_lex_next(&p->l);
// Array only. This has to be a function parameter.
if (p->l.t == BC_LEX_RBRACKET) {
// Error if arrays are not allowed.
if (BC_ERR(!(flags & BC_PARSE_ARRAY)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
*type = BC_INST_ARRAY;
*can_assign = false;
}
else {
// If we are here, we have an array element. We need to set the
// expression parsing flags.
uint8_t flags2 = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) |
BC_PARSE_NEEDVAL;
bc_parse_expr_status(p, flags2, bc_parse_next_elem);
// The next token *must* be a right bracket.
if (BC_ERR(p->l.t != BC_LEX_RBRACKET))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
*type = BC_INST_ARRAY_ELEM;
*can_assign = true;
}
// Make sure to get the next token.
bc_lex_next(&p->l);
// Push the instruction and the name of the identifier.
bc_parse_push(p, *type);
bc_parse_pushName(p, name, false);
}
else if (p->l.t == BC_LEX_LPAREN) {
// We are parsing a function call; error if not allowed.
if (BC_ERR(flags & BC_PARSE_NOCALL))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
*type = BC_INST_CALL;
*can_assign = false;
bc_parse_call(p, name, flags);
}
else {
// Just a variable.
*type = BC_INST_VAR;
*can_assign = true;
bc_parse_push(p, BC_INST_VAR);
bc_parse_pushName(p, name, true);
}
err:
// Need to make sure to unallocate the name.
BC_SIG_MAYLOCK;
free(name);
BC_LONGJMP_CONT;
}
/**
* Parses a builtin function that takes no arguments. This includes read(),
* rand(), maxibase(), maxobase(), maxscale(), and maxrand().
* @param p The parser.
* @param inst The instruction corresponding to the builtin.
*/
static void bc_parse_noArgBuiltin(BcParse *p, BcInst inst) {
// Must have a left paren.
bc_lex_next(&p->l);
if (BC_ERR(p->l.t != BC_LEX_LPAREN)) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// Must have a right paren.
bc_lex_next(&p->l);
if ((p->l.t != BC_LEX_RPAREN)) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_parse_push(p, inst);
bc_lex_next(&p->l);
}
/**
* Parses a builtin function that takes 1 argument. This includes length(),
* sqrt(), abs(), scale(), and irand().
* @param p The parser.
* @param type The lex token.
* @param flags The expression parsing flags for parsing the argument.
* @param prev An out parameter; the previous instruction pointer.
*/
static void bc_parse_builtin(BcParse *p, BcLexType type,
uint8_t flags, BcInst *prev)
{
// Must have a left paren.
bc_lex_next(&p->l);
if (BC_ERR(p->l.t != BC_LEX_LPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
// Change the flags as needed for parsing the argument.
flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
flags |= BC_PARSE_NEEDVAL;
// Since length can take arrays, we need to specially add that flag.
if (type == BC_LEX_KW_LENGTH) flags |= BC_PARSE_ARRAY;
bc_parse_expr_status(p, flags, bc_parse_next_rel);
// Must have a right paren.
if (BC_ERR(p->l.t != BC_LEX_RPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// Adjust previous based on the token and push it.
*prev = type - BC_LEX_KW_LENGTH + BC_INST_LENGTH;
bc_parse_push(p, *prev);
bc_lex_next(&p->l);
}
/**
* Parses a builtin function that takes 3 arguments. This includes modexp() and
* divmod().
*/
static void bc_parse_builtin3(BcParse *p, BcLexType type,
uint8_t flags, BcInst *prev)
{
assert(type == BC_LEX_KW_MODEXP || type == BC_LEX_KW_DIVMOD);
// Must have a left paren.
bc_lex_next(&p->l);
if (BC_ERR(p->l.t != BC_LEX_LPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
// Change the flags as needed for parsing the argument.
flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
flags |= BC_PARSE_NEEDVAL;
bc_parse_expr_status(p, flags, bc_parse_next_builtin);
// Must have a comma.
if (BC_ERR(p->l.t != BC_LEX_COMMA))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
bc_parse_expr_status(p, flags, bc_parse_next_builtin);
// Must have a comma.
if (BC_ERR(p->l.t != BC_LEX_COMMA))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
// If it is a divmod, parse an array name. Otherwise, just parse another
// expression.
if (type == BC_LEX_KW_DIVMOD) {
// Must have a name.
if (BC_ERR(p->l.t != BC_LEX_NAME)) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// This is safe because the next token should not overwrite the name.
bc_lex_next(&p->l);
// Must have a left bracket.
if (BC_ERR(p->l.t != BC_LEX_LBRACKET))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// This is safe because the next token should not overwrite the name.
bc_lex_next(&p->l);
// Must have a right bracket.
if (BC_ERR(p->l.t != BC_LEX_RBRACKET))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// This is safe because the next token should not overwrite the name.
bc_lex_next(&p->l);
}
else bc_parse_expr_status(p, flags, bc_parse_next_rel);
// Must have a right paren.
if (BC_ERR(p->l.t != BC_LEX_RPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// Adjust previous based on the token and push it.
*prev = type - BC_LEX_KW_MODEXP + BC_INST_MODEXP;
bc_parse_push(p, *prev);
// If we have divmod, we need to assign the modulus to the array element, so
// we need to push the instructions for doing so.
if (type == BC_LEX_KW_DIVMOD) {
// The zeroth element.
bc_parse_push(p, BC_INST_ZERO);
bc_parse_push(p, BC_INST_ARRAY_ELEM);
// Push the array.
bc_parse_pushName(p, p->l.str.v, false);
// Swap them and assign. After this, the top item on the stack should
// be the quotient.
bc_parse_push(p, BC_INST_SWAP);
bc_parse_push(p, BC_INST_ASSIGN_NO_VAL);
}
bc_lex_next(&p->l);
}
/**
* Parses the scale keyword. This is special because scale can be a value or a
* builtin function.
* @param p The parser.
* @param type An out parameter; the instruction for the parse.
* @param can_assign An out parameter; whether the expression can be assigned
* to.
* @param flags The expression parsing flags for parsing a scale() arg.
*/
static void bc_parse_scale(BcParse *p, BcInst *type,
bool *can_assign, uint8_t flags)
{
bc_lex_next(&p->l);
// Without the left paren, it's just the keyword.
if (p->l.t != BC_LEX_LPAREN) {
// Set, push, and return.
*type = BC_INST_SCALE;
*can_assign = true;
bc_parse_push(p, BC_INST_SCALE);
return;
}
// Handle the scale function.
*type = BC_INST_SCALE_FUNC;
*can_assign = false;
// Once again, adjust the flags.
flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL);
flags |= BC_PARSE_NEEDVAL;
bc_lex_next(&p->l);
bc_parse_expr_status(p, flags, bc_parse_next_rel);
// Must have a right paren.
if (BC_ERR(p->l.t != BC_LEX_RPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_parse_push(p, BC_INST_SCALE_FUNC);
bc_lex_next(&p->l);
}
/**
* Parses and increment or decrement operator. This is a bit complex.
* @param p The parser.
* @param prev An out parameter; the previous instruction pointer.
* @param can_assign An out parameter; whether the expression can be assigned
* to.
* @param nexs An in/out parameter; the number of expressions in the
* parse tree that are not used.
* @param flags The expression parsing flags for parsing a scale() arg.
*/
static void bc_parse_incdec(BcParse *p, BcInst *prev, bool *can_assign,
size_t *nexs, uint8_t flags)
{
BcLexType type;
uchar inst;
BcInst etype = *prev;
BcLexType last = p->l.last;
assert(prev != NULL && can_assign != NULL);
// If we can't assign to the previous token, then we have an error.
if (BC_ERR(last == BC_LEX_OP_INC || last == BC_LEX_OP_DEC ||
last == BC_LEX_RPAREN))
{
bc_parse_err(p, BC_ERR_PARSE_ASSIGN);
}
// Is the previous instruction for a variable?
if (BC_PARSE_INST_VAR(etype)) {
// If so, this is a postfix operator.
if (!*can_assign) bc_parse_err(p, BC_ERR_PARSE_ASSIGN);
// Only postfix uses BC_INST_INC and BC_INST_DEC.
*prev = inst = BC_INST_INC + (p->l.t != BC_LEX_OP_INC);
bc_parse_push(p, inst);
bc_lex_next(&p->l);
*can_assign = false;
}
else {
// This is a prefix operator. In that case, we just convert it to
// an assignment instruction.
*prev = inst = BC_INST_ASSIGN_PLUS + (p->l.t != BC_LEX_OP_INC);
bc_lex_next(&p->l);
type = p->l.t;
// Because we parse the next part of the expression
// right here, we need to increment this.
*nexs = *nexs + 1;
// Is the next token a normal identifier?
if (type == BC_LEX_NAME) {
// Parse the name.
uint8_t flags2 = flags & ~BC_PARSE_ARRAY;
bc_parse_name(p, prev, can_assign, flags2 | BC_PARSE_NOCALL);
}
// Is the next token a global?
else if (type >= BC_LEX_KW_LAST && type <= BC_LEX_KW_OBASE) {
bc_parse_push(p, type - BC_LEX_KW_LAST + BC_INST_LAST);
bc_lex_next(&p->l);
}
// Is the next token specifically scale, which needs special treatment?
else if (BC_NO_ERR(type == BC_LEX_KW_SCALE)) {
bc_lex_next(&p->l);
// Check that scale() was not used.
if (BC_ERR(p->l.t == BC_LEX_LPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
else bc_parse_push(p, BC_INST_SCALE);
}
// Now we know we have an error.
else bc_parse_err(p, BC_ERR_PARSE_TOKEN);
*can_assign = false;
bc_parse_push(p, BC_INST_ONE);
bc_parse_push(p, inst);
}
}
/**
* Parses the minus operator. This needs special treatment because it is either
* subtract or negation.
* @param p The parser.
* @param prev An in/out parameter; the previous instruction.
* @param ops_bgn The size of the operator stack.
* @param rparen True if the last token was a right paren.
* @param binlast True if the last token was a binary operator.
* @param nexprs An in/out parameter; the number of unused expressions.
*/
static void bc_parse_minus(BcParse *p, BcInst *prev, size_t ops_bgn,
bool rparen, bool binlast, size_t *nexprs)
{
BcLexType type;
bc_lex_next(&p->l);
// Figure out if it's a minus or a negation.
type = BC_PARSE_LEAF(*prev, binlast, rparen) ? BC_LEX_OP_MINUS : BC_LEX_NEG;
*prev = BC_PARSE_TOKEN_INST(type);
// We can just push onto the op stack because this is the largest
// precedence operator that gets pushed. Inc/dec does not.
if (type != BC_LEX_OP_MINUS) bc_vec_push(&p->ops, &type);
else bc_parse_operator(p, type, ops_bgn, nexprs);
}
/**
* Parses a string.
* @param p The parser.
* @param inst The instruction corresponding to how the string was found and
* how it should be printed.
*/
static void bc_parse_str(BcParse *p, BcInst inst) {
bc_parse_addString(p);
bc_parse_push(p, inst);
bc_lex_next(&p->l);
}
/**
* Parses a print statement.
* @param p The parser.
*/
static void bc_parse_print(BcParse *p, BcLexType type) {
BcLexType t;
bool comma = false;
BcInst inst = type == BC_LEX_KW_STREAM ?
BC_INST_PRINT_STREAM : BC_INST_PRINT_POP;
bc_lex_next(&p->l);
t = p->l.t;
// A print or stream statement has to have *something*.
if (bc_parse_isDelimiter(p)) bc_parse_err(p, BC_ERR_PARSE_PRINT);
do {
// If the token is a string, then print it with escapes.
// BC_INST_PRINT_POP plays that role for bc.
if (t == BC_LEX_STR) bc_parse_str(p, inst);
else {
// We have an actual number; parse and add a print instruction.
bc_parse_expr_status(p, BC_PARSE_NEEDVAL, bc_parse_next_print);
bc_parse_push(p, inst);
}
// Is the next token a comma?
comma = (p->l.t == BC_LEX_COMMA);
// Get the next token if we have a comma.
if (comma) bc_lex_next(&p->l);
else {
// If we don't have a comma, the statement needs to end.
if (!bc_parse_isDelimiter(p))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
else break;
}
t = p->l.t;
} while (true);
// If we have a comma but no token, that's bad.
if (BC_ERR(comma)) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
}
/**
* Parses a return statement.
* @param p The parser.
*/
static void bc_parse_return(BcParse *p) {
BcLexType t;
bool paren;
uchar inst = BC_INST_RET0;
// If we are not in a function, that's an error.
if (BC_ERR(!BC_PARSE_FUNC(p))) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// If we are in a void function, make sure to return void.
if (p->func->voidfn) inst = BC_INST_RET_VOID;
bc_lex_next(&p->l);
t = p->l.t;
paren = (t == BC_LEX_LPAREN);
// An empty return statement just needs to push the selected instruction.
if (bc_parse_isDelimiter(p)) bc_parse_push(p, inst);
else {
BcParseStatus s;
// Need to parse the expression whose value will be returned.
s = bc_parse_expr_err(p, BC_PARSE_NEEDVAL, bc_parse_next_expr);
// If the expression was empty, just push the selected instruction.
if (s == BC_PARSE_STATUS_EMPTY_EXPR) {
bc_parse_push(p, inst);
bc_lex_next(&p->l);
}
// POSIX requires parentheses.
if (!paren || p->l.last != BC_LEX_RPAREN) {
bc_parse_err(p, BC_ERR_POSIX_RET);
}
// Void functions require an empty expression.
if (BC_ERR(p->func->voidfn)) {
if (s != BC_PARSE_STATUS_EMPTY_EXPR)
bc_parse_verr(p, BC_ERR_PARSE_RET_VOID, p->func->name);
}
// If we got here, we want to be sure to end the function with a real
// return instruction, just in case.
else bc_parse_push(p, BC_INST_RET);
}
}
/**
* Clears flags that indicate the end of an if statement and its block and sets
* the jump location.
* @param p The parser.
*/
static void bc_parse_noElse(BcParse *p) {
uint16_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
*flag_ptr = (*flag_ptr & ~(BC_PARSE_FLAG_IF_END));
bc_parse_setLabel(p);
}
/**
* Ends (finishes parsing) the body of a control statement or a function.
* @param p The parser.
* @param brace True if the body was ended by a brace, false otherwise.
*/
static void bc_parse_endBody(BcParse *p, bool brace) {
bool has_brace, new_else = false;
// We cannot be ending a body if there are no bodies to end.
if (BC_ERR(p->flags.len <= 1)) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
if (brace) {
// The brace was already gotten; make sure that the caller did not lie.
// We check for the requirement of braces later.
assert(p->l.t == BC_LEX_RBRACE);
bc_lex_next(&p->l);
// If the next token is not a delimiter, that is a problem.
if (BC_ERR(!bc_parse_isDelimiter(p)))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
}
// Do we have a brace flag?
has_brace = (BC_PARSE_BRACE(p) != 0);
do {
size_t len = p->flags.len;
bool loop;
// If we have a brace flag but not a brace, that's a problem.
if (has_brace && !brace) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// Are we inside a loop?
loop = (BC_PARSE_LOOP_INNER(p) != 0);
// If we are ending a loop or an else...
if (loop || BC_PARSE_ELSE(p)) {
// Loops have condition labels that we have to take care of as well.
if (loop) {
size_t *label = bc_vec_top(&p->conds);
bc_parse_push(p, BC_INST_JUMP);
bc_parse_pushIndex(p, *label);
bc_vec_pop(&p->conds);
}
bc_parse_setLabel(p);
bc_vec_pop(&p->flags);
}
// If we are ending a function...
else if (BC_PARSE_FUNC_INNER(p)) {
BcInst inst = (p->func->voidfn ? BC_INST_RET_VOID : BC_INST_RET0);
bc_parse_push(p, inst);
bc_parse_updateFunc(p, BC_PROG_MAIN);
bc_vec_pop(&p->flags);
}
// If we have a brace flag and not an if statement, we can pop the top
// of the flags stack because they have been taken care of above.
else if (has_brace && !BC_PARSE_IF(p)) bc_vec_pop(&p->flags);
// This needs to be last to parse nested if's properly.
if (BC_PARSE_IF(p) && (len == p->flags.len || !BC_PARSE_BRACE(p))) {
// Eat newlines.
while (p->l.t == BC_LEX_NLINE) bc_lex_next(&p->l);
// *Now* we can pop the flags.
bc_vec_pop(&p->flags);
// If we are allowed non-POSIX stuff...
if (!BC_S) {
// Have we found yet another dangling else?
*(BC_PARSE_TOP_FLAG_PTR(p)) |= BC_PARSE_FLAG_IF_END;
new_else = (p->l.t == BC_LEX_KW_ELSE);
// Parse the else or end the if statement body.
if (new_else) bc_parse_else(p);
else if (!has_brace && (!BC_PARSE_IF_END(p) || brace))
bc_parse_noElse(p);
}
// POSIX requires us to do the bare minimum only.
else bc_parse_noElse(p);
}
// If these are both true, we have "used" the braces that we found.
if (brace && has_brace) brace = false;
// This condition was perhaps the hardest single part of the parser. If the
// flags stack does not have enough, we should stop. If we have a new else
// statement, we should stop. If we do have the end of an if statement and
// we have eaten the brace, we should stop. If we do have a brace flag, we
// should stop.
} while (p->flags.len > 1 && !new_else && (!BC_PARSE_IF_END(p) || brace) &&
!(has_brace = (BC_PARSE_BRACE(p) != 0)));
// If we have a brace, yet no body for it, that's a problem.
if (BC_ERR(p->flags.len == 1 && brace))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
else if (brace && BC_PARSE_BRACE(p)) {
// If we make it here, we have a brace and a flag for it.
uint16_t flags = BC_PARSE_TOP_FLAG(p);
// This condition ensure that the *last* body is correctly finished by
// popping its flags.
if (!(flags & (BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_LOOP_INNER)) &&
!(flags & (BC_PARSE_FLAG_IF | BC_PARSE_FLAG_ELSE)) &&
!(flags & (BC_PARSE_FLAG_IF_END)))
{
bc_vec_pop(&p->flags);
}
}
}
/**
* Starts the body of a control statement or function.
* @param p The parser.
* @param flags The current flags (will be edited).
*/
static void bc_parse_startBody(BcParse *p, uint16_t flags) {
assert(flags);
flags |= (BC_PARSE_TOP_FLAG(p) & (BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_LOOP));
flags |= BC_PARSE_FLAG_BODY;
bc_vec_push(&p->flags, &flags);
}
/**
* Parses an if statement.
* @param p The parser.
*/
static void bc_parse_if(BcParse *p) {
// We are allowed relational operators, and we must have a value.
size_t idx;
uint8_t flags = (BC_PARSE_REL | BC_PARSE_NEEDVAL);
// Get the left paren and barf if necessary.
bc_lex_next(&p->l);
if (BC_ERR(p->l.t != BC_LEX_LPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// Parse the condition.
bc_lex_next(&p->l);
bc_parse_expr_status(p, flags, bc_parse_next_rel);
// Must have a right paren.
if (BC_ERR(p->l.t != BC_LEX_RPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
// Insert the conditional jump instruction.
bc_parse_push(p, BC_INST_JUMP_ZERO);
idx = p->func->labels.len;
// Push the index for the instruction and create an exit label for an else
// statement.
bc_parse_pushIndex(p, idx);
bc_parse_createExitLabel(p, idx, false);
bc_parse_startBody(p, BC_PARSE_FLAG_IF);
}
/**
* Parses an else statement.
* @param p The parser.
*/
static void bc_parse_else(BcParse *p) {
size_t idx = p->func->labels.len;
// We must be at the end of an if statement.
if (BC_ERR(!BC_PARSE_IF_END(p)))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// Push an unconditional jump to make bc jump over the else statement if it
// executed the original if statement.
bc_parse_push(p, BC_INST_JUMP);
bc_parse_pushIndex(p, idx);
// Clear the else stuff. Yes, that function is misnamed for its use here,
// but deal with it.
bc_parse_noElse(p);
// Create the exit label and parse the body.
bc_parse_createExitLabel(p, idx, false);
bc_parse_startBody(p, BC_PARSE_FLAG_ELSE);
bc_lex_next(&p->l);
}
/**
* Parse a while loop.
* @param p The parser.
*/
static void bc_parse_while(BcParse *p) {
// We are allowed relational operators, and we must have a value.
size_t idx;
uint8_t flags = (BC_PARSE_REL | BC_PARSE_NEEDVAL);
// Get the left paren and barf if necessary.
bc_lex_next(&p->l);
if (BC_ERR(p->l.t != BC_LEX_LPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
// Create the labels. Loops need both.
bc_parse_createCondLabel(p, p->func->labels.len);
idx = p->func->labels.len;
bc_parse_createExitLabel(p, idx, true);
// Parse the actual condition and barf on non-right paren.
bc_parse_expr_status(p, flags, bc_parse_next_rel);
if (BC_ERR(p->l.t != BC_LEX_RPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
// Now we can push the conditional jump and start the body.
bc_parse_push(p, BC_INST_JUMP_ZERO);
bc_parse_pushIndex(p, idx);
bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
}
/**
* Parse a for loop.
* @param p The parser.
*/
static void bc_parse_for(BcParse *p) {
size_t cond_idx, exit_idx, body_idx, update_idx;
// Barf on the missing left paren.
bc_lex_next(&p->l);
if (BC_ERR(p->l.t != BC_LEX_LPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
// The first statement can be empty, but if it is, check for error in POSIX
// mode. Otherwise, parse it.
if (p->l.t != BC_LEX_SCOLON)
bc_parse_expr_status(p, 0, bc_parse_next_for);
else bc_parse_err(p, BC_ERR_POSIX_FOR);
// Must have a semicolon.
if (BC_ERR(p->l.t != BC_LEX_SCOLON)) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
// These are indices for labels. There are so many of them because the end
// of the loop must unconditionally jump to the update code. Then the update
// code must unconditionally jump to the condition code. Then the condition
// code must *conditionally* jump to the exit.
cond_idx = p->func->labels.len;
update_idx = cond_idx + 1;
body_idx = update_idx + 1;
exit_idx = body_idx + 1;
// This creates the condition label.
bc_parse_createLabel(p, p->func->code.len);
// Parse an expression if it exists.
if (p->l.t != BC_LEX_SCOLON) {
uint8_t flags = (BC_PARSE_REL | BC_PARSE_NEEDVAL);
bc_parse_expr_status(p, flags, bc_parse_next_for);
}
else {
// Set this for the next call to bc_parse_number because an empty
// condition means that it is an infinite loop, so the condition must be
// non-zero. This is safe to set because the current token is a
// semicolon, which has no string requirement.
bc_vec_string(&p->l.str, sizeof(bc_parse_one) - 1, bc_parse_one);
bc_parse_number(p);
// An empty condition makes POSIX mad.
bc_parse_err(p, BC_ERR_POSIX_FOR);
}
// Must have a semicolon.
if (BC_ERR(p->l.t != BC_LEX_SCOLON))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
// Now we can set up the conditional jump to the exit and an unconditional
// jump to the body right after. The unconditional jump to the body is
// because there is update code coming right after the condition, so we need
// to skip it to get to the body.
bc_parse_push(p, BC_INST_JUMP_ZERO);
bc_parse_pushIndex(p, exit_idx);
bc_parse_push(p, BC_INST_JUMP);
bc_parse_pushIndex(p, body_idx);
// Now create the label for the update code.
bc_parse_createCondLabel(p, update_idx);
// Parse if not empty, and if it is, let POSIX yell if necessary.
if (p->l.t != BC_LEX_RPAREN)
bc_parse_expr_status(p, 0, bc_parse_next_rel);
else bc_parse_err(p, BC_ERR_POSIX_FOR);
// Must have a right paren.
if (BC_ERR(p->l.t != BC_LEX_RPAREN))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// Set up a jump to the condition right after the update code.
bc_parse_push(p, BC_INST_JUMP);
bc_parse_pushIndex(p, cond_idx);
bc_parse_createLabel(p, p->func->code.len);
// Create an exit label for the body and start the body.
bc_parse_createExitLabel(p, exit_idx, true);
bc_lex_next(&p->l);
bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER);
}
/**
* Parse a statement or token that indicates a loop exit. This includes an
* actual loop exit, the break keyword, or the continue keyword.
* @param p The parser.
* @param type The type of exit.
*/
static void bc_parse_loopExit(BcParse *p, BcLexType type) {
size_t i;
BcInstPtr *ip;
// Must have a loop. If we don't, that's an error.
if (BC_ERR(!BC_PARSE_LOOP(p))) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// If we have a break statement...
if (type == BC_LEX_KW_BREAK) {
// If there are no exits, something went wrong somewhere.
if (BC_ERR(!p->exits.len)) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// Get the exit.
i = p->exits.len - 1;
ip = bc_vec_item(&p->exits, i);
// The condition !ip->func is true if the exit is not for a loop, so we
// need to find the first actual loop exit.
while (!ip->func && i < p->exits.len) ip = bc_vec_item(&p->exits, i--);
// Make sure everything is hunky dory.
assert(ip != NULL && (i < p->exits.len || ip->func));
// Set the index for the exit.
i = ip->idx;
}
// If we have a continue statement or just the loop end, jump to the
// condition (or update for a foor loop).
else i = *((size_t*) bc_vec_top(&p->conds));
// Add the unconditional jump.
bc_parse_push(p, BC_INST_JUMP);
bc_parse_pushIndex(p, i);
bc_lex_next(&p->l);
}
/**
* Parse a function (header).
* @param p The parser.
*/
static void bc_parse_func(BcParse *p) {
bool comma = false, voidfn;
uint16_t flags;
size_t idx;
bc_lex_next(&p->l);
// Must have a name.
if (BC_ERR(p->l.t != BC_LEX_NAME)) bc_parse_err(p, BC_ERR_PARSE_FUNC);
// If the name is "void", and POSIX is not on, mark as void.
voidfn = (!BC_IS_POSIX && p->l.t == BC_LEX_NAME &&
!strcmp(p->l.str.v, "void"));
// We can safely do this because the expected token should not overwrite the
// function name.
bc_lex_next(&p->l);
// If we *don't* have another name, then void is the name of the function.
voidfn = (voidfn && p->l.t == BC_LEX_NAME);
// With a void function, allow POSIX to complain and get a new token.
if (voidfn) {
bc_parse_err(p, BC_ERR_POSIX_VOID);
// We can safely do this because the expected token should not overwrite
// the function name.
bc_lex_next(&p->l);
}
// Must have a left paren.
if (BC_ERR(p->l.t != BC_LEX_LPAREN))
bc_parse_err(p, BC_ERR_PARSE_FUNC);
// Make sure the functions map and vector are synchronized.
assert(p->prog->fns.len == p->prog->fn_map.len);
// Must lock signals because vectors are changed, and the vector functions
// expect signals to be locked.
BC_SIG_LOCK;
// Insert the function by name into the map and vector.
idx = bc_program_insertFunc(p->prog, p->l.str.v);
BC_SIG_UNLOCK;
// Make sure the insert worked.
assert(idx);
// Update the function pointer and stuff in the parser and set its void.
bc_parse_updateFunc(p, idx);
p->func->voidfn = voidfn;
bc_lex_next(&p->l);
// While we do not have a right paren, we are still parsing arguments.
while (p->l.t != BC_LEX_RPAREN) {
BcType t = BC_TYPE_VAR;
// If we have an asterisk, we are parsing a reference argument.
if (p->l.t == BC_LEX_OP_MULTIPLY) {
t = BC_TYPE_REF;
bc_lex_next(&p->l);
// Let POSIX complain if necessary.
bc_parse_err(p, BC_ERR_POSIX_REF);
}
// If we don't have a name, the argument will not have a name. Barf.
if (BC_ERR(p->l.t != BC_LEX_NAME))
bc_parse_err(p, BC_ERR_PARSE_FUNC);
// Increment the number of parameters.
p->func->nparams += 1;
// Copy the string in the lexer so that we can use the lexer again.
bc_vec_string(&p->buf, p->l.str.len, p->l.str.v);
bc_lex_next(&p->l);
// We are parsing an array parameter if this is true.
if (p->l.t == BC_LEX_LBRACKET) {
// Set the array type, unless we are already parsing a reference.
if (t == BC_TYPE_VAR) t = BC_TYPE_ARRAY;
bc_lex_next(&p->l);
// The brackets *must* be empty.
if (BC_ERR(p->l.t != BC_LEX_RBRACKET))
bc_parse_err(p, BC_ERR_PARSE_FUNC);
bc_lex_next(&p->l);
}
// If we did *not* get a bracket, but we are expecting a reference, we
// have a problem.
else if (BC_ERR(t == BC_TYPE_REF))
bc_parse_verr(p, BC_ERR_PARSE_REF_VAR, p->buf.v);
// Test for comma and get the next token if it exists.
comma = (p->l.t == BC_LEX_COMMA);
if (comma) bc_lex_next(&p->l);
// Insert the parameter into the function.
bc_func_insert(p->func, p->prog, p->buf.v, t, p->l.line);
}
// If we have a comma, but no parameter, barf.
if (BC_ERR(comma)) bc_parse_err(p, BC_ERR_PARSE_FUNC);
// Start the body.
flags = BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_FUNC_INNER;
bc_parse_startBody(p, flags);
bc_lex_next(&p->l);
// POSIX requires that a brace be on the same line as the function header.
// If we don't have a brace, let POSIX throw an error.
if (p->l.t != BC_LEX_LBRACE) bc_parse_err(p, BC_ERR_POSIX_BRACE);
}
/**
* Parse an auto list.
* @param p The parser.
*/
static void bc_parse_auto(BcParse *p) {
bool comma, one;
// Error if the auto keyword appeared in the wrong place.
if (BC_ERR(!p->auto_part)) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_lex_next(&p->l);
p->auto_part = comma = false;
// We need at least one variable or array.
one = (p->l.t == BC_LEX_NAME);
// While we have a variable or array.
while (p->l.t == BC_LEX_NAME) {
BcType t;
// Copy the name from the lexer, so we can use it again.
bc_vec_string(&p->buf, p->l.str.len - 1, p->l.str.v);
bc_lex_next(&p->l);
// If we are parsing an array...
if (p->l.t == BC_LEX_LBRACKET) {
t = BC_TYPE_ARRAY;
bc_lex_next(&p->l);
// The brackets *must* be empty.
if (BC_ERR(p->l.t != BC_LEX_RBRACKET))
bc_parse_err(p, BC_ERR_PARSE_FUNC);
bc_lex_next(&p->l);
}
else t = BC_TYPE_VAR;
// Test for comma and get the next token if it exists.
comma = (p->l.t == BC_LEX_COMMA);
if (comma) bc_lex_next(&p->l);
// Insert the auto into the function.
bc_func_insert(p->func, p->prog, p->buf.v, t, p->l.line);
}
// If we have a comma, but no auto, barf.
if (BC_ERR(comma)) bc_parse_err(p, BC_ERR_PARSE_FUNC);
// If we don't have any variables or arrays, barf.
if (BC_ERR(!one)) bc_parse_err(p, BC_ERR_PARSE_NO_AUTO);
// The auto statement should be all that's in the statement.
if (BC_ERR(!bc_parse_isDelimiter(p)))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
}
/**
* Parses a body.
* @param p The parser.
* @param brace True if a brace was encountered, false otherwise.
*/
static void bc_parse_body(BcParse *p, bool brace) {
uint16_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p);
assert(flag_ptr != NULL);
assert(p->flags.len >= 2);
// The body flag is for when we expect a body. We got a body, so clear the
// flag.
*flag_ptr &= ~(BC_PARSE_FLAG_BODY);
// If we are inside a function, that means we just barely entered it, and
// we can expect an auto list.
if (*flag_ptr & BC_PARSE_FLAG_FUNC_INNER) {
// We *must* have a brace in this case.
if (BC_ERR(!brace)) bc_parse_err(p, BC_ERR_PARSE_TOKEN);
p->auto_part = (p->l.t != BC_LEX_KW_AUTO);
if (!p->auto_part) {
// Make sure this is true to not get a parse error.
p->auto_part = true;
// Since we already have the auto keyword, parse.
bc_parse_auto(p);
}
// Eat a newline.
if (p->l.t == BC_LEX_NLINE) bc_lex_next(&p->l);
}
else {
// This is the easy part.
size_t len = p->flags.len;
assert(*flag_ptr);
// Parse a statement.
bc_parse_stmt(p);
// This is a very important condition to get right. If there is no
// brace, and no body flag, and the flags len hasn't shrunk, then we
// have a body that was not delimited by braces, so we need to end it
// now, after just one statement.
if (!brace && !BC_PARSE_BODY(p) && len <= p->flags.len)
bc_parse_endBody(p, false);
}
}
/**
* Parses a statement. This is the entry point for just about everything, except
* function definitions.
* @param p The parser.
*/
static void bc_parse_stmt(BcParse *p) {
size_t len;
uint16_t flags;
BcLexType type = p->l.t;
// Eat newline.
if (type == BC_LEX_NLINE) {
bc_lex_next(&p->l);
return;
}
// Eat auto list.
if (type == BC_LEX_KW_AUTO) {
bc_parse_auto(p);
return;
}
// If we reach this point, no auto list is allowed.
p->auto_part = false;
// Everything but an else needs to be taken care of here, but else is
// special.
if (type != BC_LEX_KW_ELSE) {
// After an if, no else found.
if (BC_PARSE_IF_END(p)) {
// Clear the expectation for else, end body, and return. Returning
// gives us a clean slate for parsing again.
bc_parse_noElse(p);
if (p->flags.len > 1 && !BC_PARSE_BRACE(p))
bc_parse_endBody(p, false);
return;
}
// With a left brace, we are parsing a body.
else if (type == BC_LEX_LBRACE) {
// We need to start a body if we are not expecting one yet.
if (!BC_PARSE_BODY(p)) {
bc_parse_startBody(p, BC_PARSE_FLAG_BRACE);
bc_lex_next(&p->l);
}
// If we *are* expecting a body, that body should get a brace. This
// takes care of braces being on a different line than if and loop
// headers.
else {
*(BC_PARSE_TOP_FLAG_PTR(p)) |= BC_PARSE_FLAG_BRACE;
bc_lex_next(&p->l);
bc_parse_body(p, true);
}
// If we have reached this point, we need to return for a clean
// slate.
return;
}
// This happens when we are expecting a body and get a single statement,
// i.e., a body with no braces surrounding it. Returns after for a clean
// slate.
else if (BC_PARSE_BODY(p) && !BC_PARSE_BRACE(p)) {
bc_parse_body(p, false);
return;
}
}
len = p->flags.len;
flags = BC_PARSE_TOP_FLAG(p);
switch (type) {
// All of these are valid for expressions.
case BC_LEX_OP_INC:
case BC_LEX_OP_DEC:
case BC_LEX_OP_MINUS:
case BC_LEX_OP_BOOL_NOT:
case BC_LEX_LPAREN:
case BC_LEX_NAME:
case BC_LEX_NUMBER:
case BC_LEX_KW_IBASE:
case BC_LEX_KW_LAST:
case BC_LEX_KW_LENGTH:
case BC_LEX_KW_OBASE:
case BC_LEX_KW_SCALE:
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_SEED:
#endif // BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_SQRT:
case BC_LEX_KW_ABS:
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_IRAND:
#endif // BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_ASCIIFY:
case BC_LEX_KW_MODEXP:
case BC_LEX_KW_DIVMOD:
case BC_LEX_KW_READ:
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_RAND:
#endif // BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_MAXIBASE:
case BC_LEX_KW_MAXOBASE:
case BC_LEX_KW_MAXSCALE:
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_MAXRAND:
#endif // BC_ENABLE_EXTRA_MATH
{
bc_parse_expr_status(p, BC_PARSE_PRINT, bc_parse_next_expr);
break;
}
case BC_LEX_KW_ELSE:
{
bc_parse_else(p);
break;
}
// Just eat.
case BC_LEX_SCOLON:
{
// Do nothing.
break;
}
case BC_LEX_RBRACE:
{
bc_parse_endBody(p, true);
break;
}
case BC_LEX_STR:
{
bc_parse_str(p, BC_INST_PRINT_STR);
break;
}
case BC_LEX_KW_BREAK:
case BC_LEX_KW_CONTINUE:
{
bc_parse_loopExit(p, p->l.t);
break;
}
case BC_LEX_KW_FOR:
{
bc_parse_for(p);
break;
}
case BC_LEX_KW_HALT:
{
bc_parse_push(p, BC_INST_HALT);
bc_lex_next(&p->l);
break;
}
case BC_LEX_KW_IF:
{
bc_parse_if(p);
break;
}
case BC_LEX_KW_LIMITS:
{
// `limits` is a compile-time command, so execute it right away.
bc_vm_printf("BC_LONG_BIT = %lu\n", (ulong) BC_LONG_BIT);
bc_vm_printf("BC_BASE_DIGS = %lu\n", (ulong) BC_BASE_DIGS);
bc_vm_printf("BC_BASE_POW = %lu\n", (ulong) BC_BASE_POW);
bc_vm_printf("BC_OVERFLOW_MAX = %lu\n", (ulong) BC_NUM_BIGDIG_MAX);
bc_vm_printf("\n");
bc_vm_printf("BC_BASE_MAX = %lu\n", BC_MAX_OBASE);
bc_vm_printf("BC_DIM_MAX = %lu\n", BC_MAX_DIM);
bc_vm_printf("BC_SCALE_MAX = %lu\n", BC_MAX_SCALE);
bc_vm_printf("BC_STRING_MAX = %lu\n", BC_MAX_STRING);
bc_vm_printf("BC_NAME_MAX = %lu\n", BC_MAX_NAME);
bc_vm_printf("BC_NUM_MAX = %lu\n", BC_MAX_NUM);
#if BC_ENABLE_EXTRA_MATH
bc_vm_printf("BC_RAND_MAX = %lu\n", BC_MAX_RAND);
#endif // BC_ENABLE_EXTRA_MATH
bc_vm_printf("MAX Exponent = %lu\n", BC_MAX_EXP);
bc_vm_printf("Number of vars = %lu\n", BC_MAX_VARS);
bc_lex_next(&p->l);
break;
}
case BC_LEX_KW_STREAM:
case BC_LEX_KW_PRINT:
{
bc_parse_print(p, type);
break;
}
case BC_LEX_KW_QUIT:
{
// Quit is a compile-time command. We don't exit directly, so the vm
// can clean up.
vm.status = BC_STATUS_QUIT;
BC_JMP;
break;
}
case BC_LEX_KW_RETURN:
{
bc_parse_return(p);
break;
}
case BC_LEX_KW_WHILE:
{
bc_parse_while(p);
break;
}
default:
{
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
}
}
// If the flags did not change, we expect a delimiter.
if (len == p->flags.len && flags == BC_PARSE_TOP_FLAG(p)) {
if (BC_ERR(!bc_parse_isDelimiter(p)))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
}
// Make sure semicolons are eaten.
while (p->l.t == BC_LEX_SCOLON) bc_lex_next(&p->l);
}
void bc_parse_parse(BcParse *p) {
assert(p);
BC_SETJMP(exit);
// We should not let an EOF get here unless some partial parse was not
// completed, in which case, it's the user's fault.
if (BC_ERR(p->l.t == BC_LEX_EOF)) bc_parse_err(p, BC_ERR_PARSE_EOF);
// Functions need special parsing.
else if (p->l.t == BC_LEX_KW_DEFINE) {
if (BC_ERR(BC_PARSE_NO_EXEC(p)))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
bc_parse_func(p);
}
// Otherwise, parse a normal statement.
else bc_parse_stmt(p);
exit:
BC_SIG_MAYLOCK;
// We need to reset on error.
if (BC_ERR(((vm.status && vm.status != BC_STATUS_QUIT) || vm.sig)))
bc_parse_reset(p);
BC_LONGJMP_CONT;
}
/**
* Parse an expression. This is the actual implementation of the Shunting-Yard
* Algorithm.
* @param p The parser.
* @param flags The flags for what is valid in the expression.
* @param next A set of tokens for what is valid *after* the expression.
* @return A parse status. In some places, an empty expression is an
* error, and sometimes, it is required. This allows this function
* to tell the caller if the expression was empty and let the
* caller handle it.
*/
static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags,
BcParseNext next)
{
BcInst prev = BC_INST_PRINT;
uchar inst = BC_INST_INVALID;
BcLexType top, t;
size_t nexprs, ops_bgn;
uint32_t i, nparens, nrelops;
bool pfirst, rprn, done, get_token, assign, bin_last, incdec, can_assign;
// One of these *must* be true.
assert(!(flags & BC_PARSE_PRINT) || !(flags & BC_PARSE_NEEDVAL));
// These are set very carefully. In fact, controlling the values of these
// locals is the biggest part of making this work. ops_bgn especially is
// important because it marks where the operator stack begins for *this*
// invocation of this function. That's because bc_parse_expr_err() is
// recursive (the Shunting-Yard Algorithm is most easily expressed
// recursively when parsing subexpressions), and each invocation needs to
// know where to stop.
//
// - nparens is the number of left parens without matches.
// - nrelops is the number of relational operators that appear in the expr.
// - nexprs is the number of unused expressions.
// - rprn is a right paren encountered last.
// - done means the expression has been fully parsed.
// - get_token is true when a token is needed at the end of an iteration.
// - assign is true when an assignment statement was parsed last.
// - incdec is true when the previous operator was an inc or dec operator.
// - can_assign is true when an assignemnt is valid.
// - bin_last is true when the previous instruction was a binary operator.
t = p->l.t;
pfirst = (p->l.t == BC_LEX_LPAREN);
nparens = nrelops = 0;
nexprs = 0;
ops_bgn = p->ops.len;
rprn = done = get_token = assign = incdec = can_assign = false;
bin_last = true;
// We want to eat newlines if newlines are not a valid ending token.
// This is for spacing in things like for loop headers.
if (!(flags & BC_PARSE_NOREAD)) {
while ((t = p->l.t) == BC_LEX_NLINE) bc_lex_next(&p->l);
}
// This is the Shunting-Yard algorithm loop.
for (; !done && BC_PARSE_EXPR(t); t = p->l.t)
{
switch (t) {
case BC_LEX_OP_INC:
case BC_LEX_OP_DEC:
{
// These operators can only be used with items that can be
// assigned to.
if (BC_ERR(incdec)) bc_parse_err(p, BC_ERR_PARSE_ASSIGN);
bc_parse_incdec(p, &prev, &can_assign, &nexprs, flags);
rprn = get_token = bin_last = false;
incdec = true;
flags &= ~(BC_PARSE_ARRAY);
break;
}
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_OP_TRUNC:
{
// The previous token must have been a leaf expression, or the
// operator is in the wrong place.
if (BC_ERR(!BC_PARSE_LEAF(prev, bin_last, rprn)))
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
// I can just add the instruction because
// negative will already be taken care of.
bc_parse_push(p, BC_INST_TRUNC);
rprn = can_assign = incdec = false;
get_token = true;
flags &= ~(BC_PARSE_ARRAY);
break;
}
#endif // BC_ENABLE_EXTRA_MATH
case BC_LEX_OP_MINUS:
{
bc_parse_minus(p, &prev, ops_bgn, rprn, bin_last, &nexprs);
rprn = get_token = can_assign = false;
// This is true if it was a binary operator last.
bin_last = (prev == BC_INST_MINUS);
if (bin_last) incdec = false;
flags &= ~(BC_PARSE_ARRAY);
break;
}
// All of this group, including the fallthrough, is to parse binary
// operators.
case BC_LEX_OP_ASSIGN_POWER:
case BC_LEX_OP_ASSIGN_MULTIPLY:
case BC_LEX_OP_ASSIGN_DIVIDE:
case BC_LEX_OP_ASSIGN_MODULUS:
case BC_LEX_OP_ASSIGN_PLUS:
case BC_LEX_OP_ASSIGN_MINUS:
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_OP_ASSIGN_PLACES:
case BC_LEX_OP_ASSIGN_LSHIFT:
case BC_LEX_OP_ASSIGN_RSHIFT:
#endif // BC_ENABLE_EXTRA_MATH
case BC_LEX_OP_ASSIGN:
{
// We need to make sure the assignment is valid.
if (!BC_PARSE_INST_VAR(prev))
bc_parse_err(p, BC_ERR_PARSE_ASSIGN);
}
// Fallthrough.
BC_FALLTHROUGH
case BC_LEX_OP_POWER:
case BC_LEX_OP_MULTIPLY:
case BC_LEX_OP_DIVIDE:
case BC_LEX_OP_MODULUS:
case BC_LEX_OP_PLUS:
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_OP_PLACES:
case BC_LEX_OP_LSHIFT:
case BC_LEX_OP_RSHIFT:
#endif // BC_ENABLE_EXTRA_MATH
case BC_LEX_OP_REL_EQ:
case BC_LEX_OP_REL_LE:
case BC_LEX_OP_REL_GE:
case BC_LEX_OP_REL_NE:
case BC_LEX_OP_REL_LT:
case BC_LEX_OP_REL_GT:
case BC_LEX_OP_BOOL_NOT:
case BC_LEX_OP_BOOL_OR:
case BC_LEX_OP_BOOL_AND:
{
// This is true if the operator if the token is a prefix
// operator. This is only for boolean not.
if (BC_PARSE_OP_PREFIX(t)) {
// Prefix operators are only allowed after binary operators
// or prefix operators.
if (BC_ERR(!bin_last && !BC_PARSE_OP_PREFIX(p->l.last)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
}
// If we execute the else, that means we have a binary operator.
// If the previous operator was a prefix or a binary operator,
// then a binary operator is not allowed.
else if (BC_ERR(BC_PARSE_PREV_PREFIX(prev) || bin_last))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
nrelops += (t >= BC_LEX_OP_REL_EQ && t <= BC_LEX_OP_REL_GT);
prev = BC_PARSE_TOKEN_INST(t);
bc_parse_operator(p, t, ops_bgn, &nexprs);
rprn = incdec = can_assign = false;
get_token = true;
bin_last = !BC_PARSE_OP_PREFIX(t);
flags &= ~(BC_PARSE_ARRAY);
break;
}
case BC_LEX_LPAREN:
{
// A left paren is *not* allowed right after a leaf expr.
if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
nparens += 1;
rprn = incdec = can_assign = false;
get_token = true;
// Push the paren onto the operator stack.
bc_vec_push(&p->ops, &t);
break;
}
case BC_LEX_RPAREN:
{
// This needs to be a status. The error is handled in
// bc_parse_expr_status().
if (BC_ERR(p->l.last == BC_LEX_LPAREN))
return BC_PARSE_STATUS_EMPTY_EXPR;
// The right paren must not come after a prefix or binary
// operator.
if (BC_ERR(bin_last || BC_PARSE_PREV_PREFIX(prev)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
// If there are no parens left, we are done, but we need another
// token.
if (!nparens) {
done = true;
get_token = false;
break;
}
nparens -= 1;
rprn = true;
get_token = bin_last = incdec = false;
bc_parse_rightParen(p, &nexprs);
break;
}
case BC_LEX_STR:
{
// POSIX only allows strings alone.
if (BC_IS_POSIX) bc_parse_err(p, BC_ERR_POSIX_EXPR_STRING);
// A string is a leaf and cannot come right after a leaf.
if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
bc_parse_addString(p);
get_token = true;
bin_last = rprn = false;
nexprs += 1;
break;
}
case BC_LEX_NAME:
{
// A name is a leaf and cannot come right after a leaf.
if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
get_token = bin_last = false;
bc_parse_name(p, &prev, &can_assign, flags & ~BC_PARSE_NOCALL);
rprn = (prev == BC_INST_CALL);
nexprs += 1;
flags &= ~(BC_PARSE_ARRAY);
break;
}
case BC_LEX_NUMBER:
{
// A number is a leaf and cannot come right after a leaf.
if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
// The number instruction is pushed in here.
bc_parse_number(p);
nexprs += 1;
prev = BC_INST_NUM;
get_token = true;
rprn = bin_last = can_assign = false;
flags &= ~(BC_PARSE_ARRAY);
break;
}
case BC_LEX_KW_IBASE:
case BC_LEX_KW_LAST:
case BC_LEX_KW_OBASE:
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_SEED:
#endif // BC_ENABLE_EXTRA_MATH
{
// All of these are leaves and cannot come right after a leaf.
if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
prev = t - BC_LEX_KW_LAST + BC_INST_LAST;
bc_parse_push(p, prev);
get_token = can_assign = true;
rprn = bin_last = false;
nexprs += 1;
flags &= ~(BC_PARSE_ARRAY);
break;
}
case BC_LEX_KW_LENGTH:
case BC_LEX_KW_SQRT:
case BC_LEX_KW_ABS:
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_IRAND:
#endif // BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_ASCIIFY:
{
// All of these are leaves and cannot come right after a leaf.
if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
bc_parse_builtin(p, t, flags, &prev);
rprn = get_token = bin_last = incdec = can_assign = false;
nexprs += 1;
flags &= ~(BC_PARSE_ARRAY);
break;
}
case BC_LEX_KW_READ:
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_RAND:
#endif // BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_MAXIBASE:
case BC_LEX_KW_MAXOBASE:
case BC_LEX_KW_MAXSCALE:
#if BC_ENABLE_EXTRA_MATH
case BC_LEX_KW_MAXRAND:
#endif // BC_ENABLE_EXTRA_MATH
{
// All of these are leaves and cannot come right after a leaf.
if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
// Error if we have read and it's not allowed.
else if (t == BC_LEX_KW_READ && BC_ERR(flags & BC_PARSE_NOREAD))
bc_parse_err(p, BC_ERR_EXEC_REC_READ);
prev = t - BC_LEX_KW_READ + BC_INST_READ;
bc_parse_noArgBuiltin(p, prev);
rprn = get_token = bin_last = incdec = can_assign = false;
nexprs += 1;
flags &= ~(BC_PARSE_ARRAY);
break;
}
case BC_LEX_KW_SCALE:
{
// This is a leaf and cannot come right after a leaf.
if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
// Scale needs special work because it can be a variable *or* a
// function.
bc_parse_scale(p, &prev, &can_assign, flags);
rprn = get_token = bin_last = false;
nexprs += 1;
flags &= ~(BC_PARSE_ARRAY);
break;
}
case BC_LEX_KW_MODEXP:
case BC_LEX_KW_DIVMOD:
{
// This is a leaf and cannot come right after a leaf.
if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
bc_parse_builtin3(p, t, flags, &prev);
rprn = get_token = bin_last = incdec = can_assign = false;
nexprs += 1;
flags &= ~(BC_PARSE_ARRAY);
break;
}
default:
{
#ifndef NDEBUG
// We should never get here, even in debug builds.
bc_parse_err(p, BC_ERR_PARSE_TOKEN);
break;
#endif // NDEBUG
}
}
if (get_token) bc_lex_next(&p->l);
}
// Now that we have parsed the expression, we need to empty the operator
// stack.
while (p->ops.len > ops_bgn) {
top = BC_PARSE_TOP_OP(p);
assign = top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN;
// There should not be *any* parens on the stack anymore.
if (BC_ERR(top == BC_LEX_LPAREN || top == BC_LEX_RPAREN))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
bc_parse_push(p, BC_PARSE_TOKEN_INST(top));
// Adjust the number of unused expressions.
nexprs -= !BC_PARSE_OP_PREFIX(top);
bc_vec_pop(&p->ops);
incdec = false;
}
// There must be only one expression at the top.
if (BC_ERR(nexprs != 1)) bc_parse_err(p, BC_ERR_PARSE_EXPR);
// Check that the next token is correct.
for (i = 0; i < next.len && t != next.tokens[i]; ++i);
if (BC_ERR(i == next.len && !bc_parse_isDelimiter(p)))
bc_parse_err(p, BC_ERR_PARSE_EXPR);
// Check that POSIX would be happy with the number of relational operators.
if (!(flags & BC_PARSE_REL) && nrelops)
bc_parse_err(p, BC_ERR_POSIX_REL_POS);
else if ((flags & BC_PARSE_REL) && nrelops > 1)
bc_parse_err(p, BC_ERR_POSIX_MULTIREL);
// If this is true, then we might be in a situation where we don't print.
// We would want to have the increment/decrement operator not make an extra
// copy if it's not necessary.
if (!(flags & BC_PARSE_NEEDVAL) && !pfirst) {
// We have the easy case if the last operator was an assignment
// operator.
if (assign) {
inst = *((uchar*) bc_vec_top(&p->func->code));
inst += (BC_INST_ASSIGN_POWER_NO_VAL - BC_INST_ASSIGN_POWER);
incdec = false;
}
// If we have an inc/dec operator and we are *not* printing, implement
// the optimization to get rid of the extra copy.
else if (incdec && !(flags & BC_PARSE_PRINT)) {
inst = *((uchar*) bc_vec_top(&p->func->code));
incdec = (inst <= BC_INST_DEC);
inst = BC_INST_ASSIGN_PLUS_NO_VAL + (inst != BC_INST_INC &&
inst != BC_INST_ASSIGN_PLUS);
}
// This condition allows us to change the previous assignment
// instruction (which does a copy) for a NO_VAL version, which does not.
// This condition is set if either of the above if statements ends up
// being true.
if (inst >= BC_INST_ASSIGN_POWER_NO_VAL &&
inst <= BC_INST_ASSIGN_NO_VAL)
{
// Pop the previous assignment instruction and push a new one.
// Inc/dec needs the extra instruction because it is now a binary
// operator and needs a second operand.
bc_vec_pop(&p->func->code);
if (incdec) bc_parse_push(p, BC_INST_ONE);
bc_parse_push(p, inst);
}
}
// If we might have to print...
if ((flags & BC_PARSE_PRINT)) {
// With a paren first or the last operator not being an assignment, we
// *do* want to print.
if (pfirst || !assign) bc_parse_push(p, BC_INST_PRINT);
}
// We need to make sure to push a pop instruction for assignment statements
// that will not print. The print will pop, but without it, we need to pop.
else if (!(flags & BC_PARSE_NEEDVAL) &&
(inst < BC_INST_ASSIGN_POWER_NO_VAL ||
inst > BC_INST_ASSIGN_NO_VAL))
{
bc_parse_push(p, BC_INST_POP);
}
// We want to eat newlines if newlines are not a valid ending token.
// This is for spacing in things like for loop headers.
//
// Yes, this is one case where I reuse a variable for a different purpose;
// in this case, incdec being true now means that newlines are not valid.
for (incdec = true, i = 0; i < next.len && incdec; ++i)
incdec = (next.tokens[i] != BC_LEX_NLINE);
if (incdec) {
while (p->l.t == BC_LEX_NLINE) bc_lex_next(&p->l);
}
return BC_PARSE_STATUS_SUCCESS;
}
/**
* Parses an expression with bc_parse_expr_err(), but throws an error if it gets
* an empty expression.
* @param p The parser.
* @param flags The flags for what is valid in the expression.
* @param next A set of tokens for what is valid *after* the expression.
*/
static void bc_parse_expr_status(BcParse *p, uint8_t flags, BcParseNext next) {
BcParseStatus s = bc_parse_expr_err(p, flags, next);
if (BC_ERR(s == BC_PARSE_STATUS_EMPTY_EXPR))
bc_parse_err(p, BC_ERR_PARSE_EMPTY_EXPR);
}
void bc_parse_expr(BcParse *p, uint8_t flags) {
assert(p);
bc_parse_expr_status(p, flags, bc_parse_next_read);
}
#endif // BC_ENABLED
|
the_stack_data/26701390.c | /* Exercise 1 - Calculations
Write a C program to input marks of two subjects. Calculate and print the average of the two marks. */
#include <stdio.h>
int main() {
//declaring variables
int marks1,marks2,total;
float average;
//getting inputs
printf("enter the marks 1: ");
scanf("%d",&marks1);
printf("enter the marks 2: ");
scanf("%d",&marks2);
if(marks1>=0&&marks2<=100&&marks1<=100&&marks2>=0)
{
//calculating the total
total=marks1+marks2;
//calculating the average
average=total/2.0;
//displaying the output
printf("the average is:%.2f",average);
}
else printf("invalid entry");
return 0;
}
|
the_stack_data/61076471.c | #include <stdio.h>
int main()
{
float latitude;
float longitude;
char info[80];
int started = 0;
puts("data=[");
while (scanf("%f,%f,%79[^\n]", &latitude, &longitude, info) == 3)
{
if (started)
printf(",\n");
else
started = 1;
printf("{latitude: %f, longitude: %f, info: '%s'}",latitude,longitude,info);
}
puts("\n]");
return 0;
} |
the_stack_data/183186.c | /* ACM 441 Lotto
* mythnc
* 2012/01/10 21:08:05
* run time: 0.008
*/
#include <stdio.h>
#define MAXN 12
#define OUT 6
void input(int n);
void com(int, int, int);
int list[MAXN];
int output[OUT];
int main(void)
{
int n, set;
set = 0;
while (scanf("%d", &n) && n != 0) {
if (set == 1)
putchar('\n');
input(n);
com(0, n, 0);
set = 1;
}
return 0;
}
/* input: receive input data */
void input(int n)
{
int i;
for (i = 0; i < n; i++)
scanf("%d", &list[i]);
}
/*
void com1(int *list, int n)
{
int i, j, k, l, m, o;
for (i = 0; n - i >= OUT; i++)
for (j = i + 1; n - j >= OUT - 1; j++)
for (k = j + 1; n - k >= OUT - 2; k++)
for (l = k + 1; n - l >= OUT - 3; l++)
for (m = l + 1; n - m >= OUT - 4; m++)
for (o = m + 1; n - o >= OUT - 5; o++)
printf("%d %d %d %d %d %d\n",
list[i], list[j], list[k], list[l], list[m], list[o]);
}
*/
/* com: recursive combine to all conditions */
void com(int x, int n, int times)
{
int i;
if (times == OUT) {
printf("%d", output[0]);
for (i = 1; i < OUT; i++)
printf(" %d", output[i]);
putchar('\n');
return;
}
for (i = x; n - i >= OUT - times; i++) {
output[times] = list[i];
com(i + 1, n, times + 1);
}
}
|
the_stack_data/877794.c | //file"bot.c"
//#include<tictactoe.c>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#ifdef __unix__
#define clrscr() printf("\x1B[2J")
#elif __BORLANDC__ && __MSDOS__
#include <conio.h>
#elif __WIN32__ || _MSC_VER
#define clrscr() system("cls")
#else
#define clrscr() printf("clrscr() - Fehler\n")
#endif
extern char spielfeld[3][3];
extern void print_spielfeld();
extern int win();
extern void repeat();
void bot(char z)
{
srand(time(NULL));
printf("Spieler \"%c\" ist an der reihe\n",z);
if(spielfeld[0][0]==z &&
spielfeld[0][1]==z &&
spielfeld[0][2] == ' ')
{
spielfeld[0][2]=z;
}
else if(spielfeld[1][0]==z &&
spielfeld[1][1]==z &&
spielfeld[1][2] == ' ')
{
spielfeld[1][2]=z;
}
else if(spielfeld[2][0]==z &&
spielfeld[2][1]==z &&
spielfeld[2][2] == ' ')
{
spielfeld[2][2]=z;
}
else if(spielfeld[0][2]==z &&
spielfeld[0][1]==z &&
spielfeld[0][0] == ' ')
{
spielfeld[0][0]=z;
}
else if(spielfeld[1][2]==z &&
spielfeld[1][1]==z &&
spielfeld[1][0] == ' ')
{
spielfeld[1][0]=z;
}
else if(spielfeld[2][2]==z &&
spielfeld[2][1]==z &&
spielfeld[2][0] == ' ')
{
spielfeld[2][0]=z;
}
else if(spielfeld[0][0]==z &&
spielfeld[1][0]==z &&
spielfeld[2][0] == ' ')
{
spielfeld[2][0]=z;
}
else if(spielfeld[0][1]==z &&
spielfeld[1][1]==z &&
spielfeld[2][1] == ' ')
{
spielfeld[2][1]=z;
}
else if(spielfeld[0][2]==z &&
spielfeld[1][2]==z &&
spielfeld[2][2] == ' ')
{
spielfeld[2][2]=z;
}
else if(spielfeld[2][0]==z &&
spielfeld[1][0]==z &&
spielfeld[0][0] == ' ')
{
spielfeld[0][0]=z;
}
else if(spielfeld[2][1]==z &&
spielfeld[1][1]==z &&
spielfeld[0][1] == ' ')
{
spielfeld[0][1]=z;
}
else if(spielfeld[2][2]==z &&
spielfeld[1][2]==z &&
spielfeld[0][2] == ' ')
{
spielfeld[0][2]=z;
}
else if(spielfeld[0][0]==z &&
spielfeld[1][1]==z &&
spielfeld[2][2] == ' ')
{
spielfeld[2][2]=z;
}
else if(spielfeld[2][2]==z &&
spielfeld[1][1]==z &&
spielfeld[0][0] == ' ')
{
spielfeld[0][0]=z;
}
else if(spielfeld[2][0]==z &&
spielfeld[1][1]==z &&
spielfeld[0][2] == ' ')
{
spielfeld[0][2]=z;
}
else if(spielfeld[0][2]==z &&
spielfeld[1][1]==z &&
spielfeld[2][0] == ' ')
{
spielfeld[2][0]=z;
}
else if(spielfeld[0][0] != ' ' &&
spielfeld[0][1] != ' ' &&
spielfeld[0][0] != z &&
spielfeld[0][1] != z &&
spielfeld[0][2] == ' ')
{
spielfeld[0][2]=z;
}
else if(spielfeld[1][0] != ' ' &&
spielfeld[1][1] != ' ' &&
spielfeld[1][0] != z &&
spielfeld[1][1] != z &&
spielfeld[1][2] == ' ')
{
spielfeld[1][2]=z;
}
else if(spielfeld[2][0] != ' ' &&
spielfeld[2][1] != ' ' &&
spielfeld[2][0] != z &&
spielfeld[2][1] != z &&
spielfeld[2][2] == ' ')
{
spielfeld[2][2]=z;
}
else if(spielfeld[0][2] != ' ' &&
spielfeld[0][1] != ' ' &&
spielfeld[0][2] != z &&
spielfeld[0][1] != z &&
spielfeld[0][0] == ' ')
{
spielfeld[0][0]=z;
}
else if(spielfeld[1][2] != ' ' &&
spielfeld[1][1] != ' ' &&
spielfeld[1][2] != z &&
spielfeld[1][1] != z &&
spielfeld[1][0] == ' ')
{
spielfeld[1][0]=z;
}
else if(spielfeld[2][2] != ' ' &&
spielfeld[2][1] != ' ' &&
spielfeld[2][2] != z &&
spielfeld[2][1] != z &&
spielfeld[2][0] == ' ')
{
spielfeld[2][0]=z;
}
else if(spielfeld[0][0] != ' ' &&
spielfeld[1][0] != ' ' &&
spielfeld[0][0] != z &&
spielfeld[1][0] != z &&
spielfeld[2][0] == ' ')
{
spielfeld[2][0]=z;
}
else if(spielfeld[0][1] != ' ' &&
spielfeld[1][1] != ' ' &&
spielfeld[0][1] != z &&
spielfeld[1][1] != z &&
spielfeld[2][1] == ' ')
{
spielfeld[2][1]=z;
}
else if(spielfeld[0][2] != ' ' &&
spielfeld[1][2] != ' ' &&
spielfeld[0][2] != z &&
spielfeld[1][2] != z &&
spielfeld[2][2] == ' ')
{
spielfeld[2][2]=z;
}
else if(spielfeld[2][0] != ' ' &&
spielfeld[1][0] != ' ' &&
spielfeld[2][0] != z &&
spielfeld[1][0] != z &&
spielfeld[0][0] == ' ')
{
spielfeld[0][0]=z;
}
else if(spielfeld[2][1] != ' ' &&
spielfeld[1][1] != ' ' &&
spielfeld[2][1] != z &&
spielfeld[1][1] != z &&
spielfeld[0][1] == ' ')
{
spielfeld[0][1]=z;
}
else if(spielfeld[2][2] != ' ' &&
spielfeld[1][2] != ' ' &&
spielfeld[2][2] != z &&
spielfeld[1][2] != z &&
spielfeld[0][2] == ' ')
{
spielfeld[0][2]=z;
}
else if(spielfeld[0][0] != ' ' &&
spielfeld[1][1] != ' ' &&
spielfeld[0][0] != z &&
spielfeld[1][1] != z &&
spielfeld[2][2] == ' ')
{
spielfeld[2][2]=z;
}
else if(spielfeld[2][2] != ' ' &&
spielfeld[1][1] != ' ' &&
spielfeld[2][2] != z &&
spielfeld[1][1] != z &&
spielfeld[0][0] == ' ')
{
spielfeld[0][0]=z;
}
else if(spielfeld[2][0] != ' ' &&
spielfeld[1][1] != ' ' &&
spielfeld[2][0] != z &&
spielfeld[1][1] != z &&
spielfeld[0][2] == ' ')
{
spielfeld[0][2]=z;
}
else if(spielfeld[0][2] != ' ' &&
spielfeld[1][1] != ' ' &&
spielfeld[0][2] != z &&
spielfeld[1][1] != z &&
spielfeld[2][0] == ' ')
{
spielfeld[2][0]=z;
}
else if(spielfeld[0][0] != ' ' &&
spielfeld[2][0] != ' ' &&
spielfeld[0][0] != z &&
spielfeld[2][0] != z &&
spielfeld[1][0] == ' ')
{
spielfeld[1][0]=z;
}
else if(spielfeld[0][1] != ' ' &&
spielfeld[2][1] != ' ' &&
spielfeld[0][1] != z &&
spielfeld[2][1] != z &&
spielfeld[1][1] == ' ')
{
spielfeld[1][1]=z;
}
else if(spielfeld[0][2] != ' ' &&
spielfeld[2][2] != ' ' &&
spielfeld[0][2] != z &&
spielfeld[2][2] != z &&
spielfeld[1][2] == ' ')
{
spielfeld[1][2]=z;
}
else if(spielfeld[0][0] != ' ' &&
spielfeld[0][2] != ' ' &&
spielfeld[0][0] != z &&
spielfeld[0][2] != z &&
spielfeld[0][1] == ' ')
{
spielfeld[0][1]=z;
}
else if(spielfeld[1][0] != ' ' &&
spielfeld[1][2] != ' ' &&
spielfeld[1][0] != z &&
spielfeld[1][2] != z &&
spielfeld[1][1] == ' ')
{
spielfeld[1][1]=z;
}
else if(spielfeld[2][0] != ' ' &&
spielfeld[2][2] != ' ' &&
spielfeld[2][0] != z &&
spielfeld[2][2] != z &&
spielfeld[2][1] == ' ')
{
spielfeld[2][1]=z;
}
else if(spielfeld[0][0] != ' ' &&
spielfeld[2][2] != ' ' &&
spielfeld[0][0] != z &&
spielfeld[2][2] != z &&
spielfeld[1][1] == ' ')
{
spielfeld[1][1]=z;
}
else if(spielfeld[2][0] != ' ' &&
spielfeld[0][2] != ' ' &&
spielfeld[2][0] != z &&
spielfeld[0][2] != z &&
spielfeld[1][1] == ' ')
{
spielfeld[1][1]=z;
}
else
{
do
{
if(rand() % 3 == 0 && rand() % 3 == 0 && spielfeld[0][0] == ' ')
{
spielfeld[0][0]=z;
break;
}
else if(rand() % 3 == 0 && rand() % 3 == 1 && spielfeld[0][1] == ' ')
{
spielfeld[0][1]=z;
break;
}
else if(rand() % 3 == 0 && rand() % 3 == 2 && spielfeld[0][2] == ' ')
{
spielfeld[0][2]=z;
break;
}
else if(rand() % 3 == 1 && rand() % 3 == 0 && spielfeld[1][0] == ' ')
{
spielfeld[1][0]=z;
break;
}
else if(rand() % 3 == 1 && rand() % 3 == 1 && spielfeld[1][1] == ' ')
{
spielfeld[1][1]=z;
break;
}
else if(rand() % 3 == 1 && rand() % 3 == 2 && spielfeld[1][2] == ' ')
{
spielfeld[1][2]=z;
break;
}
else if(rand() % 3 == 2 && rand() % 3 == 0 && spielfeld[2][0] == ' ')
{
spielfeld[2][0]=z;
break;
}
else if(rand() % 3 == 2 && rand() % 3 == 1 && spielfeld[2][1] == ' ')
{
spielfeld[2][1]=z;
break;
}
else if(rand() % 3 == 2 && rand() % 3 == 2 && spielfeld[2][2] == ' ')
{
spielfeld[2][2]=z;
break;
}
}while(1);
}
clrscr();
print_spielfeld();
win();
if(win() == 1 || win() == 2 || win() == 3)
{
repeat();
}
}
|
the_stack_data/179830178.c | /*
*
* Copyright (c) 2005 Carnegie Mellon University.
* All rights reserved.
* Permission to use this software and its documentation for any purpose is hereby granted,
* provided that the above copyright notice appear and that both that copyright notice and
* this permission notice appear in supporting documentation, and that the name of CMU not
* be used in advertising or publicity pertaining to distribution of the software without
* specific, written prior permission.
*
* CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, RISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <string.h>
int main(int argc, char *argv[])
{
char name [2048];
if(argc == 3)
{
strncpy(name, argv[1], sizeof name - 1);
name[sizeof name - 1] = '\0';
strncat(name, " = ", sizeof name - strlen(name) - 1);
strcat(name, argv[2]); /* FLAW */
}
return 0;
}
|
the_stack_data/673287.c | #ifndef FONT5X7_H
#define FONT5X7_H
#ifdef __AVR__
#include <avr/io.h>
#include <avr/pgmspace.h>
#else
#define PROGMEM
#endif
// Standard ASCII 5x7 font
static const unsigned char font[] PROGMEM = {
0x00, 0x00, 0x00, 0x00, 0x00,
0x3E, 0x5B, 0x4F, 0x5B, 0x3E,
0x3E, 0x6B, 0x4F, 0x6B, 0x3E,
0x1C, 0x3E, 0x7C, 0x3E, 0x1C,
0x18, 0x3C, 0x7E, 0x3C, 0x18,
0x1C, 0x57, 0x7D, 0x57, 0x1C,
0x1C, 0x5E, 0x7F, 0x5E, 0x1C,
0x00, 0x18, 0x3C, 0x18, 0x00,
0xFF, 0xE7, 0xC3, 0xE7, 0xFF,
0x00, 0x18, 0x24, 0x18, 0x00,
0xFF, 0xE7, 0xDB, 0xE7, 0xFF,
0x30, 0x48, 0x3A, 0x06, 0x0E,
0x26, 0x29, 0x79, 0x29, 0x26,
0x40, 0x7F, 0x05, 0x05, 0x07,
0x40, 0x7F, 0x05, 0x25, 0x3F,
0x5A, 0x3C, 0xE7, 0x3C, 0x5A,
0x7F, 0x3E, 0x1C, 0x1C, 0x08,
0x08, 0x1C, 0x1C, 0x3E, 0x7F,
0x14, 0x22, 0x7F, 0x22, 0x14,
0x5F, 0x5F, 0x00, 0x5F, 0x5F,
0x06, 0x09, 0x7F, 0x01, 0x7F,
0x00, 0x66, 0x89, 0x95, 0x6A,
0x60, 0x60, 0x60, 0x60, 0x60,
0x94, 0xA2, 0xFF, 0xA2, 0x94,
0x08, 0x04, 0x7E, 0x04, 0x08,
0x10, 0x20, 0x7E, 0x20, 0x10,
0x08, 0x08, 0x2A, 0x1C, 0x08,
0x08, 0x1C, 0x2A, 0x08, 0x08,
0x1E, 0x10, 0x10, 0x10, 0x10,
0x0C, 0x1E, 0x0C, 0x1E, 0x0C,
0x30, 0x38, 0x3E, 0x38, 0x30,
0x06, 0x0E, 0x3E, 0x0E, 0x06,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x5F, 0x00, 0x00,
0x00, 0x07, 0x00, 0x07, 0x00,
0x14, 0x7F, 0x14, 0x7F, 0x14,
0x24, 0x2A, 0x7F, 0x2A, 0x12,
0x23, 0x13, 0x08, 0x64, 0x62,
0x36, 0x49, 0x56, 0x20, 0x50,
0x00, 0x08, 0x07, 0x03, 0x00,
0x00, 0x1C, 0x22, 0x41, 0x00,
0x00, 0x41, 0x22, 0x1C, 0x00,
0x2A, 0x1C, 0x7F, 0x1C, 0x2A,
0x08, 0x08, 0x3E, 0x08, 0x08,
0x00, 0x80, 0x70, 0x30, 0x00,
0x08, 0x08, 0x08, 0x08, 0x08,
0x00, 0x00, 0x60, 0x60, 0x00,
0x20, 0x10, 0x08, 0x04, 0x02,
0x3E, 0x51, 0x49, 0x45, 0x3E,
0x00, 0x42, 0x7F, 0x40, 0x00,
0x72, 0x49, 0x49, 0x49, 0x46,
0x21, 0x41, 0x49, 0x4D, 0x33,
0x18, 0x14, 0x12, 0x7F, 0x10,
0x27, 0x45, 0x45, 0x45, 0x39,
0x3C, 0x4A, 0x49, 0x49, 0x31,
0x41, 0x21, 0x11, 0x09, 0x07,
0x36, 0x49, 0x49, 0x49, 0x36,
0x46, 0x49, 0x49, 0x29, 0x1E,
0x00, 0x00, 0x14, 0x00, 0x00,
0x00, 0x40, 0x34, 0x00, 0x00,
0x00, 0x08, 0x14, 0x22, 0x41,
0x14, 0x14, 0x14, 0x14, 0x14,
0x00, 0x41, 0x22, 0x14, 0x08,
0x02, 0x01, 0x59, 0x09, 0x06,
0x3E, 0x41, 0x5D, 0x59, 0x4E,
0x7C, 0x12, 0x11, 0x12, 0x7C,
0x7F, 0x49, 0x49, 0x49, 0x36,
0x3E, 0x41, 0x41, 0x41, 0x22,
0x7F, 0x41, 0x41, 0x41, 0x3E,
0x7F, 0x49, 0x49, 0x49, 0x41,
0x7F, 0x09, 0x09, 0x09, 0x01,
0x3E, 0x41, 0x41, 0x51, 0x73,
0x7F, 0x08, 0x08, 0x08, 0x7F,
0x00, 0x41, 0x7F, 0x41, 0x00,
0x20, 0x40, 0x41, 0x3F, 0x01,
0x7F, 0x08, 0x14, 0x22, 0x41,
0x7F, 0x40, 0x40, 0x40, 0x40,
0x7F, 0x02, 0x1C, 0x02, 0x7F,
0x7F, 0x04, 0x08, 0x10, 0x7F,
0x3E, 0x41, 0x41, 0x41, 0x3E,
0x7F, 0x09, 0x09, 0x09, 0x06,
0x3E, 0x41, 0x51, 0x21, 0x5E,
0x7F, 0x09, 0x19, 0x29, 0x46,
0x26, 0x49, 0x49, 0x49, 0x32,
0x03, 0x01, 0x7F, 0x01, 0x03,
0x3F, 0x40, 0x40, 0x40, 0x3F,
0x1F, 0x20, 0x40, 0x20, 0x1F,
0x3F, 0x40, 0x38, 0x40, 0x3F,
0x63, 0x14, 0x08, 0x14, 0x63,
0x03, 0x04, 0x78, 0x04, 0x03,
0x61, 0x59, 0x49, 0x4D, 0x43,
0x00, 0x7F, 0x41, 0x41, 0x41,
0x02, 0x04, 0x08, 0x10, 0x20,
0x00, 0x41, 0x41, 0x41, 0x7F,
0x04, 0x02, 0x01, 0x02, 0x04,
0x40, 0x40, 0x40, 0x40, 0x40,
0x00, 0x03, 0x07, 0x08, 0x00,
0x20, 0x54, 0x54, 0x78, 0x40,
0x7F, 0x28, 0x44, 0x44, 0x38,
0x38, 0x44, 0x44, 0x44, 0x28,
0x38, 0x44, 0x44, 0x28, 0x7F,
0x38, 0x54, 0x54, 0x54, 0x18,
0x00, 0x08, 0x7E, 0x09, 0x02,
0x18, 0xA4, 0xA4, 0x9C, 0x78,
0x7F, 0x08, 0x04, 0x04, 0x78,
0x00, 0x44, 0x7D, 0x40, 0x00,
0x20, 0x40, 0x40, 0x3D, 0x00,
0x7F, 0x10, 0x28, 0x44, 0x00,
0x00, 0x41, 0x7F, 0x40, 0x00,
0x7C, 0x04, 0x78, 0x04, 0x78,
0x7C, 0x08, 0x04, 0x04, 0x78,
0x38, 0x44, 0x44, 0x44, 0x38,
0xFC, 0x18, 0x24, 0x24, 0x18,
0x18, 0x24, 0x24, 0x18, 0xFC,
0x7C, 0x08, 0x04, 0x04, 0x08,
0x48, 0x54, 0x54, 0x54, 0x24,
0x04, 0x04, 0x3F, 0x44, 0x24,
0x3C, 0x40, 0x40, 0x20, 0x7C,
0x1C, 0x20, 0x40, 0x20, 0x1C,
0x3C, 0x40, 0x30, 0x40, 0x3C,
0x44, 0x28, 0x10, 0x28, 0x44,
0x4C, 0x90, 0x90, 0x90, 0x7C,
0x44, 0x64, 0x54, 0x4C, 0x44,
0x00, 0x08, 0x36, 0x41, 0x00,
0x00, 0x00, 0x77, 0x00, 0x00,
0x00, 0x41, 0x36, 0x08, 0x00,
0x02, 0x01, 0x02, 0x04, 0x02,
0x3C, 0x26, 0x23, 0x26, 0x3C,
0x1E, 0xA1, 0xA1, 0x61, 0x12,
0x3A, 0x40, 0x40, 0x20, 0x7A,
0x38, 0x54, 0x54, 0x55, 0x59,
0x21, 0x55, 0x55, 0x79, 0x41,
0x21, 0x54, 0x54, 0x78, 0x41,
0x21, 0x55, 0x54, 0x78, 0x40,
0x20, 0x54, 0x55, 0x79, 0x40,
0x0C, 0x1E, 0x52, 0x72, 0x12,
0x39, 0x55, 0x55, 0x55, 0x59,
0x39, 0x54, 0x54, 0x54, 0x59,
0x39, 0x55, 0x54, 0x54, 0x58,
0x00, 0x00, 0x45, 0x7C, 0x41,
0x00, 0x02, 0x45, 0x7D, 0x42,
0x00, 0x01, 0x45, 0x7C, 0x40,
0xF0, 0x29, 0x24, 0x29, 0xF0,
0xF0, 0x28, 0x25, 0x28, 0xF0,
0x7C, 0x54, 0x55, 0x45, 0x00,
0x20, 0x54, 0x54, 0x7C, 0x54,
0x7C, 0x0A, 0x09, 0x7F, 0x49,
0x32, 0x49, 0x49, 0x49, 0x32,
0x32, 0x48, 0x48, 0x48, 0x32,
0x32, 0x4A, 0x48, 0x48, 0x30,
0x3A, 0x41, 0x41, 0x21, 0x7A,
0x3A, 0x42, 0x40, 0x20, 0x78,
0x00, 0x9D, 0xA0, 0xA0, 0x7D,
0x39, 0x44, 0x44, 0x44, 0x39,
0x3D, 0x40, 0x40, 0x40, 0x3D,
0x3C, 0x24, 0xFF, 0x24, 0x24,
0x48, 0x7E, 0x49, 0x43, 0x66,
0x2B, 0x2F, 0xFC, 0x2F, 0x2B,
0xFF, 0x09, 0x29, 0xF6, 0x20,
0xC0, 0x88, 0x7E, 0x09, 0x03,
0x20, 0x54, 0x54, 0x79, 0x41,
0x00, 0x00, 0x44, 0x7D, 0x41,
0x30, 0x48, 0x48, 0x4A, 0x32,
0x38, 0x40, 0x40, 0x22, 0x7A,
0x00, 0x7A, 0x0A, 0x0A, 0x72,
0x7D, 0x0D, 0x19, 0x31, 0x7D,
0x26, 0x29, 0x29, 0x2F, 0x28,
0x26, 0x29, 0x29, 0x29, 0x26,
0x30, 0x48, 0x4D, 0x40, 0x20,
0x38, 0x08, 0x08, 0x08, 0x08,
0x08, 0x08, 0x08, 0x08, 0x38,
0x2F, 0x10, 0xC8, 0xAC, 0xBA,
0x2F, 0x10, 0x28, 0x34, 0xFA,
0x00, 0x00, 0x7B, 0x00, 0x00,
0x08, 0x14, 0x2A, 0x14, 0x22,
0x22, 0x14, 0x2A, 0x14, 0x08,
0xAA, 0x00, 0x55, 0x00, 0xAA,
0xAA, 0x55, 0xAA, 0x55, 0xAA,
0x00, 0x00, 0x00, 0xFF, 0x00,
0x10, 0x10, 0x10, 0xFF, 0x00,
0x14, 0x14, 0x14, 0xFF, 0x00,
0x10, 0x10, 0xFF, 0x00, 0xFF,
0x10, 0x10, 0xF0, 0x10, 0xF0,
0x14, 0x14, 0x14, 0xFC, 0x00,
0x14, 0x14, 0xF7, 0x00, 0xFF,
0x00, 0x00, 0xFF, 0x00, 0xFF,
0x14, 0x14, 0xF4, 0x04, 0xFC,
0x14, 0x14, 0x17, 0x10, 0x1F,
0x10, 0x10, 0x1F, 0x10, 0x1F,
0x14, 0x14, 0x14, 0x1F, 0x00,
0x10, 0x10, 0x10, 0xF0, 0x00,
0x00, 0x00, 0x00, 0x1F, 0x10,
0x10, 0x10, 0x10, 0x1F, 0x10,
0x10, 0x10, 0x10, 0xF0, 0x10,
0x00, 0x00, 0x00, 0xFF, 0x10,
0x10, 0x10, 0x10, 0x10, 0x10,
0x10, 0x10, 0x10, 0xFF, 0x10,
0x00, 0x00, 0x00, 0xFF, 0x14,
0x00, 0x00, 0xFF, 0x00, 0xFF,
0x00, 0x00, 0x1F, 0x10, 0x17,
0x00, 0x00, 0xFC, 0x04, 0xF4,
0x14, 0x14, 0x17, 0x10, 0x17,
0x14, 0x14, 0xF4, 0x04, 0xF4,
0x00, 0x00, 0xFF, 0x00, 0xF7,
0x14, 0x14, 0x14, 0x14, 0x14,
0x14, 0x14, 0xF7, 0x00, 0xF7,
0x14, 0x14, 0x14, 0x17, 0x14,
0x10, 0x10, 0x1F, 0x10, 0x1F,
0x14, 0x14, 0x14, 0xF4, 0x14,
0x10, 0x10, 0xF0, 0x10, 0xF0,
0x00, 0x00, 0x1F, 0x10, 0x1F,
0x00, 0x00, 0x00, 0x1F, 0x14,
0x00, 0x00, 0x00, 0xFC, 0x14,
0x00, 0x00, 0xF0, 0x10, 0xF0,
0x10, 0x10, 0xFF, 0x10, 0xFF,
0x14, 0x14, 0x14, 0xFF, 0x14,
0x10, 0x10, 0x10, 0x1F, 0x00,
0x00, 0x00, 0x00, 0xF0, 0x10,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xFF, 0xFF, 0xFF, 0x00, 0x00,
0x00, 0x00, 0x00, 0xFF, 0xFF,
0x0F, 0x0F, 0x0F, 0x0F, 0x0F,
0x38, 0x44, 0x44, 0x38, 0x44,
0x7C, 0x2A, 0x2A, 0x3E, 0x14,
0x7E, 0x02, 0x02, 0x06, 0x06,
0x02, 0x7E, 0x02, 0x7E, 0x02,
0x63, 0x55, 0x49, 0x41, 0x63,
0x38, 0x44, 0x44, 0x3C, 0x04,
0x40, 0x7E, 0x20, 0x1E, 0x20,
0x06, 0x02, 0x7E, 0x02, 0x02,
0x99, 0xA5, 0xE7, 0xA5, 0x99,
0x1C, 0x2A, 0x49, 0x2A, 0x1C,
0x4C, 0x72, 0x01, 0x72, 0x4C,
0x30, 0x4A, 0x4D, 0x4D, 0x30,
0x30, 0x48, 0x78, 0x48, 0x30,
0xBC, 0x62, 0x5A, 0x46, 0x3D,
0x3E, 0x49, 0x49, 0x49, 0x00,
0x7E, 0x01, 0x01, 0x01, 0x7E,
0x2A, 0x2A, 0x2A, 0x2A, 0x2A,
0x44, 0x44, 0x5F, 0x44, 0x44,
0x40, 0x51, 0x4A, 0x44, 0x40,
0x40, 0x44, 0x4A, 0x51, 0x40,
0x00, 0x00, 0xFF, 0x01, 0x03,
0xE0, 0x80, 0xFF, 0x00, 0x00,
0x08, 0x08, 0x6B, 0x6B, 0x08,
0x36, 0x12, 0x36, 0x24, 0x36,
0x06, 0x0F, 0x09, 0x0F, 0x06,
0x00, 0x00, 0x18, 0x18, 0x00,
0x00, 0x00, 0x10, 0x10, 0x00,
0x30, 0x40, 0xFF, 0x01, 0x01,
0x00, 0x1F, 0x01, 0x01, 0x1E,
0x00, 0x19, 0x1D, 0x17, 0x12,
0x00, 0x3C, 0x3C, 0x3C, 0x3C,
0x00, 0x00, 0x00, 0x00, 0x00
};
#endif // FONT5X7_H
|
the_stack_data/150140813.c | int foo(int a, int b) {
int c=a+b;
return c+3;
}
int main(void) {
return foo(5,900);
} |
the_stack_data/161081139.c | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#include<sys/time.h>
unsigned long long rdtsc()
{
unsigned long long dst;
__asm__ __volatile__("rdtsc":"=A"(dst));
return dst;
}
int32_t main()
{
long long int start,end;
start=rdtsc();
getpid();
end=rdtsc();
printf("The getpid function took %lld seconds\n",end-start);
return 0;
} |
the_stack_data/133888.c | /* $OpenBSD: uthread_read.c,v 1.10 2010/01/03 23:05:35 fgsch Exp $ */
/*
* Copyright (c) 1995-1998 John Birrell <[email protected]>
* 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 John Birrell.
* 4. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL 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 AUTHOR 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: uthread_read.c,v 1.8 1999/08/28 00:03:43 peter Exp $
*
*/
#include <sys/types.h>
#include <sys/fcntl.h>
#include <sys/uio.h>
#include <errno.h>
#include <unistd.h>
#ifdef _THREAD_SAFE
#include <pthread.h>
#include "pthread_private.h"
ssize_t
read(int fd, void *buf, size_t nbytes)
{
struct pthread *curthread = _get_curthread();
ssize_t ret;
int type;
/* This is a cancellation point: */
_thread_enter_cancellation_point();
/* POSIX says to do just this: */
if (nbytes == 0)
ret = 0;
/* Lock the file descriptor for read: */
else if ((ret = _FD_LOCK(fd, FD_READ, NULL)) == 0) {
/* Get the read/write mode type: */
type = _thread_fd_table[fd]->status_flags->flags & O_ACCMODE;
/* Check if the file is not open for read: */
if (type != O_RDONLY && type != O_RDWR) {
/* File is not open for read: */
errno = EBADF;
ret = -1;
}
/* Perform a non-blocking read syscall: */
else while ((ret = _thread_sys_read(fd, buf, nbytes)) < 0) {
if ((_thread_fd_table[fd]->status_flags->flags & O_NONBLOCK) == 0 &&
(errno == EWOULDBLOCK || errno == EAGAIN)) {
curthread->data.fd.fd = fd;
_thread_kern_set_timeout(_FD_RCVTIMEO(fd));
/* Reset the interrupted operation flag: */
curthread->interrupted = 0;
curthread->closing_fd = 0;
curthread->timeout = 0;
_thread_kern_sched_state(PS_FDR_WAIT,
__FILE__, __LINE__);
/*
* Check if the operation was
* interrupted by a signal,
* a closing fd or timed out.
*/
if (curthread->interrupted) {
errno = EINTR;
ret = -1;
break;
} else if (curthread->closing_fd) {
errno = EBADF;
ret = -1;
break;
} else if (curthread->timeout) {
errno = EWOULDBLOCK;
ret = -1;
break;
}
} else {
break;
}
}
_FD_UNLOCK(fd, FD_READ);
}
/* No longer in a cancellation point: */
_thread_leave_cancellation_point();
return (ret);
}
#endif
|
the_stack_data/156393771.c |
/**********************************************************************************************
cycle-to-pdf Cycle Detection Application cycle-to-pdf.c by Dan Lindamood III
V11 2013-04 Initial Release
V12 2014-01-15 Added PDF security
V13 2014-03-30 1)Removed locked cycle number starting point argument.
2)Created floating value (Line 59).
3)Added Reboot Command after adjustable amount of prints completed.
V14 2014-04-18 Added alarm list for logging and optional email.
V15 2014-07-02 Replaced printing with libharu
V16 2014-07-02 Do not pritn to PDF if file already created
V17-Add Author for Metadata as argv[8]
Allow cycle start information to load before checking for legitimate cycle
V17 2014-07-23 Removed redundant code "detect_end".
Added PDF PCL5/PCL6 Option
V18 2015-04-23 Set nohup timestamps to offset UTC time
V19 2015-09-11 Print text file before copy to pcl folder
V20 2015-10-21 Print to Printer (file_tcp applition) every time log file is active.
Function:
Read active_log.txt and determine if the print is from a cycle.
If not, clear the file.
If the print is from a cycle then:
find the cycle number to be used in the print file name.
wait for an end of cycle indication.
Print to PDF file and copy raw text to PCL folder.
***********************************************************************************************/
#include <stdio.h>
#include <string.h>
#include<stdlib.h>
#include <time.h>
#define false (0!=0)
#define LOG_FILE "/var/www/active_log.txt"
//////////////Get Time/////////////////////////////////////////////////////////////////////////////////
int print_time()
{
struct tm *localtime;
time_t rawtime;
time_t offset;
setenv( "TZ", "EST5EDT", 1 );
tzset();
time(&rawtime);
/* Get GMT time */
offset = (rawtime - timezone + (daylight*3600));
localtime = gmtime(&offset);
printf("%02d/%02d/%02d %2d:%02d:%02d\n",localtime->tm_year+1900, localtime->tm_mon+1, localtime->tm_mday, localtime->tm_hour, localtime->tm_min, localtime->tm_sec);
return(0);
}
////////// GET CYCLE NUMBER ////////// GET CYCLE NUMBER ////////// GET CYCLE NUMBER ////////// GET CYCLE NUMBER //////////
//get_cycle_number function started from main below
char *get_cycle_number(char *cycle_str, char *cycle_num)
{
FILE * pFile;
int cycle_line_num = 1; //represents each line being checked for cycle number. Starts at 1
int cycle_find_result = 0; //if cycle found, then 0 changes to how many times found.
char cycle_temp[512]; //entire file
char str[100]; //character strings withing each line
char space[] = " ";//used to find end of cycle number
int line_length; //length of string line where cycle is found
int start_point = -1;//Location of cycle count number in print header. Let's try the strchr search?
int num_length; //How many digits in the cycle count.
pFile = fopen(LOG_FILE, "r"); // Read text file
if (pFile != NULL) //if file exists then do this.....
{
while ((fgets(cycle_temp, 512, pFile) != NULL) && (cycle_find_result == 0)) //while checking each line for a cycle and not yet found
{
if ((strstr(cycle_temp, cycle_str)) != NULL) //If cycle number found then extract the number from the text string.......
{
start_point = strstr(cycle_temp, cycle_str) - cycle_temp + strlen(cycle_str); //Determine start point of cycle number.
//Determine how many characters the cycle number contains by finding the first space character at the end of the number.
num_length = 1; //start with a default 1 character
if (cycle_temp[start_point + 1] == space[0]) num_length = 1;
else if (cycle_temp[start_point + 2] == space[0])num_length = 2;
else if (cycle_temp[start_point + 3] == space[0])num_length = 3;
else if (cycle_temp[start_point + 4] == space[0])num_length = 4;
else if (cycle_temp[start_point + 5] == space[0])num_length = 5;
//http://www.dreamincode.net/forums/topic/54086-cut-a-string-into-different-peices/
strncpy(cycle_num, &cycle_temp[start_point], num_length);
cycle_num[num_length] = '\0';
// printf("cycle number test %s\n", cycle_num);//For Testing
cycle_find_result++; //indicate that cycle number was found
}
else // if cycle number not found, spoil the number to be ignored in the main function
{
cycle_num[1] = '\0';
strncpy(cycle_num, "X", 1);
}
cycle_line_num++;
}
fclose(pFile);
}
return cycle_num;
}
////////// DETECT ALARM - EMAIL ////////// DETECT ALARM - EMAIL ////////// DETECT ALARM - EMAIL //////////////////
int alarm_detected(char *str_alarm, int alarm_start_point){
FILE * pFile;
int alarm_line_num = 0;
int alarm_find_result = 0;
char alarm_temp[512];
pFile = fopen(LOG_FILE, "r");
while ((fgets(alarm_temp, 512, pFile) != NULL) && (alarm_find_result == 0))
{
if (((strstr(alarm_temp, str_alarm)) != NULL) && (alarm_line_num > alarm_start_point))
{
alarm_start_point = alarm_line_num;
alarm_find_result++;
}
alarm_line_num++;
}
fclose(pFile);
return(alarm_find_result, alarm_start_point);
}
////////// DETECT ////////// DETECT ////////// DETECT ////////// DETECT ////////// DETECT
int detect_cycle(char *str_detect)
{
FILE * pFile;
int detect_line_num = 1;
int detect_find_result = 0;
char detect_temp[512];
pFile = fopen(LOG_FILE, "r");
while ((fgets(detect_temp, 512, pFile) != NULL) && (detect_find_result == 0))
{
if ((strstr(detect_temp, str_detect)) != NULL)
{
detect_find_result++;
}
detect_line_num++;
}
fclose(pFile);
return(detect_find_result);
}
////////// PRINT ////////// PRINT ////////// PRINT ////////// PRINT ////////// PRINT ////////// PRINT ////////// PRINT
void out_to_print(char *cyclenum, char *lines, char *author, char *pcl, int PDF)
{
FILE * pFile;
FILE * newpdfFile;
char cp_pcl[128];
char newpdf[128];
char prntcmnd[128];
if (PDF == 1){
sprintf(prntcmnd, "/var/www/apps/pcl_to_pdf /var/www/pdf/cycle_%s.pdf /var/www/active_log.txt %s %s\'%s\' cycle-to-pdf cycle_%s.pdf", cyclenum, lines, pcl, author, cyclenum);
sprintf(newpdf, "/var/www/pdf/cycle_%s.pdf", cyclenum);
newpdfFile = fopen(newpdf, "r"); //open new pdf file to verify that it exists.
if (newpdfFile == NULL){
system(prntcmnd); // print to pdf
newpdfFile = fopen(newpdf, "r"); //open new pdf file to verify that it exists.
if (newpdfFile == NULL) printf("PRINT TO PDF FAILED\n"); // if pdf file not created, indicate failure.
else printf("PRINT TO PDF SUCCESSFUL\n"); // if pdf file created, clear log file.
}
else printf("PDF FILE ALREADY CREATED\n");
sprintf(cp_pcl, "cp /var/www/active_log.txt /var/www/pcl/cycle_%s.pcl", cyclenum);
system(cp_pcl); // Copy log file to pcl storage
}
else printf("PDF NOT PRINTED\n");
system("/var/www/apps/print.sh");
pFile = fopen(LOG_FILE, "w");
fclose(pFile);
}
////////// MAIN ////////// MAIN ////////// MAIN ////////// MAIN ////////// MAIN ////////// MAIN ////////// MAIN ////////// MAIN
int main(int argc, char ** argv)
{
FILE * pFile; //active_log.txt
FILE *pAlarms; //Alarm log
int sequence = 0; //used for delaying functions
int interval = atoi(argv[1]); // Interval timer for checking log file
int count = 0; //used to count characters
int receiving = 0; //compared with character count to determine if log file still receiving data
int c; //each character
char cycnum[6];
int done = false;
int cycles = 0; //Amount of printed cycles
int alarm_argc = 0;
int alarm_start_point = 0;
int start_relay = 0;
int alarm_count = 0;
int alarm_active = 0;
char alarm_cmd[64];
int print_pdf = 0;
int i = 0;
// for (i=1; i< argc; i++) {
// printf("\n%s", argv[i]);
// }
//used for providing time for logging process displayed on web page
//Printed to nohup.out (processlog.txt) in web page
printf("\n\nCycle Detection Application Started ");
print_time();
printf("Monitors active_log.txt file every %d seconds.\n\nVersion 0 2015-OCT-20 By -DL-\n\n", interval);//send to web page log once at startup.
while (!done) // Stay Running Continously unless error or manually stopped.
{
sleep(interval);// Check Log file every ## seconds---must have argument or segment fault
alarm_argc = 0; //reset alarms list
//used for providing time for logging process displayed on web page
pFile = fopen(LOG_FILE, "r"); // read only active_log.txt
if (pFile != NULL){ //if active_log.txt exist, then do this below......
c = getc(pFile); // open log file to read characters
while (c != EOF) {//Continue to read each character until the end of file is detected.
count++; // increase count for each character.
c = getc(pFile);
}
fclose(pFile); //must close the file to reset for next interval pass
if (count == 0){
sequence = 0; // Always reset sequence when file empty
start_relay = 0;
alarm_start_point = 0;
alarm_count = 0;
}
else { //If log file is active, perform the following actions within the brackets.
if ((sequence == 0) &&(receiving == count)){ // Start the sequence.
sequence = 1; //Chna
printf("LOG FILE ACTIVE ");
print_time();
}
if (sequence == 3){ // After allowing page header to print, confirm cycle
if (detect_cycle(argv[3]) == 0){//Even though cycle number detected, if not valid cycle then clear log
printf("NON CYCLE PRINT\n");
sequence = 5;//reset sequence to 0
}
else { //if cycle confirmed, display cycle number on web page process log
printf("CYCLE NUMBER: %s \n", cycnum);//display cycle number
sequence = 4;//Allow for cycle end detection
print_pdf = 1;
}
}
if (sequence == 4){ //After cycle is confirmed, monitor for end of cycle.
if (detect_cycle(argv[4]) >= 1){
printf("END OF CYCLE DETECTED ");
print_time();
sequence = 5;//allow print function
}
}
if ((sequence == 5) && (receiving == count)){//Wait for printing to finish after detecting end.
out_to_print(cycnum, argv[5], argv[8], argv[9], print_pdf);//Start printing function. Argument 5 sets lines per page.
sequence = 0; //reset sequence to 0
printf("\n\n\n");
if (print_pdf == 1) {
cycles++;
printf("(%d)out of (%d) cycles printed before reboot.\n\n\n", cycles, atoi(argv[6]));
}
print_pdf = 0;
if (cycles == atoi(argv[6])){
printf("Rebooting system");
system("sudo /sbin/shutdown -r now");
}
}
if (sequence == 2){ //Get cycle number
get_cycle_number(argv[2], cycnum);//send to function for cycle number
if (strlen(cycnum) >= 2) sequence = 3; // Is there a cycle number (at least 2 digits)? If yes, go to next sequence.
else { // if no cycle number, clear the log and reset sequence.
printf("NO CYCLE NUMBER DETECTED\n");
sequence = 5; //reset sequence to 0
}
}
if ((sequence == 1) && (receiving == count)) sequence = 2;// Allow initial start information to print, get the cycle number during next interval.
// Check for alarms only when there is an active cycle
if ((sequence == 4) && (alarm_count < atoi(argv[7]))){
for (alarm_argc = 10; alarm_argc < argc; alarm_argc++) {
alarm_active, start_relay = alarm_detected(argv[alarm_argc], alarm_start_point);
if (start_relay > alarm_start_point){
printf("%s ALARM DETECTED ", argv[alarm_argc]);
print_time();
pAlarms = fopen("/var/www/alarms.txt", "a"); // add to alarm log
fprintf(pAlarms, "%s ", argv[alarm_argc]);
print_time();
fclose(pAlarms);
// Email Service Only sprintf(alarm_cmd, "/var/www/applications/email.sh \'%s\' \'%s\' %s",argv[alarm_argc], print_time, cycnum);
// system(alarm_cmd);
// printf("%s\n", alarm_cmd);
alarm_start_point = start_relay;
alarm_count++;
}
}
}
} // End bracket for active_log.txt not empty
// printf("Sequence Num: %d", sequence);
receiving = count; //equalize with character count to be check for active printing on next interval
count = 0; // reset for next interval
} //End bracket for checking if active_log.txt exists.
else printf("LOG_FILE = NULL\n");//if active_log file does no exist
fflush(stdout);//clear stdout every interval. This is for the proper function of writing to the process log.
}
}
|
the_stack_data/29825698.c | // RUN: %ucc -S -o- %s -fsanitize=unreachable -DF=__builtin_trap | grep ud2 >/dev/null
// RUN: %ucc -S -o- %s -DF=__builtin_trap | grep ud2 >/dev/null
// RUN: %ucc -S -o- %s -fsanitize=unreachable -DF=__builtin_unreachable | grep ud2 >/dev/null
// RUN: ! %ucc -S -o- %s -DF=__builtin_unreachable | grep ud2 >/dev/null
void f()
{
F();
}
|
the_stack_data/3045.c | int atoi(const char*);
int main(int argc, char** argv)
{
char* matrix[argc][atoi(argv[1])];
return 0;
}
int getInt(void);
void f(void) {
typedef char myType[10 * 4][3 + getInt()][3][90 * getInt()];
myType var;
char c1, c2 = 'x', buf[10 * 4][2 + getInt()][3][80 * getInt()], buf2[getInt()], *ptr = buf;
}
|
the_stack_data/32888.c | #include <stdio.h>
int main ()
{
int a,b;
scanf("%d %d",&a,&b);
printf("%d", b>=a);
return 0;
}
|
the_stack_data/54825792.c | // We need to forward routine registration from C to Rust
// to avoid the linker removing the static library.
void R_init_fcl_extendr(void *dll);
void R_init_fcl(void *dll) {
R_init_fcl_extendr(dll);
}
|
the_stack_data/532699.c | // SPDX-License-Identifier: GPL-2.0
#define pr_fmt(fmt) KBUILD_MODNAME ":%s: " fmt, __func__
#ifdef CONFIG_PROC_FS
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/ktime.h>
#include <linux/seq_file.h>
#include <linux/uaccess.h>
#include <linux/atmmpc.h>
#include <linux/atm.h>
#include <linux/gfp.h>
#include "mpc.h"
#include "mpoa_caches.h"
/*
* mpoa_proc.c: Implementation MPOA client's proc
* file system statistics
*/
#if 1
#define dprintk(format, args...) \
printk(KERN_DEBUG "mpoa:%s: " format, __FILE__, ##args) /* debug */
#else
#define dprintk(format, args...) \
do { if (0) \
printk(KERN_DEBUG "mpoa:%s: " format, __FILE__, ##args);\
} while (0)
#endif
#if 0
#define ddprintk(format, args...) \
printk(KERN_DEBUG "mpoa:%s: " format, __FILE__, ##args) /* debug */
#else
#define ddprintk(format, args...) \
do { if (0) \
printk(KERN_DEBUG "mpoa:%s: " format, __FILE__, ##args);\
} while (0)
#endif
#define STAT_FILE_NAME "mpc" /* Our statistic file's name */
extern struct mpoa_client *mpcs;
extern struct proc_dir_entry *atm_proc_root; /* from proc.c. */
static int proc_mpc_open(struct inode *inode, struct file *file);
static ssize_t proc_mpc_write(struct file *file, const char __user *buff,
size_t nbytes, loff_t *ppos);
static int parse_qos(const char *buff);
static const struct proc_ops mpc_proc_ops = {
.proc_open = proc_mpc_open,
.proc_read = seq_read,
.proc_lseek = seq_lseek,
.proc_write = proc_mpc_write,
.proc_release = seq_release,
};
/*
* Returns the state of an ingress cache entry as a string
*/
static const char *ingress_state_string(int state)
{
switch (state) {
case INGRESS_RESOLVING:
return "resolving ";
case INGRESS_RESOLVED:
return "resolved ";
case INGRESS_INVALID:
return "invalid ";
case INGRESS_REFRESHING:
return "refreshing ";
}
return "";
}
/*
* Returns the state of an egress cache entry as a string
*/
static const char *egress_state_string(int state)
{
switch (state) {
case EGRESS_RESOLVED:
return "resolved ";
case EGRESS_PURGE:
return "purge ";
case EGRESS_INVALID:
return "invalid ";
}
return "";
}
/*
* FIXME: mpcs (and per-mpc lists) have no locking whatsoever.
*/
static void *mpc_start(struct seq_file *m, loff_t *pos)
{
loff_t l = *pos;
struct mpoa_client *mpc;
if (!l--)
return SEQ_START_TOKEN;
for (mpc = mpcs; mpc; mpc = mpc->next)
if (!l--)
return mpc;
return NULL;
}
static void *mpc_next(struct seq_file *m, void *v, loff_t *pos)
{
struct mpoa_client *p = v;
(*pos)++;
return v == SEQ_START_TOKEN ? mpcs : p->next;
}
static void mpc_stop(struct seq_file *m, void *v)
{
}
/*
* READING function - called when the /proc/atm/mpoa file is read from.
*/
static int mpc_show(struct seq_file *m, void *v)
{
struct mpoa_client *mpc = v;
int i;
in_cache_entry *in_entry;
eg_cache_entry *eg_entry;
time64_t now;
unsigned char ip_string[16];
if (v == SEQ_START_TOKEN) {
atm_mpoa_disp_qos(m);
return 0;
}
seq_printf(m, "\nInterface %d:\n\n", mpc->dev_num);
seq_printf(m, "Ingress Entries:\nIP address State Holding time Packets fwded VPI VCI\n");
now = ktime_get_seconds();
for (in_entry = mpc->in_cache; in_entry; in_entry = in_entry->next) {
unsigned long seconds_delta = now - in_entry->time;
sprintf(ip_string, "%pI4", &in_entry->ctrl_info.in_dst_ip);
seq_printf(m, "%-16s%s%-14lu%-12u",
ip_string,
ingress_state_string(in_entry->entry_state),
in_entry->ctrl_info.holding_time -
seconds_delta,
in_entry->packets_fwded);
if (in_entry->shortcut)
seq_printf(m, " %-3d %-3d",
in_entry->shortcut->vpi,
in_entry->shortcut->vci);
seq_printf(m, "\n");
}
seq_printf(m, "\n");
seq_printf(m, "Egress Entries:\nIngress MPC ATM addr\nCache-id State Holding time Packets recvd Latest IP addr VPI VCI\n");
for (eg_entry = mpc->eg_cache; eg_entry; eg_entry = eg_entry->next) {
unsigned char *p = eg_entry->ctrl_info.in_MPC_data_ATM_addr;
unsigned long seconds_delta = now - eg_entry->time;
for (i = 0; i < ATM_ESA_LEN; i++)
seq_printf(m, "%02x", p[i]);
seq_printf(m, "\n%-16lu%s%-14lu%-15u",
(unsigned long)ntohl(eg_entry->ctrl_info.cache_id),
egress_state_string(eg_entry->entry_state),
(eg_entry->ctrl_info.holding_time - seconds_delta),
eg_entry->packets_rcvd);
/* latest IP address */
sprintf(ip_string, "%pI4", &eg_entry->latest_ip_addr);
seq_printf(m, "%-16s", ip_string);
if (eg_entry->shortcut)
seq_printf(m, " %-3d %-3d",
eg_entry->shortcut->vpi,
eg_entry->shortcut->vci);
seq_printf(m, "\n");
}
seq_printf(m, "\n");
return 0;
}
static const struct seq_operations mpc_op = {
.start = mpc_start,
.next = mpc_next,
.stop = mpc_stop,
.show = mpc_show
};
static int proc_mpc_open(struct inode *inode, struct file *file)
{
return seq_open(file, &mpc_op);
}
static ssize_t proc_mpc_write(struct file *file, const char __user *buff,
size_t nbytes, loff_t *ppos)
{
char *page, *p;
unsigned int len;
if (nbytes == 0)
return 0;
if (nbytes >= PAGE_SIZE)
nbytes = PAGE_SIZE-1;
page = (char *)__get_free_page(GFP_KERNEL);
if (!page)
return -ENOMEM;
for (p = page, len = 0; len < nbytes; p++, len++) {
if (get_user(*p, buff++)) {
free_page((unsigned long)page);
return -EFAULT;
}
if (*p == '\0' || *p == '\n')
break;
}
*p = '\0';
if (!parse_qos(page))
printk("mpoa: proc_mpc_write: could not parse '%s'\n", page);
free_page((unsigned long)page);
return len;
}
static int parse_qos(const char *buff)
{
/* possible lines look like this
* add 130.230.54.142 tx=max_pcr,max_sdu rx=max_pcr,max_sdu
*/
unsigned char ip[4];
int tx_pcr, tx_sdu, rx_pcr, rx_sdu;
__be32 ipaddr;
struct atm_qos qos;
memset(&qos, 0, sizeof(struct atm_qos));
if (sscanf(buff, "del %hhu.%hhu.%hhu.%hhu",
ip, ip+1, ip+2, ip+3) == 4) {
ipaddr = *(__be32 *)ip;
return atm_mpoa_delete_qos(atm_mpoa_search_qos(ipaddr));
}
if (sscanf(buff, "add %hhu.%hhu.%hhu.%hhu tx=%d,%d rx=tx",
ip, ip+1, ip+2, ip+3, &tx_pcr, &tx_sdu) == 6) {
rx_pcr = tx_pcr;
rx_sdu = tx_sdu;
} else if (sscanf(buff, "add %hhu.%hhu.%hhu.%hhu tx=%d,%d rx=%d,%d",
ip, ip+1, ip+2, ip+3, &tx_pcr, &tx_sdu, &rx_pcr, &rx_sdu) != 8)
return 0;
ipaddr = *(__be32 *)ip;
qos.txtp.traffic_class = ATM_CBR;
qos.txtp.max_pcr = tx_pcr;
qos.txtp.max_sdu = tx_sdu;
qos.rxtp.traffic_class = ATM_CBR;
qos.rxtp.max_pcr = rx_pcr;
qos.rxtp.max_sdu = rx_sdu;
qos.aal = ATM_AAL5;
dprintk("parse_qos(): setting qos parameters to tx=%d,%d rx=%d,%d\n",
qos.txtp.max_pcr, qos.txtp.max_sdu,
qos.rxtp.max_pcr, qos.rxtp.max_sdu);
atm_mpoa_add_qos(ipaddr, &qos);
return 1;
}
/*
* INITIALIZATION function - called when module is initialized/loaded.
*/
int mpc_proc_init(void)
{
struct proc_dir_entry *p;
p = proc_create(STAT_FILE_NAME, 0, atm_proc_root, &mpc_proc_ops);
if (!p) {
pr_err("Unable to initialize /proc/atm/%s\n", STAT_FILE_NAME);
return -ENOMEM;
}
return 0;
}
/*
* DELETING function - called when module is removed.
*/
void mpc_proc_clean(void)
{
remove_proc_entry(STAT_FILE_NAME, atm_proc_root);
}
#endif /* CONFIG_PROC_FS */
|
the_stack_data/75137889.c | /* Test prefetch support. */
/* { dg-options "-mcpu=fr400" } */
/* { dg-do compile } */
void foo (void *x)
{
__data_prefetch0 (x);
}
/* { dg-final { scan-assembler "\tdcpl " } } */
|
the_stack_data/29824510.c | /*
* Copyright (c) 1997, 2000 Hellmuth Michaelis. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
*---------------------------------------------------------------------------
*
* i4b daemon - curses fullscreen output
* -------------------------------------
*
* $Id: curses.c,v 1.36 2000/10/09 12:53:29 hm Exp $
*
* $FreeBSD: src/usr.sbin/i4b/isdnd/curses.c,v 1.6.2.2 2001/08/01 17:45:03 obrien Exp $
* $DragonFly: src/usr.sbin/i4b/isdnd/curses.c,v 1.2 2003/06/17 04:29:54 dillon Exp $
*
* last edit-date: [Thu Jun 1 16:24:43 2000]
*
*---------------------------------------------------------------------------*/
#ifdef USE_CURSES
#include "isdnd.h"
#define CHPOS(cfgp) (((cfgp)->isdncontrollerused*2) + (cfgp)->isdnchannelused)
static void display_budget(void);
static void display_cards(void);
static void menuexit(WINDOW *menu_w);
/*---------------------------------------------------------------------------*
* init curses fullscreen display
*---------------------------------------------------------------------------*/
void
init_screen(void)
{
char buffer[512];
int uheight, lheight;
int i, j;
cfg_entry_t *p;
initscr(); /* curses init */
if((COLS < 80) || (LINES < 24))
{
dolog(LL_ERR, "ERROR, minimal screensize must be 80x24, is %dx%d, terminating!",COLS, LINES);
do_exit(1);
}
noecho();
raw();
uheight = ncontroller * 2; /* cards * b-channels */
lheight = LINES - uheight - 6 + 1; /* rest of display */
if((upper_w = newwin(uheight, COLS, UPPER_B, 0)) == NULL)
{
dolog(LL_ERR, "ERROR, curses init upper window, terminating!");
exit(1);
}
if((mid_w = newwin(1, COLS, UPPER_B+uheight+1, 0)) == NULL)
{
dolog(LL_ERR, "ERROR, curses init mid window, terminating!");
exit(1);
}
if((lower_w = newwin(lheight, COLS, UPPER_B+uheight+3, 0)) == NULL)
{
dolog(LL_ERR, "ERROR, curses init lower window, LINES = %d, lheight = %d, uheight = %d, terminating!", LINES, lheight, uheight);
exit(1);
}
scrollok(lower_w, 1);
snprintf(buffer, sizeof(buffer), "----- isdn controller channel state ------------- isdnd %02d.%02d.%d [pid %d] -", VERSION, REL, STEP, (int)getpid());
while(strlen(buffer) < COLS && strlen(buffer) < sizeof(buffer) - 1)
strcat(buffer, "-");
move(0, 0);
standout();
addstr(buffer);
standend();
move(1, 0);
/* 01234567890123456789012345678901234567890123456789012345678901234567890123456789 */
addstr("c tei b remote iface dir outbytes obps inbytes ibps units");
snprintf(buffer, sizeof(buffer), "----- isdn userland interface state ------------------------------------------");
while(strlen(buffer) < COLS && strlen(buffer) < sizeof(buffer) - 1)
strcat(buffer, "-");
move(uheight+2, 0);
standout();
addstr(buffer);
standend();
snprintf(buffer, sizeof(buffer), "----- isdnd logfile display --------------------------------------------------");
while(strlen(buffer) < COLS && strlen(buffer) < sizeof(buffer) - 1)
strcat(buffer, "-");
move(uheight+4, 0);
standout();
addstr(buffer);
standend();
refresh();
for(i=0, j=0; i <= ncontroller; i++, j+=2)
{
if(isdn_ctrl_tab[i].tei == -1)
mvwprintw(upper_w, j, H_CNTL, "%d --- 1 ", i);
else
mvwprintw(upper_w, j, H_CNTL, "%d %3d 1 ", i, isdn_ctrl_tab[i].tei);
mvwprintw(upper_w, j+1, H_CNTL, " L12 2 ");
}
wrefresh(upper_w);
for(i=0, j=0; i < nentries; i++) /* walk thru all entries */
{
p = &cfg_entry_tab[i]; /* get ptr to enry */
mvwprintw(mid_w, 0, j, "%s%d ", bdrivername(p->usrdevicename), p->usrdeviceunit);
p->fs_position = j;
j += ((strlen(bdrivername(p->usrdevicename)) + (p->usrdeviceunit > 9 ? 2 : 1) + 1));
}
wrefresh(mid_w);
wmove(lower_w, 0, 0);
wrefresh(lower_w);
curses_ready = 1;
}
/*---------------------------------------------------------------------------*
* curses menu for fullscreen command mode
*---------------------------------------------------------------------------*/
void
do_menu(void)
{
static char *menu[WMITEMS] =
{
"1 - (D)isplay refresh",
"2 - (H)angup (choose a channel)",
"3 - (R)eread config file",
"4 - (S)how card types",
"5 - (B)udget information",
"6 - (Q)uit the program",
};
WINDOW *menu_w;
int c;
int mpos;
fd_set set;
struct timeval timeout;
/* create a new window in the lower screen area */
if((menu_w = newwin(WMENU_HGT, WMENU_LEN, WMENU_POSLN, WMENU_POSCO )) == NULL)
{
dolog(LL_WRN, "ERROR, curses init menu window!");
return;
}
/* create a border around the window */
box(menu_w, '|', '-');
/* add a title */
wstandout(menu_w);
mvwaddstr(menu_w, 0, (WMENU_LEN / 2) - (strlen(WMENU_TITLE) / 2), WMENU_TITLE);
wstandend(menu_w);
/* fill the window with the menu options */
for(mpos=0; mpos <= (WMITEMS-1); mpos++)
mvwaddstr(menu_w, mpos + 2, 2, menu[mpos]);
/* highlight the first menu option */
mpos = 0;
wstandout(menu_w);
mvwaddstr(menu_w, mpos + 2, 2, menu[mpos]);
wstandend(menu_w);
/* input loop */
for(;;)
{
wrefresh(menu_w);
FD_ZERO(&set);
FD_SET(STDIN_FILENO, &set);
timeout.tv_sec = WMTIMEOUT;
timeout.tv_usec = 0;
/* if no char is available within timeout, exit menu*/
if((select(STDIN_FILENO + 1, &set, NULL, NULL, &timeout)) <= 0)
goto mexit;
c = wgetch(menu_w);
switch(c)
{
case ' ':
case '\t': /* hilite next option */
mvwaddstr(menu_w, mpos + 2, 2, menu[mpos]);
mpos++;
if(mpos >= WMITEMS)
mpos = 0;
wstandout(menu_w);
mvwaddstr(menu_w, mpos + 2, 2, menu[mpos]);
wstandend(menu_w);
break;
case ('0'+WBUDGET+1): /* display budget info */
case 'B':
case 'b':
display_budget();
goto mexit;
case ('0'+WREFRESH+1): /* display refresh */
case 'D':
case 'd':
wrefresh(curscr);
goto mexit;
case ('0'+WQUIT+1): /* quit program */
case 'Q':
case 'q':
menuexit(menu_w);
do_exit(0);
goto mexit;
case ('0'+WHANGUP+1): /* hangup connection */
case 'H':
case 'h':
display_chans();
goto mexit;
case ('0'+WREREAD+1): /* reread config file */
case 'R':
case 'r':
rereadconfig(42);
goto mexit;
case ('0'+WSHOW+1): /* reread config file */
case 'S':
case 's':
display_cards();
goto mexit;
case '\n':
case '\r': /* exec highlighted option */
switch(mpos)
{
case WREFRESH:
wrefresh(curscr);
break;
case WQUIT:
menuexit(menu_w);
do_exit(0);
break;
case WHANGUP:
display_chans();
break;
case WREREAD:
rereadconfig(42);
break;
case WBUDGET:
display_budget();
break;
case WSHOW:
display_cards();
break;
}
goto mexit;
break;
default:
goto mexit;
break;
}
}
mexit:
menuexit(menu_w);
}
static void
menuexit(WINDOW *menu_w)
{
int uheight = ncontroller * 2; /* cards * b-channels */
char buffer[512];
/* delete the menu window */
delwin(menu_w);
/* re-display the original lower window contents */
touchwin(mid_w);
wrefresh(mid_w);
touchwin(lower_w);
wrefresh(lower_w);
touchwin(upper_w);
wrefresh(upper_w);
move(1, 0);
/* 01234567890123456789012345678901234567890123456789012345678901234567890123456789 */
addstr("c tei b remote iface dir outbytes obps inbytes ibps units");
sprintf(buffer, "----- isdn userland interface state ------------------------------------------");
while(strlen(buffer) < COLS)
strcat(buffer, "-");
move(uheight+2, 0);
standout();
addstr(buffer);
standend();
sprintf(buffer, "----- isdnd logfile display --------------------------------------------------");
while(strlen(buffer) < COLS)
strcat(buffer, "-");
move(uheight+4, 0);
standout();
addstr(buffer);
standend();
refresh();
}
/*---------------------------------------------------------------------------*
* display the charge in units
*---------------------------------------------------------------------------*/
void
display_charge(cfg_entry_t *cep)
{
mvwprintw(upper_w, CHPOS(cep), H_UNITS, "%d", cep->charge);
wclrtoeol(upper_w);
wrefresh(upper_w);
}
/*---------------------------------------------------------------------------*
* display the calculated charge in units
*---------------------------------------------------------------------------*/
void
display_ccharge(cfg_entry_t *cep, int units)
{
mvwprintw(upper_w, CHPOS(cep), H_UNITS, "(%d)", units);
wclrtoeol(upper_w);
wrefresh(upper_w);
}
/*---------------------------------------------------------------------------*
* display accounting information
*---------------------------------------------------------------------------*/
void
display_acct(cfg_entry_t *cep)
{
mvwprintw(upper_w, CHPOS(cep), H_OUT, "%-10d", cep->outbytes);
mvwprintw(upper_w, CHPOS(cep), H_OUTBPS, "%-4d", cep->outbps);
mvwprintw(upper_w, CHPOS(cep), H_IN, "%-10d", cep->inbytes);
mvwprintw(upper_w, CHPOS(cep), H_INBPS, "%-4d", cep->inbps);
wrefresh(upper_w);
}
/*---------------------------------------------------------------------------*
* display connect information
*---------------------------------------------------------------------------*/
void
display_connect(cfg_entry_t *cep)
{
char buffer[256];
/* remote telephone number */
if(aliasing)
{
if(cep->direction == DIR_IN)
snprintf(buffer, sizeof(buffer), "%s", get_alias(cep->real_phone_incoming));
else
snprintf(buffer, sizeof(buffer), "%s", get_alias(cep->remote_phone_dialout));
}
else
{
if(cep->direction == DIR_IN)
snprintf(buffer, sizeof(buffer), "%s/%s", cep->name, cep->real_phone_incoming);
else
snprintf(buffer, sizeof(buffer), "%s/%s", cep->name, cep->remote_phone_dialout);
}
buffer[H_IFN - H_TELN - 1] = '\0';
mvwprintw(upper_w, CHPOS(cep), H_TELN, "%s", buffer);
/* interface */
mvwprintw(upper_w, CHPOS(cep), H_IFN, "%s%d ",
bdrivername(cep->usrdevicename), cep->usrdeviceunit);
mvwprintw(upper_w, CHPOS(cep), H_IO,
cep->direction == DIR_OUT ? "out" : "in");
mvwprintw(upper_w, CHPOS(cep), H_OUT, "-");
mvwprintw(upper_w, CHPOS(cep), H_OUTBPS, "-");
mvwprintw(upper_w, CHPOS(cep), H_IN, "-");
mvwprintw(upper_w, CHPOS(cep), H_INBPS, "-");
if(do_bell)
display_bell();
wrefresh(upper_w);
}
/*---------------------------------------------------------------------------*
* erase line at disconnect time
*---------------------------------------------------------------------------*/
void
display_disconnect(cfg_entry_t *cep)
{
wmove(upper_w, CHPOS(cep),
H_TELN);
wclrtoeol(upper_w);
wrefresh(upper_w);
if(do_bell)
display_bell();
}
/*---------------------------------------------------------------------------*
* display interface up/down information
*---------------------------------------------------------------------------*/
void
display_updown(cfg_entry_t *cep, int updown)
{
if(updown)
wstandend(mid_w);
else
wstandout(mid_w);
mvwprintw(mid_w, 0, cep->fs_position, "%s%d ",
bdrivername(cep->usrdevicename), cep->usrdeviceunit);
wstandend(mid_w);
wrefresh(mid_w);
}
/*---------------------------------------------------------------------------*
* display interface up/down information
*---------------------------------------------------------------------------*/
void
display_l12stat(int controller, int layer, int state)
{
if(controller > ncontroller)
return;
if(!(layer == 1 || layer == 2))
return;
if(state)
wstandout(upper_w);
else
wstandend(upper_w);
if(layer == 1)
{
mvwprintw(upper_w, (controller*2)+1, H_TEI+1, "1");
if(!state)
mvwprintw(upper_w, (controller*2)+1, H_TEI+2, "2");
}
else if(layer == 2)
{
mvwprintw(upper_w, (controller*2)+1, H_TEI+2, "2");
if(state)
mvwprintw(upper_w, (controller*2)+1, H_TEI+1, "1");
}
wstandend(upper_w);
wrefresh(upper_w);
}
/*---------------------------------------------------------------------------*
* display TEI
*---------------------------------------------------------------------------*/
void
display_tei(int controller, int tei)
{
if(controller > ncontroller)
return;
if(tei == -1)
mvwprintw(upper_w, controller*2, H_TEI, "---");
else
mvwprintw(upper_w, controller*2, H_TEI, "%3d", tei);
wrefresh(upper_w);
}
/*---------------------------------------------------------------------------*
* display bell :-)
*---------------------------------------------------------------------------*/
void
display_bell(void)
{
static char bell[1] = { 0x07 };
write(STDOUT_FILENO, &bell[0], 1);
}
/*---------------------------------------------------------------------------*
* display channel information for shutdown
*---------------------------------------------------------------------------*/
void
display_chans(void)
{
char buffer[80];
int i;
int cnt = 0;
WINDOW *chan_w;
int nlines, ncols, pos_x, pos_y;
fd_set set;
struct timeval timeout;
cfg_entry_t *cep = NULL;
/* need this later to close the connection */
struct ctlr_chan {
int cntl;
int chn;
} *cc = NULL;
for (i = 0; i < ncontroller; i++)
{
if((get_controller_state(i)) != CTRL_UP)
continue;
if((ret_channel_state(i, CHAN_B1)) == CHAN_RUN)
cnt++;
if((ret_channel_state(i, CHAN_B2)) == CHAN_RUN)
cnt++;
}
if(cnt > 0)
{
if ((cc = (struct ctlr_chan *)malloc (cnt *
sizeof (struct ctlr_chan))) == NULL)
{
return;
}
nlines = cnt + 4;
ncols = 60;
}
else
{
nlines = 5;
ncols = 22;
}
pos_y = WMENU_POSLN + 4;
pos_x = WMENU_POSCO + 10;
/* create a new window in the lower screen area */
if((chan_w = newwin(nlines, ncols, pos_y, pos_x )) == NULL)
{
dolog(LL_WRN, "ERROR, curses init channel window!");
if (cnt > 0)
free(cc);
return;
}
/* create a border around the window */
box(chan_w, '|', '-');
/* add a title */
wstandout(chan_w);
mvwaddstr(chan_w, 0, (ncols / 2) - (strlen("Channels") / 2), "Channels");
wstandend(chan_w);
/* no active channels */
if (cnt == 0)
{
mvwaddstr(chan_w, 2, 2, "No active channels");
wrefresh(chan_w);
sleep(1);
/* delete the channels window */
delwin(chan_w);
return;
}
nlines = 2;
ncols = 1;
for (i = 0; i < ncontroller; i++)
{
if((get_controller_state(i)) != CTRL_UP)
continue;
if((ret_channel_state(i, CHAN_B1)) == CHAN_RUN)
{
snprintf(buffer, sizeof(buffer), "%d - Controller %d channel %s", ncols, i, "B1");
mvwaddstr(chan_w, nlines, 2, buffer);
cc[ncols - 1].cntl = i;
cc[ncols - 1].chn = CHAN_B1;
nlines++;
ncols++;
}
if((ret_channel_state(i, CHAN_B2)) == CHAN_RUN)
{
snprintf(buffer, sizeof(buffer), "%d - Controller %d channel %s", ncols, i, "B2");
mvwaddstr(chan_w, nlines, 2, buffer);
cc[ncols - 1].cntl = i;
cc[ncols - 1].chn = CHAN_B2;
nlines++;
ncols++;
}
}
for(;;)
{
wrefresh(chan_w);
FD_ZERO(&set);
FD_SET(STDIN_FILENO, &set);
timeout.tv_sec = WMTIMEOUT;
timeout.tv_usec = 0;
/* if no char is available within timeout, exit menu*/
if((select(STDIN_FILENO + 1, &set, NULL, NULL, &timeout)) <= 0)
break;
ncols = wgetch(chan_w);
if (!(isdigit(ncols)))
{
display_bell();
continue;
}
nlines = ncols - '0';
if ((nlines == 0) || (nlines > cnt))
{
display_bell();
continue;
}
if((cep = get_cep_by_cc(cc[nlines-1].cntl, cc[nlines-1].chn))
!= NULL)
{
dolog(LL_CHD, "%05d %s manual disconnect (fullscreen menu)", cep->cdid, cep->name);
cep->hangup = 1;
break;
}
}
free(cc);
/* delete the channels window */
delwin(chan_w);
}
/*---------------------------------------------------------------------------*
* display card type information
*---------------------------------------------------------------------------*/
static void
display_cards(void)
{
WINDOW *chan_w;
int nlines, ncols, pos_x, pos_y;
fd_set set;
struct timeval timeout;
int i;
nlines = 6+ncontroller;
ncols = 60;
pos_y = WMENU_POSLN;
pos_x = WMENU_POSCO;
/* create a new window in the lower screen area */
if((chan_w = newwin(nlines, ncols, pos_y, pos_x )) == NULL)
{
dolog(LL_WRN, "ERROR, curses init channel window!");
return;
}
/* create a border around the window */
box(chan_w, '|', '-');
/* add a title */
wstandout(chan_w);
mvwaddstr(chan_w, 0, (ncols / 2) - (strlen("Cards") / 2), "Cards");
wstandend(chan_w);
mvwprintw(chan_w, 2, 2, "ctrl description");
mvwprintw(chan_w, 3, 2, "---- ----------------------------------------------");
for (i = 0; i < ncontroller; i++)
{
mvwprintw(chan_w, 4+i, 2, " #%d %s", i,
name_of_controller(isdn_ctrl_tab[i].ctrl_type,
isdn_ctrl_tab[i].card_type));
}
wrefresh(chan_w);
FD_ZERO(&set);
FD_SET(STDIN_FILENO, &set);
timeout.tv_sec = WMTIMEOUT*2;
timeout.tv_usec = 0;
if((select(STDIN_FILENO + 1, &set, NULL, NULL, &timeout)) <= 0)
{
delwin(chan_w);
return;
}
wgetch(chan_w);
delwin(chan_w);
}
/*---------------------------------------------------------------------------*
* display budget info
*---------------------------------------------------------------------------*/
static void
display_budget(void)
{
WINDOW *bud_w;
int nlines, ncols, pos_x, pos_y;
fd_set set;
struct timeval timeout;
int i, j;
cfg_entry_t *cep;
time_t now;
double uptime;
int minutes;
int hours;
int days;
nlines = 0;
ncols = 73;
pos_y = WMENU_POSLN;
pos_x = WMENU_POSCO-3;
for(i=0, j=0; i < nentries; i++) /* walk thru all entries */
{
cep = &cfg_entry_tab[i]; /* get ptr to entry */
if(cep->budget_callbackperiod && cep->budget_callbackncalls)
nlines++;
if(cep->budget_calloutperiod && cep->budget_calloutncalls)
nlines++;
}
if(nlines == 0)
return;
nlines += 6;
/* create a new window in the lower screen area */
if((bud_w = newwin(nlines, ncols, pos_y, pos_x )) == NULL)
{
dolog(LL_WRN, "ERROR, curses init budget window!");
return;
}
now = time(NULL);
uptime = difftime(now, starttime);
minutes = (time_t) (uptime / 60) % 60;
hours = (time_t) (uptime / (60*60)) % (60*60);
days = (time_t) (uptime / (60*60*24)) % (60*60*24);
uptime = uptime / (60*60);
/* create a border around the window */
box(bud_w, '|', '-');
/* add a title */
wstandout(bud_w);
mvwaddstr(bud_w, 0, (ncols / 2) - (strlen("Budget") / 2), "Budget");
wstandend(bud_w);
mvwprintw(bud_w, 1, 2, "isdnd uptime: %d %s - %d %s - %d %s",
days,
days == 1 ? "day" : "days",
hours,
hours == 1 ? "hour" : "hours",
minutes,
minutes == 1 ? "minute" : "minutes");
mvwprintw(bud_w, 2, 2, "name t period rest ncall rest rqsts /hr rdone /hr rrjct /hr ");
mvwprintw(bud_w, 3, 2, "-------- - ------ ------ ----- ----- ----- ---- ----- ---- ----- ----");
for(i=0, j=4; i < nentries; i++) /* walk thru all entries */
{
cep = &cfg_entry_tab[i]; /* get ptr to enry */
if(cep->budget_calloutperiod && cep->budget_calloutncalls)
{
mvwprintw(bud_w, j, 2, "%-8s %c %-6d %-6ld %-5d %-5d %-5d %-4.1f %-5d %-4.1f %-5d %-4.1f",
cep->name,
'o',
cep->budget_calloutperiod,
(long)(cep->budget_calloutperiod_time - now),
cep->budget_calloutncalls,
cep->budget_calloutncalls_cnt,
cep->budget_callout_req,
(double)cep->budget_callout_req / uptime,
cep->budget_callout_done,
(double)cep->budget_callout_done / uptime,
cep->budget_callout_rej,
(double)cep->budget_callout_rej / uptime);
j++;
}
if(cep->budget_callbackperiod && cep->budget_callbackncalls)
{
mvwprintw(bud_w, j, 2, "%-8s %c %-6d %-6ld %-5d %-5d %-5d %-4.1f %-5d %-4.1f %-5d %-4.1f",
(cep->budget_calloutperiod && cep->budget_calloutncalls) ? "" : cep->name,
'b',
cep->budget_callbackperiod,
(long)(cep->budget_callbackperiod_time - now),
cep->budget_callbackncalls,
cep->budget_callbackncalls_cnt,
cep->budget_callback_req,
(double)cep->budget_callback_req / uptime,
cep->budget_callback_done,
(double)cep->budget_callback_done / uptime,
cep->budget_callback_rej,
(double)cep->budget_callback_rej / uptime);
j++;
}
}
wrefresh(bud_w);
FD_ZERO(&set);
FD_SET(STDIN_FILENO, &set);
timeout.tv_sec = WMTIMEOUT*3;
timeout.tv_usec = 0;
if((select(STDIN_FILENO + 1, &set, NULL, NULL, &timeout)) <= 0)
{
delwin(bud_w);
return;
}
wgetch(bud_w);
delwin(bud_w);
}
#endif
/* EOF */
|
the_stack_data/232954813.c | void function_dir_2b_file2(void)
{
}
|
the_stack_data/45386.c | #include <stdio.h>
#include <stdlib.h>
/*
*/
int main (void)
{
char Continuar,Matriz[3][50];
int i,j,Indice;
do
{
system("cls");
for(i=0;i<3;i++)
{
printf("Informe um nome:");
fflush(stdin);
gets(Matriz[i]);
Indice=j=0;
while (Matriz[i][j] != '\0')
{
if(Matriz[i][j] != ' ' || (Matriz[i][j] != ' ' && Matriz[i][j+1] != ' ' ))
{
Matriz[i][Indice] = Matriz[i][j];
Indice++;
}
j++;
}
Matriz[i][Indice]='\0';
}
for(i=0;i<3;i++)
{
printf("%s\n",Matriz[i]);
}
printf("\n\n________________________________________________________________________________\n\n");
printf("\n Executar Novamente (S/s para Sim): ");
fflush(stdin);
scanf("%c",&Continuar);
}while(Continuar == 's' || Continuar == 'S');
}
|
the_stack_data/104827707.c | /* PR tree-optimization/47443 */
/* { dg-do compile } */
/* { dg-options "-O -fstack-check=generic" } */
static inline int bar (char *c, int i)
{
return c + i > c;
}
int foo ()
{
char c[100];
return (bar (c, 1));
}
|
the_stack_data/64199980.c | #include <stdio.h>
void read_message(char msg[]) {
printf("Message reads: %s\n", msg);
// 这里 sizeof(msg) (64位系统)会返回 8 , 实际表示的是指针变量的大小,并非 msg 字符串总长度
printf("msg occupies %i bytes\n", sizeof msg);
}
int main() {
char message[] = "Hello World.";
// 数组变量可以当指针使用
printf("message save at: %p\n", message);
read_message(message);
} |
the_stack_data/63748.c |
#if 0
double __builtin_nan(const char);
double __builtin_nan_XXX(const char);
const char xxx;
char* a;
const char* b;
#endif
typedef double __v4df __attribute__ ((__vector_size__ (32)));
typedef float __v8sf __attribute__ ((__vector_size__ (32)));
typedef long long __v4di __attribute__ ((__vector_size__ (32)));
typedef unsigned long long __v4du __attribute__ ((__vector_size__ (32)));
typedef int __v8si __attribute__ ((__vector_size__ (32)));
typedef unsigned int __v8su __attribute__ ((__vector_size__ (32)));
typedef short __v16hi __attribute__ ((__vector_size__ (32)));
typedef unsigned short __v16hu __attribute__ ((__vector_size__ (32)));
typedef char __v32qi __attribute__ ((__vector_size__ (32)));
typedef unsigned char __v32qu __attribute__ ((__vector_size__ (32)));
/* The Intel API is flexible enough that we must allow aliasing with other
vector types, and their scalar components. */
typedef float __m256 __attribute__ ((__vector_size__ (32), __may_alias__));
typedef long long __m256i __attribute__ ((__vector_size__ (32), __may_alias__));
typedef double __m256d __attribute__ ((__vector_size__ (32), __may_alias__));
__m256d __builtin_ia32_addsubpd256 (__v4df __A, __v4df __B);
__m256 __builtin_ia32_addsubps256 (__v8sf __A, __v8sf __B);
__m256d __builtin_ia32_andpd256 (__v4df __A, __v4df __B);
__m256 __builtin_ia32_andps256 (__v8sf __A, __v8sf __B);
__m256d __builtin_ia32_andnpd256 (__v4df __A, __v4df __B);
__m256 __builtin_ia32_andnps256 (__v8sf __A, __v8sf __B);
void __builtin_ia32_maskloadpd256 (const __v4df *__P, __v4di __M);
typedef double __v4df __attribute__ ((__vector_size__ (32)));
|
the_stack_data/82186.c | #if defined(__STDC__) || defined(ANSI) || defined(NRANSI) /* ANSI */
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#define NR_END 1
#define FREE_ARG char*
void nrerror(char error_text[])
/* Numerical Recipes standard error handler */
{
/* fprintf(stderr,"Numerical Recipes run-time error...\n");
fprintf(stderr,"%s\n",error_text);
fprintf(stderr,"...now exiting to system...\n"); */
}
float *vector(long nl, long nh)
/* allocate a float vector with subscript range v[nl..nh] */
{
float *v;
v=(float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float)));
if (!v) nrerror("allocation failure in vector()");
return v-nl+NR_END;
}
int *ivector(long nl, long nh)
/* allocate an int vector with subscript range v[nl..nh] */
{
int *v;
v=(int *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(int)));
if (!v) nrerror("allocation failure in ivector()");
return v-nl+NR_END;
}
unsigned char *cvector(long nl, long nh)
/* allocate an unsigned char vector with subscript range v[nl..nh] */
{
unsigned char *v;
v=(unsigned char *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(unsigned char)));
if (!v) nrerror("allocation failure in cvector()");
return v-nl+NR_END;
}
unsigned long *lvector(long nl, long nh)
/* allocate an unsigned long vector with subscript range v[nl..nh] */
{
unsigned long *v;
v=(unsigned long *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(long)));
if (!v) nrerror("allocation failure in lvector()");
return v-nl+NR_END;
}
double *dvector(long nl, long nh)
/* allocate a double vector with subscript range v[nl..nh] */
{
double *v;
v=(double *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(double)));
if (!v) nrerror("allocation failure in dvector()");
return v-nl+NR_END;
}
float **matrix(long nrl, long nrh, long ncl, long nch)
/* allocate a float matrix with subscript range m[nrl..nrh][ncl..nch] */
{
long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
float **m;
/* allocate pointers to rows */
m=(float **) malloc((size_t)((nrow+NR_END)*sizeof(float*)));
if (!m) nrerror("allocation failure 1 in matrix()");
m += NR_END;
m -= nrl;
/* allocate rows and set pointers to them */
m[nrl]=(float *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(float)));
if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
m[nrl] += NR_END;
m[nrl] -= ncl;
for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
/* return pointer to array of pointers to rows */
return m;
}
double **dmatrix(long nrl, long nrh, long ncl, long nch)
/* allocate a double matrix with subscript range m[nrl..nrh][ncl..nch] */
{
long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
double **m;
/* allocate pointers to rows */
m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
if (!m) nrerror("allocation failure 1 in matrix()");
m += NR_END;
m -= nrl;
/* allocate rows and set pointers to them */
m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
m[nrl] += NR_END;
m[nrl] -= ncl;
for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
/* return pointer to array of pointers to rows */
return m;
}
int **imatrix(long nrl, long nrh, long ncl, long nch)
/* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
{
long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
int **m;
/* allocate pointers to rows */
m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
if (!m) nrerror("allocation failure 1 in matrix()");
m += NR_END;
m -= nrl;
/* allocate rows and set pointers to them */
m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
m[nrl] += NR_END;
m[nrl] -= ncl;
for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
/* return pointer to array of pointers to rows */
return m;
}
float **submatrix(float **a, long oldrl, long oldrh, long oldcl, long oldch,
long newrl, long newcl)
/* point a submatrix [newrl..][newcl..] to a[oldrl..oldrh][oldcl..oldch] */
{
long i,j,nrow=oldrh-oldrl+1,ncol=oldcl-newcl;
float **m;
/* allocate array of pointers to rows */
m=(float **) malloc((size_t) ((nrow+NR_END)*sizeof(float*)));
if (!m) nrerror("allocation failure in submatrix()");
m += NR_END;
m -= newrl;
/* set pointers to rows */
for(i=oldrl,j=newrl;i<=oldrh;i++,j++) m[j]=a[i]+ncol;
/* return pointer to array of pointers to rows */
return m;
}
float **convert_matrix(float *a, long nrl, long nrh, long ncl, long nch)
/* allocate a float matrix m[nrl..nrh][ncl..nch] that points to the matrix
declared in the standard C manner as a[nrow][ncol], where nrow=nrh-nrl+1
and ncol=nch-ncl+1. The routine should be called with the address
&a[0][0] as the first argument. */
{
long i,j,nrow=nrh-nrl+1,ncol=nch-ncl+1;
float **m;
/* allocate pointers to rows */
m=(float **) malloc((size_t) ((nrow+NR_END)*sizeof(float*)));
if (!m) nrerror("allocation failure in convert_matrix()");
m += NR_END;
m -= nrl;
/* set pointers to rows */
m[nrl]=a-ncl;
for(i=1,j=nrl+1;i<nrow;i++,j++) m[j]=m[j-1]+ncol;
/* return pointer to array of pointers to rows */
return m;
}
float ***f3tensor(long nrl, long nrh, long ncl, long nch, long ndl, long ndh)
/* allocate a float 3tensor with range t[nrl..nrh][ncl..nch][ndl..ndh] */
{
long i,j,nrow=nrh-nrl+1,ncol=nch-ncl+1,ndep=ndh-ndl+1;
float ***t;
/* allocate pointers to pointers to rows */
t=(float ***) malloc((size_t)((nrow+NR_END)*sizeof(float**)));
if (!t) nrerror("allocation failure 1 in f3tensor()");
t += NR_END;
t -= nrl;
/* allocate pointers to rows and set pointers to them */
t[nrl]=(float **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(float*)));
if (!t[nrl]) nrerror("allocation failure 2 in f3tensor()");
t[nrl] += NR_END;
t[nrl] -= ncl;
/* allocate rows and set pointers to them */
t[nrl][ncl]=(float *) malloc((size_t)((nrow*ncol*ndep+NR_END)*sizeof(float)));
if (!t[nrl][ncl]) nrerror("allocation failure 3 in f3tensor()");
t[nrl][ncl] += NR_END;
t[nrl][ncl] -= ndl;
for(j=ncl+1;j<=nch;j++) t[nrl][j]=t[nrl][j-1]+ndep;
for(i=nrl+1;i<=nrh;i++) {
t[i]=t[i-1]+ncol;
t[i][ncl]=t[i-1][ncl]+ncol*ndep;
for(j=ncl+1;j<=nch;j++) t[i][j]=t[i][j-1]+ndep;
}
/* return pointer to array of pointers to rows */
return t;
}
void free_vector(float *v, long nl, long nh)
/* free a float vector allocated with vector() */
{
free((FREE_ARG) (v+nl-NR_END));
}
void free_ivector(int *v, long nl, long nh)
/* free an int vector allocated with ivector() */
{
free((FREE_ARG) (v+nl-NR_END));
}
void free_cvector(unsigned char *v, long nl, long nh)
/* free an unsigned char vector allocated with cvector() */
{
free((FREE_ARG) (v+nl-NR_END));
}
void free_lvector(unsigned long *v, long nl, long nh)
/* free an unsigned long vector allocated with lvector() */
{
free((FREE_ARG) (v+nl-NR_END));
}
void free_dvector(double *v, long nl, long nh)
/* free a double vector allocated with dvector() */
{
free((FREE_ARG) (v+nl-NR_END));
}
void free_matrix(float **m, long nrl, long nrh, long ncl, long nch)
/* free a float matrix allocated by matrix() */
{
free((FREE_ARG) (m[nrl]+ncl-NR_END));
free((FREE_ARG) (m+nrl-NR_END));
}
void free_dmatrix(double **m, long nrl, long nrh, long ncl, long nch)
/* free a double matrix allocated by dmatrix() */
{
free((FREE_ARG) (m[nrl]+ncl-NR_END));
free((FREE_ARG) (m+nrl-NR_END));
}
void free_imatrix(int **m, long nrl, long nrh, long ncl, long nch)
/* free an int matrix allocated by imatrix() */
{
free((FREE_ARG) (m[nrl]+ncl-NR_END));
free((FREE_ARG) (m+nrl-NR_END));
}
void free_submatrix(float **b, long nrl, long nrh, long ncl, long nch)
/* free a submatrix allocated by submatrix() */
{
free((FREE_ARG) (b+nrl-NR_END));
}
void free_convert_matrix(float **b, long nrl, long nrh, long ncl, long nch)
/* free a matrix allocated by convert_matrix() */
{
free((FREE_ARG) (b+nrl-NR_END));
}
void free_f3tensor(float ***t, long nrl, long nrh, long ncl, long nch,
long ndl, long ndh)
/* free a float f3tensor allocated by f3tensor() */
{
free((FREE_ARG) (t[nrl][ncl]+ndl-NR_END));
free((FREE_ARG) (t[nrl]+ncl-NR_END));
free((FREE_ARG) (t+nrl-NR_END));
}
#else /* ANSI */
/* traditional - K&R */
#include <stdio.h>
#define NR_END 1
#define FREE_ARG char*
void nrerror(error_text)
char error_text[];
/* Numerical Recipes standard error handler */
{
fprintf(stderr,"Numerical Recipes run-time error...\n");
fprintf(stderr,"%s\n",error_text);
fprintf(stderr,"...now exiting to system...\n");
}
float *vector(nl,nh)
long nh,nl;
/* allocate a float vector with subscript range v[nl..nh] */
{
float *v;
v=(float *)malloc((unsigned int) ((nh-nl+1+NR_END)*sizeof(float)));
if (!v) nrerror("allocation failure in vector()");
return v-nl+NR_END;
}
int *ivector(nl,nh)
long nh,nl;
/* allocate an int vector with subscript range v[nl..nh] */
{
int *v;
v=(int *)malloc((unsigned int) ((nh-nl+1+NR_END)*sizeof(int)));
if (!v) nrerror("allocation failure in ivector()");
return v-nl+NR_END;
}
unsigned char *cvector(nl,nh)
long nh,nl;
/* allocate an unsigned char vector with subscript range v[nl..nh] */
{
unsigned char *v;
v=(unsigned char *)malloc((unsigned int) ((nh-nl+1+NR_END)*sizeof(unsigned char)));
if (!v) nrerror("allocation failure in cvector()");
return v-nl+NR_END;
}
unsigned long *lvector(nl,nh)
long nh,nl;
/* allocate an unsigned long vector with subscript range v[nl..nh] */
{
unsigned long *v;
v=(unsigned long *)malloc((unsigned int) ((nh-nl+1+NR_END)*sizeof(long)));
if (!v) nrerror("allocation failure in lvector()");
return v-nl+NR_END;
}
double *dvector(nl,nh)
long nh,nl;
/* allocate a double vector with subscript range v[nl..nh] */
{
double *v;
v=(double *)malloc((unsigned int) ((nh-nl+1+NR_END)*sizeof(double)));
if (!v) nrerror("allocation failure in dvector()");
return v-nl+NR_END;
}
float **matrix(nrl,nrh,ncl,nch)
long nch,ncl,nrh,nrl;
/* allocate a float matrix with subscript range m[nrl..nrh][ncl..nch] */
{
long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
float **m;
/* allocate pointers to rows */
m=(float **) malloc((unsigned int)((nrow+NR_END)*sizeof(float*)));
if (!m) nrerror("allocation failure 1 in matrix()");
m += NR_END;
m -= nrl;
/* allocate rows and set pointers to them */
m[nrl]=(float *) malloc((unsigned int)((nrow*ncol+NR_END)*sizeof(float)));
if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
m[nrl] += NR_END;
m[nrl] -= ncl;
for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
/* return pointer to array of pointers to rows */
return m;
}
double **dmatrix(nrl,nrh,ncl,nch)
long nch,ncl,nrh,nrl;
/* allocate a double matrix with subscript range m[nrl..nrh][ncl..nch] */
{
long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
double **m;
/* allocate pointers to rows */
m=(double **) malloc((unsigned int)((nrow+NR_END)*sizeof(double*)));
if (!m) nrerror("allocation failure 1 in matrix()");
m += NR_END;
m -= nrl;
/* allocate rows and set pointers to them */
m[nrl]=(double *) malloc((unsigned int)((nrow*ncol+NR_END)*sizeof(double)));
if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
m[nrl] += NR_END;
m[nrl] -= ncl;
for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
/* return pointer to array of pointers to rows */
return m;
}
int **imatrix(nrl,nrh,ncl,nch)
long nch,ncl,nrh,nrl;
/* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
{
long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
int **m;
/* allocate pointers to rows */
m=(int **) malloc((unsigned int)((nrow+NR_END)*sizeof(int*)));
if (!m) nrerror("allocation failure 1 in matrix()");
m += NR_END;
m -= nrl;
/* allocate rows and set pointers to them */
m[nrl]=(int *) malloc((unsigned int)((nrow*ncol+NR_END)*sizeof(int)));
if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
m[nrl] += NR_END;
m[nrl] -= ncl;
for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
/* return pointer to array of pointers to rows */
return m;
}
float **submatrix(a,oldrl,oldrh,oldcl,oldch,newrl,newcl)
float **a;
long newcl,newrl,oldch,oldcl,oldrh,oldrl;
/* point a submatrix [newrl..][newcl..] to a[oldrl..oldrh][oldcl..oldch] */
{
long i,j,nrow=oldrh-oldrl+1,ncol=oldcl-newcl;
float **m;
/* allocate array of pointers to rows */
m=(float **) malloc((unsigned int) ((nrow+NR_END)*sizeof(float*)));
if (!m) nrerror("allocation failure in submatrix()");
m += NR_END;
m -= newrl;
/* set pointers to rows */
for(i=oldrl,j=newrl;i<=oldrh;i++,j++) m[j]=a[i]+ncol;
/* return pointer to array of pointers to rows */
return m;
}
float **convert_matrix(a,nrl,nrh,ncl,nch)
float *a;
long nch,ncl,nrh,nrl;
/* allocate a float matrix m[nrl..nrh][ncl..nch] that points to the matrix
declared in the standard C manner as a[nrow][ncol], where nrow=nrh-nrl+1
and ncol=nch-ncl+1. The routine should be called with the address
&a[0][0] as the first argument. */
{
long i,j,nrow=nrh-nrl+1,ncol=nch-ncl+1;
float **m;
/* allocate pointers to rows */
m=(float **) malloc((unsigned int) ((nrow+NR_END)*sizeof(float*)));
if (!m) nrerror("allocation failure in convert_matrix()");
m += NR_END;
m -= nrl;
/* set pointers to rows */
m[nrl]=a-ncl;
for(i=1,j=nrl+1;i<nrow;i++,j++) m[j]=m[j-1]+ncol;
/* return pointer to array of pointers to rows */
return m;
}
float ***f3tensor(nrl,nrh,ncl,nch,ndl,ndh)
long nch,ncl,ndh,ndl,nrh,nrl;
/* allocate a float 3tensor with range t[nrl..nrh][ncl..nch][ndl..ndh] */
{
long i,j,nrow=nrh-nrl+1,ncol=nch-ncl+1,ndep=ndh-ndl+1;
float ***t;
/* allocate pointers to pointers to rows */
t=(float ***) malloc((unsigned int)((nrow+NR_END)*sizeof(float**)));
if (!t) nrerror("allocation failure 1 in f3tensor()");
t += NR_END;
t -= nrl;
/* allocate pointers to rows and set pointers to them */
t[nrl]=(float **) malloc((unsigned int)((nrow*ncol+NR_END)*sizeof(float*)));
if (!t[nrl]) nrerror("allocation failure 2 in f3tensor()");
t[nrl] += NR_END;
t[nrl] -= ncl;
/* allocate rows and set pointers to them */
t[nrl][ncl]=(float *) malloc((unsigned int)((nrow*ncol*ndep+NR_END)*sizeof(float)));
if (!t[nrl][ncl]) nrerror("allocation failure 3 in f3tensor()");
t[nrl][ncl] += NR_END;
t[nrl][ncl] -= ndl;
for(j=ncl+1;j<=nch;j++) t[nrl][j]=t[nrl][j-1]+ndep;
for(i=nrl+1;i<=nrh;i++) {
t[i]=t[i-1]+ncol;
t[i][ncl]=t[i-1][ncl]+ncol*ndep;
for(j=ncl+1;j<=nch;j++) t[i][j]=t[i][j-1]+ndep;
}
/* return pointer to array of pointers to rows */
return t;
}
void free_vector(v,nl,nh)
float *v;
long nh,nl;
/* free a float vector allocated with vector() */
{
free((FREE_ARG) (v+nl-NR_END));
}
void free_ivector(v,nl,nh)
int *v;
long nh,nl;
/* free an int vector allocated with ivector() */
{
free((FREE_ARG) (v+nl-NR_END));
}
void free_cvector(v,nl,nh)
long nh,nl;
unsigned char *v;
/* free an unsigned char vector allocated with cvector() */
{
free((FREE_ARG) (v+nl-NR_END));
}
void free_lvector(v,nl,nh)
long nh,nl;
unsigned long *v;
/* free an unsigned long vector allocated with lvector() */
{
free((FREE_ARG) (v+nl-NR_END));
}
void free_dvector(v,nl,nh)
double *v;
long nh,nl;
/* free a double vector allocated with dvector() */
{
free((FREE_ARG) (v+nl-NR_END));
}
void free_matrix(m,nrl,nrh,ncl,nch)
float **m;
long nch,ncl,nrh,nrl;
/* free a float matrix allocated by matrix() */
{
free((FREE_ARG) (m[nrl]+ncl-NR_END));
free((FREE_ARG) (m+nrl-NR_END));
}
void free_dmatrix(m,nrl,nrh,ncl,nch)
double **m;
long nch,ncl,nrh,nrl;
/* free a double matrix allocated by dmatrix() */
{
free((FREE_ARG) (m[nrl]+ncl-NR_END));
free((FREE_ARG) (m+nrl-NR_END));
}
void free_imatrix(m,nrl,nrh,ncl,nch)
int **m;
long nch,ncl,nrh,nrl;
/* free an int matrix allocated by imatrix() */
{
free((FREE_ARG) (m[nrl]+ncl-NR_END));
free((FREE_ARG) (m+nrl-NR_END));
}
void free_submatrix(b,nrl,nrh,ncl,nch)
float **b;
long nch,ncl,nrh,nrl;
/* free a submatrix allocated by submatrix() */
{
free((FREE_ARG) (b+nrl-NR_END));
}
void free_convert_matrix(b,nrl,nrh,ncl,nch)
float **b;
long nch,ncl,nrh,nrl;
/* free a matrix allocated by convert_matrix() */
{
free((FREE_ARG) (b+nrl-NR_END));
}
void free_f3tensor(t,nrl,nrh,ncl,nch,ndl,ndh)
float ***t;
long nch,ncl,ndh,ndl,nrh,nrl;
/* free a float f3tensor allocated by f3tensor() */
{
free((FREE_ARG) (t[nrl][ncl]+ndl-NR_END));
free((FREE_ARG) (t[nrl]+ncl-NR_END));
free((FREE_ARG) (t+nrl-NR_END));
}
#endif /* ANSI */
|
the_stack_data/107952277.c | // RUN: not %clang -o /dev/null -v -fxray-instrument -c %s
// XFAIL: -linux-, -freebsd, x86_64-apple-darwin, x86_64-apple-macos
// REQUIRES: amd64 || x86_64 || x86_64h || arm || aarch64 || arm64
typedef int a;
|
the_stack_data/37638915.c | // RUN: %clang_cc1 -emit-llvm -o - %s
// PR4610
#pragma pack(4)
struct ref {
struct ref *next;
} refs;
|
the_stack_data/122016184.c | #include<stdio.h>
#include<string.h>
main()
{
int a;
char string1[20];
printf("Enter the String : ");
gets(string1);
strlen(string1);
printf("The length of The string is %d ",strlen(string1));
//here a short cut for find a lenght of string.
printf("hello%n\n",&a); //%n also count length of string before %n.
printf("%d",a);
}
|
the_stack_data/50137466.c | #include <stdio.h>
int queens[8]={0},counts=0;
int check(int line,int list){
//遍历该行之前的所有行
for (int index=0; index<line; index++) {
//挨个取出前面行中皇后所在位置的列坐标
int data=queens[index];
//如果在同一列,该位置不能放
if (list==data) {
return 0;
}
//如果当前位置的斜上方有皇后,在一条斜线上,也不行
if ((index+data)==(line+list)) {
return 0;
}
//如果当前位置的斜下方有皇后,在一条斜线上,也不行
if ((index-data)==(line-list)) {
return 0;
}
}
//如果以上情况都不是,当前位置就可以放皇后
return 1;
}
//输出语句
void print()
{
for (int line = 0; line < 8; line++)
{
int list;
for (list = 0; list < queens[line]; list++)
printf("0");
printf("#");
for (list = queens[line] + 1; list < 8; list++){
printf("0");
}
printf("\n");
}
printf("=========================\n");
}
void eight_queen(int line){
//在数组中为0-7列
for (int list=0; list<8; list++) {
//对于固定的行列,检查是否和之前的皇后位置冲突
if (check(line, list)) {
//不冲突,以行为下标的数组位置记录列数
queens[line]=list;
//如果最后一样也不冲突,证明为一个正确的摆法
if (line==7) {
//统计摆法的counts加1
counts++;
//输出这个摆法
print();
//每次成功,都要将数组重归为0
queens[line]=0;
return;
}
//继续判断下一样皇后的摆法,递归
eight_queen(line+1);
//不管成功失败,该位置都要重新归0,以便重复使用。
queens[line]=0;
}
}
}
int main() {
//调用回溯函数,参数0表示从棋盘的第一行开始判断
eight_queen(0);
printf("total ways:%d",counts);
return 0;
} |
the_stack_data/60993.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
int main(int argc, char **argv) {
fprintf(stdout,"Hello World\n");
return EXIT_SUCCESS;
}
|
the_stack_data/100141126.c | #include <stdio.h>
void main()
{
float celsius, fahr;
int lower, upper, step;
lower = -100;
upper = 100;
step = 10;
celsius = lower;
printf("===C==|==F===\n");
while (celsius <= upper)
{
fahr = celsius * (9.0 / 5.0) + 32;
printf("%6.1f %3.0f\n", celsius, fahr);
celsius += step;
}
}
|
the_stack_data/92325144.c | // Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <pthread.h>
#define MAX_STRING 100
#define EXP_TABLE_SIZE 1000
#define MAX_EXP 6
#define MAX_SENTENCE_LENGTH 1000
#define MAX_CODE_LENGTH 40
const int vocab_hash_size = 30000000; // Maximum 30 * 0.7 = 21M words in the vocabulary
typedef float real; // Precision of float numbers
struct vocab_word {
long long cn;
int *point;
char *word, *code, codelen;
};
char train_file[MAX_STRING], output_file[MAX_STRING], context_output_file[MAX_STRING];
char save_vocab_file[MAX_STRING], read_vocab_file[MAX_STRING];
struct vocab_word *vocab;
int binary = 0, cbow = 1, debug_mode = 2, window = 5, min_count = 5, num_threads = 12, min_reduce = 1;
int *vocab_hash;
long long vocab_max_size = 1000, vocab_size = 0, layer1_size = 100;
long long train_words = 0, word_count_actual = 0, iter = 5, file_size = 0, classes = 0;
real alpha = 0.025, starting_alpha, sample = 1e-3;
real *syn0, *syn1, *syn1neg, *expTable;
clock_t start;
int hs = 0, negative = 5;
const int table_size = 1e8;
int *table;
void InitUnigramTable() {
int a, i;
double train_words_pow = 0;
double d1, power = 0.75;
table = (int *)malloc(table_size * sizeof(int));
for (a = 0; a < vocab_size; a++) train_words_pow += pow(vocab[a].cn, power);
i = 0;
d1 = pow(vocab[i].cn, power) / train_words_pow;
for (a = 0; a < table_size; a++) {
table[a] = i;
if (a / (double)table_size > d1) {
i++;
d1 += pow(vocab[i].cn, power) / train_words_pow;
}
if (i >= vocab_size) i = vocab_size - 1;
}
}
// Reads a single word from a file, assuming space + tab + EOL to be word boundaries
void ReadWord(char *word, FILE *fin) {
int a = 0, ch;
while (!feof(fin)) {
ch = fgetc(fin);
if (ch == 13) continue;
if ((ch == ' ') || (ch == '\t') || (ch == '\n')) {
if (a > 0) {
if (ch == '\n') ungetc(ch, fin);
break;
}
if (ch == '\n') {
strcpy(word, (char *)"</s>");
return;
} else continue;
}
word[a] = ch;
a++;
if (a >= MAX_STRING - 1) a--; // Truncate too long words
}
word[a] = 0;
}
// Returns hash value of a word
int GetWordHash(char *word) {
unsigned long long a, hash = 0;
for (a = 0; a < strlen(word); a++) hash = hash * 257 + word[a];
hash = hash % vocab_hash_size;
return hash;
}
// Returns position of a word in the vocabulary; if the word is not found, returns -1
int SearchVocab(char *word) {
unsigned int hash = GetWordHash(word);
while (1) {
if (vocab_hash[hash] == -1) return -1;
if (!strcmp(word, vocab[vocab_hash[hash]].word)) return vocab_hash[hash];
hash = (hash + 1) % vocab_hash_size;
}
return -1;
}
// Reads a word and returns its index in the vocabulary
int ReadWordIndex(FILE *fin) {
char word[MAX_STRING];
ReadWord(word, fin);
if (feof(fin)) return -1;
return SearchVocab(word);
}
// Adds a word to the vocabulary
int AddWordToVocab(char *word) {
unsigned int hash, length = strlen(word) + 1;
if (length > MAX_STRING) length = MAX_STRING;
vocab[vocab_size].word = (char *)calloc(length, sizeof(char));
strcpy(vocab[vocab_size].word, word);
vocab[vocab_size].cn = 0;
vocab_size++;
// Reallocate memory if needed
if (vocab_size + 2 >= vocab_max_size) {
vocab_max_size += 1000;
vocab = (struct vocab_word *)realloc(vocab, vocab_max_size * sizeof(struct vocab_word));
}
hash = GetWordHash(word);
while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;
vocab_hash[hash] = vocab_size - 1;
return vocab_size - 1;
}
// Used later for sorting by word counts
int VocabCompare(const void *a, const void *b) {
return ((struct vocab_word *)b)->cn - ((struct vocab_word *)a)->cn;
}
// Sorts the vocabulary by frequency using word counts
void SortVocab() {
int a, size;
unsigned int hash;
// Sort the vocabulary and keep </s> at the first position
qsort(&vocab[1], vocab_size - 1, sizeof(struct vocab_word), VocabCompare);
for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;
size = vocab_size;
train_words = 0;
for (a = 0; a < size; a++) {
// Words occuring less than min_count times will be discarded from the vocab
if ((vocab[a].cn < min_count) && (a != 0)) {
vocab_size--;
free(vocab[a].word);
} else {
// Hash will be re-computed, as after the sorting it is not actual
hash=GetWordHash(vocab[a].word);
while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;
vocab_hash[hash] = a;
train_words += vocab[a].cn;
}
}
vocab = (struct vocab_word *)realloc(vocab, (vocab_size + 1) * sizeof(struct vocab_word));
// Allocate memory for the binary tree construction
for (a = 0; a < vocab_size; a++) {
vocab[a].code = (char *)calloc(MAX_CODE_LENGTH, sizeof(char));
vocab[a].point = (int *)calloc(MAX_CODE_LENGTH, sizeof(int));
}
}
// Reduces the vocabulary by removing infrequent tokens
void ReduceVocab() {
int a, b = 0;
unsigned int hash;
for (a = 0; a < vocab_size; a++) if (vocab[a].cn > min_reduce) {
vocab[b].cn = vocab[a].cn;
vocab[b].word = vocab[a].word;
b++;
} else free(vocab[a].word);
vocab_size = b;
for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;
for (a = 0; a < vocab_size; a++) {
// Hash will be re-computed, as it is not actual
hash = GetWordHash(vocab[a].word);
while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;
vocab_hash[hash] = a;
}
fflush(stdout);
min_reduce++;
}
// Create binary Huffman tree using the word counts
// Frequent words will have short uniqe binary codes
void CreateBinaryTree() {
long long a, b, i, min1i, min2i, pos1, pos2, point[MAX_CODE_LENGTH];
char code[MAX_CODE_LENGTH];
long long *count = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long));
long long *binary = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long));
long long *parent_node = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long));
for (a = 0; a < vocab_size; a++) count[a] = vocab[a].cn;
for (a = vocab_size; a < vocab_size * 2; a++) count[a] = 1e15;
pos1 = vocab_size - 1;
pos2 = vocab_size;
// Following algorithm constructs the Huffman tree by adding one node at a time
for (a = 0; a < vocab_size - 1; a++) {
// First, find two smallest nodes 'min1, min2'
if (pos1 >= 0) {
if (count[pos1] < count[pos2]) {
min1i = pos1;
pos1--;
} else {
min1i = pos2;
pos2++;
}
} else {
min1i = pos2;
pos2++;
}
if (pos1 >= 0) {
if (count[pos1] < count[pos2]) {
min2i = pos1;
pos1--;
} else {
min2i = pos2;
pos2++;
}
} else {
min2i = pos2;
pos2++;
}
count[vocab_size + a] = count[min1i] + count[min2i];
parent_node[min1i] = vocab_size + a;
parent_node[min2i] = vocab_size + a;
binary[min2i] = 1;
}
// Now assign binary code to each vocabulary word
for (a = 0; a < vocab_size; a++) {
b = a;
i = 0;
while (1) {
code[i] = binary[b];
point[i] = b;
i++;
b = parent_node[b];
if (b == vocab_size * 2 - 2) break;
}
vocab[a].codelen = i;
vocab[a].point[0] = vocab_size - 2;
for (b = 0; b < i; b++) {
vocab[a].code[i - b - 1] = code[b];
vocab[a].point[i - b] = point[b] - vocab_size;
}
}
free(count);
free(binary);
free(parent_node);
}
void LearnVocabFromTrainFile() {
char word[MAX_STRING];
FILE *fin;
long long a, i;
for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;
fin = fopen(train_file, "rb");
if (fin == NULL) {
printf("ERROR: training data file not found!\n");
exit(1);
}
vocab_size = 0;
AddWordToVocab((char *)"</s>");
while (1) {
ReadWord(word, fin);
if (feof(fin)) break;
train_words++;
if ((debug_mode > 1) && (train_words % 100000 == 0)) {
printf("%lldK%c", train_words / 1000, 13);
fflush(stdout);
}
i = SearchVocab(word);
if (i == -1) {
a = AddWordToVocab(word);
vocab[a].cn = 1;
} else vocab[i].cn++;
if (vocab_size > vocab_hash_size * 0.7) ReduceVocab();
}
SortVocab();
if (debug_mode > 0) {
printf("Vocab size: %lld\n", vocab_size);
printf("Words in train file: %lld\n", train_words);
}
file_size = ftell(fin);
fclose(fin);
}
void SaveVocab() {
long long i;
FILE *fo = fopen(save_vocab_file, "wb");
for (i = 0; i < vocab_size; i++) fprintf(fo, "%s %lld\n", vocab[i].word, vocab[i].cn);
fclose(fo);
}
void ReadVocab() {
long long a, i = 0;
char c;
char word[MAX_STRING];
FILE *fin = fopen(read_vocab_file, "rb");
if (fin == NULL) {
printf("Vocabulary file not found\n");
exit(1);
}
for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;
vocab_size = 0;
while (1) {
ReadWord(word, fin);
if (feof(fin)) break;
a = AddWordToVocab(word);
fscanf(fin, "%lld%c", &vocab[a].cn, &c);
i++;
}
SortVocab();
if (debug_mode > 0) {
printf("Vocab size: %lld\n", vocab_size);
printf("Words in train file: %lld\n", train_words);
}
fin = fopen(train_file, "rb");
if (fin == NULL) {
printf("ERROR: training data file not found!\n");
exit(1);
}
fseek(fin, 0, SEEK_END);
file_size = ftell(fin);
fclose(fin);
}
void InitNet() {
long long a, b;
unsigned long long next_random = 1;
a = posix_memalign((void **)&syn0, 128, (long long)vocab_size * layer1_size * sizeof(real));
if (syn0 == NULL) {printf("Memory allocation failed\n"); exit(1);}
if (hs) {
a = posix_memalign((void **)&syn1, 128, (long long)vocab_size * layer1_size * sizeof(real));
if (syn1 == NULL) {printf("Memory allocation failed\n"); exit(1);}
for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++)
syn1[a * layer1_size + b] = 0;
}
if (negative>0) {
a = posix_memalign((void **)&syn1neg, 128, (long long)vocab_size * layer1_size * sizeof(real));
if (syn1neg == NULL) {printf("Memory allocation failed\n"); exit(1);}
for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++)
syn1neg[a * layer1_size + b] = 0;
}
for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++) {
next_random = next_random * (unsigned long long)25214903917 + 11;
syn0[a * layer1_size + b] = (((next_random & 0xFFFF) / (real)65536) - 0.5) / layer1_size;
}
CreateBinaryTree();
}
void *TrainModelThread(void *id) {
long long a, b, d, cw, word, last_word, sentence_length = 0, sentence_position = 0;
long long word_count = 0, last_word_count = 0, sen[MAX_SENTENCE_LENGTH + 1];
long long l1, l2, c, target, label, local_iter = iter;
unsigned long long next_random = (long long)id;
real f, g;
clock_t now;
real *neu1 = (real *)calloc(layer1_size, sizeof(real));
real *neu1e = (real *)calloc(layer1_size, sizeof(real));
FILE *fi = fopen(train_file, "rb");
fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET);
while (1) {
if (word_count - last_word_count > 10000) {
word_count_actual += word_count - last_word_count;
last_word_count = word_count;
if ((debug_mode > 1)) {
now=clock();
printf("%cAlpha: %f Progress: %.2f%% Words/thread/sec: %.2fk ", 13, alpha,
word_count_actual / (real)(iter * train_words + 1) * 100,
word_count_actual / ((real)(now - start + 1) / (real)CLOCKS_PER_SEC * 1000));
fflush(stdout);
}
alpha = starting_alpha * (1 - word_count_actual / (real)(iter * train_words + 1));
if (alpha < starting_alpha * 0.0001) alpha = starting_alpha * 0.0001;
}
if (sentence_length == 0) {
while (1) {
word = ReadWordIndex(fi);
if (feof(fi)) break;
if (word == -1) continue;
word_count++;
if (word == 0) break;
// The subsampling randomly discards frequent words while keeping the ranking same
if (sample > 0) {
real ran = (sqrt(vocab[word].cn / (sample * train_words)) + 1) * (sample * train_words) / vocab[word].cn;
next_random = next_random * (unsigned long long)25214903917 + 11;
if (ran < (next_random & 0xFFFF) / (real)65536) continue;
}
sen[sentence_length] = word;
sentence_length++;
if (sentence_length >= MAX_SENTENCE_LENGTH) break;
}
sentence_position = 0;
}
if (feof(fi) || (word_count > train_words / num_threads)) {
word_count_actual += word_count - last_word_count;
local_iter--;
if (local_iter == 0) break;
word_count = 0;
last_word_count = 0;
sentence_length = 0;
fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET);
continue;
}
word = sen[sentence_position];
if (word == -1) continue;
for (c = 0; c < layer1_size; c++) neu1[c] = 0;
for (c = 0; c < layer1_size; c++) neu1e[c] = 0;
next_random = next_random * (unsigned long long)25214903917 + 11;
b = next_random % window;
if (cbow) { //train the cbow architecture
// in -> hidden
cw = 0;
for (a = b; a < window * 2 + 1 - b; a++) if (a != window) {
c = sentence_position - window + a;
if (c < 0) continue;
if (c >= sentence_length) continue;
last_word = sen[c];
if (last_word == -1) continue;
for (c = 0; c < layer1_size; c++) neu1[c] += syn0[c + last_word * layer1_size];
cw++;
}
if (cw) {
for (c = 0; c < layer1_size; c++) neu1[c] /= cw;
if (hs) for (d = 0; d < vocab[word].codelen; d++) {
f = 0;
l2 = vocab[word].point[d] * layer1_size;
// Propagate hidden -> output
for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1[c + l2];
if (f <= -MAX_EXP) continue;
else if (f >= MAX_EXP) continue;
else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];
// 'g' is the gradient multiplied by the learning rate
g = (1 - vocab[word].code[d] - f) * alpha;
// Propagate errors output -> hidden
for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[c + l2];
// Learn weights hidden -> output
for (c = 0; c < layer1_size; c++) syn1[c + l2] += g * neu1[c];
}
// NEGATIVE SAMPLING
if (negative > 0) for (d = 0; d < negative + 1; d++) {
if (d == 0) {
target = word;
label = 1;
} else {
next_random = next_random * (unsigned long long)25214903917 + 11;
target = table[(next_random >> 16) % table_size];
if (target == 0) target = next_random % (vocab_size - 1) + 1;
if (target == word) continue;
label = 0;
}
l2 = target * layer1_size;
f = 0;
for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1neg[c + l2];
if (f > MAX_EXP) g = (label - 1) * alpha;
else if (f < -MAX_EXP) g = (label - 0) * alpha;
else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha;
for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2];
for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * neu1[c];
}
// hidden -> in
for (a = b; a < window * 2 + 1 - b; a++) if (a != window) {
c = sentence_position - window + a;
if (c < 0) continue;
if (c >= sentence_length) continue;
last_word = sen[c];
if (last_word == -1) continue;
for (c = 0; c < layer1_size; c++) syn0[c + last_word * layer1_size] += neu1e[c];
}
}
} else { //train skip-gram
for (a = b; a < window * 2 + 1 - b; a++) if (a != window) {
c = sentence_position - window + a;
if (c < 0) continue;
if (c >= sentence_length) continue;
last_word = sen[c];
if (last_word == -1) continue;
l1 = last_word * layer1_size; // cur env word.
for (c = 0; c < layer1_size; c++) neu1e[c] = 0;
// HIERARCHICAL SOFTMAX
if (hs) for (d = 0; d < vocab[word].codelen; d++) {
f = 0;
l2 = vocab[word].point[d] * layer1_size;
// Propagate hidden -> output
for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1[c + l2];
if (f <= -MAX_EXP) continue;
else if (f >= MAX_EXP) continue;
else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];
// 'g' is the gradient multiplied by the learning rate
g = (1 - vocab[word].code[d] - f) * alpha;
// Propagate errors output -> hidden
for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[c + l2];
// Learn weights hidden -> output
for (c = 0; c < layer1_size; c++) syn1[c + l2] += g * syn0[c + l1];
}
// NEGATIVE SAMPLING
if (negative > 0) for (d = 0; d < negative + 1; d++) {
if (d == 0) {
target = word;
label = 1;
} else {
next_random = next_random * (unsigned long long)25214903917 + 11;
target = table[(next_random >> 16) % table_size];
if (target == 0) target = next_random % (vocab_size - 1) + 1;
if (target == word) continue;
label = 0;
}
l2 = target * layer1_size;
f = 0;
for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1neg[c + l2];
if (f > MAX_EXP) g = (label - 1) * alpha;
else if (f < -MAX_EXP) g = (label - 0) * alpha;
else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha;
for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2];
for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * syn0[c + l1];
}
// Learn weights input -> hidden
for (c = 0; c < layer1_size; c++) syn0[c + l1] += neu1e[c];
}
}
sentence_position++;
if (sentence_position >= sentence_length) {
sentence_length = 0;
continue;
}
}
fclose(fi);
free(neu1);
free(neu1e);
pthread_exit(NULL);
}
void TrainModel() {
long a, b, c, d;
FILE *fo;
FILE *fo2;
pthread_t *pt = (pthread_t *)malloc(num_threads * sizeof(pthread_t));
printf("Starting training using file %s\n", train_file);
starting_alpha = alpha;
if (read_vocab_file[0] != 0) ReadVocab(); else LearnVocabFromTrainFile();
if (save_vocab_file[0] != 0) SaveVocab();
if (output_file[0] == 0) return;
InitNet();
if (negative > 0) InitUnigramTable();
start = clock();
for (a = 0; a < num_threads; a++) pthread_create(&pt[a], NULL, TrainModelThread, (void *)a);
for (a = 0; a < num_threads; a++) pthread_join(pt[a], NULL);
fo = fopen(output_file, "wb");
strcpy(context_output_file, "context-");
strcat(context_output_file, output_file);
fo2 = fopen(context_output_file, "wb");
if (classes == 0) {
// Save the word vectors
fprintf(fo, "%lld %lld\n", vocab_size, layer1_size);
fprintf(fo2, "%lld %lld\n", vocab_size, layer1_size);
for (a = 0; a < vocab_size; a++) {
fprintf(fo, "%s ", vocab[a].word);
fprintf(fo2, "%s ", vocab[a].word);
if (binary) for (b = 0; b < layer1_size; b++) fwrite(&syn0[a * layer1_size + b], sizeof(real), 1, fo);
else for (b = 0; b < layer1_size; b++){
fprintf(fo, "%lf ", syn0[a * layer1_size + b]);
fprintf(fo2, "%lf ", syn1neg[a * layer1_size + b]);
}
fprintf(fo, "\n");
fprintf(fo2, "\n");
}
} else {
// Run K-means on the word vectors
int clcn = classes, iter = 10, closeid;
int *centcn = (int *)malloc(classes * sizeof(int));
int *cl = (int *)calloc(vocab_size, sizeof(int));
real closev, x;
real *cent = (real *)calloc(classes * layer1_size, sizeof(real));
for (a = 0; a < vocab_size; a++) cl[a] = a % clcn;
for (a = 0; a < iter; a++) {
for (b = 0; b < clcn * layer1_size; b++) cent[b] = 0;
for (b = 0; b < clcn; b++) centcn[b] = 1;
for (c = 0; c < vocab_size; c++) {
for (d = 0; d < layer1_size; d++) cent[layer1_size * cl[c] + d] += syn0[c * layer1_size + d];
centcn[cl[c]]++;
}
for (b = 0; b < clcn; b++) {
closev = 0;
for (c = 0; c < layer1_size; c++) {
cent[layer1_size * b + c] /= centcn[b];
closev += cent[layer1_size * b + c] * cent[layer1_size * b + c];
}
closev = sqrt(closev);
for (c = 0; c < layer1_size; c++) cent[layer1_size * b + c] /= closev;
}
for (c = 0; c < vocab_size; c++) {
closev = -10;
closeid = 0;
for (d = 0; d < clcn; d++) {
x = 0;
for (b = 0; b < layer1_size; b++) x += cent[layer1_size * d + b] * syn0[c * layer1_size + b];
if (x > closev) {
closev = x;
closeid = d;
}
}
cl[c] = closeid;
}
}
// Save the K-means classes
for (a = 0; a < vocab_size; a++) fprintf(fo, "%s %d\n", vocab[a].word, cl[a]);
free(centcn);
free(cent);
free(cl);
}
fclose(fo);
fclose(fo2);
}
int ArgPos(char *str, int argc, char **argv) {
int a;
for (a = 1; a < argc; a++) if (!strcmp(str, argv[a])) {
if (a == argc - 1) {
printf("Argument missing for %s\n", str);
exit(1);
}
return a;
}
return -1;
}
int main(int argc, char **argv) {
int i;
if (argc == 1) {
printf("WORD VECTOR estimation toolkit v 0.1c\n\n");
printf("Options:\n");
printf("Parameters for training:\n");
printf("\t-train <file>\n");
printf("\t\tUse text data from <file> to train the model\n");
printf("\t-output <file>\n");
printf("\t\tUse <file> to save the resulting word vectors / word clusters\n");
printf("\t-size <int>\n");
printf("\t\tSet size of word vectors; default is 100\n");
printf("\t-window <int>\n");
printf("\t\tSet max skip length between words; default is 5\n");
printf("\t-sample <float>\n");
printf("\t\tSet threshold for occurrence of words. Those that appear with higher frequency in the training data\n");
printf("\t\twill be randomly down-sampled; default is 1e-3, useful range is (0, 1e-5)\n");
printf("\t-hs <int>\n");
printf("\t\tUse Hierarchical Softmax; default is 0 (not used)\n");
printf("\t-negative <int>\n");
printf("\t\tNumber of negative examples; default is 5, common values are 3 - 10 (0 = not used)\n");
printf("\t-threads <int>\n");
printf("\t\tUse <int> threads (default 12)\n");
printf("\t-iter <int>\n");
printf("\t\tRun more training iterations (default 5)\n");
printf("\t-min-count <int>\n");
printf("\t\tThis will discard words that appear less than <int> times; default is 5\n");
printf("\t-alpha <float>\n");
printf("\t\tSet the starting learning rate; default is 0.025 for skip-gram and 0.05 for CBOW\n");
printf("\t-classes <int>\n");
printf("\t\tOutput word classes rather than word vectors; default number of classes is 0 (vectors are written)\n");
printf("\t-debug <int>\n");
printf("\t\tSet the debug mode (default = 2 = more info during training)\n");
printf("\t-binary <int>\n");
printf("\t\tSave the resulting vectors in binary moded; default is 0 (off)\n");
printf("\t-save-vocab <file>\n");
printf("\t\tThe vocabulary will be saved to <file>\n");
printf("\t-read-vocab <file>\n");
printf("\t\tThe vocabulary will be read from <file>, not constructed from the training data\n");
printf("\t-cbow <int>\n");
printf("\t\tUse the continuous bag of words model; default is 1 (use 0 for skip-gram model)\n");
printf("\nExamples:\n");
printf("./word2vec -train data.txt -output vec.txt -size 200 -window 5 -sample 1e-4 -negative 5 -hs 0 -binary 0 -cbow 1 -iter 3\n\n");
return 0;
}
output_file[0] = 0;
save_vocab_file[0] = 0;
read_vocab_file[0] = 0;
if ((i = ArgPos((char *)"-size", argc, argv)) > 0) layer1_size = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-train", argc, argv)) > 0) strcpy(train_file, argv[i + 1]);
if ((i = ArgPos((char *)"-save-vocab", argc, argv)) > 0) strcpy(save_vocab_file, argv[i + 1]);
if ((i = ArgPos((char *)"-read-vocab", argc, argv)) > 0) strcpy(read_vocab_file, argv[i + 1]);
if ((i = ArgPos((char *)"-debug", argc, argv)) > 0) debug_mode = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-binary", argc, argv)) > 0) binary = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-cbow", argc, argv)) > 0) cbow = atoi(argv[i + 1]);
if (cbow) alpha = 0.05;
if ((i = ArgPos((char *)"-alpha", argc, argv)) > 0) alpha = atof(argv[i + 1]);
if ((i = ArgPos((char *)"-output", argc, argv)) > 0) strcpy(output_file, argv[i + 1]);
if ((i = ArgPos((char *)"-window", argc, argv)) > 0) window = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-sample", argc, argv)) > 0) sample = atof(argv[i + 1]);
if ((i = ArgPos((char *)"-hs", argc, argv)) > 0) hs = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-negative", argc, argv)) > 0) negative = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-threads", argc, argv)) > 0) num_threads = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-iter", argc, argv)) > 0) iter = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-min-count", argc, argv)) > 0) min_count = atoi(argv[i + 1]);
if ((i = ArgPos((char *)"-classes", argc, argv)) > 0) classes = atoi(argv[i + 1]);
vocab = (struct vocab_word *)calloc(vocab_max_size, sizeof(struct vocab_word));
vocab_hash = (int *)calloc(vocab_hash_size, sizeof(int));
expTable = (real *)malloc((EXP_TABLE_SIZE + 1) * sizeof(real));
for (i = 0; i < EXP_TABLE_SIZE; i++) {
expTable[i] = exp((i / (real)EXP_TABLE_SIZE * 2 - 1) * MAX_EXP); // Precompute the exp() table
expTable[i] = expTable[i] / (expTable[i] + 1); // Precompute f(x) = x / (x + 1)
}
TrainModel();
return 0;
}
|
the_stack_data/148578679.c | /*
归并排序:分治思想
- 先分割(回归),再归并(两路归并)
1. 回归(参考后向遍历)
*/
#include <stdio.h>
#include <stdlib.h>
// (已排序)两路归并:左路-(left, mid); 右路-(mid+1, right)
void merge(int a[], int left, int mid, int right)
{
int i, j;
i = left;
j = mid + 1;
int N = right-left+1; // 两路归并后新数组长度
int tmp[N]; //存放归并的新数组
int k = 0;
for (k = 0; k < N; ++k)
{
// 左路归并结束(将右路所剩依次存进新数组)
if (i == mid + 1)
{
tmp[k] = a[j];
j++;
// 右路归并结束(将左路剩余元素依次放入新数组)
}else if (j == right + 1)
{
tmp[k] = a[i];
i++;
}else if (a[i] < a[j])
{
tmp[k] = a[i];
i++;
}else{
tmp[k] = a[j];
j++;
}
}
// 将归并后新数组(已排序),赋值给原数组位置
for (i = 0; i < N; ++i)
{
a[left+i] = tmp[i];
}
}
// 递归(参考后序遍历):分割至单个元素(叶),左右根(处理根节点:两路归并)的顺序
void mergeSort(int a[], int left, int right)
{
// 遍历结束条件
if (a == NULL || left >= right)
{
return;
}
int mid = (left + right)/2;
mergeSort(a, left, mid);
mergeSort(a, mid+1, right);
merge(a, left, mid, right);
/*
// 分割
int mid = (left + right)/2;
// 左、右路均含一个元素为止(跳出递归)
if (left < mid)
{
mergeSort(a, left, mid);
}
if (mid + 1 < right)
{
mergeSort(a, mid + 1, right);
}
// 统治(两路归并) -- 左路:(left, mid); 右路:(mid+1, right)
merge(a, left, mid, right);
*/
}
// 遍历
void traveral(int a[], int n)
{
for (int i = 0; i < n; ++i)
{
printf("%d ", a[i]);
}
printf("\n");
}
int main()
{
int a[20] = {10, 2, 3, 8, 4, 6, 1, 5, 9, 7, 13, 11, 12, 19, 17, 18, 16, 15, 14, 20};
printf("排序前:\n");
traveral(a, 20);
mergeSort(a, 0, 19);
printf("排序后:\n");
traveral(a, 20);
return 0;
} |
the_stack_data/232956540.c | #include <stdio.h>
#include <termios.h>
#include <fcntl.h>
#include <string.h>
#include <time.h>
#include <signal.h>
#define ASK "Do you want another transaction"
#define TRIES 3
#define SLEEPTIME 2
#define BEEP putchar('\a')
int get_response(char *,int);
void set_crmode();
void tty_mode_restore(int);
char get_ok_char();
void set_nodelay_mode();
void ctrl_c_handler(int);
int main(){
int response;
tty_mode_restore(0);
set_crmode();
set_nodelay_mode();
signal(SIGINT,ctrl_c_handler);
signal(SIGQUIT,SIG_IGN);
response = get_response(ASK,TRIES);
printf("response is %d",response);
tty_mode_restore(1);
return response;
}
int get_response(char *question,int maxtries){
char input;
printf("%s (y/n)",question);
//printf("\njust for test");
fflush(stdout);
while(1){
sleep(SLEEPTIME);
input = tolower(get_ok_char());
if(input == 'y')
return 0;
if(input == 'n')
return 1;
if(maxtries-- == 0)
return 2;
BEEP;
}
}
char get_ok_char(){
int c;
while((c=getchar())!=EOF && strchr("yYnN",c) == NULL);
return c;
}
void set_crmode(){
//set no buffer
struct termios ttystate;
tcgetattr(0,&ttystate);
ttystate.c_lflag &= ~ICANON;
ttystate.c_lflag &= ~ECHO;
ttystate.c_cc[VMIN] = 1;
tcsetattr(0,TCSANOW,&ttystate);
}
void set_nodelay_mode(){
int termflags;
termflags = fcntl(0,F_GETFL);
termflags |= O_NDELAY;
fcntl(0,F_SETFL,termflags);
}
void tty_mode_restore(int how){
static struct termios original_mode;
static int original_flags;
if(!how){
tcgetattr(0,&original_mode);
original_flags = fcntl(0,F_GETFL);
}
else{
tcsetattr(0,TCSANOW,&original_mode);
fcntl(0,F_SETFL,original_flags);
}
}
void ctrl_c_handler(int signum){
tty_mode_restore(1);
exit(1);
} |
the_stack_data/154831947.c |
int main()
{
int *p=malloc(sizeof(int));
int x;
int i;
if(i==4711) p=&x;
// should fail if i==4711
free(p);
}
|
the_stack_data/145452383.c | // this source is derived from CHILL AST originally from file '/uufs/chpc.utah.edu/common/home/u1142914/lib/ytopt_vinu/polybench/polybench-code/stencils/jacobi-2d/kernel.c' as parsed by frontend compiler rose
void kernel_jacobi_2d(int tsteps, int n, double A[1300 + 0][1300 + 0], double B[1300 + 0][1300 + 0]) {
int t10;
int t8;
int t6;
int t4;
int t2;
for (t2 = 0; t2 <= tsteps - 1; t2 += 1) {
for (t4 = 1; t4 <= n - 2; t4 += 16)
for (t6 = t4; t6 <= (n - 2 < t4 + 15 ? n - 2 : t4 + 15); t6 += 1)
for (t8 = 1; t8 <= n - 2; t8 += 64)
for (t10 = t8; t10 <= (t8 + 63 < n - 2 ? t8 + 63 : n - 2); t10 += 1)
B[t6][t10] = 0.20000000000000001 * (A[t6][t10] + A[t6][t10 - 1] + A[t6][1 + t10] + A[1 + t6][t10] + A[t6 - 1][t10]);
for (t4 = 1; t4 <= n - 2; t4 += 16)
for (t6 = t4; t6 <= (n - 2 < t4 + 15 ? n - 2 : t4 + 15); t6 += 1)
for (t8 = 1; t8 <= n - 2; t8 += 64)
for (t10 = t8; t10 <= (t8 + 63 < n - 2 ? t8 + 63 : n - 2); t10 += 1)
A[t6][t10] = 0.20000000000000001 * (B[t6][t10] + B[t6][t10 - 1] + B[t6][1 + t10] + B[1 + t6][t10] + B[t6 - 1][t10]);
}
}
|
the_stack_data/100660.c | /**~deployment~
* DeploymentSpecification [Class]
*
* Description
*
* A deployment specification specifies a set of properties that determine execution parameters of a component artifact that
* is deployed on a node. A deployment specification can be aimed at a specific type of container. An artifact that reifies or
* implements deployment specification properties is a deployment descriptor.
*
* Diagrams
*
* Deployments
*
* Generalizations
*
* Artifact
*
* Attributes
*
* deploymentLocation : String [0..1]
*
* The location where an Artifact is deployed onto a Node. This is typically a 'directory' or 'memory address.'
*
* executionLocation : String [0..1]
*
* The location where a component Artifact executes. This may be a local or remote location.
*
* Association Ends
*
* deployment : Deployment [0..1]{subsets Element::owner} (opposite Deployment::configuration)
*
* The deployment with which the DeploymentSpecification is associated.
*
* Constraints
*
* deployment_target
*
* The DeploymentTarget of a DeploymentSpecification is a kind of ExecutionEnvironment.
*
* inv: deployment->forAll (location.oclIsKindOf(ExecutionEnvironment))
*
* deployed_elements
*
* The deployedElements of a DeploymentTarget that are involved in a Deployment that has an associated
* Deployment-Specification is a kind of Component (i.e., the configured components).
*
* inv: deployment->forAll (location.deployedElement->forAll (oclIsKindOf(Component)))
**/ |
the_stack_data/127126.c | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char ** argv)
{
printf("Processus 1 - PID : %d - Paramètre : %s\n", getpid(), argv[1]);
}
|
the_stack_data/73576006.c | /* { dg-do compile } */
/* { dg-options "-O2" } */
/* { dg-require-effective-target alloca } */
extern void bar (int *);
static inline __attribute__((always_inline))
int
foo (int i)
{
struct S {
int ar[1][i];
} s;
s.ar[0][0] = 0;
bar (&s.ar[0][0]);
}
void
baz (int i)
{
foo (i + 2);
}
|
the_stack_data/32950611.c | #include <stdio.h>
#include <ctype.h>
#include <math.h>
#define INF 1.e+37
#define F .25
struct xy {
int xlbf; /*flag:explicit lower bound*/
int xubf; /*flag:explicit upper bound*/
int xqf; /*flag:explicit quantum*/
double (*xf)(); /*transform function, e.g. log*/
float xa,xb; /*scaling coefficients*/
float xlb,xub; /*lower and upper bound*/
float xquant; /*quantum*/
float xoff; /*screen offset fraction*/
float xsize; /*screen fraction*/
int xbot,xtop; /*screen coords of border*/
float xmult; /*scaling constant*/
} xd,yd;
struct val {
float xv;
float yv;
int lblptr;
} *xx;
char *labs;
int labsiz;
int tick = 50;
int top = 4000;
int bot = 200;
float absbot;
int n;
int erasf = 1;
int gridf = 2;
int symbf = 0;
int absf = 0;
int transf;
int brkf;
float dx;
char *plotsymb;
double atof();
#define BSIZ 80
char labbuf[BSIZ];
char titlebuf[BSIZ];
char *modes[] = {
"disconnected",
"solid",
"dotted",
"dotdashed",
"shortdashed",
"longdashed"
};
int mode = 1;
char *realloc();
char *malloc();
double ident(x)
double x;
{
return(x);
}
main(argc,argv)
char *argv[];
{
space(0,0,4096,4096);
init(&xd);
init(&yd);
xd.xsize = yd.xsize = 1.;
xx = (struct val *)malloc((unsigned)sizeof(struct val));
labs = malloc(1);
labs[labsiz++] = 0;
setopt(argc,argv);
if(erasf)
erase();
readin();
transpose();
scale(&xd,(struct val *)&xx->xv);
scale(&yd,(struct val *)&xx->yv);
axes();
title();
plot();
move(1,1);
closevt();
return(0);
}
init(p)
struct xy *p;
{
p->xf = ident;
p->xmult = 1;
}
setopt(argc,argv)
char *argv[];
{
char *p1, *p2;
float temp;
xd.xlb = yd.xlb = INF;
xd.xub = yd.xub = -INF;
while(--argc > 0) {
argv++;
again: switch(argv[0][0]) {
case '-':
argv[0]++;
goto again;
case 'l': /* label for plot */
p1 = titlebuf;
if (argc>=2) {
argv++;
argc--;
p2 = argv[0];
while (*p1++ = *p2++);
}
break;
case 'd': /*disconnected,obsolete option*/
case 'm': /*line mode*/
mode = 0;
if(!numb(&temp,&argc,&argv))
break;
if(temp>=sizeof(modes)/sizeof(*modes))
mode = 1;
else if(temp>=0)
mode = temp;
break;
case 'a': /*automatic abscissas*/
absf = 1;
dx = 1;
if(!numb(&dx,&argc,&argv))
break;
if(numb(&absbot,&argc,&argv))
absf = 2;
break;
case 's': /*save screen, overlay plot*/
erasf = 0;
break;
case 'g': /*grid style 0 none, 1 ticks, 2 full*/
gridf = 0;
if(!numb(&temp,&argc,&argv))
temp = argv[0][1]-'0'; /*for caompatibility*/
if(temp>=0&&temp<=2)
gridf = temp;
break;
case 'c': /*character(s) for plotting*/
if(argc >= 2) {
symbf = 1;
plotsymb = argv[1];
argv++;
argc--;
}
break;
case 't': /*transpose*/
transf = 1;
break;
case 'b': /*breaks*/
brkf = 1;
break;
case 'x': /*x limits */
limread(&xd,&argc,&argv);
break;
case 'y':
limread(&yd,&argc,&argv);
break;
case 'h': /*set height of plot */
if(!numb(&yd.xsize, &argc,&argv))
badarg();
break;
case 'w': /*set width of plot */
if(!numb(&xd.xsize, &argc, &argv))
badarg();
break;
case 'r': /* set offset to right */
if(!numb(&xd.xoff, &argc, &argv))
badarg();
break;
case 'u': /*set offset up the screen*/
if(!numb(&yd.xoff,&argc,&argv))
badarg();
break;
default:
badarg();
}
}
}
limread(p, argcp, argvp)
register struct xy *p;
int *argcp;
char ***argvp;
{
if(*argcp>1 && (*argvp)[1][0]=='l') {
(*argcp)--;
(*argvp)++;
p->xf = log10;
}
if(!numb(&p->xlb,argcp,argvp))
return;
p->xlbf = 1;
if(!numb(&p->xub,argcp,argvp))
return;
p->xubf = 1;
if(!numb(&p->xquant,argcp,argvp))
return;
p->xqf = 1;
}
numb(np, argcp, argvp)
int *argcp;
float *np;
register char ***argvp;
{
register char c;
if(*argcp <= 1)
return(0);
while((c=(*argvp)[1][0]) == '+')
(*argvp)[1]++;
if(!(isdigit(c) || c=='-'&&(*argvp)[1][1]<'A' || c=='.'))
return(0);
*np = atof((*argvp)[1]);
(*argcp)--;
(*argvp)++;
return(1);
}
readin()
{
register t;
struct val *temp;
if(absf==1) {
if(xd.xlbf)
absbot = xd.xlb;
else if(xd.xf==log10)
absbot = 1;
}
for(;;) {
temp = (struct val *)realloc((char*)xx,
(unsigned)(n+1)*sizeof(struct val));
if(temp==0)
return;
xx = temp;
if(absf)
xx[n].xv = n*dx + absbot;
else
if(!getfloat(&xx[n].xv))
return;
if(!getfloat(&xx[n].yv))
return;
xx[n].lblptr = -1;
t = getstring();
if(t>0)
xx[n].lblptr = copystring(t);
n++;
if(t<0)
return;
}
}
transpose()
{
register i;
float f;
struct xy t;
if(!transf)
return;
t = xd; xd = yd; yd = t;
for(i= 0;i<n;i++) {
f = xx[i].xv; xx[i].xv = xx[i].yv; xx[i].yv = f;
}
}
copystring(k)
{
register char *temp;
register i;
int q;
temp = realloc(labs,(unsigned)(labsiz+1+k));
if(temp==0)
return(0);
labs = temp;
q = labsiz;
for(i=0;i<=k;i++)
labs[labsiz++] = labbuf[i];
return(q);
}
float
modceil(f,t)
float f,t;
{
t = fabs(t);
return(ceil(f/t)*t);
}
float
modfloor(f,t)
float f,t;
{
t = fabs(t);
return(floor(f/t)*t);
}
getlim(p,v)
register struct xy *p;
struct val *v;
{
register i;
i = 0;
do {
if(!p->xlbf && p->xlb>v[i].xv)
p->xlb = v[i].xv;
if(!p->xubf && p->xub<v[i].xv)
p->xub = v[i].xv;
i++;
} while(i < n);
}
struct z {
float lb,ub,mult,quant;
} setloglim(), setlinlim();
setlim(p)
register struct xy *p;
{
float t,delta,sign;
struct z z;
int mark[50];
float lb,ub;
int lbf,ubf;
lb = p->xlb;
ub = p->xub;
delta = ub-lb;
if(p->xqf) {
if(delta*p->xquant <=0 )
badarg();
return;
}
sign = 1;
lbf = p->xlbf;
ubf = p->xubf;
if(delta < 0) {
sign = -1;
t = lb;
lb = ub;
ub = t;
t = lbf;
lbf = ubf;
ubf = t;
}
else if(delta == 0) {
if(ub > 0) {
ub = 2*ub;
lb = 0;
}
else
if(lb < 0) {
lb = 2*lb;
ub = 0;
}
else {
ub = 1;
lb = -1;
}
}
if(p->xf==log10 && lb>0 && ub>lb) {
z = setloglim(lbf,ubf,lb,ub);
p->xlb = z.lb;
p->xub = z.ub;
p->xmult *= z.mult;
p->xquant = z.quant;
if(setmark(mark,p)<2) {
p->xqf = lbf = ubf = 1;
lb = z.lb; ub = z.ub;
} else
return;
}
z = setlinlim(lbf,ubf,lb,ub);
if(sign > 0) {
p->xlb = z.lb;
p->xub = z.ub;
} else {
p->xlb = z.ub;
p->xub = z.lb;
}
p->xmult *= z.mult;
p->xquant = sign*z.quant;
}
struct z
setloglim(lbf,ubf,lb,ub)
float lb,ub;
{
float r,s,t;
struct z z;
for(s=1; lb*s<1; s*=10) ;
lb *= s;
ub *= s;
for(r=1; 10*r<=lb; r*=10) ;
for(t=1; t<ub; t*=10) ;
z.lb = !lbf ? r : lb;
z.ub = !ubf ? t : ub;
if(ub/lb<100) {
if(!lbf) {
if(lb >= 5*z.lb)
z.lb *= 5;
else if(lb >= 2*z.lb)
z.lb *= 2;
}
if(!ubf) {
if(ub*5 <= z.ub)
z.ub /= 5;
else if(ub*2 <= z.ub)
z.ub /= 2;
}
}
z.mult = s;
z.quant = r;
return(z);
}
struct z
setlinlim(lbf,ubf,xlb,xub)
int lbf,ubf;
float xlb,xub;
{
struct z z;
float r,s,delta;
float ub,lb;
loop:
ub = xub;
lb = xlb;
delta = ub - lb;
/*scale up by s, a power of 10, so range (delta) exceeds 1*/
/*find power of 10 quantum, r, such that delta/10<=r<delta*/
r = s = 1;
while(delta*s < 10)
s *= 10;
delta *= s;
while(10*r < delta)
r *= 10;
lb *= s;
ub *= s;
/*set r=(1,2,5)*10**n so that 3-5 quanta cover range*/
if(r>=delta/2)
r /= 2;
else if(r<delta/5)
r *= 2;
z.ub = ubf? ub: modceil(ub,r);
z.lb = lbf? lb: modfloor(lb,r);
if(!lbf && z.lb<=r && z.lb>0) {
xlb = 0;
goto loop;
}
else if(!ubf && z.ub>=-r && z.ub<0) {
xub = 0;
goto loop;
}
z.quant = r;
z.mult = s;
return(z);
}
scale(p,v)
register struct xy *p;
struct val *v;
{
float edge;
getlim(p,v);
setlim(p);
edge = top-bot;
p->xa = p->xsize*edge/((*p->xf)(p->xub) - (*p->xf)(p->xlb));
p->xbot = bot + edge*p->xoff;
p->xtop = p->xbot + (top-bot)*p->xsize;
p->xb = p->xbot - (*p->xf)(p->xlb)*p->xa + .5;
}
axes()
{
register i;
int mark[50];
int xn, yn;
if(gridf==0)
return;
line(xd.xbot,yd.xbot,xd.xtop,yd.xbot);
cont(xd.xtop,yd.xtop);
cont(xd.xbot,yd.xtop);
cont(xd.xbot,yd.xbot);
xn = setmark(mark,&xd);
for(i=0; i<xn; i++) {
if(gridf==2)
line(mark[i],yd.xbot,mark[i],yd.xtop);
if(gridf==1) {
line(mark[i],yd.xbot,mark[i],yd.xbot+tick);
line(mark[i],yd.xtop-tick,mark[i],yd.xtop);
}
}
yn = setmark(mark,&yd);
for(i=0; i<yn; i++) {
if(gridf==2)
line(xd.xbot,mark[i],xd.xtop,mark[i]);
if(gridf==1) {
line(xd.xbot,mark[i],xd.xbot+tick,mark[i]);
line(xd.xtop-tick,mark[i],xd.xtop,mark[i]);
}
}
}
setmark(xmark,p)
int *xmark;
register struct xy *p;
{
int xn = 0;
float x,xl,xu;
float q;
if(p->xf==log10&&!p->xqf) {
for(x=p->xquant; x<p->xub; x*=10) {
submark(xmark,&xn,x,p);
if(p->xub/p->xlb<=100) {
submark(xmark,&xn,2*x,p);
submark(xmark,&xn,5*x,p);
}
}
} else {
xn = 0;
q = p->xquant;
if(q>0) {
xl = modceil(p->xlb+q/6,q);
xu = modfloor(p->xub-q/6,q)+q/2;
} else {
xl = modceil(p->xub-q/6,q);
xu = modfloor(p->xlb+q/6,q)-q/2;
}
for(x=xl; x<=xu; x+=fabs(p->xquant))
xmark[xn++] = (*p->xf)(x)*p->xa + p->xb;
}
return(xn);
}
submark(xmark,pxn,x,p)
int *xmark;
int *pxn;
float x;
struct xy *p;
{
if(1.001*p->xlb < x && .999*p->xub > x)
xmark[(*pxn)++] = log10(x)*p->xa + p->xb;
}
plot()
{
int ix,iy;
int i;
int conn;
conn = 0;
if(mode!=0)
linemod(modes[mode]);
for(i=0; i<n; i++) {
if(!conv(xx[i].xv,&xd,&ix) ||
!conv(xx[i].yv,&yd,&iy)) {
conn = 0;
continue;
}
if(mode!=0) {
if(conn != 0)
cont(ix,iy);
else
move(ix,iy);
conn = 1;
}
conn &= symbol(ix,iy,xx[i].lblptr);
}
linemod(modes[1]);
}
conv(xv,p,ip)
float xv;
register struct xy *p;
int *ip;
{
long ix;
ix = p->xa*(*p->xf)(xv*p->xmult) + p->xb;
if(ix<p->xbot || ix>p->xtop)
return(0);
*ip = ix;
return(1);
}
getfloat(p)
float *p;
{
register i;
i = scanf("%f",p);
return(i==1);
}
getstring()
{
register i;
char junk[20];
i = scanf("%1s",labbuf);
if(i==-1)
return(-1);
switch(*labbuf) {
default:
if(!isdigit(*labbuf)) {
ungetc(*labbuf,stdin);
i = scanf("%s",labbuf);
break;
}
case '.':
case '+':
case '-':
ungetc(*labbuf,stdin);
return(0);
case '"':
i = scanf("%[^\"\n]",labbuf);
scanf("%[\"]",junk);
break;
}
if(i==-1)
return(-1);
return(strlen(labbuf));
}
symbol(ix,iy,k)
{
if(symbf==0&&k<0) {
if(mode==0)
point(ix,iy);
return(1);
}
else {
move(ix,iy);
label(k>=0?labs+k:plotsymb);
move(ix,iy);
return(!brkf|k<0);
}
}
title()
{
move(xd.xbot,yd.xbot-60);
if (titlebuf[0]) {
label(titlebuf);
label(" ");
}
if(erasf&&gridf) {
axlab('x',&xd);
label(" ");
axlab('y',&yd);
}
}
axlab(c,p)
char c;
struct xy *p;
{
char buf[50];
sprintf(buf,"%g -%s%c- %g", p->xlb/p->xmult,
p->xf==log10?"log ":"", c, p->xub/p->xmult);
label(buf);
}
badarg()
{
fprintf(stderr,"graph: error in arguments\n");
exit(1);
}
|
the_stack_data/247018764.c | /* lshrdi3.c extracted from gcc-2.7.2/libgcc2.c which is: */
/* Copyright (C) 1989, 1992, 1993, 1994, 1995 Free Software Foundation, Inc.
This file is part of GNU CC.
GNU CC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public Licence as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU CC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public Licence for more details.
You should have received a copy of the GNU General Public Licence
along with GNU CC; see the file COPYING. If not, write to
the Free Software Foundation, 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA. */
#define BITS_PER_UNIT 8
typedef int SItype __attribute__((mode(SI)));
typedef unsigned int USItype __attribute__((mode(SI)));
typedef int DItype __attribute__((mode(DI)));
typedef int word_type __attribute__((mode(__word__)));
struct DIstruct {
SItype low;
SItype high;
};
union DIunion {
struct DIstruct s;
DItype ll;
};
DItype __lshrdi3(DItype u, word_type b)
{
union DIunion w;
word_type bm;
union DIunion uu;
if (b == 0)
return u;
uu.ll = u;
bm = (sizeof(SItype) * BITS_PER_UNIT) - b;
if (bm <= 0) {
w.s.high = 0;
w.s.low = (USItype) uu.s.high >> -bm;
} else {
USItype carries = (USItype) uu.s.high << bm;
w.s.high = (USItype) uu.s.high >> b;
w.s.low = ((USItype) uu.s.low >> b) | carries;
}
return w.ll;
}
|
the_stack_data/16115.c | /* This testcase is part of GDB, the GNU debugger.
Copyright 2012-2017 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
extern int get_version_1 (void);
extern int get_version_2 (void);
int
main (void)
{
int v1 = get_version_1 ();
int v2 = get_version_2 ();
if (v1 != 104)
return 1;
/* The value returned by get_version_2 depends on the target.
On GNU/Linux, for instance, it should return 104. But on
x86-windows, for instance, it will return 203. */
if (v2 != 104 && v2 != 203)
return 2;
return 0;
}
|
the_stack_data/31653.c | #include <stdio.h>
int main(int argc, char *argv[]) {
int n,m,t,i,s;
int a[100];
while (scanf("%d",&t)!=EOF&&t<20) {
for(i=1;i<=t;i++){
scanf("%d",&a[i]);
}
m=-1;
scanf("%d",&s);
for(i=1;i<=t;i++){
if(a[i]==s){
m=i;
break;
}
}
if(m>=0)
printf("%d\n",m-1);
else
printf("No\n");
}
return 0;
}
|
the_stack_data/1069700.c | #include <stdio.h>
int main() {
float a, b, c, d, max, min;
printf("Unesite brojeve a,b,c,d: ");
scanf("%f %f %f %f", &a, &b, &c, &d);
if(c<b && d<a){ printf("Skupovi se ne sijeku."); return 0; }
if((c<b)|| (d<a)) {
if(a>c) min=a; else min=c;
if(d<b) max=d; else max=b;
printf("Rezultantni interval je [%g,%g].", min, max);
}
else printf("Skupovi se ne sijeku.");
return 0;
}
|
the_stack_data/32951599.c | #include<stdio.h>
#include<stdlib.h>
#include <math.h>
typedef struct PQ{
int node;
int min_dist;
int predecessor;
}PQ;
typedef struct Heap{
PQ *Array;
int capacity;
int size;
}Heap;
// Prototype of a utility function to swap two numbers
void swap(PQ *x, PQ *y);
Heap* build_heap(int n)
{
Heap *heap = (Heap *)malloc(sizeof(Heap));
heap->Array = (PQ *)malloc(sizeof(PQ)*n);
heap->capacity = n;
heap->size = 0;
return heap;
}
int left_child(int i){
return 2*i+1;
}
int right_child(int i){
return 2*i+2;
}
int parent(int i){
return (i-1)/2;
}
PQ heap_getMin(Heap *heap){
if (heap->size <= 0)
return (PQ){__INT16_MAX__, __INT16_MAX__, __INT16_MAX__};
return heap->Array[0];
}
void heapify(int i, Heap *heap)
{
int l = left_child(i);
int r = right_child(i);
int min = i;
if(l < heap->size && heap->Array[l].min_dist < heap->Array[i].min_dist)
min = l;
if (r < heap->size && heap->Array[r].min_dist < heap->Array[min].min_dist)
min = r;
if (min != i)
{
swap(&(heap->Array[i]), &(heap->Array[min]));
heapify(min, heap);
}
return;
}
void heap_insert(Heap *heap, int dist, int node, int pred)
{
if(heap->size == heap->capacity){
printf("\nOverflow: Could not insertKey\n");
return;
}
heap->size += 1;
int i = heap->size -1;
heap->Array[i].min_dist = dist;
heap->Array[i].node = node;
heap->Array[i].predecessor = pred;
while (i != 0 && heap->Array[i].min_dist < heap->Array[parent(i)].min_dist)
{
swap(&(heap->Array[i]), &(heap->Array[parent(i)]));
i = parent(i);
}
return;
}
PQ heap_remove_min(Heap *heap)
{
if (heap->size <= 0)
return (PQ){__INT16_MAX__, __INT16_MAX__, __INT16_MAX__};
if (heap->size == 1)
{
heap->size = 0;
return heap->Array[0];
}
PQ root = heap->Array[0];
heap->Array[0] = heap->Array[heap->size-1];
heap->size -= 1;
heapify(0, heap);
return root;
}
void print_heap(Heap *heap)
{
printf("\n");
for (int i = 0; i < heap->size; i++)
{
printf("Node: %d\n", heap->Array[i].node);
printf("Dist: %d\n", heap->Array[i].min_dist);
printf("Pred_Node: %d\n", heap->Array[i].predecessor);
}
printf("\n");
}
void swap(PQ *x, PQ *y)
{
PQ temp = *x;
*x = *y;
*y = temp;
}
//function to print the dijkstra's shortest path
void print_path(int* Array, int n, int start, int end)
{
printf("\nPath => ");
int x = 1;
int temp = end;
while(1)
{
if (temp == start) break;
x += 1;
temp = Array[temp];
}
int *print = (int *)malloc(x*sizeof(int));
temp = end;
for(int i = 0; i < x; i++)
{
print[x-1-i] = temp;
temp = Array[temp];
}
for(int i = 0; i < x-1; i++)
{
printf(" %d ->", print[i]);
}
printf(" %d\n", print[x-1]);
}
//dijkstra's algorithm including path and without update_val function
int dijkstra(int** Graph, int n, int start, int end, int print)
{
if (end == start)
{
printf("No path exixts if start and goal nodes are the same\n");
}
Heap *heap = build_heap((n*n));
int* visited = (int*)malloc(n*sizeof(int));
for (int i=0;i<n;i++)
{
visited[i] = -1;
}
int* cost_array = (int*)malloc(n*sizeof(int));
for (int i=0;i<n;i++)
{
cost_array[i] = __INT16_MAX__;
}
int* pred_array = (int*)malloc(n*sizeof(int));
for (int i=0;i<n;i++)
{
pred_array[i] = -1;
}
for (int i=0;i<n;i++)
{
if (i!=start) heap_insert(heap,__INT16_MAX__,i,-1);
}
heap_insert(heap,0,start,-1);
while (1)
{
PQ min;
//minimum distance node is removed
do{
min = heap_remove_min(heap);
}while(visited[min.node] == 1);
//we check whether this node has already been processed, this is possible due to duplicates
if (min.node == end)
{
break;
}
//if node being removed is the goal node, we have our solution
//we go throught the successors of the node being processed
for (int i=0;i<n;i++)
{
if (Graph[min.node][i] != 0 && i!=min.node && visited[i] != 1)
{
if (min.min_dist + Graph[min.node][i] < cost_array[i])
{
heap_insert(heap,Graph[min.node][i]+min.min_dist,i,min.node);
visited[i]= 0;
cost_array[i] = Graph[min.node][i]+min.min_dist;
pred_array[i] = min.node;
}
}
}
visited[min.node] = 1;
//this node has been processed
}
//print function if needed
if (print == 1){
print_path(pred_array,n,start,end);
printf("Distance: %d\n\n", cost_array[end]);
}
return cost_array[end];
}
int main()
{
int n;
scanf("%d",&n);
int** Graph = (int**)malloc(n*sizeof(int*));
for (int i=0;i<n;i++){
Graph[i] = (int*)malloc(n*sizeof(int));
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++) scanf("%d",&Graph[i][j]);
}
int distance = dijkstra(Graph,n,0,4, 1);
printf("\n");
}
|
the_stack_data/95451062.c | int climbStairs(int n) {
int f[3] = {1, 1, 0};
for (int i = 2; i <= n; i++) {
f[1] = f[2] = f[0] + f[1];
f[0] = f[1] - f[0];
}
return n < 2 ? f[n] : f[2];
} |
the_stack_data/197828.c | #ifdef STM32F4xx
#include "stm32f4xx_hal_sai.c"
#endif
#ifdef STM32F7xx
#include "stm32f7xx_hal_sai.c"
#endif
#ifdef STM32H7xx
#include "stm32h7xx_hal_sai.c"
#endif
#ifdef STM32L4xx
#include "stm32l4xx_hal_sai.c"
#endif
|
the_stack_data/28263631.c | //2.3: Write a program to input a number and check it to be even or odd using bitwise operator.
#include<stdio.h>
int main(){
int n;
printf("Enter the number : ");
scanf("%d",&n);
if(n&1)
printf("%d is Odd",n);
else
printf("%d is Even",n);
}
/*
OUTPUT
Enter the number : 76
76 is Even*/
|
the_stack_data/98575606.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sha256.h"
int main(int argc, char *argv[])
{
if (argc < 3)
{
printf("Usage: checkhash [filename] [hash]\nCompares file to SHA-256 hash. Returns 0 if they match, and 1 if they don't.\n");
}
else if (strlen(argv[2]) != 64)
{
printf("Hash is wrong size (should be 64-digits long)\n");
}
else
{
FILE *file = fopen(argv[1], "rb");
if (!file)
{
printf("Could not open file '%s'\n", argv[1]);
}
else
{
// Read file into buffer
fseek(file, 0, SEEK_END);
const long file_size = ftell(file);
rewind(file);
unsigned char *file_buffer = malloc(file_size);
fread(file_buffer, 1, file_size, file);
fclose(file);
// Generate hash
SHA256_CTX sha256_ctx;
sha256_init(&sha256_ctx);
sha256_update(&sha256_ctx, file_buffer, file_size);
free(file_buffer);
unsigned char hash[32];
sha256_final(&sha256_ctx, hash);
// Convert hash to string, so we can compare with the argument
const char lookup[0x10] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
char hash_string[64];
for (unsigned int i = 0; i < 32; ++i)
{
hash_string[i * 2] = lookup[hash[i] >> 4];
hash_string[(i * 2) + 1] = lookup[hash[i] & 0xF];
}
// Compare hashes
if (memcmp(hash_string, argv[2], 64))
{
printf("File does not match hash\n");
}
else
{
printf("File matches hash\n");
return 0;
}
}
}
return 1;
}
|
the_stack_data/176706879.c | /* Exercise 1 - Calculations
Write a C program to input marks of two subjects. Calculate and print the average of the two marks. */
#include <stdio.h>
int main() {
int number1, number2;
int sum;
float avg;
printf("Enter mark 1:");
scanf("%d", &number1);
printf("Enter mark 2:");
scanf("%d", &number2);
sum = number1 + number2;
avg = sum /2;
printf("Average is %.2f", avg);
return 0;
}
|
the_stack_data/36074071.c | // This program is done by CS20B1044 Avinash R Changrani
// Extra Question : To find if square matrix of order nxn is symmetric using transpose
#include<stdio.h>
void main()
{
int n,i,j;
printf("This is a program to find variance of elements in a matrix\n");
// Ask user for number of rows and columns
printf("Enter the value for order of the square matrix n :\n");
scanf("%d", &n);
int mat[n][n];
// Ask user for elements of the matrix
printf("Enter the value of elements of the matrix\n");
for(i=1; i<=n; i++) {
for(j=1;j<=n;j++) {
printf("Enter value for mat[%d][%d]:", i, j);
scanf("%d", &mat[i][j]);
}
}
// Printing the original matrix
printf("The Original matrix is\n");
for(i=1; i<=n; i++) {
for(j=1;j<=n;j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
// Tranpose matrix
int mattranspose[n][n];
for(i=1; i<=n; i++) {
for(j=1;j<=n;j++) {
mattranspose[i][j] = mat[j][i];
}
}
// Printing the transpose matrix
printf("The Transpose matrix is\n");
for(i=1; i<=n; i++) {
for(j=1;j<=n;j++) {
printf("%d ", mattranspose[i][j]);
}
printf("\n");
}
int not = 0 ; // Number of asymmetries
//Checking if it's Symmetric as when A = A(T) it's symmetric
for(i=1; i<=n; i++) {
for(j=1;j<=n;j++) {
if( mat[i][j] != mattranspose[i][j])
not++;
}
}
if (not == 0)
printf("Matrix is Symmetric\n");
else
printf("Matrix is not symmetric\n");
}
|
the_stack_data/215767978.c | #include <stdio.h>
#include <stdlib.h>
#define REPORT_LENGTH 8
int main(int argc, char** argv)
{
if (argc < 2)
{
printf("generatelist: missing quantity operand\n");
return 1;
}
int report_quantity = (int) strtol(argv[1], (char **) NULL, 10);
if (report_quantity <= 0)
{
printf("generatelist: invalid quantity operand\n");
printf("Argument must be a positive integer.\n");
return 2;
}
char random_digit;
FILE* list = fopen("report_list", "w");
for (int i = 0; i < report_quantity; i++)
{
fputs("./YYYY-MM-DD/", list);
for (int j = 0; j < REPORT_LENGTH; j++)
{
random_digit = rand() % 10 + '0';
fputc(random_digit, list);
}
fputs(".json", list);
random_digit = '\n';
fputc(random_digit, list);
}
fclose(list);
return 0;
}
|
the_stack_data/258695.c | /* We were ICEing in bsi_after_labels because
we had a BB which did not have a lablel.
PR middle-end/18903 */
#ifndef NO_LABEL_VALUES
void g (int s, int f)
{
&&ff;
s = f;
ff:
goto end;
f = s;
end:;
}
#else
int g;
#endif
|
the_stack_data/19103.c | #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(){
int mypid, myppid;
printf("This is the main() program\n");
printf("I would likde to know the PID and PPID's information\n");
mypid = getpid();
myppid = getppid();
printf("The process ID is %d\n", mypid);
printf("The parent process ID is %d\n", myppid);
return 0;
}
|
the_stack_data/247017772.c | #include "syscall.h"
int main()
{
int i;
char *message = "2_2: Should print before 2_3 in HRRN because waited long enough\n\r";
int messageLength = getStringSize(message);
PredictCPU(55);
for(i = 0; i < 100; i++){
i++;
}
Write(message, messageLength, 1);
return 0;
}
int getStringSize(char *s) {
int count = 0;
while (*s != 0) {
s++;
count++;
}
/*count++;*/
return count;
} |
the_stack_data/246451.c | /*
* Cyril DE CATHEU
* 08/31/2018
* The C Book. Exercise 2.10
* Implement Example 2.2 in order to answer questions found in exercise2.1011121314.md
*/
#include <stdio.h>
#include <stdlib.h>
#define BOILING 212 /* degrees Farenheit */
int main(){
float f_var;
double d_var;
/* long double weren't correctly managed on the Cygwin used */
long double l_d_var;
int i;
i=0;
printf("Fahrenheit to Centigrade\n");
while(i <= BOILING){
l_d_var = 5 * (i-32);
l_d_var = l_d_var/9;
d_var = l_d_var;
f_var = l_d_var;
/*Replace %Lf by %lf depending on the machine and the compiler used*/
printf("%d %f %f %Lf\n", i ,f_var, d_var, l_d_var);
i = i + 1;
}
exit(EXIT_SUCCESS);
}
|
the_stack_data/261317.c | #define MAXQUEUE 3
#include<stdbool.h>
#include<stdio.h>
#include<errno.h>
#include<string.h>
/*
void error(char s[])
{
throw runtime_error (s);
}
*/
/*
typedef char Item_type;
typedef bool Boolean_type;
typedef struct queue_tag{
int count;
int front;
int rear;
Item_type entry[MAXQUEUE];
} Queue_type;
void AddQueue(Item_type,Queue_type *);
void DeleteQueue(Item_type *,Queue_type *);
void Initialize(Queue_type *);
int Size(Queue_type *);
Boolean_type Empty(Queue_type *);
Boolean_type Full(Queue_type *);
void Initialize(Queue_type *queue_ptr)
{
queue_ptr->count = 0;
queue_ptr->front = 0;
queue_ptr->rear = -1;
}
void AddQueue(Item_type item, Queue_type *queue_ptr)
{
if(queue_ptr->count >=MAXQUEUE)
printf("Queue is full");
else{
queue_ptr->count++;
queue_ptr->rear = (queue_ptr+1)%MAXQUEUE;
queue_ptr->entry[queue_ptr->rear] = item;
}
}
void DeleteQueue(Item_type *item, Queue_type *queue_ptr)
{
if(queue_ptr->count <=0)
printf("\nThe queue is empty!");
else{
queue_ptr->count--;
*item = queue_ptr->entry[queue_ptr->front];
queue_ptr->front = (queue_ptr->front+1)%MAXQUEUE;
}
}
int Size(Queue_type *queue_ptr)
{
return queue_ptr->count;
}
Boolean_type Empty(Queue_type *queue_ptr)
{
return queue_ptr->count <=0;
}
Boolean_type Full(Queue_type *queue_ptr)
{
return queue_ptr->count >=MAXQUEUE;
}
*/
|
the_stack_data/854826.c | #include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main(int argc, char** argv)
{
srandom(time(0));
printf("random() - %i\n", random());
}
|
the_stack_data/1157169.c | int f(int a) {
return a + 1;
}
unsigned int f2(void) {
unsigned int c = 10;
return c;
}
|
the_stack_data/128130.c | #include <stdio.h>
int main(void)
{
char firstname[40];
char lastname[40];
printf("Your firstname\n");
scanf("%s",firstname);
printf("Your lastname\n");
scanf("%s",lastname);
printf("%s %s\n",firstname,lastname );
printf("%*d %*d\n",strlen(firstname),strlen(firstname),strlen(lastname),strlen(lastname));
printf("%s %s\n",firstname,lastname );
printf("%-*d %-*d\n",strlen(firstname),strlen(firstname),strlen(lastname),strlen(lastname));
return 0;
} |
the_stack_data/20481.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdint.h>
#define LINE_LENGTH 10000
#define WF_LENGTH 1019
#define PRE 256
#define POST 256
void importWaveform(char * line, uint16_t * wf);
void printWaveform(uint16_t * wf, uint16_t len);
void printWindow(uint16_t * wf, uint16_t len);
// find rising edge function:
// - inputs:
// - waveform: unsigned 16-bit integer
// - length of waveform: unsigned 16-bit integer
// - windowLen: moving window width, should be a power of 2 to make division
// easier
// - threshold: float, multiple of standard deviation
// - output: unsigned 16-bit integer, zero-suppressed waveform
// - return: length of the output
uint16_t findRisingEdge(uint16_t * wf, uint16_t len,
uint16_t windowLen, float threshold, uint16_t * output);
int main() {
FILE *fp = fopen("../liverpoolPulses.txt", "r");
if(fp == NULL) {
perror("Unable to open file!");
exit(1);
}
char line[LINE_LENGTH];
uint16_t wf[WF_LENGTH];
fgets(line, sizeof(line), fp);
importWaveform(line, wf);
printWaveform(wf, 20);
uint16_t output[WF_LENGTH];
int outputLen = findRisingEdge(wf, WF_LENGTH, 128, 4.0, output);
printf("outputLen %d\n", outputLen);
printWaveform(output, outputLen);
return 0;
}
void importWaveform(char * line, uint16_t * wf){
char * pch;
pch = strtok(line, " ");
int i = 0;
while ((pch != NULL) || (i == WF_LENGTH - 1)){
sscanf(pch, "%hu", &wf[i]);
i ++;
pch = strtok(NULL, " ");
}
}
void printWaveform(uint16_t * wf, uint16_t len){
for (uint16_t i = 0; i < len; ++i) {
printf("%d ", wf[i]);
}
printf("\n");
}
void printWindow(uint16_t *data, uint16_t len) {
for (uint16_t i = 0; i < len; ++i) {
if (data[i] != 0){
printf("%d: %d\n", i, data[i]);
}
}
}
uint16_t findRisingEdge(uint16_t * wf, uint16_t len,
uint16_t windowLen, float threshold, uint16_t * output) {
// have to be signed numbers so that the arithmetic below works correctly
int64_t ped = 0;
int64_t var = 0;
// calculate first ped and var
for (uint16_t i = 0; i < windowLen; i++)
ped += wf[i];
ped /= windowLen;
for (uint16_t i = 0; i < windowLen; i++)
var += (wf[i] - ped) * (wf[i] - ped);
var /= windowLen;
printf("ped %llu, var %llu\n", ped, var);
for (uint16_t i = windowLen; i < len; i++) {
int64_t oldped = ped;
int height = wf[i] - oldped;
// only find positive edge
if ((height * height > var * threshold * threshold) && (height >= 0)){
// check next 2 samples for positive gradient
if (i+2 >= len) { // just return 0 if at the end of data
return 0;
}
else {
if ((wf[i+2] > wf[i+1]) && (wf[i+1] > wf[i])) { // this is it!
uint16_t firstSample, lastSample;
if (i - PRE < 0)
firstSample = 0;
else
firstSample = i - PRE;
if (i + POST >= len)
lastSample = len;
else
lastSample = i + POST;
memcpy(output, wf + firstSample, (lastSample - firstSample) * sizeof(uint16_t));
return (lastSample - firstSample);
}
}
}
ped += (wf[i] - wf[i - windowLen]) / windowLen;
var += (wf[i] - wf[i - windowLen]) * (wf[i] + wf[i - windowLen] - ped - oldped) / windowLen;
/* printf("sample %d: y %d, ped %lld, var %lld\n", i, wf[i], ped, var); */
}
return 0;
}
|
the_stack_data/21709.c | #if (TK_MAJOR_VERSION == 3)
/*
* bltBell.c --
*
* Copyright 1993-1996 by AT&T Bell Laboratories.
* Permission to use, copy, modify, and distribute this software
* and its documentation for any purpose and without fee is hereby
* granted, provided that the above copyright notice appear in all
* copies and that both that the copyright notice and warranty
* disclaimer appear in supporting documentation, and that the
* names of AT&T Bell Laboratories any of their entities not be used
* in advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
*
* AT&T disclaims all warranties with regard to this software, including
* all implied warranties of merchantability and fitness. In no event
* shall AT&T be liable for any special, indirect or consequential
* damages or any damages whatsoever resulting from loss of use, data
* or profits, whether in an action of contract, negligence or other
* tortuous action, arising out of or in connection with the use or
* performance of this software.
*
*/
#include "bltInt.h"
#define BELL_VERSION "1.0 ($Id: bltBell.c,v 1.1.1.1 1998/08/21 05:59:11 chaffee Exp $)"
/*
*----------------------------------------------------------------------
*
* Blt_BellCmd --
*
* This procedure is invoked to process the "bell" Tcl command.
* See the user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
/* ARGSUSED */
static int
BellCmd(clientData, interp, argc, argv)
ClientData clientData; /* Main window associated with interpreter.*/
Tcl_Interp *interp; /* Current interpreter. */
int argc; /* Number of arguments. */
char **argv; /* Argument strings. */
{
Tk_Window tkwin = (Tk_Window)clientData;
int percent;
if (argc > 2) {
Tcl_AppendResult(interp, "wrong # args: should be \"",
argv[0], " ?volumePercent?\"", (char *)NULL);
return TCL_ERROR;
}
if (argc == 1) {
percent = 50; /* Default setting */
} else if (argc == 2) {
if (Tcl_GetInt(interp, argv[1], &percent) != TCL_OK) {
return TCL_ERROR;
}
if ((percent < -100) || (percent > 100)) {
Tcl_AppendResult(interp, "bad volume percentage value \"",
argv[1], "\"", (char *)NULL);
return TCL_ERROR;
}
}
XBell(Tk_Display(tkwin), percent);
return TCL_OK;
}
int
Blt_BellInit(interp)
Tcl_Interp *interp;
{
static Blt_CmdSpec cmdSpec = { "bell", BELL_VERSION, BellCmd, };
return (Blt_InitCmd(interp, &cmdSpec));
}
#endif /* TK_MAJOR_VERSION == 3 */
|
the_stack_data/37637903.c | /*
* minimal program to read out data from Corsair RMi and HXi series of PSUs
* tested on RM650i, RM750i, HX1000i
*
* Copyright (c) notaz, 2016
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the organization nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER 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.
*/
/*
* register list from SIV by Ray Hinchliffe
*
* left unimplemented:
* 3a fan mode
* 3b fan pwm
* 81 fan status
* f0 fan1 mode
*
* left unknown:
* 40: e6 d3 00 ... (15.6; const?)
* 44: 1a d2 00 ... ( 8.4; const?)
* 46: 2c f1 00 ... (75.0; const?)
* 4f: 46 00 ...
* 7a: 00 ...
* 7b: 00 ...
* 7d: 00 ...
* 7e: c0 00 ...
* c4: 01 00 ...
* d4: b9 bd eb fe 00 ... (32bit const?)
* d8: 02 00 ...
* d9: 00 ...
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <stdint.h>
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <errno.h>
#include <linux/hidraw.h>
static const uint16_t products[] = {
0x1c0a, /* RM650i */
0x1c0b, /* RM750i */
0x1c0c, /* RM850i */
/* 0x1c0d for RM1000i? */
0x1c04, /* HX650i */
0x1c05, /* HX750i */
0x1c06, /* HX850i */
0x1c07, /* HX1000i */
0x1c08, /* HX1200i */
};
static void dump(const uint8_t *buf, size_t size)
{
size_t i, j;
for (i = 0; i < size; i += 16) {
for (j = 0; j < 16; j++) {
if (i + j < size)
printf(" %02x", buf[i + j]);
else
fputs(" ", stdout);
}
fputs(" ", stdout);
for (j = 0; j < 16; j++) {
if (i + j < size) {
uint8_t c = buf[i + j];
printf("%c", 0x20 <= c && c <= 0x7f ? c : '.');
}
else
break;
}
puts("");
}
}
static void send_recv_cmd(int fd, uint8_t b0, uint8_t b1, uint8_t b2,
void *buf, size_t buf_size)
{
uint8_t buf_w[65], buf_r[64];
ssize_t ret;
memset(buf_w, 0, sizeof(buf_w));
buf_w[1] = b0;
buf_w[2] = b1;
buf_w[3] = b2;
ret = write(fd, buf_w, sizeof(buf_w));
if (ret != sizeof(buf_w)) {
fprintf(stderr, "write %zd/%zd: ", ret, sizeof(buf_w));
perror(NULL);
exit(1);
}
ret = read(fd, buf_r, sizeof(buf_r));
if (ret != sizeof(buf_r)) {
fprintf(stderr, "read %zd/%zd: ", ret, sizeof(buf_r));
perror(NULL);
if (ret > 0)
dump(buf_r, ret);
exit(1);
}
if (buf_r[0] != b0 || buf_r[1] != b1) {
fprintf(stderr, "unexpected response %02x %02x "
"to cmd %02x %02x %02x\n",
buf_r[0], buf_r[1], b0, b1, b2);
dump(buf_r, sizeof(buf_r));
exit(1);
}
if (buf != NULL && buf_size > 0) {
if (buf_size > sizeof(buf_r) - 2)
buf_size = sizeof(buf_r) - 2;
memcpy(buf, buf_r + 2, buf_size);
}
}
static void read_reg(int fd, uint8_t reg, void *buf, size_t buf_size)
{
send_recv_cmd(fd, 0x03, reg, 0x00, buf, buf_size);
}
static void read_reg16(int fd, uint8_t reg, uint16_t *v)
{
send_recv_cmd(fd, 0x03, reg, 0x00, v, sizeof(*v));
// FIXME: big endian host
}
static void read_reg32(int fd, uint8_t reg, uint32_t *v)
{
send_recv_cmd(fd, 0x03, reg, 0x00, v, sizeof(*v));
// FIXME: big endian host
}
static double mkv(uint16_t v16)
{
int p = (int)(int16_t)v16 >> 11;
int v = ((int)v16 << 21) >> 21;
return (double)v * pow(2.0, p);
}
static void print_std_reg(int fd, uint8_t reg, const char *fmt, ...)
{
uint16_t val;
va_list ap;
read_reg16(fd, reg, &val);
va_start(ap, fmt);
vprintf(fmt, ap);
printf("\t");
va_end(ap);
printf("%.2f\n", mkv(val));
}
static int try_open_device(const char *name, int report_errors)
{
struct hidraw_devinfo info;
int found = 0;
int i, ret, fd;
fd = open(name, O_RDWR);
if (fd == -1) {
if (report_errors) {
fprintf(stderr, "open %s: ", name);
perror(NULL);
}
return -1;
}
memset(&info, 0, sizeof(info));
ret = ioctl(fd, HIDIOCGRAWINFO, &info);
if (ret != 0) {
perror("HIDIOCGRAWINFO");
goto out;
}
if (info.vendor != 0x1b1c)
goto out;
for (i = 0; i < sizeof(products) / sizeof(products[0]); i++) {
if (info.product == products[i]) {
found = 1;
break;
}
}
out:
if (!found) {
if (report_errors)
fprintf(stderr, "unexpected device: %04hx:%04hx\n",
info.vendor, info.product);
close(fd);
fd = -1;
}
return fd;
}
int main(int argc, char *argv[])
{
int had_eacces = 0;
char name[63];
uint32_t v32;
uint8_t osel;
int i, fd;
if (argc > 1) {
if (argv[1][0] == '-' || argc != 2) {
fprintf(stderr, "usage:\n");
fprintf(stderr, "%s [/dev/hidrawN]\n", argv[0]);
return 1;
}
fd = try_open_device(argv[1], 1);
}
else {
for (i = 0; i < 16; i++) {
snprintf(name, sizeof(name), "/dev/hidraw%d", i);
fd = try_open_device(name, 0);
if (fd != -1)
break;
if (errno == EACCES)
had_eacces = 1;
}
if (fd == -1) {
fprintf(stderr, "No compatible devices found.\n");
if (had_eacces)
fprintf(stderr, "At least one device "
"could not be checked because "
"of lack of permissions for "
"/dev/hidraw*.\n");
}
}
if (fd == -1)
return 1;
name[sizeof(name) - 1] = 0;
send_recv_cmd(fd, 0xfe, 0x03, 0x00, name, sizeof(name) - 1);
printf("name\t%s\n", name);
read_reg(fd, 0x99, name, sizeof(name) - 1);
printf("vendor\t%s\n", name);
read_reg(fd, 0x9a, name, sizeof(name) - 1);
printf("product\t%s\n", name);
read_reg32(fd, 0xd1, &v32);
printf("powered_seconds\t%u\n", v32);
int days, hours, minutes, seconds;
seconds = v32 % 60; v32 /= 60;
minutes = v32 % 60; v32 /= 60;
hours = v32 % 24; v32 /= 24;
days = v32;
printf("powered_formatted\t%dd. %dh. %dm. %ds.\n", days, hours, minutes, seconds);
read_reg32(fd, 0xd2, &v32);
printf("uptime_seconds\t%u\n", v32);
seconds = v32 % 60; v32 /= 60;
minutes = v32 % 60; v32 /= 60;
hours = v32 % 24; v32 /= 24;
days = v32;
printf("uptime_formatted\t%dd. %dh. %dm. %ds.\n", days, hours, minutes, seconds);
print_std_reg(fd, 0x8d, "temp1");
print_std_reg(fd, 0x8e, "temp2");
print_std_reg(fd, 0x90, "fan_rpm");
print_std_reg(fd, 0x88, "supply_volts");
print_std_reg(fd, 0xee, "total_watts");
const char* output_names[] = {"12v", "5v", "3.3v"};
for (osel = 0; osel < 3; osel++) {
// reg0 write (output select)
send_recv_cmd(fd, 0x02, 0x00, osel, NULL, 0);
printf("output%u_name\t%s\n", osel, output_names[osel]);
print_std_reg(fd, 0x8b, "output%u_volts", osel);
print_std_reg(fd, 0x8c, "output%u_amps", osel);
print_std_reg(fd, 0x96, "output%u_watts", osel);
}
send_recv_cmd(fd, 0x02, 0x00, 0x00, NULL, 0);
close(fd);
return 0;
}
|
the_stack_data/11074215.c | /* (c) Anders Claesson 2013 */
#include <stdlib.h>
/* Determines whether the subword in v specified by m is order
* isomorphic to u; len is the length of u.
*/
int
ordiso(const long *u, const long *v, const long *m, long len)
{
register long i;
long *w = alloca(len*sizeof(*w));
/* Let w = v.m.u^{-1} */
for (i = 0; i < len; i++, u++, m++)
w[*u] = v[*m];
/* Return 1 if w is increasing, 0 otherwise */
for (; len > 1; len--, w++) {
if (*w > *(w+1))
return 0;
}
return 1;
}
|
the_stack_data/978246.c | //Calcula a diferença entre dois valores inseridos.
#include <stdio.h>
main(){
int idade1, idade2;
printf("Quantos anos voce tem? ");
scanf("%d", &idade1);
printf("Quantos anos tem seu pai? ");
scanf("%d", &idade2);
printf("Ele eh %d anos mais velho do que voce", (idade2 - idade1));
}
|
the_stack_data/50138470.c | // RUN: %layout_check %s
struct A
{
int a;
int x[4];
int c;
} x = {
.x = 2,
3, // x[1]
.c = 4
};
|
the_stack_data/1035585.c |
/* text version of maze 'mazefiles/binary/japan1997f.maz'
generated by mazetool (c) Peter Harrison 2018
o---o---o---o---o---o---o---o---o---o---o---o---o---o---o---o---o
| |
o o---o---o---o---o o---o---o---o---o o---o---o---o---o o
| | | |
o o o---o---o---o---o---o---o---o---o---o---o---o---o o o
| | | | | |
o o o o---o o---o---o---o---o---o---o o---o o o o
| | | | | | | | | |
o o o o o---o o---o---o---o---o o---o o o o o
| | | | | | | | | |
o o o o---o o---o o---o---o o---o o---o o o o
| | | | | | | | | |
o o o o o---o o---o o o---o o---o o o o o
| | | | | | | | | | |
o o o o o o---o o---o---o o---o o o o o o
| | | | | | | | | | |
o o o o---o o o---o o o---o o---o o o o o
| | | | | | | | | | | |
o o o o o o o o---o---o o---o o o o o o
| | | | | | | | | | | |
o o o o o---o o---o o o---o o---o o o o o
| | | | | | | | | | |
o o o o---o o---o o---o---o o---o o---o o o o
| | | | | | | | | |
o o o o o---o o---o---o---o---o o---o o o o o
| | | | | | | | | |
o o o o---o o---o---o---o---o---o---o o---o o o o
| | | | | | | |
o o o o---o---o---o---o---o---o---o---o---o---o---o o o
| | | | |
o o o---o---o---o---o---o---o---o---o---o---o---o---o---o o
| | |
o---o---o---o---o---o---o---o---o---o---o---o---o---o---o---o---o
*/
int japan1997f_maz[] ={
0x0E, 0x0A, 0x0A, 0x0A, 0x0A, 0x08, 0x0A, 0x0A, 0x0A, 0x0A, 0x08, 0x0A, 0x0A, 0x0A, 0x0A, 0x09,
0x0C, 0x0A, 0x0A, 0x0A, 0x0A, 0x02, 0x0A, 0x0A, 0x0A, 0x0A, 0x02, 0x0A, 0x0A, 0x0A, 0x09, 0x05,
0x05, 0x0C, 0x0A, 0x0A, 0x08, 0x0A, 0x0A, 0x08, 0x08, 0x0A, 0x0A, 0x08, 0x0A, 0x09, 0x05, 0x05,
0x05, 0x05, 0x0F, 0x0C, 0x03, 0x0C, 0x0A, 0x03, 0x06, 0x0A, 0x09, 0x06, 0x09, 0x05, 0x05, 0x05,
0x05, 0x05, 0x0C, 0x03, 0x0C, 0x03, 0x0C, 0x0A, 0x0A, 0x09, 0x06, 0x09, 0x06, 0x01, 0x05, 0x05,
0x05, 0x05, 0x05, 0x0C, 0x03, 0x0C, 0x02, 0x08, 0x09, 0x04, 0x09, 0x06, 0x09, 0x05, 0x04, 0x01,
0x05, 0x05, 0x05, 0x05, 0x0C, 0x03, 0x0C, 0x03, 0x06, 0x01, 0x06, 0x09, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x05, 0x05, 0x0C, 0x03, 0x0C, 0x09, 0x06, 0x09, 0x05, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x05, 0x05, 0x06, 0x09, 0x06, 0x01, 0x0C, 0x03, 0x05, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x05, 0x06, 0x09, 0x06, 0x09, 0x04, 0x03, 0x0C, 0x03, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x06, 0x09, 0x06, 0x09, 0x06, 0x03, 0x0C, 0x03, 0x0C, 0x03, 0x05, 0x04, 0x01,
0x05, 0x05, 0x04, 0x09, 0x06, 0x09, 0x06, 0x09, 0x0C, 0x03, 0x0C, 0x03, 0x0C, 0x01, 0x05, 0x05,
0x05, 0x05, 0x05, 0x06, 0x09, 0x06, 0x0A, 0x02, 0x02, 0x0A, 0x03, 0x0C, 0x03, 0x05, 0x05, 0x05,
0x05, 0x05, 0x06, 0x0A, 0x02, 0x0A, 0x0A, 0x0A, 0x0A, 0x08, 0x0A, 0x02, 0x0A, 0x03, 0x05, 0x05,
0x05, 0x06, 0x0A, 0x0A, 0x0A, 0x0A, 0x08, 0x0A, 0x0A, 0x02, 0x08, 0x0A, 0x0A, 0x0A, 0x03, 0x05,
0x06, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x02, 0x0A, 0x0A, 0x0A, 0x02, 0x0A, 0x0A, 0x0A, 0x0A, 0x03,
};
/* end of mazefile */
|
the_stack_data/104828711.c | #include<stdio.h>
int main()
{
int m,n;
int fz=1,fm=1,ans;
scanf("%d%d",&m,&n);
for (int i=0;i<n;i++)
{
fz*=(m-i);
}
for(int j=1;j<=n;j++)
{
fm*=j;
}
ans=fz/fm;
printf("%d",ans);
return 0;
} |
the_stack_data/142621.c | #include "stdio.h"
long long a[5];
long long i = 2;
int main() {
a[i] = 33;
printf("%lld\n", a[i]);
return 0;
}
|
the_stack_data/179829593.c | /*
* Solution to Part 1 & Part 2 of https://adventofcode.com/2018/day/3
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define testing false // 'true' loads a smaller test file, and sends some trace to stdout.
#define fabric_width 1000
#define fabric_height 1000
int main(void)
{
FILE * fp;
int claim=0;
int from_left=0;
int from_top=0;
int width=0;
int height=0;
int i=0;
int j=0;
int two_or_more=0;
int uncontested=false;
int *fabric = (int *) calloc(fabric_width * fabric_height, sizeof(int)); // int fabric[fabric_width][fabric_height];
if (testing)
fp = fopen("test.txt", "r");
else fp = fopen("input.txt", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
while (fscanf(fp, "#%d @ %d,%d: %dx%d\n",&claim,&from_left,&from_top,&width,&height) != EOF)
{
if (testing)
printf("claim=%d from_left=%d from_top=%d width=%d height=%d\n",claim,from_left,from_top,width,height);
// Check the claim doesn't go off the edge of the fabric.
if (fabric_width <= (from_left+width)
|| fabric_height <= (from_top+height))
exit(EXIT_FAILURE);
for (i=from_top;i<=(from_top+height-1);i++)
for (j=from_left;j<=(from_left+width-1);j++)
{
*(fabric + i*fabric_height + j)=*(fabric + i*fabric_height + j)+1; // fabric[j][i]++;
if (*(fabric + i*fabric_height + j) ==2) // if (fabric[j][i] ==2)
two_or_more++;
}
}
if (testing)
{
/* Print out the fabric */
for (i=0;i<=10;i++)
{
for (j=0;j<=10;j++)
if (*(fabric + i*fabric_height + j) == 0) // (fabric[j][i]==0)
printf("0");
else printf("%d", *(fabric + i*fabric_height + j)); // printf("%d",fabric[j][i]);
printf("\n");
}
}
printf("Two or more=%d\n",two_or_more);
/* Look for an unchallenged claim */
rewind(fp);
while (fscanf(fp, "#%d @ %d,%d: %dx%d\n",&claim,&from_left,&from_top,&width,&height) != EOF)
{
// Assume the claim is uncontested at start.
uncontested=true;
for (i=from_top;i<=(from_top+height-1);i++)
for (j=from_left;j<=(from_left+width-1);j++)
if (*(fabric + i*fabric_height + j) !=1)
uncontested=false;
if (uncontested)
printf("uncontested claim=%d from_left=%d from_top=%d width=%d height=%d\n",claim,from_left,from_top,width,height);
}
fclose(fp);
return 0;
} |
the_stack_data/225143117.c | // This program prints "My First C Programme"
#include <stdio.h>
#include <math.h>
int main()
{
printf("My First C Programme\n");
}
|
the_stack_data/218892406.c | typedef struct { int re,im; } complex;
int pof(int n, complex IN[3][n]) {
complex (*a)[n] = (complex(*)[n])&IN[2];
return (*a)[3].im;
}
|
the_stack_data/73612.c | void main()
{
int x,y,z;
__CPROVER_assume(x>=0);
__CPROVER_assume(-20<=z && z<=-1);
while(x>0)
{
if(y) x--;
else x += z;
assert(z>=-20);
assert(x>=-19);
assert(x>=z);
}
assert(z>=-20);
assert(x>=-20);
assert(x>=z); //can only be verified if relation between x and z known
}
|
the_stack_data/54154.c | /* Exercise 1-3. Create the temperature conversion program (°F to °C) to print a heading above the table.*/
#include <stdio.h>
#define START 0
#define END 300
#define STEP 20
int main()
{
int i;
int temperature;
printf("%s\n", "----------------------------------------");
printf("Temperature Conversion from F to C\n");
printf("%s\n", "----------------------------------------");
printf("%3s\t%6s\n", "F", "C");
printf("%s\n", "----------------------------------------");
for(i = START; i <= END; i = i + STEP)
{
temperature = 5 * (i - 32) / 9;
printf("%3d\t%6d\n", i, temperature);
}
return 0;
}
|
the_stack_data/12636664.c | #include <stdio.h>
#include <stdlib.h>
int main() {
int n;
printf("Give a positive integer:\n");
if (scanf_s("%d", &n) != 1) {
printf("Wrong input!");
exit(1);
}
if (n <= 0) {
printf("Wrong input!");
exit(1);
}
while(n>=0) {
printf("%d\n", n);
n--;
}
return 0;
} |
the_stack_data/1105072.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <unistd.h>
#define MYPORT 3491
#define BACKLOG 5
int main(int argc, char const *argv[])
{
int sockfd, newfd, nbytes;
char buf[1024];
struct sockaddr_in srvaddr;
struct sockaddr_in cliaddr;
int sin_size;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket error");
exit(1);
}
bzero(&srvaddr, sizeof(srvaddr));
srvaddr.sin_family = AF_INET;
srvaddr.sin_port = htons(MYPORT);
if ((bind(sockfd, (struct sockaddr *)&srvaddr, sizeof(srvaddr))) == -1) {
perror("bind error");
exit(1);
}
if ((listen(sockfd, BACKLOG)) == -1) {
perror("listen error");
exit(1);
}
printf("%s\n", "Wait connect");
for (;;) {
sin_size = sizeof(struct sockaddr_in);
if ((newfd = accept(sockfd, (struct sockaddr *) &cliaddr, (socklen_t *) &sin_size)) == -1) {
perror("accept error");
continue;
}
printf("server: got connection from %s \n", inet_ntoa(cliaddr.sin_addr));
if (write(newfd, "Hello, World\n", 12) == -1) {
perror("write error");
}
if ((nbytes = read(newfd, buf, 500)) == -1) {
perror("read error");
exit(1);
}
buf[nbytes] = '\0';
printf("read: %s\n", buf);
close(newfd);
}
close(sockfd);
return 0;
}
|
the_stack_data/93354.c | /*-------------------------------------------------------------------------
*
* port.c--
* Linux-specific routines
*
* Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* $Header: /usr/local/cvsroot/postgres95/src/backend/port/dgux/port.c,v 1.1 1996/07/25 20:44:00 scrappy Exp $
*
*-------------------------------------------------------------------------
*/
|
the_stack_data/19048.c | /* Taxonomy Classification: 0000020000000000000000 */
/*
* WRITE/READ 0 write
* WHICH BOUND 0 upper
* DATA TYPE 0 char
* MEMORY LOCATION 0 stack
* SCOPE 0 same
* CONTAINER 2 struct
* POINTER 0 no
* INDEX COMPLEXITY 0 constant
* ADDRESS COMPLEXITY 0 constant
* LENGTH COMPLEXITY 0 N/A
* ADDRESS ALIAS 0 none
* INDEX ALIAS 0 none
* LOCAL CONTROL FLOW 0 none
* SECONDARY CONTROL FLOW 0 none
* LOOP STRUCTURE 0 no
* LOOP COMPLEXITY 0 N/A
* ASYNCHRONY 0 no
* TAINT 0 no
* RUNTIME ENV. DEPENDENCE 0 no
* MAGNITUDE 0 no overflow
* CONTINUOUS/DISCRETE 0 discrete
* SIGNEDNESS 0 no
*/
/*
Copyright 2004 M.I.T.
Permission is hereby granted, without written agreement or royalty fee, to use,
copy, modify, and distribute this software and its documentation for any
purpose, provided that the above copyright notice and the following three
paragraphs appear in all copies of this software.
IN NO EVENT SHALL M.I.T. BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE
AND ITS DOCUMENTATION, EVEN IF M.I.T. HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMANGE.
M.I.T. SPECIFICALLY DISCLAIMS ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO
THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND M.I.T. HAS NO OBLIGATION TO
PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
typedef struct
{
char buf[10];
} my_struct;
int main(int argc, char *argv[])
{
my_struct s;
/* OK */
s.buf[9] = 'A';
return 0;
}
|
the_stack_data/397623.c | #include <stdio.h>
int one = 1;
char ten = 10;
int main() {
int inputA = 0;
char inputB = 0;
scanf("%d %c", &inputA, &inputB);
while (one < ten) {
printf("%d %c\n", one, one + '0');
if (one < 5) {
printf("Still smaller than five\n");
}
printf("%d\n", one * ten / 3 + 2 - 1);
if (one % 2 == 0) {
printf("\tEven\n");
} else {
printf("\tOdd\n");
}
one = one + 1;
}
printf("%d %c\n", inputA, inputB);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.