language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#ifndef DEF_UNIV_TYPE_OPS
#define DEF_UNIV_TYPE_OPS
// UnivType operations
#include "UnivType.h"
// C++ operator overload
UnivType operator+(const UnivType& x, const UnivType& y);
UnivType operator-(const UnivType& x, const UnivType& y);
UnivType operator*(const UnivType& x, const UnivType& y);
UnivType operator/(const UnivType& x, const UnivType& y);
UnivType operator%(const UnivType& x, const UnivType& y);
UnivType operator&(const UnivType& x, const UnivType& y);
UnivType operator|(const UnivType& x, const UnivType& y);
UnivType operator^(const UnivType& x, const UnivType& y);
UnivType operator&&(const UnivType& x, const UnivType& y);
UnivType operator||(const UnivType& x, const UnivType& y);
UnivType operator!(const UnivType& x);
UnivType operator~(const UnivType& x);
UnivType operator==(const UnivType& x, const UnivType& y);
UnivType operator!=(const UnivType& x, const UnivType& y);
UnivType operator>(const UnivType& x, const UnivType& y);
UnivType operator<(const UnivType& x, const UnivType& y);
UnivType operator>=(const UnivType& x, const UnivType& y);
UnivType operator<=(const UnivType& x, const UnivType& y);
// Arithmetic operations
void AopPlus(UnivType& result, const UnivType& x, const UnivType& y);
void AopMinus(UnivType& result, const UnivType& x, const UnivType& y);
void AopMult(UnivType& result, const UnivType& x, const UnivType& y);
void AopDiv(UnivType& result, const UnivType& x, const UnivType& y);
void AopMod(UnivType& result, const UnivType& x, const UnivType& y);
void AopDotMult(UnivType& result, const UnivType& x, const UnivType& y);
void AopDotDiv(UnivType& result, const UnivType& x, const UnivType& y);
void AopBitAnd(UnivType& result, const UnivType& x, const UnivType& y);
void AopBitOr(UnivType& result, const UnivType& x, const UnivType& y);
void AopBitXor(UnivType& result, const UnivType& x, const UnivType& y);
void AopBitNot(UnivType& result, const UnivType& x);
void AopLogicalAnd(UnivType& result, const UnivType& x, const UnivType& y);
void AopLogicalOr(UnivType& result, const UnivType& x, const UnivType& y);
void AopLogicalXor(UnivType& result, const UnivType& x, const UnivType& y);
void AopLogicalNot(UnivType& result, const UnivType& x);
void AopEqual(UnivType& result, const UnivType& x, const UnivType& y);
void AopNotEqual(UnivType& result, const UnivType& x, const UnivType& y);
void AopLarge(UnivType& result, const UnivType& x, const UnivType& y);
void AopSmall(UnivType& result, const UnivType& x, const UnivType& y);
void AopELarge(UnivType& result, const UnivType& x, const UnivType& y);
void AopESmall(UnivType& result, const UnivType& x, const UnivType& y);
void AopPower(UnivType& result, const UnivType& x, const UnivType& y);
void AopDotPower(UnivType& result, const UnivType& x, const UnivType& y);
void AopUnaryMinus(UnivType& result, const UnivType& x);
void AopComplexConj(UnivType& result, const UnivType& x);
void AopSeries(UnivType& result, const UnivType& begin, const UnivType& end);
void AopSeries(UnivType& result, const UnivType& begin, const UnivType& delta, const UnivType& end);
void AopCatRow(UnivType& result, UnivType** pArgs, int nArgs, bool isConstRef);
void AopCatCol(UnivType& result, UnivType** pArgs, int nArgs, bool isConstRef);
void AopCatPartialRef(UnivType& result, UnivType** pArgs, int nArgs);
void AopArraySize(UnivType& result, UnivType& array);
void AopArraySize(UnivType& result, UnivType& array, int nDim, bool isVectorSize);
void AopSubsetAccess(UnivType& result, UnivType& subset, const char *pVariableName);
void AopIf(UnivType& result, const UnivType& cond, UnivType& arg0, UnivType& arg1, bool isConstRef);
void AopCond(UnivType& result, UnivType** pArgs, int nArgs, bool isConstRef);
void AopSwitch(UnivType& result, UnivType** pArgs, int nArgs, bool isConstRef);
// some handy functions for operations of UnivType
typedef void (*ScalarBinaryOperations)(UnivType& result, const UnivType& x, const UnivType& y);
typedef void (*ScalarUnaryOperations)(UnivType& result, const UnivType& x);
void ElementOperationScalarAndMatrix(UnivType& result, const UnivType& x, const UnivType& y, ScalarBinaryOperations ScalarOp);
void ElementOperationUnaryMatrix(UnivType& result, const UnivType& x, ScalarUnaryOperations ScalarOp);
#endif
|
C
|
#include "my_malloc.h"
/* You *MUST* use this macro when calling my_sbrk to allocate the
* appropriate size. Failure to do so may result in an incorrect
* grading!
*/
#define SBRK_SIZE 2048
/* Please use this value as your canary! */
#define CANARY 0x2110CAFE
/* If you want to use debugging printouts, it is HIGHLY recommended
* to use this macro or something similar. If you produce output from
* your code then you may receive a 20 point deduction. You have been
* warned.
*/
#ifdef DEBUG
#define DEBUG_PRINT(x) printf x
#else
#define DEBUG_PRINT(x)
#endif
/* our freelist structure - this is where the current freelist of
* blocks will be maintained. failure to maintain the list inside
* of this structure will result in no credit, as the grader will
* expect it to be maintained here.
* Technically this should be declared static for the same reasons
* as above, but DO NOT CHANGE the way this structure is declared
* or it will break the autograder.
*/
metadata_t* freelist;
void* my_malloc(size_t size)
{
if (size == 0) {
return NULL;
}
int block = size + sizeof(metadata_t) + 2 * sizeof(int);
if (block > SBRK_SIZE) {
ERRNO = SINGLE_REQUEST_TOO_LARGE;
return NULL;
}
metadata_t* current = freelist;
metadata_t* tmp = current;
metadata_t* prev = freelist;
//loop through freelist
while(current) {
prev = current;
//check freelist for a big enough block
if (current->block_size >= block) {
current = (metadata_t*) ((char*)current + block);
current->block_size = prev->block_size - block;
//check if when splitting, there is room for another block to malloc
if (current->block_size < sizeof(metadata_t) + 2 * sizeof(int) + 1) {
//set canaries and metadata
tmp->block_size = block + current->block_size;
tmp->request_size = size;
int* cp = (int*)((char*)tmp + sizeof(metadata_t));
*cp = CANARY;
int* cp2 = (int *) ((char *)tmp + sizeof(int) + sizeof(metadata_t) + size);
*cp2 = CANARY;
ERRNO = NO_ERROR;
freelist = freelist->next;
tmp->next = NULL;
tmp->prev = NULL;
return (void*)((char*)tmp + sizeof(metadata_t) + sizeof(int));
}
// if the free block previous is null, then set the freelist to the current
if (prev -> prev == NULL) {
current->next = freelist->next;
if (freelist->next != NULL) {
freelist->next->prev = current;
}
freelist = current;
freelist->prev = NULL;
} else { //set the previous and next of the new free block
prev->prev->next = current;
prev->next = current -> next;
current->prev = prev->prev;
}
//set canaries and tmp to give to user
tmp->block_size = block;
tmp->request_size = size;
int* cp = (int*)((char*)tmp + sizeof(metadata_t));
*cp = CANARY;
int* cp2 = (int *) ((char *)tmp + sizeof(int) + sizeof(metadata_t) + size);
*cp2 = CANARY;
ERRNO = NO_ERROR;
return (void*)((char*)tmp + sizeof(metadata_t) + sizeof(int));
}
current = current->next;
tmp = current;
}
//create a new block
metadata_t* current2 = (metadata_t*) my_sbrk(SBRK_SIZE);
if (current2 == NULL) {
ERRNO = OUT_OF_MEMORY;
return NULL;
}
tmp = current2;
current2 = (metadata_t*)((char*)tmp + block);
current2->block_size = SBRK_SIZE - block;
current2->request_size = 0;
current2->prev = NULL;
current2->next = NULL;
//set the new free block
if (freelist == NULL) {
freelist = current2;
} else if (freelist -> block_size == 0) {
freelist = current2;
} else {
prev -> next = current2;
current2 -> prev = prev;
}
//set canries and temp to give to user
tmp->block_size = block;
tmp->request_size = size;
tmp->prev = NULL;
tmp->next = NULL;
int* cp = (int*)((char*)tmp + sizeof(metadata_t));
*cp = CANARY;
int* cp2 = (int *) ((char *)tmp + sizeof(int) + sizeof(metadata_t) + size);
*cp2 = CANARY;
ERRNO = NO_ERROR;
return (void*)((char*)tmp + sizeof(metadata_t) + sizeof(int));
}
void my_free(void* ptr)
{
if (ptr == NULL) {
return;
}
// variables to see if memory addresses are consecutive
int l = 0;
int r = 0;
//freeingblock is the pointer to freed block
metadata_t* freeingBlock = (metadata_t*)((char*)ptr - (sizeof(int) + sizeof(metadata_t)));
//check if canaries are corrupted
int* cp = (int*) ((char*) freeingBlock + sizeof(metadata_t));
int* cp2 = (int*) ((char*) freeingBlock + sizeof(metadata_t) + sizeof(int) + freeingBlock->request_size);
if (*cp != CANARY) {
ERRNO = CANARY_CORRUPTED;
return;
} else if (*cp2 != CANARY) {
ERRNO = CANARY_CORRUPTED;
return;
}
metadata_t* leftFree = freelist;
metadata_t* rightFree = freelist;
//find the left consecutive block
while(leftFree && !l) {
if((metadata_t*)((char*) leftFree + leftFree->block_size) == freeingBlock) {
l = 1;
}
if (!l) {
leftFree = leftFree->next;
}
}
//find the right consecutive block
while(rightFree && !r) {
if ((metadata_t*)((char*) freeingBlock + freeingBlock->block_size) == rightFree) {
r = 1;
}
if (!r) {
rightFree = rightFree->next;
}
}
//merge left and right block with freeing block
if (l && r) {
leftFree->block_size = leftFree->block_size + freeingBlock->block_size + rightFree->block_size;
if (rightFree->prev != NULL) {
rightFree->prev->next = rightFree->next;
}
if (rightFree->next != NULL) {
rightFree->next->prev = rightFree->prev;
}
rightFree = NULL;
freeingBlock = leftFree;
freeingBlock -> request_size = 0;
} else if (l) { //merge left block with freeing block
leftFree->block_size = leftFree->block_size + freeingBlock->block_size;
freeingBlock = leftFree;
} else if (r) {
//merge freeing block with right block
freeingBlock->block_size = freeingBlock->block_size + rightFree->block_size;
freeingBlock->next = rightFree->next;
if (freeingBlock->next != NULL) {
freeingBlock->next->prev = freeingBlock;
}
freeingBlock->prev = rightFree->prev;
if (rightFree->prev != NULL) {
rightFree->prev->next = freeingBlock;
}
freeingBlock->request_size = 0;
if (rightFree == freelist) {
freelist = freeingBlock;
freelist->prev = NULL;
}
} else {
// free block with no left and right consecutive blocks
if (freelist->block_size == 0) {
freelist = freeingBlock;
} else {
freeingBlock->next = freelist;
freelist->prev = freeingBlock;
freeingBlock->request_size = 0;
freelist = freeingBlock;
}
}
}
|
C
|
#include<stdio.h>
struct vivek
{
int n1;
int n2;
int ans;
};
int main()
{
int t,i;
printf("enter the total test cases:\n");
scanf("%d",&t);
struct vivek a[t];
for(i=0;i<t;i++)
{
scanf("%d %d",&a[i].n1,&a[i].n2);
a[i].ans=a[i].n1+a[i].n2;
}
printf("\n\n");
for(i=0;i<t;i++)
{
printf("%d\n",a[i].ans);\
}
}
|
C
|
#include<stdio.h>
int parent(int i);
int left(int i);
int right(int i);
void max_heapify(int A[],int i, int n);//maintain max heap property => parentvalue > childvalue
void build_max_heap(int A[],int n);
void heapsort(int A[],int n);
int main(void){
int i;
int A[10] = {4, 1, 3, 2, 16, 9, 10, 14, 8, 7 };
for(i = 0; i <= 9; i++) printf(" %d", A[i]);
printf("\n");
heap_sort(A, 9);
for(i = 0; i<= 9; i++) printf(" %d", A[i]);
printf("\n");
return 0;
}
int parent(int i){
return (int)((i-1)/2);
}
int left(int i){
return 2 * i + 1;
}
int right(int i){
return 2 * i + 2;
}
void max_heapify(int A[],int i, int n){
int l, r, largest, tmp;
l = left(i);
r = right(i);
if(l <= n && A[l] > A[i]){
largest = l;
}
else{
largest = i;
}
if (r <= n && A[r] > A[largest] ){
largest = r;
}
if (largest != i){
tmp = A[i];
A[i] = A[largest];
A[largest] = tmp;
max_heapify(A, largest, n);
}
}
void build_max_heap(int A[], int n){
int i;
for(i = parent(n); i >= 0; i--) max_heapify(A, i, n);
}
void heapsort( int A, int n){
build_max_heap(A, n);
int i;
int tmp;
for(i = n; i >= 1; i--){
tmp = A[0];
A[0] = A[i];
A[i] = tmp;
max_heapify(A, 0, i - 1);
}
}
|
C
|
#include <sys/mman.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#define SC_LENGTH 1024*1024
int debug_enabled = 0;
void debug(char *fmt, ...) {
va_list ap;
if (!debug_enabled)
return;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
}
int main(int argc, char **argv) {
void *code;
int r, total = 0;
int fd = STDIN_FILENO;
/* Setup the environment */
debug_enabled = (getenv("DEBUG") != NULL) ? 1 : 0;
code = mmap(NULL, SC_LENGTH, PROT_READ|PROT_WRITE|PROT_EXEC,
MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
if (code == MAP_FAILED) {
fprintf(stderr, "Failed to allocate memory for mapping.\n");
return 1;
}
debug("Allocated 0x%08x bytes at %p. Send shellcode now.\n", SC_LENGTH, code);
/* Check if we should read a file.
* Yes, we could just mmap this file, but this has more code commonality.
*/
if (argc > 1 && strcmp("-", argv[1])) {
fd = open(argv[1], O_RDONLY);
if (fd == -1) {
fprintf(stderr, "Failed to open shellcode file (%s): %s\n",
argv[1], strerror(errno));
return 1;
}
}
/* Read shellcode */
while (1) {
r = read(fd, code + total, SC_LENGTH - total);
if (r <= 0) {
break;
}
total += r;
}
if (!total) {
debug("No shellcode read. Aborting.\n");
return 1;
}
/* Run shellcode */
debug("Read 0x%08x bytes. Executing.\n", total);
((void(*)())code)();
return 0;
}
|
C
|
/**
* @file main.c
* @author Shreya Chakraborty
* @brief Main task which spawns the other threads
* @version 0.1
* @date 2019-03-16
*
* @copyright Copyright (c) 2019
*
*/
#include "includes.h"
#include "main.h"
#include "logger.h"
#include "temp.h"
#include "socket.h"
#include "light.h"
#include "bist.h"
#include "logger.h"
#include "bbgled.h"
#include "mysignal.h"
#include "bist.h"
#include "heartbeat.h"
pthread_t threads[MAX_TASKS] = {0};
int thread_flag[MAX_TASKS] = {0};
//thread entry functions
void* (*ThreadEntryFunction[MAX_TASKS]) (void*) =
{
bist_task,
logger_task,
light_task,
temp_task,
socket_task
};
const char * moduleIdName[MAX_TASKS+1] = {
"BIST_TASK",
"LOGGER_TASK",
"TEMP_TASK",
"LIGHT_TASK",
"SOCKET_TASK",
"MAIN_TASK",
};
void *threadParamArgs[MAX_TASKS] = {0};
#ifndef TEST_MODE
int main(int argc , char **argv){
int rc;
signal(SIGINT,signal_handler);
logger_queue_init();
LOG_INFO(MAIN_TASK, "-----Project1 started main thread------");
if (argc < 2)
{
PRINTLOGCONSOLE("Command line Arg Error: USAGE <LOG FILE NAME>");
GREENLEDOFF();
REDLEDON();
exit(EXIT_FAILURE);
}
struct loggerTask_param loggerParam = {
.filename = argv[1],
.loglevel = LOG_DEBUG
};
if(argc == 3){
loggerParam.loglevel = atoi(argv[2]);
}
threadParamArgs[LOGGER_TASK] = (void*)&loggerParam;
//creating all threads except the bist for tasks
for(int i = 1; i < MAX_TASKS; i++)
{
rc = pthread_create(&threads[i],NULL,ThreadEntryFunction[i], threadParamArgs[i]);
if(rc)
{
PRINT("pthread_create for thread %s failed\n", (char*)ThreadEntryFunction[i]);
GREENLEDOFF();
REDLEDON();
exit(EXIT_FAILURE);
}
else
{
thread_flag[i]=1;
PRINT("%s thread created\n",moduleIdName[i]);
}
}
LOG_INFO(MAIN_TASK, "Threads spawned from the main");
//Creating bist thread
rc = pthread_create(&threads[BIST_TASK],NULL,ThreadEntryFunction[BIST_TASK], threadParamArgs[BIST_TASK]);
if(rc)
{
PRINT("pthread_create for thread %s failed\n", (char*)ThreadEntryFunction[0]);
GREENLEDOFF();
REDLEDON();
exit(EXIT_FAILURE);
}
else
{
thread_flag[0]=1;
PRINT("%s thread created\n",moduleIdName[0]);
}
//joing only the bist thread initially to do the built in selt tests
rc = pthread_join(threads[BIST_TASK],NULL);
if(rc)
{
PRINTLOGCONSOLE("pthread_join for thread %s failed\n", (char*)ThreadEntryFunction[0]);
exit(EXIT_FAILURE);
}
PostBistOkResult(); //if bist has been successful then post semaphores to the rest of the waiting threads
if(CheckBistResult()) // check if test is successful before joining other threads
{
LOG_INFO(MAIN_TASK,"Built in Self Test Result - Pass");
GREENLEDON();
REDLEDOFF();
startHearbeatCheck();// when bist return val is 1 start heartbeat check
}
else
{
LOG_INFO(MAIN_TASK,"Built in Self Test Result - Fail");
REDLEDON();
GREENLEDOFF();
}
//joining other threads
for(int i = 2; i < MAX_TASKS; i++)
{
rc = pthread_join(threads[i],NULL);
if(rc)
{
PRINTLOGCONSOLE("pthread_join for thread %s failed\n", (char*)ThreadEntryFunction[i]);
GREENLEDOFF();
REDLEDON();
exit(EXIT_FAILURE);
}
}
kill_logger_thread();
//all tasks have exited. only then exit the logger task to make sure we have all logs
rc = pthread_join(threads[LOGGER_TASK],NULL);
if(rc)
{
PRINTLOGCONSOLE("pthread_join for thread %s failed\n", (char*)ThreadEntryFunction[LOGGER_TASK]);
GREENLEDOFF();
REDLEDON();
exit(EXIT_FAILURE);
}
PRINT("******Program Clean Exit******\n");
GREENLEDOFF();
return 0;
}
#endif
|
C
|
/*
* udptunnel : Lightweight TCP over UDP Tunneling
*
* Copyright (C) 2014 Jingyu jingyu.niu@gmail.com
*
* 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 <string.h>
#include <stdlib.h>
#include <signal.h>
#include <assert.h>
#include <getopt.h>
#include "config.h"
#if defined(_WIN32) || defined(_WIN64)
#include "socket.h"
#endif
#include "log.h"
#include "tunnel.h"
static int mode;
static char *host; /* local udp or tcp server address */
static char *port;
static char *tunnel_host; /* tunnel server address */
static char *tunnel_port;
static char *remote_host; /* remote address */
static char *remote_port;
static char *acl;
#ifdef _DEBUG
static int log_level = UDPTUNNEL_LOG_DEBUG;
#else
static int log_level = UDPTUNNEL_LOG_INFO;
#endif
static Tunnel *t;
static void usage()
{
printf("usage: udptunnel -s [host:]port [-a acl]|[-d acl] ...\n");
printf(" or: udptunnel -c [host:]port -p host:port -t host:port\n");
printf("\n"
" Server options:\n"
" -s server mode. server host and port\n"
" -a allowed source and dest\n"
" src_ip,dest_ip,dest_port,allow|deny\n"
" any ip is 0.0.0.0, any port is 0"
"\n"
" Client options:\n"
" -c client mode. local TCP server host and port\n"
" -t tunnel server host and port\n"
" -r remote host and port\n"
"\n"
" Common options:\n"
" -v verbose level, 0-3, default is 1\n"
" 0 - Error, 1 - Warning, 2 - Info, 3 - Debug\n"
" -h show this help and exit\n"
"\n");
}
static void parse_addr(char *addr, char **host, char **port)
{
char *p;
assert(addr && host && port);
p = strchr(addr, ':');
if (p) {
*p++ = 0;
*host = *addr ? addr : NULL;
*port = *p ? p : NULL;
} else {
*host = NULL;
*port = addr;
}
}
static void parse_args(int argc, char *argv[])
{
int opt;
static struct option long_options[] = {
{"server", required_argument, 0, 's'},
{"acl", required_argument, 0, 'a'},
{"client", required_argument, 0, 'c'},
{"tunnel", required_argument, 0, 't'},
{"remote", required_argument, 0, 'r'},
{"verbose", required_argument, 0, 'v'},
{"help", no_argument, 0, 'h'},
};
while ((opt = getopt_long(argc, argv, "s:a:c:t:r:v:h", long_options, NULL))
!= -1) {
switch (opt) {
case 's':
mode = 's';
parse_addr(optarg, &host, &port);
break;
case 'a':
acl = optarg;
break;
case 'c':
mode = 'c';
parse_addr(optarg, &host, &port);
break;
case 't':
parse_addr(optarg, &tunnel_host, &tunnel_port);
break;
case 'r':
parse_addr(optarg, &remote_host, &remote_port);
break;
case 'v':
log_level = atoi(optarg);
break;
case 'h':
usage();
exit(0);
break;
case '?':
usage();
exit(1);
break;
case ':':
usage();
exit(1);
break;
}
}
if (mode == 0) {
printf("Tunnel mode option must be provided by -s or -c.\n\n");
usage();
exit(1);
}
if (mode == 's' && !port) {
printf("Tunnel server option missing argument.\n\n");
usage();
exit(1);
}
if (mode == 'c') {
if (!port) {
printf("Tunnel client option missing argument.\n\n");
usage();
exit(1);
}
if (!tunnel_host || !tunnel_port) {
printf("Missing tunnel server address option for client mode.\n\n");
usage();
exit(1);
}
if (!remote_host || !remote_port) {
printf("Missing remote address option for client mode.\n\n");
usage();
exit(1);
}
}
}
static void stop(int UNUSED(sig) )
{
tunnel_stop(t);
}
int main(int argc, char *argv[])
{
#if defined(_WIN32) || defined(_WIN64)
WSADATA wsa_data;
if (WSAStartup(MAKEWORD(2,0), &wsa_data) != 0)
return -1;
#endif
parse_args(argc, argv);
utlog_set_level(log_level);
signal(SIGINT, stop);
signal(SIGTERM, stop);
if (mode == 's')
t = tunnel_create_server(host, port, acl);
else
t = tunnel_create_client(host, port, tunnel_host, tunnel_port,
remote_host, remote_port);
if (!t)
return -1;
tunnel_run(t);
tunnel_close(t);
#if defined(_WIN32) || defined(_WIN64)
WSACleanup();
#endif
}
|
C
|
/**
Read Stata version 6.0 and 5.0 .dta files, write version 6.0.
(c) 1999, 2000 Thomas Lumley.
The format of Stata files is documented under 'file formats'
in the Stata manual.
This code currently does not make use of the print format or value
label information in a .dta file. It cannot handle files with 'int'
'float' or 'double' that differ from IEEE 4-byte integer, 4-byte
real and 8-byte real respectively: it's not clear whether such files
can exist.
Versions of Stata before 4.0 used different file formats.
**/
#include "R.h"
#include "Rinternals.h"
#include <stdio.h>
/** R 1.2 compatibility definitions **/
#if R_VERSION < R_Version(1, 2, 0)
# define STRING_ELT(x,i) (STRING(x)[i])
# define VECTOR_ELT(x,i) (VECTOR(x)[i])
# define SET_STRING_ELT(x,i,v) (STRING(x)[i]=(v))
# define SET_VECTOR_ELT(x,i,v) (VECTOR(x)[i]=(v))
#endif
/* handling endianess*/
#define LOHI 1
#define HILO 2
#define NATIVE_ENDIAN 0
/* Stata format constants */
#define STATA_FLOAT 'f'
#define STATA_DOUBLE 'd'
#define STATA_INT 'l'
#define STATA_SHORTINT 'i'
#define STATA_BYTE 'b'
#define STATA_STRINGOFFSET 0x7f
#define STATA_BYTE_NA 127
#define STATA_SHORTINT_NA 32767
#define STATA_INT_NA 2147483647
static double STATA_FLOAT_NA;
static double STATA_DOUBLE_NA;
static int endian,stata_endian;
/** these are not portable, but we can only handle Stata files
on machines with IEEE numbers anyway
**/
typedef union {
double value;
unsigned char bytes[8];
} stata8;
typedef union {
int ivalue;
float fvalue;
unsigned char bytes[4];
} stata4;
static double swapd(double d){
stata8 rval,input;
input.value=d;
rval.bytes[7]=input.bytes[0];
rval.bytes[0]=input.bytes[7];
rval.bytes[6]=input.bytes[1];
rval.bytes[1]=input.bytes[6];
rval.bytes[5]=input.bytes[2];
rval.bytes[2]=input.bytes[5];
rval.bytes[4]=input.bytes[3];
rval.bytes[3]=input.bytes[4];
return rval.value;
}
static int swapi(int i){
stata4 rval,input;
input.ivalue=i;
rval.bytes[0]=input.bytes[3];
rval.bytes[3]=input.bytes[0];
rval.bytes[1]=input.bytes[2];
rval.bytes[2]=input.bytes[1];
return rval.ivalue;
}
static double swapf(float f){
stata4 rval,input;
input.fvalue=f;
rval.bytes[0]=input.bytes[3];
rval.bytes[3]=input.bytes[0];
rval.bytes[1]=input.bytes[2];
rval.bytes[2]=input.bytes[1];
return (double) rval.fvalue;
}
typedef union
{
double value;
unsigned int word[2];
} ieee_double;
static void setup_consts()
{
ieee_double x;
x.value = 1;
if (x.word[0] == 0x3ff00000) {
endian=LOHI;
}
else if (x.word[1] == 0x3ff00000) {
endian=HILO;
}
else error("couldn't determine endianness.");
STATA_FLOAT_NA=pow(2,127);
STATA_DOUBLE_NA=pow(2,1023);
}
/** Low-level input **/
static int InIntegerBinary(FILE * fp, int naok, int swapends)
{
int i;
if (fread(&i, sizeof(int), 1, fp) != 1)
error("a binary read error occured");
if (swapends)
i=swapi(i);
return ((i==STATA_INT_NA) & !naok ? NA_INTEGER : i);
}
static int InByteBinary(FILE * fp, int naok)
{
unsigned char i;
if (fread(&i, sizeof(char), 1, fp) != 1)
error("a binary read error occured");
return ((i==STATA_BYTE_NA) & !naok ? NA_INTEGER : (int) i);
}
static int InShortIntBinary(FILE * fp, int naok,int swapends)
{
unsigned short first,second,result;
first = InByteBinary(fp,1);
second = InByteBinary(fp,1);
if (stata_endian==LOHI){
result= (first<<8) | second;
} else {
result= (second<<8) | first;
}
return ((result==STATA_SHORTINT_NA) & !naok ? NA_INTEGER : result);
}
static double InDoubleBinary(FILE * fp, int naok, int swapends)
{
double i;
if (fread(&i, sizeof(double), 1, fp) != 1)
error("a binary read error occured");
if (swapends)
i=swapd(i);
return ((i==STATA_DOUBLE_NA) & !naok ? NA_REAL : i);
}
static float InFloatBinary(FILE * fp, int naok, int swapends)
{
float i;
if (fread(&i, sizeof(float), 1, fp) != 1)
error("a binary read error occured");
if (swapends)
i= swapf(i);
return ((i==STATA_FLOAT_NA) & !naok ? (float) NA_REAL : i);
}
static void InStringBinary(FILE * fp, int nchar, char* buffer)
{
if (fread(buffer, nchar, 1, fp) != 1)
error("a binary read error occured");
}
static char* nameMangle(char *stataname, int len){
int i;
for(i=0;i<len;i++)
if (stataname[i]=='_') stataname[i]='.';
return stataname;
}
/*****
Turn a .dta file into a data frame
Variable labels go to attributes of the data frame
value labels and characteristics could go as attributes of the variables
not yet implemented
****/
SEXP R_LoadStataData(FILE *fp)
{
int i,j,nvar,nobs,charlen, version5,swapends;
unsigned char abyte;
char datalabel[81], timestamp[18], aname[9];
SEXP df,names,tmp,varlabels,types,row_names;
setup_consts(); /*endianness*/
/** first read the header **/
abyte=InByteBinary(fp,1); /* release version */
version5=0; /*-Wall*/
switch (abyte){
case 0x69:
version5=1;
break;
case 'l':
version5=0;
break;
default:
error("Not a Stata v5 or v6 file");
}
stata_endian=(int) InByteBinary(fp,1); /* byte ordering */
if (endian!=stata_endian)
swapends=1;
else
swapends=0;
InByteBinary(fp,1); /* filetype -- junk */
InByteBinary(fp,1); /* padding */
nvar = (InShortIntBinary(fp,1,swapends)); /* number of variables */
nobs =(InIntegerBinary(fp,1,swapends)); /* number of cases */
/* data label - zero terminated string */
if (version5)
InStringBinary(fp,32,datalabel);
else
InStringBinary(fp,81,datalabel);
/* file creation time - zero terminated string */
InStringBinary(fp,18,timestamp);
/** make the data frame **/
PROTECT(df=allocVector(VECSXP, nvar));
/** and now stick the labels on it **/
PROTECT(tmp=allocVector(STRSXP,1));
/* STRING(tmp)[0]=mkChar(datalabel);*/
SET_STRING_ELT(tmp,0,mkChar(datalabel));
setAttrib(df,install("datalabel"),tmp);
UNPROTECT(1);
PROTECT(tmp=allocVector(STRSXP,1));
/* STRING(tmp)[0]=mkChar(timestamp);*/
SET_STRING_ELT(tmp,0,mkChar(timestamp));
setAttrib(df,install("time.stamp"),tmp);
UNPROTECT(1);
/** read variable descriptors **/
/** types **/
PROTECT(types=allocVector(INTSXP,nvar));
for(i=0;i<nvar;i++){
abyte = InByteBinary(fp,1);
INTEGER(types)[i]= abyte;
switch (abyte) {
case STATA_FLOAT:
case STATA_DOUBLE:
/* VECTOR(df)[i]=allocVector(REALSXP,nobs);*/
SET_VECTOR_ELT(df,i,allocVector(REALSXP,nobs));
break;
case STATA_INT:
case STATA_SHORTINT:
case STATA_BYTE:
/* VECTOR(df)[i]=allocVector(INTSXP,nobs);*/
SET_VECTOR_ELT(df,i,allocVector(INTSXP,nobs));
break;
default:
if (abyte<STATA_STRINGOFFSET)
error("Unknown data type");
/* VECTOR(df)[i]=allocVector(STRSXP,nobs);*/
SET_VECTOR_ELT(df,i,allocVector(STRSXP,nobs));
break;
}
}
/** names **/
PROTECT(names=allocVector(STRSXP,nvar));
for (i=0;i<nvar;i++){
InStringBinary(fp,9,aname);
/* STRING(names)[i]=mkChar(nameMangle(aname,9));*/
SET_STRING_ELT(names,i,mkChar(nameMangle(aname,9)));
}
setAttrib(df,R_NamesSymbol, names);
UNPROTECT(1);
/** sortlist -- not relevant **/
for (i=0;i<2*(nvar+1);i++)
InByteBinary(fp,1);
/** format list
passed back to R as attributes.
Useful to identify date variables.
**/
PROTECT(tmp=allocVector(STRSXP,nvar));
for (i=0;i<nvar;i++){
InStringBinary(fp,12,timestamp);
/* STRING(tmp)[i]=mkChar(timestamp);*/
SET_STRING_ELT(tmp,i,mkChar(timestamp));
}
setAttrib(df,install("formats"),tmp);
UNPROTECT(1);
/** value labels. These are stored as the names of label formats,
which are themselves stored later in the file. Not implemented**/
for(i=0;i<nvar;i++){
InStringBinary(fp,9,aname);
}
/** Variable Labels **/
PROTECT(varlabels=allocVector(STRSXP,nvar));
if (version5){
for(i=0;i<nvar;i++) {
InStringBinary(fp,32,datalabel);
/* STRING(varlabels)[i]=mkChar(datalabel);*/
SET_STRING_ELT(varlabels,i,mkChar(datalabel));
}
} else {
for(i=0;i<nvar;i++) {
InStringBinary(fp,81,datalabel);
/* STRING(varlabels)[i]=mkChar(datalabel);*/
SET_STRING_ELT(varlabels,i,mkChar(datalabel));
}
}
setAttrib(df, install("var.labels"), varlabels);
UNPROTECT(1);
/** variable 'characteristics' -- not yet implemented **/
while(InByteBinary(fp,1)) {
charlen= (InShortIntBinary(fp,1,swapends));
for (i=0;i<charlen;i++)
InByteBinary(fp,1);
}
charlen=(InShortIntBinary(fp,1,swapends));
if (charlen!=0)
error("Something strange in the file\n (Type 0 characteristic of nonzero length)");
/** The Data **/
for(i=0;i<nobs;i++){
for(j=0;j<nvar;j++){
switch (INTEGER(types)[j]) {
case STATA_FLOAT:
/* REAL(VECTOR(df)[j])[i]=(InFloatBinary(fp,0,swapends));*/
REAL(VECTOR_ELT(df,j))[i]=(InFloatBinary(fp,0,swapends));
break;
case STATA_DOUBLE:
REAL(VECTOR_ELT(df,j))[i]=(InDoubleBinary(fp,0,swapends));
break;
case STATA_INT:
INTEGER(VECTOR_ELT(df,j))[i]=(InIntegerBinary(fp,0,swapends));
break;
case STATA_SHORTINT:
INTEGER(VECTOR_ELT(df,j))[i]=(InShortIntBinary(fp,0,swapends));
break;
case STATA_BYTE:
INTEGER(VECTOR_ELT(df,j))[i]=(int) InByteBinary(fp,0);
break;
default:
charlen=INTEGER(types)[j]-STATA_STRINGOFFSET;
PROTECT(tmp=allocString(charlen+1));
InStringBinary(fp,charlen,CHAR(tmp));
CHAR(tmp)[charlen]=0;
SET_STRING_ELT(VECTOR_ELT(df,j),i,tmp);
UNPROTECT(1);
break;
}
}
}
PROTECT(tmp = mkString("data.frame"));
setAttrib(df, R_ClassSymbol, tmp);
UNPROTECT(1);
PROTECT(row_names = allocVector(STRSXP, nobs));
for (i=0; i<nobs; i++) {
sprintf(datalabel, "%d", i+1);
/*STRING(row_names)[i] = mkChar(datalabel);*/
SET_STRING_ELT(row_names,i,mkChar(datalabel));
}
setAttrib(df, R_RowNamesSymbol, row_names);
UNPROTECT(1);
UNPROTECT(2); /* types, df */
return(df);
}
SEXP do_readStata(SEXP call)
{
SEXP fname, result;
FILE *fp;
if ((sizeof(double)!=8) | (sizeof(int)!=4) | (sizeof(float)!=4))
error("can't yet read Stata .dta on this platform");
if (!isValidString(fname = CADR(call)))
error("first argument must be a file name\n");
fp = fopen(R_ExpandFileName(CHAR(STRING_ELT(fname,0))), "rb");
if (!fp)
error("unable to open file");
result = R_LoadStataData(fp);
fclose(fp);
return result;
}
/** low level output **/
static void OutIntegerBinary(int i, FILE * fp, int naok)
{
i=((i==NA_INTEGER) & !naok ? STATA_INT_NA : i);
if (fwrite(&i, sizeof(int), 1, fp) != 1)
error("a binary write error occured");
}
static void OutByteBinary(unsigned char i, FILE * fp)
{
if (fwrite(&i, sizeof(char), 1, fp) != 1)
error("a binary write error occured");
}
static void OutShortIntBinary(int i,FILE * fp)
{
unsigned char first,second;
if (endian==LOHI){
first= (i>>8);
second=i & 0xff;
}
else {
first=i & 0xff;
second=i>>8;
}
if (fwrite(&first, sizeof(char), 1, fp) != 1)
error("a binary write error occured");
if (fwrite(&second, sizeof(char), 1, fp) != 1)
error("a binary write error occured");
}
static void OutDoubleBinary(double d, FILE * fp, int naok)
{
d=(R_FINITE(d) ? d : STATA_DOUBLE_NA);
if (fwrite(&d, sizeof(double), 1, fp) != 1)
error("a binary write error occured");
}
static void OutStringBinary(char *buffer, FILE * fp, int nchar)
{
if (fwrite(buffer, nchar, 1, fp) != 1)
error("a binary write error occured");
}
static char* nameMangleOut(char *stataname, int len){
int i;
for(i=0;i<len;i++){
if (stataname[i]=='.') stataname[i]='_';
}
return stataname;
}
void R_SaveStataData(FILE *fp, SEXP df)
{
int i,j,k,l,nvar,nobs,charlen;
char datalabel[81]="Written by R. ", timestamp[18], aname[9];
char format9g[12]="%9.0g", strformat[12]="";
SEXP names,types;
k=0; /* -Wall */
setup_consts(); /*endianness*/
/** first write the header **/
OutByteBinary((char) 108,fp); /* release */
OutByteBinary((char) endian,fp);
OutByteBinary(1,fp); /* filetype */
OutByteBinary(0,fp); /* padding */
nvar=length(df);
OutShortIntBinary(nvar,fp);
nobs=length(VECTOR_ELT(df,0));
OutIntegerBinary(nobs,fp,1); /* number of cases */
OutStringBinary(datalabel,fp,81); /* data label - zero terminated string */
for(i=0;i<18;i++){
timestamp[i]=0;
}
OutStringBinary(timestamp,fp,18); /* file creation time - zero terminated string */
/** write variable descriptors **/
/** types **/
/* FIXME: writes everything as double or integer to save effort*/
PROTECT(types=allocVector(INTSXP,nvar));
for(i=0;i<nvar;i++){
switch(TYPEOF(VECTOR_ELT(df,i))){
case LGLSXP:
case INTSXP:
OutByteBinary(STATA_INT,fp);
break;
case REALSXP:
OutByteBinary(STATA_DOUBLE,fp);
break;
case STRSXP:
charlen=0;
for(j=0;j<nobs;j++){
k=length(STRING_ELT(VECTOR_ELT(df,i),j));
if (k>charlen)
charlen=k;
}
OutByteBinary((unsigned char)(k+STATA_STRINGOFFSET),fp);
INTEGER(types)[i]=k;
break;
default:
error("Unknown data type");
break;
}
}
/** names truncated to 8 characters**/
PROTECT(names=getAttrib(df,R_NamesSymbol));
for (i=0;i<nvar;i++){
strncpy(aname,CHAR(STRING_ELT(names,i)),8);
OutStringBinary(nameMangleOut(aname,8),fp,8);
OutByteBinary(0,fp);
}
/** sortlist -- not relevant **/
for (i=0;i<2*(nvar+1);i++)
OutByteBinary(0,fp);
/** format list: arbitrarily write numbers as %9g format
but strings need accurate types */
for (i=0;i<nvar;i++){
if (TYPEOF(VECTOR_ELT(df,i))==STRSXP){
/* string types are at most 128 characters
so we can't get a buffer overflow in sprintf **/
sprintf(strformat,"%%%ds",INTEGER(types)[i]);
OutStringBinary(strformat,fp,12);
} else {
OutStringBinary(format9g,fp,12);
}
}
/** value labels. These are stored as the names of label formats,
which are themselves stored later in the file. Not implemented**/
for(i=0;i<9;i++)
aname[i]=(char) 0;
for(i=0;i<nvar;i++){
OutStringBinary(aname,fp,9);
}
/** Variable Labels -- full R name of column**/
for(i=0;i<nvar;i++) {
strncpy(datalabel,CHAR(STRING_ELT(names,i)),81);
datalabel[80]=(char) 0;
OutStringBinary(datalabel,fp,81);
}
UNPROTECT(1); /*names*/
/** variable 'characteristics' -- not relevant**/
OutByteBinary(0,fp);
OutByteBinary(0,fp);
OutByteBinary(0,fp);
/** The Data **/
for(i=0;i<nobs;i++){
for(j=0;j<nvar;j++){
switch (TYPEOF(VECTOR_ELT(df,j))) {
case LGLSXP:
OutIntegerBinary(LOGICAL(VECTOR_ELT(df,j))[i],fp,0);
break;
case INTSXP:
OutIntegerBinary(INTEGER(VECTOR_ELT(df,j))[i],fp,0);
break;
case REALSXP:
OutDoubleBinary(REAL(VECTOR_ELT(df,j))[i],fp,0);
break;
case STRSXP:
k=length(STRING_ELT(VECTOR_ELT(df,j),i));
OutStringBinary(CHAR(STRING_ELT(VECTOR_ELT(df,j),i)),fp,k);
for(l=INTEGER(types)[j]-k;l>0;l--)
OutByteBinary(0,fp);
break;
default:
error("This can't happen.");
break;
}
}
}
UNPROTECT(1); /*types*/
}
SEXP do_writeStata(SEXP call)
{
SEXP fname, df;
FILE *fp;
if ((sizeof(double)!=8) | (sizeof(int)!=4) | (sizeof(float)!=4))
error("can't yet read write .dta on this platform");
if (!isValidString(fname = CADR(call)))
error("first argument must be a file name\n");
fp = fopen(R_ExpandFileName(CHAR(STRING_ELT(fname,0))), "wb");
if (!fp)
error("unable to open file");
df=CADDR(call);
if (!inherits(df,"data.frame"))
error("data to be saved must be in a data frame.");
R_SaveStataData(fp,df);
fclose(fp);
return R_NilValue;
}
|
C
|
/*
Filename: heapSort.c
Author: Tony Zeng
Mail: laoweiyeah@gmail.com
Function: implement of heap sorting algorithm
Time: 2013-6-23 22:57:54
*/
#include <stdio.h>
#include "array.h"
void heapSort(int* array, int count)
{
int temp;
for (int j = count - 1; j > 0; --j)
{
for (int i = j; i > 0; --i)
{
if (array[i] > array[(i-1)/2])
{
temp = array[i];
array[i] = array[(i-1)/2];
array[(i-1)/2] = temp;
}
}
temp = array[0];
array[0] = array[j];
array[j] = temp;
}
}
int main(int argc, char** args)
{
printArray(array, length);
heapSort(array, length);
printArray(array, length);
if (!checkArray(array, length))
{
printf("Error occured!\n");
}
return 0;
}
|
C
|
/*Botworx VR - A Virtual Reality Framework
Copyright (C) 2005 Kurtis Fields. See BotworxVR_License.txt for details.
*/
#ifndef _BwMath_H
#define _BwMath_H
//namespace bwmath {
inline bwDegree makeDegree(const bwRadian& r) {
return (r * bwReal(180.0f)) / bwRealTraits::Pi ;
}
inline bwRadian makeRadian(const bwDegree& d) {
return (d * bwRealTraits::Pi) / bwReal(180.0f) ;
}
enum {
yawElem = 0,
pitchElem,
rollElem
} ;
/////////////////
/*courtesy of euclideanspace*/
inline bwQuat makeQuatFromEuler(bwReal yaw, bwReal pitch, bwReal roll) {
bwReal cosY = cos(yaw / bwReal(2)) ;
bwReal sinY = sin(yaw / bwReal(2)) ;
bwReal cosP = cos(pitch / bwReal(2)) ;
bwReal sinP = sin(pitch / bwReal(2)) ;
bwReal cosR = cos(roll / bwReal(2)) ;
bwReal sinR = sin(roll / bwReal(2)) ;
bwQuat quat ;
quat[3] = cosR * sinP * cosY + sinR * cosP * sinY ;
quat[0] = cosR * cosP * sinY - sinR * sinP * cosY ;
quat[1] = sinR * cosP * cosY - cosR * sinP * sinY ;
quat[2] = cosR * cosP * cosY + sinR * sinP * sinY ;
return quat ;
}
inline void makePitch(bwEuler &euler, bwReal degree) {
bwReal d = euler[0] + degree ;
if(d < bwRealTraits::Zero)
d = bwRealTraits::Pi2 - degree ;
else
if(d > bwRealTraits::Pi2)
d = degree ;
euler[0] = d ;
}
/*courtesy of euclideanspace*/
inline bwEuler makeEulerFromQuaternion(const bwQuat &quat) {
bwEuler euler ;
bwReal sqw = quat[3]*quat[3] ;
bwReal sqx = quat[0]*quat[0] ;
bwReal sqy = quat[1]*quat[1] ;
bwReal sqz = quat[2]*quat[2] ;
bwReal unit = sqx + sqy + sqz + sqw ; // if normalised is one, otherwise is correction factor
bwReal test = quat[0]*quat[1] + quat[2]*quat[3] ;
if (test > bwReal(0.499)*unit) { // singularity at north pole ... constant ... AlmostHalf???
euler[0] = bwRealTraits::Two * atan2(quat[0],quat[3]);
euler[1] = bwRealTraits::PiDiv2 ;
euler[2] = 0;
return euler ;
} if (test < -bwReal(0.499)*unit) { // singularity at south pole
euler[0] = -bwRealTraits::Two * atan2(quat[0],quat[3]);
euler[1] = bwRealTraits::NegPiDiv2 ;
euler[2] = 0;
return euler ;
}
euler[0] = atan2(bwRealTraits::Two*quat[1]*quat[3]-bwRealTraits::Two*quat[0]*quat[2] , sqx - sqy - sqz + sqw);
euler[1] = asin(bwRealTraits::Two*test/unit);
euler[2] = atan2(bwRealTraits::Two*quat[0]*quat[3]-bwRealTraits::Two*quat[1]*quat[2] , -sqx + sqy - sqz + sqw) ;
return euler ;
}
//} //namespace bwmath
#endif //_BwMath_H
|
C
|
#include<stdio.h>
int main()
{
float sp,pr,tcp,cp;
printf("enter the selling price of 15 item - " );
scanf("%f",&sp);
printf("enter the profit - ");
scanf("%f",&pr);
tcp=sp-pr;
cp=tcp/15;
printf("Cost price of each item = %05.000f\n",cp);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
// gcc -DFLAG_1 -DFLAG_2 -E test.c > test_E.c
// All FLAG wil be compiler
// gcc -DFLAG_1=0 -DFLAG_2=0 -E test.c > test_E.c
// FLAG_2 still be compiler....
// gcc -E test.c > test_E.c
// FLAG_3 can compiler sucess even if we don't add -DFLAG_3
// FLAG_3 can compiler sucess
int main()
{
#if (FLAG_1 == 1)
printf("FLAG_1 == 1\n");
#endif
// -DFLAG_2=0 still will compielr it
#ifdef FLAG_2
printf("FLAG_2 == 1\n");
#endif
#if defined FLAG_3 && (FLAG_3 == 1)
printf("FLAG_3 == 1\n");
#endif
return 0;
}
|
C
|
#include "flash.h"
#include "debug_usart.h"
uint8_t CopyMemory( uint32_t src_addr
, uint32_t dst_addr
, size_t size
)
{
HAL_FLASH_Unlock();
for( size_t written = 0; written < size; written += 4 ){
// erase sector if we just reached one
for( int32_t i=0; i < sector_count; ++i ){
if( dst_addr == kSectorBaseAddress[i] ){
uint32_t sector_error;
Debug_USART_printf("erase\n\r");
FLASH_EraseInitTypeDef erase_setup =
{ .TypeErase = FLASH_TYPEERASE_SECTORS
, .Sector = i
, .NbSectors = 1
, .VoltageRange = FLASH_VOLTAGE_RANGE_3
};
HAL_FLASHEx_Erase( &erase_setup
, §or_error
);
Debug_USART_putn8(i);
}
}
if( dst_addr > (kStartReceiveAddress - 4) ){
Debug_USART_printf("overwrite_flash\n\r");
return 1; // trying to overwrite receive buffer
}
//Program the word
HAL_FLASH_Program( FLASH_TYPEPROGRAM_WORD
, dst_addr
, *(uint32_t*)src_addr
);
src_addr += 4;
dst_addr += 4;
}
return 0;
}
uint8_t ProgramPage( uint32_t* current_address
, const uint8_t* data
, size_t size
)
{
HAL_FLASH_Unlock();
for( int32_t i=0; i < sector_count; ++i ){
if( *current_address == kSectorBaseAddress[i] ){
uint32_t sector_error;
Debug_USART_printf("erase\n\r");
FLASH_WaitForLastOperation( 10000 );
FLASH_EraseInitTypeDef erase_setup =
{ .TypeErase = FLASH_TYPEERASE_SECTORS
, .Sector = i
, .NbSectors = 1
, .VoltageRange = FLASH_VOLTAGE_RANGE_3
};
HAL_FLASHEx_Erase( &erase_setup
, §or_error
);
// check sector_error value for erase error reporting
Debug_USART_putn8(i);
}
}
uint32_t* words = (uint32_t*)data;
for( size_t written = 0; written < size; written += 4 ){
FLASH_WaitForLastOperation( 10000 );
HAL_FLASH_Program( FLASH_TYPEPROGRAM_WORD
, *current_address
, *words++
);
*current_address += 4;
if( *current_address >= EndOfMemory ){
Debug_USART_printf("endofmem\n\r");
return 1; // end of memory
}
}
return 0; // no error
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/*Recursividad: Es una funcion que se llama a si misma
1. Caso Base
2. Caso Recursiva
*/
long factorial(int n);
int main()
{
int numero;
printf("Ingrese un numero: ");
scanf("%d", &numero);
printf("\nEl factorial es: %d\n", factorial(numero));
return 0;
}
long factorial(int n){
if(n<=1){
return 1;
}else{
return (n * factorial(n - 1));
}
}
|
C
|
#include<stdio.h>
#include<conio.h>
#define MAX 10 // Changing this value will change length of array
int kuyruk[MAX];
int on = -1, son = -1;
void ekle(void);
int delete_element(void);
int peek(void);
void display(void);
void TersCevir(void);
int val;
int main()
{
int option, val;
do
{
printf("\n\n ***** Ana MENU *****");
printf("\n 0. KUYRUGUN ELEMANLARINI TERS CEVIR");
printf("\n 1. Eleman ekleme");
printf("\n 2.Eleman Silme");
printf("\n 3. Peek");
printf("\n 4. Kuyrugu Gosterme");
printf("\n 5. EXIT");
printf("\n Birini secin : ");
scanf("%d", &option);
switch(option)
{
case 1:
ekle();
break;
case 2:
val = delete_element();
if (val != -1)
printf("\n The number deleted is : %d", val);
break;
case 3:
val = peek();
if (val != -1)
printf("\n The first value in kuyruk is : %d", val);
break;
case 4:
display();
break;
case 0:
TersCevir();
break;
}
}while(option != 5);
getch();
return 0;
}
void ekle()
{
int num;
printf("\n Enter the number to be ekleed in the kuyruk : ");
scanf("%d", &num);
if(son == MAX-1) printf("\n OVERFLOW");
else if(on == -1 && son == -1)
on = son = 0;
else
son++;
kuyruk[son] = num;
}
int delete_element()
{
if(on == -1 || on>son)
{
printf("\n UNDERFLOW");
return -1;
}
else
{
val = kuyruk[on];
on++;
if(on > son)
on = son = -1;
return val;
}
}
int peek()
{
if(on==-1 || on>son)
{
printf("\n kuyruk IS EMPTY");
return -1;
}
else
{
return kuyruk[on];
}
}
void display()
{
int i;
printf("\n");
if(on == -1 || on > son)
printf("\n kuyruk IS EMPTY");
else
{
for(i = on;i <= son;i++)
printf("\t %d", kuyruk[i]);
}
}
void TersCevir(){
if(on == -1 || on > son)
printf("\n kuyruk IS EMPTY");
else {
int sonGecici = 0;
int geciciKuyruk[MAX];
for (int i = son; i >= on; i--) {
geciciKuyruk[sonGecici] = kuyruk[i];
sonGecici++;
}
for (int i = on; i < sonGecici + 1; ++i) {
kuyruk[i] = geciciKuyruk[i];
}
printf("KUYRUK ELEMANLARI TERS CEVRILDI \n ");
}
}
|
C
|
#include <stdio.h>
void info() { //easier way than repeatedly typing the info in different places.
printf("*************COMMANDS*************\n"); //yes it could be done in one line, it's easier on the eyes to format this way.
printf("d NUMBER deletes the given number from the list of numbers\n"); //The delete function
printf("i NUMBER inserts the given number into the list of numbers\n"); //The insert function
printf("p prints the entire list of numbers in the list\n"); //The print function
printf("s NUMBER searches for the given number inside the list\n"); //The search function
printf("x exits the program and disregards anything enterd after the x\n"); //The exit function
}
|
C
|
#include <stdio.h>
void *SumarConPunteros(int *a);//declaro funcion como puntero
int main(){
int a =1;
int b =0;
int *p, *x;
p=&a;
printf("Muestro p=&a : %d\n",*p);
b=*p+10;
printf("Muestro b=*p+10 : %d\n", b);
*p=*p+1;
printf("Muestro *p=*p+1: %d\n",*p);
a=SumarConPunteros(p);
printf("Muestro *p despues de la funcion: %i",a);
}
void *SumarConPunteros(int *a){
a++;
return a;
}
|
C
|
//
// Created by liushan on 18-7-25.
//
#include <stdio.h>
#include <sys/utsname.h>
#include <unistd.h>
void myuname(void)
{
struct utsname name_ptr;
char name[64];
uname(&name_ptr);
gethostname(name, 64);
printf("%s %s %s %s %s\n",
name_ptr.sysname, name_ptr.nodename, name_ptr.release, name_ptr.version, name_ptr.machine);
printf("%s\n", name);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* type_dec.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: apoplavs <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/03/03 11:34:36 by apoplavs #+# #+# */
/* Updated: 2017/03/03 11:34:36 by apoplavs ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
void type_d_i(va_list *arg, t_flags *flag)
{
char *str;
long long val;
if (flag->mod_ll == TRUE)
val = va_arg(*arg, long long);
else if (flag->mod_l == TRUE || flag->mod_j == TRUE || flag->mod_z == TRUE)
val = va_arg(*arg, long);
else if (flag->mod_h == TRUE)
val = (short)va_arg(*arg, int);
else if (flag->mod_hh == TRUE)
val = (char)va_arg(*arg, int);
else
val = (int)va_arg(*arg, int);
if (val < 0 || flag->plus == TRUE || flag->space == TRUE)
flag->width--;
if (val == 0 && flag->precision >= TRUE)
str = ft_strnew(1);
else
str = ft_atol_base(val, 10);
str = write_d(str, flag, (int)ft_strlen(str), val);
final_write(str, flag);
}
char *check_spaced(char *str, t_flags *flag, long long val)
{
char *p;
int i;
char c;
p = str;
i = 0;
c = ' ';
while (str[i] == ' ')
i++;
if (val < 0)
c = '-';
else if (flag->plus == TRUE)
c = '+';
str = ft_strnew(ft_strlen(str) + 2);
ft_strncpy(str, p, i);
str[i] = c;
ft_strcat(str, p + i);
free(p);
return (str);
}
char *write_d(char *str, t_flags *flag, int len,
long long val)
{
char *s;
char c;
if (flag->zero == TRUE && flag->precision <= FALSE && flag->hyphen == FALSE)
c = '0';
else
c = ' ';
s = ft_strdup(str);
if (flag->precision > len)
{
free(s);
s = ft_strnew(flag->precision + 1);
ft_memset(s, 48, flag->precision - len);
ft_strncat(s, str, flag->precision);
}
if (flag->width > (int)ft_strlen(s) && flag->width != FALSE)
s = ft_filwidth(flag, s, c);
free(str);
if (val < 0 || flag->plus == TRUE || flag->space == TRUE)
s = check_spaced(s, flag, val);
return (s);
}
void type_u(va_list *arg, t_flags *flag)
{
char *str;
unsigned long long val;
if (flag->mod_ll == TRUE)
val = va_arg(*arg, unsigned long long);
else if (flag->mod_l == TRUE || flag->mod_j == TRUE || flag->mod_z == TRUE)
val = va_arg(*arg, unsigned long);
else if (flag->mod_h == TRUE)
val = (unsigned short)va_arg(*arg, int);
else if (flag->mod_hh == TRUE)
val = (unsigned char)va_arg(*arg, int);
else
val = (unsigned int)va_arg(*arg, unsigned int);
if (val == 0 && flag->precision >= TRUE)
str = ft_strnew(1);
else
str = ft_unsigned_atol(val, 10);
str = main_write(str, flag, (int)ft_strlen(str));
final_write(str, flag);
}
|
C
|
#include <unistd.h>
int is_in_list(char printed[127], int nb_printed, char c)
{
int i;
i = 0;
while (i <= nb_printed)
{
if (c == printed[i])
return (1);
i++;
}
return (0);
}
void inter(char *first, char *second)
{
char printed[127];
int i;
int j;
int nb_printed;
nb_printed = 0;
i = 0;
while (first[i])
{
j = 0;
while (second[j])
{
if (!is_in_list(printed, nb_printed, first[i]) &&
first[i] == second[j])
{
printed[nb_printed] = first[i];
nb_printed++;
write(1, &first[i], 1);
}
j++;
}
i++;
}
}
int main(int ac, char **av)
{
if (ac == 3)
inter(av[1], av[2]);
write(1, "\n", 2);
return (1);
}
|
C
|
#include <stdio.h>
#include "lk_debug.h"
#include "1.5.2_keyword_sizeof.h"
//int b[2][3];
static void sizeof_func(int b[2][3])
{
int **p = NULL;
lk_print("=== int **p = NULL;\n");
p = (void *)&b;
lk_print("sizeof(**b):%ld, **b:%d\n", sizeof(**b), **b /**(*(b + 1) + 2)*/); /* **b: b[0], int type is 4 Bytes. */
lk_print("sizeof(*(b+1)):%ld, *(b+1):%p\n", sizeof(*(b+1)), *(b+1)); /* *b: the address of b[0], 3*4=12. */
lk_print("sizeof(b):%ld, b:%p\n", sizeof(b), b); /* b: the address of array b, in 64bit system is 8 Bytes. */
lk_print("=== p = &b\n");
lk_print("sizeof(p):%ld, p:%p\n", sizeof(p), p); /* p: b. */
lk_print("sizeof(*p):%ld, *p:%p\n", sizeof(*p), *p); /* *p: *b. */
lk_print("sizeof(**p):%ld, **p:%d\n", sizeof(**p), **p/**(*p + 5)*/); /* **p: **b. */
}
void keyword_sizeof_test(void)
{
int *p = NULL;
int array[2][3] = {{0, 1, 2}, {3, 4, 5}};
lk_print("=== int *p = NULL;\n");
lk_print("sizeof(p):%ld\n", sizeof(p));
lk_print("sizeof(*p):%ld.\n", sizeof(*p));
lk_print("=== int array[2][3] = {0-5};\n");
lk_print("sizeof(array):%ld, %p\n", sizeof(array), array);
lk_print("sizeof(array[1]):%ld, %p, &array[1][0]: %p.\n", sizeof(array[1]), array[1], &array[1][0]);
lk_print("sizeof(&array):%ld, &array: %p\n", sizeof(&array), &array);
lk_print("sizeof(&array[0]):%ld\n", sizeof(&array[0]));
sizeof_func(array);
}
|
C
|
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
char** findRepeatedDnaSequences(char*s, int* returnSize)
{
int size = strlen(s);
if(size < 11) return NULL; //at least 11 letters;
int hashTable[1 << 20] = {0}; //allocate a hash map array for 20-bit key;
int hashNum = 0;
int index = 0;
char** sArray = (char**)malloc(sizeof(char*) * size);
for(int i = 0; i < 9; i++) //the head of the first key;
hashNum = hashNum << 2 | (*(s+i) - 'A' + 1) % 5;
for(int i = 9; i < size; i++) //one step forward, one different string will be covered by the key simply;
{
if(hashTable[hashNum = (hashNum << 2 | (*(s+i) - 'A' + 1) % 5) & 0x000fffff]++ == 1) //each repeated substring will only be collected once;
{
sArray[index] = (char*)malloc(11 * sizeof(char));
strncpy(sArray[index], s+i-9, 10);
sArray[index++][10] = '\0';
}
}
*returnSize = index;
return sArray;
}
|
C
|
#include<stdio.h>
int main()
{
int a[10]={1,2,3,4,5,6,7,8,9,10};
int n,m,x,i,j,q;
printf("开始位置与个数:");
scanf("%d%d",&n,&m);
i=n-1;
j=m+n-2;
do
{
x=a[i];
a[i]=a[j];
a[j]=x;
++i;
--j;
}while(i<j);
for(q=0;q<10;q++)
{
printf("%d",a[q]);
}
printf("\n");
return 0;
}
|
C
|
// C# program to Sort square
// of the numbers of the array
using System;
class GFG
{
// Function to sort
// an square array
public static void sortSquares(int []arr)
{
int n = arr.Length;
// First convert each array
// elements into its square
for (int i = 0 ; i < n ; i++)
arr[i] = arr[i] * arr[i];
// Sort an array using
// "inbuild sort function"
// in Arrays class.
Array.Sort(arr);
}
// Driver Code
public static void Main ()
{
int []arr = {-6, -3, -1,
2, 4, 5 };
int n = arr.Length;
Console.WriteLine("Before sort ");
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
sortSquares(arr);
Console.WriteLine("");
Console.WriteLine("After Sort ");
for (int i = 0 ; i < n ; i++)
Console.Write(arr[i] + " ");
}
}
|
C
|
/*
* NAME: PARTHO SARTHI
* ID: 2015A7PS0088P
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "lexer.h"
#include "langDef.h"
TokenInfo setTokenValue(int state,char * name,int line){
TokenInfo token;
memset(token.name,'\0',MAX_LENGTH+1);
strcpy(token.name,name);
token.id=state;
token.line=line;
return token;
}
TokenInfo getToken(FILE *fp,char **fileBuffInit,char *lexeme,int *begin){
int state=1,offset=0,tokLen=0,tokLenErr=0,unknownErr=0;
char ch;
char *fileBuff = (*fileBuffInit)+(*begin);
memset(lexeme,'\0',MAX_LENGTH+1);
while(1){
if(*fileBuff=='\0'){
memset(*fileBuffInit,'\0',BUFF_SIZE);
fread(*fileBuffInit,1,BUFF_SIZE,fp);
*begin = 0;
fileBuff = (*fileBuffInit)+(*begin);
}
ch=*fileBuff;
// printf("%c ",ch );
if(ch=='\0'){
if(state==1){
strcpy(lexeme,"$");
state=0;
}
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
if(ch=='\n'){
if(state==1)
line++;
else if(state!=2 && state!=23 && state!=42 && state!=45){ // not for comment lines
fileBuff-=1;
printf("%d: LEXICAL ERROR: Unknown Pattern %s\n",line,lexeme);
state=-1;
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
}
// check for invalid characters
if(ch<0){
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
switch(state){
case 1:
switch(ch){
case ' ':
case '\t':
case '\n':
case '\r':
break;
case '#':
state = 2;
break;
case '[':
state = 4;
strcpy(lexeme,"[");
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
case ']':
state = 5;
strcpy(lexeme,"]");
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
case '(':
state = 6;
strcpy(lexeme,"(");
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
case ')':
state = 7;
strcpy(lexeme,")");
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
case ';':
state = 8;
strcpy(lexeme,";");
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
case ',':
state = 9;
strcpy(lexeme,",");
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
case '+':
state = 10;
strcpy(lexeme,"+");
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
case '-':
state = 11;
strcpy(lexeme,"-");
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
case '*':
state = 12;
strcpy(lexeme,"*");
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
case '/':
state = 13;
strcpy(lexeme,"/");
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
case '@':
state = 14;
strcpy(lexeme,"@");
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
case'<':
state=15;
lexeme[offset++] = ch;
break;
case'>':
state=17;
lexeme[offset++] = ch;
break;
case '=':
state = 19;
lexeme[offset++] = ch;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
tokLen=1;
tokLenErr=0;
state = 23;
lexeme[offset++] = ch;
break;
case '"':
state = 27;
tokLen=0;
tokLenErr=0;
unknownErr=0;
lexeme[offset++] = ch;
break;
case '.':
state = 30;
lexeme[offset++] = ch;
break;
case 'a': case 'A':
case 'b': case 'B':
case 'c': case 'C':
case 'd': case 'D':
case 'e': case 'E':
case 'f': case 'F':
case 'g': case 'G':
case 'h': case 'H':
case 'i': case 'I':
case 'j': case 'J':
case 'k': case 'K':
case 'l': case 'L':
case 'm': case 'M':
case 'n': case 'N':
case 'o': case 'O':
case 'p': case 'P':
case 'q': case 'Q':
case 'r': case 'R':
case 's': case 'S':
case 't': case 'T':
case 'u': case 'U':
case 'v': case 'V':
case 'w': case 'W':
case 'x': case 'X':
case 'y': case 'Y':
case 'z': case 'Z':
state = 42;
tokLen=1;
tokLenErr=0;
lexeme[offset++] = ch;
break;
case '_':
state = 44;
tokLen=1;
tokLenErr=0;
lexeme[offset++] = ch;
break;
default:
state = -1;
// strcpy(lexeme,"ERROR");
lexeme[offset++] = ch;
printf("%d: LEXICAL ERROR: Unknown Symbol %s\n",line,lexeme);
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
break;
// <,<=,>,>=,==
case 2:
if(ch!='\n'){
state=2;
}else{
state=3;
fileBuff-=1;
strcpy(lexeme,"COMMENT");
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
break;
case 15:
case 17:
case 19:
if(strcmp(lexeme,"=")==0 && ch=='/'){
if(*(fileBuff+1)!='='){ // check for empty
// printf("%d: LEXICAL ERROR: Unknown Pattern %s\n",line,lexeme);
fileBuff-=1;
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
state=21;
lexeme[offset++]=ch;
}
else {
if(ch=='='){
state++;
lexeme[offset++]=ch;
}
else{
fileBuff-=1;
}
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
break;
// =/=
case 21:
if(ch=='='){
lexeme[offset++]=ch;
state++;
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}else{
// strcpy(lexeme,"ERROR");
fileBuff-=1;
state = -1;
printf("%d: LEXICAL ERROR: Unknown Pattern %s\n",line,lexeme);
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
break;
case 23:
if(isdigit(ch)){
state = 23;
if(tokLen<MAX_LENGTH){
lexeme[offset++] = ch;
tokLen++;
}
}else if(ch=='.'){
if(isalpha(*(fileBuff+1))){
if(*(fileBuff+1)=='a'||*(fileBuff+1)=='o'||*(fileBuff+1)=='n'){
fileBuff-=1;
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}else{
fileBuff-=1;
*begin = fileBuff - (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
}else{
// fileBuff-=1;
state = 24;
if(tokLen<MAX_LENGTH){
lexeme[offset++] = ch;
tokLen++;
}
}
}else{
// lexeme[offset++] = '\0';
fileBuff-=1;
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
break;
case 24:
if(isdigit(ch)){
if(tokLen<MAX_LENGTH){
lexeme[offset++] = ch;
tokLen++;
}
state++;
}else{
// strcpy(lexeme,"ERROR");
fileBuff-=1;
state = -1;
printf("%d: LEXICAL ERROR: Unknown Pattern %s\n",line,lexeme);
*begin = fileBuff - (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
break;
case 25:
if(isdigit(ch)){
if(tokLen<MAX_LENGTH){
lexeme[offset++] = ch;
tokLen++;
}
state++;
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}else{
// strcpy(lexeme,"ERROR");
fileBuff-=1;
state = -1;
printf("%d: LEXICAL ERROR: Unknown Pattern %s\n",line,lexeme);
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
break;
case 27:
if ((ch >= 'a' && ch <= 'z')|| ch==' '){
lexeme[offset++] = ch;
state=28;
tokLen++;
}else{
// strcpy(lexeme,"ERROR");
fileBuff-=1;
state = -1;
printf("%d: LEXICAL ERROR: Unknown Pattern %s\n",line,lexeme);
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
break;
case 28:
if ((ch >= 'a' && ch <= 'z') || ch==' '){
state=28;
if(tokLen<(MAX_LENGTH-2)){
lexeme[offset++] = ch;
tokLen++;
}
else
tokLenErr=1;
}else if(ch=='"'){
state=29;
*begin = fileBuff- (*fileBuffInit);
lexeme[offset++] = ch;
tokLen++;
// printf("len: %d\n",tokLen );
if(unknownErr){
state=-1;
// lexeme[offset++] = ch;
printf("%d: LEXICAL ERROR: Unknown Pattern %s\n",line,lexeme);
return setTokenValue(state,lexeme,line);
}
if(tokLenErr){
// state=-1;
printf("%d: LEXICAL ERROR: String is longer than the prescribed length: %s...\n",line,lexeme);
return setTokenValue(state,lexeme,line);
}
return setTokenValue(state,lexeme,line);
}
else{
state=28;
unknownErr=1;
if(tokLen<(MAX_LENGTH-2)){
lexeme[offset++] = ch;
tokLen++;
}
else
tokLenErr=1;
// strcpy(lexeme,"ERROR");
}
break;
case 30:
switch(ch){
case 'o':
lexeme[offset++] = ch;
state=31;
break;
case 'a':
lexeme[offset++] = ch;
state=34;
break;
case 'n':
lexeme[offset++] = ch;
state=38;
break;
default:
if(!isalpha(ch))
fileBuff-=1;
else
lexeme[offset++] = ch;
state = -1;
printf("%d: LEXICAL ERROR: Unknown Pattern %s\n",line,lexeme);
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
break;
}
break;
case 31:
if(ch=='r'){
lexeme[offset++] = ch;
state=32;
}
else{
fileBuff-=1;
state = -1;
printf("%d: LEXICAL ERROR: Unknown Pattern %s\n",line,lexeme);
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
break;
case 32:
if(ch=='.'){
lexeme[offset++] = ch;
state=33;
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
else{
// strcpy(lexeme,"ERROR");
fileBuff-=1;
state = -1;
printf("%d: LEXICAL ERROR: Unknown Pattern %s\n",line,lexeme);
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
break;
case 34:
if(ch=='n'){
lexeme[offset++] = ch;
state=35;
}
else{
// strcpy(lexeme,"ERROR");
fileBuff-=1;
state = -1;
printf("%d: LEXICAL ERROR: Unknown Pattern %s\n",line,lexeme);
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
break;
case 35:
if(ch=='d'){
lexeme[offset++] = ch;
state=36;
}
else{
// strcpy(lexeme,"ERROR");
fileBuff-=1;
state = -1;
printf("%d: LEXICAL ERROR: Unknown Pattern %s\n",line,lexeme);
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
break;
case 36:
if(ch=='.'){
lexeme[offset++] = ch;
state=37;
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
else{
// strcpy(lexeme,"ERROR");
fileBuff-=1;
state = -1;
printf("%d: LEXICAL ERROR: Unknown Pattern %s\n",line,lexeme);
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
break;
case 38:
if(ch=='o'){
lexeme[offset++] = ch;
state=39;
}
else{
// strcpy(lexeme,"ERROR");
fileBuff-=1;
state = -1;
printf("%d: LEXICAL ERROR: Unknown Pattern %s\n",line,lexeme);
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
break;
case 39:
if(ch=='t'){
lexeme[offset++] = ch;
state=40;
}
else{
// strcpy(lexeme,"ERROR");
fileBuff-=1;
state = -1;
printf("%d: LEXICAL ERROR: Unknown Pattern %s\n",line,lexeme);
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
break;
case 40:
if(ch=='.'){
state=41;
lexeme[offset++] = ch;
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
else{
// strcpy(lexeme,"ERROR");
fileBuff-=1;
state = -1;
printf("%d: LEXICAL ERROR: Unknown Pattern %s\n",line,lexeme);
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
break;
case 42:
if(isalpha(ch)){
state=42;
if(tokLen<MAX_LENGTH){
lexeme[offset++] = ch;
tokLen++;
}
else
tokLenErr=1;
}else if(isdigit(ch)){
state=43;
if(tokLen<MAX_LENGTH){
lexeme[offset++] = ch;
tokLen++;
}
else
tokLenErr=1;
*begin = fileBuff- (*fileBuffInit);
if(tokLenErr){
// state = -1;
printf("%d: LEXICAL ERROR: Identifier is longer than the prescribed length '%s...'\n",line,lexeme);
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
return setTokenValue(state,lexeme,line);
}else{
fileBuff-=1;
if(tokLenErr){
// state = -1;
printf("%d: LEXICAL ERROR: Identifier is longer than the prescribed length '%s...'\n",line,lexeme);
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
break;
case 44:
if(isalpha(ch)){
tokLen++;
lexeme[offset++] = ch;
state=45;
}else{
fileBuff-=1;
state = -1;
// strcpy(lexeme,"ERROR");
printf("%d: LEXICAL ERROR: Unknown Pattern %s\n",line,lexeme);
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
break;
case 45:
if(isalpha(ch)||isdigit(ch)){
state=45;
if(tokLen<MAX_LENGTH){
lexeme[offset++] = ch;
tokLen++;
}
else
tokLenErr=1;
}else{
fileBuff-=1;
if(tokLenErr){
// state = -1;
printf("%d: LEXICAL ERROR: Identifier is longer than the prescribed length '%s...'\n",line,lexeme);
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
break;
default:
// strcpy(lexeme,"ERROR");
lexeme[offset++] = ch;
state = -1;
printf("%d: LEXICAL ERROR: Unknown Pattern %s\n",line,lexeme);
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
fileBuff++;
}
state = 1;
*begin = fileBuff- (*fileBuffInit);
return setTokenValue(state,lexeme,line);
}
char *getTokenForIdentifiers(int id,char *name){
if(strcmp(name,"int")==0)
return "INT";
if(strcmp(name,"end")==0)
return "END";
if(strcmp(name,"real")==0)
return "REAL";
if(strcmp(name,"string")==0)
return "STRING";
if(strcmp(name,"matrix")==0)
return "MATRIX";
if(strcmp(name,"if")==0)
return "IF";
if(strcmp(name,"else")==0)
return "ELSE";
if(strcmp(name,"endif")==0)
return "ENDIF";
if(strcmp(name,"read")==0)
return "READ";
if(strcmp(name,"print")==0)
return "PRINT";
if(strcmp(name,"function")==0)
return "FUNCTION";
return "ID";
}
char *getTokenForFunctions(int id,char *name){
if(strcmp(name,"_main")==0)
return "MAIN";
else
return "FUNID";
}
char *getTokenFromId(int id,char * name){
switch(id){
case 0:return "EOF";
case 3:return "COMMENT";
case 4:return "SQO";
case 5:return "SQC";
case 6:return "OP";
case 7:return "CL";
case 8:return "SEMICOLON";
case 9:return "COMMA";
case 10:return "PLUS";
case 11:return "MINUS";
case 12:return "MUL";
case 13:return "DIV";
case 14:return "SIZE";
case 15:return "LT";
case 16:return "LE";
case 17:return "GT";
case 18:return "GE";
case 19:return "ASSIGNOP";
case 20:return "EQ";
case 22:return "NE";
case 23:return "NUM";
case 26:return "RNUM";
case 29:return "STR";
case 33:return "OR";
case 37:return "AND";
case 41:return "NOT";
case 42:
case 43:return getTokenForIdentifiers(id,name);
case 45:return getTokenForFunctions(id,name);
case -1:return "ERROR";
default:return "ERROR";
}
}
void removeComments(char *testFile,char *cleanFile){
int i,j;
for(i=0,j=0;testFile[i]!='\0';i++){
if(testFile[i]=='#'){
while(testFile[i]!='\0' && testFile[i]!='\n')
i++;
i++;
while(testFile[i]!='\0' && (testFile[i]==' ' || testFile[i]=='\t'))
i++;
i--;
}else{
cleanFile[j] = testFile[i];
j++;
}
}
}
|
C
|
#include<math.h>
#include<stdio.h>
int main() {
for(double x = -3.5; x<=3.5; x+=1) {
printf("%g %g\n", x, tgamma(x));
}
return 0;
}
|
C
|
#include<iostream>
#include<stdio.h>
#include<algorithm>
struct point
{
int x;
int y;
};
int cmp(point a,point b)
{
if(a.x!=b.x)return a.x<b.x;
return a.y<b.y;
}
main()
{
int n,i,count;
point a[400];
while(scanf("%d",&n)!=EOF)
{
count=0;
for(i=0;i<n;i++)std::cin>>a[i].x>>a[i].y;
std::sort(a,a+n,cmp);
for(i=0;i<n;i++)
{
while(i<n-1 && a[i].x==a[i+1].x &&a[i].y==a[i+1].y)i++;
count++;
}
printf("%d\n", count);
}
}
|
C
|
#include<stdio.h>
int main()
{
char a[1000];
while(gets(a)!=EOF)
{
printf("%s",a);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "sequence.h"
#include "distance.h"
#include "famille.h"
LISTE * initialiser_liste()
{
LISTE * l = malloc(sizeof(LISTE*)); //On alloue de la mémoire pour une liste et pour une première distance ( qui vaudra 0)
DISTANCE *d = malloc(sizeof(DISTANCE));
if(l == NULL || d == NULL)
{
printf("Pas assez de mémoire pour l ou d \n");
exit(2);
}
l->nombre = 1 ;
d->val = 0.0 ;
d->indiced = 0 ;
d->indiceg = 0 ; //Première distance = "vierge"
d->suiv = NULL ;
l->premier = d ;
return l ;
}
int est_vide(LISTE *l)
{
if(l->nombre == 0 ) //Si la première distance est vierge ou si la liste est vide on renvoie 0 sinon 1
{
//printf("la liste est vide \n");
return 1 ;
}
else
{
return 0 ;
}
}
void liberer_liste(LISTE *l)
{
DISTANCE *e = l->premier ;
while(e != NULL)
{
DISTANCE *e = l->premier ;
DISTANCE *f = e->suiv ;
l->premier = f ;
free(e);
}
free(l);
}
int liste_vide(LISTE *l)
{
if(l->premier == NULL)
{
return 0 ;
}
else
{
return 1 ;
}
}
void push_liste(LISTE *l , float val , int a , int b)
{
if(l == NULL )
{
printf("la liste n'a pas été crée\n");
exit(6);
}
if(l->premier->indiced == 0 && l->premier->indiceg == 0)
{
l->premier->val = val;
l->premier->indiceg = a;
l->premier->indiced = b;
}
else
{
DISTANCE *d = malloc(sizeof(DISTANCE));
if(d == NULL)
{
printf("la distance n'a pas été créée\n");
exit(7);
}
d->val = val;
d->indiceg = a;
d->indiced = b;
d->suiv = l->premier ;
l->premier = d ;
(l->nombre)++ ;
}
}
float pop_liste_place( LISTE *l , int place)
{
float valeur = 0 ;
if(l == NULL)
{
printf("la liste n'a pas été créee\n");
exit(7);
}
DISTANCE *d = l->premier ;
if(place < l->nombre)
{
if(place != 0)
{
for(int i = 1 ; i < place ; i++)
{
d = d->suiv ;
}
DISTANCE *e = d->suiv ;
DISTANCE *f = e->suiv ;
valeur = e->val ;
d->suiv = f ;
free(e);
(l->nombre)--;
}
else
{
DISTANCE *e = d->suiv ;
l->premier = e ;
valeur = d->val ;
(l->nombre)--;
free(d);
}
}
else if(place > l->nombre)
{
printf("la place est en dehors de la liste\n");
}
return valeur ;
}
void ecrire_fichier_liste_fin(LISTE *l , char * argv)
{
FILE *F = fopen(argv,"w");
if(F == NULL)
{
printf("problème d'ouverture de fichier ecriture\n");
exit(3);
}
DISTANCE *d = l->premier ;
fprintf(F,"La liste de distance est [ \n");
while( d != NULL)
{
fprintf(F,"la distance entre les sequences numero %2d et numero %2d est est %f\n",d->indiceg,d->indiced,d->val);
d = d->suiv ;
}
fprintf(F,"]\n");
fprintf(F,"Il y a %d elements dans la liste \n",l->nombre);
fclose(F);
}
void ajouter_fichier_fin(LISTE *l , char * argv)
{
FILE *F = fopen(argv,"a");
if(F == NULL)
{
printf("problème d'ouverture de fichier ecriture\n");
exit(3);
}
DISTANCE *d = l->premier ;
fprintf(F,"La liste de distance est [ \n");
while( d != NULL)
{
fprintf(F,"la distance entre les séquences numéro %2d et numéro %2d est est %f\n",d->indiceg,d->indiced,d->val);
d = d->suiv ;
}
fprintf(F,"]\n");
fprintf(F,"il y a %d éléments.\n",l->nombre);
fclose(F);
}
void afficher_liste(LISTE *l)
{
if( l->nombre == 1)
{
exit(5);
}
DISTANCE *d ; //on entre dans toute la liste
d = l->premier ;
printf("la liste de distance est \n");
printf("[ \n");
while(d != NULL)
{
printf("distance entre les séquences %d et %d : %f \n",d->indiceg,d->indiced,d->val); //on affiche valeur par valeur
d = d->suiv ;
}
printf("]\n");
}
int get_numero_distance(LISTE *l , int indiceg , int indiced)
{
DISTANCE *d = l->premier ;
int cmp = 0;
while(d != NULL)
{
if(d->indiceg == indiceg && d->indiced == indiced) //on cherche le numéro distance entre la séquence numéro indiceg et indiced
{
return cmp ;
}
else
{
d = d->suiv ; // si ce n'est pas le premier on cherche dans toute la liste
(cmp)++;
}
}
printf("la distance cherchée n'existe pas ou plus dans la liste\n");
return 0 ;
}
void supp_numero_seq(LISTE *l , int numero )
{
int indice ;
DISTANCE *e = l->premier ;
while( e != NULL )
{
if(e->indiceg == numero ) //si on trouvre le numéro de la séquence en indice gauche on supprime directement la distance dans la liste
{
indice = get_numero_distance (l,numero,e->indiced);
pop_liste_place(l,indice);
}
if(e->indiced == numero ) //si on trouvre le numéro de la séquence en indice droite on supprime directement la distance dans la liste
{
indice = get_numero_distance (l,e->indiceg,numero);
pop_liste_place(l,indice);
}
e = e->suiv ;
}
}
|
C
|
/*
* dpend_mpfr.c - Arbitrary precision solution to double pendulum ODEs
* using fourth order Runge-Kutta.
*
* Parameters are passed in at the command line:
*
* $./dpend_mpfr.c TH10 W10 TH20 W20 NSTEP
*
* TH10, TH20 - initial angles of the pendulums (degrees)
* W10, W20 - initial angular velocities of the pendulums (degrees per second)
* NSTEP - number of times steps (default step size is h=0.0001)
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gmp.h>
#include <mpfr.h>
#include "dpend.h"
#include "dpend_out.h"
#include "dpend_math.h"
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#include <math.h>
int main(int argc, char *argv[])
{
int NSTEP = atoi(argv[5]);
int mantissa_sz[5] = {113,11,24,53,64};
// int eps[5] = {0, 2^(-11), 2^(-24), 2^(-53), 2^(-64)};
h = pow( atoi(argv[6]), atoi(argv[7]) );
create_output_directory();
output_initial_conditions(argv);
y_t * y_actual;
y_actual = malloc(NSTEP*sizeof(y_t));
//mpfr_t radian_conv;
/* Preform Runga Kutta method to solve the dpend system for each mantissa size. */
for (int j = 0; j < 5; j++) {
mpfr_t t_curr, t_next;
mpfr_t mag, dot, r_error;
y_t yin, yout;
nbits = mantissa_sz[j];
/* Create constant for converting angles to radians. */
//mpfr_init2(h, 113);
// mpfr_set_d(h, 0.001, MPFR_RNDN);
mpfr_t radian_conv;
mpfr_init2(radian_conv, nbits);
//mpfr_const_pi(radian_conv, MPFR_RNDN);
mpfr_set_d(radian_conv, 3.14159, MPFR_RNDN);
mpfr_div_ui(radian_conv, radian_conv, 180, MPFR_RNDN);
mpfr_inits2(113, mag, dot, r_error, NULL);
mpfr_set_d(r_error, 0.0, MPFR_RNDN);
mpfr_inits2(nbits, yin.th1, yin.w1, yin.th2, yin.w2, yout.th1, yout.w1, yout.th2, yout.w2, NULL);
// printf("\nA: underflow: %d overflow: %d div0: %d nanflag: %d inexflag: %d erangeflag: %d\n",
// mpfr_underflow_p(), mpfr_overflow_p(), mpfr_divby0_p(), mpfr_nanflag_p(), mpfr_inexflag_p(), mpfr_erangeflag_p());
/* Create output files to hold results for calculations using nbits. */
create_out_files(mantissa_sz[j]);
/* Initilize and set time values. */
mpfr_inits2(113, t_curr, t_next, NULL);
mpfr_set_d(t_curr, 0.0, MPFR_RNDN);
mpfr_set_d(t_next, 0.0, MPFR_RNDN);
/* Set initial values converting angles to radians. */
mpfr_mul_d(yin.th1, radian_conv, atof(argv[1]), MPFR_RNDN); // th1[0] = TH1*PI/180.0
mpfr_mul_d(yin.w1, radian_conv, atof(argv[2]) , MPFR_RNDN); // w1[0] = W1*PI/180.0
mpfr_mul_d(yin.th2, radian_conv, atof(argv[3]), MPFR_RNDN); // th2[0] = TH2*PI/180.0
mpfr_mul_d(yin.w2, radian_conv, atof(argv[4]) , MPFR_RNDN); // w2[0] = W2*PI/180.0
// printf("B: underflow: %d overflow: %d div0: %d nanflag: %d inexflag: %d erangeflag: %d\n",
// mpfr_underflow_p(), mpfr_overflow_p(), mpfr_divby0_p(), mpfr_nanflag_p(), mpfr_inexflag_p(), mpfr_erangeflag_p());
magnitude(&yin, &mag);
if (nbits != 113) {
dot_product(&yin, &y_actual[0], &dot);
// relative_error(&y_actual[0], &yout, &r_error);
output_mag(&t_curr, &mag, &dot, &r_error);
} else {
y_actual[0] = yin;
output_mag(&t_curr, &mag, NULL, NULL);
}
/* Output initial values. */
output_polar(&t_curr, &yin);
output_cartesian(&t_curr, &yin);
//output_energy(&t_curr, &yin);
printf("Computing %d-bit result... ", nbits); fflush(stdout);
/* Perform the integration. */
for (int i = 1; i < NSTEP; i++) {
mpfr_add_d(t_next, t_curr, h, MPFR_RNDN); // update time
runge_kutta(t_curr, &yin, &yout); // preform runge kutta
/* Print output to files. */
output_polar(&t_next, &yout);
// output_cartesian(&t_next, &yout);
//output_energy(&t_next, &yout);
/* Set yin to yout. */
mpfr_set(yin.th1, yout.th1, MPFR_RNDN);
mpfr_set(yin.w1, yout.w1, MPFR_RNDN);
mpfr_set(yin.th2, yout.th2, MPFR_RNDN);
mpfr_set(yin.w2, yout.w2, MPFR_RNDN);
mpfr_set(t_curr, t_next, MPFR_RNDN);
if (nbits == 113) { y_actual[i] = yin; }
magnitude(&yout, &mag);
if (nbits != 113) {
dot_product(&yout, &y_actual[i], &dot);
relative_error(&y_actual[i], &yout, &r_error);
output_mag(&t_curr, &mag, &dot, &r_error);
} else {
output_mag(&t_curr, &mag, NULL, NULL);
}
}
//mpfr_clear_flags();
printf("Done.\n");
mpfr_clears(radian_conv, NULL);
mpfr_clears(mag, dot, t_curr, t_next, yin.th1, yin.w1, yin.th2, yin.w2,
yout.th1, yout.w1, yout.th2, yout.w2, NULL);
mpfr_free_cache();
/* Close files. */
fclose(polar_output);
fclose(cartesian_output);
fclose(mag_output);
//fclose(energy_output);
}
free(y_actual);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <process.h>
#define NEW (struct node *)malloc(sizeof(struct node))
struct node
{
char name[100],tel[20];
struct node *next;
};
output(struct node *h)//ļֲᣩ
{
struct node *p;
p=h;
if(h==NULL)
{
printf("ͨѶ¼ûд洢Ϣ");
return;
}
printf ("ͨѶ¼б:\n");
while (p!=NULL)
{
printf("%s %s\n",p->name,p->tel);
p=p->next;
}
printf ("ͨѶ¼!\n");
}
struct node *creat()//
{
struct node *p,*q,*h,*q1,*p1,*r;
h=p=q=r=NULL;
char name[20],tel[20];
int i;
printf(":");
gets(name);
while(strlen(name)!=0)
{
p=NEW;
printf("绰:");
gets(tel);
while(1)
{
if(strlen(tel)!=7||strlen(tel)!=11)
{printf("ĺдȷҪ((1)/(0)");
scanf("%d",&i);
if(i)
{strcpy(p->tel,tel);
break;}
if(!i)
{
printf("绰:");
fflush(stdin);
gets(tel);
}}
if(strlen(tel)==7||strlen(tel)==11)
break;
}
strcpy(p->name,name);
strcpy(p->tel,tel);
if(h==NULL)
h=p;
else
q->next=p;
q=p;
printf("ǷҪ룺1,0");
scanf("%d",&i);
getchar();
if(i)
{printf(":");
gets(name);}
if(!i)
break;
}p->next=NULL;
for(p1=h;p1!=NULL;p1=p1->next)
{r=NEW;
for(q1=p1->next;q1!=NULL;q1=q1->next)
{if(strcmp(p1->name,q1->name)>0)
{
strcpy(r->name,p1->name);
strcpy(r->tel,p1->tel);
strcpy(p1->name,q1->name);
strcpy(p1->tel,q1->tel);
strcpy(q1->name,r->name);
strcpy(q1->tel,r->tel);
}
free(r);
if(strcmp(p1->name,q1->name)==0)
;
}
}
return h;
}
modify(struct node *h)//()
{ char name[20],name1[20],tel[20];
struct node *p,*q;
printf("\n:");
gets(name);
for(p=h;p!=NULL;p=p->next)
{
if(!strcmp(name,p->name))
{
printf("\nѲ鵽¼Ϊ");
printf("\n%s,%s",p->name,p->tel);
printf("\n");
gets(name1);
strcpy(p->name,name1);
printf("\nµ绰");
gets(tel);
strcpy(p->tel,tel);
}
if(strcmp(name,p->name)!=0)
printf("\nԲͨѶ¼ûд˵ļ¼");
}
}
delet(struct node *h)//ɾ
{ char name[20];
struct node *p,*q;
printf("\n:");
gets(name);
p=q=h;
while((p->next!=NULL)&&!strcmp(p->name,name))
{
q=p;
p=p->next;
}
q->next=p->next;
free(p);
}
search(struct node *h)//ңɣ
{
int k=0;
char name[20];
struct node *p,*q;
printf("\n:");
gets(name);
for(p=h;p!=NULL;p=p->next)
{if(!strcmp(name,p->name))
{
printf("\n\nѲ鵽¼Ϊ");
printf("\nname:%s\ntel:%s",p->name,p->tel);
k=1;
}
}
if(!k)
printf("\n\nԲͨѶ¼ûд˵ļ¼");
}
append(struct node *h)//
{
char name[20],tel[20];
int i;
struct node *p,*q,*r,*q1;
q=r=q1=NULL;
if(h==NULL)
{printf("ȴͨѶ¼");
return;}
if(h!=NULL)
{ printf("Ҫӵ:");
gets(name);
while(strlen(name)!=0)
{ q=NEW;
strcpy(q->name,name);
printf("绰");
gets(tel);
while(1)
{
if(strlen(tel)!=7||strlen(tel)!=11)
{printf("ĺдȷҪ((1)/(0)");
scanf("%d",&i);
if(i)
{strcpy(q->tel,tel);
break;}
if(!i)
{
printf("绰:");
fflush(stdin);
gets(tel);
}}
if(strlen(tel)==7||strlen(tel)==11)
break;
}
strcpy(q->name,name);
strcpy(q->tel,tel);
for(p=h;p!=NULL;p=p->next)
{if(strcmp(name,h->name)<0)
{
q->next=h;
h=q;
break;
}
if(strcmp(name,p->name)>0&&p->next!=NULL)
{p->next=q;
q->next=p->next->next;
break;}
if(p->next==NULL)
{p->next=q;
q->next=NULL;}}
printf("ǷҪӣ1,0");
scanf("%d",&i);
getchar();
if(i)
{printf(":");
gets(name);}
if(!i)
break;
}}}
main()
{
int m;
struct node *creat();
struct node *h,*h1;
h=NULL;
while(1)
{
printf("\n\t\t*********ӭʹͨѶ¼*********\n\n");
printf("\n\t\t 밴1\n");
printf("\n\t\t ң밴2\n");
printf("\n\t\t ģ밴3\n");
printf("\n\t\t ɾ밴4\n");
printf("\n\t\t ӣ밴5\n");
printf("\n\t\t 밴6\n");
printf("\n\t\t ˳밴0\n");
printf("\n\t\t********************************\n\n");
printf("0~6еһ:");
scanf("%d",&m);
getchar();
if(m>=0&&m<=6)
{
switch(m)
{
case 1: h=creat(h);//
break;
case 2: search(h);//
break;
case 3: modify(h);//
break;
case 4: delet(h);//
break;
case 5: append(h);break;//
case 6:output(h);//
break;
case 0: exit(0);
}
printf("\n\n,");
}
else
printf("\n\nѡ,");
system("pause");
system("cls");
}
} //ʼ˵
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <mpi.h>
#include <sys/time.h>
#include <time.h>
#define MIN 0
#define MAX 5
//Citing Sources: https://www.geeksforgeeks.org/generating-random-number-range-c/
// http://homepages.math.uic.edu/~jan/mcs572/using_mpi.pdf
// http://homepages.math.uic.edu/~jan/mcs572/mcs572notes/lec05.html
int* generateRands(int lower, int upper, int count){
int i;
int *num_array = (int *)malloc(sizeof(int)*count);
if(num_array == NULL){
printf("malloc failed");
exit(1);
}
srand(53);
for(i = 0; i < count; i++){
num_array[i] = (rand() % (upper-lower+1))+lower;
}
return num_array;
}
long long serialSum(long randNums, int *numArray){
int i;
long sum = 0;
for(i=0; i<randNums; i++){
sum += numArray[i];
}
return sum;
}
long long pTopSum(long randNums, int *numArray, int np, int pid, MPI_Status status){
int load = randNums/np;
int excess = randNums % np;
int sum = 0;
int i;
int ptp_sum = 0;
if (pid == 0)
{
for (i = 0; i < load; i++)
{
ptp_sum += numArray[pid*load+i];
}
for(i = 1; i < np; i++){
MPI_Recv(&sum, 1, MPI_INT, i, 1, MPI_COMM_WORLD, &status);
ptp_sum += sum;
}
}else{
if(pid == (np-1)){
for(i = 0; i < (load + excess); i++){
sum += numArray[pid*load+i];
}
}else{
for(i = 0; i < load; i++){
sum += numArray[pid*load+i];
}
}
MPI_Send(&sum, 1, MPI_INT, 0, 1, MPI_COMM_WORLD);
}
if(pid == 0){
return ptp_sum;
}
return 0;
}
long long collectiveSum(long randNums, int *numArray, int np, int pid){
int load = randNums/np;
long long coll_sum = 0;
int i;
int *output = (int*) malloc(sizeof(int)* randNums);
int excess = randNums % np;
if(pid == (np-1)){
for(i = 0; i < (load+excess); i++){
coll_sum += numArray[pid*load+i];
}
}else{
for(i =0; i < load; i++){
coll_sum += numArray[pid*load+i];
}
}
MPI_Reduce(&coll_sum, output, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
if(pid == 0){
return output[0];
}
return 0;
}
int main(int argc, char **argv){
int np, pid;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &pid);
MPI_Comm_size(MPI_COMM_WORLD, &np);
long randNums;
int *numArray;
if(argc != 2){
printf("Invalid number of argument\n");
return 1;
}
randNums = atoi(argv[1]);
randNums *= 100000;
numArray = generateRands(MIN, MAX, randNums);
// SERIAL SUMMATION!
clock_t begin = clock();
if(pid==0){
long long serial = serialSum(randNums, numArray);
printf("The serial sum is %d\n", serial);
clock_t end = clock();
double time_spent = (double)(end - begin);
printf("Time spent in serial: %f\n", (float)time_spent/CLOCKS_PER_SEC);
printf("\n");
}
MPI_Barrier(MPI_COMM_WORLD);
// POINT TO POINT SUMMATION!
clock_t begin1 = clock();
long long ptop = pTopSum(randNums, numArray, np, pid, status);
if(pid==0){
printf("The point to point sum is %d\n", ptop);
clock_t end1 = clock();
double time_spent1 = (double)(end1 - begin1);
printf("Time spent in point to point: %f\n", (float)time_spent1/CLOCKS_PER_SEC);
printf("\n");
}
MPI_Barrier(MPI_COMM_WORLD);
// COLLECTIVE COMMUNICATION SUMMATION!
clock_t begin2 = clock();
long long collSum = collectiveSum(randNums, numArray, np, pid);
if(pid==0){
printf("The collective sum is %d\n", collSum);
clock_t end2 = clock();
double time_spent2 = (double)(end2 - begin2);
printf("Time spent in collective communication: %f\n", (float)time_spent2/CLOCKS_PER_SEC);
}
MPI_Finalize();
return 0;
}
|
C
|
#include "../../src/http/http_headers.h"
#include <stdio.h>
#include "../mocks/mock_socket_connector.h"
#include <criterion/criterion.h>
Test(str2int, happy) {
char str[] = "3451";
int res = str2int(str, strlen(str));
cr_assert(3451 == res, "expected value of 3451, not:%d", res);
}
Test(str2int, empty) {
char str[] = "";
int res = str2int(str, 0);
cr_assert(0 == res, "expected to be 0, not:%d", res);
}
Test(strmncpy, empty) {
char *str = "a line";
char *result = strmncpy(str, 2, 2);
cr_assert(0 == strlen(result), "length not 0 as expected: %lu", strlen(result));
cr_assert(strcmp("", result) == 0, "expected '', not: %s", result);
}
Test(strmncpy, happy) {
char *str = "a non-empty line";
char *result = strmncpy(str, 2, 5);
cr_assert(3 == strlen(result), "length not 3 as expected: %lu", strlen(result));
cr_assert(strcmp("non", result) == 0, "expected 'non', not: %s", result);
}
Test(http_headers_init, should_create_entries) {
http_header_t *header = http_headers_init(NULL);
cr_assert(NULL != header, "Is expected to return a non null value");
for (int i = 0; i < NUM_HTTP_HEADERS; i++) {
cr_assert(NULL != header->headers[i], "Stack at entry %d should not be null", i);
cr_assert(0 == header->headers[i]->num_elems, "Stack at entry %d should be initialized with value 0, not:%d",
i, header->headers[i]->num_elems);
}
}
extern int is_eol (char *ptr, int size);
Test(is_eol, empty) {
char str[] = "";
int res = is_eol(str, 0);
cr_assert(-1 == res, "expected:true, found:%d", res);
}
Test(is_eol, true_1) {
char str[] = "\n";
int res = is_eol(str, 1);
cr_assert(0 != res, "expected:true, found:%d", res);
}
Test(is_eol, true_2) {
char str[] = {0x0A, 0x0D};
int res = is_eol(str, 2);
cr_assert(0 != res, "expected:true, found:%d", res);
}
/*! This test should be modified once we can expand the test accross the buffer boundary
*
*/
Test(is_eol, A_NULL) {
char str[] = {0x0A};
int res = is_eol(str, 1);
cr_assert(1 == res, "expected:false, found:%d", res);
}
Test(is_eol, true_2_reverse) {
char str[] = {0x0D, 0x0A};
int res = is_eol(str, 2);
cr_assert(0 != res, "expected:true, found:%d", res);
}
Test(is_eol, false_1) {
char str[] = " \n";
int res = is_eol(str, 2);
cr_assert(0 == res, "expected:false, found:%d", res);
}
Test(is_eol, false_2) {
char str[] = {0x0D, 0x020};
int res = is_eol(str, 2);
cr_assert(0 == res, "expected:false, found:%d", res);
}
extern char* mock_result_get_buffer[];
extern void skip_eol_if_present (http_header_t *header);
Test(skip_eol_if_present, empty_string) {
char buf[] = "";
mock_result_get_buffer[0] = buf;
circular_buffer_t* cb = new_circular_buffer(3, NULL, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = 0;
http_header_t *header = http_headers_init(cb);
skip_eol_if_present(header);
cr_assert(0 == header->start_of_line.circ_index, "'start_of_line.circ_index' should not have been updated");
cr_assert(0 == header->start_of_line.buff_pos, "'start_of_line.buff_pos' should not have been updated");
cr_assert(0 == header->cur_loc.circ_index, "'cur_loc.circ_index' should not have been updated");
cr_assert(0 == header->cur_loc.buff_pos, "'max_len.buff_pos' should not have been updated");
}
Test(skip_eol_if_present, unix_1) {
char buf[] = "\n";
mock_result_get_buffer[0] = buf;
circular_buffer_t* cb = new_circular_buffer(3, NULL, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = 1;
http_header_t *header = http_headers_init(cb);
skip_eol_if_present(header);
cr_assert(0 == header->start_of_line.circ_index, "'start_of_line.circ_index' expected:0, found:%d", header->start_of_line.circ_index);
cr_assert(1 == header->start_of_line.buff_pos, "'start_of_line.circ_index' expected:1, found:%d", header->start_of_line.buff_pos);
cr_assert(0 == header->cur_loc.circ_index, "'cur_loc.circ_index' should not have been updated");
cr_assert(1 == header->cur_loc.buff_pos, "cur_loc expected:1, found: %d", header->cur_loc.buff_pos);
}
Test(skip_eol_if_present, ms_1) {
char str[] = {0x0A, 0x0D};
mock_result_get_buffer[0] = str;
circular_buffer_t* cb = new_circular_buffer(3, NULL, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = 2;
http_header_t *header = http_headers_init(cb);
skip_eol_if_present(header);
cr_assert(0 == header->start_of_line.circ_index, "'start_of_line.circ_index' expected:0, found:%d", header->start_of_line.circ_index);
cr_assert(2 == header->start_of_line.buff_pos, "start_of_line expected:2, found:%d", header->start_of_line.buff_pos);
cr_assert(0 == header->cur_loc.circ_index, "cur_loc expected:2, found: %d", header->cur_loc.circ_index);
cr_assert(2 == header->cur_loc.buff_pos, "cur_loc expected:2, found: %d", header->cur_loc.buff_pos);
}
Test(skip_eol_if_present, ms_2) {
char str[] = {0x0D, 0x0A};
mock_result_get_buffer[0] = str;
circular_buffer_t* cb = new_circular_buffer(3, NULL, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = 2;
http_header_t *header = http_headers_init(cb);
skip_eol_if_present(header);
cr_assert(0 == header->start_of_line.circ_index, "'start_of_line.circ_index' expected:0, found:%d", header->start_of_line.circ_index);
cr_assert(2 == header->start_of_line.buff_pos, "start_of_line expected:2, found:%d", header->start_of_line.buff_pos);
cr_assert(0 == header->cur_loc.circ_index, "cur_loc expected:2, found: %d", header->cur_loc.circ_index);
cr_assert(2 == header->cur_loc.buff_pos, "cur_loc expected:2, found: %d", header->cur_loc.buff_pos);
}
Test(skip_eol_if_present, ms_3) {
char str[] = {0x0A, 0x20, 0x0D};
mock_result_get_buffer[0] = str;
circular_buffer_t* cb = new_circular_buffer(3, NULL, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = 3;
http_header_t *header = http_headers_init(cb);
skip_eol_if_present(header);
cr_assert(0 == header->start_of_line.circ_index, "'start_of_line.circ_index' should not have been updated");
cr_assert(1 == header->start_of_line.buff_pos, "'start_of_line.buff_pos' should not have been updated:%d", header->start_of_line.buff_pos);
cr_assert(0 == header->cur_loc.circ_index, "'cur_loc.circ_index' should not have been updated");
cr_assert(1 == header->cur_loc.buff_pos, "'max_len.buff_pos' should not have been updated");
}
Test(skip_eol_if_present, ms_4) {
char str[] = {0x0D, 0x20, 0x0A};
mock_result_get_buffer[0] = str;
circular_buffer_t* cb = new_circular_buffer(3, NULL, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = 3;
http_header_t *header = http_headers_init(cb);
skip_eol_if_present(header);
cr_assert(0 == header->start_of_line.circ_index, "'start_of_line.circ_index' should not have been updated");
cr_assert(0 == header->start_of_line.buff_pos, "'start_of_line.buff_pos' should not have been updated:%d", header->start_of_line.buff_pos);
cr_assert(0 == header->cur_loc.circ_index, "'cur_loc.circ_index' should not have been updated");
cr_assert(0 == header->cur_loc.buff_pos, "'max_len.buff_pos' should not have been updated");
}
Test(skip_eol_if_present, unix_2) {
char str[] = " \n";
mock_result_get_buffer[0] = str;
circular_buffer_t* cb = new_circular_buffer(3, NULL, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = 2;
http_header_t *header = http_headers_init(cb);
skip_eol_if_present(header);
cr_assert(0 == header->start_of_line.circ_index, "'start_of_line.circ_index' should not have been updated");
cr_assert(0 == header->start_of_line.buff_pos, "'start_of_line.buff_pos' should not have been updated");
cr_assert(0 == header->cur_loc.circ_index, "'cur_loc.circ_index' should not have been updated");
cr_assert(0 == header->cur_loc.buff_pos, "'max_len.buff_pos' should not have been updated");
}
extern circular_buffer_t* mock_create_circular_buffer (char** data, int size);
Test(http_headers_add, happy) {
char data[] = {"Server:value\n"};
mock_result_get_buffer[0] = data;
circular_buffer_t* cb = new_circular_buffer(3, NULL, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = strlen(data);
http_header_t *header = http_headers_init(cb);
header->last_semicolon.circ_index = 0;
header->last_semicolon.buff_pos = 6;
header->cur_loc.circ_index = 0;
header->cur_loc.buff_pos = 12;
http_headers_add(header);
char* v = str_stack_2_formatted_line(header->headers[HTTP_SERVER]); //NOTE: returns single-quoted elements
int size = stack_depth(header->headers[HTTP_SERVER]);
cr_assert(1 == size, "expected 1 element at HTTP_SERVER(57), not:%d", size);
cr_assert(strcmp("'value'", v) == 0, "Expected 'value', not:%s", v);
}
Test(http_headers_add, non_existing) {
char data[] = {"funny:value"};
mock_result_get_buffer[0] = data;
circular_buffer_t* cb = new_circular_buffer(3, NULL, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = strlen(data);
http_header_t *header = http_headers_init(cb);
header->last_semicolon.circ_index = 0;
header->last_semicolon.buff_pos = 5;
header->cur_loc.circ_index = 0;
header->cur_loc.buff_pos = 11;
http_headers_add(header);
}
int mock_called_feeder;
int mock_result_feeder[100];
int mock_feeder(void* params, char* buffer, int size)
{
mock_called_feeder += 1;
return mock_result_feeder[mock_called_feeder-1];
}
extern int is_ptr_pointing_to_eol_or_eos (circular_buffer_t* cb, circular_ptr_t* ptr, circular_ptr_t* max_len);
Test (is_ptr_pointing_to_eol_or_eos, empty_buffer)
{
char data[] = "";
mock_result_get_buffer[0] = data;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = 0;
cb->next_to_be_received = 1;
mock_result_feeder[0] = 0;
mock_called_feeder = 0;
circular_ptr_t from;
from.circ_index = 0;
from.buff_pos = 0;
circular_ptr_t to;
to.circ_index = 0;
to.buff_pos = 0;
int is_eol = is_ptr_pointing_to_eol_or_eos (cb, &from, &to);
cr_assert (is_eol, "An empty string and no next one is an EOL. Result was:%d", is_eol);
cr_assert (mock_called_feeder == 1, "Feeder should have been called once, not:%d", mock_called_feeder);
}
Test (is_ptr_pointing_to_eol_or_eos, big_buffer_full_of_spaces)
{
char data[] = " ";
mock_result_get_buffer[0] = data;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = strlen(data);
cb->next_to_be_received = 1;
mock_result_feeder[0] = 0;
mock_called_feeder = 0;
circular_ptr_t from;
from.circ_index = 0;
from.buff_pos = 0;
circular_ptr_t to;
to.circ_index = 0;
to.buff_pos = strlen(data);
int is_eol = is_ptr_pointing_to_eol_or_eos (cb, &from, &to);
cr_assert (!is_eol, "An empty string and no next one is an EOL. Result was:%d", is_eol);
cr_assert (mock_called_feeder == 0, "Feeder should should have been called, not:%d", mock_called_feeder);
}
Test (is_ptr_pointing_to_eol_or_eos, big_buffer_with_eol)
{
char data[] = " \n";
mock_result_get_buffer[0] = data;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = strlen(data);
cb->next_to_be_received = 1;
mock_result_feeder[0] = 0;
mock_called_feeder = 0;
circular_ptr_t from;
from.circ_index = 0;
from.buff_pos = 0;
circular_ptr_t to;
to.circ_index = 0;
to.buff_pos = strlen(data);
int is_eol = is_ptr_pointing_to_eol_or_eos (cb, &from, &to);
cr_assert (!is_eol, "An empty string and no next one is an EOL. Result was:%d", is_eol);
cr_assert (mock_called_feeder == 0, "Feeder should should have been called, not:%d", mock_called_feeder);
}
Test (is_ptr_pointing_to_eol_or_eos, buffer_size_1_with_CR_no_next_line)
{
char data[] = "\n";
mock_result_get_buffer[0] = data;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = strlen(data);
cb->next_to_be_received = 1;
mock_result_feeder[0] = 0;
mock_called_feeder = 0;
circular_ptr_t from;
from.circ_index = 0;
from.buff_pos = 0;
circular_ptr_t to;
to.circ_index = 0;
to.buff_pos = strlen(data);
int is_eol = is_ptr_pointing_to_eol_or_eos (cb, &from, &to);
cr_assert (is_eol, "An empty string and no next one is an EOL. Result was:%d", is_eol);
cr_assert (mock_called_feeder == 1, "Feeder should have been called once, not:%d", mock_called_feeder);
}
int mock_result_alloc_buffer;
Test (is_ptr_pointing_to_eol_or_eos, buffer_size_1_with_CR_and_next_line)
{
char line1[] = "\n";
char line2[] = " ";
mock_result_get_buffer[0] = line1;
mock_result_get_buffer[1] = line2;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = strlen(line1);
cb->next_to_be_received = 1;
mock_result_alloc_buffer = 1;
mock_result_feeder[0] = 0;
mock_called_feeder = 0;
circular_ptr_t from;
from.circ_index = 0;
from.buff_pos = 0;
circular_ptr_t to;
to.circ_index = 0;
to.buff_pos = strlen(line1);
int is_eol = is_ptr_pointing_to_eol_or_eos (cb, &from, &to);
cr_assert (is_eol, "An empty string and no next one is an EOL. Result was:%d", is_eol);
cr_assert (1 == mock_called_feeder, "feeder should not have been called (done pre-emptively)");
}
extern int mock_called_get_buffer;
Test (is_ptr_pointing_to_eol_or_eos, buffer_size_2_with_NL_CR)
{
char data[] = {0x0A, 0x0D};
mock_result_get_buffer[0] = data;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = 2;
cb->next_to_be_received = 1;
mock_result_feeder[0] = 0;
mock_called_feeder = 0;
mock_called_get_buffer = 0;
circular_ptr_t from;
from.circ_index = 0;
from.buff_pos = 0;
circular_ptr_t to;
to.circ_index = 0;
to.buff_pos = strlen(data);
int is_eol = is_ptr_pointing_to_eol_or_eos (cb, &from, &to);
cr_assert(1 == mock_called_get_buffer, "Should have get data from mocked shared buffer");
cr_assert (is_eol, "A 2-bytes eol. Result was:%d", is_eol);
}
Test (is_ptr_pointing_to_eol_or_eos, buffer_size_1_with_NL_and_CR_on_next_buffer)
{
char line1[] = {0x0A};
char line2[] = {0x0D};
mock_result_get_buffer[0] = line1;
mock_result_get_buffer[1] = line2;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = 1;
cb->next_to_be_received = 1;
mock_result_alloc_buffer = 1;
mock_result_feeder[0] = 1;
mock_result_feeder[1] = 0;
mock_called_feeder = 0;
circular_ptr_t from;
from.circ_index = 0;
from.buff_pos = 0;
circular_ptr_t to;
to.circ_index = 0;
to.buff_pos = strlen(line1);
int is_eol = is_ptr_pointing_to_eol_or_eos (cb, &from, &to);
cr_assert (is_eol, "a 2-butes eol split between 2 buffers. Result was:%d", is_eol);
cr_assert (1 == mock_called_feeder, "feeder should have been called");
}
Test (is_ptr_pointing_to_eol_or_eos, buffer_size_1_with_NL_and_no_next_buffer)
{
char line1[] = {0x0D};
mock_result_get_buffer[0] = line1;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = 1;
cb->next_to_be_received = 1;
mock_result_alloc_buffer = 1;
mock_result_feeder[0] = 0;
mock_called_feeder = 0;
circular_ptr_t from;
from.circ_index = 0;
from.buff_pos = 0;
circular_ptr_t to;
to.circ_index = 0;
to.buff_pos = strlen(line1);
int is_eol = is_ptr_pointing_to_eol_or_eos (cb, &from, &to);
cr_assert (!is_eol, "an incomplete 2-butes eol . Result was:%d", is_eol);
cr_assert (1 == mock_called_feeder, "feeder should have been called");
}
extern int mock_called_alloc_buffer;
Test (get_next_line, null)
{
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
http_header_t *header = http_headers_init(cb);
mock_called_alloc_buffer = 0;
mock_called_feeder = 0;
mock_result_feeder[0] = 0;
mock_result_get_buffer[1] = "";
get_next_line(header);
cr_assert(1 <= mock_called_alloc_buffer, "Should initiate read into next buffer. Expected 1, not:%d", mock_called_alloc_buffer);
cr_assert(0 == header->cur_loc.buff_pos,"No character read, expect 0, not:%d", header->cur_loc.buff_pos);
}
Test(get_next_line, semicolon_true)
{
char str[] = "key:value";
mock_result_get_buffer[0] = str;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = strlen(str);
cb->next_to_be_received = 1;
mock_result_feeder[0] = 0;
mock_called_feeder = 0;
http_header_t *header = http_headers_init(cb);
header->max_len.circ_index = 0;
header->max_len.buff_pos = strlen(str);
mock_called_alloc_buffer = 0;
mock_result_alloc_buffer = 1;
get_next_line(header);
cr_assert(3 == header->last_semicolon.buff_pos, "not the expected position for semicolon(buf_pos): %d", header->last_semicolon.buff_pos);
cr_assert(0 == header->last_semicolon.circ_index, "not the expected position for semicolon(circ_index: %d", header->last_semicolon.circ_index);
cr_assert(1 <= mock_called_alloc_buffer, "'alloc_buffer' should have been called");
cr_assert (1 <= mock_called_feeder, "feeder should have been called");
}
Test(get_next_line, semicolon_false)
{
char str[] = "keyvalue";
mock_result_get_buffer[0] = str;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = strlen(str);
cb->next_to_be_received = 1;
mock_result_feeder[0] = 0;
mock_called_feeder = 0;
http_header_t *header = http_headers_init(cb);
header->max_len.circ_index = 0;
header->max_len.buff_pos = strlen(str);
mock_called_alloc_buffer = 0;
mock_result_alloc_buffer = 1;
get_next_line(header);
cr_assert(-1 == header->last_semicolon.buff_pos, "not the expected position for semicolon: %d", header->last_semicolon.buff_pos);
cr_assert(-1 == header->last_semicolon.circ_index, "not the expected position for semicolon: %d", header->last_semicolon.circ_index);
cr_assert(1 <= mock_called_alloc_buffer, "'alloc_buffer' should have been called");
cr_assert (1 <= mock_called_feeder, "feeder should have been called");
cr_assert(0 == header->start_of_line.circ_index, "start_of_line should not have changed(circ_index): %d", header->start_of_line.circ_index);
cr_assert(0 == header->start_of_line.buff_pos, "start_of_line should not have changed(buff_pos): %d", header->start_of_line.buff_pos);
cr_assert(0 == header->cur_loc.circ_index, "end of line not as expected(circ_index): %d", header->cur_loc.circ_index);
cr_assert(8 == header->cur_loc.buff_pos, "end of line not as expected(buff_pos): %d", header->cur_loc.buff_pos);
}
Test(get_next_line, 2_lines_1_buffer)
{
char str[] = "line1\nline2";
mock_result_get_buffer[0] = str;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = 11;
cb->next_to_be_received = 1;
mock_result_feeder[0] = 0;
mock_called_feeder = 0;
http_header_t *header = http_headers_init(cb);
header->max_len.circ_index = 0;
header->max_len.buff_pos = 11;
mock_called_alloc_buffer = 0;
mock_result_alloc_buffer = 1;
get_next_line(header);
get_next_line(header);
cr_assert(0 == header->start_of_line.circ_index, "start_of_line should not have changed(circ_index): %d", header->start_of_line.circ_index);
cr_assert(6 == header->start_of_line.buff_pos, "start_of_line should not have changed(buff_pos): %d", header->start_of_line.buff_pos);
cr_assert(0 == header->cur_loc.circ_index, "end of line not as expected: %d", header->cur_loc.circ_index);
cr_assert(11 == header->cur_loc.buff_pos, "end of line not as expected: %d", header->cur_loc.buff_pos);
}
Test(get_next_line, 3_lines_1_buffer)
{
char str[] = "first line\nsecond line\nthird line";
mock_result_get_buffer[0] = str;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = 33;
cb->next_to_be_received = 1;
mock_result_feeder[0] = 0;
mock_called_feeder = 0;
http_header_t *header = http_headers_init(cb);
header->max_len.circ_index = 0;
header->max_len.buff_pos = 33;
mock_called_alloc_buffer = 0;
mock_result_alloc_buffer = 1;
get_next_line(header);
get_next_line(header);
get_next_line(header);
cr_assert(0 == header->start_of_line.circ_index, "start_of_line should not have changed(circ_index): %d", header->start_of_line.circ_index);
cr_assert(23 == header->start_of_line.buff_pos, "start_of_line should not have changed(buff_pos): %d", header->start_of_line.buff_pos);
cr_assert(0 == header->cur_loc.circ_index, "end of line not as expected: %d", header->cur_loc.circ_index);
cr_assert(33 == header->cur_loc.buff_pos, "end of line not as expected: %d", header->cur_loc.buff_pos);
}
Test(get_next_line, 2_CR_1_buffer)
{
char str[] = "\n\nthird line";
mock_result_get_buffer[0] = str;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = 12;
cb->next_to_be_received = 1;
mock_result_feeder[0] = 0;
mock_called_feeder = 0;
http_header_t *header = http_headers_init(cb);
header->max_len.circ_index = 0;
header->max_len.buff_pos = 12;
mock_called_alloc_buffer = 0;
mock_result_alloc_buffer = 1;
get_next_line(header);
get_next_line(header);
get_next_line(header);
cr_assert(0 == header->start_of_line.circ_index, "start_of_line should not have changed(circ_index): %d", header->start_of_line.circ_index);
cr_assert(2 == header->start_of_line.buff_pos, "start_of_line should not have changed(buff_pos): %d", header->start_of_line.buff_pos);
cr_assert(0 == header->cur_loc.circ_index, "end of line not as expected: %d", header->cur_loc.circ_index);
cr_assert(12 == header->cur_loc.buff_pos, "end of line not as expected: %d", header->cur_loc.buff_pos);
}
Test(get_next_line, special_char)
{
char str[] = "Content-Type: text/html; charset=UTF-8";
mock_result_get_buffer[0] = str;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = strlen(str);
cb->next_to_be_received = 1;
mock_result_feeder[0] = 0;
mock_called_feeder = 0;
http_header_t *header = http_headers_init(cb);
header->max_len.circ_index = 0;
header->max_len.buff_pos = strlen(str);
mock_called_alloc_buffer = 0;
mock_result_alloc_buffer = 1;
get_next_line(header);
cr_assert(12 == header->last_semicolon.buff_pos, "not the expected position for semicolon: %d", header->last_semicolon.buff_pos);
cr_assert(0 == header->last_semicolon.circ_index, "not the expected position for semicolon: %d", header->last_semicolon.circ_index);
cr_assert(1 <= mock_called_alloc_buffer, "'alloc_buffer' should have been called");
cr_assert (1 <= mock_called_feeder, "feeder should have been called");
}
//TODO write get_next_line with line split over 2, 3 reads from socket
Test(get_next_line, read_from_socket)
{
char str1[] = " charset=UTF-8";
char str2[] = "Content-Type: text/html;";
mock_result_get_buffer[0] = str2;
mock_result_get_buffer[1] = str1;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = strlen(str2);
cb->next_to_be_received = 1;
mock_result_alloc_buffer = 1;
mock_result_feeder[0] = strlen(str1);
mock_result_feeder[1] = 0;
mock_called_feeder = 0;
http_header_t *header = http_headers_init(cb);
header->max_len.circ_index = 0;
header->max_len.buff_pos = strlen(str2);
mock_called_alloc_buffer = 0;
get_next_line(header);
cr_assert(12 == header->last_semicolon.buff_pos, "not the expected position for semicolon: %d", header->last_semicolon.buff_pos);
cr_assert(0 == header->last_semicolon.circ_index, "not the expected position for semicolon: %d", header->last_semicolon.circ_index);
cr_assert(1 <= mock_called_alloc_buffer, "'alloc_buffer' should have been called");
cr_assert (1 <= mock_called_feeder, "feeder should have been called");
}
Test(get_next_line, split_header)
{
char str1[] = "ype: text/html; charset=UTF-8";
char str2[] = "Content-T";
mock_result_get_buffer[0] = str2;
mock_result_get_buffer[1] = str1;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = strlen(str2);
cb->next_to_be_received = 1;
mock_result_feeder[0] = strlen(str1);
mock_result_feeder[1] = 0;
mock_called_feeder = 0;
http_header_t *header = http_headers_init(cb);
header->max_len.circ_index = 0;
header->max_len.buff_pos = strlen(str2);
mock_called_alloc_buffer = 0;
get_next_line(header);
cr_assert(3 == header->last_semicolon.buff_pos, "not the expected position for semicolon.buff_pos: %d", header->last_semicolon.buff_pos);
cr_assert(1 == header->last_semicolon.circ_index, "not the expected position for semicolon.circ_index: %d", header->last_semicolon.circ_index);
cr_assert(1 <= mock_called_alloc_buffer, "'alloc_buffer' should have been called");
cr_assert (1 <= mock_called_feeder, "feeder should have been called");
}
Test(get_next_line, 3_lines_read)
{
char str1[] = " charset=UTF-8\nAccept-Language:value1";
char str2[] = "ype: text/html;";
char str3[] = "Content-T";
mock_result_get_buffer[0] = str3;
mock_result_get_buffer[1] = str2;
mock_result_get_buffer[2] = str1;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = strlen(str3);
cb->next_to_be_received = 1;
mock_result_feeder[0] = strlen(str2);
mock_result_feeder[1] = strlen(str1);
mock_result_feeder[2] = 0;
mock_called_feeder = 0;
http_header_t *header = http_headers_init(cb);
header->max_len.circ_index = 0;
header->max_len.buff_pos = strlen(str3);
mock_called_alloc_buffer = 0;
get_next_line(header);
cr_assert(3 == header->last_semicolon.buff_pos, "not the expected position for semicolon.buff_pos: %d", header->last_semicolon.buff_pos);
cr_assert(1 == header->last_semicolon.circ_index, "not the expected position for semicolon.circ_index: %d", header->last_semicolon.circ_index);
cr_assert(1 <= mock_called_alloc_buffer, "'alloc_buffer' should have been called");
cr_assert (1 <= mock_called_feeder, "feeder should have been called");
cr_assert(2 == header->cur_loc.circ_index, "Expected 'curr_loc.circ_index' to be 2, not:%d", header->cur_loc.circ_index);
cr_assert(14 == header->cur_loc.buff_pos, "Expected 'curr_loc.buff_pos' to be 14, not:%d", header->cur_loc.buff_pos);
}
Test(header_strlen, 1_line) {
char str[] = "a line";
mock_result_get_buffer[0] = str;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = strlen(str);
cb->next_to_be_received = 1;
mock_result_feeder[0] = 0;
mock_called_feeder = 0;
http_header_t *header = http_headers_init(cb);
mock_called_alloc_buffer = 0;
mock_result_alloc_buffer = 1;
get_next_line(header);
int i = header_strlen(header);
cr_assert(6 == i, "Not the expected length: %d", i);
}
Test(header_strlen, 1_line_cr) {
char str[] = "a line\n";
mock_result_get_buffer[0] = str;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = 7;
cb->next_to_be_received = 1;
mock_result_feeder[0] = 0;
mock_called_feeder = 0;
http_header_t *header = http_headers_init(cb);
mock_called_alloc_buffer = 0;
mock_result_alloc_buffer = 1;
get_next_line(header);
int i = header_strlen(header);
cr_assert(6 == i, "Not the expected length: %d", i);
}
Test(header_strlen, 1_line_cr_2) {
char str[] = {'a', ' ', 'l', 'i', 'n', 'e', 0x0A, 0x0D};
mock_result_get_buffer[0] = str;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = 7;
cb->next_to_be_received = 1;
mock_result_feeder[0] = 0;
mock_called_feeder = 0;
http_header_t *header = http_headers_init(cb);
mock_called_alloc_buffer = 0;
mock_result_alloc_buffer = 1;
get_next_line(header);
int i = header_strlen(header);
cr_assert(6 == i, "Not the expected length: %d", i);
}
Test(header_strlen, 2_lines_cr) {
char str[] = "a line\nsecond line";
mock_result_get_buffer[0] = str;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = 18;
cb->next_to_be_received = 1;
mock_result_feeder[0] = 0;
mock_called_feeder = 0;
http_header_t *header = http_headers_init(cb);
mock_called_alloc_buffer = 0;
mock_result_alloc_buffer = 1;
get_next_line(header);
get_next_line(header);
int i = header_strlen(header);
cr_assert(11 == i, "Not the expected length: %d", i);
}
Test(header_strlen, 2_line_scr_2) {
char str[] = {'a', ' ', 'l', 'i', 'n', 'e', 0x0A, 0x0D, 's', 'e', 'c', 'o', 'n', 'd', ' ', 'l', 'i', 'n', 'e'};
mock_result_get_buffer[0] = str;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = 19;
cb->next_to_be_received = 1;
mock_result_feeder[0] = 0;
mock_called_feeder = 0;
http_header_t *header = http_headers_init(cb);
mock_called_alloc_buffer = 0;
mock_result_alloc_buffer = 1;
get_next_line(header);
get_next_line(header);
int i = header_strlen(header);
cr_assert(11 == i, "Not the expected length: %d", i);
}
Test(header_strlen, 2_lines_empty_line) {
char str[] = {'a', ' ', 'l', 'i', 'n', 'e', 0x0A, 0x0D, 0x0A, 0x0D, 's', 'e', 'c', 'o', 'n', 'd', ' ', 'l', 'i',
'n', 'e'};
mock_result_get_buffer[0] = str;
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
cb->buffers[0] = 0;
cb->data_sizes[0] = 21;
cb->next_to_be_received = 1;
mock_result_feeder[0] = 0;
mock_called_feeder = 0;
http_header_t *header = http_headers_init(cb);
mock_called_alloc_buffer = 0;
mock_result_alloc_buffer = 1;
get_next_line(header);
get_next_line(header);
int i = header_strlen(header);
cr_assert(0 == i, "Not the expected length: %d", i);
}
Test(body_length, not_present) {
circular_buffer_t* cb = new_circular_buffer(3, NULL, NULL, 1024);
http_header_t *header = http_headers_init(cb);
int result = decode_body_length(header);
cr_assert(0 == result, "expected 0 if field not present, not:%d", result);
}
Test(body_length, happy) {
circular_buffer_t* cb = new_circular_buffer(3, NULL, NULL, 1024);
http_header_t *header = http_headers_init(cb);
str_stack_push(header->headers[HTTP_CONTENT_LENGTH], "32");
int result = decode_body_length(header);
cr_assert(32 == result, "expected 32, not:%d", result);
}
Test(decode_http_headers, empty_0)
{
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
http_header_t *header = http_headers_init(cb);
mock_called_alloc_buffer = 0;
mock_called_feeder = 0;
mock_result_feeder[0] = 0;
mock_result_get_buffer[1] = "";
decode_http_headers(header);
cr_assert(2 == mock_called_feeder, "Feed function should have been called");
}
Test(decode_http_headers, empty_1)
{
char str[] = "HTTP 1/1 GET\n";
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
http_header_t *header = http_headers_init(cb);
mock_called_alloc_buffer = 0;
mock_called_feeder = 0;
mock_result_feeder[0] = 13;
mock_result_get_buffer[1] = str;
decode_http_headers(header);
cr_assert(2 == mock_called_feeder, "Feed function should have been called");
}
Test(decode_http_headers, happy_1)
{
char str[] = "HTTP 1/1 GET\nAccept: Apple\nServer: localhost\n\n<html>\n";
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
http_header_t *header = http_headers_init(cb);
mock_called_alloc_buffer = 0;
mock_called_feeder = 0;
mock_result_feeder[0] = 53;
mock_result_get_buffer[1] = str;
decode_http_headers(header);
int size = stack_depth(header->headers[HTTP_ACCEPT]);
cr_assert(1 == size, "expected 'Accept' in headers");
size = stack_depth(header->headers[HTTP_SERVER]);
cr_assert(1 == size, "expected 'Server' in headers");
}
Test(http_headers, get_empty)
{
circular_buffer_t* cb = new_circular_buffer(3, NULL, NULL, 1024);
http_header_t *header = http_headers_init(cb);
stack_head_t *empty = http_headers_get(header, 3);
cr_assert(is_stack_empty(empty), "expected to return NULL on prop not found");
http_headers_free(header); //TODO should be propagated
}
Test(decode_http_header, parse_retrieve)
{
char msg[] = "HTTP/1.1 200 OK\nDate: Mon, 23 May 2005 22:38:34 GMT\nContent-Type: text/html; charset=UTF-8\nContent-Length: 14\nLast-Modified: Wed, 08 Jan 2003 23:11:55 GMT\nServer: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)\nETag: \"3f80f-1b6-3e1cb03b\"\nAccept-Ranges: bytes\n\n<html>\n</html>";
circular_buffer_t* cb = new_circular_buffer(3, mock_feeder, NULL, 1024);
http_header_t *header = http_headers_init(cb);
mock_called_alloc_buffer = 0;
mock_called_feeder = 0;
mock_result_feeder[0] = 264;
mock_result_get_buffer[1] = msg;
decode_http_headers(header);
stack_head_t *vals = http_headers_get(header, HTTP_CONTENT_TYPE);
printf("%s\n", http_headers_to_string(header));
cr_assert(vals->num_elems == 1, "expected to have 1 element for Content-Type, not: %d", vals->num_elems);
char *value = str_stack_pop(vals);
cr_assert(strcmp("text/html; charset=UTF-8", value) == 0, "expected value 'text/html; charset=UTF-8', not '%s'",
value);
cr_assert(14 == decode_body_length(header), "Body length not as expected:%d", decode_body_length(header));
free(value);
http_headers_free(header);
}
Test(http_headers, constants_sorted) {
for (int i = 0; i < 80; i++) {
cr_assert(strcmp(HTTP_HEADER_STRINGS[i], HTTP_HEADER_STRINGS[i + 1]) < 0, "Not sorted at %d", i);
}
}
Test(http_headers, search_1) {
int pos = find_header_index("Trailer");
cr_assert(pos == HTTP_TRAILER, "'Trailer' not at expected position:%d", HTTP_TRAILER);
}
Test(http_headers, search_first) {
int pos = find_header_index("Accept");
cr_assert(pos == HTTP_ACCEPT, "first element in array 'Accept' not at expected position:%d", pos);
}
Test(http_headers, search_before_first) {
int pos = find_header_index("A");
cr_assert(pos < 0, "element before first in array not returning expected position:%d", pos);
}
Test(http_headers, search_last) {
int pos = find_header_index("X-XSS-Protection");
cr_assert(pos == HTTP_X_XSS_PROTECTION, "last element in array 'X-XSS-Protection' not at expected position:%d",
pos);
}
Test(http_headers, search_after_last) {
int pos = find_header_index("Z");
cr_assert(pos < 0, "element after last in array not returning expected position:%d", pos);
}
Test(http_headers, search_not_found) {
int pos = find_header_index("MMM");
cr_assert(pos < 0, "string 'MMM' should not be found, instead returned:%d", pos);
}
Test(http_headers, accept_charset) {
cr_assert(strcmp("Accept-Charset", HTTP_HEADER_STRINGS[HTTP_ACCEPT_CHARSET]) == 0,
"Expected 'Accept-Charset', not:%s", HTTP_HEADER_STRINGS[HTTP_ACCEPT_CHARSET]);
}
Test(http_headers, accept) {
cr_assert(strcmp("Accept", HTTP_HEADER_STRINGS[HTTP_ACCEPT]) == 0,
"Expected 'Accept', not:%s", HTTP_HEADER_STRINGS[HTTP_ACCEPT]);
}
Test(http_headers, accept_encoding) {
cr_assert(strcmp("Accept-Encoding", HTTP_HEADER_STRINGS[HTTP_ACCEPT_ENCODING]) == 0,
"Expected 'Accept-Encoding', not:%s", HTTP_HEADER_STRINGS[HTTP_ACCEPT_ENCODING]);
}
Test(http_headers, accept_language) {
cr_assert(strcmp("Accept-Language", HTTP_HEADER_STRINGS[HTTP_ACCEPT_LANGUAGE]) == 0,
"Expected 'Accept-Language', not:%s", HTTP_HEADER_STRINGS[HTTP_ACCEPT_LANGUAGE]);
}
Test(http_headers, accept_ranges) {
cr_assert(strcmp("Accept-Ranges", HTTP_HEADER_STRINGS[HTTP_ACCEPT_RANGES]) == 0,
"Expected 'Accept-Ranges', not:%s", HTTP_HEADER_STRINGS[HTTP_ACCEPT_RANGES]);
}
Test(http_headers, access_control_allow_credentials) {
cr_assert(
strcmp("Access-Control-Allow-Credentials", HTTP_HEADER_STRINGS[HTTP_ACCESS_CONTROL_ALLOW_CREDENTIALS]) == 0,
"Expected 'Access-Control-Allow-Credentials', not:%s",
HTTP_HEADER_STRINGS[HTTP_ACCESS_CONTROL_ALLOW_CREDENTIALS]);
}
Test(http_headers, access_control_allow_headers) {
cr_assert(strcmp("Access-Control-Allow-Headers", HTTP_HEADER_STRINGS[HTTP_ACCESS_CONTROL_ALLOW_HEADERS]) == 0,
"Expected 'Access-Control-Allow-Headers', not:%s",
HTTP_HEADER_STRINGS[HTTP_ACCESS_CONTROL_ALLOW_HEADERS]);
}
Test(http_headers, access_control_allow_methods) {
cr_assert(strcmp("Access-Control-Allow-Methods", HTTP_HEADER_STRINGS[HTTP_ACCESS_CONTROL_ALLOW_METHODS]) == 0,
"Expected 'Access-Control-Allow-Methods', not:%s",
HTTP_HEADER_STRINGS[HTTP_ACCESS_CONTROL_ALLOW_METHODS]);
}
Test(http_headers, access_control_allow_origin) {
cr_assert(strcmp("Access-Control-Allow-Origin", HTTP_HEADER_STRINGS[HTTP_ACCESS_CONTROL_ALLOW_ORIGIN]) == 0,
"Expected 'Access-Control-Allow-Origin', not:%s", HTTP_HEADER_STRINGS[HTTP_ACCESS_CONTROL_ALLOW_ORIGIN]);
}
Test(http_headers, access_control_expose_headers) {
cr_assert(strcmp("Access-Control-Expose-Headers", HTTP_HEADER_STRINGS[HTTP_ACCESS_CONTROL_EXPOSE_HEADERS]) == 0,
"Expected 'Access-Control-Expose-Headers', not:%s",
HTTP_HEADER_STRINGS[HTTP_ACCESS_CONTROL_EXPOSE_HEADERS]);
}
Test(http_headers, access_control_max_age) {
cr_assert(strcmp("Access-Control-Max-Age", HTTP_HEADER_STRINGS[HTTP_ACCESS_CONTROL_MAX_AGE]) == 0,
"Expected 'Access-Control-Max-Age', not:%s", HTTP_HEADER_STRINGS[HTTP_ACCESS_CONTROL_MAX_AGE]);
}
Test(http_headers, access_control_request_headers) {
cr_assert(strcmp("Access-Control-Request-Headers", HTTP_HEADER_STRINGS[HTTP_ACCESS_CONTROL_REQUEST_HEADERS]) == 0,
"Expected 'Access-Control-Request-Headers', not:%s",
HTTP_HEADER_STRINGS[HTTP_ACCESS_CONTROL_REQUEST_HEADERS]);
}
Test(http_headers, access_control_request_method) {
cr_assert(strcmp("Access-Control-Request-Method", HTTP_HEADER_STRINGS[HTTP_ACCESS_CONTROL_REQUEST_METHOD]) == 0,
"Expected 'Access-Control-Request-Method', not:%s",
HTTP_HEADER_STRINGS[HTTP_ACCESS_CONTROL_REQUEST_METHOD]);
}
Test(http_headers, age) {
cr_assert(strcmp("Age", HTTP_HEADER_STRINGS[HTTP_AGE]) == 0,
"Expected 'Age', not:%s", HTTP_HEADER_STRINGS[HTTP_AGE]);
}
Test(http_headers, allow) {
cr_assert(strcmp("Allow", HTTP_HEADER_STRINGS[HTTP_ALLOW]) == 0,
"Expected 'Allow', not:%s", HTTP_HEADER_STRINGS[HTTP_ALLOW]);
}
Test(http_headers, authorization) {
cr_assert(strcmp("Authorization", HTTP_HEADER_STRINGS[HTTP_AUTHORIZATION]) == 0,
"Expected 'Authorization', not:%s", HTTP_HEADER_STRINGS[HTTP_AUTHORIZATION]);
}
Test(http_headers, cache_control) {
cr_assert(strcmp("Cache-Control", HTTP_HEADER_STRINGS[HTTP_CACHE_CONTROL]) == 0,
"Expected 'Cache-Control', not:%s", HTTP_HEADER_STRINGS[HTTP_CACHE_CONTROL]);
}
Test(http_headers, connection) {
cr_assert(strcmp("Connection", HTTP_HEADER_STRINGS[HTTP_CONNECTION]) == 0,
"Expected 'Connection', not:%s", HTTP_HEADER_STRINGS[HTTP_CONNECTION]);
}
Test(http_headers, content_disposition) {
cr_assert(strcmp("Content-Disposition", HTTP_HEADER_STRINGS[HTTP_CONTENT_DISPOSITION]) == 0,
"Expected 'Content-Disposition', not:%s", HTTP_HEADER_STRINGS[HTTP_CONTENT_DISPOSITION]);
}
Test(http_headers, content_encoding) {
cr_assert(strcmp("Content-Encoding", HTTP_HEADER_STRINGS[HTTP_CONTENT_ENCODING]) == 0,
"Expected 'Content-Encoding', not:%s", HTTP_HEADER_STRINGS[HTTP_CONTENT_ENCODING]);
}
Test(http_headers, content_language) {
cr_assert(strcmp("Content-Language", HTTP_HEADER_STRINGS[HTTP_CONTENT_LANGUAGE]) == 0,
"Expected 'Content-Language', not:%s", HTTP_HEADER_STRINGS[HTTP_CONTENT_LANGUAGE]);
}
Test(http_headers, content_length) {
cr_assert(strcmp("Content-Length", HTTP_HEADER_STRINGS[HTTP_CONTENT_LENGTH]) == 0,
"Expected 'Content-Length', not:%s", HTTP_HEADER_STRINGS[HTTP_CONTENT_LENGTH]);
}
Test(http_headers, content_location) {
cr_assert(strcmp("Content-Location", HTTP_HEADER_STRINGS[HTTP_CONTENT_LOCATION]) == 0,
"Expected 'Content-Location', not:%s", HTTP_HEADER_STRINGS[HTTP_CONTENT_LOCATION]);
}
Test(http_headers, content_range) {
cr_assert(strcmp("Content-Range", HTTP_HEADER_STRINGS[HTTP_CONTENT_RANGE]) == 0,
"Expected 'Content-Range', not:%s", HTTP_HEADER_STRINGS[HTTP_CONTENT_RANGE]);
}
Test(http_headers, content_security_policy) {
cr_assert(strcmp("Content-Security-Policy", HTTP_HEADER_STRINGS[HTTP_CONTENT_SECURITY_POLICY]) == 0,
"Expected 'Content-Security-Policy', not:%s", HTTP_HEADER_STRINGS[HTTP_CONTENT_SECURITY_POLICY]);
}
Test(http_headers, content_security_policy_report_only) {
cr_assert(strcmp("Content-Security-Policy-Report-Only",
HTTP_HEADER_STRINGS[HTTP_CONTENT_SECURITY_POLICY_REPORT_ONLY]) == 0,
"Expected 'Content-Security-Policy-Report-Only', not:%s",
HTTP_HEADER_STRINGS[HTTP_CONTENT_SECURITY_POLICY_REPORT_ONLY]);
}
Test(http_headers, content_type) {
cr_assert(strcmp("Content-Type", HTTP_HEADER_STRINGS[HTTP_CONTENT_TYPE]) == 0,
"Expected 'Content-Type', not:%s", HTTP_HEADER_STRINGS[HTTP_CONTENT_TYPE]);
}
Test(http_headers, cookie) {
cr_assert(strcmp("Cookie", HTTP_HEADER_STRINGS[HTTP_COOKIE]) == 0,
"Expected 'Cookie', not:%s", HTTP_HEADER_STRINGS[HTTP_COOKIE]);
}
Test(http_headers, cookie2) {
cr_assert(strcmp("Cookie2", HTTP_HEADER_STRINGS[HTTP_COOKIE2]) == 0,
"Expected 'Cookie2', not:%s", HTTP_HEADER_STRINGS[HTTP_COOKIE2]);
}
Test(http_headers, DNT) {
cr_assert(strcmp("DNT", HTTP_HEADER_STRINGS[HTTP_DNT]) == 0,
"Expected 'DNT', not:%s", HTTP_HEADER_STRINGS[HTTP_DNT]);
}
Test(http_headers, date) {
cr_assert(strcmp("Date", HTTP_HEADER_STRINGS[HTTP_DATE]) == 0,
"Expected 'Date', not:%s", HTTP_HEADER_STRINGS[HTTP_DATE]);
}
Test(http_headers, ETag) {
cr_assert(strcmp("ETag", HTTP_HEADER_STRINGS[HTTP_ETAG]) == 0,
"Expected 'ETag', not:%s", HTTP_HEADER_STRINGS[HTTP_ETAG]);
}
Test(http_headers, Expect) {
cr_assert(strcmp("Expect", HTTP_HEADER_STRINGS[HTTP_EXPECT]) == 0,
"Expected 'Expect', not:%s", HTTP_HEADER_STRINGS[HTTP_EXPECT]);
}
Test(http_headers, Expect_CT) {
cr_assert(strcmp("Expect-CT", HTTP_HEADER_STRINGS[HTTP_EXPECT_CT]) == 0,
"Expected 'Expect-CT', not:%s", HTTP_HEADER_STRINGS[HTTP_EXPECT_CT]);
}
Test(http_headers, expires) {
cr_assert(strcmp("Expires", HTTP_HEADER_STRINGS[HTTP_EXPIRES]) == 0,
"Expected 'Expires', not:%s", HTTP_HEADER_STRINGS[HTTP_EXPIRES]);
}
Test(http_headers, forwarded) {
cr_assert(strcmp("Forwarded", HTTP_HEADER_STRINGS[HTTP_FORWARDED]) == 0,
"Expected 'Forwarded', not:%s", HTTP_HEADER_STRINGS[HTTP_FORWARDED]);
}
Test(http_headers, from) {
cr_assert(strcmp("From", HTTP_HEADER_STRINGS[HTTP_FROM]) == 0,
"Expected 'From', not:%s", HTTP_HEADER_STRINGS[HTTP_FROM]);
}
Test(http_headers, host) {
cr_assert(strcmp("Host", HTTP_HEADER_STRINGS[HTTP_HOST]) == 0,
"Expected 'Host', not:%s", HTTP_HEADER_STRINGS[HTTP_HOST]);
}
Test(http_headers, if_match) {
cr_assert(strcmp("If-Match", HTTP_HEADER_STRINGS[HTTP_IF_MATCH]) == 0,
"Expected 'If-Match', not:%s", HTTP_HEADER_STRINGS[HTTP_IF_MATCH]);
}
Test(http_headers, if_modified_since) {
cr_assert(strcmp("If-Modified-Since", HTTP_HEADER_STRINGS[HTTP_IF_MODIFIED_SINCE]) == 0,
"Expected 'If-Modified-Since', not:%s", HTTP_HEADER_STRINGS[HTTP_IF_MODIFIED_SINCE]);
}
Test(http_headers, if_mone_match) {
cr_assert(strcmp("If-None-Match", HTTP_HEADER_STRINGS[HTTP_IF_NONE_MATCH]) == 0,
"Expected 'If-None-Match', not:%s", HTTP_HEADER_STRINGS[HTTP_IF_NONE_MATCH]);
}
Test(http_headers, if_range) {
cr_assert(strcmp("If-Range", HTTP_HEADER_STRINGS[HTTP_IF_RANGE]) == 0,
"Expected 'If-Range', not:%s", HTTP_HEADER_STRINGS[HTTP_IF_RANGE]);
}
Test(http_headers, if_unmodified_since) {
cr_assert(strcmp("If-Unmodified-Since", HTTP_HEADER_STRINGS[HTTP_IF_UNMODIFIED_SINCE]) == 0,
"Expected 'If-Unmodified-Since', not:%s", HTTP_HEADER_STRINGS[HTTP_IF_UNMODIFIED_SINCE]);
}
Test(http_headers, keep_alive) {
cr_assert(strcmp("Keep-Alive", HTTP_HEADER_STRINGS[HTTP_KEEP_ALIVE]) == 0,
"Expected 'Keep-Alive', not:%s", HTTP_HEADER_STRINGS[HTTP_KEEP_ALIVE]);
}
Test(http_headers, large_allocation) {
cr_assert(strcmp("Large-Allocation", HTTP_HEADER_STRINGS[HTTP_LARGE_ALLOCATION]) == 0,
"Expected 'Large-Allocation', not:%s", HTTP_HEADER_STRINGS[HTTP_LARGE_ALLOCATION]);
}
Test(http_headers, last_modified) {
cr_assert(strcmp("Last-Modified", HTTP_HEADER_STRINGS[HTTP_LAST_MODIFIED]) == 0,
"Expected 'Last-Modified', not:%s", HTTP_HEADER_STRINGS[HTTP_LAST_MODIFIED]);
}
Test(http_headers, location) {
cr_assert(strcmp("Location", HTTP_HEADER_STRINGS[HTTP_LOCATION]) == 0,
"Expected 'Location', not:%s", HTTP_HEADER_STRINGS[HTTP_LOCATION]);
}
Test(http_headers, origin) {
cr_assert(strcmp("Origin", HTTP_HEADER_STRINGS[HTTP_ORIGIN]) == 0,
"Expected 'Origin', not:%s", HTTP_HEADER_STRINGS[HTTP_ORIGIN]);
}
Test(http_headers, pragma) {
cr_assert(strcmp("Pragma", HTTP_HEADER_STRINGS[HTTP_PRAGMA]) == 0,
"Expected 'Pragma', not:%s", HTTP_HEADER_STRINGS[HTTP_PRAGMA]);
}
Test(http_headers, proxy_authenticate) {
cr_assert(strcmp("Proxy-Authenticate", HTTP_HEADER_STRINGS[HTTP_PROXY_AUTHENTICATE]) == 0,
"Expected 'Proxy-Authenticate', not:%s", HTTP_HEADER_STRINGS[HTTP_PROXY_AUTHENTICATE]);
}
Test(http_headers, proxy_authorization) {
cr_assert(strcmp("Proxy-Authorization", HTTP_HEADER_STRINGS[HTTP_PROXY_AUTHORIZATION]) == 0,
"Expected 'Proxy-Authorization', not:%s", HTTP_HEADER_STRINGS[HTTP_PROXY_AUTHORIZATION]);
}
Test(http_headers, public_key_pins) {
cr_assert(strcmp("Public-Key-Pins", HTTP_HEADER_STRINGS[HTTP_PUBLIC_KEY_PINS]) == 0,
"Expected 'Public-Key-Pins', not:%s", HTTP_HEADER_STRINGS[HTTP_PUBLIC_KEY_PINS]);
}
Test(http_headers, public_key_pins_report_only) {
cr_assert(strcmp("Public-Key-Pins-Report-Only", HTTP_HEADER_STRINGS[HTTP_PUBLIC_KEY_PINS_REPORT_ONLY]) == 0,
"Expected 'Public-Key-Pins-Report-Only', not:%s", HTTP_HEADER_STRINGS[HTTP_PUBLIC_KEY_PINS_REPORT_ONLY]);
}
Test(http_headers, referer) {
cr_assert(strcmp("Referer", HTTP_HEADER_STRINGS[HTTP_REFERER]) == 0,
"Expected 'Referer', not:%s", HTTP_HEADER_STRINGS[HTTP_REFERER]);
}
Test(http_headers, referrer_policy) {
cr_assert(strcmp("Referrer-Policy", HTTP_HEADER_STRINGS[HTTP_REFERRER_POLICY]) == 0,
"Expected 'Referrer-Policy', not:%s", HTTP_HEADER_STRINGS[HTTP_REFERRER_POLICY]);
}
Test(http_headers, retry_after) {
cr_assert(strcmp("Retry-After", HTTP_HEADER_STRINGS[HTTP_RETRY_AFTER]) == 0,
"Expected 'Retry-After', not:%s", HTTP_HEADER_STRINGS[HTTP_RETRY_AFTER]);
}
Test(http_headers, server) {
cr_assert(strcmp("Server", HTTP_HEADER_STRINGS[HTTP_SERVER]) == 0,
"Expected 'Server', not:%s", HTTP_HEADER_STRINGS[HTTP_SERVER]);
}
Test(http_headers, server_timing) {
cr_assert(strcmp("Server-Timing", HTTP_HEADER_STRINGS[HTTP_SERVER_TIMING]) == 0,
"Expected 'Server-Timing', not:%s", HTTP_HEADER_STRINGS[HTTP_SERVER_TIMING]);
}
Test(http_headers, set_cookie) {
cr_assert(strcmp("Set-Cookie", HTTP_HEADER_STRINGS[HTTP_SET_COOKIE]) == 0,
"Expected 'Set-Cookie', not:%s", HTTP_HEADER_STRINGS[HTTP_SET_COOKIE]);
}
Test(http_headers, set_cookie2) {
cr_assert(strcmp("Set-Cookie2", HTTP_HEADER_STRINGS[HTTP_SET_COOKIE2]) == 0,
"Expected 'Set-Cookie2', not:%s", HTTP_HEADER_STRINGS[HTTP_SET_COOKIE2]);
}
Test(http_headers, sourcemap) {
cr_assert(strcmp("SourceMap", HTTP_HEADER_STRINGS[HTTP_SOURCEMAP]) == 0,
"Expected 'SourceMap', not:%s", HTTP_HEADER_STRINGS[HTTP_SOURCEMAP]);
}
Test(http_headers, strict_transport_security) {
cr_assert(strcmp("Strict-Transport-Security", HTTP_HEADER_STRINGS[HTTP_STRICT_TRANSPORT_SECURITY]) == 0,
"Expected 'Strict-Transport-Security', not:%s", HTTP_HEADER_STRINGS[HTTP_STRICT_TRANSPORT_SECURITY]);
}
Test(http_headers, TE) {
cr_assert(strcmp("TE", HTTP_HEADER_STRINGS[HTTP_TE]) == 0,
"Expected 'TE', not:%s", HTTP_HEADER_STRINGS[HTTP_TE]);
}
Test(http_headers, timing_allow_origin) {
cr_assert(strcmp("Timing-Allow-Origin", HTTP_HEADER_STRINGS[HTTP_TIMING_ALLOW_ORIGIN]) == 0,
"Expected 'Timing-Allow-Origin', not:%s", HTTP_HEADER_STRINGS[HTTP_TIMING_ALLOW_ORIGIN]);
}
Test(http_headers, Tk) {
cr_assert(strcmp("Tk", HTTP_HEADER_STRINGS[HTTP_TK]) == 0,
"Expected 'Tk', not:%s", HTTP_HEADER_STRINGS[HTTP_TK]);
}
Test(http_headers, trailer) {
cr_assert(strcmp("Trailer", HTTP_HEADER_STRINGS[HTTP_TRAILER]) == 0,
"Expected 'Trailer', not:%s", HTTP_HEADER_STRINGS[HTTP_TRAILER]);
}
Test(http_headers, transfer_encoding) {
cr_assert(strcmp("Transfer-Encoding", HTTP_HEADER_STRINGS[HTTP_TRANSFER_ENCODING]) == 0,
"Expected 'Transfer-Encoding', not:%s", HTTP_HEADER_STRINGS[HTTP_TRANSFER_ENCODING]);
}
Test(http_headers, upgrade_insecure_requests) {
cr_assert(strcmp("Upgrade-Insecure-Requests", HTTP_HEADER_STRINGS[HTTP_UPGRADE_INSECURE_REQUESTS]) == 0,
"Expected 'Upgrade-Insecure-Requests', not:%s", HTTP_HEADER_STRINGS[HTTP_UPGRADE_INSECURE_REQUESTS]);
}
Test(http_headers, user_agent) {
cr_assert(strcmp("User-Agent", HTTP_HEADER_STRINGS[HTTP_USER_AGENT]) == 0,
"Expected 'User-Agent', not:%s", HTTP_HEADER_STRINGS[HTTP_USER_AGENT]);
}
Test(http_headers, vary) {
cr_assert(strcmp("Vary", HTTP_HEADER_STRINGS[HTTP_VARY]) == 0,
"Expected 'Vary', not:%s", HTTP_HEADER_STRINGS[HTTP_VARY]);
}
Test(http_headers, via) {
cr_assert(strcmp("Via", HTTP_HEADER_STRINGS[HTTP_VIA]) == 0,
"Expected 'Via', not:%s", HTTP_HEADER_STRINGS[HTTP_VIA]);
}
Test(http_headers, WWW_authenticate) {
cr_assert(strcmp("WWW-Authenticate", HTTP_HEADER_STRINGS[HTTP_WWW_AUTHENTICATE]) == 0,
"Expected 'WWW-Authenticate', not:%s", HTTP_HEADER_STRINGS[HTTP_WWW_AUTHENTICATE]);
}
Test(http_headers, warning) {
cr_assert(strcmp("Warning", HTTP_HEADER_STRINGS[HTTP_WARNING]) == 0,
"Expected 'Warning', not:%s", HTTP_HEADER_STRINGS[HTTP_WARNING]);
}
Test(http_headers, x_content_type_options) {
cr_assert(strcmp("X-Content-Type-Options", HTTP_HEADER_STRINGS[HTTP_X_CONTENT_TYPE_OPTIONS]) == 0,
"Expected 'X-Content-Type-Options', not:%s", HTTP_HEADER_STRINGS[HTTP_X_CONTENT_TYPE_OPTIONS]);
}
Test(http_headers, X_DNS_prefetch_control) {
cr_assert(strcmp("X-DNS-Prefetch-Control", HTTP_HEADER_STRINGS[HTTP_X_DNS_PREFETCH_CONTROL]) == 0,
"Expected 'X-DNS-Prefetch-Control', not:%s", HTTP_HEADER_STRINGS[HTTP_X_DNS_PREFETCH_CONTROL]);
}
Test(http_headers, x_forwarded_for) {
cr_assert(strcmp("X-Forwarded-For", HTTP_HEADER_STRINGS[HTTP_X_FORWARDED_FOR]) == 0,
"Expected 'X-Forwarded-For', not:%s", HTTP_HEADER_STRINGS[HTTP_X_FORWARDED_FOR]);
}
Test(http_headers, X_forwarded_host) {
cr_assert(strcmp("X-Forwarded-Host", HTTP_HEADER_STRINGS[HTTP_X_FORWARDED_HOST]) == 0,
"Expected 'X-Forwarded-Host', not:%s", HTTP_HEADER_STRINGS[HTTP_X_FORWARDED_HOST]);
}
Test(http_headers, X_forwarded_proto) {
cr_assert(strcmp("X-Forwarded-Proto", HTTP_HEADER_STRINGS[HTTP_X_FORWARDED_PROTO]) == 0,
"Expected 'X-Forwarded-Proto', not:%s", HTTP_HEADER_STRINGS[HTTP_X_FORWARDED_PROTO]);
}
Test(http_headers, X_frame_options) {
cr_assert(strcmp("X-Frame-Options", HTTP_HEADER_STRINGS[HTTP_X_FRAME_OPTIONS]) == 0,
"Expected 'X-Frame-Options', not:%s", HTTP_HEADER_STRINGS[HTTP_X_FRAME_OPTIONS]);
}
Test(http_headers, X_XSS_protection) {
cr_assert(strcmp("X-XSS-Protection", HTTP_HEADER_STRINGS[HTTP_X_XSS_PROTECTION]) == 0,
"Expected 'X-XSS-Protection', not:%s", HTTP_HEADER_STRINGS[HTTP_X_XSS_PROTECTION]);
}
|
C
|
/* ***************************************************************** */
/* */
/* */
/* ***************************************************************** */
/* The code to read a memory trace and simulate it on the various
caches. */
#include "global.h"
#include "utils.h" // utility functions
#include "cds.h" // Cache Description Structures
#include "caches.h" // cache manipulation code
struct memory_reference
{
enum memory_access_type type;
memory_address address;
unsigned int length;
};
typedef struct memory_reference memory_reference;
static int trace_line_number;
/* ***************************************************************** */
/* */
/* */
/* ***************************************************************** */
/* read on input line */
void read_reference(FILE *trace_file, memory_reference *reference)
{
int c;
/* we have the first character; it defined the
memory access type. Skip any blanks, get the
hexadecimal address, skip the comma and get the length */
/* skip any leading blanks */
c = skip_blanks(trace_file);
memory_address a = 0;
while (ishex(c))
{
a = (a << 4) | hexvalue(c);
c = getc(trace_file);
}
if (c != ',')
{
fprintf(stderr, "bad trace file input at line %d: %c\n", trace_line_number, c);
exit(-1);
}
/* skip the comma */
/* and get the length */
int n = 0;
c = getc(trace_file);
while (isdigit(c))
{
n = n * 10 + decvalue(c);
c = getc(trace_file);
}
/* skip to end of line */
while ((c != '\n') && (c != EOF)) c = getc(trace_file);
/* define reference fields */
reference->address = a;
reference->length = n;
}
/* ***************************************************************** */
/* */
/* */
/* ***************************************************************** */
int Read_trace_file_line(FILE *trace_file, memory_reference *reference)
{
int c;
trace_line_number = 0;
while ((c = getc(trace_file)) != EOF)
{
/* start the next line */
trace_line_number += 1;
/* skip any leading blanks */
while (isspace(c) && (c != EOF)) c = getc(trace_file);
/* what is the character ? */
switch (c)
{
case 'I': /* instruction trace */
{
reference->type = MAT_FETCH;
read_reference(trace_file, reference);
return('I');
}
case 'M': /* read/modify/write -- treat as a store */
case 'S': /* store */
{
reference->type = MAT_STORE;
read_reference(trace_file, reference);
return('S');
}
case 'L': /* load */
{
reference->type = MAT_LOAD;
read_reference(trace_file, reference);
return('L');
}
}
/* apparently not a reference line. There are a bunch
of other lines that valgrind puts out. They start
with ====, or --, or such. Skip the entire line. */
/* skip to end of line */
while ((c != '\n') && (c != EOF)) c = getc(trace_file);
}
return(EOF);
}
/* ***************************************************************** */
/* */
/* */
/* ***************************************************************** */
/* LFU counts the number of times something is used. To prevent
a large number from just sitting there, we cause it to decay
over time. Every "tick" time units, we shift left one bit,
so that eventually a count will go to zero if it is not continuing
to be used. */
void Check_For_Decay(CDS *cds)
{
if (cds->replacement_policy != CRP_LFU) return;
if ((cds->number_of_memory_reference % cds->LFU_Decay_Interval) == 0)
{
int i;
if (debug) fprintf(debug_file, "%s: LFU decay for all LFU counters\n", cds->name);
for (i = 0; i < cds->number_of_cache_entries; i++)
{
cds->c[i].replacement_data = cds->c[i].replacement_data/2;
}
}
}
/* ***************************************************************** */
/* */
/* */
/* ***************************************************************** */
int Find_Victim_by_Replacement_Policy(CDS *cds, int first_index, int set_size)
{
int i;
int victim;
if (debug) fprintf(debug_file, "%s: look for victim in %d lines starting at %d\n", cds->name, set_size, first_index);
/* first look to see if any entry is empty */
for (i = 0; i < set_size; i++)
{
if (!(cds->c[first_index+i].valid))
{
victim = first_index+i;
if (debug) fprintf(debug_file, "%s: found empty cache entry at %d\n", cds->name, victim);
return(victim);
}
}
victim = first_index; /* default victim */
switch (cds->replacement_policy)
{
case CRP_FIFO: /* replacement data is the order we were brought in: 1, 2, 3, ... */
/* choose the smallest */
case CRP_LRU: /* replacement data is the time we were last hit */
/* choose the smallest */
case CRP_LFU: /* replacement data is the number of uses, so
choose the smallest */
{
int min = cds->c[first_index].replacement_data;
if (debug) fprintf(debug_file, "%s: replacement data: [%d, 0x%08X]: %d", cds->name, victim, cds->c[victim].tag, min);
for (i = 1; i < set_size; i++)
{
if (debug) fprintf(debug_file, ", [%d, 0x%08X]: %d", first_index+i, cds->c[first_index+i].tag, cds->c[first_index+i].replacement_data);
if (cds->c[first_index+i].replacement_data < min)
{
victim = first_index+i;
min = cds->c[victim].replacement_data;
}
}
if (debug) fprintf(debug_file, "\n");
}
break;
case CRP_RANDOM:
victim = first_index + (random() % set_size);
break;
}
if (debug) fprintf(debug_file, "%s: found victim in entry %d\n", cds->name, victim);
return(victim);
}
void write_dirty_line_to_memory(CDS *cds, cache_line *victim_line)
{
if (debug) fprintf(debug_file, "%s: Write victim 0x%08X to memory\n",
cds->name, victim_line->tag);
cds->number_memory_writes += 1;
victim_line->dirty = FALSE;
}
void Set_Replacement_Policy_Data(CDS *cds, int first_index, int i)
{
switch (cds->replacement_policy)
{
case CRP_FIFO: /* replacement data is the order we were brought in: 1, 2, 3, ... */
cds->c[first_index+i].replacement_data = cds->number_of_memory_reference;
break;
case CRP_LRU: /* replacement data is the time we were last hit */
cds->c[first_index+i].replacement_data = cds->number_of_memory_reference;
break;
case CRP_LFU: /* replacement data is a count; starts at zero */
cds->c[first_index+i].replacement_data = 0;
Check_For_Decay(cds);
case CRP_RANDOM:
break;
}
}
void Update_Replacement_Policy_Data(CDS *cds, int first_index, int i)
{
switch (cds->replacement_policy)
{
case CRP_FIFO: /* replacement data is the order we were brought in: 1, 2, 3, ... */
break;
case CRP_LRU: /* replacement data is the time we were last hit */
cds->c[first_index+i].replacement_data = cds->number_of_memory_reference;
break;
case CRP_LFU: /* replacement data is the count of the number of uses */
cds->c[first_index+i].replacement_data += 1;
Check_For_Decay(cds);
case CRP_RANDOM:
break;
}
}
/* ***************************************************************** */
/* */
/* */
/* ***************************************************************** */
void evict_from_cache(CDS *cds, cache_line *victim_line, memory_address cache_address)
{
/* if victim is dirty, must write back to memory first */
if (victim_line->dirty)
write_dirty_line_to_memory(cds, victim_line);
}
/* ***************************************************************** */
/* */
/* */
/* ***************************************************************** */
memory_address Base_Cache_Address(CDS *cds, memory_address a)
{
/* find number of low-order bits to mask off to find beginning cache
line address */
int number_of_low_order_bits = which_power(cds->cache_line_size);
memory_address low_order_mask = mask_of(number_of_low_order_bits);
memory_address cache_address = a & (~low_order_mask);
return(cache_address);
}
void Simulate_Reference_to_Cache_Line(CDS *cds, memory_reference *reference)
{
if (debug) fprintf(debug_file, "%s: %s Reference 0x%08X of length %d\n",
cds->name, memory_reference_type_name(reference->type),
reference->address, reference->length);
cds->number_total_cache_access += 1;
/* find cache line for this reference */
/* find number of low-order bits to mask off to find beginning cache
line address */
memory_address cache_address = Base_Cache_Address(cds, reference->address);
/* shift off low-order offset bits and find bits for
indexing into cache table */
/* the number of sets is the number of cache entries
divided by the number of ways. */
int number_of_low_order_bits = which_power(cds->cache_line_size);
int number_of_sets = cds->number_of_cache_entries/cds->number_of_ways;
int sets_bits = which_power(number_of_sets);
memory_address sets_bits_mask = mask_of(sets_bits);
int cache_set_index = (cache_address >> number_of_low_order_bits) & sets_bits_mask;
int cache_entry_index = cache_set_index * cds->number_of_ways;
/* index into cache table and search the number of ways to
try to find cache line. */
int i;
for (i = 0; i < cds->number_of_ways; i++)
{
if (cds->c[cache_entry_index+i].valid && (cache_address == cds->c[cache_entry_index+i].tag))
{
/* found it -- record cache hit and exit */
if (debug) fprintf(debug_file, "%s: Found address 0x%08X in cache line %d\n", cds->name,
reference->address, cache_entry_index+i);
cds->number_cache_hits += 1;
/* update reference specific info */
if (reference->type == MAT_STORE)
{
/* If it's not write-back, then it is write-thru.
For write-thru, if it's a write, we write to memory. */
if (!cds->write_back)
cds->number_memory_writes += 1;
else
/* For write-back, if it's a write, it's dirty. */
cds->c[cache_entry_index+i].dirty = TRUE;
}
Update_Replacement_Policy_Data(cds, cache_entry_index, i);
return;
}
}
/* Did not find it. */
cds->number_cache_misses += 1;
/* Choose a victim from the set */
int victim = Find_Victim_by_Replacement_Policy(cds, cache_entry_index, cds->number_of_ways);
if (debug) fprintf(debug_file, "%s: Pick victim %d to replace\n", cds->name, victim);
/* evict victim */
if (cds->c[victim].valid)
evict_from_cache(cds, &(cds->c[victim]), cache_address);
/* fill in evicted cache line for this new line */
cds->c[victim].valid = TRUE;
cds->c[victim].tag = cache_address;
if (debug) fprintf(debug_file, "%s: Read cache line 0x%08X into entry %d\n", cds->name, cds->c[victim].tag, victim);
Set_Replacement_Policy_Data(cds, cache_entry_index, victim-cache_entry_index);
/* read cache line from memory into cache table */
cds->number_memory_reads += 1;
cds->c[victim].dirty = FALSE;
if (reference->type == MAT_STORE)
{
if (!cds->write_back)
{
/* If it's not write-back, then it is write-thru.
For write-thru, if it's a write, we write to memory. */
cds->number_memory_writes += 1;
if (debug) fprintf(debug_file, "%s: Write cache line 0x%08X thru to memory\n", cds->name, cds->c[victim].tag);
}
else
{
cds->c[victim].dirty = TRUE;
}
}
}
void Simulate_Reference_to_Memory(CDS *cds, memory_reference *reference)
{
cds->number_of_memory_reference += 1;
cds->number_of_type[reference->type] += 1;
/* check if the entire reference fits into just one cache line */
if (Base_Cache_Address(cds, reference->address) == Base_Cache_Address(cds, reference->address + reference->length -1))
{
Simulate_Reference_to_Cache_Line(cds, reference);
}
else
{
/* reference spans two cache lines. Convert it to two
references: the first cache line, and the second cache line */
memory_reference reference1;
memory_reference reference2;
/* easiest to compute the second part first */
reference2.type = reference->type;
reference2.address = Base_Cache_Address(cds, reference->address + reference->length -1);
reference2.length = reference->address + reference->length - reference2.address;
reference1.type = reference->type;
reference1.address = reference->address;
reference1.length = reference->length - reference2.length;
/* but we do the references first, then second */
Simulate_Reference_to_Cache_Line(cds, &reference1);
Simulate_Reference_to_Cache_Line(cds, &reference2);
}
}
/* ***************************************************************** */
/* */
/* */
/* ***************************************************************** */
/* read each input line, and then simulate that reference on each
cache. */
void Simulate_Caches(String trace_file_name)
{
FILE *trace_file;
memory_reference reference;
/* open input file */
trace_file = fopen(trace_file_name, "r");
if (trace_file == NULL)
{
fprintf (stderr,"Cannot open trace file %s\n", trace_file_name);
exit(1);
}
Init_caches_for_trace();
while (Read_trace_file_line(trace_file, &reference) != EOF)
{
CDS *cds = CDS_root;
while (cds != NULL)
{
Simulate_Reference_to_Memory(cds, &reference);
cds = cds->next;
}
}
fclose(trace_file);
}
int number_dirty_lines(CDS *cds)
{
int n = 0;
int i;
for (i = 0; i < cds->number_of_cache_entries; i++)
{
if (cds->c[i].dirty)
{
n += 1;
if (debug) fprintf(debug_file, "%s: Cache Line 0x%08X is dirty\n", cds->name, cds->c[i].tag);
}
}
return(n);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define USER_NUM 5128
typedef struct node_ {
int val ;
struct node_* next ;
} node ;
typedef struct queue_ {
node *front;
node *rear;
int count;
} queue ;
typedef struct mutual_ {
int user1 ;
int user2 ;
int check ;
} mutual ;
int *id_set ;
mutual set[4000] ;
void initQueue(queue *q) ;
int isEmpty(queue *q) ;
void insert(queue *q, int data) ;
int delete(queue *q) ;
int id2idx(int id) {
for (int i=0 ; i<USER_NUM ; i++) {
if (id_set[i] == id)
return i ;
}
return -1 ;
}
int idx2id(int idx) {
return id_set[idx] ;
}
int isNoMutual(int id) {
for (int i=0 ; i<3873 ; i++) {
if (set[i].user1 == id || set[i].user2 == id) {
return 0 ;
}
}
return 1 ;
}
int main() {
FILE *fp_id = fopen("id_array.txt", "r") ;
int i = 0 ;
id_set = (int *)malloc(sizeof(int) * USER_NUM) ;
int temp = 0 ;
for (int i=0 ; i<USER_NUM ; i++) {
fscanf(fp_id, "%d", &temp) ;
id_set[i] = temp ;
}
fclose(fp_id) ;
int **relationArray = (int **)malloc(sizeof(int*) * USER_NUM) ;
for (int i=0 ; i<USER_NUM ; i++) {
relationArray[i] = (int *)malloc(sizeof(int) * USER_NUM) ;
}
FILE *fp_data = fopen("twitter_sampled.txt", "r") ;
int x, y ;
for (int i=0 ; i<21270 ; i++) {
fscanf(fp_data, "%d %d", &x, &y) ;
x = id2idx(x) ;
y = id2idx(y) ;
relationArray[x][y] = 1 ;
}
fclose(fp_data) ;
printf("read data\n") ;
int count = 0 ;
for (int i=0 ; i<USER_NUM ; i++) {
for (int j=i ; j < USER_NUM ; j++) {
if ((relationArray[i][j] == relationArray[j][i]) && (relationArray[i][j] == 1)) {
set[count].user1 = idx2id(i) ;
set[count].user2 = idx2id(j) ;
set[count].check = 0 ; // init
//printf("%d %d %d\n", count, set[count].user1, set[count].user2) ;
count += 1;
}
}
}
printf("%d\n", count) ; // 3873
//printf("found set\n") ;
int markingArray[USER_NUM] = {0, } ;
int markSign = 1;
int newID = 0 ;
queue qq ;
initQueue(&qq) ;
for(int i=0 ; i<USER_NUM ; i++) {
if(isNoMutual(idx2id(i))) {
markingArray[i] = -1 ;
printf("%d has no mutual\n", idx2id(i)) ;
}
}
for(int i=0 ; i<USER_NUM ; i++) {
if(markingArray[i] == 0) {
newID = i ;
while(1) {
markingArray[newID] = markSign ;
for (int j=0 ; j<count ; j++) {
if(set[j].user1 == idx2id(newID)) {
insert(&qq, set[j].user2) ;
}
}
if (isEmpty(&qq)) {
markSign += 1 ;
break ;
} else {
newID = delete(&qq) ;
newID = id2idx(newID) ;
}
}
}
}
FILE *fp_result = fopen("marking", "w") ;
for(int i=0 ; i<USER_NUM ; i++) {
fprintf(fp_result, "%d\n", markingArray[i]) ;
}
for (int i=0 ; i<USER_NUM ; i++) {
free(relationArray[i]) ;
}
free(relationArray) ;
free(id_set) ;
}
void initQueue(queue *q) {
q->front = NULL ;
q->rear = NULL ;
q->count = 0 ;
}
int isEmpty(queue *q) {
if (q->count == 0)
return 1 ;
else
return 0 ;
}
void insert(queue *q, int data) {
node *new = (node *)malloc(sizeof(node)) ;
new->val = data;
new->next = NULL;
if (isEmpty(q)) {
q->front = new ;
} else {
for (node *curr = q->front ; curr != NULL ; curr = curr->next) {
if (data == curr->val) // remove duplicated user
return ;
}
q->rear->next = new;
}
q->rear = new ;
q->count += 1 ;
}
int delete(queue *q) { // return -1 when queue is empty
node *temp = NULL;
if (isEmpty(q)) {
return -1 ;
}
temp = q->front ;
int value = temp->val ;
q->front = temp->next ;
free(temp);
q->count -= 1 ;
return value;
}#include <stdio.h>
#include <stdlib.h>
#define USER_NUM 5128
typedef struct node_ {
int val ;
struct node_* next ;
} node ;
typedef struct queue_ {
node *front;
node *rear;
int count;
} queue ;
typedef struct mutual_ {
int user1 ;
int user2 ;
int check ;
} mutual ;
int *id_set ;
mutual set[4000] ;
void initQueue(queue *q) ;
int isEmpty(queue *q) ;
void insert(queue *q, int data) ;
int delete(queue *q) ;
int id2idx(int id) {
for (int i=0 ; i<USER_NUM ; i++) {
if (id_set[i] == id)
return i ;
}
return -1 ;
}
int idx2id(int idx) {
return id_set[idx] ;
}
int isNoMutual(int id) {
for (int i=0 ; i<3873 ; i++) {
if (set[i].user1 == id || set[i].user2 == id) {
return 0 ;
}
}
return 1 ;
}
int main() {
FILE *fp_id = fopen("id_array.txt", "r") ;
int i = 0 ;
id_set = (int *)malloc(sizeof(int) * USER_NUM) ;
int temp = 0 ;
for (int i=0 ; i<USER_NUM ; i++) {
fscanf(fp_id, "%d", &temp) ;
id_set[i] = temp ;
}
fclose(fp_id) ;
int **relationArray = (int **)malloc(sizeof(int*) * USER_NUM) ;
for (int i=0 ; i<USER_NUM ; i++) {
relationArray[i] = (int *)malloc(sizeof(int) * USER_NUM) ;
}
FILE *fp_data = fopen("twitter_sampled.txt", "r") ;
int x, y ;
for (int i=0 ; i<21270 ; i++) {
fscanf(fp_data, "%d %d", &x, &y) ;
x = id2idx(x) ;
y = id2idx(y) ;
relationArray[x][y] = 1 ;
}
fclose(fp_data) ;
printf("read data\n") ;
int count = 0 ;
for (int i=0 ; i<USER_NUM ; i++) {
for (int j=i ; j < USER_NUM ; j++) {
if ((relationArray[i][j] == relationArray[j][i]) && (relationArray[i][j] == 1)) {
set[count].user1 = idx2id(i) ;
set[count].user2 = idx2id(j) ;
set[count].check = 0 ; // init
//printf("%d %d %d\n", count, set[count].user1, set[count].user2) ;
count += 1;
}
}
}
printf("%d\n", count) ; // 3873
//printf("found set\n") ;
int markingArray[USER_NUM] = {0, } ;
int markSign = 1;
int newID = 0 ;
queue qq ;
initQueue(&qq) ;
for(int i=0 ; i<USER_NUM ; i++) {
if(isNoMutual(idx2id(i))) {
markingArray[i] = -1 ;
printf("%d has no mutual\n", idx2id(i)) ;
}
}
for(int i=0 ; i<USER_NUM ; i++) {
if(markingArray[i] == 0) {
newID = i ;
while(1) {
markingArray[newID] = markSign ;
for (int j=0 ; j<count ; j++) {
if(set[j].user1 == idx2id(newID)) {
if (markingArray[set[j].user2] != 0)
continue ;
insert(&qq, set[j].user2) ;
}
if(set[j].user2 == idx2id(newID)) {
if (markingArray[set[j].user1] != 0)
continue ;
insert(&qq, set[j].user1) ;
}
}
if (isEmpty(&qq)) {
markSign += 1 ;
break ;
} else {
newID = delete(&qq) ;
newID = id2idx(newID) ;
}
}
}
}
FILE *fp_result = fopen("temp.txt", "w") ;
for(int i=0 ; i<USER_NUM ; i++) {
fprintf(fp_result, "%d\n", markingArray[i]) ;
}
fclose(fp_result) ;
for (int i=0 ; i<USER_NUM ; i++) {
free(relationArray[i]) ;
}
free(relationArray) ;
free(id_set) ;
}
void initQueue(queue *q) {
q->front = NULL ;
q->rear = NULL ;
q->count = 0 ;
}
int isEmpty(queue *q) {
if (q->count == 0)
return 1 ;
else
return 0 ;
}
void insert(queue *q, int data) {
node *new = (node *)malloc(sizeof(node)) ;
new->val = data;
new->next = NULL;
if (isEmpty(q)) {
q->front = new ;
} else {
for (node *curr = q->front ; curr != NULL ; curr = curr->next) {
if (data == curr->val) // remove duplicated user
return ;
}
q->rear->next = new;
}
q->rear = new ;
q->count += 1 ;
}
int delete(queue *q) { // return -1 when queue is empty
node *temp = NULL;
if (isEmpty(q)) {
return -1 ;
}
temp = q->front ;
int value = temp->val ;
q->front = temp->next ;
free(temp);
q->count -= 1 ;
return value;
}
|
C
|
//
// Copyright 2018 Staysail Systems, Inc. <info@staysail.tech>
// Copyright 2018 Capitar IT Group BV <info@capitar.com>
//
// This software is supplied under the terms of the MIT License, a
// copy of which should be located in the distribution where this
// file was obtained (LICENSE.txt). A copy of the license may also be
// found online at https://opensource.org/licenses/MIT.
//
#include <string.h>
#include <nng/nng.h>
#include <nng/supplemental/util/options.h>
#include "convey.h"
static nng_optspec case1[] = {
// clang-format off
{ "flag", 'f', 1, false },
{ "longflag", 0, 2, false },
{ "value", 'v', 3, true },
{ NULL, 'b', 4, false },
{ NULL, 0, 0, false },
// clang-format on
};
TestMain("Option Parsing", {
Convey("Simple works", {
int opti = 1;
char *av[6];
int ac = 5;
int v;
char *a = NULL;
av[0] = "program";
av[1] = "-f";
av[2] = "-v";
av[3] = "123";
av[4] = "456";
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == 0);
So(v == 1);
So(a == NULL);
So(opti == 2);
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == 0);
So(opti == 4);
So(v == 3);
So(strcmp(a, "123") == 0);
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == -1);
So(opti == 4);
So(strcmp(av[opti], "456") == 0);
});
Convey("Long works", {
int opti = 1;
char *av[6];
int ac = 5;
int v;
char *a = NULL;
av[0] = "program";
av[1] = "--flag";
av[2] = "--value";
av[3] = "123";
av[4] = "456";
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == 0);
So(v == 1);
So(a == NULL);
So(opti == 2);
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == 0);
So(opti == 4);
So(v == 3);
So(strcmp(a, "123") == 0);
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == -1);
So(opti == 4);
So(strcmp(av[opti], "456") == 0);
});
Convey("Attached short works", {
int opti = 1;
char *av[3];
int ac = 3;
int v;
char *a = NULL;
av[0] = "program";
av[1] = "-v123";
av[2] = "456";
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == 0);
So(opti == 2);
So(v == 3);
So(strcmp(a, "123") == 0);
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == -1);
So(opti == 2);
So(strcmp(av[opti], "456") == 0);
});
Convey("Attached long (=) works", {
int opti = 1;
char *av[3];
int ac = 3;
int v;
char *a = NULL;
av[0] = "program";
av[1] = "--value=123";
av[2] = "456";
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == 0);
So(opti == 2);
So(v == 3);
So(strcmp(a, "123") == 0);
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == -1);
So(opti == 2);
So(strcmp(av[opti], "456") == 0);
});
Convey("Attached long (:) works", {
int opti = 1;
char *av[3];
int ac = 3;
int v;
char *a = NULL;
av[0] = "program";
av[1] = "--value:123";
av[2] = "456";
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == 0);
So(opti == 2);
So(v == 3);
So(strcmp(a, "123") == 0);
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == -1);
So(opti == 2);
So(strcmp(av[opti], "456") == 0);
});
Convey("Negative bad short works", {
int opti = 1;
char *av[3];
int ac = 3;
int v;
char *a = NULL;
av[0] = "program";
av[1] = "-Z";
av[2] = "456";
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == NNG_EINVAL);
So(opti == 1);
});
Convey("Negative bad long works", {
int opti = 1;
char *av[3];
int ac = 3;
int v;
char *a = NULL;
av[0] = "program";
av[1] = "--something";
av[2] = "456";
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == NNG_EINVAL);
So(opti == 1);
});
Convey("Separator flag works", {
int opti = 1;
char *av[5];
int ac = 5;
int v;
char *a = NULL;
av[0] = "program";
av[1] = "-f";
av[2] = "-";
av[3] = "-v";
av[4] = "456";
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == 0);
So(v == 1);
So(opti == 2);
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == -1);
So(opti == 3);
});
Convey("No options works", {
int opti = 1;
char *av[1];
int ac = 1;
int v;
char *a = NULL;
av[0] = "program";
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == -1);
});
Convey("No options (but arguments) works", {
int opti = 1;
char *av[2];
int ac = 2;
int v;
char *a = NULL;
av[0] = "program";
av[1] = "123";
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == -1);
So(opti == 1);
});
Convey("Mixed long and short works", {
int opti = 1;
char *av[7];
int ac = 7;
int v;
char *a = NULL;
av[0] = "program";
av[1] = "--value=123";
av[2] = "-f";
av[3] = "--longflag";
av[4] = "-b";
av[5] = "-vxyz";
av[6] = "456";
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == 0);
So(opti == 2);
So(v == 3);
So(strcmp(a, "123") == 0);
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == 0);
So(opti == 3);
So(v == 1);
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == 0);
So(opti == 4);
So(v == 2);
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == 0);
So(opti == 5);
So(v == 4);
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == 0);
So(opti == 6);
So(v == 3);
So(strcmp(a, "xyz") == 0);
So(strcmp(av[opti], "456") == 0);
So(nng_opts_parse(ac, av, case1, &v, &a, &opti) == -1);
So(opti == 6);
});
})
|
C
|
/* Test program for <next-at-end> and
* <leaves-core-file-on-quit> bugs.
*/
#include <stdio.h>
#include <stdlib.h>
#include "../lib/unbuffer_output.c"
int callee (int x)
{
int y = x * x; /* -break1- */
return (y - 2);
}
int main()
{
int *p;
int i;
gdb_unbuffer_output ();
p = (int *) malloc( 4 );
for (i = 1; i < 10; i++)
{
printf( "%d ", callee( i ));
fflush (stdout);
}
printf( " Goodbye!\n" ); fflush (stdout); /* -break2- */
return 0;
}
|
C
|
#include "pustaka.h"
// NAMA : MOCHAMAD SAIFULLAH
// NIM : A11.2018.11511
// KELP : A11.4218
int main()
{
int a1[10] = {NULL}, a2[10] = {NULL};
int a3[10] = {NULL}, a4[10] = {NULL};
a1[0]=1; a1[1]=2; a1[2]=3; a1[3]=4; a1[4]=5; a1[5]=6;
a2[0]=1; a2[1]=2; a2[2]=3; a2[3]=4;
a3[0]=2; a3[1]=4; a3[2]=9; a3[3]=5; a3[4]=1;
a4[0]=2; a4[1]=8; a4[2]=5;
printf("jumlah : %d\n", count_arr(a1, 10));
printf("jumlah : %d\n", count_arr(a2, 10));
printf("jumlah : %d\n", count_arr(a3, 10));
printf("jumlah : %d\n", count_arr(a4, 10));
int arr1[] = { 3, 5, 38, 44, 47 };
int arr2[] = { 3, 44, 38, 5, 47 };
int arr3[] = { 2, 15, 26, 27, 36 };
int arr4[] = { 15, 36, 27, 2, 26 };
cek_urut(arr1, 5);
printf("hasil : %d", cek_urut(arr1, 5));
printf("\n");
printf("\tTugas 3\n");
int arra1[]={3,44,38,5,47};
int arra2[]={15,36,27,2,26};
bubble_sort1(arra1, 5);
bubble_sort1(arra2, 5);
printf("\tTugas 4\n");
int array1[]={3,44,38,5,47};
int array2[]={15,36,27,2,46};
bubble_sort2(array1,5);
bubble_sort2(array2,5);
return 0;
}
|
C
|
#include <stdio.h>
/*
Функция sscanf работает похоже на scanf, но только считывает данные
не из стандартного входа, а из строки.
С её помощью можно конвертировать числа из строки в числа
*/
int main() {
char str[20] = "5-10-1872";
int day, month, year;
// Считываем числа из строки
sscanf(str, "%d-%d-%d", &day, &month, &year);
printf("Day: %d. Month: %d. Year: %d.\n", day, month, year);
// Аналогично -- sprintf(строка, <то же самое, что и в printf>)
}
/*
Пусть есть строки:
char str1[10] = "79";
char str2[10] = "435";
Используйте sscanf, чтобы конвертировать эти строки в числа 79 и 435 соответственно
*/
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_epur_str.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lmarques <lmarques@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/24 21:25:14 by lmarques #+# #+# */
/* Updated: 2016/11/24 21:34:21 by lmarques ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_count_spaces(char *str)
{
int count;
int count_spaces;
count = 0;
count_spaces = 0;
while (str[count])
{
if (str[count] == ' ')
{
count++;
while (count < (int)ft_strlen(str) && str[count] == ' ')
{
count++;
count_spaces++;
}
}
count++;
}
return (count_spaces);
}
char *ft_epur_str(char *str)
{
int count;
int count_str;
char *str_new;
count = 0;
count_str = 0;
str_new = ft_strnew(ft_strlen(str) - ft_count_spaces(str));
while (str[count_str])
{
if (str[count_str] == ' ')
{
str_new[count] = str[count_str];
count++;
count_str++;
while (str[count_str] == ' ')
count_str++;
}
str_new[count] = str[count_str];
count++;
count_str++;
}
return (str_new);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("\t\t1 - \tClientes\n\t\t2 - \tFornecedores\n\t\t3 - \tFaturas\n\n\t\t0 - \tSair\n ");
return 0;
}
|
C
|
// Compare two strings for quick sort
static int cmpfunc(const void* a,const void* b){
const char **ia = (const char **) a;
const char **ib = (const char **) b;
return strcmp(*ia, *ib);
}
// create BWT and SA
struct SA_BWT create_bwt(char* seq){
int length = strlen(seq)+1;
char* appended_seq = (char*) malloc(sizeof(char)*(length+1));
appended_seq = strcpy(appended_seq, seq);
appended_seq[length-1] = '$';
struct permutation permutations[length];
int i, j, k;
// ROTATIONS OF SEQUENCE
printf("\nPermutations of sequence\n\n");
for (i = 0; i < length; i++){
permutations[i].string = (char*) malloc(sizeof(char)*length);
permutations[i].number = i;
for (j = 0; j < length; j++){
k = i+j;
if (k >= length) k = k - length;
permutations[i].string[j] = appended_seq[k];
}
printf("(");
if (permutations[i].number+1 < 10) printf("0");
printf("%d) %s\n",permutations[i].number+1, permutations[i].string); // To print rotations
}
printf("\nPress ENTER\n");
getchar();
printf("\nSorted Permutations of sequence\n\n");
// SORT ROTATIONS
qsort(permutations, length, sizeof(struct permutation), cmpfunc);
for (i = 0; i < length; i++){
printf("(");
if (permutations[i].number+1 < 10) printf("0");
printf("%d) %s\n",permutations[i].number+1, permutations[i].string); //To print sorted strings
}
printf("Press ENTER\n");
getchar();
// Calculate C lookup table (Here we will assume DNA)
int C_table[5]; // $, A, C, G, T
C_table[0] = 0;
C_table[1] = 1;
C_table[2] = 0;
C_table[3] = 0;
C_table[4] = 0;
for (i = length-1; i > 0; i--){
if (permutations[i].string[0] == 'C') C_table[2] = i;
if (permutations[i].string[0] == 'G') C_table[3] = i;
if (permutations[i].string[0] == 'T') C_table[4] = i;
}
printf("\nIndex of the first occurence of each character in the first column\n$-%d A-%d C-%d G-%d T-%d\n\n", C_table[0], C_table[1], C_table[2], C_table[3], C_table[4]);
// To print the C_table
// MAKE BWT SEQUENCE && SUFFIX ARRAY
char* bwt_seq = (char*) malloc(sizeof(char)*(length+1));
int* suffix_array = (int*) malloc(sizeof(int)*(length+1));
for (i = 0; i < length; i++){
bwt_seq[i] = permutations[i].string[length-1];
suffix_array[i] = permutations[i].number+1;
}
printf("\nBWT Sequence (The last column of the sorted permutations:\n\n%s\n\n", bwt_seq); //To print BWT sequence
printf("The suffix array: The original possition of each permutation before sorting\n\n");
for (i = 0; i < length; i++) printf("%d, ", suffix_array[i]); // To print Suffix Array
// Free memory TODO check for more memory leaks (there will be a couple)
for (i = 0; i < length; i++){
free(permutations[i].string);
}
printf("\n\nPress ENTER\n");
getchar();
// RANK Matrix
int* BWT_Rank[5];
for (i = 0; i < 5; i++) BWT_Rank[i] = (int*) malloc(sizeof(int)*(length+1));
int count$ = 0, countA = 0, countC = 0, countG = 0, countT = 0;
for (i = 0; i < length; i++){
if (bwt_seq[i] == '$') count$++;
if (bwt_seq[i] == 'A') countA++;
if (bwt_seq[i] == 'C') countC++;
if (bwt_seq[i] == 'G') countG++;
if (bwt_seq[i] == 'T') countT++;
BWT_Rank[0][i] = count$;
BWT_Rank[1][i] = countA;
BWT_Rank[2][i] = countC;
BWT_Rank[3][i] = countG;
BWT_Rank[4][i] = countT;
}
//To Print the BWT_Rank Matrix
printf("\n\nBWT_Rank matrix:\n");
for (i = 0; i < length; i++){
printf("(%d) $-%d, A-%d, C-%d, G-%d, T-%d\n",i+1, BWT_Rank[0][i], BWT_Rank[1][i], BWT_Rank[2][i], BWT_Rank[3][i], BWT_Rank[4][i]);
}
printf("\nPress ENTER\n");
getchar();
free ((void*)appended_seq);
// Return Struct
struct SA_BWT seq_SA_BWT;
seq_SA_BWT.length = length;
for (i=1; i < 5; i++) seq_SA_BWT.C_table[i] = C_table[i];
seq_SA_BWT.bwt_seq = bwt_seq;
seq_SA_BWT.suffix_array = suffix_array;
for (i=1; i < 5; i++) seq_SA_BWT.BWT_RANK[i] = BWT_Rank[i];
return seq_SA_BWT;
}
|
C
|
/*** p08ex01.c ***/
/*** s12083 2J18 ܖS ***/
#include <stdio.h>
#include <math.h>
#define PAI 3.14159265358979
typedef struct{
int x;
int y;
}point_t;
point_t rotatePoint(point_t point,double theta)
{
point_t npoint;
npoint.x=point.x*cos(theta)-point.y*sin(theta);
npoint.y=point.x*sin(theta)+point.y*cos(theta);
//x cos - y sin , x sin + y cos
return npoint;
}
int main()
{
point_t point={100,100};
double rad0=PAI/4,rad1=-1*PAI/4;
printf(" /4] : (x,y)=(%d,%d)\n",rotatePoint(point,rad0));
printf("-/4] : (x,y)=(%d,%d)\n",rotatePoint(point,rad1));
return 0;
}
/**************** s *****************
/4] : (x,y)=(0,141)
-/4] : (x,y)=(141,0)
*******************************************/
|
C
|
#ifndef __TYPES_H
#define __TYPES_H
#include <stddef.h>
typedef char i8;
typedef short i16;
typedef int i32;
typedef long long i64;
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;
typedef unsigned long long u64;
typedef float f32;
typedef double f64;
#endif /* end of include guard: __TYPES_H */
|
C
|
#include<stdio.h>
// This can help swap two elements using pointers to make code easier.
void swap_double( double *a, double *b ); //For some reason, functions needs to be mentioned here though placed at bottom.
//Sorting method for array
void sort_numeric( double *a, char input )
{
int i, j;
int size=11;
//Using nested loops for using sorting algorithm to sort
for( i = 0; i < size; i++ ) {
for( j = 1; j < size - i;j++ ) {
//Ascending code for input when A or a
if( (*(a + j - 1)) > (*(a + j)) && (input=='A'|| input=='a'))
swap_double( (a + j - 1), (a + j) );
//When Input for descending is here, this code works as the previous lower number is placed higher by swapping.
else if(( *(a + j - 1)) < (*(a + j)) && (input=='D'||input=='d'))
swap_double( (a + j - 1), (a + j) );
}
}
}
int main()
{
double arr[11]={10,0.25,-2342.0,12123,3.145435,6,6,5.999,-2,-5,-109.56};
int i;
for(i=0;i<11;i++)
printf(" %lf\n",arr[i]); //Printing Array
printf("To sort in ascending order, type the following: A or a\n");
printf("To sort in desncending order, type the following: D or d\n");
printf("Input: "); //Input command to ascend or descend
char input;
scanf("%c",&input); //Scaner input
sort_numeric(arr,input); //function execution
printf("After sorting, results is: \n");
for(i=0;i<11 ;i++)
printf(" %lf\n",arr[i]); //Printing out Array that should be sorted.
}
void swap_double( double *a, double *b ) //Makes swapping easier between two elements
{
double _t = *a;
*a = *b;
*b = _t;
}
|
C
|
#include <stdio.h>
int main (){
int c1, c2, c3, c4, nullvote, whitevote, cont, totalvotes, vote;
cont = 0;
totalvotes = 10;
c1 = 0;
c2 = 0;
c3 = 0;
c4 = 0;
nullvote = 0;
whitevote = 0;
while (cont < totalvotes){
printf("Vote for which candidate you want to vote:\n");
printf("Type 1 for candidate 1\n");
printf("Type 2 for candidate 2\n");
printf("Type 3 for candidate 3\n");
printf("Type 4 for candidate 4\n");
printf("Type 5 for a null vote\n");
printf("Type 6 for a white vote\n");
scanf("%d", &vote);
switch(vote){
case 1:
c1++;
cont++;
printf("You voted for candidate 1\n");
break;
case 2:
c2++;
cont++;
printf("You voted for candidate 2\n");
break;
case 3:
c3++;
cont++;
printf("You voted for candidate 3\n");
break;
case 4:
c4++;
cont++;
printf("You voted for candidate 4\n");
break;
case 5:
nullvote++;
cont++;
printf("You voted null\n");
break;
case 6:
whitevote++;
cont++;
printf("You voted white\n");
break;
case 0:
cont=totalvotes+1;
break;
}
}
printf("Quantity of votes for candidate 1: %d\n", c1);
printf("Quantity of votes for candidate 2: %d\n", c2);
printf("Quantity of votes for candidate 3: %d\n", c3);
printf("Quantity of votes for candidate 4: %d\n", c4);
printf("Quantity of null votes: %d\n", nullvote);
printf("Quantity of white votes: %d\n", whitevote);
return 0;
}
|
C
|
#include <stdio.h>
int main() {
int i;
printf("SSD1331Begin\n");
SSD1331Begin();
printf("Clear\n");
SSD1331Clear(0x00);
//for(i=0; i<64; i++) SSD1331DrawPixel(i, i, 0xF800);
printf("String\n");
SSD1331String(0,0,"Hello World!", 0xF800);
printf("Display\n");
SSD1331Display();
return 0;
}
|
C
|
/*
cause_fear.h
*/
#include "defs.h"
/* -------- Fear ---------- */
cause_fear(str) {
object target_obj;
if (!str) {
write("You must specify who you want to frighten.\n");
write("Use: fear <who>\n");
return 1;
}
if (MY_LEVEL < 7 || MY_GUILD_EXP < 669) {
write("You can't use that abilitiy yet.\n");
return 1;
}
if (MY_SPELL_POINTS < 25) {
write("You don't have enough spell points.\n");
return 1;
}
MY_PLAYER->add_spell_point(- 25);
target_obj=present(str, MY_ROOM);
if (!target_obj) {
write(capitalize(str)+" is not here.\n");
return 1;
}
if (!target_obj->query_npc() &&
target_obj->query_level() > 19 &&
MY_LEVEL < 20) {
write("You can't frighten a wizard!\n");
return 1;
}
/* adding this in as a level checker.. all force runaways and all must check versus level - mythos <1-29-96> */
if(target_obj->query_level() > (this_player()->query_level() - 1)) {
write("The target is far too powerful to fear,\n");
return 1;}
if (!target_obj->query_wimpy()) {
write(capitalize(str)+" withstands your fearsome glare.\n");
return 1;
}
write("You glare at "+str+"!\n");
tell_object(target_obj, MY_NAME_CAP+" glares at you! You panic!\n");
target_obj->run_away();
return 1;
}
|
C
|
#include "parser.h"
static char getsymbol() {
char c;
while (isspace(c = getchar()));
if (c == COMMENT_SYMBOL) {
while (getchar() != '\n');
return getsymbol();
}
return c;
}
static const Expr* getExprList(const Expr *vars[], int * const parenLevel) {
int currentLevel = *parenLevel;
const Expr *expr, *arg;
Expr *app;
expr = getExpr(vars, parenLevel);
if (!expr) {
if (*parenLevel < currentLevel) RAISE(NULL, "empty expression\n");
return NULL;
}
if (*parenLevel < currentLevel) return expr;
while (1) {
arg = getExpr(vars, parenLevel);
if (!arg)
if (*parenLevel < currentLevel)
return expr;
else
return NULL;
MALLOC(app)
app->type = APP;
app->data.app.func = expr;
app->data.app.arg = arg;
expr = app;
if (*parenLevel < currentLevel) return expr;
}
}
Expr* parse() {
int parenLevel = 0;
const Expr *vars[256];
for (int i = 0; i < 256; ++i)
vars[i] = NULL;
const Expr *root = getExprList(&vars[0], &parenLevel);
if (!root && parenLevel > -1)
return NULL;
return (Expr*) root;
}
static const Expr* getFunction(const Expr *vars[], int * const parenLevel) {
char c;
const Expr *prev, *body;
Expr *func;
c = getsymbol();
if (c == EOF) RAISE(NULL, "unexpected EOF in function\n")
if (!isalpha(c)) RAISE(NULL, "invalid parameter: %c\n", c)
if (getsymbol() != DOT_SYMBOL) RAISE(NULL, "expected %c\n", DOT_SYMBOL)
MALLOC(func)
prev = vars[c];
vars[c] = func;
body = getExprList(vars, parenLevel);
if (!body) return NULL;
vars[c] = prev;
func->type = FUNC;
func->data.func = (Expr*) body;
return func;
}
static const Expr* getVar(const Expr *vars[], char c) {
Expr *var;
MALLOC(var)
if (!isalpha(c)) RAISE(NULL, "invalid character: %c\n", c)
if (!vars[c]) {
var->type = FREE;
var->data.freeVar = c;
} else {
var->type = BOUND;
var->data.func = (Expr*) vars[c];
}
return var;
}
static const Expr* getExpr(const Expr *vars[], int * const parenLevel) {
char c = getsymbol();
switch (c) {
case LAMBDA_SYMBOL:
return getFunction(vars, parenLevel);
case EOF:
if (*parenLevel > 0) RAISE(NULL, "expected %c\n", CLOSEPAREN_SYMBOL)
--(*parenLevel);
return NULL;
case OPENPAREN_SYMBOL:
++(*parenLevel);
return getExprList(vars, parenLevel);
case CLOSEPAREN_SYMBOL:
if (*parenLevel == 0) RAISE(NULL, "unexpected %c\n", CLOSEPAREN_SYMBOL)
--(*parenLevel);
return NULL;
default:
return getVar(vars, c);
}
}
void freeExpr(const Expr * const expr) {
switch (expr->type) {
case FUNC:
freeExpr(expr->data.func);
break;
case APP:
freeExpr(expr->data.app.func);
freeExpr(expr->data.app.arg);
case BOUND:
case FREE:
break;
case NULL_T:
RAISE(, "cant free null\n")
}
P_DEBUG("freeing %p\n", (void*) expr)
free((void*) expr);
}
|
C
|
#include "bsp_watch.h"
void watch_background(void)
{
TFT_INIT();
lcdFillScreen(&dev, BLACK);
lcdDrawCircle(&dev, CONFIG_WIDTH/2, CONFIG_HEIGHT/2, 100, RED);
}
void watch_pointer(void)
{
float hour_pointer = 0;
float second_pointer = 0;
float minute_pointer = 0;
while(1)
{
// * Params:
// * x: horizontal start position
// * y: vertical start position
// * start: start offset from (x,y)
// * len: length of the line
// * angle: line angle in degrees
// * color: line color
// 绘制秒针
TFTDrawLineByAngle(&dev, CONFIG_WIDTH/2, CONFIG_HEIGHT/2, 0, 80, second_pointer*6, GREEN);
// 绘制分针
TFTDrawLineByAngle(&dev, CONFIG_WIDTH/2, CONFIG_HEIGHT/2, 0, 60, (minute_pointer+second_pointer/60)*6, BLUE);
// 绘制时针
TFTDrawLineByAngle(&dev, CONFIG_WIDTH/2, CONFIG_HEIGHT/2, 0, 40, (hour_pointer+minute_pointer/60)*30, RED);
vTaskDelay(WATCHDelayDebug);
// 绘制秒针
TFTDrawLineByAngle(&dev, CONFIG_WIDTH/2, CONFIG_HEIGHT/2, 0, 80, second_pointer*6, BLACK);
// 绘制分针
TFTDrawLineByAngle(&dev, CONFIG_WIDTH/2, CONFIG_HEIGHT/2, 0, 60, (minute_pointer+second_pointer/60)*6, BLACK);
// 绘制时针
printf("%f\n", hour_pointer);
TFTDrawLineByAngle(&dev, CONFIG_WIDTH/2, CONFIG_HEIGHT/2, 0, 40, (hour_pointer+minute_pointer/60)*30, BLACK);
watch_print_time(&hour_pointer,&minute_pointer,&second_pointer);
}
}
void watch_print_time(float *hour_pointer,float *minute_pointer,float *second_pointer)
{
time_t now;
char strftime_buf[64];
struct tm timeinfo;
time(&now);
// Set timezone to China Standard Time
setenv("TZ", "CST-8", 1);
tzset();
localtime_r(&now, &timeinfo);
strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
*hour_pointer = timeinfo.tm_hour;
*minute_pointer = timeinfo.tm_min;
*second_pointer = timeinfo.tm_sec;
ESP_LOGI(TAG, "当前时间:\tisdst:%d\tyday:%d\twday:%d\tyear:%d\tmon:%d\tmday:%d\thour:%d\tmin:%d\tsec:%d",
timeinfo.tm_isdst, timeinfo.tm_yday,
timeinfo.tm_wday, timeinfo.tm_year,
timeinfo.tm_mon, timeinfo.tm_mday,
timeinfo.tm_hour, timeinfo.tm_min,
timeinfo.tm_sec);
ESP_LOGI(TAG, "The current date/time in Shanghai is: %s", strftime_buf);
}
// struct timeval tv; // struct timeval {
// // time_t tv_sec; /* seconds */
// // suseconds_t tv_usec; /* microseconds */
// // };
// gettimeofday(&tv, NULL); // and gives the number of seconds and microseconds since the Epoch (see
// // time(2)). The tz argument is a struct timezone:
// secondsSinceEpoch = (uint64_t)(tv.tv_sec);
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/shm.h>
#include<sys/sem.h>
#include<errno.h>
#define Key1 1234
#define Key2 7654
#define MaxCount 50
struct shmarea{
unsigned int read;
unsigned int write;
unsigned int userCount;
int buf[50];
};
union semun{
int val;
struct semid *_buf;
struct seminfo *buf;
unsigned short *arr;
}u1;
int main()
{
struct sembuf semp[3];
unsigned short arr[3];
int shm_id,sem_id,ret,ret1,ret2,ret3;
int value1;
struct shmarea *shma;
shm_id=shmget(Key1,3*4096,IPC_CREAT|0666);
if(shm_id<0)
{
perror("Error in share memory creation");
exit(1);
}
shma=shmat(shm_id,0,0);
if(shma<0)
{
perror("Error in attaching memory");
exit(1);
}
sem_id=semget(Key2,3,IPC_CREAT|0600);
if(sem_id<0)
{
perror("Error in semaphore creation");
exit(1);
}
u1.arr=arr;
ret1=semctl(sem_id,0,GETALL,u1);
if(ret1<0)
{
perror("Error in getting semaphore");
exit(1);
}
//printf("Values=%d %d %d",arr[0],arr[1],arr[2]);
while(1)
{
//if(shma->read==50)
//{
// sleep(120);
// }
semp[0].sem_num=2;
semp[0].sem_op=-1;
semp[0].sem_flg=0;
semp[1].sem_num=1;
semp[1].sem_op=-1;
semp[1].sem_flg=0;
ret1=semop(sem_id,semp,2);
if(ret1<0)
{
perror("Semop error");
}
u1.arr=arr;
ret1=semctl(sem_id,0,GETALL,u1);
if(ret1<0)
{
perror("Error in getting semaphore");
exit(1);
}
//printf("\nValues after dec binary semaphore=%d %d %d",arr[0],arr[1],arr[2]);
if((shma->userCount)!=0)
{
value1=shma->buf[shma->read];
printf("\nValue read at %d is %d \n",shma->read,value1);
shma->read=((shma->read+1)%MaxCount);
shma->userCount--;
}
semp[0].sem_num=0;
semp[0].sem_op=+1;
semp[0].sem_flg=0;
//semop(sem_id,&sb3,1);
semp[1].sem_num=1;
semp[1].sem_op=+1;
semp[1].sem_flg=0;
semop(sem_id,semp,2);
u1.arr=arr;
ret1=semctl(sem_id,0,GETALL,u1);
if(ret1<0)
{
perror("Error in getting semaphore");
exit(1);
}
//printf("\nValues after incrementing binary semaphore=%d %d %d",arr[0],arr[1],arr[2]);
}
exit(0);
}
|
C
|
#include<stdio.h>
#include<math.h>
int main(int argc, char *argv[]) {
int n, i, f = 0, x = 1, y = 1, l1, l2, j = 0, k = 0;
long long int a1[200000] = {0}, sum = 0,a2[200000], a;
scanf("%d", &n);
for(i = 0 ; i < n ; i++) {
scanf("%lld", &a);
if(a > 0)
a1[j++] = a;
else
a2[k++] = -a;
sum = sum + a;
}
if(sum > 0)
printf("first");
else if(sum < 0)
printf("second");
else {
for(i = 0 ; i < j&&i<k ;i++) {
if(a1[i] > a2[i]) {
printf("first");
break;
}
else if(a1[i] < a2[i]){
printf("second");
break;
}
}
if(i==j||i==k) {
if(a > 0)
printf("first");
else
printf("second");
}
return 0;
}
return 0;
}
|
C
|
#include <stdio.h>
int n;
char S[17];
void gen(int len, int prev)
{
if(len == n)
{
printf("%s\n", S);
return;
}
S[len] = '0';
gen(len + 1, 0);
if(prev != 1)
{
S[len] = '1';
gen(len + 1, 1);
}
}
int main()
{
int i, f1 = 1, f2 = 2;
freopen("vectors.in", "r", stdin);
freopen("vectors.out", "w", stdout);
scanf("%d", &n);
for(i = 2; i <= n; i++)
{
int f3 = f1 + f2;
f1 = f2;
f2 = f3;
}
printf("%d\n", f2);
gen(0, 0);
return 0;
}
|
C
|
// This is good for max to be a value greater than 0
int maxVal(int num1, int num2)
{
return ((num1 < num2)?num2:num1);
}
int maxSubArray(int* nums, int numsSize)
{
int len = numsSize - 1;
int max = nums[0];
int max_end = nums[0];
int itr = 1;
while(itr <= len)
{
max_end = maxVal(nums[itr],(max_end+nums[itr]));
max = maxVal(max,max_end);
++itr;
}
return max;
}
|
C
|
#include <stdio.h>
#include "minunit.h"
// https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/
/**
* Definition for singly-linked list.
*/
struct ListNode
{
int val;
struct ListNode *next;
};
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB)
{
if (headA == NULL || headB == NULL)
{
return NULL;
}
struct ListNode *nodeA = headA;
struct ListNode *nodeB = headB;
while (nodeA != nodeB)
{
if (nodeA != NULL)
{
nodeA = nodeA->next;
}
else
{
nodeA = headB;
}
if (nodeB != NULL)
{
nodeB = nodeB->next;
}
else
{
nodeB = headA;
}
}
return nodeA;
}
struct ListNode *getIntersectionNode1(struct ListNode *headA, struct ListNode *headB)
{
struct ListNode *headToA = headA, *headToB = headB;
int countA = 0, countB = 0;
while (headToA != NULL)
{
headToA = headToA->next;
countA++;
}
while (headToB != NULL)
{
headToB = headToB->next;
countB++;
}
headToA = headA, headToB = headB;
if (countA > countB)
{
int gap = countA - countB;
for (int i = 0; i < gap; i++)
{
headToA = headToA->next;
}
}
else if (countB > countA)
{
int gap = countB - countA;
for (int i = 0; i < gap; i++)
{
headToB = headToB->next;
}
}
while (headToA != headToB)
{
headToA = headToA->next;
headToB = headToB->next;
}
return headToA;
}
MU_TEST(test_case)
{
mu_check(5 == 7);
}
MU_TEST_SUITE(test_suite)
{
MU_RUN_TEST(test_case);
}
int main()
{
MU_RUN_SUITE(test_suite);
MU_REPORT();
return MU_EXIT_CODE;
}
|
C
|
#include "linked_list.h"
t_list *list_create(void *_content)
{
t_list *new;
new = (t_list *)malloc(sizeof(t_list));
if (!new)
return (NULL);
new->content = content;
new->next = NULL;
return (new);
}
void list_add_front(t_list **_list_first, t_list *_to_add)
{
*_list_first =
}
|
C
|
/*
*
*
* project: hw3
* name:
* user??
* date:
* file: hw3.c
*/
#include "hw3.h"
void sorting_angle(Points points)
{
/*
* Code
*/
}
//
Points convex(Points points)
{
/*
* Code
*/
}
void write2csv(Points points, char *file)
{
FILE *f = fopen(file, "w");
TEST_FILE(f,"write2csv",file);
Point *data = points.data;
for (int i = 0; i < points.length; ++i)
fprintf(f, "%f,%f\n",data[i].x,data[i].y);
fclose(f);
}
Points createData(int seed,int num)
{
srand48(seed); /* seeding the pseudorandom number generator */
Point* data = malloc(sizeof(Point) * num);
Points points = {data, num};
for (int i = 0; i < num; i++)
{
data[i].x = drand48();
data[i].y = drand48();
}
return points;
}
void freePoints(Points points)
{
free(points.data);
}
|
C
|
#define max 5
#include<stdio.h>
void display(int *,int);
int main(){
int a[max],i;
printf("enter values:");
for(i=0;i<max;i++)
scanf("%d",(a+i));
display(a,max);
return 0;
}
void display(int *b,int s){
int i;
printf("\nvalues:\n");
for(i=0;i<s;i++)
printf(" %d ",*(b+i));
}
|
C
|
/* *************************************************
DESCRIPTION:
Implemets of:
Swap functions:
Int by poiners.
Values by size_t pointers.
Pointers by size_t **.
Athor: Gal Dahan
***************************************************/
#include <stdlib.h> /* for size_t */
void SwapSizeT (size_t *a, size_t *b);
void SwapSizeTPointers (size_t **a, size_t **b);
void SwapInt (int *a, int *b);
/* Swap values of 2 size_t variables */
void SwapSizeT(size_t *a, size_t *b)
{
size_t temp;
temp = *a;
*a = *b;
*b = temp;
}
/* Swap values of 2 size_t* variables */
void SwapSizeTPointers(size_t **a, size_t **b)
{
size_t *temp;
temp = *a;
*a = *b;
*b = temp;
}
/* Swap values of 2 int variables */
void SwapInt(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
|
C
|
#include <vector.h>
#include <stdio.h>
#include <stdlib.h>
#include <test.h>
static void display(struct vector_node *element)
{
switch(TYPE(element)) {
case CHAR:
printf("%c ", VALUE(element));
break;
case SHORT:
printf("%hd ", VALUE(element));
break;
case INT:
printf("%d ", VALUE(element));
break;
case LONG:
printf("%ld ", VALUE(element));
break;
case FLOAT:
printf("%f ", VALUE_F(element));
break;
case DOUBLE:
printf("%lf ", VALUE_D(element));
break;
}
}
int main(void)
{
struct vector *v = malloc(sizeof(struct vector));
struct element t1;
struct element t2;
struct vector *h;
int val1 = 10;
char val2 = 'a';
short val3 = 34;
long val4 = 4560007867645;
float val6 = 34.333;
double val7 = 3456.9999;
if (v == NULL)
return 0;
vector(v);
v->append(v, ELEMENT(val6, FLOAT));
v->append(v, ELEMENT(val4, LONG));
v->append(v, ELEMENT(val2, CHAR));
v->append(v, ELEMENT(val7, DOUBLE));
v->append(v, ELEMENT(val1, INT));
v->prepend(v, ELEMENT(val3, SHORT));
v->prepend(v, ELEMENT(val7, DOUBLE));
printf("Reverse:\n");
h = v;
for_each_rev(element, h)
display(element);
printf("\n");
printf("Non Reverse:\n");
h = v;
for_each(element1, h)
display(element1);
printf("\n");
printf("\nInserting at 6 element:\n");
v->insert(v, 6, ELEMENT(val2, CHAR));
h = v;
for_each(element2, h)
display(element2);
printf("\n");
for_each_rev(element3, h)
display(element3);
printf("\n\nChoping at end\n");
v->chop(v);
h = v;
for_each(element2, h)
display(element2);
printf("\n");
for_each_rev(element3, h)
display(element3);
printf("\n\nBehead at front\n");
v->behead(v);
h = v;
for_each(element2, h)
display(element2);
printf("\n");
for_each_rev(element3, h)
display(element3);
printf("\n\nDeleting at 3\n");
v->delete(v, 3);
h = v;
for_each(element2, h)
display(element2);
printf("\n");
for_each_rev(element3, h)
display(element3);
printf("\n\nSize of vector\n");
printf("size = %d\n", v->size(v));
printf("\nset value in pos 3\n");
v->set(v, 5, ELEMENT(val7, DOUBLE));
h = v;
for_each(element2, h)
display(element2);
printf("\n");
printf("get at los 3\n");
v->get(v, 3, &t1);
printf("%d %d\n", t1.field, t1.field_type);
printf("\n");
printf("\nmoving data in list\n");
v->move(v, 1, 3);
h = v;
for_each(element2, h)
display(element2);
printf("\n");
/* printf("\nspliting vector into two\n"); */
/* h = v->splice(v, 3); */
/* for_each(element2, h) */
/* display(element2); */
/* printf("\n"); */
printf("\nset value in pos 1\n");
v->set(v, 1, ELEMENT(val1, INT));
h = v;
for_each(element2, h)
display(element2);
printf("\n");
printf("geting first element\n");
v->clear(v);
h = v;
for_each(element2, h)
display(element2);
/* v->first(v, &t1); */
/* printf("%d %d\n", t1.field, t1.field_type); */
/* printf("\n"); */
/* printf("\nset value in pos 3\n"); */
/* v->set(v, 3, ELEMENT((val1 + 3), INT)); */
/* h = v; */
/* for_each(element2, h) */
/* display(element2); */
/* printf("\n"); */
/* printf("geting last element\n"); */
/* v->last(v, &t1); */
/* printf("%c %d\n", t1.field, t1.field_type); */
/* v->destruct(v); */
/* v = NULL; */
/* if (v != NULL) */
/* v->insert(v, 6, ELEMENT(val2, CHAR)); */
return 0;
}
|
C
|
#include "holberton.h"
/**
* print_most_numbers - prints from 0 to 9 and a new line
*
*
* Return: 0 Success
*/
void print_most_numbers(void)
{
int n;
for (n = '0'; n <= '9'; n++)
if (n != '2' && n != '4')
_putchar (n);
_putchar('\n');
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* check_arg1.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abosch <abosch@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/08/27 14:18:31 by abosch #+# #+# */
/* Updated: 2020/09/13 10:55:59 by abosch ### ########.fr */
/* */
/* ************************************************************************** */
#include "parser.h"
void check_dir(t_list *label, t_token *tok)
{
if (tok->type == SYMBOL)
{
if (!ft_strisnumber(tok->content->buf))
ft_printerr(EBADDIR);
}
else if (tok->type == LABELARG)
{
if (!is_valid_label(label, tok->content->buf))
ft_printerr(EINVLAB, tok->content->buf);
}
else
ft_printerr(EBADDIR);
}
void check_reg_ind(t_list *label, t_token *tok)
{
int reg;
if (tok->type == SYMBOL)
{
if ((reg = is_reg(tok->content->buf)) == 0
&& !ft_strisnumber(tok->content->buf))
ft_printerr(ENOREGIND);
else if (reg != 0)
tok->type = REG;
}
else if (tok->type == LABELARG)
{
if (!is_valid_label(label, tok->content->buf))
ft_printerr(EINVLAB, tok->content->buf);
}
else
ft_printerr(ENOREGIND);
}
void check_reg_dir(t_list *label, t_list_link **lnk)
{
t_token *tok;
tok = (*lnk)->content;
if (tok->type == SYMBOL)
{
if (!is_reg(tok->content->buf))
ft_printerr(ENOREG);
tok->type = REG;
*lnk = (*lnk)->next;
}
else if (tok->type == DIR)
{
check_dir(label, (*lnk)->next->content);
*lnk = (*lnk)->next->next;
}
else
ft_printerr(ENOREGDIR);
}
void check_ind_dir(t_list *label, t_list_link **lnk)
{
t_token *tok;
tok = (*lnk)->content;
if (tok->type == SYMBOL)
{
if (!ft_strisnumber(tok->content->buf))
ft_printerr(ENONUM);
*lnk = (*lnk)->next;
}
else if (tok->type == LABELARG)
{
if (!is_valid_label(label, tok->content->buf))
ft_printerr(EINVLAB, tok->content->buf);
*lnk = (*lnk)->next;
}
else if (tok->type == DIR)
{
check_dir(label, (*lnk)->next->content);
*lnk = (*lnk)->next->next;
}
else
ft_printerr(ENODIRIND);
}
void check_all_type(t_list *label, t_list_link **lnk)
{
t_token *tok;
int reg;
tok = (*lnk)->content;
if (tok->type == SYMBOL || tok->type == LABELARG)
{
if ((reg = is_reg(tok->content->buf)) == 0
&& !is_valid_label(label, tok->content->buf)
&& !ft_strisnumber(tok->content->buf))
ft_printerr(ENOREGIND);
if (reg != 0)
tok->type = REG;
*lnk = (*lnk)->next;
}
else if (tok->type == DIR)
{
check_dir(label, (*lnk)->next->content);
*lnk = (*lnk)->next->next;
}
else
ft_printerr(ENOALL);
}
|
C
|
/////////////////////jLIB//////////////////////////////////////////
#define _GNU_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <time.h>
#include <errno.h>
#include <string.h>
/////////////////////MACROS////////////////////////////////////////
//Print error info and exit
#define ERR(source) (fprintf(stderr,"%s:%d\n",__FILE__,__LINE__),\
perror(source),kill(0,SIGKILL), \
exit(EXIT_FAILURE))
//Debug
#define DBG(source) (fprintf(stderr,"%s:%d\t",__FILE__,__LINE__),\
perror(source),
//Call function and exit if return value != result
#define CALL_AND_CHECK(function, result)\
do {\
if (function != result)\
{\
ERR(#function);\
}\
} while (0)
//Call function and exit if error occured
#define CALL_AND_EXIT_ON_ERR(function) CALL_AND_CHECK(function, 0)
//Iterate over table
#define foreach(item, array)\
for(int keep=1,\
count=0,\
size=sizeof (array)/sizeof *(array);\
count != size;\
keep=1, count++)\
for(item = (array)+count; keep; keep = !keep)
#define TRUE (!FALSE)
#define FALSE (0)
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#define ABS(a) (((a) < 0) ? -(a) : (a))
//Ensures that x is between the limits set by low and high. If low is greater than high the result is undefined.
#define CLAMP(x, low, high) (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x)))
#define IMPLIES(x, y) (!(x) || (y))
#define COMPARE(x, y) (((x) > (y)) - ((x) < (y)))
#define SIGN(x) COMPARE(x, 0)
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*a))
#define SWAP(x, y, T) do { T tmp = (x); (x) = (y); (y) = tmp; } while(0)
#define SORT2(a, b, T) do { if ((a) > (b)) SWAP((a), (b), T); } while (0)
#define SET(d, n, v) do{ size_t i_, n_; for (n_ = (n), i_ = 0; n_ > 0; --n_, ++i_) (d)[i_] = (v); } while(0)
#define ZERO(d, n) SET(d, n, 0)
//Checking whether a floating point x is Not A Number
#define ISNAN(x) ((x) != (x))
////////////////////////////////////////////////////////////////////
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "hashtag.h"
#include "mergesort.h"
/* Aplica a funcao MERGE auxiliar do mergesort
Versao estavel (usa vetor auxiliar b)
INPUT : Item para ordenar, limite inferior(low), medio(mid)
e limite superior (high) */
void merge(ItemToSort a, int low, int mid, int high){
int i = low, j = mid + 1, k = 0;
while (i <= mid && j <= high) {
if(less_sort(a[i],a[j]))
b[k++] = a[i++];
else
b[k++] = a[j++];
}
while (i <= mid)
b[k++] = a[i++];
while (j <= high)
b[k++] = a[j++];
k--;
while (k >= 0) {
a[low + k] = b[k];
k--;
}
}
/* Mergesort
INPUT : Item para ordenar(a), limite inferior(l), limite superior(r) */
void mergesort(ItemToSort a, int l, int r){
int m = (r+l)/2;
if (r <= l) return;
mergesort(a, l, m);
mergesort(a, m+1, r);
merge(a, l, m, r);
}
/* Aplica algoritmo de mergesort ao vetor auxiliar usando
memoria dinamica
INPUT : Item para ordenar(a), limite inferior(r), limite superior(l) */
void Sort(ItemToSort a, int r, int l){
if(l <= r) return;
/*cria vetor auxiliar*/
b = (ItemToSort)malloc(sizeof(Item)*(l-r+1));
mergesort(a, r, l);
/*liberta vetor auxiliar*/
free(b);
}
|
C
|
// gcc -O3 -o fib-c fib-c.c
#include <stdio.h>
int fib(int n) {
if (n <= 1) return n;
return fib(n-1)+fib(n-2);
}
int main() {
for (int x = 0; x <= 45; x++) {
printf("fib(%d)=%d\n", x, fib(x));
}
}
|
C
|
/*
* Faça um programa para mostrar o valor total a pagar por um produto em promoção.
* O valor básico do produto e percentual de desconto são obtidos do código do produto
* que possui 4 algarismos de acordo com a seguinte regra:
* Código do produto: xxyy
* Preço básico: XX*15,00 + YY
* Percentual de desconto: YY
* Por exemplo: código do produto: 2314
* Preço : 23*15,00 + 14,00 = 359,00
* Desconto: 14%
* Total a pagar: 308,74
* Lembre-se que: 32/10 = 3 (quociente da divisão inteira) e
* 32%10 = 2( resto da divisão inteira)
*/
#include <stdio.h>
#define FATOR_PRECO 15 //Definido na regra de negócio
#define ITENS_CADASTRADOS 10 //Itens que o sistema pode suportar
#define REFERENCIA_DOS_PRODUTOS 5 //Atributos por produto
//Matriz referência para armazenamento dos itens
float matriz[ITENS_CADASTRADOS][REFERENCIA_DOS_PRODUTOS]={0};
//Variáveis globais utilizadas nas funções auxiliares e na main
int gCodigo = 0;
int gPosicaoItem = 0;
int gIdProduto = 1;
int gColunaItem = 0;
int gColunaCodigo = 1;
int gColunaPreco = 2;
int gColunaDesconto = 3;
int gColunaTotal = 4;
float gPrecoDoProduto;
float gDescontoDoProduto;
float gTotalDoProduto;
//Cadastrar produtos
void sessaoCadastrarProduto();
//Calcular preço bruto do produto
float calcularPrecoBruto(int codigoDoProduto);
//Calcular o desconto do produto
float calcularDesconto(int codigoDoProduto);
//Calcular o valor total do produto
float calcularTotal(int codigoDoProduto);
//Apagar um produto já listado
void apagarProduto(int identificacaoDoProduto);
//Listar a matriz com todas as posições
void listarItensCadastrados(void);
int main(void){
int menu;
printf("\n\nPROGRAMA DE CADASTRO DE PRODUTOS\n\n");
printf("Informe a opção desejada\n");
printf("1 - CADASTRAR ITEM\n2 - COLSULTAR ITENS CADASTRADOS\n3 - APAGAR ITEM\n4 - SAIR DO PROGRAMA\n");
printf("Sua opção: ");
scanf("%i", &menu);
while(menu < 1 || menu > 4){
printf("ERRO!\n");
printf("Informe a opção desejada\n");
printf("1 - CADASTRAR ITEM\n2 - LISTAR ITENS CADASTRADOS\n3 - APAGAR ITEM\n4 - SAIR DO PROGRAMA\n");
printf("Sua opção: ");
scanf("%i", &menu);
}
switch (menu)
{
case 1:
sessaoCadastrarProduto();
break;
case 2:
listarItensCadastrados();
break;
case 3:
printf("\n\n******ATENÇÃO******\n");
printf("TEM CERTEZA QUE DESEJA APAGAR UM PRODUTO?");
printf("0 = NÃO / 1 = SIM: ");
int apagar;
scanf("%i", &apagar);
int itemParaApagar;
if(apagar){
printf("Informe o ID do Produto: ");
scanf("%i", &itemParaApagar);
apagarProduto(itemParaApagar-1);
}else{
listarItensCadastrados();
}
break;
case 4:
break;
default:
break;
}
return 0;
}
/****Início da função de Cadastro de Produtos****/
void sessaoCadastrarProduto(void){
float precoBruto;
float desconto;
float total;
printf("\n\n******SESSÃO DE CADASTRO DE PRODUTOS******\n");
printf("Informe o código de 4 dígitos: ");
scanf("%i", &gCodigo);
while(gCodigo < 1000 || gCodigo > 9999){
printf("\nERRO! Digite um código de 4 dígitos\n");
printf("SEÇÃO DE CADASTRO DE PRODUTO\n");
printf("Informe o código de 4 dígitos: ");
scanf("%i", &gCodigo);
}
matriz[gPosicaoItem][gColunaItem] = gIdProduto;
matriz[gPosicaoItem][gColunaCodigo] = gCodigo;
matriz[gPosicaoItem][gColunaPreco] = calcularPrecoBruto(gCodigo);
matriz[gPosicaoItem][gColunaDesconto] = calcularDesconto(gCodigo);
matriz[gPosicaoItem][gColunaTotal] = calcularTotal(gCodigo);
printf("ID \t CODIGO\t PREÇO BRUTO\t DESCONTO%%\t TOTAL\n");
printf("%2.0f\t", matriz[gPosicaoItem][gColunaItem]);
printf(" %.0f\t", matriz[gPosicaoItem][gColunaCodigo]);
printf(" R$ %.2f\t", matriz[gPosicaoItem][gColunaPreco]);
printf(" %2.0f%%\t", matriz[gPosicaoItem][gColunaDesconto]);
printf("R$ %.2f\t", matriz[gPosicaoItem][gColunaTotal]);
printf("\n");
gPosicaoItem++;
gIdProduto++;
if(gPosicaoItem == ITENS_CADASTRADOS - 1){
printf("ATENÇÃO! VOCÊ SÓ PODE CADASTRAR MAIS UM PRODUTO\n");
}
if(gPosicaoItem == ITENS_CADASTRADOS){
printf("ATENÇÃO! SISTEMA NÃO SUPORTA MAIS ITENS CADASTRADOS\n");
}
printf("******FIM DA SESSÃO DE CADASTRO DE PRODUTOS******\n");
main();
}
/****Fim da função de Cadastro de Produtos****/
/****Início da função de Calculo de preço bruto de Produtos****/
float calcularPrecoBruto(int codigoDoProduto){
gPrecoDoProduto = ( (codigoDoProduto / 100) * FATOR_PRECO) + codigoDoProduto % 100;
return gPrecoDoProduto;
}
/****Fim da função de Calculo de preço bruto de Produtos****/
/****Início da função de Calculo de desconto de Produtos****/
float calcularDesconto(int codigoDoProduto){
gDescontoDoProduto = codigoDoProduto % 100;
return gDescontoDoProduto;
}
/****Fim da função de Calculo de desconto de Produtos****/
/****Início da função de Calculo de valor total do Produto****/
float calcularTotal(int codigoDoProduto){
gTotalDoProduto = gPrecoDoProduto - (gPrecoDoProduto * (gDescontoDoProduto / 100) );
return gTotalDoProduto;
}
/****Fim da função de Calculo de valor total do Produto****/
/****Início da função de listar todos os produtos****/
void listarItensCadastrados(void){
printf("\n\n******SESSÃO DE LISTAGEM DE PRODUTOS******\n");
printf("ID \t CODIGO\t PREÇO BRUTO\t DESCONTO%%\t TOTAL\n");
for(int i = 0; i < ITENS_CADASTRADOS; i++){
printf("%2.0f\t", matriz[i][gColunaItem]);
printf(" %.0f\t", matriz[i][gColunaCodigo]);
printf(" R$ %.2f\t", matriz[i][gColunaPreco]);
printf(" %2.0f%%\t", matriz[i][gColunaDesconto]);
printf("R$ %.2f\t", matriz[i][gColunaTotal]);
printf("\n");
}
printf("******FIM DA SESSÃO DE LISTAGEM DE PRODUTOS******\n");
main();
}
/****Fim da função de listar todos os produtos****/
/****Início da função de apagar um produto determinado****/
void apagarProduto(int identificacaoDoProduto){
matriz[identificacaoDoProduto][gColunaItem] = 0;
matriz[identificacaoDoProduto][gColunaCodigo] = 0;
matriz[identificacaoDoProduto][gColunaPreco] = 0;
matriz[identificacaoDoProduto][gColunaDesconto] = 0;
matriz[identificacaoDoProduto][gColunaTotal] = 0;
main();
}
/****Fim da função de apagar um produto determinado****/
|
C
|
/*2 – Implement a function void fill_vec(int *vec, int n)
* that, through the use of pointers,
* stores a set of 20 integers (read from the keyboard) into a vector.*/
#include <stdio.h>
#include "input_vec.h"
int main( ) {
//initialize the variables
int vector[20];
int n = 20;
//call the funtion
fill_vec(&vector[0], n);
//output the results to confirmation
int j;
printf("the inputed values were:\n indice-valor\n");
for (j= 0; j < 10; j++){
printf("%d-%d \t |%d-%d \t\n", j, vector[j], j+10, vector[j+10]);
}
printf("\nTHANK YOU\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct _list_node
{
int key;
struct _list_node *next;
}list_node;
void *list_insert(list_node *head, int key)
{
list_node *p = head;
while(p->next != NULL)
p = p->next;
list_node *node = calloc(1, sizeof(list_node));
node->key = key;
node->next = NULL;
p->next = node;
}
void list_delete(list_node *del_node)
{
list_node *p = del_node->next;
del_node->key = p->key; /*copy data*/
del_node->next = p->next;
free(p);
}
void list_dispaly(list_node *head)
{
list_node *p = head->next;
printf("list:");
while(p)
{
printf(" %d", p->key);
p = p->next;
}
printf("\n");
}
int main(int argc, char *argv[])
{
list_node *head = calloc(1, sizeof(list_node));
head->key = 0;
head->next = NULL;
list_insert(head, 1);
list_insert(head, 2);
list_insert(head, 3);
list_insert(head, 4);
list_insert(head, 5);
list_dispaly(head);
list_delete(head->next->next);
list_dispaly(head);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
double n;
scanf("%lf",&n);
if(n<0||n>100)
printf("Fora de intervalo\n");
else if(0<=n&&n<=25.0)
printf("Intervalo [0,25]\n");
else if(25.0<n&&n<=50.0)
printf("Intervalo (25,50]\n");
else if(50<n&&n<=75)
printf("Intervalo (50,75]\n");
else if(75<n&&n<=100)
printf("Intervalo (75,100]\n");
return 0;
}
|
C
|
/**
@file ficheiros.c
Funções relacionadas com ficheiros.
*/
#include "ficheiros.h"
/** Caminho para guardar o ficheiro dos utilizadores. */
#define PATH_UTILIZADORES "/var/www/html/users/"
/**Função que importa um tabuleiro do ficheiro. */
ESTADO puzzle_reader(ESTADO e, FILE *fp){
int l,c;
int i,j,m=0;
char linha[100];
if (fscanf(fp,"%d %d ", &i, &j) == 2)
{
e.num_lins = i;
e.num_cols = j;
if (fscanf(fp,"%s",linha) == 1)
{
for(l = 0; l < e.num_lins; l++)
{
for(c = 0; c < e.num_cols; c++)
{
switch (linha[m])
{
case '.': e.grelha[l][c] = VAZIA; break;
case 'x':
case 'X': e.grelha[l][c] = FIXO_X; break;
case 'o':
case 'O': e.grelha[l][c] = FIXO_O; break;
case '#': e.grelha[l][c] = BLOQUEADA; break;
case 'c': e.grelha[l][c] = SOL_X; break;
case 'p': e.grelha[l][c] = SOL_O; break;
case 'h': e.grelha[l][c] = AJUDA; break;
}
m++;
}
}
}
}
return e;
}
/** Após uma alteração no tabuleiro, a função escreve no ficheiro o tabuleiro resultante. */
void puzzle_writer(ESTADO e,FILE *fp)
{
int l,c;
fprintf(fp,"%d %d ", e.num_lins, e.num_cols);
for(l=0; l < e.num_lins; l++)
{
for(c = 0; c < e.num_cols; c++)
{
switch (e.grelha[l][c])
{
case VAZIA: fprintf(fp,".");
break;
case FIXO_X: fprintf(fp,"x");
break;
case FIXO_O: fprintf(fp,"o");
break;
case BLOQUEADA: fprintf(fp,"#");
break;
case SOL_X: fprintf(fp,"c");
break;
case SOL_O: fprintf(fp,"p");
break;
case AJUDA: fprintf(fp,"h");
break;
}
}
}
}
/** Função responsável por ler o ESTADO que se encontra num ficheiro.
* Transforma os caracteres lidos no tabuleiro do jogo.
* Para além disso, lê a stack que está no ficheiro e atribui-a ao parametro stack do ESTADO.
*/
ESTADO state_reader(ESTADO e)
{
char caminho_utilizador[100];
sprintf(caminho_utilizador,"%splayer%d.txt",PATH_UTILIZADORES,e.utilizador);
FILE *fp = fopen(caminho_utilizador,"r");
chmod(caminho_utilizador,0777);
e = puzzle_reader(e,fp);
e.stack = readstack(fp);
fclose(fp);
return e;
}
//Função responsável por escrever no ficheiro o resultado da alteração do estado.
void state_writer(ESTADO e)
{
char auxiliar[20];
sprintf(auxiliar,"%splayer%d.txt",PATH_UTILIZADORES,e.utilizador);
FILE *fp = fopen(auxiliar,"w");
chmod(auxiliar,0777);
puzzle_writer(e,fp);
stack2str(&e,fp);
fclose(fp);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* instructions_update.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jacher <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/10 14:02:55 by jacher #+# #+# */
/* Updated: 2021/05/15 12:28:17 by jacher ### ########.fr */
/* */
/* ************************************************************************** */
#include "../sort.h"
void update_inst_third(t_list **tmp)
{
t_list *del;
if ((((ft_strncmp((const char *)(*tmp)->content, "rra", 4) == 0)
&& ft_strncmp((const char *)(*tmp)->next->content, "rrb", 4) == 0))
|| ((ft_strncmp((const char *)(*tmp)->content, "rrb", 4) == 0)
&& ft_strncmp((const char *)(*tmp)->next->content, "rra", 4) == 0))
{
free((*tmp)->content);
free((*tmp)->next->content);
del = (*tmp)->next;
(*tmp)->next = (*tmp)->next->next;
free(del);
(*tmp)->content = ft_strdup("rrr");
}
}
void update_inst_bis(t_list **tmp)
{
t_list *del;
if ((((ft_strncmp((const char *)(*tmp)->content, "sa", 3) == 0)
&& ft_strncmp((const char *)(*tmp)->next->content, "sb", 3) == 0))
|| ((ft_strncmp((const char *)(*tmp)->content, "sb", 3) == 0)
&& ft_strncmp((const char *)(*tmp)->next->content, "sa", 3) == 0))
{
free((*tmp)->content);
free((*tmp)->next->content);
del = (*tmp)->next;
(*tmp)->next = (*tmp)->next->next;
free(del);
(*tmp)->content = ft_strdup("ss");
}
else
update_inst_third(tmp);
}
int update_inst(t_list **l)
{
t_list *tmp;
t_list *del;
tmp = *l;
while (tmp && tmp->next)
{
if ((((ft_strncmp((const char *)tmp->content, "ra", 3) == 0)
&& ft_strncmp((const char *)tmp->next->content, "rb", 3) == 0))
|| ((ft_strncmp((const char *)tmp->content, "rb", 3) == 0)
&& ft_strncmp((const char *)tmp->next->content, "ra", 3) == 0))
{
free(tmp->content);
free(tmp->next->content);
del = tmp->next;
tmp->next = tmp->next->next;
free(del);
tmp->content = ft_strdup("rr");
}
else
update_inst_bis(&tmp);
if (tmp->content == NULL)
return (-1);
tmp = tmp->next;
}
return (0);
}
|
C
|
#include "lists.h"
#include <stdlib.h>
/**
* delete_nodeint_at_index - delete a node form the list.
* @head : list
* @index : int
* Return: 1.
*/
int delete_nodeint_at_index(listint_t **head, unsigned int index)
{
unsigned int x = 0, count = 0;
listint_t *temp = *head;
listint_t *new;
if (temp == NULL)
return (-1);
if (index == 0)
{
*head = temp->next;
free(temp);
return (1);
}
while (temp != NULL)
{
temp = temp->next;
count++;
}
if (index > count)
return (-1);
temp = *head;
while (x < index - 1)
{
temp = temp->next;
x++;
}
new = temp;
temp = temp->next;
new->next = temp->next;
free(temp);
return (1);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int sacarFactoreo(int numero);
float sacarDivision(int numeroUno, int numeroDos);
int sacarProducto(int numeroUno, int numeroDos);
int sacarResta(int numeroUno, int numeroDos);
int sacarSuma(int numeroUno, int numeroDos);
int pedirMenu(char texto[]);
int main()
{
int factor;
int primerOperando;
int segundoOperando;
int opcionIngresada;
char continuar='s';
do
{
opcionIngresada=pedirMenu("1. Ingresar 1er operando(A=X)\n2. Ingresar 2do operando(B=Y)\n3. Calcular las operaciones\n4. Informar los resultados\n5. Salir del menu\nSeleccione una opcion: ");
switch(opcionIngresada)
{
case 1:
printf("Ingrese el 1er operando (X): ");
scanf("%d",&primerOperando);
break;
case 2:
printf("Ingrese el 2do operando (Y): ");
scanf("%d",&segundoOperando);
break;
case 3:
factor=sacarFactoreo(primerOperando);
break;
case 4:
printf("%d",factor);
break;
case 5:
continuar='n';
break;
default:
printf("La opcion ingresada no es valida");
break;
}
system("pause");
system("cls");
}
while(continuar=='s');
return 0;
}
int pedirMenu(char texto[])
{
int miOpcion;
printf("%s",texto);
scanf("%d",&miOpcion);
return miOpcion;
}
int sacarSuma(int numeroUno, int numeroDos)
{
int miSuma;
miSuma=numeroUno + numeroDos;
return miSuma;
}
int sacarFactoreo(int numero)
{
int resultado;
int acumulador=1;
if(numero==0 || numero==1)
{
resultado=1;
}
else
{
acumulador=numero*sacarFactoreo(numero-1);
resultado=acumulador;
}
return resultado;
}
int sacarResta(int numeroUno, int numeroDos)
{
int miResta;
miResta=numeroUno - numeroDos;
return miResta;
}
int sacarProducto(int numeroUno, int numeroDos)
{
int miProducto;
miProducto=numeroUno * numeroDos;
return miProducto;
}
float sacarDivision(int numeroUno, int numeroDos)
{
float miDivision;
miDivision= (float)numeroUno / numeroDos;
return miDivision;
}
|
C
|
/******************************************************************************/
/* */
/* motord.c - motor daemon for controlling boat motors connected to the */
/* Raspberry Pi. */
/* */
/* Creates and listens to requests on a message queue to control */
/* the motor. The motor interface is defined in motor.h */
/* */
/* The daemon also creates a listener and sender thread for an */
/* external connection. */
/* */
/******************************************************************************/
// Standard headers
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
#include <stdarg.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <errno.h>
// For message queue
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
// For signal handling
#include <signal.h>
// For posix threads
#include <pthread.h>
// For rand48
#include <sys/time.h>
// Socket headers
#include <sys/socket.h> // Socket structure declarations
#include <netinet/in.h> // Structures needed for internet domain addresses
#include <netdb.h> // Defines structure hostnet
#include "motor.h"
#define M_ID 2013
// Node Controller port
#define NC_PORT 2018
// message queue variable
// This is global because it will be read by multiple threads.
int msqid;
// These threads are responsible for keeping lifetime connection to other nodes.
// This will receive messages from message queue and send them out the socket.
void *sender_thread(void *arg);
// This will listen to the socket and place messages on message queue.
void *receiver_thread(void *arg);
// Signal thread
// This will remain blocked until a signal arrives
// (recommended technique when dealing with threads and signals)
void *sig_waiter(void *arg);
// Signal handler function
void sig_handler(int sig);
// Error function to exit gracefully (frees resources)
void error(int error_code, char *msg, ...) {
va_list argptr;
// Error code is used to figure out if there are resources that need to be freed.
switch (error_code) {
case 2:
// Listener/Receiver thread cleanup
// TODO clean up threads
case 1:
// Message queue cleanup
// Deleting message queue
msgctl(msqid, IPC_RMID, NULL);
default:
break;
}
// Get variable number of arguments and pass to fprintf.
va_start(argptr, msg);
vfprintf(stderr, msg, argptr);
va_end(argptr);
exit(error_code);
}
int main(int argc, char *argv[]) {
// Command line arguments
// General variables
int i;
char buffer[256];
// Socket variables
int sockfd_c, sockfd_l, newsockfd;
struct sockaddr_in serv_addr, host_addr;
struct hostent *server;
// Signal handler variables
sigset_t all_signals;
struct sigaction new_act;
int nsigs;
int sigs[] = { SIGTERM, SIGBUS, SIGSEGV, SIGFPE };
// Thread variables
pthread_t handlr_id, snd_id, rcv_id;
// Setup for managing signals
sigfillset(&all_signals);
nsigs = sizeof(sigs) / sizeof(int);
for ( i = 0; i < nsigs; i++ )
sigdelset(&all_signals, sigs[i]);
// Blocking all signals other than those listed in the signal array above.
sigprocmask(SIG_BLOCK, &all_signals, NULL);
sigfillset(&all_signals);
for ( i = 0; i < nsigs; i++ ) {
new_act.sa_handler = sig_handler;
new_act.sa_mask = all_signals;
new_act.sa_flags = 0;
// This is saying that if the listed signals are receive,
// ignore any other incoming signals and run the sig_handler.
if (sigaction(sigs[i], &new_act, NULL) == -1) {
perror("Can't set signals :\n");
exit(1);
}
}
// Creating message queue.
// This will be used to relay messages from:
// 1. Local processes (bluetooth remote) that wants to send message to handler
// 2. The receiver thread to the message handler thread
// 3. The handler thread to sender thread
if ((msqid = msgget(M_ID, (IPC_CREAT | 0600))) == -1) {
perror("msgget failed :\n");
exit(1);
}
// Make message handler thread to be defined in motor.c
if (pthread_create(&handlr_id, NULL, msg_handler, (void *) &msqid) != 0) {
fprintf(stderr, "pthread_create failed\n");
exit(1);
}
// Fork bluetooth wiimote process
switch( fork() ) {
case -1:
error(2, "Error forking");
case 0:
execl("./wiimoted.py", NULL);
perror("Error running bluetooth listener\n");
exit(1);
}
// Wait for message handler to exit (should never happen)
pthread_join(handlr_id, NULL);
// Deleting message queue
if (msgctl(msqid, IPC_RMID, NULL) == -1) {
fprintf(stderr, "Message queue could not be deleted.\n");
exit(1);
}
return 0;
}
void sig_handler(int sig) {
// TODO handle closing signals and properly free resources.
}
void *sig_waiter(void *arg) {
while (1)
pause();
}
|
C
|
#include "synth_wind.h"
double *cdf_v(double **param, double v, int i){
int j , n, prog;
double vn, *res;
n = ceil(v/DV);
res = malloc(n*sizeof(double));
vn = 0;
*res = DV*mgd_f(param, vn);
// printf(" Generating CDF for State \033[31;1m%d\033[0m\n", i);
// fflush(stdout);
for(j=1; j<=n; j++){
//print progress
prog = ceil(100*j/n);
// printf("\r \033[31;1m%d\033[0m", prog);
// fflush(stdout);
vn+=DV;
*(res+j) = *(res+j-1) + DV*mgd_f(param, vn);
// printf("%f %f\n", vn, res);
}
// printf("\n\n");
return(res);
}
|
C
|
#include "landCellState.h"
void landCellCheckState(landCell *lc,
MPI_Request *request,
MPI_Status status,
int message[2],
MPI_Request *request1)
{
int ierr;
// Another squirrel was here
lc->populationInflux[lc->populationInfluxIndex]++;
if (message[0] == INFECTED)
//Another infected squirrel was here
lc->infectionLevel++;
ierr = MPI_Irecv(message, 2, MPI_INT, MPI_ANY_SOURCE, SQUIRREL_TAG, MPI_COMM_WORLD, request);
if (ierr != MPI_SUCCESS)
printf("LANDCELL: I couldn't receive from Squirrel\n");
// Send to that squirrel the Infection level
int sendMessage[3];
// population Influx level
int tmp_populationInflux = 0;
int i;
for (i = 0; i < 3; i++)
tmp_populationInflux += lc->populationInflux[i];
sendMessage[0] = lc->actor.myRank;
sendMessage[1] = tmp_populationInflux;
sendMessage[2] = lc->infectionLevel;
MPI_Isend(sendMessage, 3, MPI_INT, message[1], LANDCELL_TAG, MPI_COMM_WORLD, request1);
if (ierr != MPI_SUCCESS)
printf("LANDCELL: I couldn't send to squirrel\n");
}
|
C
|
/*
若文件已经打开,可以用fstat获取文件信息(效率高,直接从内存获取)
如文件未打开,用stat
对于符号链接,stat和fstat可以获取符号链接指向文件的属性,而lstat获取的是
符号链接文件本身的属性
*/
# include <sys/types.h>
# include <sys/stat.h>
# include <unistd.h>
# include <stdio.h>
# include <string.h>
# include <error.h>
int main()
{
int ret = -1;
struct stat buf;
memset(&buf,0,sizeof(buf));
ret = stat("test.txt",&buf);
if(ret < 0)
{
perror("stat错误!\n");
_exit(-1);
}
printf("inode = %ld\n",buf.st_ino);
printf("size = %d\n",buf.st_size);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main() {
return 0;
}
void fillRand(int mat[4][4]){
int i, j;
for(i=0; i<4; i++){
for(j=0; j<4; j++){
mat[i][j]=(rand()%2000)-1000;
}
}
}
void rotateCCW270(int mat[4][4]){
int mat2[4][4], i, j;
for(i=0; i<4; i++){
for(j=0; j<4; j++){
mat2[i][j]=mat[3-j][i];
}
}
for(i=0; i<4; i++){
for(j=0; j<4; j++){
mat[i][j]=mat2[i][j];
}
}
}
void flipH(int mat[4][4]){
int mat3[4][4], i, j;
for(i=0; i<4; i++){
for(j=0; j<4; j++){
mat3[i][j]=mat[i][3-j];
}
}
for(i=0; i<4; i++){
for(j=0; j<4; j++){
mat[i][j]=mat3[i][j];
}
}
}
void transposSide(int mat[4][4]){
int i, j, mat4[4][4];
for(i=0; i<4; i++){
for(j=0; j<4; j++){
mat4[i][j]=mat[3-j][3-i];
}
}
for(i=0; i<4; i++){
for(j=0; j<4; j++){
mat[i][j]=mat4[i][j];
}
}
}
|
C
|
#include<unistd.h>
void ft_putchar(char c)
{
write(1, &c, 1);
}
int is_letter(char c)
{
return (('a'<= c && c <= 'z')||('A'<= c && c <= 'Z'));
}
void alpha_mirror(char *str)
{
int i;
i = 0;
while (str[i])
{
if('a'<= str[i] && str[i]<= 'z')
ft_putchar('a' + 'z' - str[i]);
else if('A'<= str[i] && str[i]<= 'Z')
ft_putchar('A' + 'Z' - str[i]);
else
ft_putchar(str[i]);
i++;
}
}
int main (int ac, char **av)
{
int i;
i = 0;
if(ac != 2)
{
ft_putchar('\n');
return 0;
}
alpha_mirror(av[1]);
ft_putchar ('\n');
return 0;
}
|
C
|
/*
Author: Aryaman Kejriwal
Course: Introduction to Programming in C
instructor: Gilbert Pajela
Assignment: Lab 7.1
This program defines a type long_lat_t that stores latitude and longitude and methods to scan, print and check
their equality.
*/
#include <stdio.h>
typedef struct {
int degrees;
int minutes;
char direction;
} long_lat_t;
long_lat_t scan_long_lat(long_lat_t l);
void print_long_lat(long_lat_t l);
int long_lat_equal(long_lat_t l1, long_lat_t l2);
int main() {
long_lat_t l1;
long_lat_t l2;
printf("First Longitude/Latitude:\n");
l1 = scan_long_lat(l1);
printf("Second Longitude/Latitude:\n");
l2 = scan_long_lat(l2);
printf("First Longitude/Latitude:\n");
print_long_lat(l1);
printf("Second Longitude/Latitude:\n");
print_long_lat(l2);
int are_equal = long_lat_equal(l1, l2);
//Checks the returned value from lat_long_equal()
if(are_equal) {
printf("The first longitude/latitude is equal to the second.\n");
} else {
printf("The first longitude/latitude is not equal to the second.\n");
}
return(0);
}
//Gets data for and returns a long_lat_t
long_lat_t scan_long_lat(long_lat_t l) {
printf("Enter the degrees> ");
scanf("%d", &(l.degrees));
printf("Enter the minutes> ");
scanf("%d", &(l.minutes));
printf("Enter the direction> ");
scanf(" %c", &(l.direction));
return(l);
}
//Prints a long_lat_t
void print_long_lat(long_lat_t l) {
printf("The data of the latitude/longitude is as follows:\n");
printf("Degrees:\t%d\nMinutes:\t%d\nDirection:\t%c\n", l.degrees, l.minutes, l.direction);
}
//Returns 1 if all members of l1 are equal to all members of l2 and 0 otherwise
int long_lat_equal(long_lat_t l1, long_lat_t l2) {
if(l1.degrees == l2.degrees && l1.minutes == l2.minutes && l1.direction == l2.direction) {
return(1);
} else {
return(0);
}
}
|
C
|
/*
* Crypt Kicker
* PC/UVa IDs: 110204/843
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORDS_IN_DICTIONARY 1000
#define MAX_WORD_LENGTH 16
#define MAX_LINE_LENGTH 160
/* 字典,不同长度的词分组存储 */
char dict[MAX_WORD_LENGTH + 1][MAX_WORDS_IN_DICTIONARY][MAX_WORD_LENGTH + 1];
/* 字典中单词的个数,按长度分组 */
int nDWords[MAX_WORD_LENGTH + 1];
int is_unique(char words[][MAX_WORD_LENGTH + 1], int n) {
int i;
if (n) {
for (i = 0; i < n; i++) {
if (!strcmp(words[i], words[n])) {
return 0;
}
}
}
return 1;
}
int split(const char *text, char words[][MAX_WORD_LENGTH + 1], int *n) {
int l;
char *p;
*n = l = 0, p = words[*n];
while (*text) {
if (*text == ' ' || *text == '\n') {
*p = '\0';
if (is_unique(words, *n)) {
(*n)++;
}
p = words[*n], l = 0;
} else {
*p = *text, p++, l++;
}
text++;
}
if (l) {
*p = '\0';
if (is_unique(words, *n)) {
(*n)++;
}
}
return (*n);
}
int try_map(const char *ciphertext, const char *dword, char map[], char rmap[],
int l) {
int i, k;
for (i = 0; i < l; i++, ciphertext++, dword++) {
k = *ciphertext - 'a';
if (map[k]) {
if (map[k] != (*dword)) {
return 0;
}
} else {
map[k] = *dword;
k = *dword - 'a';
if (rmap[k]) {
return 0;
}
rmap[k] = *ciphertext;
}
}
return 1;
}
int decrypt(const char aEWords[][MAX_WORD_LENGTH + 1], char map[], char rmap[],
int k, int n) {
int i, l, r;
char nmap[26], nrmap[26];
l = strlen(aEWords[k]);
for (i = 0; i < nDWords[l]; i++) {
memcpy(nmap, map, 26), memcpy(nrmap, rmap, 26);
/* 尝试匹配 aEWords[k] 与 dict[l][i] */
if (try_map(aEWords[k], dict[l][i], nmap, nrmap, l)) {
/* 最后一个单词,返回成功 */
if (k + 1 == n) {
memcpy(map, nmap, 26), memcpy(rmap, nrmap, 26);
return 1;
}
/* 否则解密下一个单词 */
if (decrypt(aEWords, nmap, nrmap, k + 1, n)) {
memcpy(map, nmap, 26), memcpy(rmap, nrmap, 26);
return 1;
}
}
}
return 0;
}
int main() {
int nEWords; /* number of encrypted words */
char aEWords[MAX_LINE_LENGTH][MAX_WORD_LENGTH + 1]; /* 密文单词 */
int lEWords[MAX_LINE_LENGTH]; /* 密文单词的长度 */
char mapping[26], rmapping[26]; /* */
int i, l, n, result;
char buff[MAX_LINE_LENGTH + 1];
/* 初始化字典 */
for (i = 0; i <= MAX_WORD_LENGTH; i++) {
nDWords[i] = 0;
}
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%s", buff);
l = strlen(buff);
strcpy(dict[l][nDWords[l]], buff);
nDWords[l]++;
}
fgets(buff, MAX_LINE_LENGTH + 1, stdin); /* the last \n */
/* 读入密文 */
while (fgets(buff, MAX_LINE_LENGTH + 1, stdin) != NULL) {
split(buff, aEWords, &nEWords);
/* 排序后提高匹配的效率 */
qsort(aEWords, nEWords, MAX_WORD_LENGTH + 1,
(int (*)(const void *, const void *))strcmp);
/* 解密 */
memset(mapping, 0, 26), memset(rmapping, 0, 26);
result = decrypt(aEWords, mapping, rmapping, 0, nEWords);
/* 输出 */
for (i = 0; buff[i]; i++) {
if (buff[i] == '\n') {
break;
} else if (buff[i] == ' ') {
putchar(' ');
} else {
putchar(result ? mapping[buff[i] - 'a'] : '*');
}
}
putchar('\n');
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct element{
int value;
struct element *prev, *next;
} element;
typedef struct linked_list{
element *start;
int count;
} ll;
ll* create_ll(){
element *head = (element*)malloc(sizeof(element));
head->value=0;
head->prev=NULL;
head->next=NULL;
ll *linked_list = (ll*)malloc(sizeof(ll));
linked_list->start=head;
linked_list->count=0;
return linked_list;
}
void print_ll(ll *linked_list){
puts("");
int index=0;
element* temp=linked_list->start;
if (temp->next!=NULL){
temp=linked_list->start->next;
}
if (temp->next==NULL && temp->prev==NULL){
printf("There is no elements"); return;
}
while (temp->next!=NULL){
printf("ll[%d]=%d\n", index, temp->value);
index++;
temp=temp->next;
}
if (temp->prev!=NULL)
printf("ll[%d]=%d\n", index, temp->value);
}
void print_ll_bck(ll *linked_list){
int index=0;
element *temp = linked_list->start;
if (temp->next!=NULL)
temp=linked_list->start->next;
if (temp->next==NULL && temp->prev==NULL){
printf("There is no elements"); return;
}
while(temp->next!=NULL){
temp=temp->next;
index++;
}
while (temp->prev!=NULL){
printf("ll[%d]=%d\n", index, temp->value);
index--;
temp=temp->prev;
}
}
void del_node_at_inx(ll* linked_list, int index){
if (index<0) {printf("Index must ba grater or equal 0"); return; }
int ix;
element* temp=linked_list->start;
for (ix=0; ix<=index; ix++){
if (temp->next!=NULL)
temp=temp->next;
if (temp->next==NULL && ix<index)
{
printf("There is no such an index");
return;
}
}
if (temp->next!=NULL){
temp->next->prev=temp->prev;
temp->prev->next=temp->next;
}
else
temp->prev->next=NULL;
free(temp);
}
void add_node_at_inx(ll* linked_list, int value, int index){
element* temp=linked_list->start;
if (index<0) { printf("Error: index must be greater than 0"); fflush(stdout); return; }
while(temp->next!=NULL && index>0){
temp=temp->next;
index--;
}
element* node = (element*)malloc(sizeof(element));
node->next=temp->next;
node->prev=temp;
temp->next=node;
node->value=value;
if (node->next!=NULL)
node->next->prev=node;
linked_list->count++;
}
int get_node_inx_by_val(ll* linked_list, int value){
element* temp= linked_list->start;
int ix=0;
while (temp->next!=NULL){
if (temp->value==value)
return ix;
ix++;
temp=temp->next;
}
if (temp->next==NULL)
if (temp->value==value){
ix++;
return ix;
}
return -1;
}
void replace_node_by_value(ll* linked_list, int fromVal, int toVal){
element* temp= linked_list->start;
while (temp->next!=NULL){
if (temp->value==fromVal){
temp->value=toVal;
return;
}
temp=temp->next;
}
if (temp->next==NULL)
if (temp->value==fromVal){
temp->value=toVal;
}
}
void delete_node_by_value(ll* linked_list, int value){
element* temp= linked_list->start;
while (temp->next!=NULL){
if (temp->value==value){
temp->next->prev=temp->prev;
temp->prev->next=temp->next;
free(temp);
return;
}
temp=temp->next;
}
if (temp->next==NULL)
if (temp->value==value){
temp->prev->next=NULL;
return;
}
}
int main(){
ll* linked_list = create_ll();
int choose, val, idx, toVal;
while(1==1){
printf("What do you want to do? 1-add an element, 2-print elements 3-print backwards, 4-Delete element at index, 5-Get first index by value, 6-replace values, 7-delete element by value: ");
scanf("%d", &choose);
switch(choose){
case 1:
printf("Input value of element and index you want to put it after: ");
scanf("%d %d", &val, &idx);
add_node_at_inx(linked_list, val, idx);
break;
case 2: print_ll(linked_list); printf("\n"); break;
case 3: print_ll_bck(linked_list); printf("\n"); break;
case 4:
printf("Input index of element you want to delete: ");
scanf("%d", &idx);
del_node_at_inx(linked_list, idx);
break;
case 5:
printf("Input value you looking for: ");
scanf("%d", &val);
printf("Is at index %d", get_node_inx_by_val(linked_list, val));
break;
case 6:
printf("Input value you want to replace and value to replace with: ");
scanf("%d %d", &val, &toVal);
replace_node_by_value(linked_list, val, toVal);
break;
case 7:
printf("Input value to delete: ");
scanf("%d", &val);
delete_node_by_value(linked_list, val);
break;
default: printf("Wrong choice\n");
}
printf("\n\n\n\n");
}
}
|
C
|
/*
* Write a pointer version of the function strcat that we showed
* in Chapter 2: strcat(s,t) copies the string t to the end of s
*/
#include <stdio.h>
#define BUFFER 1000
void strcat2(char *s, char *t) {
while (*++s); //iterate pointer to end of string s
while (*s++ = *t++);
}
int main() {
char s[] = "hello ";
char t[] = "world!";
strcat2(s, t);
printf("%s\n", s);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#ifndef NO_PROTECT
#define LEFT_DATA_CAN_ *(can_type*)stk->data_canary
#define RIGHT_DATA_CAN_ *(can_type*)(stk->data_canary + stk->capacity * sizeof(data_type) + sizeof(can_type))
#endif
#define CHECK_STK_ check_stk_err(stk, __LINE__)
typedef int data_type;
typedef int can_type;
const int BASE_STK_SIZE = 20;
const can_type const_r_stk_canary = 101;
const can_type const_l_stk_canary = 201;
enum errors {
NO_ERROR = 0,
STACK_UNDERFLOW = -1,
STACK_OVERFLOW = -2,
DATA_SIZE_ERR = -3,
DATA_CAPACITY_ERR = -4,
NULL_STK_POINTER = -5,
DATA_LEFT_CANARY_ERR = -6,
DATA_RIGHT_CANARY_ERR = -7,
STK_LEFT_CANARY_ERR = -8,
STK_RIGHT_CANARY_ERR = -9,
HASH_ERR = -10
};
typedef struct Stack_tag {
#ifndef NO_PROTECT
can_type left_stk_can;
#endif
#ifdef TWO_LVL_PROTECT
int hash;
#endif
char* data_canary;
data_type* data;
int size;
int capacity;
#ifndef NO_PROTECT
can_type right_stk_can;
#endif
} Stack;
void StackPush (Stack *stk, const data_type value);
int StackPop (Stack *stk);
int StackPeek (Stack* stk);
void StackCtor (Stack* stk, const int capacity );
void StackDtor (Stack* stk);
void StackResize (Stack* stk, int new_capacity);
void StackDump (Stack* stk, const int line, const int error);
int check_stk_err(Stack* stk, const int line);
int MurMurHash (Stack* stk);
int stk_status (Stack* stk);
|
C
|
#include "holberton.h"
/**
* print_last_digit - function that prints the last digit of a number.
* @NumberIntg: Variable type int.
* Return: Return the last digit of a number.
*/
int print_last_digit(int NumberIntg)
{
NumberIntg %= 10;
NumberIntg = (NumberIntg < 0) ? (-1) * NumberIntg : NumberIntg;
_putchar(NumberIntg + '0');
return (NumberIntg);
}
|
C
|
/*----------------------------------------------------------------------------*\
| link.c |
| |
| Copyright 2002-2007, Team Brainix, original authors. |
| All rights reserved. |
\*----------------------------------------------------------------------------*/
/*
| This program is free software: you can redistribute it and/or modify it under
| the terms of the GNU General Public License as published by the Free Software
| Foundation, either version 3 of the License, or (at your option) any later
| version.
|
| This program is distributed in the hope that it will be useful, but WITHOUT
| ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
| FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
| details.
|
| You should have received a copy of the GNU General Public License along with
| this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <fs/fs.h>
/*----------------------------------------------------------------------------*\
| do_fs_link() |
\*----------------------------------------------------------------------------*/
int do_fs_link(const char *path1, const char *path2)
{
/*
| Perform various checks, and create a new link (directory entry) for an
| existing file. Return 0 on success, or a negative error number.
*/
inode_t *inode_ptr_1 = path_to_inode(path1);
inode_t *inode_ptr_2 = path_to_inode(path2);
if (inode_ptr_1 == NULL)
{
/* The first path name could not be resolved. */
inode_put(inode_ptr_1);
inode_put(inode_ptr_2);
return -err_code;
}
if (inode_ptr_1->i_links_count >= LINK_MAX)
{
/* The file is already linked the maximum number of times. */
inode_put(inode_ptr_1);
inode_put(inode_ptr_2);
return -(err_code = EMLINK);
}
if (!super_user && is_dir(inode_ptr_1))
{
/* Only the super user may link to directories. */
inode_put(inode_ptr_1);
inode_put(inode_ptr_2);
return -(err_code = EPERM);
}
if (inode_ptr_2 != NULL)
{
/* The second path name resolved. */
inode_put(inode_ptr_1);
inode_put(inode_ptr_2);
return -(err_code = EEXIST);
}
/* All checks passed. Perform the link. */
inode_ptr_1->i_links_count++;
inode_ptr_1->dirty = true;
inode_put(inode_ptr_1);
return 0;
}
/*----------------------------------------------------------------------------*\
| do_fs_unlink() |
\*----------------------------------------------------------------------------*/
int do_fs_unlink(const char *path)
{
/*
| Perform various checks, and remove a link to a file. Return 0 on success, or
| a negative error number.
*/
inode_t *inode_ptr = path_to_inode(path);
if (inode_ptr == NULL)
{
/* The path name could not be resolved. */
inode_put(inode_ptr);
return -err_code;
}
if (inode_ptr->ino == EXT2_ROOT_INO)
{
inode_put(inode_ptr);
return -(err_code = EBUSY);
}
if (!super_user && is_dir(inode_ptr))
{
/* Only the super user may unlink directories. */
inode_put(inode_ptr);
return -(err_code = EPERM);
}
/* All checks passed. Perform the unlink. */
if (--inode_ptr->i_links_count == 0)
;
inode_ptr->dirty = true;
inode_put(inode_ptr);
return 0;
}
|
C
|
#include "holberton.h"
#include <stdlib.h>
/**
* malloc_checked - allocates memory using malloc
*
* @b: size of the memory allocated
* Return: pointer to the allocated memory
*/
void *malloc_checked(unsigned int b)
{
void *memory;
memory = malloc(b);
if (memory == NULL)
{
exit(98);
}
return (memory);
}
|
C
|
#include <stdio.h> /* for printf() and fprintf() */
#include <sys/socket.h> /* for recv() and send() */
#include <unistd.h> /* for close() */
#include <string.h>
#include "ClientInfo.h"
#define BUFSIZE 200 /* Size of receive buffer */
#define USERNUM 2 /* Number of users */
#define USERBUF 100 /* Size of userlist buffer */
void DieWithError(char *errorMessage); /* Error handling function */
void HandleTCPClient(struct clientinfo *users, struct clientinfo *currentUser, int clntSocket) {
char recvBuffer[BUFSIZE]; /* Buffer for received message */
char sendBuffer[BUFSIZE]; /* Buffer for sending message */
int recvMsgSize; /* Size of received message */
while (1) {
/* Receive message from client */
if ((recvMsgSize = recv(clntSocket, recvBuffer, BUFSIZE, 0)) < 0)
DieWithError("recv() failed");
recvBuffer[recvMsgSize] = '\0';
/* Get the user list by command 1 */
if (strcmp(recvBuffer, "Option 1") == 0) {
printf("Return user list!\n");
int i;
char userList[USERBUF] = "There are 2 users: \n";
for (i = 0; i < USERNUM; i++) {
strcat(userList, users[i].username);
strcat(userList, "\n");
}
/* Send the user list to the client */
if (send(clntSocket, userList, strlen(userList), 0) != strlen(userList))
DieWithError("send() failed");
}
/* Send a message by command 2 */
else if (strcmp(recvBuffer, "Option 2") == 0) {
/* Receive the target username from client */
if ((recvMsgSize = recv(clntSocket, recvBuffer, BUFSIZE, 0)) < 0)
DieWithError("recv() failed");
recvBuffer[recvMsgSize] = '\0';
int i;
struct clientinfo *targetUser;
/* Find the target user */
for (i = 0; i < USERNUM; i++) {
if (strcmp(users[i].username, recvBuffer) == 0) {
targetUser = &users[i];
printf("Got a message to <%s>\n", recvBuffer);
break;
}
}
/* Receive the target message from client */
if ((recvMsgSize = recv(clntSocket, recvBuffer, BUFSIZE, 0)) < 0)
DieWithError("recv() failed");
recvBuffer[recvMsgSize] = '\0';
printf("The message is <%s>\n", recvBuffer);
strcat(targetUser->msgBuffer, recvBuffer); /* Store the message under the target username */
strcpy(sendBuffer, "Message sent successfully!");
printf("%s\n", sendBuffer);
/* Send the successful notice to the client */
if (send(clntSocket, sendBuffer, strlen(sendBuffer), 0) != strlen(sendBuffer))
DieWithError("send() failed");
}
/* Get user's messages by command 3 */
else if (strcmp(recvBuffer, "Option 3") == 0) {
printf("Send back <%s> message!\n", currentUser->username);
/* Check if user has messages */
if (strcmp(currentUser->msgBuffer, "") == 0) {
printf("There is no message for <%s>.\n", currentUser->username);
} else {
printf("Sending out messages: <%s>\n", currentUser->msgBuffer);
}
/* Send user's message to the client */
if (send(clntSocket, currentUser->msgBuffer, strlen(currentUser->msgBuffer), 0)
!= strlen(currentUser->msgBuffer))
DieWithError("send() failed");
}
/* Initiate a chat with friend by command 4 */
else if (strcmp(recvBuffer, "Option 4") == 0) {
printf("Client disconnected!\n\n");
close(clntSocket); /* Close the socket that handles client */
break;
}
/* Chat with friend by command 5 */
else if (strcmp(recvBuffer, "Option 5") == 0) {
printf("Client disconnected!\n\n");
close(clntSocket); /* Close the socket that handles client */
break;
}
else if (strcmp(recvBuffer, "Option 6") == 0) {
printf("Client disconnected!\n\n");
close(clntSocket); /* Close the socket that handles client */
break;
}
strcpy(recvBuffer, ""); /* Set recvBuffer back to an empty string */
strcpy(sendBuffer, ""); /* Set sendBuffer back to an empty string */
}
}
|
C
|
int main()
{
int n, year, a, b, k, i, t, sum;
int x[12]={3,1,3,2,3,2,3,3,2,3,2,3};
int y[12]={3,0,3,2,3,2,3,3,2,3,2,3};
cin >> n;
for(i=0;i<n;i++)
{
cin >> year >> a >> b;
sum = 0;
if(a>b)
{
k = a;
a = b;
b = k;
}
if((year%4==0&&year%100!=0)||(year%400==0))
{
for(t=a-1;t<b-1;t++) //?????!?a?????x[a-1]!!!
sum = sum + x[t];
}
else
{
for(t=a-1;t<b-1;t++)
sum = sum + y[t];
}
if(sum%7==0)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
}
|
C
|
/*
1.Sa se scrie un program care calculeaza suma elementelor unui
vector folosindu-ne doar de variabile de tip pointer.
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int nr, suma = 0, * adr, * i, * n;
printf("Cate elemente sunt in vector?\n ");
scanf("%d", &nr);
adr = (int*)malloc(nr * sizeof(int));
n = adr + nr;
printf("Introduceti elementele vectorului: \n");
for (i = adr; i < n; i++)
{
scanf("%d", i);
suma = suma + *i;
}
printf("Suma este: %d \n", suma);
free(adr);
system("pause");
return 0;
}
|
C
|
#include <GL/glew.h>
#include <GL/glut.h>
//#include <GL/gl.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stdarg.h>
#include <math.h>
#include "./lib.h"
#define DEBUG
//Triangle indices for the bunny
int * bunny_indices;
GLuint vertex_ID;
GLuint texture_ID[2];
int * vertex_count;
GLuint p; //program
GLuint time = 0; //for animation
GLuint toon = 0; //for toon shading
GLuint twotex = 0; //for toon shading
//bunny as global so that it can be accessed from any function
ply_object bunny;
projection_data proj;
modelview_data mod;
light_params lights[2];
material_params material;
GLuint num_lights = 1;
class MeshObject {
private:
float * vertices;
int amount_of_vertices;
int * faces_indices;
float * faces_normals;
int amount_of_faces;
float * vertex_normals;
float * tex_coordinates;
public:
MeshObject(const char *);
}
MeshObject::MeshObject(const char * file_name) {
//BEGIN PLY FILE HANDLING
FILE *ply;
char line[LINE_LENGTH]; //line to be read
bunny.amount_of_vertices = 0;
bunny.amount_of_faces = 0;
ply = fopen (file_name, "rt"); //open ply file
//read header
while (fgets(line, LINE_LENGTH, ply) != NULL)
{
/* convert the string to a long int */
if (!strncmp (line, "element vertex", 14)) {
sscanf(line, "element vertex %i", &bunny.amount_of_vertices);
} else if (!strncmp (line, "element face", 12)) {
sscanf(line, "element face %i", &bunny.amount_of_faces);
}
else if (!strncmp(line, "end_header", 10)) {
break;
}
}
#ifdef DEBUG
printf("file format says %i vertices, %i faces\n",
bunny.amount_of_vertices,
bunny.amount_of_faces);
#endif
//read vertices
int i;
float x;
float y;
float z;
//create vertex table for pushing into GLSL
bunny.vertices = (float *) malloc(bunny.amount_of_vertices * 3 * sizeof(float));
bunny.tex_coordinates = (float *) malloc(bunny.amount_of_vertices * 2 *
sizeof(float)); //only u and v for texture
//set the vertex coordinates into bunny.vertices
for(i = 0; i < bunny.amount_of_vertices; i++) {
if(fgets(line, LINE_LENGTH, ply) != NULL)
{
sscanf(line, "%f %f %f", &x, &y, &z);
bunny.vertices[(3*i)] = x;
bunny.vertices[(3*i)+1] = y;
bunny.vertices[(3*i)+2] = z;
//trivial x=u, y=v mapping
bunny.tex_coordinates[2*i] = x;
bunny.tex_coordinates[2*i+1] = y;
}
}
//the indices of the faces is needed for what?
bunny.faces_indices = (int *) malloc(bunny.amount_of_faces * 3 * sizeof(int));
//we need the face normal to be able to shade the faces correclty
bunny.faces_normals = (float *) malloc(bunny.amount_of_faces * 3 * sizeof(float));
//the vertex normals
bunny.vertex_normals = (float *) malloc(bunny.amount_of_vertices * 3 * sizeof(float));
//count the face normals
int amount_of_face_indices;
int a, b, c;
int * amount_of_faces_per_vertex = (int *) malloc(bunny.amount_of_vertices * sizeof(int));
for(i = 0; i < bunny.amount_of_vertices; i++) {
amount_of_faces_per_vertex[i] = 0;
}
bool * visited = (bool*) malloc(bunny.amount_of_faces * sizeof(bool*));
for(i = 0; i < bunny.amount_of_faces; i++) {
visited[i] = false;
}
int ** vertex_in_faces =(int**) malloc(bunny.amount_of_vertices * sizeof(int*));
for (i = 0; i < bunny.amount_of_vertices; i++){
vertex_in_faces[i] = (int *)malloc(9 * sizeof(int)); //hope this is enough
int j;
for (j = 0; j < 9; j++) {
vertex_in_faces[i][j] = -1;
}
}
//todoo, free vertex_in_faces and visited after they're not needed
for(i = 0; i < bunny.amount_of_faces; i++) {
fscanf (ply, "%i %i %i %i", &amount_of_face_indices, &a, &b, &c);
if (amount_of_face_indices == 3) //we're only interested in triangels
{
//save the index of each vertex
bunny.faces_indices[3*i] = a;
bunny.faces_indices[(3*i)+1] = b;
bunny.faces_indices[(3*i)+2] = c;
vertex_in_faces[a][amount_of_faces_per_vertex[a]] = i;
vertex_in_faces[b][amount_of_faces_per_vertex[b]] = i;
vertex_in_faces[c][amount_of_faces_per_vertex[c]] = i;
amount_of_faces_per_vertex[a]++;
amount_of_faces_per_vertex[b]++;
amount_of_faces_per_vertex[c]++;
}
else {
fprintf(stderr, "error, bad index data: not triangle!");
}
}
//just choose the face index where to start recursive calculation
float reference[3];
lazy_calc_normal(bunny.faces_indices[3*vertex_in_faces[0][0]],
bunny.faces_indices[3*vertex_in_faces[0][0]+1],
bunny.faces_indices[3*vertex_in_faces[0][0]+2],
reference);
//count the face normals
for(i = 0; i < bunny.amount_of_faces; i++) {
a = bunny.faces_indices[3*i];
b = bunny.faces_indices[(3*i)+1];
c = bunny.faces_indices[(3*i)+2];
//point vectors to the vertices for the triangle
float v1[3] = {bunny.vertices[(a * 3)],
bunny.vertices[(a * 3) + 1],
bunny.vertices[(a * 3) + 2]};
float v2[3] = {bunny.vertices[(b * 3)],
bunny.vertices[(b * 3) + 1],
bunny.vertices[(b * 3) + 2]};
float v3[3] = {bunny.vertices[(c * 3)],
bunny.vertices[(c * 3) + 1],
bunny.vertices[(c * 3) + 2]};
//calculate the face normal
float res[3];
calc_normal(v1, v2, v3, res);
// add the face normal to bunny
bunny.faces_normals[(i * 3)] = res[0];
bunny.faces_normals[(i * 3) + 1] = res[1];
bunny.faces_normals[(i * 3) + 2] = res[2];
}
//check the faces_normals just calculated and turn them around
//if needed
//choose a reference face (index of the reference face)
int reference_face_index = 0;
recursive_orient(reference_face_index,
bunny.faces_normals,
bunny.faces_indices,
vertex_in_faces,
visited);
//add the faces normals to the vertex normals
for(i = 0; i < bunny.amount_of_faces; i++) {
a = bunny.faces_indices[3*i];
b = bunny.faces_indices[(3*i)+1];
c = bunny.faces_indices[(3*i)+2];
float res[3] = {
bunny.faces_normals[(i * 3)],
bunny.faces_normals[(i * 3) + 1],
bunny.faces_normals[(i * 3) + 2]
};
//(only add, normalize later)
bunny.vertex_normals[(a * 3)] += res[0];
bunny.vertex_normals[(a * 3) + 1] += res[1];
bunny.vertex_normals[(a * 3) + 2] += res[2];
bunny.vertex_normals[(b * 3)] += res[0];
bunny.vertex_normals[(b * 3) + 1] += res[1];
bunny.vertex_normals[(b * 3) + 2] += res[2];
bunny.vertex_normals[(c * 3)] += res[0];
bunny.vertex_normals[(c * 3) + 1] += res[1];
bunny.vertex_normals[(c * 3) + 2] += res[2];
}
//normalize the vertex normals (average)
for(i = 0; i < bunny.amount_of_vertices; i++) {
float temp[3];
temp[0] = bunny.vertex_normals[(i * 3)];
temp[1] = bunny.vertex_normals[(i * 3) + 1];
temp[2] = bunny.vertex_normals[(i * 3) + 2];
float normalization = sqrt(temp[0] * temp[0] + temp[1] * temp[1] + temp[2] * temp[2]);
temp[0] = temp[0]/normalization;
temp[1] = temp[1]/normalization;
temp[2] = temp[2]/normalization;
bunny.vertex_normals[(i * 3)] = temp[0];
bunny.vertex_normals[(i * 3) + 1] = temp[1];
bunny.vertex_normals[(i * 3) + 2] = temp[2];
}
fclose(ply); //close file
//END PLY FILE HANDLING
}
//sets, loads and whatnot shaders
void set_shaders(){
#ifdef DEBUG
printf("starting to load shaders\n");
#endif
GLuint f, v;
//create the shader program
p = glCreateProgram ();
GLchar *vs, *fs;
//create shaders
v = glCreateShader (GL_VERTEX_SHADER);
f = glCreateShader (GL_FRAGMENT_SHADER);
GLint vlen = 0;
GLint flen = 0;
vs = simple_fileread((char *)"simple_shader.vert", &vlen);
#ifdef DEBUG
printf("loaded vertex shader with %i chars\n", vlen);
#endif
fs = simple_fileread((char *)"simple_shader.frag", &flen);
#ifdef DEBUG
printf("loaded fragment shader with %i characters\n",flen);
#endif
const GLchar * vv = vs;
const GLchar * ff = fs;
const GLint flenc = flen;
const GLint vlenc = vlen;
glShaderSource (v, 1, &vv, &vlenc);
glShaderSource (f, 1, &ff, &flenc);
//compile shaders
#ifdef DEBUG
printf("shaders loaded. compiling next\n");
#endif
int compiled;
int infoLogLen = 1000, charsWritten = 0;
char *infoLog = 0;
glCompileShader (v);
glGetShaderiv (v, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
//glGetShaderiv (shader, GL_INFO_LOG_LENGTH, &infoLogLen);
if (infoLogLen > 0) {
printf("Errors compling vertex shader:\n");
infoLog = (char *)malloc (infoLogLen);
glGetShaderInfoLog (v, infoLogLen, &charsWritten,
infoLog);
printf ("%s\n", infoLog);
free (infoLog);
}
}
compiled = 0;
glCompileShader(f);
glGetShaderiv (f, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
//glGetShaderiv (shader, GL_INFO_LOG_LENGTH, &infoLogLen);
if (infoLogLen > 0) {
printf("Errors compling fragment shader:\n");
infoLog = (char *)malloc (infoLogLen);
glGetShaderInfoLog (f, infoLogLen, &charsWritten,
infoLog);
printf ("%s\n", infoLog);
free (infoLog);
}
}
// run shaders
#ifdef DEBUG
printf("compiled.any errors are above. running shaders.\n");
#endif
//attach shaders
glAttachShader (p, v);
glAttachShader (p, f);
glLinkProgram (p);
glUseProgram (p);
}
//loads our only texture
void load_textures(char * filename1, char * filename2){
GLuint n_textures = 2;
// texture_id is global
glGenTextures(n_textures, texture_ID);
// glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture_ID[0]);
img_data * tex = simple_bmp_read(filename1);
img_data mytex = *tex;
#ifdef DEBUG
printf("attaching an %i by %i texture image from %p\n", mytex.width,
mytex.height, mytex.whole+mytex.rgbstart);
#endif
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, mytex.width, mytex.height,
GL_RGB, GL_UNSIGNED_BYTE, mytex.whole+mytex.rgbstart);
glTexParameteri (GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri (GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri (GL_TEXTURE_2D,GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri (GL_TEXTURE_2D,GL_TEXTURE_WRAP_T, GL_REPEAT);
// glTexImage2D(GL_TEXTURE_2D,0, GL_RGB, mytex.width, mytex.height,0,
// GL_RGB, GL_UNSIGNED_BYTE, mytex.whole+mytex.rgbstart);
// glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture_ID[1]);
img_data *tex2 = simple_bmp_read(filename2);
img_data mytex2 = *tex2;
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, mytex2.width, mytex2.height,
GL_RGB, GL_UNSIGNED_BYTE, mytex2.whole+mytex2.rgbstart);
glTexParameteri (GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri (GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri (GL_TEXTURE_2D,GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri (GL_TEXTURE_2D,GL_TEXTURE_WRAP_T, GL_REPEAT);
free(mytex.whole);
free(tex);
free(mytex2.whole);
free(tex2);
}
int main (int argc, char **argv)
{
#ifdef DEBUG
printf("starting main function\n");
#endif
if (argc != 4){
printf("incorrect usage, please give ply file and 2 names of"
"(24-bit BMP)textures as command line parameters!");
exit(-1);
}
//initialize glut, create a window
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE|GLUT_RGBA|GLUT_DEPTH);
glutInitWindowSize (600, 600);
glutCreateWindow ("OpenGL Test");
//glewinit error reporting
GLenum err = glewInit();
if (GLEW_OK != err)
{
/* Problem: glewInit failed, something is seriously wrong. */
fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
}
fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
printf ("Supported OpenGL version: %s\n",
glGetString (GL_VERSION));
//connecting the UI interaction function
glutKeyboardFunc(keyb_cb);
glutMotionFunc(mouse_motion_cb);
glutMouseFunc(mouse_cb);
glutSpecialFunc(sp_keyb_cb);
glutTimerFunc(100, timer_cb, 0);
glutReshapeFunc(window_resize_cb);
//initialize modelview and projection matrices
mod.camera_x = 0.0;
mod.camera_y = 0.0;
mod.camera_z = -1.0;
mod.lookat_x = 0.0;
mod.lookat_y = 0.0;
mod.lookat_z = 0.0;
mod.up_x = 0.0;
mod.up_y = 1.0;
mod.up_z = 0.0;
mod.angle = 0.0;
proj.height = 600;
proj.width = 600;
proj.fovy = 45;
proj.aspect = 1.0;
proj.near = 1;
proj.far = 2000;
update_projection();
update_modelview();
// load shaders
set_shaders();
#ifdef DEBUG
printf("beginning read from file.\n");
#endif
//read bunny from file
read_ply_from_file(argv[1]);
//setting up the vertex array and then buffers
GLuint vertex_array_object_ID;
unsigned int number_of_arrays = 1;
glGenVertexArrays (number_of_arrays, &vertex_array_object_ID);
glBindVertexArray (vertex_array_object_ID);
vertex_ID = vertex_array_object_ID;
// three buffers: vertex, vertex_normal,, TODO textures and colors
unsigned int number_of_buffers = 3;
unsigned int vertex_buffer_object_ID[number_of_buffers];
glGenBuffers (number_of_buffers, vertex_buffer_object_ID);
//what is this?
//unsigned int index_buffer_object_ID[1];
//glGenBuffers(1, index_buffer_object_ID);
//bind vertices data to the buffer
unsigned int elements_per_vertex = 3;
//unsigned int elements_per_triangle = 3 * elements_per_vertex;
glBindBuffer (GL_ARRAY_BUFFER, vertex_buffer_object_ID[0]);
glBufferData (GL_ARRAY_BUFFER,
elements_per_vertex * bunny.amount_of_vertices * sizeof (float),
bunny.vertices,
GL_STATIC_DRAW);
//vertex position x y z in the buffer
int vertex_position_location = 0;
glBindAttribLocation(p, vertex_position_location, "vertex_position");
glVertexAttribPointer (vertex_position_location,
elements_per_vertex,
GL_FLOAT,
GL_FALSE,
0,
0);
glEnableVertexAttribArray (vertex_position_location);
//vertex normal buffer
glBindBuffer (GL_ARRAY_BUFFER, vertex_buffer_object_ID[1]);
glBufferData(GL_ARRAY_BUFFER,
bunny.amount_of_vertices * 3 * sizeof(float),
bunny.vertex_normals,
GL_STATIC_DRAW);
unsigned int location_vertex_normal = 1;
glBindAttribLocation(p, location_vertex_normal, "vertex_normal");
glVertexAttribPointer(location_vertex_normal,
3,
GL_FLOAT,
GL_FALSE,
0,
0);
glEnableVertexAttribArray(location_vertex_normal);
//texture coordinate buffer
glBindBuffer (GL_ARRAY_BUFFER, vertex_buffer_object_ID[2]);
glBufferData(GL_ARRAY_BUFFER,
bunny.amount_of_vertices * 2 * sizeof(float),
bunny.tex_coordinates,
GL_STATIC_DRAW);
unsigned int location_vertex_tex = 2;
glBindAttribLocation(p, location_vertex_tex, "vertex_texcoord");
glVertexAttribPointer(location_vertex_tex,
2,
GL_FLOAT,
GL_FALSE,
0,
0);
glEnableVertexAttribArray(location_vertex_tex);
#ifdef DEBUG
printf("reading texture\n");
#endif
load_textures(argv[2], argv[3]);
//initialize lights and materials here
material.shininess = 40.0;
GLfloat ambient[4] = {0.05,0.05,0.05,1.0};
material.ambient = (GLfloat*)&ambient;
GLfloat diffuse[4] = {0.5,0.5,0.5,1.0};
material.diffuse = (GLfloat*)&diffuse;
GLfloat specular[4] = {0.5,0.5,0.5,1.0};
material.specular = (GLfloat*)&specular;
//light 0 is a directed light up high
GLfloat light0pos[4] = {0.0, 50.0, 5.0, 0.0};
lights[0].position = (GLfloat*) &light0pos;
GLfloat light0diffuse[4] = {0.3,0.3,0.3,1.0};
lights[0].diffuse = (GLfloat*) &light0diffuse;
GLfloat light0specular[4] = {0.3,0.3,0.3,1.0};
lights[0].specular = light0specular;
GLfloat light0ambient[4] = {0.1,0.1,0.1,1.0};
lights[0].ambient = light0ambient;//do we need this?
lights[0].type = 0; //directed light
//light 1 is either a point light or a spotlight depending on config
/*
lights[1].position = {0.0,1.0,0.0,0.0}; //in eye coords, just above eye
lights[1].spot_exponent = 4.0;
lights[1].spot_cosine_cutoff = 0.2; //how large spot angle
lights[1].spot_dir = {0.0,0.0,-1.0,0.0}; //straight forward from eye
lights[1].spot_ambient = {0.0,0.0,0.0,0.0};
lights[1].spot_diffuse = {1.0,0.0,0.0,0.0}; //red
lights[1].type = 1;
*/
#ifdef DEBUG
printf(" attaching display function and running main loop\n");
#endif
glutDisplayFunc(display_cb);
glutMainLoop ();
return 0;
}
void display_cb(void)
{
#ifdef DEBUG
// printf("display callback called\n");
#endif
glClearColor(0.0, 0.0, 0.0, 0.0);
glClearDepth(1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(p);
unsigned int location_projection_matrix = glGetUniformLocation(p,
"projection_matrix");
unsigned int location_modelview_matrix = glGetUniformLocation(p,
"modelview_matrix");
GLfloat mp[16];
GLfloat mv[16];
glGetFloatv (GL_PROJECTION_MATRIX, mp);
glGetFloatv (GL_MODELVIEW_MATRIX, mv);
glUniformMatrix4fv (location_projection_matrix, 1, GL_FALSE, mp);
glUniformMatrix4fv (location_modelview_matrix, 1, GL_FALSE, mv);
GLfloat base_color[4] = {0.05, 0.05, 0.05, 1.0}; //light grey by default
unsigned int location_base_color = glGetUniformLocation(p, "base_color");
//glUniform1iv(location_lights,2, lights);
//glUniform4fv(location_material, 1, material);
glUniform4fv(location_base_color, 1, base_color);
//crap, can't send a struct as a struct, need to send piece by piece
glUniform4fv(glGetUniformLocation(p,"light0.diffuse"),1,
lights[0].diffuse);
glUniform4fv(glGetUniformLocation(p,"light0.position"),1,
lights[0].position);
glUniform4fv(glGetUniformLocation(p,"light0.specular"),1,
lights[0].specular);
glUniform4fv(glGetUniformLocation(p,"light0.ambient"),1,
lights[0].ambient);
glUniform1i(glGetUniformLocation(p,"light0.type"),
lights[0].type);
glUniform4fv(glGetUniformLocation(p,"material.ambient"),1,
material.ambient);
glUniform4fv(glGetUniformLocation(p,"material.diffuse"),1,
material.diffuse);
glUniform4fv(glGetUniformLocation(p,"material.specular"),1,
material.specular);
glUniform4fv(glGetUniformLocation(p,"material.emission"),1,
material.emission);
glUniform1f(glGetUniformLocation(p,"material.shininess"),
material.shininess);
//time step for animation
// if (time > 0)
// time++;
glUniform1i(glGetUniformLocation(p, "time"),time);
glUniform1i(glGetUniformLocation(p, "toon"),toon);
glUniform1i(glGetUniformLocation(p, "twotex"),twotex);
// printf("uniform locations %i, %i, %i, %i, %i\n", location_base_color,
//
// location_projection_matrix, location_light_pos, location_light_col,
// location_material_diffuse);
/* GLfloat temp[4];
glGetUniformfv(p, location_light_pos,temp);
printf("color %f, %f, %f\n", temp[0], temp[1], temp[2]);
*/
//create samplers
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture_ID[0]);
int texture_sampler = glGetUniformLocation(p, "texture_1");
glUniform1i(texture_sampler, 0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture_ID[1]);
int texture_sampler2 = glGetUniformLocation(p, "texture_2");
glUniform1i(texture_sampler2, 1);
//here goes actual drawing code
glFrontFace(GL_CCW);
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
//z-buffering
glDepthFunc(GL_LESS);
glDepthRange(0.0, 1.0);
glEnable(GL_DEPTH_TEST);
//vertex array
glBindVertexArray (vertex_ID);
//draw the bunny according to indices and the vertices in the server buffer
glDrawElements(GL_TRIANGLES,
3*bunny.amount_of_faces,
GL_UNSIGNED_INT,
bunny.faces_indices);
glFlush();
glutSwapBuffers();
}
|
C
|
/******************************************************************************
** Coypright(C) 2016-2026 Qiware technology Co., Ltd
**
** 文件名: mem_ref.c
** 版本号: 1.0
** 描 述: 内存引用计数管理
** 作 者: # Qifeng.zou # 2016年06月27日 星期一 21时19分37秒 #
******************************************************************************/
#include "comm.h"
#include "atomic.h"
#include "rb_tree.h"
#include "mem_ref.h"
/* 内存引用项 */
typedef struct
{
void *addr; // 内存地址
uint32_t count; // 引用次数
struct {
void *pool; // 内存池
mem_dealloc_cb_t dealloc; // 释放回调
};
} mem_ref_item_t;
/* 内存引用槽 */
typedef struct
{
pthread_rwlock_t lock; // 读写锁
rbt_tree_t *tree; // 内存引用表
} mem_ref_slot_t;
/* 全局对象 */
typedef struct
{
#define MEM_REF_SLOT_LEN (777)
mem_ref_slot_t slot[MEM_REF_SLOT_LEN];
} mem_ref_cntx_t;
#define MEM_REF_IDX(addr) ((uint64_t)addr % MEM_REF_SLOT_LEN)
static mem_ref_cntx_t g_mem_ref_ctx; // 全局对象
static int mem_ref_add(void *addr, void *pool, mem_dealloc_cb_t dealloc);
/******************************************************************************
**函数名称: mem_ref_cmp_cb
**功 能: 比较回调函数
**输入参数:
** item1: 数据项1
** item2: 数据项2
**输出参数: NONE
**返 回: 0:相等 <0:小于 >0:大于
**实现描述:
**注意事项:
**作 者: # Qifeng.zou # 2016.08.09 11:22:10 #
******************************************************************************/
static int mem_ref_cmp_cb(const mem_ref_item_t *item1, const mem_ref_item_t *item2)
{
return ((uint64_t)item1->addr - (uint64_t)item2->addr);
}
/******************************************************************************
**函数名称: mem_ref_init
**功 能: 初始化内存引用计数表
**输入参数: NONE
**输出参数: NONE
**返 回: 0:成功 !0:失败
**实现描述:
**注意事项:
**作 者: # Qifeng.zou # 2016.06.29 14:45:15 #
******************************************************************************/
int mem_ref_init(void)
{
int idx;
mem_ref_slot_t *slot;
mem_ref_cntx_t *ctx = &g_mem_ref_ctx;
memset(ctx, 0, sizeof(mem_ref_cntx_t));
for (idx=0; idx<MEM_REF_SLOT_LEN; ++idx) {
slot = &ctx->slot[idx];
pthread_rwlock_init(&slot->lock, NULL);
slot->tree = (rbt_tree_t *)rbt_creat(NULL, (cmp_cb_t)mem_ref_cmp_cb);
if (NULL == slot->tree) {
return -1;
}
}
return 0;
}
/******************************************************************************
**函数名称: mem_ref_alloc
**功 能: 申请内存空间
**输入参数: NONE
**输出参数: NONE
**返 回: 内存地址
**实现描述:
**注意事项:
**作 者: # Qifeng.zou # 2016.07.04 00:33:34 #
******************************************************************************/
void *mem_ref_alloc(size_t size, void *pool,
mem_alloc_cb_t alloc, mem_dealloc_cb_t dealloc)
{
void *addr;
addr = (void *)alloc(pool, size);
if (NULL == addr) {
return NULL;
}
mem_ref_add(addr, pool, dealloc);
return addr;
}
/******************************************************************************
**函数名称: mem_ref_add
**功 能: 添加新的引用
**输入参数:
** addr: 内存地址
**输出参数: NONE
**返 回: 引用次数
**实现描述:
**注意事项:
**作 者: # Qifeng.zou # 2016.09.08 #
******************************************************************************/
static int mem_ref_add(void *addr, void *pool, mem_dealloc_cb_t dealloc)
{
int cnt, idx;
mem_ref_slot_t *slot;
mem_ref_item_t *item, key;
mem_ref_cntx_t *ctx = &g_mem_ref_ctx;
idx = MEM_REF_IDX(addr);
slot = &ctx->slot[idx];
AGAIN:
pthread_rwlock_rdlock(&slot->lock);
/* > 查询引用 */
key.addr = addr;
item = (mem_ref_item_t *)rbt_query(slot->tree, (void *)&key);
if (NULL != item) {
cnt = (int)atomic32_inc(&item->count);
pthread_rwlock_unlock(&slot->lock);
return cnt;
}
pthread_rwlock_unlock(&slot->lock);
/* > 新增引用 */
item = (mem_ref_item_t *)calloc(1, sizeof(mem_ref_item_t));
if (NULL == item) {
return -1;
}
item->addr = addr;
cnt = ++item->count;
item->pool = pool;
item->dealloc = dealloc;
pthread_rwlock_wrlock(&slot->lock);
if (rbt_insert(slot->tree, item)) {
pthread_rwlock_unlock(&slot->lock);
free(item);
goto AGAIN;
}
pthread_rwlock_unlock(&slot->lock);
return cnt;
}
/******************************************************************************
**函数名称: mem_ref_dealloc
**功 能: 回收内存空间
**输入参数: NONE
**输出参数: NONE
**返 回: VOID
**实现描述:
**注意事项:
**作 者: # Qifeng.zou # 2016.07.04 00:33:34 #
******************************************************************************/
void mem_ref_dealloc(void *pool, void *addr)
{
mem_ref_decr(addr);
}
/******************************************************************************
**函数名称: mem_ref_incr
**功 能: 增加1次引用
**输入参数:
** addr: 内存地址
**输出参数: NONE
**返 回: 内存池对象
**实现描述:
**注意事项: 内存addr必须由mem_ref_alloc进行分配.
**作 者: # Qifeng.zou # 2016.07.06 #
******************************************************************************/
int mem_ref_incr(void *addr)
{
int cnt, idx;
mem_ref_slot_t *slot;
mem_ref_item_t *item, key;
mem_ref_cntx_t *ctx = &g_mem_ref_ctx;
idx = MEM_REF_IDX(addr);
slot = &ctx->slot[idx];
key.addr = addr;
pthread_rwlock_rdlock(&slot->lock);
item = (mem_ref_item_t *)rbt_query(slot->tree, (void *)&key);
if (NULL != item) {
cnt = (int)atomic32_inc(&item->count);
pthread_rwlock_unlock(&slot->lock);
return cnt;
}
pthread_rwlock_unlock(&slot->lock);
return -1; // 未创建结点
}
/******************************************************************************
**函数名称: mem_ref_decr
**功 能: 减少1次引用
**输入参数:
** addr: 内存地址
**输出参数: NONE
**返 回: 内存引用次数
**实现描述:
**注意事项:
** 1. 内存addr是通过系统调用分配的方可使用内存引用
** 2. 如果引用计数减为0, 则释放该内存空间.
**作 者: # Qifeng.zou # 2016.06.29 14:53:09 #
******************************************************************************/
int mem_ref_decr(void *addr)
{
int cnt, idx;
mem_ref_slot_t *slot;
mem_ref_item_t *item, *temp, key;
mem_ref_cntx_t *ctx = &g_mem_ref_ctx;
idx = MEM_REF_IDX(addr);
slot = &ctx->slot[idx];
key.addr = addr;
pthread_rwlock_rdlock(&slot->lock);
item = (mem_ref_item_t *)rbt_query(slot->tree, (void *)&key);
if (NULL == item) {
pthread_rwlock_unlock(&slot->lock);
return 0; // Didn't find
}
cnt = (int)atomic32_dec(&item->count);
if (0 == cnt) {
pthread_rwlock_unlock(&slot->lock);
pthread_rwlock_wrlock(&slot->lock);
item = (mem_ref_item_t *)rbt_query(slot->tree, (void *)&key);
if (NULL == item) {
pthread_rwlock_unlock(&slot->lock);
return 0; // Didn't find
}
if (0 == item->count) {
rbt_delete(slot->tree, (void *)&key, (void **)&temp);
pthread_rwlock_unlock(&slot->lock);
item->dealloc(item->pool, item->addr); // 释放被管理的内存
free(item);
return 0;
}
pthread_rwlock_unlock(&slot->lock);
return 0;
}
pthread_rwlock_unlock(&slot->lock);
return cnt;
}
/******************************************************************************
**函数名称: mem_ref_check
**功 能: 内存引用检测
**输入参数:
** addr: 内存地址
**输出参数: NONE
**返 回: 引用次数
**实现描述:
**注意事项:
**作 者: # Qifeng.zou # 2016.09.08 #
******************************************************************************/
int mem_ref_check(void *addr)
{
int cnt, idx;
mem_ref_slot_t *slot;
mem_ref_item_t *item, key;
mem_ref_cntx_t *ctx = &g_mem_ref_ctx;
idx = MEM_REF_IDX(addr);
slot = &ctx->slot[idx];
key.addr = addr;
pthread_rwlock_rdlock(&slot->lock);
/* > 查询引用 */
item = (mem_ref_item_t *)rbt_query(slot->tree, (void *)&key);
if (NULL != item) {
cnt = item->count;
pthread_rwlock_unlock(&slot->lock);
return cnt;
}
pthread_rwlock_unlock(&slot->lock);
assert(0);
return 0;
}
|
C
|
//The buble sort gets its name because as array elements are sorted they gradually "bubbles" to their proper position.
//A bubble sort will compare two adjacent element of ana array and will swap them they are not in order.
//The compare starts with the first and second element.After that it will compare the second with the third one and soo on....the processs continues till the end of the bubble sort array
//When the end of the array is reached the bubble sort algorithm will returns to element one and starts the process all over again.
//as we can see in the source below,the bubble sort algorithm is easy to programm. but the bubble sot algorithm is slower than any other sorting algorithms.Because the Because the sort always needs a final extra pass to check to see that there are no more swaps are made. If there are no more swaps the swap flag is put up and the process ends
#include <stdio.h> //It is a statement which tells the compiler to insert the contends of stdio at that particular place
int main() //function returns the int value.
{
//declaring the variable size to read the input from the user and c,d for the iteration purpose
//arr and swap are used to store the elements
int arr[100],size,c,d,swap;
printf("Enter number of elements\n"); //printf formates the data to stdout
scanf("%d", &size);// it reads the input from the user
printf("Enter %d integers\n", size);
for (c = 0; c < size; c++) // "for loop" genearlly iterates the function.
{
scanf("%d", &arr[c]);
}
for (c = 0 ; c < ( size - 1 ); c++)
{
for (d = 0 ; d < size - c - 1; d++)
{
if (arr[d] > arr[d+1]) //a "if loop" says mainly about the condition
{
swap = arr[d]; //Assigning value of arr[d] to swap just to hold it temporary
arr[d] =arr[d+1]; //Assigning arr[d] to next element of arr[]
arr[d+1] = swap; //moving temporary swap to next element of arr[] i.e., arr[d+1]
}
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < size ; c++ ) // it iterates to display all the elements of the array in the output
{
printf("%d\n", arr[c]); // shows the sorted result
}
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_2__ TYPE_1__ ;
/* Type definitions */
struct TYPE_2__ {scalar_t__* name; } ;
union acpi_predefined_info {TYPE_1__ info; } ;
/* Variables and functions */
scalar_t__ ACPI_COMPARE_NAMESEG (char*,scalar_t__*) ;
union acpi_predefined_info* acpi_gbl_predefined_methods ;
union acpi_predefined_info* acpi_ut_get_next_predefined_method (union acpi_predefined_info const*) ;
const union acpi_predefined_info *acpi_ut_match_predefined_method(char *name)
{
const union acpi_predefined_info *this_name;
/* Quick check for a predefined name, first character must be underscore */
if (name[0] != '_') {
return (NULL);
}
/* Search info table for a predefined method/object name */
this_name = acpi_gbl_predefined_methods;
while (this_name->info.name[0]) {
if (ACPI_COMPARE_NAMESEG(name, this_name->info.name)) {
return (this_name);
}
this_name = acpi_ut_get_next_predefined_method(this_name);
}
return (NULL); /* Not found */
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#define STR_LEN 1000
unsigned int N = 1000;
int number, position;
char* readLine() {
char* inputLine = malloc(sizeof(char[STR_LEN]));
fgets(inputLine, STR_LEN, stdin);
if (inputLine == NULL) {
perror("Unable to read command\n");
exit(1);
}
return inputLine;
}
char** parseCommand(char *line) {
number = 0;
int index = 0;
char **argv = malloc(number * sizeof(char *));
char *token;
char *buffer = strdup(line);
if (argv == NULL) {
fprintf(stderr, "memory allocation error\n");
exit(1);
}
token = strtok(buffer, " \n");
number++;
while (token != NULL) {
argv = realloc(argv, sizeof(char *) * number);
if (argv == NULL) {
fprintf(stderr, "memory allocation error\n");
exit(1);
}
argv[index++] = token;
token = strtok(NULL, " \n");
number++;
}
argv = realloc(argv, sizeof(char *) * number);
argv[index] = NULL;
return argv;
}
int runCommand(char **args) {
pid_t n;
n = fork();
if (n < 0) {
// fork failed
fprintf(stderr, "Fork Failed\n");
exit(1);
} else if (n == 0) {
// child process
execvp(args[0], args);
fprintf(stderr, "Cannot run command\n");
} else {
// parent process
wait(NULL);
}
return 1;
}
int checkCommand(char* line) {
int found = 0;
position = 0;
char **tokens = parseCommand(line);
while (tokens[position] != NULL) {
if (strchr(tokens[position], '|')) {
found = 1;
break;
}
position++;
}
return found;
}
int runNormalMode(char *line) {
char **tokens = parseCommand(line);
int check, first, second;
second = 0;
first = position + 1;
check = number - position;
char **str1 = malloc((first) * sizeof(char *));
char **str2 = malloc((check) * sizeof(char *));
for (int x = 0; x < position; x++) {
str1[x] = tokens[x];
}
for (int y = (first); y < number; y++) {
str2[second] = tokens[y];
second++;
}
str1[position] = NULL;
str2[check] = NULL;
// measure time of experiment
srand(time(0));
struct timeval start, end;
gettimeofday(&start, NULL);
int pipe1[2];
if (pipe(pipe1) == -1) {
fprintf(stderr, "\nError");
exit(1);
}
pid_t n1;
n1 = fork();
if (n1 < 0) {
// fork failed
fprintf(stderr, "\nFork Failed");
exit(1);
}
if (n1 == 0) {
// child process 1
dup2(pipe1[1], STDOUT_FILENO);
close(pipe1[0]);
close(pipe1[1]);
if (execvp(str1[0], str1) == -1) {
fprintf(stderr, "Cannot run command\n");
exit(2);
}
}
pid_t n2;
n2 = fork();
if (n2 < 0) {
// fork failed
fprintf(stderr, "\nFork Failed");
exit(3);
}
if (n2 == 0) {
// child process 2
dup2(pipe1[0], STDIN_FILENO);
close(pipe1[0]);
close(pipe1[1]);
if (execvp(str2[0], str2) == -1) {
fprintf(stderr, "Cannot run command\n");
}
}
close(pipe1[0]);
close(pipe1[1]);
waitpid(n1, NULL, 0);
waitpid(n2, NULL, 0);
// get time of experiment
gettimeofday(&end, NULL);
int seconds = (end.tv_sec - start.tv_sec);
int micros = ((seconds * 1000000) + end.tv_usec) - (start.tv_usec);
printf("Time taken: %d s and %d ms\n", seconds, micros);
return 0;
}
void runTappedMode(char *line) {
char **tokens = parseCommand(line);
int check, first, second;
second = 0;
first = position + 1;
check = number - position;
char **str1 = malloc((first) * sizeof(char *));
char **str2 = malloc((check) * sizeof(char *));
for (int x = 0; x < position; x++) {
str1[x] = tokens[x];
}
for (int y = (first); y < number; y++) {
str2[second] = tokens[y];
second++;
}
str1[position] = NULL;
str2[check] = NULL;
// measure time of experiment
srand(time(0));
struct timeval start, end;
gettimeofday(&start, NULL);
int pipe1[2];
int pipe2[2];
if (pipe(pipe1) == -1) {
fprintf(stderr, "Error\n");
exit(1);
}
if (pipe(pipe2) == -1) {
fprintf(stderr, "Error\n");
exit(1);
}
// child process 1
pid_t n1;
n1 = fork();
if (n1 < 0) {
// fork failed
fprintf(stderr, "Fork Failed\n");
exit(1);
} else if (n1 == 0) {
close(pipe2[0]); // close unused ends
close(pipe2[1]);
close(pipe1[0]);
dup2(pipe1[1], STDOUT_FILENO);
if (execvp(str1[0], str1) == -1) {
fprintf(stderr, "Cannot run first command\n");
exit(1);
}
} else {
// child process 2
pid_t n2;
n2 = fork();
if (n2 < 0) {
// fork failed
fprintf(stderr, "Fork Failed\n");
exit(3);
} else if (n2 == 0) {
close(pipe1[0]);
close(pipe1[1]);
close(pipe2[1]);
dup2(pipe2[0], STDIN_FILENO);
if (execvp(str2[0], str2) == -1) {
fprintf(stderr, "Cannot run second command\n");
exit(1);
}
} else {
// parent process
int characterCount = 0;
int bytesRead;
int count = 0;
close(pipe1[1]);
close(pipe2[0]);
char *buffer;
buffer = malloc(sizeof(char) * N);
while ((bytesRead = read(pipe1[0], &buffer, N)) > 0) {
write(pipe2[1], &buffer, bytesRead);
characterCount = characterCount + bytesRead;
count++;
}
close(pipe1[0]);
close(pipe2[1]);
waitpid(n1, NULL, 0);
waitpid(n2, NULL, 0);
// get time of experiment
gettimeofday(&end, NULL);
int seconds = (end.tv_sec - start.tv_sec);
int micros = ((seconds * 1000000) + end.tv_usec) - (start.tv_usec);
printf("Time taken: %d s and %d ms\n", seconds, micros);
printf("\ncharacter-count: %d\nread-call-count: %d\nwrite-call-count: %d\n",
characterCount, count, count);
}
}
}
void userLoop(int mode) {
while (1) {
printf("isp:~$ ");
char *line = readLine();
char **args;
if (checkCommand(line) == 1) {
if (mode == 1) {
runNormalMode(line);
}
if (mode == 2) {
runTappedMode(line);
}
continue;
} else {
args = parseCommand(line);
}
// check if command is empty
if (args[0] == NULL) {
continue;
}
// check for exit
if (strcmp(args[0], "exit") == 0) {
break;
}
runCommand(args);
}
}
int main(int argc, char *argv[]) {
N = atoi(argv[1]);
int mode = atoi(argv[2]);
if (!(mode == 1 | mode == 2)) {
fprintf(stderr, "Mode can be 1 (normal mode) or 2 (tapped mode)\n");
exit(1);
}
if (N < 1 || N > 4096) {
printf("N should be between 1 and 4096\n");
exit(1);
}
userLoop(mode);
}
|
C
|
#include "lists.h"
/**
* delete_dnodeint_at_index - deletes a node at a given postion
* @head: pointer to a pointer of a linked list.
* @index: position of the node to delete.
*
* Return: 1 on Sucess else -1 on failure.
*/
int delete_dnodeint_at_index(dlistint_t **head, unsigned int index)
{
dlistint_t *node;
size_t idx = 0;
if (!head || !(*head))
return (-1);
node = *head;
if (index == 0)
{
if (node->next)
{
*head = node->next;
(*head)->prev = NULL;
}
else
*head = NULL;
free(node);
return (1);
}
while (idx++ < index && node)
node = node->next;
if (!node)
return (-1);
else if (node->prev && node->next)
{
node->next->prev = node->prev;
node->prev->next = node->next;
free(node);
}
else if (!node->next)
{
node->prev->next = NULL;
free(node);
}
return (1);
}
|
C
|
#include<stdio.h>
#define MAX 100
int bbi_recursivo (int x, int * v, int ini, int tam)
{
if (x==v[(ini+tam)/2])
return (ini+tam)/2+1;
if (ini>=tam)
return 0;
if (x>v[(ini+tam)/2])
return bbi_recursivo (x,v,ini=(ini+tam)/2 +1,tam);
else
return bbi_recursivo (x,v,ini,tam=(ini+tam)/2 -1);
}
void ler_vetor (int *v,int tam)
{
int i=0;
for (i=0; i<tam; i++)
scanf ("%d", &v[i]);
}
int main (void)
{
int vetor[MAX], tam, x, i, achou;
scanf ("%d" "%d", &tam, &x);
ler_vetor (vetor,tam);
for (i=0; i<tam; i++)
printf ("%d ", vetor[i]);
achou=bbi_recursivo (x,vetor,0,tam-1);
if (achou == 0)
printf ("Não existe esse número no vetor\n");
else
printf ("O número esta na posição %d do vetor\n", achou);
return 0;
}
|
C
|
/*
* started: 28jan15
* finished:
* written by: Damon Getsman
*
* This project is a simple test to make sure that the different functions
* available in my-nc_flashcard.h are working properly; a predecessor to the
* flashcard program that I am writing for my son, so that he can be able
* to practice his multiplication on anything from a text-only terminal to
* a terminal on any machine in the house. It seems like so many of the other
* programs that I've used are buggy... I figured, why not put this library
* to use, get more familiar with C again, and code him up something simple
* and quick that'll get the job done.
*/
#include <stdio.h>
#include <stdlib.h>
#include <ncurses.h>
#include "my-nc_flashcard.h"
#define TEXTLINES 3
#define MAXLEN 78
WINDOW *mainWinder;
char testMsg[3][78] = { "We come for your daughter,",
"Chuck. Nuh uh uh! Nobody",
"says the B word!" };
if (!init_ncurses(mainWinder)) {
printf("\nHouston, we have a bad friggin' problem\n");
exit(1);
}
if (center_shit(testMsg) != 0) {
printf("\nHouston, we've had a problem at number 2. :|\n");
exit(2);
} else {
exit(0);
}
|
C
|
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <elf.h>
typedef struct {
char debug_mode;
char file_name[128];
int unit_size;
unsigned char mem_buf[10000];
size_t mem_count;
} state;
struct fun_desc {
char *name;
void (*fun)(state* s);
};
void Toggle_Debug_Mode (state* s);
void Examine_ELF_File (state* s);
void Quit(state* s);
void Print_Section_Names(state* s);
void Print_Symbols (state* s);
char* typeString (uint32_t type);
int option;
char op [4];
state * s;
int Currentfd = -1;
struct stat fd_stat;
Elf32_Ehdr* header;
Elf32_Shdr* section;
Elf32_Sym* symbol;
void *map_start;
int main (int argc , char* argv[]){
s = (state *) malloc (sizeof(state));
s->unit_size = 1;
s->debug_mode = 0;
struct fun_desc menu[] = { { "Toggle Debug Mode", Toggle_Debug_Mode }, { "Examine ELF File", Examine_ELF_File}, { "Print Section Names", Print_Section_Names},{ "Print Symbols", Print_Symbols} ,{ "Quit", Quit}, { NULL, NULL}};
int menu_size = sizeof(menu)/sizeof(menu[0]);
while(true){
if(s->debug_mode){
fprintf(stderr,"unit size is: %d\nfile name is: %s\nmem count is: %d\n\n",s->unit_size, s->file_name, s-> mem_count);
}
printf("%s\n","please choose an action: ");
for(int j = 0 ; j<menu_size-1; j++){
printf("%d",j);
printf(") %s\n",menu[j].name);
}
printf("%s","option: ");
fgets(op, 4 ,stdin);
sscanf(op, "%d", &option);
if(option<0 || option >= menu_size-1)
printf("\n%s\n\n","not within bounds");
else{
printf("%s\n","");
void (*f) (state* s) = menu[option].fun; //save the function of the requested function
f(s); //execute the requested function
printf("%s\n","");
}
}
return 0;
}
void Toggle_Debug_Mode (state* s){
if(s->debug_mode == 0){
s->debug_mode = 1;
fprintf(stderr,"Debug flag now on");
}
else{
s->debug_mode = 0;
fprintf(stderr,"Debug flag now off");
}
}
void Examine_ELF_File (state* s){
char file [100];
printf("please enter file name: ");
fgets(file, 99, stdin);
file[strlen(file)-1]='\0';
strncpy(s->file_name, file, 100);
if(s->debug_mode)
fprintf(stderr, "Debug: file name set to %s\n", s->file_name);
if(Currentfd != -1) // it means we already open some file
close(Currentfd);
Currentfd = open(file, O_RDONLY);
if( fstat(Currentfd, &fd_stat) != 0 ) {
perror("stat failed");
exit(-1);
}
map_start =mmap(NULL, fd_stat.st_size, PROT_READ, MAP_SHARED, Currentfd, 0);
header = (Elf32_Ehdr *) map_start;
printf("\nMagic:\t\t\t\t%x %x %x\n", header-> e_ident[EI_MAG1], header-> e_ident[EI_MAG2], header-> e_ident[EI_MAG3]);
if(header-> e_ident[EI_MAG1]!=0x45 || header-> e_ident[EI_MAG2]!=0x4c || header-> e_ident[EI_MAG3]!=0x46){
fprintf(stderr, "The magic number isn't consistent with an ELF file");
munmap(map_start, fd_stat.st_size);
close(Currentfd);
Currentfd = -1;
}
else{
printf("Data:\t\t\t\t0x%x\n", header-> e_ident[EI_DATA]);
printf("Entry point address:\t\t%x\n", header-> e_entry);
printf("Start of section headers:\t%d (bytes into file)\n", header-> e_shoff);
printf("Number of section headers:\t%d\n", header-> e_shnum);
printf("Size of section headers:\t%d (bytes)\n", header-> e_shentsize);
printf("Start of program headers:\t%d (bytes into file)\n", header-> e_phoff);
printf("Number of program headers:\t%d\n", header-> e_phnum);
printf("Size of program headers:\t%d (bytes)\n", header-> e_phentsize);
}
}
void Print_Section_Names(state* s){
if(Currentfd == -1)
{
perror("Can't print section names because there is no file loaded");
return;
}
//Elf32_Ehdr* header_struct = (Elf32_Ehdr *)map_start; //points to elf header structure
section = (Elf32_Shdr *)(map_start + header->e_shoff);// points to the section header
int sections_num = header->e_shnum;
char* string_table = (char*)(map_start + (section[header->e_shstrndx]).sh_offset); //points to the first name in section headers string table
if(s->debug_mode){
fprintf(stderr , "section header table index: %d\n" , header->e_shstrndx);
printf("[Nr] Name\t\t\t Addr\t\t Off\t\t Size\t\t Type\t\t Name offset\n");
}
else
printf("[Nr] Name\t\t\t Addr\t\t Off\t\t Size\t\t Type\t\t\n");
for(int i = 1 ; i < sections_num ; i++){
if(s->debug_mode)
printf("[%d] %-16s\t\t %08x\t %08x\t %08x\t %-10s\t %d\n" , i , &string_table[section[i].sh_name] , section[i].sh_addr , section[i].sh_offset , section[i].sh_size , typeString(section[i].sh_type) , section[i].sh_name);
else
printf("[%d] %-16s\t\t %08x\t %08x\t %08x\t %s\t\n" , i , &string_table[section[i].sh_name] , section[i].sh_addr , section[i].sh_offset , section[i].sh_size , typeString(section[i].sh_type));
}
}
void Print_Symbols (state* s){
if(Currentfd == -1){
fprintf(stderr, "please eximine a file first\n");
return;
}
section = (Elf32_Shdr *)(map_start + header->e_shoff);
char* sec_head_str_table = (char*)(map_start + (section[header->e_shstrndx]).sh_offset);
char* str_table;
for(int i =0; i<header->e_shnum; i++)
if(section[i].sh_type == SHT_STRTAB && strcmp(".strtab", &sec_head_str_table[section[i].sh_name])==0)
str_table = (char*) map_start+section[i].sh_offset;
for(int i =0; i<header->e_shnum; i++)
if(section[i].sh_type == SHT_SYMTAB){
symbol = (Elf32_Sym*) ((char *)map_start + section[i].sh_offset);
int size = section[i].sh_size/section[i].sh_entsize;
if(s->debug_mode)
fprintf(stderr, "Debug: size of each symbol table: %x\n number of entries: %d\n\n", section[i].sh_entsize, size);
printf("[Nr] Value Sec_Index Sec_Name\t Sym_name\n");
for(int i = 0; i<size; i++){
printf("[%2d] %08x ", i, symbol[i].st_value);
if(symbol[i].st_shndx == SHN_UNDEF)
printf(" UND\t%-15s ", "");
if(symbol[i].st_shndx == SHN_COMMON)
printf(" COM\t%-15s ", "");
if(symbol[i].st_shndx == SHN_ABS)
printf(" ABS\t%-15s ", "");
else printf("%5d\t%-16s ", symbol[i].st_shndx, &sec_head_str_table[section[symbol[i].st_shndx].sh_name]);
printf("%-16s\n", &str_table[symbol[i].st_name]);
}
}
}
void Quit(state* s){
if(s->debug_mode)
fprintf(stderr, "quitting\n");
munmap(map_start, fd_stat.st_size);
free (s);
exit(0);
}
char* typeString (Elf32_Word type){
switch (type)
{
case SHT_NULL:
return "NULL";
case SHT_PROGBITS:
return "PROGBITS";
case SHT_SYMTAB:
return "SYMTAB";
case SHT_STRTAB:
return "STRTAB";
case SHT_RELA:
return "RELA";
case SHT_HASH:
return "HASH";
case SHT_DYNAMIC:
return "SYNAMIC";
case SHT_NOTE:
return "NOTE";
case SHT_NOBITS:
return "NOBITS";
case SHT_REL:
return "REL";
case SHT_SHLIB:
return "SHLIB";
case SHT_DYNSYM:
return "SYNSYM";
case SHT_LOPROC:
return "LOPROC";
case SHT_HIPROC:
return "HIPROC";
case SHT_LOUSER:
return "LOUSER";
case SHT_HIUSER:
return "HIUSER";
default:
return "";
}
}
|
C
|
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
void sighup_handler()
{
printf("Receive SIGHUP signal.\n");
}
int main()
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = &sighup_handler;
sigaction(SIGHUP, &sa, NULL);
while (1);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.