language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
/*******************************************************************************\
| gavrInterrupt.c
| Author: Todd Sukolsky
| Initial Build: 4/16/2013
| Last Revised: 4/16/2013
|================================================================================
| Description: This module is a spin-off of commandCenter.c. It is used to
| alert the BeagleBone that the GAVR is sending it something. Blocks on read.
| Forks to call ReceiveGAVR which will call SendGAVR
|--------------------------------------------------------------------------------
| Revisions:
|================================================================================
| *NOTES:Polling example found at: http://bwgz57.wordpress.com/tag/beaglebone/
\*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include "pollingExtras.h"
void error(const char *msg);
void handleInterrupt(void);
int main(){
//Declare a file descriptor and open the file we need as read only.
int fd;
fd = open("/sys/class/gpio/gpio34/value", O_RDONLY); //this is the file for GAVR request to come in.
struct pollfd pfd;
//Intiailize polling file as the file descriptor
pfd.fd = fd;
pfd.events = POLLPRI;
pfd.revents = 0;
//Lead is what the current pin is set to, ready is how many times this guy has been activated.
int lead,lastLead,ready;
lastLead=get_lead(fd);
while (1) {
ready = poll(&pfd, 1, -1);
printf("ready: %d\n", ready);
if (pfd.revents != 0) { //if an event happened and the pin is a 1, that means we got an interrupt from GAVR
lead=get_lead(fd);
printf("Calling interrupt handler()");
handleInterrupt();
lastLead=lead;
}
}
return 0;
}
/****************************
error:
****************************/
void error(const char *msg){
perror(msg);
}
/****************************
handleInterrupt()
****************************/
void handleInterrupt(){
int pid2, pipes[2];
pipe(pipes);
pid2=fork();
if (pid2<0){
error("Error starting \"RecieveGAVR\" process.\n");
} else if (pid2==0){//child process
//Declare arguments and setup the pipe to see communications
char *args[]={"/home/root/Documents/beagle-bone.git/CommScripts/ReceiveGAVR.py",0};
//Close STDIN of pipe, duplicate STDOUT and STDERR as the output end of pipe.
/*close(pipes[0]);
dup2(pipes[1],1);
dup2(pipes[1],2);*/
execv(args[0],args);
error("Unable to exec ReceiveGAVR.");
} else { //Parent
/*dup2(pipes[0],0);
close(pipes[1]);*/
waitpid(pid2,NULL,0);
}//end of fork, go back to blocking
}
|
C
|
/*
* Simple microseconds delay routine, utilizingARM's DWT
* (Data Watchpoint and Trace Unit) and HAL library.
* Intended to use with gcc compiler, but can be easily edited
* for any other C compiler.
* Max K
*
*
* This file is part of DWT_Delay package.
* DWT_Delay 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.
*
* us_delay 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.
* http://www.gnu.org/licenses/.
*/
#include "stm32f1xx_hal.h"
#include "cmsis_os.h"
#include "../include/dwt_delay.h"
#define DWT_CYCCNT *(volatile unsigned long *)(DWT_BASE + 0x004UL)
#define DWT_CONTROL *(volatile unsigned long *)DWT_BASE
#define SCB_DEMCR *(volatile unsigned long *)(CoreDebug_BASE + 0x00CUL)
void DWT_Init(void)
{
//if (!(CoreDebug->DEMCR & CoreDebug_DEMCR_TRCENA_Msk)) {
//CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
//DWT->CYCCNT = 0;
//DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
//}
//разрешаем использовать счётчик
SCB_DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
//обнуляем значение счётного регистра
DWT_CYCCNT = 0;
//запускаем счётчик
DWT_CONTROL |= DWT_CTRL_CYCCNTENA_Msk;
}
static __inline uint32_t delta(uint32_t t0, uint32_t t1)
{
return (t1 - t0);
}
/**
* Delay routine itself.
* Time is in microseconds (1/1000000th of a second), not to be
* confused with millisecond (1/1000th).
*
* @param uint32_t us Number of microseconds to delay for
*/
void DWT_Delay(uint32_t us) // microseconds
{
//int32_t targetTick = DWT_CYCCNT + us * (SystemCoreClock/1000000);
//while (DWT_CYCCNT <= targetTick);
uint32_t t0 = DWT_CYCCNT;
uint32_t us_count_tic = us * (SystemCoreClock/1000000);
while (delta(t0, DWT_CYCCNT) < us_count_tic) ;
}
|
C
|
#include <stdio.h>
int main()
{
int arr1[100], arr2[100], mergeArray[100*2];
int size1, size2, mergeSize;
int index1, index2, mergeIndex;
int i,j,temp;
printf("Enter the size of first array : ");
scanf("%d", &size1);
printf("Enter elements in first array : \n");
for(i=0; i<size1; i++)
{
printf ("Element[%d]: ",i+1);
scanf("%d", &arr1[i]);
}
printf("\nEnter the size of second array : ");
scanf("%d", &size2);
printf("Enter elements in second array : \n");
for(i=0; i<size2; i++)
{
printf ("Element[%d]: ",i+1);
scanf("%d", &arr2[i]);
}
for(i=0;i<size1;i++)
for(j=i+1;j<size1;j++)
if (arr1[i]>arr1[j])
{
temp=arr1[i];
arr1[i]=arr1[j];
arr1[j]=temp;
}
for(i=0;i<size2;i++)
for(j=i+1;j<size2;j++)
if (arr2[i]>arr2[j])
{
temp=arr2[i];
arr2[i]=arr2[j];
arr2[j]=temp;
}
mergeSize = size1 + size2;
index1 = 0;
index2 = 0;
while (index1 < size1 && index2 < size2)
{
if(arr1[index1] < arr2[index2])
mergeArray[mergeIndex++] = arr1[index1++];
else
mergeArray[mergeIndex++] = arr2[index2++];
}
while(index1 < size1)
mergeArray[mergeIndex++] = arr1[index1++];
while(index2 < size2)
mergeArray[mergeIndex++] = arr2[index2++];
printf("\nArray merged in ascending order : ");
for(i=0; i<mergeSize; i++)
{
printf("%d\t", mergeArray[i]);
}
return 0;
}
|
C
|
//
// lab2.c
// lab2
//
// Created by yuejing zhu on 2017/9/6.
// Copyright © 2017年 Xianng. All rights reserved.
//
#include <stdio.h>
int main(int argc, const char * argv[]) {
int f0 = 0, f1 = 1;
int loop_number = 20;
int number = 0;
printf("First 20 Fibonacci numbers are:\n");
for (int i=0; i<loop_number; i++) {
if (i==0) {
number = f0;
}else if (i==1){
number = f1;
}else{
number = f0+f1;
f0 = f1;
f1 = number;
}
printf("%d ",number);
}
printf("\n");
return 0;
}
|
C
|
#define BYTE unsigned char
#define WORD unsigned short
#define DWORD unsigned int
#define QWORD unsigned long long
void blank2zero(QWORD* name)
{
int i;
QWORD temp;
for(i=0;i<8;i++)
{
temp = ( (*name)>>(i*8) )&0xff;
if(temp == 0x20)
{
*name -= ((QWORD)0x20)<<(i*8);
}
}
}
void zero2blank(QWORD* name)
{
int i;
QWORD temp;
for(i=0;i<8;i++)
{
temp = ( (*name)>>(i*8) )&0xff;
if(temp == 0)
{
*name += ((QWORD)0x20)<<(i*8);
}
}
}
void small2capital(QWORD* name)
{
int i;
QWORD temp;
for(i=0;i<8;i++)
{
temp = ( (*name) >> (i*8) )&0xff;
if(temp>='a' && temp<='z')
{
*name -= ( (QWORD)0x20 )<<(i*8);
}
}
}
void str2data(BYTE* str,QWORD* data)
{
int i;
*data=0;
for(i=0;i<8;i++)
{
if(str[i]<=0x20) break;
*data+=((QWORD)str[i])<<(i*8);
}
}
|
C
|
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/seq_file.h>
#include <linux/proc_fs.h>
#include <linux/jiffies.h>
#include <linux/sort.h>
int cmp(const int *a, const int *b)
{
if (*a > *b)
return 1;
if (*a < *b)
return -1;
return 0;
}
#define PROC_NAME "sort"
MODULE_LICENSE("Dual BSD/GPL");
int size = 8;
static int proc_count_show(struct seq_file *m, void *dummy)
{
int i;
int j;
int *v;
long t1;
long t2;
long ms;
v = kmalloc(size * sizeof(int), GFP_KERNEL);
for (i = 0; i < size; ++i)
v[i] = size - i;
t1 = jiffies;
for (i = 0; i < size - 1; ++i)
for (j = i + 1; j < size; ++j)
if (v[i] > v[j])
{
int tmp = v[i];
v[i] = v[j];
v[j] = tmp;
}
/* Jiffies can eventually wrap! you should not measure time like this */
t2 = jiffies;
ms = ((t2 - t1) * 1000) / HZ;
seq_printf(m, "size:%d time:%lums jiffies:%lu\n", size, ms, (t2 - t1));
for (i = 0; i < size; ++i)
v[i] = size - i;
t1 = jiffies;
sort(v, size, sizeof(int), cmp, NULL);
t2 = jiffies;
ms = ((t2 - t1) * 1000) / HZ;
seq_printf(m, "size:%d time:%lums jiffies:%lu\n", size, ms, (t2 - t1));
kfree(v);
size *= 2;
return 0;
}
static int proc_count_open(struct inode *inode, struct file *file)
{
return single_open(file, proc_count_show, NULL);
}
/*
* Aca se definen las funciones que manejan las operaciones comunes.
* .open es la funcion de abrir el archivo del /proc
* .read es la funcion para leer
* .llseek es la que se llama cuando se le hace fseek (miren que se usa una por
* defecto que ya está, si uno quiere puede usar una propia).
* .release para cerrar el archivo.
*
* Las funciones que no se definen en aca estan en otro lado. Por ejemplo,
* la funcion single_release esta en fs/seq_file.c
*
*/
static struct file_operations proc_count_operations = {
.open = proc_count_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int count_init(void)
{
struct proc_dir_entry *e;
e = create_proc_entry(PROC_NAME, 0, NULL);
/* e es un puntero a la estructura que representa nuestro archivo
* virtual en el /proc */
if (e)
{
/* aca asignamos las funciones que van a manejar los eventos en
* la entrada del /proc */
e->proc_fops = &proc_count_operations;
}
else
{
printk(KERN_ERR "/proc/" PROC_NAME " creation failed \n");
/* FIXME: tenemos que retornar aca un uno porque no se pudo crear el
* "archivo"? Que pasa si retorno un uno en esta funciOn y un cero? */
}
return 0;
}
static void count_exit(void)
{
remove_proc_entry(PROC_NAME, NULL);
}
module_init(count_init);
module_exit(count_exit);
|
C
|
/*WAP to multiply a 3*3 matrix.*/
#include<stdio.h>
int main()
{
int a[3][3],b[3][3],c[3][3];
int i,j;
printf("\nenter element of first matrix");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("\nenter element of second matrix");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
c[i][j]=a[i][j]*b[i][j];
printf("\n multiplication of two matrices is \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("%d",c[i][j]);
printf("\n");
}
return 0;
}
|
C
|
#include<stdio.h>
#include<unistd.h>
#include<errno.h>
#include<fcntl.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<stdlib.h>
#define BUFFER_SIZE 1024
int main(int argc, char *argv[]){
int fd;
char buffer[BUFFER_SIZE];
if(argc != 2){
fprintf(stderr, "Usages:%s ouffilename!\n\a", argv[0]);
exit(EXIT_FAILURE);
}
if((fd=open(argv[1], O_WRONLY|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR)) == -1){
fprintf(stderr, "Open %s Error:%s\n\a", argv[1],strerror(errno));
exit(EXIT_FAILURE);
}
if(dup2(fd, fileno(stdout)) == -1){
fprintf(stderr, "Redirect standard Out Error:%s\n\a", strerror(errno));
exit(EXIT_FAILURE);
}
fprintf(stderr, "Now ,please input string");
fprintf(stderr, "(To quit use CTRL+C)\n");
while(1){
fgets(buffer, BUFFER_SIZE, stdin);
if(feof(stdin))
break;
write(fileno(stdout), buffer, strlen(buffer));
}
exit(EXIT_SUCCESS);
return 0;
}
|
C
|
/* A library for binary decision diagrams.
*
* Many operations are given with worst-case complexity measures,
* based on the number of nodes in the BDD arguments. We write '|f|'
* to denote the number of nodes in BDD f.
*/
#ifndef BDDLIB_INCLUDED
#define BDDLIB_INCLUDED
#include <stdio.h>
#include "boolean.h"
/**********************************************************************/
/* BDD manager type and operations */
/**********************************************************************/
/* A manager of the state for multiple BDDs. */
typedef struct bdd_mgr bdd_mgr_t;
/* Creates and initializes a new BDD manager with the specified number
* of variables, which must be positive. */
extern bdd_mgr_t *
bdd_mgr_create (unsigned num_vars);
/* Creates and initializes a new BDD manager with the specified number
* of variables and with a hint for initial number of nodes to
* allocate. */
extern bdd_mgr_t *
bdd_mgr_create_with_hint (unsigned num_vars, unsigned capacity_hint);
/* Frees the resources used by the BDD manager. */
extern void
bdd_mgr_destroy (bdd_mgr_t *mgr);
/* Returns the number of variables in the manager. O(1) time and space. */
extern unsigned
bdd_mgr_get_num_vars (bdd_mgr_t *mgr);
/* Returns the number of BDD nodes in the manager. O(1) time and space. */
extern unsigned
bdd_mgr_get_num_nodes (bdd_mgr_t *mgr);
/* Returns the number of BDD nodes at the given level in the manager.
* O(1) time and space. */
extern unsigned
bdd_mgr_get_num_nodes_at_level (bdd_mgr_t *mgr, unsigned lvl);
/* Returns the number of allocated nodes in the manager. O(1) time
* and space. */
extern unsigned
bdd_mgr_get_num_allocated (bdd_mgr_t *mgr);
/* Swaps the order of variables indexed by i and i+1. The value of
* idx must be less than bdd_mgr_get_num_vars (mgr) - 1. */
extern void
bdd_mgr_swap_variables (bdd_mgr_t *mgr, unsigned idx);
/**********************************************************************/
/* Result cache types and functions */
/**********************************************************************/
typedef struct
{
unsigned num_lookups; /* the number of cache lookups */
unsigned num_hits; /* the number of cache hits */
unsigned num_inserts; /* the number of cache insertions */
} bdd_cache_stats_t;
/* Pretty-prints the cache statistics to the file handle. */
extern void
bdd_cache_stats_fprint (FILE *handle, bdd_cache_stats_t stats);
/* Gets the cache statistics for the manager. */
extern bdd_cache_stats_t
bdd_mgr_get_cache_stats (bdd_mgr_t *mgr);
/**********************************************************************/
/* BDD type, constants, and accessors */
/**********************************************************************/
typedef unsigned bdd_t;
enum {bdd_false = 0, bdd_true = 1};
/* Gets the variable of the root of the BDD. */
extern unsigned
bdd_var (bdd_mgr_t *mgr, bdd_t b);
/* Gets the variable level of the root of the BDD. */
extern unsigned
bdd_level (bdd_mgr_t *mgr, bdd_t b);
/* Gets the low branch of the root of the BDD. */
extern bdd_t
bdd_low (bdd_mgr_t *mgr, bdd_t b);
/* Gets the high branch of the root of the BDD. */
extern bdd_t
bdd_high (bdd_mgr_t *mgr, bdd_t b);
/**********************************************************************/
/* BDD reference counting operations */
/**********************************************************************/
/* Increases the reference count of the BDD. */
extern void
bdd_inc_ref (bdd_mgr_t *mgr, bdd_t b);
/* Decreases the reference count of the BDD. The reference count of
* the BDD must be positive. */
extern void
bdd_dec_ref (bdd_mgr_t *mgr, bdd_t b);
extern void
bdd_ptr_dec_ref (bdd_mgr_t *mgr, bdd_t *b);
/**********************************************************************/
/* BDD operations */
/**********************************************************************/
/* Returns a BDD representing the variable 'i', which must be less
* than the number of variables in the manager. O(1) time and
* space. */
extern bdd_t
bdd_ith_var (bdd_mgr_t *mgr, unsigned i);
/* Computes the logical AND of the two BDDs. O(|b1| * |b2|) time and
* space. */
extern bdd_t
bdd_and (bdd_mgr_t *mgr, bdd_t b1, bdd_t b2);
/* Computes the logical OR of the two BDDs. O(|b1| * |b2|) time and
* space. */
extern bdd_t
bdd_or (bdd_mgr_t *mgr, bdd_t b1, bdd_t b2);
/* Computes the logical XOR of the two BDDs. O(|b1| * |b2|) time and
* space. */
extern bdd_t
bdd_xor (bdd_mgr_t *mgr, bdd_t b1, bdd_t b2);
/* Computes the logical EQUIV of the two BDDs. O(|b1| * |b2|) time
* and space. */
extern bdd_t
bdd_equiv (bdd_mgr_t *mgr, bdd_t b1, bdd_t b2);
/* Computes the logical NAND of the two BDDs. O(|b1| * |b2|) time and
* space. */
extern bdd_t
bdd_nand (bdd_mgr_t *mgr, bdd_t b1, bdd_t b2);
/* Computes the logical IMPLIES of the two BDDs. O(|b1| * |b2|) time
* and space. */
extern bdd_t
bdd_implies (bdd_mgr_t *mgr, bdd_t b1, bdd_t b2);
/* Computes the logical negation of the BDD. O(|b|) time and
* space. */
extern bdd_t
bdd_not (bdd_mgr_t *mgr, bdd_t b);
/* Computes if-then-else of the BDDs. */
extern bdd_t
bdd_ite (bdd_mgr_t *mgr, bdd_t p, bdd_t t, bdd_t f);
/* Restricts the BDD by assigning a value to a variable. O(|b|) time
* and space. */
extern bdd_t
bdd_restrict (bdd_mgr_t *mgr, bdd_t b, unsigned var, boolean val);
/* Performs existential instantiation on the variable and BDD.
* O(|b| ^ 2) time and space. */
extern bdd_t
bdd_existential (bdd_mgr_t *mgr, unsigned var, bdd_t b);
/* Performs universal instantiation on the variable and BDD.
* O(|b| ^ 2) time and space. */
extern bdd_t
bdd_universal (bdd_mgr_t *mgr, unsigned var, bdd_t b);
/* Composes two BDDs f and g on variable x, yielding f with x replaced
* by g. O(|f| ^ 2 * |g| ^ 2) time and space. */
extern bdd_t
bdd_compose (bdd_mgr_t *mgr, bdd_t f, unsigned x, bdd_t g);
/* Returns the number of satisfying solutions of b. */
extern double
bdd_sat_count (bdd_mgr_t *mgr, bdd_t b);
/* /\* Returns the number of nodes that appear within the given BDD. *\/ */
/* unsigned */
/* bdd_get_num_nodes (bdd_mgr_t *mgr, bdd_t b); */
#endif /* BDDLIB_INCLUDED */
|
C
|
#include "lua.h"
#include "lstate.h"
#include "llex.h"
#include "lparser.h"
#include "blocks.h"
#include <string.h>
#include <sys/time.h>
#if LUA_USE_BLOCK_CONTEXT
static char *parseErrMsg(const char *error_msg, int *err) {
const char *whereEnd = NULL;
const char *lineEnd = NULL;
const char *messageStart = NULL;
const char *messageEnd = NULL;
whereEnd = strchr(error_msg,':');
if (whereEnd) {
lineEnd = strchr(whereEnd + 1,':');
}
if (lineEnd) {
if (!sscanf(lineEnd + 2,"%d:", err)) {
*err = 0;
messageStart = lineEnd + 2;
} else {
messageStart = strchr(lineEnd + 2,':');
messageStart++;
}
} else {
messageStart = error_msg;
}
messageEnd = messageStart;
while (*messageEnd && (*messageEnd != '\r') && (*messageEnd != '\n')) {
messageEnd++;
}
int size = (messageEnd - messageStart);
char *msg = calloc(1, size + 1);
lua_assert(msg != NULL);
memcpy(msg, messageStart, size);
return msg;
}
void luaVB_dumpBlock(BlockContext *bctx) {
printf("block stack\r\n");
while (bctx) {
printf("block %d\r\n",bctx->block);
bctx = bctx->previous;
}
printf("\r\n");
}
BlockContext *luaVB_getBlock(lua_State *L, CallInfo *where) {
CallInfo *ci;
if (where == NULL) {
ci = L->ci;
} else{
ci = where;
}
return ci->bctx;
}
BlockContext *luaVB_pushBlock(lua_State *L, CallInfo *where, int id) {
CallInfo *ci;
if (where == NULL) {
ci = L->ci;
} else{
ci = where;
}
// Check that id is not on top
if (ci->bctx && ci->bctx->block == id) {
return ci->bctx;
}
// Push id
BlockContext *bctx = luaM_malloc(L, sizeof(BlockContext));
if (bctx) {
bctx->block = id;
bctx->previous = ci->bctx;
ci->bctx = bctx;
}
return bctx;
}
BlockContext *luaVB_popBlock(lua_State *L, CallInfo *where) {
CallInfo *ci;
if (where == NULL) {
ci = L->ci;
} else{
ci = where;
}
BlockContext *bctx = ci->bctx;
if (bctx) {
ci->bctx = bctx->previous;
luaM_freemem(L, bctx, sizeof(BlockContext));
}
return ci->bctx;
}
#define LUAVB_BLOCK_MESSAGE_TABLE_SIZE 32
typedef struct BlockMessage {
int block; /* Block id */
uint8_t state;
uint64_t last;
struct BlockMessage *next;
} BlockMessage;
static BlockMessage **message_table;
static uint8_t get_hash(uint32_t key) {
key = key * 2654435761 & (LUAVB_BLOCK_MESSAGE_TABLE_SIZE - 1);
return key;
}
int luaVB_init(lua_State *L) {
message_table = luaM_malloc(L, sizeof(BlockMessage *) * LUAVB_BLOCK_MESSAGE_TABLE_SIZE);
if (!message_table) {
// Not enough memory
return -1;
}
memset(message_table, 0, sizeof(BlockMessage *) * LUAVB_BLOCK_MESSAGE_TABLE_SIZE);
return 0;
}
void luaVB_emitMessage(lua_State *L, int type, int id) {
// Current message
BlockMessage *current = NULL;
// Get current time
struct timeval now;
gettimeofday(&now, NULL);
// Convert to milliseconds
uint64_t now_millis = now.tv_sec * 1000 + (now.tv_usec / 1000);
if ((type == luaVB_BLOCK_START_MSG) || (type == luaVB_BLOCK_END_MSG)) {
// Locate block message into block message table
uint8_t hash = get_hash(id);
if (!message_table[hash]) {
// Has entry is empty, create the first entry, emit message always
current = luaM_malloc(L, sizeof(BlockMessage));
if (current) {
memset(current, 0, sizeof(BlockMessage));
message_table[hash] = current;
// Store block id and message type
current->block = id;
} else {
// Not enough memory, silent exit, and do not emit message
return;
}
} else {
// Search for message
current = message_table[hash];
while (current) {
if (current->block == id) {
break;
}
current = current->next;
}
if (!current) {
// Not found, create a new one
current = luaM_malloc(L, sizeof(BlockMessage));
if (current) {
memset(current, 0, sizeof(BlockMessage));
current->next = message_table[hash];
message_table[hash] = current;
// Store block id and message type
current->block = id;
} else {
// Not enough memory, silent exit, and do not emit message
return;
}
}
}
}
switch (type) {
case luaVB_BLOCK_START_MSG:
if ((current->state == luaVB_BLOCK_MSG_STATE_NONE) || (current->state == luaVB_BLOCK_MSG_STATE_END)) {
if (now_millis - current->last < 200) {
return;
}
current->state = luaVB_BLOCK_MSG_STATE_START;
current->last = now_millis;
printf("<blockStart,%d>\r\n",id);
}
break;
case luaVB_BLOCK_END_MSG:
if (current->state == luaVB_BLOCK_MSG_STATE_START) {
current->state = luaVB_BLOCK_MSG_STATE_END;
current->last = now_millis;
printf("<blockEnd,%d>\r\n",id);
}
break;
case luaVB_BLOCK_ERR_CATCH_MSG:
printf("<blockErrorCatched,%d>\r\n",id);
break;
case luaVB_BLOCK_ERR_MSG: {
// Get error message from the stack
const char *error_msg = lua_tostring(L, -1);
// Parse error message
int err;
char * msg = parseErrMsg(error_msg, &err);
if (msg) {
printf("<blockError,%d,%s>\r\n", id, msg);
}
break;
}
}
}
#endif // LUA_USE_BLOCK_CONTEXT
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
//1st code //ص㡪룬븴
//int Add(int x, int y)
//{
// int z = x+y;
// return z;
//}
//
//int main()
//{
// int a = 10;
// int b = 20;
// int c = Add(a, b);
//
// printf("%d\n", c);
// return 0;
//}
//2nd code 飺һͬԪصļ
// //ķʣͨ±
//int main()
//{
// int arr[12] = {1,2,3,4,5,6,7,8,9,10,11,12};
// int i = 0; //ѭ
// for (i = 0; i<sizeof(arr) / sizeof(arr[0]); i++) //ַijȳһַijȼַĸ
// {
// arr[i] = 0;
// }
// for (i = 0; i <sizeof(arr) / sizeof(arr[0]); i++)
// {
// printf("%d ", arr[i]);
// }
// return 0;
//}
//3rd code λ(Զƽλ)
//
//int main()
//{
// int a = 5;
// int b = a<<1;
// printf("a = %d\n", a);
// printf("b = %d\n", b);
// return 0;
//}
//code 4thstaticҵ
void test()
{
static int a = 1; //ξֲʹֲڱ߱䳤
a++;
printf("%d\n", a);
}
int main()
{
int i = 0;
for (i = 0; i < 10; i++)
{
test();
}
return 0;
}
|
C
|
#include <GLFW/glfw3.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <string.h>
#include <sys/ioctl.h>
/*
* The serialport_init function is taken from the 'arduino-serial' library
* located at https://github.com/todbot/arduino-serial.git
* Courtesy of Tod E. Kurt
*/
int serialport_init(const char* serialport, int baud)
{
struct termios toptions;
int fd;
//fd = open(serialport, O_RDWR | O_NOCTTY | O_NDELAY);
fd = open(serialport, O_RDWR | O_NONBLOCK );
if (fd == -1) {
perror("serialport_init: Unable to open port ");
return -1;
}
//int iflags = TIOCM_DTR;
//ioctl(fd, TIOCMBIS, &iflags); // turn on DTR
//ioctl(fd, TIOCMBIC, &iflags); // turn off DTR
if (tcgetattr(fd, &toptions) < 0) {
perror("serialport_init: Couldn't get term attributes");
return -1;
}
speed_t brate = baud; // let you override switch below if needed
switch(baud) {
case 4800: brate=B4800; break;
case 9600: brate=B9600; break;
#ifdef B14400
case 14400: brate=B14400; break;
#endif
case 19200: brate=B19200; break;
#ifdef B28800
case 28800: brate=B28800; break;
#endif
case 38400: brate=B38400; break;
case 57600: brate=B57600; break;
case 115200: brate=B115200; break;
}
cfsetispeed(&toptions, brate);
cfsetospeed(&toptions, brate);
// 8N1
toptions.c_cflag &= ~PARENB;
toptions.c_cflag &= ~CSTOPB;
toptions.c_cflag &= ~CSIZE;
toptions.c_cflag |= CS8;
// no flow control
toptions.c_cflag &= ~CRTSCTS;
//toptions.c_cflag &= ~HUPCL; // disable hang-up-on-close to avoid reset
toptions.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
toptions.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off s/w flow ctrl
toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // make raw
toptions.c_oflag &= ~OPOST; // make raw
// see: http://unixwiz.net/techtips/termios-vmin-vtime.html
toptions.c_cc[VMIN] = 0;
toptions.c_cc[VTIME] = 0;
//toptions.c_cc[VTIME] = 20;
tcsetattr(fd, TCSANOW, &toptions);
if( tcsetattr(fd, TCSAFLUSH, &toptions) < 0) {
perror("init_serialport: Couldn't set term attributes");
return -1;
}
return fd;
}
int main(int argc, char *argv[])
{
if(argc < 2) {
printf("Second arg should be serial device\n");
return 1;
}
GLFWwindow* window;
/* Initialize the library */
if (!glfwInit())
return -1;
int w = 640;
int h = 480;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(w, h, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
int USB = serialport_init(argv[1], 19200);
unsigned char val = 0;
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT);
int nbars = 64;
/* Render here */
for(int i = 0; i < nbars; i++) {
read(USB, &val, 1);
double vh = ((val / 255.0) * 2) - 1;
double bar_w = 1.0 / (float)nbars;
double l = i * bar_w;
double r = (i + 1) * bar_w;
l = (l * 2) - 1;
r = (r * 2) - 1;
glBegin(GL_TRIANGLES);
glColor3f(0.0, 0.3, 0.7);
glVertex2f(l, -1);
glVertex2f(r, -1);
glVertex2f(r, vh);
glVertex2f(r, vh);
glVertex2f(l, vh);
glVertex2f(l, -1);
glEnd();
}
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
glfwTerminate();
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#define cls printf("\033[H\033[2J")
int main() {
int i, iMax;
i = 0;
iMax = 10;
while(i <= iMax)
{
printf("Sto contando...%d\n" , i);
i++;
sleep(1);
cls;
}
printf("Ho contato fino a %d" , iMax);
return 0;
}
|
C
|
//Getopt() manejo de opciones -algo
#include <stdio.h>
#include <unistd.h>
#define ARGUMENTOS "i:oh"
int main (int argc, char *argv[]) {
int opcion = 0;
char *opcion1Valores = NULL;
while ( (opcion = getopt(argc, argv, ARGUMENTOS)) != -1) {
switch( opcion ) {
case 'i':
/*
optarg tiene los valores despues del argumento
-algo valores
optarg = valores;
si no existen valores
optarg = (NULL);
*/
opcion1Valores = optarg;
printf("\nOpcion i = %s", opcion1Valores);
break;
case 'o':
printf("\nOpcion o ");
break;
case 'h':
printf("Parametos admitidos\n -i valor \n");
printf("-o\n -h ayuda\n");
return 0;
break;
case '?':
/*
getopt retorna ? para parametros desconocidos
*/
if (optopt == 'i') {
printf("\nMissing mandatory input option");
} else {
printf("\nParametro desconocido");
}
break;
}
}
printf("\n");
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_process_char.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lcouto <lcouto@student.42sp.org.br> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/04 12:19:29 by lcouto #+# #+# */
/* Updated: 2020/05/22 22:03:12 by lcouto ### ########.fr */
/* */
/* ************************************************************************** */
#include "../include/ft_printf.h"
static int ft_putstr(char *string)
{
int i;
i = 0;
while (string[i])
{
ft_putchar_fd(string[i], 1);
i++;
}
return (i);
}
static int ft_apply_flags(t_pf *val, char c)
{
int j;
j = 0;
if (val->zeroflag == 1)
ft_memset(val->padding, '0', val->width - 1);
else
ft_memset(val->padding, ' ', val->width - 1);
if (val->dashflag == 1)
{
ft_putchar_fd(c, 1);
j = ft_putstr(val->padding);
val->dashflag = 0;
}
else
{
j = ft_putstr(val->padding);
ft_putchar_fd(c, 1);
}
return (j);
}
t_pf *ft_process_char(const char *format, t_pf *val, int arg)
{
char c;
int j;
j = 0;
if (!format)
return (0);
c = (char)arg;
if (!(val->padding = ft_calloc(val->width, sizeof(char) + 1)))
return (0);
if (val->width > 0)
{
j = ft_apply_flags(val, c);
val->width = 0;
}
else
ft_putchar_fd(c, 1);
val->total = val->total + j + 1;
val->dashflag = 0;
free(val->padding);
return (val);
}
|
C
|
#include "s32k144_lpuart.h"
#include "device_registers.h"
#include "clock_manager.h"
/*!
* @brief Sends the LPUART 8-bit character.
*
* This functions sends an 8-bit character.
*
*
* @param base LPUART Instance
* @param data data to send (8-bit)
*/
void lpuart_Putchar(LPUART_Type * base, uint8_t data)
{
while((base->STAT & LPUART_STAT_TDRE_MASK)>>LPUART_STAT_TDRE_SHIFT==0);
/* Wait for transmit buffer to be empty */
base->DATA=data; /* Send data */
}
/*******************************************************************************
* Code
******************************************************************************/
static void lpuaetSetBaudRate(LPUART_Type *base, unsigned int desiredBaudRate)
{
DEV_ASSERT(instance < LPUART_INSTANCE_COUNT);
uint16_t sbr, sbrTemp, i;
uint32_t osr, tempDiff, calculatedBaud, baudDiff;
uint32_t lpuartSourceClock;
clock_names_t instanceClkName ;
uint32_t baudRegValTemp;
if(base==LPUART0)
{
instanceClkName=LPUART0_CLK;
}
else if(base==LPUART1)
{
instanceClkName=LPUART1_CLK;
}
else if(base==LPUART2)
{
instanceClkName=LPUART2_CLK;
}
/* Get the LPUART clock as configured in the clock manager */
(void)CLOCK_SYS_GetFreq(instanceClkName, &lpuartSourceClock);
/* Check if current instance is clock gated off. */
DEV_ASSERT(lpuartSourceClock > 0U);
/* Check if the desired baud rate can be configured with the current protocol clock. */
DEV_ASSERT(lpuartSourceClock >= (desiredBaudRate * 4U));
/* This lpuart instantiation uses a slightly different baud rate calculation
* The idea is to use the best OSR (over-sampling rate) possible
* Note, osr is typically hard-set to 16 in other lpuart instantiations
* First calculate the baud rate using the minimum OSR possible (4) */
osr = 4;
sbr = (uint16_t)(lpuartSourceClock / (desiredBaudRate * osr));
calculatedBaud = (lpuartSourceClock / (osr * sbr));
if (calculatedBaud > desiredBaudRate)
{
baudDiff = calculatedBaud - desiredBaudRate;
}
else
{
baudDiff = desiredBaudRate - calculatedBaud;
}
/* loop to find the best osr value possible, one that generates minimum baudDiff
* iterate through the rest of the supported values of osr */
for (i = 5U; i <= 32U; i++)
{
/* calculate the temporary sbr value */
sbrTemp = (uint16_t)(lpuartSourceClock / (desiredBaudRate * i));
/* calculate the baud rate based on the temporary osr and sbr values */
calculatedBaud = (lpuartSourceClock / (i * sbrTemp));
if (calculatedBaud > desiredBaudRate)
{
tempDiff = calculatedBaud - desiredBaudRate;
}
else
{
tempDiff = desiredBaudRate - calculatedBaud;
}
if (tempDiff <= baudDiff)
{
baudDiff = tempDiff;
osr = i; /* update and store the best osr value calculated */
sbr = sbrTemp; /* update store the best sbr value calculated */
}
}
// /* Check if osr is between 4x and 7x oversampling.
// * If so, then "BOTHEDGE" sampling must be turned on */
// if ((osr > 3U) && (osr < 8U))
// {
// LPUART_SetBothEdgeSamplingCmd(base, true);
// }
// /* program the osr value (bit value is one less than actual value) */
// LPUART_SetOversamplingRatio(base, (osr - 1U));
// /* write the sbr value to the BAUD registers */
// LPUART_SetBaudRateDivisor(base, sbr);
baudRegValTemp = base->BAUD;
baudRegValTemp &= ~(LPUART_BAUD_OSR_MASK);
baudRegValTemp &= ~(LPUART_BAUD_SBR_MASK);
baudRegValTemp |= LPUART_BAUD_OSR(osr - 1U);
baudRegValTemp |= sbr & LPUART_BAUD_SBR_MASK;
base->BAUD = baudRegValTemp;
}
/*!
* @brief Enable/Disable the LPUART transmitter.
*
* This function enables or disables the LPUART transmitter, based on the
* parameter received.
*
*
* @param base LPUART base pointer.
* @param enable Enable(true) or disable(false) transmitter.
*/
static inline void LPUART_SetTransmitterCmd(LPUART_Type * base, bool enable)
{
base->CTRL = (base->CTRL & ~LPUART_CTRL_TE_MASK) | ((enable ? 1UL : 0UL) << LPUART_CTRL_TE_SHIFT);
/* Wait for the register write operation to complete */
while((bool)((base->CTRL & LPUART_CTRL_TE_MASK) != 0U) != enable) {}
}
/*!
* @brief Enable/Disable the LPUART receiver.
*
* This function enables or disables the LPUART receiver, based on the
* parameter received.
*
*
* @param base LPUART base pointer
* @param enable Enable(true) or disable(false) receiver.
*/
static inline void LPUART_SetReceiverCmd(LPUART_Type * base, bool enable)
{
base->CTRL = (base->CTRL & ~LPUART_CTRL_RE_MASK) | ((enable ? 1UL : 0UL) << LPUART_CTRL_RE_SHIFT);
/* Wait for the register write operation to complete */
while((bool)((base->CTRL & LPUART_CTRL_RE_MASK) != 0U) != enable) {}
}
/*FUNCTION**********************************************************************
*
* Function Name : LPUART_DRV_Init
* Description : This function initializes a LPUART instance for operation.
* This function will initialize the run-time state structure to keep track of
* the on-going transfers, ungate the clock to the LPUART module, initialize the
* module to user defined settings and default settings, configure the IRQ state
* structure and enable the module-level interrupt to the core, and enable the
* LPUART module transmitter and receiver.
* The following is an example of how to set up the lpuart_state_t and the
* lpuart_user_config_t parameters and how to call the LPUART_DRV_Init function
* by passing in these parameters:
* lpuart_user_config_t lpuartConfig;
* lpuartConfig.baudRate = 9600;
* lpuartConfig.bitCountPerChar = LPUART_8_BITS_PER_CHAR;
* lpuartConfig.parityMode = LPUART_PARITY_DISABLED;
* lpuartConfig.stopBitCount = LPUART_ONE_STOP_BIT;
* lpuartConfig.transferType = LPUART_USING_INTERRUPTS;
* lpuart_state_t lpuartState;
* LPUART_DRV_Init(instance, &lpuartState, &lpuartConfig);
*
* Implements : LPUART_DRV_Init_Activity
*END**************************************************************************/
void lpuart_device_Init(LPUART_Type* base,const tlpuart_config lpuartConfig)
{
DEV_ASSERT(instance < LPUART_INSTANCE_COUNT);
DEV_ASSERT(lpuartStatePtr != NULL);
DEV_ASSERT(lpuartUserConfig != NULL);
/* initialize the parameters of the LPUART config structure with desired data */
lpuaetSetBaudRate(base, lpuartConfig.baudRate);
if (lpuartConfig.bitCountPerChar == LPUART_10_BITS_PER_CHAR)
{
base->BAUD = (base->BAUD & ~LPUART_BAUD_M10_MASK) | ((uint32_t)1U << LPUART_BAUD_M10_SHIFT);
}
else
{
/* config 8-bit (M=0) or 9-bits (M=1) */
base->CTRL = (base->CTRL & ~LPUART_CTRL_M_MASK) | ((uint32_t)lpuartConfig.bitCountPerChar << LPUART_CTRL_M_SHIFT);
/* clear M10 to make sure not 10-bit mode */
base->BAUD &= ~LPUART_BAUD_M10_MASK;
}
base->CTRL = (base->CTRL & ~LPUART_CTRL_PE_MASK) | (((uint32_t)lpuartConfig.parityMode >> 1U) << LPUART_CTRL_PE_SHIFT);
base->CTRL = (base->CTRL & ~LPUART_CTRL_PT_MASK) | (((uint32_t)lpuartConfig.parityMode & 1U) << LPUART_CTRL_PT_SHIFT);
base->BAUD = (base->BAUD & ~LPUART_BAUD_SBNS_MASK) | ((uint32_t)lpuartConfig.stopBitCount << LPUART_BAUD_SBNS_SHIFT);
/* finally, enable the LPUART transmitter and receiver */
LPUART_SetTransmitterCmd(base,true);
LPUART_SetReceiverCmd(base,true);
base->CTRL = (base->CTRL & ~LPUART_CTRL_RIE_MASK) | (( 1UL ) << LPUART_CTRL_RIE_SHIFT);
}
void lpuart_device_DeInit(LPUART_Type* base)
{
LPUART_SetTransmitterCmd(base,false);
LPUART_SetReceiverCmd(base,false);
}
|
C
|
/** @file DS18B20 sensor API main code
#include "DS18B20_API.h"
/*********************************//**
*DS18 sensor init fucntion. Initializes the basics for the usage of the sensor.
*************************************/
void DS18_Init(void){
DS18_GPIOInit();
DS18_TIMInit();
}
/*********************************//**
*DS18 sensor GPIO init function.
* Initializes the GPIO port for the usage with the DS18B20 sensor.
*************************************/
void DS18_GPIOInit(){
aktdesgpio(DS18_PORT, 1);
//GPIOE->OSPEEDR = (0x01<<DS18_PIN);
//GPIOE->PUPDR = (0x01<<DS18_PIN);
setOutputMode(DS18_PORT, DS18_PIN, 1);
//Output
GPIOE->MODER |= (1<<(DS18_PIN*2));
GPIOE->MODER &= ~(2<<(DS18_PIN*2));
}
/*********************************//**
*DS18 sensor timer init function.
* Initializes the TIM6 timer for the usage
* with the delay function that will be used
* to control the wait times when using the sensor.
*************************************/
void DS18_TIMInit(void){
aktTimer();
setDebugMode(1);
//setUpdateMode(1);
setOnePulse(1);
}
/*********************************//**
*Read a bit from the OneWire line. Reads a single bit from the OneWire line and returns it.
*@return 1-0 the bit the was read.
*************************************/
uint8_t DS18_ReadBit(void){
uint8_t bit = 0;
//Low
GPIOE->BSRRH |= (1<<DS18_PIN);
//Output
GPIOE->MODER |= (1<<(DS18_PIN*2));
GPIOE->MODER &= ~(2<<(DS18_PIN*2));
delay(1);
//High
//GPIOE->BSRRL |= (1<<DS18_PIN);
//delay(1);
//Input
GPIOE->MODER &= ~(3<<(DS18_PIN*2));
delay(5);
bit = (GPIOE->IDR & (1<<DS18_PIN))>>DS18_PIN;
delay(80);
return bit;
}
/*********************************//**
*Write a bit to the OneWire line. Writes a single bit in the OneWire line.
*@param bit the bit to send.
*************************************/
void DS18_WriteBit(uint8_t bit){
if(bit & 1){
//Low
GPIOE->BSRRH |= (1<<DS18_PIN);
//Output
GPIOE->MODER |= (1<<(DS18_PIN*2));
GPIOE->MODER &= ~(2<<(DS18_PIN*2));
delay(5);
//High
GPIOE->BSRRL |= (1<<DS18_PIN);
delay(80);
}else{
//Low
GPIOE->BSRRH |= (1<<DS18_PIN);
//Output
GPIOE->MODER |= (1<<(DS18_PIN*2));
GPIOE->MODER &= ~(2<<(DS18_PIN*2));
delay(80);
//High
GPIOE->BSRRL |= (1<<DS18_PIN);
//High
delay(5);
}
}
/*********************************//**
* Read a byte from the OneWire line. Reads a byte from the OneWire line.
* Internally uses the DS18_ReadBit() function.
* @see DS18_ReadBit()
* @return The byte that has been read.
*************************************/
uint8_t DS18_ReadByte(void){
uint8_t value = 0;
uint8_t bitMask = 0x01;
uint8_t i;
for(i = 0; i < 8; i++){
if(DS18_ReadBit() == 1){
value |= bitMask;
}
bitMask <<= 1;
}
return value;
}
/*********************************//**
* Read a data array from the OneWire line. Reads a data array of n size from the OneWire line.
* Internally uses the DS18_ReadByte() function.
* @param data The pointer to the array of data where the data will be written.
* @param count The number of bytes to read.
* @see DS18_ReadByte()
*************************************/
void DS18_ReadData(uint8_t data[], uint8_t count){
int i = 0;
for(i = 0; i < count ;i++){
data[i] = DS18_ReadByte();
}
}
/*********************************//**
* Write a byte to the OneWire line. Writes a byte to the OneWire line.
* Internally uses the DS18_WriteBit() function.
* @param byte The byte to write.
* @see DS18_WriteBit();
*************************************/
void DS18_WriteByte(uint8_t byte){
uint8_t bitMask = 0x01;
uint8_t i;
for(i = 0; i < 8;i++){
if(byte & bitMask){
DS18_WriteBit(1);
}else{
DS18_WriteBit(0);
}
bitMask <<= 1;
}
}
/*********************************//**
* Send the convert temp to all DS18B20 sensors.
* First sends a reset pulse to the sensors,
* then writes the skip ROM command and finally the convert command.
* Waits 750ms to complete the conversion.
* Uses the DS18_WriteByte() and DS18_Reset() functions internally.
* @see DS18_WriteByte()
* @see DS18_Reset()
*************************************/
void DS18_convertTemp(void){
int i = 0;
if(DS18_Reset() == 1){
DS18_WriteByte(DS18_CMD_SKIPROM); //Skip ROM
DS18_WriteByte(DS18_CMD_CONVERT); //Convert temp
for(i = 0; i <= 20;i++){
delay(62500);
}
}
}
/*********************************//**
* Read the temperature from the DS18B20 sensor. Does the full process of reading the temperature from the sensor.
* First it sends the reset command to the sensor. After that, sends the skip rom and convert temp commands and
* waits to complete the conversion. Finally reads the scratchpad from the sensor and converts the values to float.
* Internally uses the DS18_Reset(), DS18_WriteByte and DS18_ReadData functions.
* @return The temperature reading of the sensor.
* @see DS18_Reset()
* @see DS18_WriteByte()
* @see DS18_ReadData()
*************************************/
DS18_DATA DS18_readSensor(void){
DS18_DATA sensorData;
uint8_t data[9];
DS18_convertTemp();
if(DS18_Reset() == 1){
DS18_WriteByte(DS18_CMD_SKIPROM);
DS18_WriteByte(DS18_CMD_READSP);
DS18_ReadData(data, 9);
DS18_Reset();
sensorData.temp = 0;
sensorData.temp += (data[0] & 0x01)*0.0625;
sensorData.temp += ((data[0] & 0x02)>>1)*0.125;
sensorData.temp += ((data[0] & 0x04)>>2)*0.25;
sensorData.temp += ((data[0] & 0x08)>>3)*0.5;
sensorData.temp += ((data[0] & 0x10)>>4)*1;
sensorData.temp += ((data[0] & 0x20)>>5)*2;
sensorData.temp += ((data[0] & 0x40)>>6)*4;
sensorData.temp += ((data[0] & 0x80)>>7)*8;
sensorData.temp += ((data[1] & 0x01))*16;
sensorData.temp += ((data[1] & 0x02)>>1)*32;
sensorData.temp += ((data[1] & 0x04)>>2)*64;
if((data[1] & 0x08) == 0x08){
sensorData.temp = -sensorData.temp;
}
}
return sensorData;
}
/*********************************//**
* Send reset signal to the sensor.
* Sends the reset signal to the sensor, to prepare it for later commands.
*
*
*************************************/
uint8_t DS18_Reset(void){
uint8_t low;
uint8_t high;
delay(100);
//Low
GPIOE->BSRRH |= (1<<DS18_PIN);
//Output
GPIOE->MODER |= (1<<(DS18_PIN*2));
GPIOE->MODER &= ~(2<<(DS18_PIN*2));
delay(560);
GPIOE->BSRRL |= (1<<DS18_PIN);
delay(80);
//Input
GPIOE->MODER &= ~(3<<(DS18_PIN*2));
low = ((GPIOE->IDR & (1<<DS18_PIN))>>DS18_PIN);
delay(80);
high = ((GPIOE->IDR & (1<<DS18_PIN))>>DS18_PIN);
delay(50);
if((low == 0) && (high == 1)){
return 1;
}else{
return 0;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void){
srand ((int) time (NULL));
//declare variables
int input = 0;
int divisor;
int dividend;
int quotient;
int count = 0;
//loop for 10 times
for(int i=0; i<10; i++){
//setting random values
divisor = rand () % 12+1;
quotient = rand () % 13;
dividend = quotient*divisor;
//receiving user input
printf("%d / %d = ", dividend, divisor);
scanf("%d", &input);
//checking if the user is correct
if(input == quotient){
printf("Correct!\n");
count++;
}
else{
printf("Wrong. The correct answer is %d\n", quotient);
}
}
//final output of score
printf("Epic! You got %d/10!\n", count);
}
|
C
|
#ifndef MATH_FUNCTIONS_H
#define MATH_FUNCTIONS_H
const double MASTER_MOE;
const double PI;
// returns the absolute value of the input. Input can be any integer or double but it returns the value as a double.
double shoesMath_abs(double input);
// returns the remainder of dividing the input by the divisor. It can take integer, double, negative, or positive input.
// divisor must be positive.
double shoesMath_mod(double input, double divisor);
// the input and maximum value both must be positive.
// if the input is greater than the max, it returns the max. otherwise it returns the input as is.
double shoesMath_max(double value, double max);
// the input and maximum value both can be positive or negative double.
// if the input is negative and less than the maximum, it returns the negative maximum.
// if the input is positive and greater than the maximum, it returns the positive maximum.
// otherwise it returns the input as is.
double shoesMath_abs_max(double value, double abs_max);
// converts degrees to radians. Input should be a double.
double shoesMath_rad(double deg);
// converts radians to degrees. Input should be a double.
double shoesMath_deg(double rad);
// input should be in radians. returns 0 if the input does not lie on one of the axis.
// 1 is the positive x axis, 2 is the positive y axis, 3 is the negative x axis, 4 is the negative y axis.
// the margin of error for floating point error is determined by the MASTER_MOE constant.
int axis_rad (double input);
// input should be in radians. returns 0 if the input does not lie in one of the quadrants.
// 1, 2, 3, and 4 are each of the quadrants respectively.
// the margin of error for floating point error is determined by the MASTER_MOE constant.
int quadrant_rad(double input);
// takes in an angle in radians and converts it to an equavilent positive angle less than 2 PI.
double simplify_rad(double input);
// input must be in radians.
// returns the angle as it would be reflected across the x-axis.
double reflect_x_rad(double input);
// input must be in radians.
// returns the angle as it would be reflected across the y-axis.
double reflect_y_rad(double input);
// input must in radians.
// returns sine of the input with 3 significant figures.
double shoesMath_sin_rad(double input);
// input must in radians.
// returns cosine of the input with 3 significant figures.
double shoesMath_cosine_rad(double input);
// input must in radians.
// returns tangent of the input with 3 significant figures.
double shoesMath_tangent_rad(double input);
#endif
|
C
|
/* ###############################################################
##
## C Tree Builder
##
## File: tree.c
##
## Revision 0.0.0.2 1996/04/03 10:26:06 kurt
## Added line,column to some printouts;
## addresses of nodes printed out, too.
## -- Kurt Cockrum <kurt@grogatch.seaslug.org>
##
## Revision 0.0.0.1 1996/04/03 10:08:46 kurt
## o missing return() in make_for()
## o misc. cleanups
## -- Kurt Cockrum <kurt@grogatch.seaslug.org>
##
## Revision 0.0.0.0 1996/03/30 02:49:41 kurt
## o added right curly brackets inside comments for benefit of vi
## o Addresses of tree nodes are printed in messages;
## minor content changes to some messages
## o Threw away ntype[]
## o Rev. 0.0 from
## -rw-r--r-- 1 1047 1047 44198 Aug 7 19:32
## ftp://ftp.cs.wisc.edu/coral/tmp/spf/ctree.0.01.tar.gz
## -- Kurt Cockrum <kurt@grogatch.seaslug.org>
##
## Programmer: Shaun Flisakowski
## Date: Jan 21, 1995
##
##
############################################################### */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include "tree.h"
#include "gram.h"
#include "globals.h"
#include "token.h"
/* ############################################################### */
if_node *make_if(tn_t type)
{
if_node *tmp_node;
if ((tmp_node = (if_node *) HeapAlloc(Parse_TOS->node_heap)) != NULL){
tmp_node->which = IF_T;
tmp_node->type = type;
tmp_node->cond = (treenode *) NULL;
tmp_node->then_n = (treenode *) NULL;
tmp_node->else_n = (treenode *) NULL;
return(tmp_node);
}
fputs("Error: Out of memory in make_if().\n",stderr);
exit(1);
}
/* ############################################################### */
for_node *make_for(tn_t type)
{
for_node *tmp_node;
if ((tmp_node = (for_node *) HeapAlloc(Parse_TOS->node_heap)) != NULL){
tmp_node->which = FOR_T;
tmp_node->type = type;
tmp_node->init = (treenode *) NULL;
tmp_node->test = (treenode *) NULL;
tmp_node->incr = (treenode *) NULL;
tmp_node->stemnt = (treenode *) NULL;
return(tmp_node);
}
fputs("Error: Out of memory in make_for().\n",stderr);
exit(1);
}
/* ############################################################### */
leafnode *make_leaf(tn_t type)
{
leafnode *tmp_node;
if ((tmp_node = (leafnode *) HeapAlloc(Parse_TOS->node_heap)) != NULL){
tmp_node->which = LEAF_T;
tmp_node->type = type;
return(tmp_node);
}
fputs("Error: Out of memory in make_leaf().\n",stderr);
exit(1);
}
/* ############################################################### */
treenode *make_node(tn_t type)
{
treenode *tmp_node;
if ((tmp_node = (treenode *) HeapAlloc(Parse_TOS->node_heap)) != NULL){
tmp_node->which = NODE_T;
tmp_node->type = type;
tmp_node->lnode = (treenode *) NULL;
tmp_node->rnode = (treenode *) NULL;
return(tmp_node);
}
fputs("Error: Out of memory in make_node().\n",stderr);
exit(1);
}
/* ############################################################### */
void free_tree(treenode *root)
{
leafnode *leaf;
if_node *ifn;
for_node *forn;
if (!root)
return;
switch (root->which){
case LEAF_T:
leaf = (leafnode *) root;
if (leaf->tok == STRING)
free(leaf->data.str);
break;
case NODE_T:
free_tree(root->lnode);
free_tree(root->rnode);
break;
case IF_T:
ifn = (if_node *) root;
free_tree(ifn->cond);
free_tree(ifn->then_n);
free_tree(ifn->else_n);
break;
case FOR_T:
forn = (for_node *) root;
free_tree(forn->init);
free_tree(forn->test);
free_tree(forn->incr);
free_tree(forn->stemnt);
break;
default:
case NONE_T:
break;
}
HeapFree(Parse_TOS->node_heap,root);
/* free(root); */
}
/* ############################################################### */
leafnode *leftmost(treenode *root)
{
if_node *ifn;
for_node *forn;
switch (root->which){
case LEAF_T:
return((leafnode *) root);
break;
case NODE_T:
if (root->lnode)
return(leftmost(root->lnode));
else if (root->rnode)
return(leftmost(root->rnode));
fprintf(stderr,"\
Tree node 0x%0x with no children reached in leftmost().\n",
(unsigned int) root);
break;
case IF_T:
ifn = (if_node *) root;
if (ifn->cond)
return(leftmost(ifn->cond));
else if (ifn->then_n)
return(leftmost(ifn->then_n));
else if (ifn->else_n)
return(leftmost(ifn->else_n));
fprintf(stderr,"\
If-node 0x%0x with no children reached in leftmost().\n",
(unsigned int) root);
break;
case FOR_T:
forn = (for_node *) root;
if (forn->init)
return(leftmost(forn->init));
else if (forn->test)
return(leftmost(forn->test));
else if (forn->incr)
return(leftmost(forn->incr));
else if (forn->stemnt)
return(leftmost(forn->stemnt));
fprintf(stderr,"\
For-node 0x%0x with no children reached in leftmost().\n",
(unsigned int) root);
break;
case NONE_T:
default:
fprintf(stderr, "\
Internal error: unknown node 0x%0x in leftmost();\n\
type is: %d\n", (unsigned int) root, root->which);
break;
}
return((leafnode *) NULL);
}
/* ############################################################### */
leafnode *rightmost(treenode *root)
{
if_node *ifn;
for_node *forn;
switch (root->which){
case LEAF_T:
return((leafnode *) root);
break;
case NODE_T:
if (root->rnode)
return(rightmost(root->rnode));
else if (root->lnode)
return(rightmost(root->lnode));
fprintf(stderr,"\
Tree node 0x%0x with no children reached in rightmost().\n",
(unsigned int) root);
break;
case IF_T:
ifn = (if_node *) root;
if (ifn->else_n)
return(rightmost(ifn->else_n));
else if (ifn->then_n)
return(rightmost(ifn->then_n));
else if (ifn->cond)
return(rightmost(ifn->cond));
fprintf(stderr,"\
If node 0x%0x with no children reached in rightmost().\n",
(unsigned int) root);
break;
case FOR_T:
forn = (for_node *) root;
if (forn->stemnt)
return(rightmost(forn->stemnt));
else if (forn->incr)
return(rightmost(forn->incr));
else if (forn->test)
return(rightmost(forn->test));
else if (forn->init)
return(rightmost(forn->init));
fprintf(stderr,"\
For node 0x%0x with no children reached in rightmost().\n",
(unsigned int) root);
break;
case NONE_T:
default:
fprintf(stderr, "\
Internal error: unknown node 0x%0x in rightmost();\n\
type is: %d\n", (unsigned int) root, root->which);
break;
}
return((leafnode *) NULL);
}
/* ############################################################### */
/* Scans the typedef declaration node N for the ident
naming the new type. --jsh */
leafnode *find_typedef_name(treenode *n)
{
switch(n->which)
{
case LEAF_T:
return (leafnode *)n;
case NODE_T:
while(n != 0 && n->which != LEAF_T)
{
switch(n->type)
{
case TN_DECL:
n = n->rnode;
break;
case TN_ARRAY_DECL:
n = n->lnode;
break;
case TN_PNTR:
fprintf(stderr,
"Internal error: TN_PNTR reached in find_typedef_name!\n");
return 0;
case TN_FUNC_DECL:
n = n->rnode;
break;
case TN_PARAM_LIST:
fprintf(stderr,
"find_typedef_name: got TN_PARAM_LIST\n");
return 0;
break;
default:
fprintf(stderr,
"Internal error: "
"unknown node type (%d) in find_typedef_name()\n",
n->type);
return 0;
}
}
return (leafnode *)n;
case IF_T:
case FOR_T:
case NONE_T:
default:
fprintf(stderr,
"Internal error: unknown node 0x%0x in find_typedef_name();\n"
" type is: %d\n", (unsigned int) n, n->which);
}
return 0;
}
/* ############################################################### */
leafnode *find_ident_name(treenode *n, treenode **rest)
{
if (rest)
*rest = (treenode*) NULL;
switch(n->which)
{
case LEAF_T:
return (leafnode *)n;
case NODE_T:
while(n != 0 && n->which != LEAF_T)
{
switch(n->type)
{
case TN_DECL:
n = n->rnode;
break;
case TN_ASSIGN:
case TN_ARRAY_DECL:
n = n->lnode;
break;
case TN_DECL_LIST:
case TN_PARAM_LIST:
if (rest)
*rest = n->rnode;
n = n->lnode;
break;
case TN_PNTR:
return 0;
case TN_FUNC_DECL:
n = n->rnode;
break;
case TN_EMPTY:
fprintf(stderr,
"find_ident_name -- got TN_EMPTY\n");
return 0;
break;
default:
fprintf(stderr,
"Internal error: "
"unknown node type (%d) in find_ident_name()\n",
n->type);
return 0;
}
}
return (leafnode *)n;
case IF_T:
case FOR_T:
case NONE_T:
default:
fprintf(stderr,
"Internal error: unknown node 0x%0x in find_ident_name();\n"
" type is: %d\n", (unsigned int) n, n->which);
}
return 0;
}
/* ############################################################### */
/* Scans the function declaration node N for the ident
naming the new function. */
leafnode *find_func_name(treenode *n)
{
for_node *f;
while((n != 0) && (n->which != LEAF_T))
{
switch(n->which)
{
case LEAF_T:
return (leafnode *)n;
case NODE_T:
switch(n->type)
{
case TN_DECL:
n = n->rnode;
break;
case TN_PNTR:
fprintf(stderr,
"Internal error: TN_PNTR reached in find_func_name!\n");
n = NULL;
break;
case TN_FUNC_DECL:
n = n->lnode;
break;
default:
fprintf(stderr,
"Internal error: "
"unknown node type (%d) in find_func_name()\n",
n->type);
n = NULL;
break;
}
break;
case FOR_T:
f = (for_node *) n;
switch(n->type)
{
case TN_FUNC_DEF:
n = f->test;
break;
default:
break;
}
break;
case IF_T:
case NONE_T:
default:
fprintf(stderr,
"Internal error: unknown node 0x%0x in find_func_name();\n"
" type is: %d\n", (unsigned int) n, n->which);
n = NULL;
break;
}
}
return (leafnode*) n;
}
/* ############################################################### */
|
C
|
/********************************************
Name: Isaias Delgado, Alex Hollis
Course: CSCE 3110.002
Assignment: Program 6, Dijkstra's Algorithm
Due Date: May 01, 2015 at 11:55PM
********************************************/
#include <stdio.h>
#include <time.h>
#define infinity 998
#define MAX 25
int prev[25];
void printPath(int index)
{
if (prev[index] > 0)
{
printPath(prev[index]);
}
if(prev[index] == 0 || prev[index] == -1)
printf("1 ");
printf("%d ", index+1);
}
void lowestCost(int nodes, int startN, int cost[MAX][MAX], int *distance) //Dijkstra's Algorithm Function
{
int i,j,count,k,flag[MAX],min;
/////////////////////////////
clock_t start, end, start2, end2; // time clocks
clock_t times[MAX]; //store times
//////////////////////////////
start2 = clock();
for(i = 0; i < nodes; i++)
distance[i] = infinity; //initialize all nodes to infinity.
start = clock(); // start timer
for(i=0;i<nodes;i++)
{
flag[i] = 0;
distance[i] = cost[startN][i]; //fill in initial known distances from start node to neighbors.
if(distance[i] != infinity) //valid edge found, take time
{
end = clock();
times[i] = (end - start); // save time in array
start = clock();
}
}
count = 0;
while(count<=nodes)
{
min=999;
for(j=0;j<nodes;j++)
{
if(distance[j]<min && !flag[j])
min=distance[j],k=j; // set smallest edge to current node
}
flag[k]=1;
count++;
for(j=0;j<nodes;j++)
{
if(((distance[k]+cost[k][j]<distance[j])) && !flag[j]) //new route found, shorter distance calculated.
{
distance[j]=distance[k]+cost[k][j]; //new path set
prev[j] = k; //update path
end = clock();
times[j] = (end - start); // save time
start = clock();
}
}
}
//////////// PRINT ///////////////
end2 = clock();
end = clock();
int z;
for(z = 1; z < nodes; z++)
{
if(distance[z] != infinity)
{
if(times[z] > 0) //check in case no time was recorded
{
printf(" %-2dc %.12fs ", (int)times[z], (times[z] /(double)CLOCKS_PER_SEC));
printPath(z);
printf("\n");
}
else // default to total algoirthm time if none calculated.
{
printf(" %-2dc %.12fs ", (int)(end2 - start2), ((end2 - start2) /(double)CLOCKS_PER_SEC));
printPath(z);
printf("\n");
}
}
else
{
printf(" No path to Node %d\n",z+1);
}
}
//////////////////////////////////////
}
int main( )
{
int nodes, startN, i, j, cost[MAX][MAX], distance[MAX];
nodes = 25;
for(i=0; i< nodes; i++) // scan in cost matrix
{
for(j=0; j<nodes; j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j] == 0)
cost[i][j] = infinity;
}
}
for(i = 0; i < nodes; i++)
prev[i] = -1;
startN = 0;
lowestCost(nodes, startN, cost, distance); // run Dijkstra's Algorithm
return 0;
}
|
C
|
#include <drivers/screen.h>
#include <kernel/memory.h>
#include <libs/stdio.h>
#include <libs/string.h>
#include <stdarg.h>
void printf(const char *fmt, ...) {
va_list arg;
va_start(arg, fmt);
int i = 0;
int state = 0;
int fmt_length = 0;
char ch;
char c;
int num;
unsigned int hex;
char *str;
while ((ch = fmt[i++]) != 0) {
if (state == 0) {
if (ch == '%') {
state = 1;
} else {
kput_char(ch);
}
} else {
switch (ch) {
case 's':
str = va_arg(arg, char *);
kprint(str);
state = 0;
break;
case 'c':
c = (char)va_arg(arg, int);
kput_char(c);
fmt_length = 0;
break;
case 'd':
num = va_arg(arg, int);
char *oct = itoa(num, fmt_length);
kprint(oct);
free(oct);
fmt_length = 0;
state = 0;
break;
case 'x':
hex = va_arg(arg, unsigned int);
kprint_hex(hex);
state = 0;
break;
default:
if (ch >= '0' && ch <= '9') {
fmt_length = fmt_length * 10 + ch - '0';
}
}
}
}
va_end(arg);
}
|
C
|
#pragma once
typedef unsigned long long ulong;
enum operation_type //
{
summ, prod, diff, none
};
typedef struct value_t // ,
{
enum operation_type operation;
float result;
}value_t;
typedef struct tnode //
{
int key;
void *data;
struct tnode *left;
struct tnode *right;
} tnode;
typedef void(*method_t)(tnode*);
typedef int(*comparator)(tnode*);
//
tnode *build_expr(float a, float b, float c, float d, float e, float f, float g, float h, float i);
void free_tree(tnode *n); // ,
void print_tree_expr(tnode *n, int level, method_t printer); // ,
void print_tree(tnode *n, int level, method_t printer); // ,
void traverse_postfix(tnode *root, method_t action); //
void traverse_infix(tnode *root, method_t action); //
void traverse_prefix(tnode *root, method_t action); //
tnode *tree_add(tnode *root, tnode *node); //
void tree_remove(tnode** root, int k, tnode** removed); //
tnode *get(tnode *tree, int k); //
tnode *get_val(tnode *tree, void* value); //
void tsort(int *arr, ulong length); //
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "define.h"
//read temporal maps and spatial maps by referring to "spatial_pairlist.txt" and "temporal_pairlist.txt".
int ReadST(char *s_listname, char *t_listname, short **t_input, short **s_input){
FILE *fp0,*fp1,*fp2;
char buf[MAXTEXT],s_filename[MAXTEXT],t_filename[MAXTEXT];
int count=0;
if((fp0=fopen(s_listname,"r"))==NULL){
fprintf(stderr,"ReadST: %s was not opened successfully\n",s_listname);
exit(1);
}
if((fp1=fopen(t_listname,"r"))==NULL){
fprintf(stderr,"ReadST: %s was not opened successfully\n",t_listname);
exit(1);
}
while(fgets(buf,sizeof(buf),fp0) != NULL){
strtok(buf,"\n\0");
snprintf(s_filename,MAXTEXT,"../input/%s",buf);
fgets(buf,sizeof(buf),fp1);
strtok(buf,"\n\0");
snprintf(t_filename,MAXTEXT,"../input/%s",buf);
printf("input s_filename is %s\n",s_filename);
printf("input t_filename is %s\n",t_filename);
if((fp2=fopen(s_filename,"rb"))==NULL){
fprintf(stderr,"ReadST: %s was not opened successfully\n",s_filename);
exit(1);
}
if((fread(s_input[count],sizeof(short),COL*ROW,fp2)) != (unsigned int)(COL*ROW)) {
fprintf(stderr, "ReadST: can't read s file\n");
exit(1);
}
fclose(fp2);
if((fp2=fopen(t_filename,"rb"))==NULL){
fprintf(stderr,"ReadST: %s was not opened successfully\n",t_filename);
exit(1);
}
if((fread(t_input[count],sizeof(short),COL*ROW,fp2)) != (unsigned int)(COL*ROW)) {
fprintf(stderr, "ReadST: can't read t file\n");
exit(1);
}
fclose(fp2);
count++;
}
if(count!=PAIRSIZE){
fprintf(stderr,"ReadST Warning: PAIRSIZE and the number of read files were not consistent\n");
}
return 0;
}
//execute DBUX with StatsCalc, GenLUT, AveLUT (if MWSIZE>=3), and PredDBUX.
int ExecDBUX(char *date_listname, short **t_input, short **s_input){
int i=0,LEVEL=0,MAXLEVEL=0;
short *tmin_input, *tmax_input;
if((tmin_input=malloc(COL*ROW*sizeof(short)))==NULL||(tmax_input=malloc(COL*ROW*sizeof(short)))==NULL){
fprintf(stderr,"ExecDBUX: can't allocate memory\n");
exit(1);
}
printf("DoStatistics...\n");
/*if(LIMITLEVEL>0){
StatsCalc(t_input,tmin_input,tmax_input);
MAXLEVEL=LIMITLEVEL;
}else if(LIMITLEVEL==0){
MAXLEVEL=StatsCalc(t_input,tmin_input,tmax_input);
}else{
fprintf(stderr,"ExecDBUX: LIMITLEVEL must not be negative value!\n");
exit(1);
}
*/
MAXLEVEL=StatsCalc(t_input,tmin_input,tmax_input,s_input);
printf("StatsCalc: MAXLEVEL=%d\n",MAXLEVEL);
//short *lookup[MAXLEVEL+1], *lookup_ave[MAXLEVEL+1], *snum[MAXLEVEL+1], *snum_ave[MAXLEVEL+1];
short **lookup,**lookup_ave,**snum,**snum_ave;
lookup=malloc(sizeof(short *)*(MAXLEVEL+1));
lookup_ave=malloc(sizeof(short *)*(MAXLEVEL+1));
snum=malloc(sizeof(short *)*(MAXLEVEL+1));
snum_ave=malloc(sizeof(short *)*(MAXLEVEL+1));
for(LEVEL=0;LEVEL<=MAXLEVEL;LEVEL++){
if((lookup[LEVEL]=malloc(COL*ROW*sizeof(short)))==NULL||(lookup_ave[LEVEL]=malloc(COL*ROW*sizeof(short)))==NULL||(snum[LEVEL]=malloc(COL*ROW*sizeof(short)))==NULL||(snum_ave[LEVEL]=malloc(COL*ROW*sizeof(short)))==NULL){
fprintf(stderr,"ExecDBUX: can't allocate memory\n");
exit(1);
}
}
for(LEVEL=0;LEVEL<=MAXLEVEL;LEVEL++){
for(i=0;i<COL*ROW;i++){
lookup[LEVEL][i]=0;
lookup_ave[LEVEL][i]=0;
snum[LEVEL][i]=0;
snum_ave[LEVEL][i]=0;
}
}
printf("LUT generating...\n");
if(GenLUT(tmin_input, tmax_input, t_input, s_input, lookup, snum, MAXLEVEL)!=0){
fprintf(stderr,"ExecDBUX: GenLUT error!\n");
exit(1);
} //input:tmin_input,t_input,s_input output:lookup,snum generate lookup maps.
if(LUT_MWSIZE==1){
printf("LUT generated! No moving average.\n");
//if you dont want to gapfill LUT, comment out from here to CO
printf("LUT gapfilling by lower LUT.\n");
for(LEVEL=1;LEVEL<=MAXLEVEL;LEVEL++){
for(i=0;i<COL*ROW;i++){
if(lookup[LEVEL][i]==NVALUE){
lookup[LEVEL][i]=lookup[LEVEL-1][i];
snum[LEVEL][i]=snum[LEVEL-1][i];
}
}
}
//CO
printf("do prediction...\n");
if(PredDBUX(date_listname, tmin_input, lookup, snum, MAXLEVEL)!=0){
fprintf(stderr,"ExecDBUX: PredDBUX error!\n");
exit(1);
}
}else if(LUT_MWSIZE%2==0){
fprintf(stderr,"ExecDBUX: LUT_MWSIZE must be an odd number. \n");
exit(1);
}else{
printf("LUT generated! applying moving average with size %d...\n",LUT_MWSIZE);
if(AveLUT(lookup, snum, lookup_ave, snum_ave, MAXLEVEL)!=0){
fprintf(stderr,"ExecDBUX: AveLUT error!\n");
exit(1);
} //input:lookup,snum output:lookup_ave,snum_ave generate averaged lookup maps.
//if you dont want to gapfill LUT, comment out from here to CO
printf("LUT gapfilling by lower LUT.\n");
for(LEVEL=1;LEVEL<=MAXLEVEL;LEVEL++){
for(i=0;i<COL*ROW;i++){
if(lookup_ave[LEVEL][i]==NVALUE){
lookup_ave[LEVEL][i]=lookup_ave[LEVEL-1][i];
snum_ave[LEVEL][i]=snum_ave[LEVEL-1][i];
}
}
}
//CO
printf("do prediction...\n");
if(PredDBUX(date_listname, tmin_input, lookup_ave, snum_ave, MAXLEVEL)!=0){
fprintf(stderr,"ExecDBUX: PredDBUX error!\n");
exit(1);
} //input:date_listname,tmin_input,lookup_ave,snum_ave output:None, generate predected maps.
}
/*LUT visualization.
//if(VisualizeLUT(tmin_input,lookup_ave,MAXLEVEL)!=0){
if(VisualizeLUT(tmin_input,lookup,MAXLEVEL)!=0){
fprintf(stderr,"ExecDBUX: VisualizeLUT error!\n");
exit(1);
}
*/
for(LEVEL=0;LEVEL<=MAXLEVEL;LEVEL++){
free(lookup[LEVEL]);
free(lookup_ave[LEVEL]);
free(snum[LEVEL]);
free(snum_ave[LEVEL]);
}
free(tmin_input);
free(tmax_input);
free(lookup);
free(lookup_ave);
free(snum);
free(snum_ave);
return 0;
}
int GenLUT(short *tmin_input, short *tmax_input, short **t_input, short **s_input, short **lookup_output, short **snum, int MAXLEVEL){
short *s_image;
//int *lookup[MAXLEVEL+1];
int **lookup;
int LEVEL=0,count=0,i=0,UPPERLEVEL=0;
char lookup_output_filename[256];
FILE *fp;
lookup=malloc(sizeof(int *)*(MAXLEVEL+1));
for(LEVEL=0;LEVEL<=MAXLEVEL;LEVEL++){
if((lookup[LEVEL]=malloc(COL*ROW*sizeof(int)))==NULL){
fprintf(stderr,"GenLUT: can't allocate memory\n");
exit(1);
}
}
if((s_image=malloc(COL*ROW*sizeof(short)))==NULL){
fprintf(stderr,"GenLUT: can't allocate memory\n");
exit(1);
}
for(LEVEL=0;LEVEL<=MAXLEVEL;LEVEL++){
for(i=0;i<ROW*COL;i++){
lookup[LEVEL][i]=0;
}
}
for(i=0;i<COL*ROW;i++){
if(tmax_input[i]==NVALUE||tmin_input[i]==NVALUE){
for(LEVEL=0;LEVEL<=MAXLEVEL;LEVEL++){
snum[LEVEL][i]=0;
}
}else{
UPPERLEVEL=(tmax_input[i]-tmin_input[i])/(STEP); //upperlevel for each pixel
for(LEVEL=0;LEVEL<=UPPERLEVEL;LEVEL++){
for(count=0;count<PAIRSIZE;count++){
s_image[i]=NVALUE;
if(LEVEL==0){
if((TNRANGE<=t_input[count][i])&&(t_input[count][i]<=tmin_input[i]+(LEVEL+1)*STEP)){
s_image[i]=s_input[count][i];
}else{
s_image[i]=NVALUE;
}
}else if(LEVEL==UPPERLEVEL){
if((tmin_input[i]+LEVEL*STEP<t_input[count][i])&&(t_input[count][i]<=TPRANGE)){
s_image[i]=s_input[count][i];
}else{
s_image[i]=NVALUE;
}
}else{
if(tmin_input[i]+LEVEL*STEP<t_input[count][i]&&t_input[count][i]<=tmin_input[i]+(LEVEL+1)*STEP){
s_image[i]=s_input[count][i];
}else{
s_image[i]=NVALUE;
}
}
if(SNRANGE<=s_image[i]&&s_image[i]<=SPRANGE){
snum[LEVEL][i]+=1;
}else{
s_image[i]=0;
}
lookup[LEVEL][i]=lookup[LEVEL][i]+s_image[i];
}
}
for(LEVEL=UPPERLEVEL+1;LEVEL<=MAXLEVEL;LEVEL++){
lookup[LEVEL][i]=lookup[UPPERLEVEL][i];
snum[LEVEL][i]=snum[UPPERLEVEL][i];
}
}
}
for(LEVEL=0;LEVEL<=MAXLEVEL;LEVEL++){
for(i=0;i<COL*ROW;i++){
if(snum[LEVEL][i]==0){
lookup[LEVEL][i]=NVALUE;
}else{
lookup[LEVEL][i]=lookup[LEVEL][i]/snum[LEVEL][i];
}
}
}
/*output lookup maps.*/
for(LEVEL=0;LEVEL<=MAXLEVEL;LEVEL++){
snprintf(lookup_output_filename,MAXTEXT,"../output/LOOKUP%d.raw",LEVEL);
for(i=0;i<COL*ROW;i++){
lookup_output[LEVEL][i]=(short)lookup[LEVEL][i];
}
if((fp=fopen(lookup_output_filename,"wb"))==NULL){
fprintf(stderr,"GenLUT: can't open output file\n");
exit(1);
}
if((fwrite(lookup_output[LEVEL],sizeof(short),COL*ROW,fp)) != (unsigned int)(COL*ROW)){
fprintf(stderr,"GenLUT: can't write output file\n");
exit(1);
}
fclose(fp);
snprintf(lookup_output_filename,MAXTEXT,"../output/LOOKUP%d_rel.raw",LEVEL);
if((fp=fopen(lookup_output_filename,"wb"))==NULL){
fprintf(stderr,"GenLUT: can't open output file\n");
exit(1);
}
if((fwrite(snum[LEVEL],sizeof(short),COL*ROW,fp)) != (unsigned int)(COL*ROW)){
fprintf(stderr,"GenLUT: can't write output file\n");
exit(1);
}
fclose(fp);
}
for(LEVEL=0;LEVEL<=MAXLEVEL;LEVEL++){
free(lookup[LEVEL]);
}
free(s_image);
free(lookup);
return 0;
}
int AveLUT(short **lookup_input, short **snum_input, short **lookup_output, short **snum_output, int MAXLEVEL){
char output_lookup_filename[256],output_snum_filename[256];
int *lookup[MAXLEVEL+1];
int LEVEL=0,i=0,m=0,count=0;
FILE *fp;
for(LEVEL=0;LEVEL<=MAXLEVEL;LEVEL++){
if((lookup[LEVEL]=(int*)malloc(COL*ROW*sizeof(int)))==NULL){
fprintf(stderr,"GenLUT: can't allocate memory\n");
exit(1);
}
}
for(LEVEL=0;LEVEL<=MAXLEVEL;LEVEL++){
for(i=0;i<ROW*COL;i++){
lookup_output[LEVEL][i]=0;
lookup[LEVEL][i]=0;
snum_output[LEVEL][i]=0;
}
}
for(LEVEL=0;LEVEL<=MAXLEVEL;LEVEL++){
for(i=0;i<ROW*COL;i++){
if((int)LUT_MWSIZE/2<=LEVEL&&LEVEL<=MAXLEVEL-(int)LUT_MWSIZE/2){
count=0;
for(m=0;m<LUT_MWSIZE;m++){
if(lookup_input[LEVEL+(int)(m-LUT_MWSIZE/2)][i]<=SNRANGE||SPRANGE<=lookup_input[LEVEL+(int)(m-LUT_MWSIZE/2)][i]){
count+=1;
}else{
lookup[LEVEL][i]+=lookup_input[LEVEL+(int)(m-LUT_MWSIZE/2)][i];
snum_output[LEVEL][i]+=snum_input[LEVEL+(int)(m-LUT_MWSIZE/2)][i];
}
}
if(count==LUT_MWSIZE){
lookup[LEVEL][i]=NVALUE;
snum_output[LEVEL][i]=0;
}else{
lookup[LEVEL][i]=lookup[LEVEL][i]/(LUT_MWSIZE-count);
}
}else{
lookup[LEVEL][i]=lookup_input[LEVEL][i];
snum_output[LEVEL][i]=snum_input[LEVEL][i];
}
}
}
for(LEVEL=0;LEVEL<=MAXLEVEL;LEVEL++){
snprintf(output_lookup_filename,MAXTEXT,"../output/LOOKUP%d_ave.raw",LEVEL);
for(i=0;i<COL*ROW;i++){
lookup_output[LEVEL][i]=(short)lookup[LEVEL][i];
}
if((fp=fopen(output_lookup_filename,"wb"))==NULL){
fprintf(stderr,"AveLUT: can't open output file\n");
exit(1);
}
if((fwrite(lookup_output[LEVEL],sizeof(short),COL*ROW,fp)) != (unsigned int)(COL*ROW)){
fprintf(stderr,"AveLUT: can't write output file\n");
exit(1);
}
fclose(fp);
snprintf(output_snum_filename,MAXTEXT,"../output/LOOKUP%d_ave_rel.raw",LEVEL);
if((fp=fopen(output_snum_filename,"wb"))==NULL){
fprintf(stderr,"AveLUT: can't open output file\n");
exit(1);
}
if((fwrite(snum_output[LEVEL],sizeof(short),COL*ROW,fp)) != (unsigned int)(COL*ROW)){
fprintf(stderr,"AveLUT: can't write output file\n");
exit(1);
}
fclose(fp);
}
return 0;
}
int PredDBUX(char *date_listname, short *tmin_input, short **lookup, short **snum, int MAXLEVEL){
FILE *fp,*fp2;
int i=0,count=0,LEVEL=0;
char date[MAXTEXT],s_filename[MAXTEXT],t_filename[MAXTEXT],output_filename[MAXTEXT];
short *t_input, *s_input, *s_output;
int *image,*snum_output;
if(((t_input=(short*)malloc(COL*ROW*sizeof(short)))==NULL)||
((s_input=(short*)malloc(COL*ROW*sizeof(short)))==NULL)||((s_output=(short*)malloc(COL*ROW*sizeof(short)))==NULL)||
((image=(int*)malloc(COL*ROW*sizeof(int)))==NULL)||((snum_output=(int*)malloc(COL*ROW*sizeof(int)))==NULL)){
fprintf(stderr,"PredDBUX: can't allocate memory\n");
exit(1);
}
//read prediction date.
if((fp=fopen(date_listname,"r"))==NULL){
fprintf(stderr,"PredDBUX: %s was not opened successfully\n",date_listname);
exit(1);
}
//loop for each prediction date.
for(count=0;count<PREDSIZE;count++){
if(fgets(date,sizeof(date),fp)==NULL){
fprintf(stderr,"PredDBUX Warning: datelist EOF\n");
}
strtok(date,"\n\0");
printf("calculation date is %s\n",date);
snprintf(s_filename,MAXTEXT,"../input/spatial_%s.raw",date);
snprintf(t_filename,MAXTEXT,"../input/temporal_%s.raw",date);
if((fp2=fopen(s_filename,"rb"))==NULL){
for(i=0;i<COL*ROW;i++)
s_input[i]=NVALUE;
}else{
if((fread(s_input,sizeof(short),COL*ROW,fp2)) != (unsigned int)(COL*ROW)){
fprintf(stderr,"PredDBUX: can't read s file\n");
exit(1);
}
fclose(fp2);
}
if((fp2=fopen(t_filename,"rb"))==NULL){
fprintf(stderr,"PredDBUX Warning: can't open %s, continue with nullmap\n",t_filename);
for(i=0;i<COL*ROW;i++)
t_input[i]=NVALUE;
}else{
if((fread(t_input,sizeof(short),COL*ROW,fp2)) != (unsigned int)(COL*ROW)){
fprintf(stderr,"PredDBUX: can't read t file\n");
exit(1);
}
fclose(fp2);
}
/* image initialize */
for(i=0;i<COL*ROW;i++){
image[i]=NVALUE;
snum_output[i]=NVALUE;
s_output[i]=NVALUE;
}
/* make gap-filled map. */
for(i=0;i<COL*ROW;i++){
if((t_input[i]<TNRANGE)||(t_input[i]>TPRANGE)){
image[i]=s_input[i]; //no temporal-base map.
snum_output[i]=-88;
}else{
if((s_input[i]<SNRANGE)||(s_input[i]>SPRANGE)){
//exist temporal-base map, no spatial-base map -> gap-filling
for(LEVEL=0;LEVEL<=MAXLEVEL;LEVEL++){
if(LEVEL==0){
if((TNRANGE<=t_input[i])&&(t_input[i]<=tmin_input[i]+(LEVEL+1)*STEP)){
image[i]=lookup[LEVEL][i];
snum_output[i]=snum[LEVEL][i];
}
}else if(LEVEL==MAXLEVEL){
if((tmin_input[i]+STEP*LEVEL<t_input[i])&&(t_input[i]<=TPRANGE)){
image[i]=lookup[LEVEL][i];
snum_output[i]=snum[LEVEL][i];
}
}else{
if((tmin_input[i]+STEP*LEVEL<t_input[i])&&(t_input[i]<=tmin_input[i]+STEP*(LEVEL+1))){
image[i]=lookup[LEVEL][i];
snum_output[i]=snum[LEVEL][i];
}
}
}
}else{
//exist temporal-base map, exist spatial-base map -> spatial-base map
image[i]=s_input[i];
snum_output[i]=-99;
}
}
}
//output gap-filled map.
snprintf(output_filename,MAXTEXT,"../output/spatial_%s_comp.raw",date);
for(i=0;i<COL*ROW;i++){
s_output[i]=(short)image[i];
}
if((fp2=fopen(output_filename,"wb"))==NULL){
fprintf(stderr,"PredDBUX: can't open output file\n");
exit(1);
}
if((fwrite(s_output,sizeof(short),COL*ROW,fp2)) != (unsigned int)(COL*ROW)){
fprintf(stderr,"PredDBUX: can't write output file\n");
exit(1);
}else{
printf("%s generated!\n",output_filename);
}
fclose(fp2);
snprintf(output_filename,MAXTEXT,"../output/spatial_%s_rel.raw",date);
for(i=0;i<COL*ROW;i++){
s_output[i]=(short)snum_output[i];
}
if((fp2=fopen(output_filename,"wb"))==NULL){
fprintf(stderr,"PredDBUX: can't open output file\n");
exit(1);
}
if((fwrite(s_output,sizeof(short),COL*ROW,fp2)) != (unsigned int)(COL*ROW)){
fprintf(stderr,"PredDBUX: can't write output file\n");
exit(1);
}else{
printf("%s generated!\n",output_filename);
}
fclose(fp2);
}
fclose(fp);
free(snum_output);
free(image);
free(t_input);
free(s_input);
free(s_output);
return 0;
}
//this is under development and not used in above codes.
int VisualizeLUT(short *tmin_input, short **lookup, int MAXLEVEL){
FILE *fp;
short t_input=TNRANGE;
int image=NVALUE,LEVEL=0,i=0;
//case A LUT visualization.
i=127577;
fp=fopen("A_LUT_DBUX.txt","w");
while(t_input<=TPRANGE){
for(LEVEL=0;LEVEL<=MAXLEVEL;LEVEL++){
if(LEVEL==0){
if((TNRANGE<=t_input)&&(t_input<=tmin_input[i]+(LEVEL+1)*STEP)){
image=lookup[LEVEL][i];
}
}else if(LEVEL==MAXLEVEL){
if((tmin_input[i]+STEP*LEVEL<t_input)&&(t_input<=TPRANGE)){
image=lookup[LEVEL][i];
}
}else{
if((tmin_input[i]+STEP*LEVEL<t_input)&&(t_input<=tmin_input[i]+STEP*(LEVEL+1))){
image=lookup[LEVEL][i];
}
}
}
fprintf(fp,"%d,%d\n",t_input,image);
t_input+=STEP/45.0;
}
fclose(fp);
t_input=TNRANGE;
i=255041;
fp=fopen("B_LUT_DBUX.txt","w");
while(t_input<=TPRANGE){
for(LEVEL=0;LEVEL<=MAXLEVEL;LEVEL++){
if(LEVEL==0){
if((TNRANGE<=t_input)&&(t_input<=tmin_input[i]+(LEVEL+1)*STEP)){
image=lookup[LEVEL][i];
}
}else if(LEVEL==MAXLEVEL){
if((tmin_input[i]+STEP*LEVEL<t_input)&&(t_input<=TPRANGE)){
image=lookup[LEVEL][i];
}
}else{
if((tmin_input[i]+STEP*LEVEL<t_input)&&(t_input<=tmin_input[i]+STEP*(LEVEL+1))){
image=lookup[LEVEL][i];
}
}
}
fprintf(fp,"%d,%d\n",t_input,image);
t_input+=STEP/45.0;
}
fclose(fp);
t_input=TNRANGE;
i=275684;
fp=fopen("C_LUT_DBUX.txt","w");
while(t_input<=TPRANGE){
for(LEVEL=0;LEVEL<=MAXLEVEL;LEVEL++){
if(LEVEL==0){
if((TNRANGE<=t_input)&&(t_input<=tmin_input[i]+(LEVEL+1)*STEP)){
image=lookup[LEVEL][i];
}
}else if(LEVEL==MAXLEVEL){
if((tmin_input[i]+STEP*LEVEL<t_input)&&(t_input<=TPRANGE)){
image=lookup[LEVEL][i];
}
}else{
if((tmin_input[i]+STEP*LEVEL<t_input)&&(t_input<=tmin_input[i]+STEP*(LEVEL+1))){
image=lookup[LEVEL][i];
}
}
}
fprintf(fp,"%d,%d\n",t_input,image);
t_input+=STEP/45.0;
}
fclose(fp);
return 0;
}
int StatsCalc(short **t_input, short *tmin_input, short *tmax_input, short **s_input){
int count=0,i=0,MAXLEVEL=0,LEVEL=0;
for(i=0;i<COL*ROW;i++){
tmin_input[i]=TPRANGE;
tmax_input[i]=TNRANGE;
for(count=0;count<PAIRSIZE;count++){
if((tmin_input[i]>t_input[count][i])&&(t_input[count][i]!=NVALUE)&&(s_input[count][i]!=NVALUE)) tmin_input[i]=t_input[count][i];
if((tmax_input[i]<t_input[count][i])&&(t_input[count][i]!=NVALUE)&&(s_input[count][i]!=NVALUE)) tmax_input[i]=t_input[count][i];
}
if(tmin_input[i]>tmax_input[i]){
tmin_input[i]=NVALUE;
tmax_input[i]=NVALUE;
}else{
LEVEL=(tmax_input[i]-tmin_input[i])/STEP;
if(MAXLEVEL<LEVEL) MAXLEVEL=LEVEL;
}
}
return MAXLEVEL;
}
|
C
|
// =============================================================================
// <core/platform/os.h>
//
// Compile-time operating system detection.
//
// Copyright Kristian Garnét.
// -----------------------------------------------------------------------------
#ifndef H_E933C36BFDD54DB8A5B047C37F93C0A0
#define H_E933C36BFDD54DB8A5B047C37F93C0A0
// -----------------------------------------------------------------------------
#define OS(feat) (defined(OS_##feat))
// -----------------------------------------------------------------------------
// macOS / iOS
#if defined(__APPLE__)
#include <TargetConditionals.h>
// macOS
#if defined(TARGET_OS_MAC)
#define OS_MACOS
// iOS
#elif defined(TARGET_OS_IPHONE)
#define OS_IOS
#endif
// -----------------------------------------------------------------------------
// BSDs
#elif defined(__FreeBSD__)
#define OS_FREEBSD
#elif defined(__NetBSD__)
#define OS_NETBSD
#elif defined(__OpenBSD__)
#define OS_OPENBSD
#elif defined(__DragonFly__)
#define OS_DRAGONFLYBSD
// -----------------------------------------------------------------------------
// Linux-based
#elif defined(__linux__)
#define OS_LINUX
// -----------------------------------------------------------------------------
// UNIX-compatible
#elif defined(__unix__)
#define OS_UNIX
// -----------------------------------------------------------------------------
// Windows
#elif defined(_WIN32)
#define OS_WIN32
// 64-bit
#if defined(_WIN64)
#define OS_WIN64
#endif
#endif
// -----------------------------------------------------------------------------
// Cygwin POSIX emulation layer for Windows
#if defined(__CYGWIN__)
#define OS_CYGWIN
#endif
// -----------------------------------------------------------------------------
// BSD
#if OS(FREEBSD) || OS(NETBSD) || OS(OPENBSD) || OS(DRAGONFLYBSD)
#define OS_BSD
#endif
// -----------------------------------------------------------------------------
// UNIX
#if defined(__unix__) || OS(MACOS) || OS(IOS) || OS(BSD) || OS(LINUX)
#define OS_UNIX
#endif
// -----------------------------------------------------------------------------
// POSIX
#if defined(__posix__) || OS(UNIX) || OS(CYGWIN)
#define OS_POSIX
#endif
// -----------------------------------------------------------------------------
// Windows uses the "\r\n" character sequence as a new line separator,
// while the rest of sane world uses just single '\n' character.
// Mac OS Classic uses "\n\r" but it's a coprolite.
#if OS(WIN32)
#define OS_EOL "\r\n"
#else
#define OS_EOL "\n"
#endif
// -----------------------------------------------------------------------------
// Windows uses the back slash as a path separator character.
// Forward slashes are preferred almost everywhere else.
#if OS(WIN32) && !OS(CYGWIN)
#define OS_PATH_SEP_CHR '\\'
#define OS_PATH_SEP_STR "\\"
#else
#define OS_PATH_SEP_CHR '/'
#define OS_PATH_SEP_STR "/"
#endif
// -----------------------------------------------------------------------------
#endif
|
C
|
#include <conio.h> /* kbhit, getch */
#include "binary.h"
#include "screen.h"
#include "cpu.h"
#include "opcodes.h"
int Accumulator;
int
next_instruction(int counter)
{
/* the next instruction to execute */
if (counter < 255) {
return counter+1;
}
/* else, loop back around to zero (keep in 0 to 255: 255+1=0) */
draw_status(STATUS_ERR | STATUS_RUN); /* overflow */
return 0;
}
int
run_instruction(int *mem, int counter)
{
int next, addr;
/* execute a single instruction from memory. implements a single
fetch/decode/execute model. fetch is the reference from mem,
decode is via the switch block, execute is each case in the
switch block. */
draw_count(counter);
draw_instr(mem[counter]);
tick();
next = next_instruction(counter);
/* some operations require an address from the next program
instruction. these instructions have a "fetch" bit set. */
if (mem[counter] & FETCH_BIT) {
draw_count(next);
draw_instr(mem[next]);
tick();
addr = mem[next]; /* set the address value */
next = next_instruction(next); /* set the next instruction */
}
/* the switch block recognizes each CPU instruction as a CPU
opcode, written in machine language (binary).
technically, there is a NOP instruction, but it's not
listed here because any unrecognized opcode is considered
a NOP instruction. BE CAREFUL OF USING UNRECOGNIZED
OPCODES WITH THE FETCH BIT SET, these will also advance
the next counter, and will result in a programming bug. */
switch(mem[counter]) {
case CPU_STOP:
return -1;
case CPU_RIGHT:
Accumulator = Accumulator>>1;
break;
case CPU_LEFT:
Accumulator = Accumulator<<1;
break;
case CPU_NOT:
Accumulator = ~Accumulator;
break;
case CPU_AND:
Accumulator = Accumulator & mem[addr];
break;
case CPU_OR:
Accumulator = Accumulator | mem[addr];
break;
case CPU_XOR:
Accumulator = Accumulator ^ mem[addr];
break;
case CPU_LOAD:
Accumulator = mem[addr];
break;
case CPU_STORE:
mem[addr] = Accumulator;
break;
case CPU_ADD:
Accumulator += mem[addr];
if (Accumulator > 255) {
Accumulator -= 256; /* keep accum in bounds 0 to 255: 255+1=0 */
draw_status(STATUS_ERR | STATUS_RUN); /* overflow */
}
break;
case CPU_SUB:
Accumulator -= mem[addr];
if (Accumulator < 0) {
Accumulator += 256; /* keep accum in bounds 0 to 255: 0-1=255 */
draw_status(STATUS_ERR | STATUS_RUN); /* underflow */
}
break;
case CPU_GOTO:
next = addr;
break;
case CPU_IFZERO:
if (Accumulator == 0) {
next = addr;
}
}
Accumulator &= 255; /* keep accum in bounds 0 to 255: 11111111 */
/* update the display */
draw_accum(Accumulator);
tick();
return next;
}
int
run_program(int *mem, int start)
{
int key;
int counter;
draw_status(STATUS_RUN); /* run mode */
/* run the program */
Accumulator = 0;
draw_accum(Accumulator);
counter = start;
do {
counter = run_instruction(mem, counter);
/* do we need to abort? */
if (kbhit()) {
key = getch();
if (key==0) {
/* getch returns zero if extended key .. call getch
again to clear it */
getch();
}
else if (key == 27) { /* ESC key */
draw_status(STATUS_ABT | STATUS_RUN);
tick();
return Accumulator;
}
}
} while (counter >= 0);
tick();
return Accumulator;
}
|
C
|
#include <stdio.h>
#include <string.h>
int main()
{
char string[100];
int R, TOTALWORDS;
TOTALWORDS = 1;
printf("\n PLEASE ENTER A STRING: ");
gets(string);
for (R = 0; string[R] != '\0'; R++)
{
if (string[R] == ' ' || string[R] == '\n' || string[R] == '\t')
{
TOTALWORDS++;
}
}
printf("\n--------------------------------------------------------------------");
printf("\n TOTAL NUMBER OF WORDS IN THE STRING |%s| : %d", string, TOTALWORDS);
printf("\n--------------------------------------------------------------------");
return (0);
}
|
C
|
#include "holberton.h"
#include <stdio.h>
/**
* *string_toupper-Entry point
* @s: is a variable pointer
* @
* @
* Return: Always 0.
*/
char *string_toupper(char *s)
{
int a;
for (a = 0; s[a] != '\0'; a++)
{
if (s[a] >= 'a' && s[a] <= 'z')
{
s[a] = s[a] - 32;
}
}
return (s);
}
|
C
|
//
// main.c
// Assign1A
//
// Created by Greyson Wright on 1/30/18.
// Copyright © 2018 Greyson Wright. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
int main(int argc, const char * argv[]) {
int n = atoi(argv[1]);
if (n < 1) {
printf("Please provide a number greater than 0.\n");
exit(-1);
}
pid_t pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork Failed\n");
} else if (pid == 0) {
while (1) {
if (n == 1) {
printf("%d\n", n);
break;
}
printf("%d, ", n);
if (n % 2 == 0) {
n /= 2;
} else {
n = 3 * n + 1;
}
}
} else if (pid > 0) {
wait(0);
}
return 0;
}
|
C
|
#include <stdint.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include "gamma.h"
#include <stdbool.h>
#include <string.h>
int main() {
/*
scenario: test_random_actions
uuid: 192061291
*/
/*
random actions, total chaos
*/
gamma_t* board = gamma_new(5, 8, 6, 10);
assert( board != NULL );
assert( gamma_move(board, 1, 4, 4) == 1 );
assert( gamma_move(board, 1, 4, 5) == 1 );
assert( gamma_move(board, 2, 2, 2) == 1 );
assert( gamma_move(board, 2, 2, 0) == 1 );
assert( gamma_move(board, 3, 6, 4) == 0 );
assert( gamma_move(board, 3, 0, 5) == 1 );
assert( gamma_move(board, 4, 3, 3) == 1 );
assert( gamma_move(board, 5, 4, 2) == 1 );
assert( gamma_busy_fields(board, 5) == 1 );
assert( gamma_golden_move(board, 5, 5, 4) == 0 );
assert( gamma_move(board, 6, 5, 3) == 0 );
assert( gamma_move(board, 1, 7, 3) == 0 );
assert( gamma_move(board, 1, 3, 0) == 1 );
assert( gamma_move(board, 2, 4, 2) == 0 );
assert( gamma_move(board, 3, 3, 0) == 0 );
assert( gamma_move(board, 3, 2, 1) == 1 );
assert( gamma_move(board, 4, 1, 4) == 1 );
assert( gamma_move(board, 4, 0, 3) == 1 );
assert( gamma_free_fields(board, 4) == 29 );
assert( gamma_move(board, 5, 1, 1) == 1 );
assert( gamma_move(board, 5, 4, 2) == 0 );
assert( gamma_free_fields(board, 5) == 28 );
assert( gamma_move(board, 6, 4, 3) == 1 );
assert( gamma_move(board, 1, 3, 1) == 1 );
assert( gamma_free_fields(board, 1) == 26 );
assert( gamma_move(board, 2, 5, 3) == 0 );
assert( gamma_golden_possible(board, 2) == 1 );
assert( gamma_move(board, 3, 6, 4) == 0 );
assert( gamma_free_fields(board, 3) == 26 );
assert( gamma_move(board, 4, 4, 5) == 0 );
assert( gamma_move(board, 5, 0, 0) == 1 );
assert( gamma_move(board, 5, 3, 5) == 1 );
assert( gamma_move(board, 6, 6, 1) == 0 );
assert( gamma_move(board, 6, 3, 1) == 0 );
assert( gamma_move(board, 1, 3, 1) == 0 );
assert( gamma_move(board, 2, 7, 2) == 0 );
assert( gamma_move(board, 3, 7, 2) == 0 );
assert( gamma_move(board, 4, 4, 3) == 0 );
assert( gamma_move(board, 4, 0, 0) == 0 );
assert( gamma_free_fields(board, 4) == 24 );
assert( gamma_move(board, 5, 3, 2) == 1 );
assert( gamma_golden_possible(board, 6) == 1 );
assert( gamma_move(board, 1, 4, 6) == 1 );
assert( gamma_move(board, 2, 1, 0) == 1 );
assert( gamma_move(board, 2, 1, 7) == 1 );
assert( gamma_move(board, 3, 4, 2) == 0 );
assert( gamma_move(board, 4, 3, 1) == 0 );
assert( gamma_move(board, 5, 3, 2) == 0 );
assert( gamma_move(board, 6, 7, 0) == 0 );
assert( gamma_move(board, 6, 2, 5) == 1 );
assert( gamma_move(board, 1, 5, 1) == 0 );
assert( gamma_move(board, 2, 1, 0) == 0 );
assert( gamma_move(board, 2, 1, 0) == 0 );
assert( gamma_move(board, 3, 4, 0) == 1 );
assert( gamma_golden_possible(board, 3) == 1 );
assert( gamma_move(board, 4, 7, 0) == 0 );
assert( gamma_move(board, 4, 4, 4) == 0 );
assert( gamma_free_fields(board, 4) == 18 );
assert( gamma_golden_possible(board, 4) == 1 );
assert( gamma_move(board, 5, 0, 4) == 1 );
assert( gamma_move(board, 5, 0, 6) == 1 );
assert( gamma_move(board, 6, 6, 3) == 0 );
char* board600924983 = gamma_board(board);
assert( board600924983 != NULL );
assert( strcmp(board600924983,
".2...\n"
"5...1\n"
"3.651\n"
"54..1\n"
"4..46\n"
"..255\n"
".531.\n"
"52213\n") == 0);
free(board600924983);
board600924983 = NULL;
assert( gamma_move(board, 1, 4, 3) == 0 );
assert( gamma_move(board, 3, 1, 4) == 0 );
assert( gamma_busy_fields(board, 3) == 3 );
assert( gamma_move(board, 4, 7, 0) == 0 );
assert( gamma_move(board, 5, 6, 3) == 0 );
assert( gamma_move(board, 6, 4, 3) == 0 );
assert( gamma_move(board, 6, 2, 1) == 0 );
assert( gamma_move(board, 1, 3, 2) == 0 );
assert( gamma_busy_fields(board, 1) == 5 );
assert( gamma_free_fields(board, 2) == 16 );
assert( gamma_move(board, 3, 2, 2) == 0 );
assert( gamma_busy_fields(board, 3) == 3 );
assert( gamma_move(board, 4, 3, 2) == 0 );
assert( gamma_move(board, 5, 1, 3) == 1 );
assert( gamma_move(board, 5, 0, 2) == 1 );
assert( gamma_move(board, 6, 4, 4) == 0 );
assert( gamma_move(board, 1, 6, 2) == 0 );
assert( gamma_busy_fields(board, 1) == 5 );
assert( gamma_move(board, 2, 4, 2) == 0 );
assert( gamma_move(board, 2, 0, 1) == 1 );
assert( gamma_move(board, 3, 4, 2) == 0 );
assert( gamma_move(board, 3, 4, 2) == 0 );
assert( gamma_move(board, 4, 7, 2) == 0 );
assert( gamma_move(board, 5, 7, 0) == 0 );
assert( gamma_move(board, 5, 1, 6) == 1 );
assert( gamma_move(board, 6, 2, 1) == 0 );
assert( gamma_free_fields(board, 6) == 12 );
assert( gamma_move(board, 1, 3, 2) == 0 );
assert( gamma_move(board, 1, 1, 7) == 0 );
assert( gamma_golden_possible(board, 1) == 1 );
assert( gamma_move(board, 2, 4, 7) == 1 );
assert( gamma_move(board, 2, 2, 7) == 1 );
assert( gamma_move(board, 3, 3, 4) == 1 );
assert( gamma_busy_fields(board, 3) == 4 );
assert( gamma_move(board, 4, 6, 2) == 0 );
assert( gamma_busy_fields(board, 4) == 3 );
char* board336866317 = gamma_board(board);
assert( board336866317 != NULL );
assert( strcmp(board336866317,
".22.2\n"
"55..1\n"
"3.651\n"
"54.31\n"
"45.46\n"
"5.255\n"
"2531.\n"
"52213\n") == 0);
free(board336866317);
board336866317 = NULL;
assert( gamma_move(board, 5, 7, 3) == 0 );
assert( gamma_free_fields(board, 5) == 9 );
assert( gamma_move(board, 6, 1, 5) == 1 );
assert( gamma_move(board, 6, 4, 4) == 0 );
assert( gamma_busy_fields(board, 6) == 3 );
char* board350630023 = gamma_board(board);
assert( board350630023 != NULL );
assert( strcmp(board350630023,
".22.2\n"
"55..1\n"
"36651\n"
"54.31\n"
"45.46\n"
"5.255\n"
"2531.\n"
"52213\n") == 0);
free(board350630023);
board350630023 = NULL;
assert( gamma_move(board, 1, 3, 0) == 0 );
assert( gamma_move(board, 2, 1, 4) == 0 );
assert( gamma_busy_fields(board, 2) == 7 );
assert( gamma_move(board, 3, 7, 0) == 0 );
assert( gamma_free_fields(board, 3) == 8 );
assert( gamma_move(board, 4, 6, 3) == 0 );
assert( gamma_move(board, 4, 1, 0) == 0 );
assert( gamma_free_fields(board, 4) == 8 );
assert( gamma_move(board, 5, 4, 2) == 0 );
assert( gamma_move(board, 6, 6, 2) == 0 );
assert( gamma_free_fields(board, 6) == 8 );
assert( gamma_golden_move(board, 6, 7, 4) == 0 );
char* board972693057 = gamma_board(board);
assert( board972693057 != NULL );
assert( strcmp(board972693057,
".22.2\n"
"55..1\n"
"36651\n"
"54.31\n"
"45.46\n"
"5.255\n"
"2531.\n"
"52213\n") == 0);
free(board972693057);
board972693057 = NULL;
assert( gamma_move(board, 1, 0, 4) == 0 );
char* board352430002 = gamma_board(board);
assert( board352430002 != NULL );
assert( strcmp(board352430002,
".22.2\n"
"55..1\n"
"36651\n"
"54.31\n"
"45.46\n"
"5.255\n"
"2531.\n"
"52213\n") == 0);
free(board352430002);
board352430002 = NULL;
assert( gamma_move(board, 2, 7, 0) == 0 );
assert( gamma_move(board, 2, 0, 0) == 0 );
assert( gamma_golden_move(board, 2, 3, 3) == 1 );
assert( gamma_move(board, 3, 4, 1) == 1 );
assert( gamma_move(board, 4, 4, 4) == 0 );
assert( gamma_move(board, 4, 3, 7) == 1 );
assert( gamma_free_fields(board, 4) == 6 );
assert( gamma_move(board, 5, 6, 2) == 0 );
assert( gamma_move(board, 5, 3, 7) == 0 );
assert( gamma_golden_move(board, 5, 5, 1) == 0 );
assert( gamma_move(board, 6, 6, 3) == 0 );
assert( gamma_move(board, 1, 2, 1) == 0 );
assert( gamma_move(board, 1, 1, 3) == 0 );
char* board428377359 = gamma_board(board);
assert( board428377359 != NULL );
assert( strcmp(board428377359,
".2242\n"
"55..1\n"
"36651\n"
"54.31\n"
"45.26\n"
"5.255\n"
"25313\n"
"52213\n") == 0);
free(board428377359);
board428377359 = NULL;
assert( gamma_move(board, 3, 4, 2) == 0 );
assert( gamma_move(board, 3, 4, 1) == 0 );
assert( gamma_busy_fields(board, 3) == 5 );
assert( gamma_move(board, 4, 6, 3) == 0 );
assert( gamma_move(board, 5, 4, 2) == 0 );
assert( gamma_move(board, 6, 1, 4) == 0 );
assert( gamma_busy_fields(board, 6) == 3 );
assert( gamma_move(board, 1, 3, 2) == 0 );
assert( gamma_move(board, 2, 6, 3) == 0 );
gamma_delete(board);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include "induction.h"
#include "timeutil.h"
int i_time_check_past (struct timeval *now, struct timeval *control) /* Is now past then... if so, then a 1 is returned */
{
if (now->tv_sec > control->tv_sec) return 1; /* Control time has been past by seconds */
if (now->tv_sec < control->tv_sec) return 0; /* Control time hasnt been reached yet */
/* At this point now->tv_sec and control->tv_sec must be equal */
if (now->tv_usec > control->tv_usec) return 1; /* Control time has been past by useconds */
if (now->tv_usec < control->tv_usec) return 0; /* Control time hasnt been reached yet */
return 0; /* Dead heat. Who'da thought! */
}
int i_time_diff_seconds (struct timeval *now, struct timeval *then) /* Return the seconds different between the two timevals */
{
return (now->tv_sec - then->tv_sec);
}
int i_time_subtract (struct timeval *pass_x, struct timeval *pass_y, struct timeval *result)
{
/* Subtract Y from X, place the result in result
*
* Returns 0 where result is positive
* Return 1 where result is negative
*/
struct timeval x;
struct timeval y;
/* Work off local copies of X and Y to ensure this
* function doesnt alter the passed structs
*/
x.tv_sec = pass_x->tv_sec;
x.tv_usec = pass_x->tv_usec;
y.tv_sec = pass_y->tv_sec;
y.tv_usec = pass_y->tv_usec;
/* Perform the carry for the later subtraction by updating y. */
if (x.tv_usec < y.tv_usec)
{
int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
y.tv_usec -= 1000000 * nsec;
y.tv_sec += nsec;
}
if (x.tv_usec - y.tv_usec > 1000000)
{
int nsec = (x.tv_usec - y.tv_usec) / 1000000;
y.tv_usec += 1000000 * nsec;
y.tv_sec -= nsec;
}
/* Compute the time remaining to wait. tv_usec is certainly positive. */
result->tv_sec = x.tv_sec - y.tv_sec;
result->tv_usec = x.tv_usec - y.tv_usec;
/* Return 1 if result is negative. */
return x.tv_sec < y.tv_sec;
}
time_t i_time_weekof (time_t ref_sec, struct tm *tm)
{
time_t daystart_sec;
time_t weekstart_sec;
struct tm daystart_tm;
/* Calculates the 'week of'
* i.e the first before Monday beforethe current time.
*
* This is used to keep track of 'week' graphs
*/
/* Get the time for the start of the day specified by ref_sec */
daystart_sec = i_time_daystart (ref_sec, &daystart_tm);
/* Move to the start of the week (Monday)*/
if (daystart_tm.tm_wday != 0)
{
/* Monday - Saturday */
weekstart_sec = daystart_sec - ((daystart_tm.tm_wday - 1) * (60 * 60 * 24));
}
else
{
/* Sunday */
weekstart_sec = daystart_sec - (6 * (60 * 60 * 24));
}
/* Store week_start seconds in passed tm struct */
localtime_r (&weekstart_sec, tm);
return weekstart_sec;
}
time_t i_time_monthend (time_t ref_sec, struct tm *tm)
{
time_t month_end;
struct tm ref_tm;
/* Find where ref_sec is */
localtime_r (&ref_sec, &ref_tm); /* Get the time struct for the ref_sec */
/* Move to the next month */
if (ref_tm.tm_mon == 11)
{ ref_tm.tm_year++; ref_tm.tm_mon = 0; } /* Go to next month (first month in the next year) */
else
{ ref_tm.tm_mon++; } /* Go to next month */
/* Move to the first second of the next month */
ref_tm.tm_mday = 1; /* Go to the first day of this month */
ref_tm.tm_hour = 0; /* Go to the first hour of this day */
ref_tm.tm_min = 0; /* Go to the first min of this day */
ref_tm.tm_sec = 0; /* Go to the first sec of this day */
ref_tm.tm_isdst = -1; /* Auto-Calc DST */
/* Move back on second */
month_end = mktime (&ref_tm); /* Get the seconds for the first second in the first day of the next month */
month_end--; /* Go back one second, hence the last second, of the last day of the month */
localtime_r (&month_end, tm); /* Set value of tm pointer passed to this func */
/* Finished */
return month_end;
}
time_t i_time_monthstart (time_t ref_sec, struct tm *tm)
{
time_t month_start;
struct tm ref_tm;
/* Find where ref_sec is */
localtime_r (&ref_sec, &ref_tm); /* Get the time struct for the ref_sec */
/* Move to the first second of the month */
ref_tm.tm_mday = 1; /* Go to the first day of this month */
ref_tm.tm_hour = 0; /* Go to the first hour of this day */
ref_tm.tm_min = 0; /* Go to the first min of this day */
ref_tm.tm_sec = 0; /* Go to the first sec of this day */
ref_tm.tm_isdst = -1; /* Auto-Calc DST */
month_start = mktime (&ref_tm); /* Get the seconds for the first second in the first day of the next month */
localtime_r (&month_start, tm); /* Set value of tm pointer passed to this func */
/* Finished */
return month_start;
}
time_t i_time_daystart (time_t now, struct tm *tm)
{
time_t day_start;
struct tm nowtm;
localtime_r (&now, &nowtm);
nowtm.tm_sec = 0;
nowtm.tm_min = 0;
nowtm.tm_hour = 0;
day_start = mktime (&nowtm);
localtime_r (&day_start, tm);
return day_start;
}
time_t i_time_yearstart (time_t now, struct tm *tm)
{
time_t year_start;
struct tm nowtm;
localtime_r (&now, &nowtm);
nowtm.tm_sec = 0;
nowtm.tm_min = 0;
nowtm.tm_hour = 0;
nowtm.tm_mon = 0;
nowtm.tm_mday = 1;
nowtm.tm_isdst = -1;
year_start = mktime (&nowtm);
localtime_r (&year_start, tm);
return year_start;
}
time_t i_time_yearend (time_t now, struct tm *tm)
{
time_t year_end;
struct tm nowtm;
localtime_r (&now, &nowtm);
nowtm.tm_sec = 0;
nowtm.tm_min = 0;
nowtm.tm_hour = 0;
nowtm.tm_mon = 0;
nowtm.tm_mday = 1;
nowtm.tm_yday = 0;
nowtm.tm_year++;
nowtm.tm_isdst = -1;
year_end = mktime (&nowtm);
year_end--;
localtime_r (&year_end, tm);
return year_end;
}
char* i_time_month_string (int tm_mon)
{
switch (tm_mon)
{
case 0: return "January";
case 1: return "February";
case 2: return "March";
case 3: return "April";
case 4: return "May";
case 5: return "June";
case 6: return "July";
case 7: return "August";
case 8: return "September";
case 9: return "October";
case 10: return "November";
case 11: return "December";
}
return "Unknown";
}
char* i_time_interval_str (struct timeval *ref_tv)
{
/* Returns a string suitable to display the interval
* given in seconds. E.g 00:00:13, 1d4h45m, 2w3d5h
*/
int days;
int hours;
int minutes;
int seconds;
int centiseconds;
time_t ref_sec;
time_t ref_usec;
char *str;
ref_sec = ref_tv->tv_sec;
ref_usec = ref_tv->tv_usec;
days = ref_sec / (60 * 60 * 24);
ref_sec %= (60 * 60 * 24);
hours = ref_sec / (60 * 60);
ref_sec %= (60 * 60);
minutes = ref_sec / 60;
seconds = ref_sec % 60;
centiseconds = ref_usec / 10000;
if (days < 1)
{
asprintf (&str, "%ih %im %is", hours, minutes, seconds);
}
else
{
asprintf (&str, "%id %ih %im", days, hours, minutes);
}
return str;
}
char* i_time_ctime (time_t ref_sec)
{
int rtn_strlen;
char *ctime_str;
char *rtn_str;
ctime_str = ctime (&ref_sec);
if (!ctime_str) return NULL;
rtn_str = strdup (ctime_str);
rtn_strlen = strlen (rtn_str);
rtn_str[rtn_strlen-1] = '\0'; /* Overwrite the \n */
return rtn_str;
}
|
C
|
#include "csapp.h"
#include <sys/ipc.h>
#include <sys/shm.h>
#define ARRAY_SIZE 40000
#define MALLOC_SIZE 100000
#define SHM_SIZE 100000
#define SHM_MODE (SHM_R |SHM_W) /*user read/ write*/
char array[ARRAY_SIZE]; /*uninitialized data = bss*/
static int a[10] = {0};
int main(int argc, char *argv[])
{
int shmid;
char *ptr, *shmptr;
printf("a from %x to %x \n", &a[0], &a[9]);
printf("array[] from %x to %x \n", &array[0], &array[ARRAY_SIZE]);
printf("stack around %x \n", &shmid);
ptr = Malloc(MALLOC_SIZE);
printf("malloc from %x to %x\n", ptr, ptr + MALLOC_SIZE);
if((shmid = shmget(IPC_PRIVATE, SHM_SIZE, SHM_MODE)) < 0)
unix_error("shmat error");
if ((shmptr = shmat(shmid, 0, 0)) == (void*)-1)
unix_error("shmat error");
printf("shared memorr attached from %x to %x\n", shmptr, shmptr + SHM_SIZE);
if(shmctl(shmid, IPC_RMID, 0) < 0)
unix_error("shmctl error");
return 0;
}
|
C
|
// Program to print the greatest common divisor using Euclid's algorithm
#include<stdio.h>
int gcd(int, int);
int main()
{
int j, k;
printf("Enter two no.s : ");
scanf("%d%d",&j,&k);
printf("Greatest common divisor is: %d",gcd(j,k));
return 0;
}
int gcd(int a, int b)
{
int r, res;
while(res!=0)
{
r = a/b;
res = a - (r*b);
a = b;
b = res;
}
return (a);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
long long expo(int x, int n)
{
if(n==0)
{
return 1;
}
return x*expo(x,n-1);
}
long long expo2(int x , int n)
{
if(n==0)
return 1;
else if(n%2 == 0)
{
long long y = expo2(x,n/2);
return y*y;
}
else
{
long long z = x*expo2(x,n-1);
return z;
}
}
int main()
{
int x,n;
long long result;
printf("Enter a number and it's power \n");
scanf("%d %d",&x,&n);
printf("\nThe expo. is %lld\nSecond method - %lld\n",expo(x,n),expo2(x,n));
}
|
C
|
#include <stdio.h>
#include <math.h>
int main()
{
double a,b,c,d,e,f,r1,r2,rr,ir;
printf("enter the cofficient of the equation \n");
scanf("%lf%lf%lf", &a,&b,&c);
d=b*b-4*a*c ;
if(d == 0)
{
r1=r2= -b/2*a;
printf("roots are equal r1=r2 %lf\n", r1);
}
else if(d>0)
{
e=sqrt(d);
r1=(-b+e)/2*a ;
r2=(-b-e)/2*a ;
printf("roots are real r1=%lf, r2=%lf\n", r1 , r2);
}
else
{
f=sqrt(-d);
rr=(-b/2*a);
ir=(f/2*a);
printf("roots are complex r1=%lf+i%lf , r2=%lf+i%lf \n", rr,ir,rr,ir);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
main()
{
char str[10],str2[10];
int i;
printf("enter some string");
scanf("%s",str);
for(i=0;str[i]!='\0';i++)
{
str2[i]=str[i];
}
str2[i]='\0';
strrev(str);
if(strcmp(str,str2)==0)
printf("string is palindrome");
}
|
C
|
#include <stdio.h>
char busca_binaria(int* vetor, int key, int size){
int inicio = 0;
int fim = size - 1;
int meio = 0;
while (inicio <= fim){
meio = (fim - inicio) / 2 + inicio;
if (vetor[meio] == key)
break;
else if (vetor[meio] < key)
inicio = ++meio;
else
fim = --meio;
meio++;
}
return meio;
}
int main(){
int v[] = {0, 2, 3, 4, 6, 7};
int k = busca_binaria(v, -1, 6);
printf("%d\n", k);
}
|
C
|
// this is a small independent file (not part of the libccc test suite)
#include <libccc_string.h>
#include <libccc_list.h>
#include <libccc_io.h>
#include <stdio.h>
#define COUNT 8
int main()
{
static char* lines[COUNT] =
{
"Yo my boi",
"What's up dog",
"Not much, you ?",
"...",
"Yo spit it out",
"What's the deal ?",
"You got the dope ?",
"I ask the questions.",
};
// s_array
{
s_array* str_array = &(s_array)
{
.item_count = COUNT,
.item_size = sizeof(char*),
.items = lines,
};
foreach (char*, str, s_array, str_array)
{
IO_Output_Format("i:%zu,ptr:%p,\tstr:%p -> \"%s\"\n", str_i, str_ptr, str, str);
}
}
// s_list
{
s_list* str_list = NULL;
for (int i = 0; i < COUNT; ++i)
{
List_Append(&str_list, List_New(lines[i], lines[i] ? String_Length(lines[i]) : 0));
}
foreach (char*, str, s_list, str_list)
{
IO_Output_Format("i:%zu,lst:%p, size: %llu,\tstr:%p -> \"%s\"\n", str_i, str_lst, str_lst->item_size, str, str);
}
}
return (OK);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
int Answer;
int partition( int a[], int l, int r) {
int pivot, i, j, t;
pivot = a[l];
i = l; j = r+1;
while( 1)
{
do ++i; while( a[i] <= pivot && i <= r );
do --j; while( a[j] > pivot );
if( i >= j ) break;
t = a[i]; a[i] = a[j]; a[j] = t;
}
t = a[l]; a[l] = a[j]; a[j] = t;
return j;
}
void quickSort( int a[], int l, int r)
{
int j;
if( l < r )
{
// divide and conquer
j = partition( a, l, r);
quickSort( a, l, j-1);
quickSort( a, j+1, r);
}
}
int main(void)
{
int T, test_case;
/*
The freopen function below opens input.txt file in read only mode, and afterward,
the program will read from input.txt file instead of standard(keyboard) input.
To test your program, you may save input data in input.txt file,
and use freopen function to read from the file when using scanf function.
You may remove the comment symbols(//) in the below statement and use it.
But before submission, you must remove the freopen function or rewrite comment symbols(//).
*/
// freopen("input.txt", "r", stdin);
/*
If you remove the statement below, your program's output may not be rocorded
when your program is terminated after the time limit.
For safety, please use setbuf(stdout, NULL); statement.
*/
setbuf(stdout, NULL);
scanf("%d", &T);
getchar();
for(test_case = 0; test_case < T; test_case++)
{
int subject_num=0;
int select_num=0;
int* arr;
scanf("%d %d",&subject_num, &select_num);
getchar();
arr = (int*)malloc(sizeof(int)*subject_num);
for(int i=0; i<subject_num; i++){
scanf("%d",&arr[i]);
getchar();
}
quickSort(arr,0,subject_num-1);
int max=0;
for(int i=0; i<select_num; i++){
max += arr[subject_num-1-i];
}
Answer=max;
printf("Case #%d\n", test_case+1);
printf("%d\n", Answer);
}
return 0;//Your program should return 0 on normal termination.
}
|
C
|
// The skill room of the adventurer's guild.
//
// DarkeLIB 0.1
// -Diewarzau 5/7/96
#include <std.h>
#define DEFAULT_SCREEN_SIZE 75
#define EXCLUDE ({ "control_change.c", "long_term.c", "skill.c", "lore_skill.c" })
inherit ROOM;
int calc_skill_inc(object who, string skill);
int dev_cost(object who, string skill);
int filter_skill(string file, mixed *info);
int skill_filter(string skill, int i);
void create() {
::create();
set_property("indoors", 1);
set_property("no attack", 1);
set_property("no magic", 1);
set_property("light", 2);
set("short", "The Adventurer's Guild Skill Room");
set("long",
"This room is absolutely immense and divided into several sections. "
"A gymnasium takes a large portion, and several students engage in "
"trials of combat and dexterity there. In the distance, separated "
"from the rest of the room by wooden partitions, are study areas, "
"where robed individuals study great tomes which have been donated "
"by the various guilds.\n"
"\n"
" Type 'help list' for information on listing skills.\n"
" Type 'train <skill>' to train a skill.\n");
add_exit("/d/damned/akkad/adv_guild_sp", "west");
add_exit("/d/damned/akkad/adv_guild_entrance", "north");
}
void init() {
::init();
add_action("train_skill", "train");
add_action("list_skills", "list");
add_action("help_list", "help");
return;
}
int help_list(string str) {
string tmp;
int lines;
if(str != "list") return 0;
tmp =
"Since there are so many skills in DarkeMUD, you must pick "
"certain criterea upon which to list skills. You may list skills "
"by level, by letter of the alphabet, by guild, or by any combination "
"of these. You do this by typing 'list skills' with any number "
"of flags after it. All flags must be preceeded by a dash, and must "
"be separated by a space.\n\n"
"-l:<level> List skills by level. All skills in the mud of\n"
"-l:<level-range> that level or level-range will be listed.\n"
" Ex: 'list skills -l:8' (all 8th level skills)\n"
" 'list skills -l:4-10 (all skills 4-10)\n"
"\n"
"-a:<letter> List skills by letter of alphabet.\n"
"-a:<letter-range> Ex: 'list skills -a:s (all skills beginning\n"
" with 's'.\n"
" 'list skills -a:b-d (all skills b thru d)\n"
"\n"
"-g:<guild-name> List all skills in a certain guild.\n"
" Ex: 'list skills -g:fighter'\n"
"\n"
"Put it all together:\n"
" 'list skills -a:s-z -l:1-5 -g:nightblade'\n"
"The above would return all skills beginning in the letters s "
"through z, from level 1-5, in the nightblade guild.\n"
"\n"
"Note that you may only cross-train at your level MINUS 5, then "
"divided by 2 (x-train at level 10 when at level 25 for example). "
"Therefore spells listed are only up to (your lev-5) / 2. "
"If you are level 10 or lower, you may not cross train at "
"all. If you supply more than one flag of a given type, "
"only the first will be used.\n"
"NOTE: traning costs 30 mithril times the level of the spell";
lines = DEFAULT_SCREEN_SIZE;
if(this_player()->getenv("SCREEN"))
lines = (int)this_player()->getenv("SCREEN");
this_player()->more(explode(wrap(tmp, lines), "\n"));
return 1;
}
int filter_skill(string file, mixed *info) {
int lev;
string skill;
if(sizeof(info) != 2) return 0;
skill = replace_string(file, "_", " ");
file = "/std/skills/"+file;
if(!file_exists(file+".c")) return 0;
lev = (int)file->query_dev() + (int)file->query_fast_dev()/2;
lev /= 4;
if(lev < 1) lev = 1;
if(intp(info[0]) && info[0] && lev != info[0]) return 0;
else if(pointerp(info[0]) && sizeof(info[0]) == 2) {
if(lev < info[0][0] || lev > info[0][1]) return 0;
}
if(stringp(info[1]) && strlen(skill) &&
skill[0..0] != info[1]) return 0;
else if(strlen(skill) && pointerp(info[1]) && sizeof(info[1]) == 2) {
if(strcmp(skill[0..0], info[1][0]) < 0 ||
strcmp(skill[0..0], info[1][1]) > 0) return 0;
}
return 1;
}
int train_skill(string str) {
int cost, my_dev, my_lev, sk_lev, mith;
string file, *sp;
if(!str) return 0;
my_dev = (int)this_player()->query_property("dev points");
my_lev = (int)this_player()->query_level();
str = lower_case(str);
sp = (string *)this_player()->query_property("sp skills");
if(!str) return 0;
if(!sp || member_array(str, sp) < 0) {
write("You may not train in a skill you have not 'specialize'-ed.\n"
"See 'help specialize'.");
return 1;
}
if((int)this_player()->query_base_skill(str) >= 75) {
write("You may not cross-train a skill past 75% base.");
return 1;
}
file = "/std/skills/"+replace_string(str, " ", "_");
if(!file_exists(file+".c") ||
member_array(replace_string(str, " ", "_")+".c",
EXCLUDE) >= 0) {
write("There is no such skill.");
return 1;
}
mith = ((int)file->query_dev() + (int)file->query_fast_dev()/2)/4;
mith *= 30;
if((int)this_player()->query_money("mithril") < mith) {
write(sprintf("You need %d mithril to train that skill.", mith));
return 1;
}
this_player()->add_money("mithril", -1*mith);
cost = dev_cost(this_player(), str);
if(cost > my_dev) {
write("You need "+cost+" development points to train that skill.\n"+
"You only have "+my_dev+".");
return 1;
}
this_player()->add_dev(-1 * cost);
this_player()->set_skill(str, (int)this_player()->query_base_skill(str) +
calc_skill_inc(this_player(), str));
this_player()->set_last_dev(str, my_lev);
write("You now have "+str+" at "+(int)this_player()->query_skill(str)+"%");
write("It will cost you "+dev_cost(this_player(), str)+
" development points to advance this skill further.");
write("You have "+sprintf("%d", (my_dev - cost)) +
" development points left.");
return 1;
}
/* Zortek: 031996 Rewrote list_skills to eliminate the
* need for file creation and removal via call_out.
*/
int list_skills(string str) {
int i, j, lev, skil, k;
string *tmpv, *foo, *list, col, tmp1, tmp2, guild;
mixed *info;
if(!str) return notify_fail("See 'help list'.\n");
foo = explode(str, " ");
if(!sizeof(foo)) return notify_fail("See 'help list'.\n");
if(sizeof(foo) == 1 && foo[0] == "skills") {
write("You must supply one or more flags. See 'help list'\n");
return 1;
}
lev = this_player()->query_level();
if(lev < 11) {
write("You must be at least level 11 to train "+
"outside of your guild.");
return 1;
}
lev = (lev-5)/2;
if(foo[0] != "skills") return notify_fail("See 'help list'.\n");
i = sizeof(foo);
info = allocate(2);
while(i--) {
if(strlen(foo[i]) < 4 || foo[i][0] != '-')
continue;
skil = strlen(foo[i])-1;
switch(foo[i][0..2]) {
case "-l:":
if(sscanf(foo[i][3..skil], "%d-%d", j, k) == 2) {
if(j > k || j < 1 || k < 1) {
write("Invalid level range.");
return 1;
}
if(k > lev) {
write("You can only view skills up to level "+
sprintf("%d.", lev));
return 1;
}
info[0] = ({ j, k });
}
else if(sscanf(foo[i][3..skil], "%d", j)) {
if(j < 1) {
write("Invalid level after -l:");
return 1;
}
if(j > lev) {
write("You can only view skills up to level "+
sprintf("%d.", lev));
return 1;
}
info[0] = j;
}
else {
write("Invalid -l flag. See 'help list'.");
return 1;
}
break;
case "-a:":
if(sscanf(foo[i][3..skil], "%s-%s", tmp1, tmp2) == 2) {
tmp1 = lower_case(tmp1);
tmp2 = lower_case(tmp2);
if(strlen(tmp1) > 1 || strlen(tmp2) > 1 ||
strcmp("a", tmp1) > 0 || strcmp("a", tmp2) > 0 ||
strcmp("z", tmp1) < 0 || strcmp("z", tmp2) < 0 ||
strcmp(tmp1, tmp2) > 0) {
write("Invalid alphabetical range.");
return 1;
}
info[1] = ({ tmp1, tmp2 });
}
else if(strlen(foo[i]) == 4) {
tmp1 = lower_case(foo[i][3..3]);
if(strcmp("a", tmp1) > 0 || strcmp("z", tmp1) < 0) {
write("Invalid alphabetical flag.");
return 1;
}
info[1] = tmp1;
}
else {
write("Invalid -a flag. See 'help list'.");
return 1;
}
break;
case "-g:":
guild = foo[i][3..skil];
break;
}
}
if(!info[0]) info[0] = ({ 1, 100 });
if(guild) {
guild = lower_case(replace_string(guild, " ", "-"));
tmpv = filter_array(get_dir("/d/damned/guilds/*"),
(: (file_size($2 + $1) == -2) :), "/d/damned/guilds/");
if(member_array(guild, tmpv) < 0) {
write("Guild: '"+guild+"' not found.");
return 1;
}
tmpv = filter_array(map_array(get_dir("/d/damned/guilds/"+guild+"/*.c"),
(: ($2 + replace_string($1, $3, $4)) :), "/d/damned/guilds/"+guild+"/",
".c", ""),
(: call_other :), "is_skill_room");
if(!tmpv || !sizeof(tmpv)) {
write("No skills found in that guild.");
return 1;
}
list = ({});
i = sizeof(tmpv);
while(i--) list +=
(string *)call_other(tmpv[i],
"query_all_skills");
list = map_array(list, (: replace_string :),
" ", "_");
}
else {
list = filter_array(get_dir("/std/skills/*.c"),
(: (member_array($1, $2) < 0) :), EXCLUDE);
list = map_array(list, (: replace_string :),
".c", "");
}
list = filter_array(list, (: filter_skill :), info);
list = map_array(list, (: replace_string :),
"_", " ");
if(!sizeof(list)) {
write("No matching skills found.");
return 1;
}
foo = ({"%^BOLD%^-=-=-=-=-=-=-=-=-=-= %^BLUE%^Skill Listing%^RESET%^BOLD%^ =-=-=-=-=-=-=-=-=-=-%^RESET%^"});
if(pointerp(info) && intp(info[0]) && info[0] < lev)
lev = info[0];
else if(pointerp(info) && pointerp(info[0]) &&
info[0][1] < lev)
lev = info[0][1];
for(i=1;i <= lev; i++) {
tmpv = filter_array(list, (: skill_filter :), i);
if(!tmpv || !sizeof(tmpv)) continue;
j = sizeof(tmpv);
foo += ({"%^BLUE%^Level "+sprintf("%2d",i)+" ------------------- Cost to Increase ---- Rating%^RESET%^"});
while(j--) {
skil = dev_cost(this_player(), tmpv[j]);
col = "%^BOLD%^GREEN%^";
if(skil > this_player()->query_property("dev points") ) col = "%^RED%^";
foo += ({ sprintf(" %-25s %s%-6d%%^RESET%%^ %6d%% %9d%%",
tmpv[j],
col,
skil,
calc_skill_inc(this_player(), tmpv[j]),
(int)this_player()->query_skill(tmpv[j])) });
}
}
foo += ({"%^BOLD%^-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-%^RESET%^"});
this_player()->more(foo);
return 1;
}
void delete_file(string file) {
seteuid(getuid());
rm(file);
return;
}
int skill_filter(string skill, int lev) {
string file;
int my_lev;
file = "/std/skills/"+replace_string(skill, " ", "_");
if(!file_exists(file+".c")) return 0;
my_lev = ((int)file->query_dev() + (int)file->query_fast_dev() / 2) / 4;
if(my_lev < 1) my_lev = 1;
if(lev == my_lev) return 1;
return 0;
}
int dev_cost(object who, string skill) {
string file;
int times, mult;
if(!who || !who->is_player()) return 0;
if(!skill) return 0;
mult = 4;
file = "/std/skills/"+replace_string(skill, " ", "_")+".c";
if(!file_exists(file)) return 0;
file = replace_string(file, ".c", "");
times = (int)who->query_dev_times(skill, (int)who->query_level());
if(!times) return (mult * (int)file->query_dev());
else return (mult * times * (int)file->query_fast_dev());
}
int calc_skill_inc(object who, string skill) {
int base;
if(!who || !skill) return 0;
base = (int)who->query_base_skill(skill);
switch(base) {
case 0..25:
return 5;
case 26..40:
return 3;
case 41..59:
return 2;
case 60..10000:
return 1;
}
return 1;
}
|
C
|
#include <stdio.h>
int main()
{
int max,m,n;
printf("Please input m and n:");
scanf("%d,%d",&m, &n);
if (0 >= m || 0 >= n) {
max = 0;
}
max = m % n;
while (max > 0) {
m = n;
n = max;
max = m % n;
}
printf("%d\r\n", n);
}
|
C
|
//Hanna Rakhsha
//CS 4328 - Xiao Chen
//Due Date: 09/19/2019
//This program creates a child TO parent pipeline. The child executes ./pre
//and the parent executes ./sort.
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
int main(int argc, const char * argv[]){
int p[2];
int pid;
if (pipe(p) == -1)
{
perror("pipe call");
exit(1);
}
pid = fork();
if (pid < 0)
{
fprintf(stderr, "Fork failed");
exit(-1);
}
else if (pid == 0)
{
close(p[1]);
dup(p[1]);
close(p[0]);
close(p[1]);
execvp("./pre", NULL);
}
else
{
wait(NULL);
close(p[0]);
dup(p[0]);
close(p[0]);
close(p[1]);
execvp("./sort", NULL);
exit(0);
}
return 0;
}
|
C
|
#include<pthread.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
pthread_mutex_t *mtx1,*mtx2;
void *thread_fn1(void *arg)
{
printf("\n locking mutex1\n",__func__);
pthread_mutex_lock(mtx1);
printf("\n mutex1 is locked\n",__func__);
sleep(2);
pthread_yield();
printf("\n locking mutex2\n",__func__);
pthread_mutex_lock(mtx2);
printf("\n mutex 2 locked\n",__func__);
printf("\n mutex 2 unlocked\n",__func__);
pthread_mutex_unlock(mtx2);
printf("\n mutex 1 unlocked\n",__func__);
pthread_mutex_unlock(mtx1);
return NULL;
}
void *thread_fn2(void *arg)
{
sleep(3);
printf("\n locking mutex2\n",__func__);
pthread_mutex_lock(mtx2);
printf("\n mutex2 locked\n");
sleep(2);
pthread_yield();
printf("\n locking mutex1\n",__func__);
pthread_mutex_lock(mtx1);
printf("\n mutex1 is locked\n");
printf("\n unlocking mutex1\n",__func__);
pthread_mutex_unlock(mtx1);
printf("\n unlocking mutex 2\n",__func__);
pthread_mutex_unlock(mtx2);
return NULL;
}
int main()
{
pthread_t t1,t2;
int ret;
int loops=1000000;
mtx1=malloc(sizeof(pthread_mutex_t));
mtx2=malloc(sizeof(pthread_mutex_t));
ret=pthread_create(&t1, NULL,thread_fn1,&loops);
if(ret!=0)
{
perror("pthread\n");
}
ret=pthread_create(&t2,NULL,thread_fn2,&loops);
if(ret!=0)
{
perror("pthread");
}
ret=pthread_join(t1,NULL);
ret=pthread_join(t2,NULL);
return 0;
}
|
C
|
/* Enter your solutions in this file */
#include <stdio.h>
#include <math.h>
int max(int [], int);
int min(int [], int);
float average(int [], int);
int mode(int [], int);
int factors(int, int []);
int max(int a[],int x)
{
int maxi=a[0];
for(int i=0;i<x;i++)
{
if(a[i]>maxi)
maxi=a[i];
}
return maxi;
}
int min(int a[],int x)
{
int mini=a[0];
for(int i=0;i<x;i++)
{
if(a[i]<mini)
mini=a[i];
}
return mini;
}
float average(int a[],int x)
{
int sum=0;
for(int i=0;i<x;i++)
{
sum=sum+a[i];
}
float avg=(float) sum/x;
return avg;
}
int mode(int a[],int x)
{
int b[x];
for(int i=0;i<x;i++)
{
int count=0;
for(int j=0;j<x;j++)
{
if(a[i]==a[j])
count++;
}
b[i]=count;
}
int maxi=a[0],flag=b[0];
for(int i=0;i<x;i++)
{
if(b[i]>flag)
maxi=a[i];
}
return maxi;
}
int factors(int n , int a[])
{
int count=0;
for(int i=0;i<100;i++)
{
while (n%2 == 0)
{
a[i]=2;
count++;
i=i+1;
n = n/2;
}
for (int j = 3; j<=sqrt(n); j=j+2)
{
while (n%j == 0)
{
a[i]=j;
count++;
i++;
n = n/j;
}
}
if (n > 2)
{
a[i]=n;
count++;
break;
}
}
return count;
}
|
C
|
#ifndef _UTIL_MEM_CACHE_H_
#define _UTIL_MEM_CACHE_H_
#define MD5_LEN 16
#include <stdlib.h>
typedef void(*fn_free_cache)(const void*);
enum cache_stat
{
EN_STAT_NORMAL,
EN_STAT_TRANSF,
};
typedef struct block_t
{
unsigned char md5[MD5_LEN];
size_t key_len;
const void* value;
fn_free_cache free_fn;
block_t* next_block;
block_t* prev_block;
void* bucket;
}block_t;
typedef struct
{
unsigned char md5[MD5_LEN];
unsigned hash;
const void* key;
size_t key_len;
const void* value;
fn_free_cache free_fn;
}cache_param_t;
typedef struct
{
block_t* bucket;
size_t num_block;
void* _cache;
}bucket_t;
typedef struct
{
bucket_t* buckets;
size_t num_bucket;
size_t clear_index;
size_t num_items;
}_cache_t;
typedef struct
{
_cache_t* cur_cache;
_cache_t* next_cache;
block_t* free_block;
block_t* alloc_blocks;
cache_stat stat;
size_t num_items;
}cache_t;
cache_t* util_create_cache();
void util_destroy_cache(cache_t** ppcache);
int util_set_item(cache_t* cache, const void* key, size_t key_len, const void* value, fn_free_cache free_fn);
const void* util_get_item(cache_t* cache, const void* key, size_t key_len);
int util_del_item(cache_t* cache, const void* key, size_t key_len);
#endif //_UTIL_MEM_CACHE_H_
|
C
|
#include<stdio.h>
int main()
{
char n, m;
printf("Enter a letter: \n");
scanf("%c",&n);
m = 'z' -(n - 'a');
printf("\n%c \n", m);
}
|
C
|
#include "raylib.h"
int partition(int *arr, int start, int end, int *states){
for(int i = start; i < end; i++){
states[i] = 0;
}
int newStart = start;
int pivot = arr[end];
states[start] = 0;
for (int i = start; i < end; i++){
if (pivot > arr[i]){
int temp = arr[newStart];
arr[newStart] = arr[i];
arr[i] = temp;
states[newStart] = 1;
newStart += 1;
states[newStart] = 0;
}
}
int temp = arr[newStart];
arr[newStart] = arr[end];
arr[end] = temp;
return newStart;
}
int main(void)
{
// Initialization
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "Quick Sort");
SetTargetFPS(60); // Set the application to run at 60 frames-per-second
//Width of the bars
int n = 4;
//Number of bars
const int w = 200;
//Array of bars and their state
int h_arr[w], states[w];
//Setting the height of bars
for (int i = 0; i < w ; i++){
h_arr[i] = GetRandomValue(10, 440);
states[i] = 1;
}
int counter = 0, flag= 0;
int end = w - 1;
int start = 0;
int size = end - start + 1;
int stack[size];
int top = 0;
stack[top] = 0;
top += 1;
stack[top] = end;
int j = 0;
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Update
//----------------------------------------------------------------------------------
// TODO: Update your variables here
//----------------------------------------------------------------------------------
if (top >= 0){
end = stack[top];
top -= 1;
start = stack[top];
top -= 1;
int p = partition(h_arr, start, end, states);
states[p] = 1;
if (p-1 > start){
top += 1;
stack[top] = start;
top += 1;
stack[top] = p - 1;
}
if (p+1 < end){
top += 1;
stack[top] = p+1;
top += 1;
stack[top] = end;
}
}else {
if (j < w){
states[j] = 2;
j+=1;
}else{
flag= 1;
}
}
// Draw
//----------------------------------------------------------------------------------
Color color = WHITE;
BeginDrawing();
ClearBackground(BLACK);
for (int i = 0; i < w; i++){
if (states[i] == 0){
color = RED;
}else if (states[i] == 2){
color = GREEN;
}else {
color = WHITE;
}
DrawRectangle(i*n, screenHeight - h_arr[i], n, h_arr[i], color);
}
if (flag == 1){
DrawText("Done", screenWidth/2 - 60, screenHeight/2, 50, RED);
}
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
|
C
|
/*Iterative method for Binary searching an sorted array*/
#include <stdio.h>
int search(int A[],int b,int n){
int mid;
int high=n-1,low=0;
int result=-1;
while(low<=high){
mid=(low+high)/2;
if(low>high){
return -1;
}
else if(b==A[mid]){
return mid+1;
}
else if(b<A[mid]){
high=mid-1;
}
else{
low=mid+1;
}
}
return -1;
}
int main(){
int A[]={1,2,3,4,5,33,42,43,45,56,98};
int b;
printf("What no to search:");
scanf("%d",&b);
printf("Index:%d\nNumber:%d\n",search(A,b,11),b);
}
|
C
|
/*
[Title] Subrectangle Queries
[Level] Medium
[Acceptance] 90.3%
[DATE] June. 22. 2020
[TIME] 4:00PM ~ 5:00PM (1h)
[Reference Site] LeetCode.com
[Questions]
Implement the class SubrectangleQueries which receives a rows x cols rectangle as a matrix of integers in the constructor and supports two methods:
1. updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)
Updates all values with newValue in the subrectangle whose upper left coordinate is (row1,col1) and bottom right coordinate is (row2,col2).
2. getValue(int row, int col)
Returns the current value of the coordinate (row,col) from the rectangle.
[Example Output & Input]
(Example 1)
- Input
["SubrectangleQueries","getValue","updateSubrectangle","getValue","getValue","updateSubrectangle","getValue","getValue"]
[[[[1,2,1],[4,3,4],[3,2,1],[1,1,1]]],[0,2],[0,0,3,2,5],[0,2],[3,1],[3,0,3,2,10],[3,1],[0,2]]
- Output
[null,1,null,5,5,null,10,5]
- Explanation
SubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,2,1],[4,3,4],[3,2,1],[1,1,1]]);
// The initial rectangle (4x3) looks like:
// 1 2 1
// 4 3 4
// 3 2 1
// 1 1 1
subrectangleQueries.getValue(0, 2); // return 1
subrectangleQueries.updateSubrectangle(0, 0, 3, 2, 5);
// After this update the rectangle looks like:
// 5 5 5
// 5 5 5
// 5 5 5
// 5 5 5
subrectangleQueries.getValue(0, 2); // return 5
subrectangleQueries.getValue(3, 1); // return 5
subrectangleQueries.updateSubrectangle(3, 0, 3, 2, 10);
// After this update the rectangle looks like:
// 5 5 5
// 5 5 5
// 5 5 5
// 10 10 10
subrectangleQueries.getValue(3, 1); // return 10
subrectangleQueries.getValue(0, 2); // return 5
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int N, M;
int max_row;
int max_col;
int arr[1000][1000];
int Get_update(int row1, int col1, int row2, int col2, int value){
int i, j;
//printf("\n %d %d %d %d %d", row1, col1, row2, col2, value);
for(i=row1; i<=row2; i++){
for(j=col1; j<=col2; j++){
arr[i][j] = value;
}
}
//print updated array
printf("\n[updated array]\n");
for(i=0; i<max_row; i++){
for(j=0; j<max_col; j++){
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
int Get_Value(int (*a)[M], int row, int col){
int x = row;
int y = col;
printf("value of arr[%d][%d]: %d\n", x, y, arr[x][y]);
return 0;
}
int main(int argc, char* argv[])
{
int i, j;
printf("you will make N x M: ");
scanf("%d %d", &N, &M);
printf("\n");
max_row=N;
max_col=M;
// make an array using input data
// 1 2 1
// 4 3 4
// 3 2 1
// 1 1 1
for(i=0; i<N; i++){
printf("Start to put the value of row%d\n", (i+1));
for(j=0; j<M; j++){
printf("put the value of arr[%d][%d]: ", i, j);
scanf("%d", &arr[i][j]);
}
printf("\n");
}
//print initialized array
printf("\n[Initialized Array]\n");
for(i=0; i<N; i++){
for(j=0; j<M; j++){
printf("%d ", arr[i][j]);
}
printf("\n");
}
// call update function
int row1, col1, row2, col2;
int value;
printf("\n[Update Function]\n");
printf("please put row1, col1, row2, col2, value: ");
scanf("%d %d %d %d %d", &row1, &col1, &row2, &col2, &value);
Get_update(row1, col1, row2, col2, value);
// get value function
int x, y;
printf("\n[Get Value Function]\n");
printf("please put x and y of arr[x][y]: ");
scanf("%d %d", &x, &y);
Get_Value(arr, x, y);
printf("\nThis Program is done!\n\n");
}
|
C
|
/*******************************************************************/
/* CT30A3370 Käyttöjärjestelmät ja systeemiohjelmointi
* my-grep.c
* Aino Liukkonen
* 21.4.2021
*/
/*******************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Read user-specified file and print all the lines that include the search term */
void grepFile(char *searchterm, char *fileName) {
FILE *fp;
char *buffer;
char *result;
size_t bufferSize = 32;
if((buffer = (char *)malloc(bufferSize * sizeof(char))) == NULL) {
fprintf(stderr, "my-grep: malloc failed\n");
exit(1);
}
if ((fp = fopen(fileName, "r")) == NULL) {
fprintf(stderr, "my-grep: cannot open file\n");
exit(1);
}
while (getline(&buffer, &bufferSize, fp) != -1) {
result = strstr(buffer, searchterm);
if(result != NULL) {
printf("%s", buffer);
}
}
fclose(fp);
}
/* Function grepStdio() reads one line from stdio and prints it if it includes
the search term. After that, user can input another string if they want to.
To end the execution of grepStdio(), user needs to press ctrl + d. It is
also possible to copy + paste text on the shell and then the function goes
through all lines and prints the ones that include the search term. */
void grepStdio(char *searchterm) {
char *buffer;
char *result;
size_t bufferSize = 32;
if((buffer = (char *)malloc(bufferSize * sizeof(char))) == NULL) {
fprintf(stderr, "my-grep: malloc failed\n");
exit(1);
}
while (getline(&buffer, &bufferSize, stdin) != -1) {
result = strstr(buffer, searchterm);
if(result != NULL) {
printf("%s", buffer);
}
}
}
int main (int argc, char *argv[]) {
int i;
if(argc == 1) {
fprintf(stderr, "my-grep: searchterm [file...]\n");
exit(1);
}
else if(argc == 2) {
grepStdio(argv[1]);
}
for(i=2; i<argc; i++) {
grepFile(argv[1], argv[i]);
}
return 0;
}
/*******************************************************************/
/* eof */
|
C
|
/*
Autor: Jos Molina
Date: 21/02/2019
*/
#include "dht11_h.h"
#include <stdint.h>
#define _XTAL_FREQ 8000000
void
dht11_begin(void)
{
DATA_DIR = 0; // Data pin as output
DATA = 0;
__delay_ms(18);
DATA = 1;
__delay_us(20);
DATA_DIR = 1; //Data pin as input
}
void
dht11_check(void)
{
while(DATA);
while(!DATA);
while(DATA);
}
uint8_t
dht11_read(void)
{
static uint8_t i = 0, temp = 0;
for(i = 0; i < 8 ; i++)
{
while(!DATA);
__delay_us(30);
if (DATA)
{
temp = ((temp<<1) | 1);
}
else
temp = (temp<<1);
while(DATA);
}
return temp;
}
|
C
|
/*
** EPITECH PROJECT, 2020
** MY PARAMS TO LIST
** File description:
** Put parameters into a chained list
*/
#include <stdlib.h>
#include "listlib.h"
linked_list_t *my_tab_array_to_list(int ac, char * const *av)
{
linked_list_t *list = NULL;
for (int i = 0; i <= (ac - 1); i++)
my_add_data_to_list(&list, av[i]);
return list;
}
|
C
|
#include<stdio.h>
#define M 1000000007
long long int A[1000000]={0};
inline int fastio()
{
int t=0;
char ch;
ch=getchar_unlocked();
while(ch<'0'||ch>'9')
ch=getchar_unlocked();
while(ch<='9'&& ch>='0')
{
t=(t<<3)+(t<<1)+ch-'0';
ch=getchar_unlocked();
}
return t;
}
main()
{
long long int a=0,b=1,c=1,i;
for(i=0;i<1000000;i++)
{
c=(a%M+b%M)%M;
a=b;
b=c;
A[i]=c;
}
int t;
t=fastio();
while(t--)
{
int n;
n=fastio();
printf("%lld\n",A[n-1]);
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_highlvl_graphics.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jsauron <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/03/16 10:02:18 by jsauron #+# #+# */
/* Updated: 2019/03/16 10:02:20 by jsauron ### ########.fr */
/* */
/* ************************************************************************** */
#include "wolf3d.h"
SDL_Color ft_hex_to_rgb(int hexa)
{
SDL_Color color;
color.r = hexa >> 24;
color.g = hexa >> 16;
color.b = hexa >> 8;
color.a = hexa;
return (color);
}
static void bresenham_tab(int *tab, t_pos p1, t_pos p2)
{
tab[0] = abs((int)p2.x - (int)p1.x);
tab[1] = (int)p1.x < (int)p2.x ? 1 : -1;
tab[2] = abs((int)p2.y - (int)p1.y);
tab[3] = (int)p1.y < (int)p2.y ? 1 : -1;
tab[4] = (tab[0] > tab[2] ? tab[0] : -tab[2]) / 2;
}
void draw_line(t_data *data, t_vec vec,
Uint32 color, t_limit *limit)
{
int e2;
int tab[5];
bresenham_tab(tab, vec.p1, vec.p2);
while (!((int)vec.p1.x == (int)vec.p2.x && (int)vec.p1.y == (int)vec.p2.y))
{
if (!limit || ((int)vec.p1.x > limit->l && (int)vec.p1.x < limit->r
&& (int)vec.p1.y > limit->t && (int)vec.p1.y < limit->b))
ft_setpixel(data->surface, (int)vec.p1.x, (int)vec.p1.y, color);
e2 = tab[4];
if (e2 > -tab[0] && (int)vec.p1.x != (int)vec.p2.x)
{
tab[4] -= tab[2];
vec.p1.x = (int)vec.p1.x + tab[1];
}
if (e2 < tab[2] && (int)vec.p1.y != (int)vec.p2.y)
{
tab[4] += tab[0];
vec.p1.y = (int)vec.p1.y + tab[3];
}
}
}
void ft_draw_rect(SDL_Rect rect, Uint32 color,
t_limit *limit, t_data *data)
{
int i;
int j;
i = 0;
while (i < rect.h)
{
j = 0;
while (j < rect.w)
{
if (!limit || (rect.x + j > limit->l && rect.x + j < limit->r
&& rect.y + i > limit->t && rect.y + i < limit->b))
ft_setpixel(data->surface, rect.x + j, rect.y + i, color);
j++;
}
i++;
}
}
void ft_draw_border(SDL_Rect rect, Uint32 color, t_data *data)
{
t_vec vec1;
t_vec vec2;
t_vec vec3;
t_vec vec4;
vec1 = (t_vec){(t_pos){rect.x, rect.y}, (t_pos){rect.x + rect.w, rect.y}};
vec2 = (t_vec){(t_pos){rect.x, rect.y}, (t_pos){rect.x, rect.y + rect.h}};
vec3 = (t_vec){(t_pos){rect.x + rect.w, rect.y},
(t_pos){rect.x + rect.w, rect.y + rect.h}};
vec4 = (t_vec){(t_pos){rect.x, rect.y + rect.h},
(t_pos){rect.x + rect.w, rect.y + rect.h}};
draw_line(data, vec1, color, 0);
draw_line(data, vec2, color, 0);
draw_line(data, vec3, color, 0);
draw_line(data, vec4, color, 0);
}
|
C
|
//Lab1
//v9malhot 20662020
//y95han 20651352
#include <LPC17xx.h>
#include <RTL.h>
#include <stdio.h>
#include "uart_polling.h"
#include "../RTX_CM3/INC/RTL_ext.h"
#include <stdlib.h>
//prints the state of the task given the integer equiavalent
void printState(unsigned int state)
{
switch (state) {
case INACTIVE:
printf("INACTIVE");
break;
case READY:
printf("READY ");
break;
case RUNNING:
printf("RUNNING ");
break;
case WAIT_DLY:
printf("WAIT_DLY");
break;
case WAIT_ITV:
printf("WAIT_ITV");
break;
case WAIT_OR:
printf("WAIT_OR ");
break;
case WAIT_AND:
printf("WAIT_AND");
break;
case WAIT_SEM:
printf("WAIT_SEM");
break;
case WAIT_MBX:
printf("WAIT_MBX");
break;
case WAIT_MUT:
printf("WAIT_MUT");
break;
default:
printf("UNKNOWN ");
}
}
__task void task1()
{
unsigned int i = 0;
//uart0_put_string("Bosco and Vyom Lab 1");
for(;;i++)
{
#ifdef MYSIM
os_dly_wait(20);
#else
os_dly_wait(100);
#endif
}
}
__task void task2()
{
RL_TASK_INFO taskInfo;
while(1)
{
int i;
int count = os_tsk_count_get();
printf("\n\n\nActive Tasks:%d\n",count);
printf("\tSTATES\t\tPRIORITY\tTID\tSTACK USAGE");
printf("\n------------------------------------------------------------");
for(i = 2; i< (count + 2); i++)
{
if(os_tsk_get(i, &taskInfo) == OS_R_OK)
{
printf("\nTask %d: ", i-1);
printState(taskInfo.state);
printf("\t%d\t",taskInfo.prio);
printf("\t%d\t",taskInfo.task_id);
printf("\t%d%%\t",taskInfo.stack_usage);
}
else
{
printf("Task %d: not okay\n", i-1);
}
}
//delay
#ifdef MYSIM
os_dly_wait(7);
#else
os_dly_wait(1000);
#endif
}
}
__task void task3()
{
while(1)
{
//delay
#ifdef MYSIM
os_dly_wait(20);
#else
os_dly_wait(300);
#endif
}
}
__task void task4()
{
// Fill stack with identifying values
U8 t[440];
U32 i = 0;
// Fill the stack with 0xAA's (see in Memory window of debugger)
t[0] = 0xAA;
for(i=1;i<sizeof(t)/sizeof(U8);i++) {
t[i] = t[i-1];
}
// Keep the task running forever
for(i=0;; i++){}
}
__task void task5()
{
//allocate space to test stack usage:
int myArray[20] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int myArray2[20] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int i = 0;
for(;;i++)
{
i = myArray[19];
i = myArray2[19];
//delay
#ifdef MYSIM
os_dly_wait(20);
#else
os_dly_wait(1000);
#endif
}
}
__task void init(void)
{
os_tsk_create(task1, 1); //task 1, priority 1
os_tsk_create(task2, 1); //task 2, priority 1
os_tsk_create(task3, 2); //task 3, priority 2
os_tsk_create(task4, 1); //task 4, priority 1
os_tsk_create(task5, 1); //task 5, priority 1
os_tsk_delete_self(); //delete itself before exiting
}
int main()
{
SystemInit();
uart0_init();
os_sys_init(init);
return 0;
}
|
C
|
#include <stdio.h>
#include <uv.h>
#include <rust_async_executor.h>
static void task_wake(RustAsyncExecutorExternTask data) {
uv_async_t* handle = data;
uv_async_send(handle);
}
static void task_poll(uv_async_t* handle) {
if (rust_async_executor_poll(handle->data)) {
printf("task_poll() = true\n");
// pending
} else {
printf("task_poll() = false\n");
// complete
rust_async_executor_drop(handle->data);
uv_close((uv_handle_t*)handle, NULL);
}
}
static RustAsyncExecutorExternTask task_new(RustAsyncExecutorUserData data) {
printf("task_new()\n");
uv_loop_t* loop = data;
uv_async_t* handle = malloc(sizeof(uv_async_t));
uv_async_init(loop, handle, task_poll);
return handle;
}
static void task_run(RustAsyncExecutorExternTask task, RustAsyncExecutorInternTask data) {
printf("task_run()\n");
uv_async_t* handle = task;
handle->data = data;
uv_async_send(handle);
}
void ffi_init(uv_loop_t *loop) {
rust_async_executor_init(task_new, task_run, task_wake, loop);
}
|
C
|
#include <stdio.h>
#include <string.h>
int countSetBits(unsigned int n)
{
unsigned int c; // the total bits set in n
for (c = 0; n; n >>= 1)
{
c += n & 1;
}
return c;
}
int main(void)
{
unsigned int n;
printf_s("Enter a positive integer: ");
scanf_s("%u", &n);
printf_s("%d\n", countSetBits(n));
scanf_s("%u", &n);
}
|
C
|
#include "server.h"
#include "threadpool.h"
#include "libhttp.h"
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h> /* Basic net operations */
#include<sys/socket.h> /* Socket lib */
#include<sys/types.h>
#include<sys/stat.h>
#include<netdb.h>
#include<dirent.h>
#include<unistd.h>
#include <time.h>
#define LIBHTTP_REQUEST_MAX_SIZE 8192
extern char *url;
struct pipe {
int src_fd, des_fd;
};
void proxy_back (void *aux) {
struct pipe *pipe = (struct pipe *)aux;
int remote_fd = pipe->src_fd;
int client_fd = pipe->des_fd;
char *buffer = malloc (LIBHTTP_REQUEST_MAX_SIZE + 1);
int readbytes;
while ( (readbytes = read (remote_fd, buffer, LIBHTTP_REQUEST_MAX_SIZE) ) > 0 ) {
buffer[readbytes] = '\0';
write (client_fd, buffer, readbytes);
}
printf("Remote %d has closed connection\n", remote_fd);
close (remote_fd);
free (buffer);
free (pipe);
}
void handle_proxy_request(int fd) {
printf("Client %d has connected\n", fd);
int remote_fd;
int proxy_port;
struct sockaddr_in remote_address;
int len_domain;
for (len_domain = 0; url[len_domain] != ':' && url[len_domain]; len_domain++);
char *domain = malloc( len_domain + 1 );
strlcpy(domain, url, len_domain + 1);
domain[len_domain] = '\0';
if ( url[len_domain] == ':') {
proxy_port = atoi (url + len_domain + 1);
if (proxy_port == 0) {
perror("Illegal port");
exit(EXIT_FAILURE);
}
}
else
proxy_port = 80;
printf("proxy %s:%d\n", domain, proxy_port);
struct hostent *host = gethostbyname (domain);
free (domain);
if (host == NULL) {
perror("unknown domain");
exit(EXIT_FAILURE);
}
remote_address.sin_family = AF_INET;
remote_address.sin_port = htons (proxy_port);
remote_address.sin_addr.s_addr = *(in_addr_t *)host->h_addr_list[0];
if ( (remote_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0 ) {
perror("socket failed");
exit(EXIT_FAILURE);
}
unsigned int value = 1;
setsockopt(remote_fd, SOL_SOCKET, SO_REUSEADDR,(void *) &value,sizeof(value));
if ( connect (remote_fd, (struct sockaddr *)&remote_address, sizeof (remote_address)) < 0 ) {
perror("connect failed");
exit(EXIT_FAILURE);
}
printf("%d --> %d connected\n", fd, remote_fd);
struct pipe *pipe = malloc( sizeof(struct pipe) );
*pipe = (struct pipe){remote_fd, fd};
executor_t recv_executor = executor_init (proxy_back, pipe);
if (recv_executor == EID_ERROR) {
perror("create receive task failed\n");
exit(EXIT_FAILURE);
}
if( !executor_start (recv_executor) ) {
perror("fail to start receive task\n");
exit(EXIT_FAILURE);
}
char *buffer = malloc (LIBHTTP_REQUEST_MAX_SIZE + 1);
int readbytes;
while ( (readbytes = read (fd, buffer, LIBHTTP_REQUEST_MAX_SIZE) ) > 0 ) {
buffer[readbytes] = '\0';
write (remote_fd, buffer, readbytes);
}
free (buffer);
printf("Client %d has closed connection\n", fd);
close (fd);
}
int isDir (char *path) {
struct stat path_stat;
if (stat(path, &path_stat) == -1)
return -1;
return S_ISDIR(path_stat.st_mode);
}
char *get_file_suffix (char *filename) {
char *p = NULL;
for (int i = 0; filename[i]; i++)
if (filename[i] == '.')
p = &filename[i];
if(p)
return p + 1;
else
return p;
}
void http_send_file (int fd, char *filename) {
// Get current time
char *buf = malloc(LIBHTTP_REQUEST_MAX_SIZE+1);
time_t now = time (0);
strftime (buf, 100, "%c", localtime (&now));
struct FILE *file = fopen(filename, "r");
fseek(file, 0, SEEK_END);
int lengthOfFile = ftell(file);
fseek(file, 0, SEEK_SET);
// Send http header
http_start_response(fd, 200);
http_send_header(fd, "Server", "Tinyhttpserver");
http_send_header(fd, "Date", buf);
char *suffix = get_file_suffix(filename);
if (strcmp(suffix, "html") == 0)
http_send_header(fd, "Content-type", "text/html; charset=utf-8");
else if (strcmp(suffix, "pdf") == 0)
http_send_header(fd, "Content-type", "application/pdf");
else
http_send_header(fd, "Content-type", "application/octet-stream");
sprintf(buf, "%d", lengthOfFile);
http_send_header(fd, "Content-Length", buf);
http_end_headers(fd);
while (lengthOfFile > 0) {
int readbytes = fread(buf, 1, LIBHTTP_REQUEST_MAX_SIZE > lengthOfFile?
lengthOfFile: LIBHTTP_REQUEST_MAX_SIZE, file );
http_send_data(fd, buf, readbytes);
lengthOfFile -= readbytes;
}
fclose (file);
free (buf);
}
void http_send_404 (int fd) {
char buf[100];
http_start_response(fd, 404);
http_send_header(fd, "Server", "Tinyhttpserver");
time_t now = time (0);
strftime (buf, 100, "%c", localtime (&now));
http_send_header(fd, "Date", buf);
http_send_header(fd, "Connection", "close");
http_send_header(fd, "Content-type", "text/html; charset=utf-8");
sprintf(buf, "%d", 0);
http_send_header(fd, "Content-Length", buf);
http_end_headers(fd);
}
// Concert %AB to uint8_t 0xAB and return as character
char read_perc (char *p) {
uint8_t ans = 0;
if (p[1] >= 'A' && p[1] <= 'F')
ans = p[1] - 'A' + 10;
else
ans = p[1] - '0';
ans <<= 4;
if (p[2] >= 'A' && p[2] <= 'F')
ans += p[2] - 'A' + 10;
else
ans += p[2] - '0';
return ans;
}
// decode url with percentage encode
void urlDecode(char *src, char *des) {
int top = 0;
for (int i = 0; src[i]; i++) {
if (src[i] == '%') {
des[top++] = read_perc(src + i);
i += 2;
}
else
des[top++] = src[i];
}
des[top] = '\0';
}
void handle_web_request (int fd) {
struct http_request *request = http_request_parse(fd);
printf("\"GET %s\"", request->path);
char *old = request->path;
request->path = malloc( strlen(old) + 10 );
request->path[0] = '.';
urlDecode(old, request->path+1);
free (old);
int isdir = isDir(request->path);
if (isdir == -1) {
http_send_404(fd);
printf(" 404 Not found\n");
return;
}
if (isdir) {
struct DIR *dir = opendir(request->path);
struct dirent *entry;
char buf[50];
sprintf(buf, "/tmp/tinyhttp_%d.html", fd);
struct FILE *file = fopen(buf, "w");
// Generate html head
fprintf(file, "%s", "<!DOCTYPE HTML PUBLIC>\n");
fprintf(file, "%s", "<html>\n");
fprintf(file, "%s", "<head>\n");
fprintf(file, "%s", "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n");
fprintf(file, "%s", "<title>Directory listing for /</title>\n");
fprintf(file, "%s", "</head>\n");
fprintf(file, "%s", "<body>\n");
fprintf(file, "%s", "<h1>Directory listing for /</h1>\n<hr>\n<ul>\n");
while( (entry = readdir(dir)) != NULL ) {
if (entry->d_name[0] == '.')
continue;
if (entry->d_type & DT_DIR)
fprintf(file, "<li><a href=\"%s/\">%s/</a></li>\n", entry->d_name, entry->d_name);
else
fprintf(file, "<li><a href=\"%s\">%s</a></li>\n", entry->d_name, entry->d_name);
}
fprintf(file, "%s", "</ul>\n<hr>\n");
fprintf(file, "%s", "</body>\n");
fprintf(file, "%s", "</html>\n");
fclose(file);
closedir(dir);
// Send and remove temporary file
http_send_file(fd, buf);
remove (buf);
} else {
http_send_file(fd, request->path);
}
printf(" 200 OK\n");
free(request->path);
free(request->method);
free(request);
}
|
C
|
// wield.c
inherit F_CLEAN_UP;
int do_wield(object me, object ob);
int main(object me, string arg)
{
object ob, *inv;
int i, count;
if (!arg)
return notify_fail("你要装备什么武器?\n");
if (arg == "all")
{
inv = all_inventory(me);
for (count = 0, i = 0; i < sizeof(inv); i++)
{
if (inv[i]->query("equipped"))
continue;
if (do_wield(me, inv[i]))
count++;
}
write("Ok.\n");
return 1;
}
if (!objectp(ob = present(arg, me)))
return notify_fail("你身上没有这样东西。\n");
if (ob->query("equipped"))
{
inv = all_inventory(me) - ({ob});
for (count = 0, i = 0; i < sizeof(inv); i++)
{
if (!inv[i]->id(arg))
continue;
if (inv[i]->query("equipped"))
continue;
if (do_wield(me, inv[i]))
{
count++;
break;
}
}
if (!count)
return notify_fail("你已经装备着了。\n");
return 1;
}
return do_wield(me, ob);
}
int do_wield(object me, object ob)
{
string str;
if (ob->wield())
{
if (!stringp(str = ob->query("wield_msg")))
str = "$N装备$n作武器。\n";
message_vision(str, me, ob);
return 1;
}
else
return 0;
}
int help(object me)
{
write(@HELP
指令格式:wield <装备名称>
这个指令让你装备某件物品作武器, 你必需要拥有这样物品.
HELP );
return 1;
}
|
C
|
#include<stdio.h>
#include<malloc.h>
struct Node
{
int info;
struct Node * next;
};
typedef struct Node node;
node* create (node*);
void traverse (node*);
node* swap (node*);
int main()
{
node *start = NULL;
start = create(start);
traverse(start);
start=swap(start);
traverse(start);
return 0;
}
node* create (node *s)
{
node *temp;
if(s==NULL)
{
s=(node*)malloc(sizeof(node));
printf("\nEnter data to first node : ");
scanf("%d",&(s -> info));
}
temp = s;
char ch = 'Y';
while(ch == 'Y' || ch == 'y')
{
temp -> next = (node*)malloc(sizeof(node));
temp = temp ->next;
printf("\nEnter data to New Node : ");
scanf("%d",&(temp -> info));
printf("\nEnter 'Y' to continue or Press 'N' to stop : ");
scanf(" %c",&ch);
}
temp->next=NULL;
return s;
}
void traverse(node *start)
{
node *ptr;
ptr = start;
printf("\nThe List is : \n");
while(ptr != NULL)
{
printf("%d\t",ptr->info);
ptr = ptr -> next;
}
}
node* swap (node* start)
{
node *ptr,*ptr2,*ptr2_Prev,*ptrPrev;
ptr = start;
ptr2 = ptr;
ptrPrev = ptr;
ptr = ptr->next;
while(ptr2->next !=NULL)
{
ptr2_Prev = ptr2;
ptr2 = ptr2->next;
}
ptrPrev -> next = ptr -> next;
ptr -> next = ptr2;
ptr2_Prev -> next = ptr;
return start;
}
|
C
|
/*
** EPITECH PROJECT, 2020
** zappy_server
** File description:
** File for the bct command
*/
#include "utils/write_list.h"
#include "server.h"
#include <stdlib.h>
void send_bct_info(data_server_t *data, char **arg, map_t *map, client_t *cli)
{
char str[200] = {0};
if (cli != data->l_graphical.first) {
sprintf(str, "bct %d %s %s %d %d %d %d %d %d %d\n", cli->drone.id,
arg[1], arg[2], map->items[0], map->items[1], map->items[2],
map->items[3], map->items[4], map->items[5], map->items[6]);
} else {
sprintf(str, "bct %d %s %s %d %d %d %d %d %d %d\n", -1,
arg[1], arg[2], map->items[0], map->items[1], map->items[2],
map->items[3], map->items[4], map->items[5], map->items[6]);
}
add_to_write_list(data->l_graphical.first, str);
}
void bct_command(__attribute__((unused))client_t *cli,
data_server_t *data, char **arg)
{
map_t *cur = data->bottom_left;
if (!arg || !arg[1] || !arg[2])
return;
for (int i = 0; i < atoi(arg[2]); ++i)
cur = cur->right;
for (int i = 0; i < atoi(arg[1]); ++i)
cur = cur->top;
send_bct_info(data, arg, cur, cli);
for (int a = 0; arg[a]; ++a)
free(arg[a]);
free(arg);
}
|
C
|
#include<stdio.h>
#include<pwd.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(){
//Get the password struct of the current user id from the system
struct passwd *p = getpwuid(getuid());
//print out user name, user ID and group ID respectively
printf("User is: %s\n", p->pw_name);
printf("UID is: %d\n", p->pw_uid);
printf("GID is: %d\n", p->pw_gid);
//This char will hold the host name
char hostname[255];
//Store the hostname in the hostname char array
gethostname(hostname, 255);
// print the hostname
printf("Host is %s\n", hostname);
int i;
//print the names of the first five entries in the password file
for( i = 0; i < 5; i++){
p = getpwuid(i);
printf("entry %d: %s\n", i, p->pw_name);
}
//The char and char[] variables are used to read scanf(), userdone is used to determine
//When the user has finished looking up environment variables userDone will be set to false
char input[31];
char *envValue;
char isExit;
int userDone = 1;
//This while loop will run until the user types Y or y when prompted to exit
while(userDone){
printf("Enter desired environment variable: ");
//Get the environment variable is looking for
scanf("%s", input);
//Get the value of the environment variable from the system
envValue = getenv(input);
//Check to see if the environment variable is null
if(envValue){
//Show the user the value of the enverionment variable
printf("Value is: %s\n", envValue);
int exitDecided = 0;
//Runs until the user responds Y/y or N/n to the query
while(!exitDecided){
printf("Exit? Y/N: ");
scanf(" %c", &isExit);
if(isExit == 'n' || isExit == 'N'){
//exit this while loop and loop through the top while loop again
exitDecided = 1;
}
else if(isExit == 'y' || isExit == 'Y'){
//exit both while loops
exitDecided = 1;
userDone = 0;
}
}
}
//If the environment varible is null, inform the user and ask if they want to go again
else{
printf("That is not a valid environment variable.\n");
int exitDecided = 0;
//Runs until the user responds Y/y or N/n to the query
while(!exitDecided){
printf("Exit? Y/N: ");
scanf(" %c", &isExit);
if(isExit == 'n' || isExit == 'N'){
//exit this while loop and loop through the top while loop again
exitDecided = 1;
}
else if(isExit == 'y' || isExit == 'Y'){
//exit both while loops
exitDecided = 1;
userDone = 0;
}
}
}
}
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
char ch = 'A';
printf ("%c\n",ch);
int age=20;
printf("%d\n",age);
long num = 1000;
printf("%d\n",num);
printf ("%d\n",sizeof(char));
printf ("%d\n",sizeof(int));
printf ("%d\n",sizeof(short));
printf ("%d\n",sizeof(long));
printf ("%d\n",sizeof(long long));
printf ("%d\n",sizeof(float));
printf ("%d\n",sizeof(double));
return 0;
}
|
C
|
#include <stdio.h>
#define MAXBUF 1024
static int count;
static int notchar(const char c) {
if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' )
return 0;
return 1;
}
static void findword(const char *line, const char *dest) {
int c, i, j,p;
i = j = p = 0;
while ( (c = line[p++]) != '\0'){
if (c != dest[0])
continue;
for (i = p, j = 1; line[i] != '\0' && dest[j] != '\0' && line[i] == dest[j]; i++, j++)
;
if ( (dest[j] == '\0') && notchar(line[i]) && ( p == 1 || notchar(line[p-2])) )
count++;
}
}
int main(int argc, char *argv[])
{
FILE *fp;
char templine[MAXBUF];
count = 0;
if (argc != 3) {
fprintf(stderr,"Usage: %s filepath searchword\n",argv[0]);
return 1;
}
if ((fp = fopen(argv[1],"r")) == NULL) {
perror(argv[1]);
return 1;
}
while (fgets(templine, MAXBUF, fp) != NULL)
findword(templine, argv[2]);
printf("%d\n",count);
fclose(fp);
return 0;
}
|
C
|
/* -------------------------------------------------------------------------------------
* The Dining Philosophers problem is a classic multi-process synchronization
* problem. The problem consists of five philosophers sitting at a table who do
* nothing but think and eat. Between each philosopher, there is a single fork
* In order to eat, a philosopher must have both forks. A problem can arise if
* each philosopher grabs the fork on the right, then waits for the fork on the
* left. In this case a deadlock has occurred, and all philosophers will starve.
* Also, the philosophers should be fair. Each philosopher should be able to eat
* as much as the rest.
*
* The Dining Philosophers
*
* Implement in the C language again the dining philosophers program. Now,
* instead of usage of processes and semaphores, use threads and mutexes from
* threads library.
*
* ------------------------------------------------------------------------------------- */
//-------------------------------------------------------------------------------------
// Includes:
//-------------------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
//-------------------------------------------------------------------------------------
// Common variable:
//-------------------------------------------------------------------------------------
#define PHILOSOPHER_NO 5
#define DINING_NO 3
#define LEFT PHILOSOPHER_ID
#define RIGHT (PHILOSOPHER_ID + 1) % PHILOSOPHER_NO
#define THINKING 0
#define HUNGRY 1
#define EATING 2
//-------------------------------------------------------------------------------------
// Mutexes and shared variables:
//-------------------------------------------------------------------------------------
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t s[PHILOSOPHER_NO] = PTHREAD_MUTEX_INITIALIZER;
int state[PHILOSOPHER_NO];
//-------------------------------------------------------------------------------------
// Definition of function:
//-------------------------------------------------------------------------------------
void eat(int i, int meal);
void grab_forks(int left_fork_id);
void put_away_forks(int left_fork_id);
void initializePhilosphers();
void* philospher(void* num);
void test(int i);
//-------------------------------------------------------------------------------------
// main():
//-------------------------------------------------------------------------------------
int main(){
initializePhilosphers();
return 0;
}
/* -------------------------------------------------------------------------------------
Pseudocode:
process P[i]
while true do {
THINK;
PICKUP(CHOPSTICK[i], CHOPSTICK[i+1 mod 5]);
EAT;
PUTDOWN(CHOPSTICK[i], CHOPSTICK[i+1 mod 5])
}
------------------------------------------------------------------------------------- */
void *philosopher(void *num) {
//Set the ID of the current philosopher
int PHILOSOPHER_ID = *(int *) num;
for (int i = 0; i < DINING_NO; i++) {
printf("Philosopher[%d] is THINKING\n", PHILOSOPHER_ID);
sleep(1);
grab_forks(PHILOSOPHER_ID); //Philosopher grabs forks
eat(PHILOSOPHER_ID, i+1); //Philosopher is eating
sleep(1);
put_away_forks(PHILOSOPHER_ID); //Philosopher puts forks down
}
return NULL;
}
//-------------------------------------------------------------------------------------
// initializePhilosphers():
//-------------------------------------------------------------------------------------
void initializePhilosphers(){
int i;
// Init mutexes - no eating
for (i = 0; i < PHILOSOPHER_NO; i++)
{
pthread_mutex_lock(s + i);
}
pthread_t threadIds[PHILOSOPHER_NO]; // Declare thread array
int philosophersIds[PHILOSOPHER_NO];
// Thread Creation
for (i = 0; i < PHILOSOPHER_NO; i++)
{
philosophersIds[i] = i;
pthread_create(&threadIds[i], NULL, philosopher, &philosophersIds[i]);
}
sleep(30);
// Wait equivalent
// Join all threads
for (i = 0; i < PHILOSOPHER_NO; i++)
{
pthread_join(threadIds[i], NULL);
}
// pthread_mutex_destroy(&m);
for (i = 0; i < PHILOSOPHER_NO; i++)
{
pthread_mutex_destroy(&threadIds[i]);
}
exit(0);
}
void grab_forks(int left_fork_id){
int PHILOSOPHER_ID = left_fork_id;
pthread_mutex_lock(&m); // Lock mutex, Begin Critical Section
state[PHILOSOPHER_ID] = HUNGRY;
printf("Philosopher[%d] TRY TO [%d-%d] GRAB FORKS.\n", RIGHT, LEFT, RIGHT);
test(PHILOSOPHER_ID);
pthread_mutex_unlock(&m); // Unlock mutex, end of ciritical section
pthread_mutex_lock(&s[PHILOSOPHER_ID]); //take forks
sleep(1);
}
void test(int i){
int PHILOSOPHER_ID = i;
if( state[PHILOSOPHER_ID] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING )
{
state[PHILOSOPHER_ID] = EATING;
pthread_mutex_unlock(&s[PHILOSOPHER_ID]);
}
}
void put_away_forks(int i)
{
int PHILOSOPHER_ID = i;
pthread_mutex_lock(&m); //Begin Critical Section
state[PHILOSOPHER_ID] = THINKING; //Set state to the philosopher to THINKING
printf("Philosopher[%d] PUTS FORK [%d-%d] DOWN.\n", RIGHT, LEFT, RIGHT);
printf("Philosopher[%d] is THINKING.\n", RIGHT);
test(LEFT); //Test eating conditions for the left philosopher
test(RIGHT); //Test eating conditions for the right philosopher
pthread_mutex_unlock(&m); //End Critical Section
}
//-------------------------------------------------------------------------------------
// eat():
//-------------------------------------------------------------------------------------
void eat(int i, int meal)
{
int PHILOSOPHER_ID = i; // initialization for defined LEFT and RIGHT
sleep(2);
printf("Philosopher[%d] TAKES FORK %d and %d\n",
RIGHT, RIGHT, LEFT);
printf("Philosopher[%d] is EATING [%d] meal\n", RIGHT, meal);
}
|
C
|
float earth[3];
float myState[12];
void init() {
earth[0] = 0.64;
earth[1] = 0;
earth[2] = 0;
}
void loop() {
api.getMyZRState(myState);
setPositionTarget(earth,3);
DEBUG(("trololololololol"));
}
float distance(float p1[], float p2[]){
float d = 0;
for(int i=0; i < 3; i++){
d += (p2[i]-p1[i])*(p2[i]-p1[i]);
}
return sqrtf(d);
}
float angle(float a[], float b[], float c[]) {
//returns the measure of angle abc
float side1[3], side2[3], cosine;
for (int i = 0; i < 3; i++) side1[i] = a[i] - c[i];
cosine = - mathVecMagnitude(side1,3) * mathVecMagnitude(side1,3);
for (int i = 0; i < 3; i++) side1[i] = b[i] - a[i];
for (int i = 0; i < 3; i++) side2[i] = c[i] - b[i];
cosine += mathVecMagnitude(side1,3) * mathVecMagnitude(side1,3) + mathVecMagnitude(side2,3) * mathVecMagnitude(side2,3);
if (mathVecMagnitude(side1,3) * mathVecMagnitude(side2,3) / 10 == 0) {
DEBUG(("DIVISION BY ZERO WHILE FINDING ANGLE!"));
}
cosine /= 2 * mathVecMagnitude(side1,3) * mathVecMagnitude(side2,3);
return acosf(cosine);
}
void mathVecProject(float c[], float a[], float b[], int n) {
// finds the projection of a onto b, puts the result in c
if (mathVecMagnitude(b,3) * mathVecMagnitude(b,3) / 10 == 0) {
DEBUG(("DIVISION BY ZERO WHILE PROJECTING!"));
}
for (int i = 0; i < n; i++) {
c[i] = (mathVecInner(a,b,3) * b[i]) / (mathVecMagnitude(b,3) * mathVecMagnitude(b,3));
}
}
float minDistanceFromOrigin(float target[]) {
float temp[3] = {0,0,0}; //temp is the origin
if (cosf(angle(temp,myState,target)) < 0) { //going away from origin
return mathVecMagnitude(myState, 3);
}
else if (cosf(angle(temp,target,myState)) < 0) { //going in direction of origin
return mathVecMagnitude(target,3);
}
else {
mathVecSubtract(temp,target,myState,3);
mathVecProject(temp,myState,temp,3);
mathVecSubtract(temp,myState,temp,3);
return mathVecMagnitude(temp,3);
}
}
void setPositionTarget(float target[3], float multiplier) {
api.getMyZRState(myState);
float myPos[3],meMag;
for(int i = 0; i < 3; i++) {
myPos[i] = myState[i];
}
meMag = mathVecMagnitude(myPos,3);
if (minDistanceFromOrigin(target) > 0.31) {
if (distance(myState, target) < 0.4) { // Save braking distance
api.setPositionTarget(target);
}
else { // Or haul ass towards target
float temp[3];
mathVecSubtract(temp,target,myState,3);
for (int i = 0 ; i < 3 ; i++) {
temp[i] = myState[i] + temp[i] * multiplier;
}
api.setPositionTarget(temp);
}
DEBUG(("GOING STRAIGHT\n"));
}
else if (meMag >= 0.22 && meMag <= 0.32) {
for (int i = 0; i < 3; i++) {
myPos[i] = myPos[i] * 1.6;
}
api.setPositionTarget(myPos);
DEBUG(("TOO CLOSE\n"));
}
else {
float opposite[3], perpendicular[3], mePrep[3], path[3], temp[3];
mathVecProject(opposite,target,myPos,3);
mathVecSubtract(perpendicular,target,opposite,3);
for (int i = 0; i < 3; i++) {
mePrep[i] = perpendicular[i] / mathVecMagnitude(perpendicular,3);
}
for (int i = 0; i < 3; i++) {
mePrep[i] = (mePrep[i] * 0.325 * meMag) / (sqrtf(meMag*meMag - 0.32*0.32));
}
mathVecSubtract(path,mePrep,myPos,3);
for (int i = 0; i < 3; i++) {
path[i] = path[i] * multiplier;
}
mathVecAdd(temp,myPos,path,3);
api.setPositionTarget(temp);
DEBUG(("TAKING THE TANGENT\n"));
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct stack {
int data;
struct stack *next;
};
typedef struct stack stack;
struct queue {
int data;
struct queue *next;
};
typedef struct queue queue;
stack *head = NULL, *temps, *current;
queue *front = NULL, *rear = NULL, *temp;
void push(int elt) {
stack *new = (stack *) malloc (sizeof(stack));
new->data = elt;
if(head == NULL) {
head = new;
head->next = NULL;
}
else {
temps = head;
new->next = temps;
head = new;
}
}
void pop() {
if (head == NULL)
printf("\nSTACK UNDERFLOW!");
else {
temps = head;
head = head->next;
free(temps);
}
}
void displaystack() {
current = head;
if (head == NULL)
printf("\nSTACK is empty!");
else {
printf("\n Elements on stack are: \n\n");
while(current != NULL) {
printf("\n \t %d \n",current->data);
printf("\t|____|");
current = current->next;
}
}
}
void emptystack() {
while(head != NULL) {
pop();
head = head->next;
}
displaystack();
head = NULL;
}
void enqueue(int elt) {
queue *new = (queue *) malloc (sizeof(queue));
new->data = elt;
new->next = NULL;
if(rear == NULL) {
rear = new;
front = rear;
}
else {
rear->next = new;
rear = new;
}
}
void dequeue() {
if(front == NULL)
printf("\n\n Queue is empty.");
else {
temp = front;
front = front->next;
free(temp);
}
printf("\n Queue is updated!");
}
void displayqueue() {
temp = front;
if(front == NULL)
printf("\n Queue is empty!");
else {
printf("\n\n The elements in queue are: \n \t");
while (temp != NULL) {
printf("%d -> ",temp->data);
temp = temp->next;
}
}
}
void emptyqueue() {
if(front == NULL)
printf("\n\n Queue is already empty.");
else {
while(front != NULL) {
dequeue();
front = front->next;
}
}
displayqueue();
front = NULL;
rear = NULL;
}
int stacks() {
int elt,ch;
do {
printf("\n\n\n Stack Operations: ");
printf("\n\n 1. Insert into Stack.");
printf("\n 2. Delete from Stack.");
printf("\n 3. Display elements of Stack");
printf("\n 4. Empty stack.");
printf("\n 5. Back.");
printf("\n Enter the action to be performed: ");
scanf("%d",&ch);
switch(ch) {
case 1:
do {
printf("\n Enter the element to be inserted(-999 to stop): ");
scanf("%d",&elt);
if(elt != -999)
push(elt);
}while(elt != -999);
break;
case 2:
pop();
printf("\n Top element is deleted! Stack is updated!");
displaystack();
break;
case 3:
displaystack();
break;
case 4:
emptystack();
break;
case 5:
return 0;
default:
printf("\n Invalid option! Try with numbers 1-3!");
}
}while(ch != 5);
}
int queues() {
int ch,elt;
do {
printf("\n\n\n Queue Operations: ");
printf("\n\n 1. Insert into queue.");
printf("\n 2. Delete from queue.");
printf("\n 3. Display elements of queue.");
printf("\n 4. Empty queue.");
printf("\n 5. Back.");
printf("\n Enter the action to be performed: ");
scanf("%d",&ch);
switch(ch) {
case 1:
do {
printf("\n Enter the element to be inserted(-999 to stop): ");
scanf("%d",&elt);
if(elt != -999)
enqueue(elt);
}while(elt != -999);
break;
case 2:
dequeue();
displayqueue();
break;
case 3:
displayqueue();
break;
case 4:
emptyqueue();
break;
case 5:
return 0;
default:
printf("\n\n Invalid option! Try with numbers 1-3!");
}
}while(ch != 5);
}
main() {
int ch;
do {
printf("\n\n 1. Implementation of Stack.");
printf("\n 2. Implementation of Queue.");
printf("\n 3. Exit.");
printf("\n\n Enter your choice: ");
scanf("%d",&ch);
switch(ch) {
case 1:
stacks();
break;
case 2:
queues();
break;
case 3:
return 0;
default:
printf("\n\n Invalid option! Try with numbers 1-3!");
}
}while(ch!=3);
}
|
C
|
//
// TestaPrimo.c
// TestaPrimo
//
// Created by Ricardo de Carvalho Destro on 12/08/20.
// Copyright © 2020 Ricardo de Carvalho Destro. All rights reserved.
//
#include "TestaPrimo.h"
/* Convencao: EhPrimo = 1 se o numero dado 'e primo */
/* EhPrimo = 0 se o numero dado nao 'e primo */
//Algoritmo 1
int TestaPrimo(long int n)
{
int EhPrimo = 1,
d=2;
if (n <= 1)
EhPrimo = 0;
while (EhPrimo == 1 && d <= n /2) {
if (n % d == 0)
EhPrimo = 0;
d = d + 1;
}
return EhPrimo;
}
//Algoritmo 2
//Teorema de Wilson que valida se os números são primos ou não
int TestePrimo2(int x)
{
int flag = 0;
int i = 0;
for (i = 2; i <= x / 2; ++i) {
// condition for non-prime
if (x % i == 0) {
flag = 1;
break;
}
}
return flag;
}
//Algoritmo 3
//Pequeno Teorema de Fermat
//estarei utilizando o maior número primo informado 2147483647 para o valor n, para validar se a é ou não primo
int TestePrimo3(int num)
{
if (num <= 3) {
return num > 1;
}
if ((num % 2 == 0) || (num % 3 == 0)) {
return num;
}
int contador = 5;
while (pow(contador, 2) <= num) {
if (num % contador == 0 || num % (contador + 2) == 0) {
return 0;
}
contador += 6;
}
return 1;
}
double desvioPadrao(double x[15], double _x, int n)
{
double dp = 0;
double soma = 0;
for (int j = 0; j < n; j++)
{
soma = pow(x[j] - _x, 2);
}
dp = sqrt(soma / n);
return dp;
}
//Algoritmo 2
int main()
{
clock_t tempo;
double media = 0;
double mediaTotal = 0;
double soma = 0;
double tempos[15];
//int x = 0;
//int temp = 0;
int isprime = 0;
double dp = 0;
long int v[] = {7, 37, 8431, 13033, 524287, 664283, 3531271, 2147483647};
printf("Variaveis\n");
printf("T = tempo medio de execucao\t");
printf("Dp = desvio padrao\n\n");
printf("Calculando...\n");
for (char j = 0; j < 8; j++)
{
for (int i = 0; i < 15; i++)
{
tempo = clock();
isprime = TestePrimo3(v[j]);
tempo = clock() - tempo;
soma += ((double)tempo / CLOCKS_PER_SEC) * 1000;
//printf("\ntempo acumulado: %f\n", soma);
tempos[i] = tempo;
//temp++;
}
media = soma / 15;
//mediaTotal = media;
dp = desvioPadrao(tempos, media, 15);
printf("\nO numero %d %s. \nT = %f ms\nDp = %f \n", v[j], ((isprime) ? " eh primo" : " nao eh primo"), media, dp);
}
return 0;
}
|
C
|
#include "stdio.h"
int main()
{
int a, b, c, d;
while( scanf("%d %d %d %d", &a, &b, &c, &d), (a+b+c+d!=0) ){
printf("%d\n", 9*(80 + (a-b>=0?a-b:a-b+40) + 40 + (c-b>=0?c-b:c-b+40) + (c-d>0?c-d:c-d+40) ));
}
}
|
C
|
#include "tests.h"
#include "utils.h"
#include "solver.h"
#include <stdio.h>
#include <string.h>
void test(char* result);
void test_row(int row[WIDTH], int expected_value);
void test_column(int column[HEIGHT], int expected_value);
void test_sub(int sub[SUB_HEIGHT][SUB_WIDTH], int expected_value);
void test_rows(int matrix[HEIGHT][WIDTH], int expected_value);
void test_columns(int matrix[HEIGHT][WIDTH], int expected_value);
void test_subs(int matrix[HEIGHT][WIDTH], int expected_value);
void test_whole(int matrix[HEIGHT][WIDTH], int expected_value);
void test_row_legality(int row[WIDTH], int expected_value);
void test_column_legality(int column[HEIGHT], int expected_value);
void test_sub_legality(int sub[SUB_HEIGHT][SUB_WIDTH], int expected_value);
void test_legality(int matrix[HEIGHT][WIDTH], int expected_value);
void test_legality_after_move(int matrix[HEIGHT][WIDTH], int move[3], int expected_value);
void print_test_results(void);
int test_index = 0;
int failed = 0;
void test(char* result) {
test_index++;
printf("Test %d: %s\n", test_index, result);
if (strcmp(result, "Fail") == 0)
failed++;
}
void test_row(int row[WIDTH], int expected_value) {
test( check_row(row) == expected_value ? "Pass" : "Fail" );
}
void test_column(int column[HEIGHT], int expected_value) {
test( check_column(column) == expected_value ? "Pass" : "Fail" );
}
void test_sub(int sub[SUB_HEIGHT][SUB_WIDTH], int expected_value) {
test( check_sub(sub) == expected_value ? "Pass" : "Fail" );
}
void test_rows(int matrix[HEIGHT][WIDTH], int expected_value) {
test( check_rows(matrix) == expected_value ? "Pass" : "Fail" );
}
void test_columns(int matrix[HEIGHT][WIDTH], int expected_value) {
test( check_columns(matrix) == expected_value ? "Pass" : "Fail" );
}
void test_subs(int matrix[HEIGHT][WIDTH], int expected_value) {
test( check_subs(matrix) == expected_value ? "Pass" : "Fail" );
}
void test_whole(int matrix[HEIGHT][WIDTH], int expected_value) {
test( is_solved(matrix) == expected_value ? "Pass" : "Fail" );
}
void test_row_legality(int row[WIDTH], int expected_value) {
test ( is_row_legal(row) == expected_value ? "Pass" : "Fail" );
}
void test_column_legality(int column[HEIGHT], int expected_value) {
test ( is_column_legal(column) == expected_value ? "Pass" : "Fail" );
}
void test_sub_legality(int sub[SUB_HEIGHT][SUB_WIDTH], int expected_value) {
test ( is_sub_legal(sub) == expected_value ? "Pass" : "Fail" );
}
void test_legality(int matrix[HEIGHT][WIDTH], int expected_value) {
test ( is_legal(matrix) == expected_value ? "Pass" : "Fail" );
}
void test_legality_after_move(int matrix[HEIGHT][WIDTH], int move[3], int expected_value) {
test ( is_legal_after_move(matrix, move) == expected_value ? "Pass" : "Fail" );
}
void print_test_results(void) {
if (failed > 1)
printf("%d tests failed!\n", failed);
else if (failed == 1) {
printf("%d test failed!\n", failed);
}
else
printf("All tests passed!\n");
}
void run_tests(void) {
int unsolved[HEIGHT][WIDTH] = { { 5, 3, 0, 0, 7, 0, 0, 0, 0 },
{ 6, 0, 0, 1, 9, 5, 0, 0, 0 },
{ 0, 9, 8, 0, 0, 0, 0, 6, 0 },
{ 8, 0, 0, 0, 6, 0, 0, 0, 3 },
{ 4, 0, 0, 8, 0, 3, 0, 0, 1 },
{ 7, 0, 0, 0, 2, 0, 0, 0, 6 },
{ 0, 6, 0, 0, 0, 0, 2, 8, 0 },
{ 0, 0, 0, 4, 1, 9, 0, 0, 5 },
{ 0, 0, 0, 0, 8, 0, 0, 7, 9 } };
int illegal[HEIGHT][WIDTH] = { { 5, 3, 5, 2, 7, 6, 7, 8, 9 },
{ 6, 1, 0, 1, 9, 5, 0, 0, 0 },
{ 0, 9, 8, 0, 0, 0, 0, 6, 0 },
{ 8, 2, 2, 0, 6, 0, 0, 0, 3 },
{ 4, 4, 0, 8, 0, 3, 6, 0, 1 },
{ 7, 0, 5, 0, 2, 0, 0, 0, 6 },
{ 0, 6, 0, 0, 0, 0, 2, 8, 0 },
{ 0, 0, 0, 4, 1, 9, 0, 0, 5 },
{ 4, 0, 0, 0, 8, 0, 0, 7, 9 } };
int solved[HEIGHT][WIDTH] = { { 5, 3, 4, 6, 7, 8, 9, 1, 2 },
{ 6, 7, 2, 1, 9, 5, 3, 4, 8 },
{ 1, 9, 8, 3, 4, 2, 5, 6, 7 },
{ 8, 5, 9, 7, 6, 1, 4, 2, 3 },
{ 4, 2, 6, 8, 5, 3, 7, 9, 1 },
{ 7, 1, 3, 9, 2, 4, 8, 5, 6 },
{ 9, 6, 1, 5, 3, 7, 2, 8, 4 },
{ 2, 8, 7, 4, 1, 9, 6, 3, 5 },
{ 3, 4, 5, 2, 8, 6, 1, 7, 9 } };
int row[WIDTH];
int column[HEIGHT];
int sub[SUB_HEIGHT][SUB_WIDTH];
puts("Unsolved tests");
test_rows(unsolved, 0);
test_columns(unsolved, 0);
test_subs(unsolved, 0);
test_whole(unsolved, 0);
copy_row(unsolved, 0, row);
test_row_legality(row, 1);
copy_column(unsolved, 0, column);
test_column_legality(column, 1);
copy_sub(unsolved, 0, 0, sub);
test_sub_legality(sub, 1);
test_legality(unsolved, 1);
int illegal_move[3] = {0, 2, 5};
test_legality_after_move(unsolved, illegal_move, 0);
int legal_move[3] = {0, 2, 4};
test_legality_after_move(unsolved, legal_move, 1);
puts("Illegal tests");
test_rows(illegal, 0);
test_columns(illegal, 0);
test_subs(illegal, 0);
test_whole(illegal, 0);
copy_row(illegal, 0, row);
test_row_legality(row, 0);
copy_column(illegal, 0, column);
test_column_legality(column, 0);
copy_sub(illegal, 0, 0, sub);
test_sub_legality(sub, 0);
test_legality(illegal, 0);
puts("Presolved tests");
test_rows(solved, 1);
test_columns(solved, 1);
test_subs(solved, 1);
test_whole(solved, 1);
solve(unsolved);
puts("Solved tests");
test_rows(unsolved, 1);
test_columns(unsolved, 1);
test_subs(unsolved, 1);
test_whole(unsolved, 1);
print_test_results();
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_suurballe_algorithm.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ssoraka <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/08/20 15:42:44 by ssoraka #+# #+# */
/* Updated: 2019/08/20 15:42:45 by ssoraka ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_lem_in.h"
/*
** Алгоритм Суурбалле: отключение маршрута, добавление фиктивных комнат
*/
void ft_restruct_point(t_all *all, t_room *first, t_room *second)
{
char second_in[MAX_NAME];
ft_memcpy((void *)second_in, second->name, ft_strlen(second->name) + 1);
ft_strcat(second_in, "_in ");
ft_add_room(all, second_in);
all->rooms->origin = second;
ft_change_in_tubes(all, second, second_in);
ft_add_tube(all, second_in, first->name, INVERS);
ft_add_tube(all, second->name, second_in, FICTIOUS_NULL);
}
/*
** Алгоритм Суурбалле: переносит выходящие связи из существующей комнаты
** на фиктивную новую
*/
void ft_change_out_tubes(t_all *all, t_room *old, char *new)
{
t_tube *tube;
tube = all->tubes;
while (tube)
{
if (tube->room1 == all->start || tube->room2 == all->start ||
tube->room1 == all->end || tube->room2 == all->end)
{
tube = tube->next;
continue ;
}
if (old == tube->room1 && tube->active == ACTIVE)
{
tube->active = DEACTIVE;
ft_add_tube(all, new, tube->room2->name, FICTIOUS);
}
tube = tube->next;
}
}
/*
** Алгоритм Суурбалле: переносит входящие связи с существующей комнаты
** на фиктивную новую
*/
void ft_change_in_tubes(t_all *all, t_room *old, char *new)
{
t_tube *tube;
tube = all->tubes;
while (tube)
{
if (old == tube->room2 && tube->active == ACTIVE)
{
tube->active = DEACTIVE;
ft_add_tube(all, tube->room1->name, new, FICTIOUS);
}
tube = tube->next;
}
}
/*
** отключение связи
*/
void ft_deactive_tube(t_all *all, t_room *room1, t_room *room2)
{
t_tube *tube;
tube = all->tubes;
while (tube)
{
if (room1 == tube->room1 && room2 == tube->room2)
{
tube->active = DEACTIVE;
return ;
}
tube = tube->next;
}
}
int ft_cost(int active)
{
if (active == ACTIVE)
return (2);
if (active == INVERS)
return (-1);
if (active == FICTIOUS)
return (2);
if (active == FICTIOUS_NULL)
return (1);
else
return (0);
}
|
C
|
/*Copyright © 2020- by Wangchuwen,2018202114. All rights reserved*/
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <unistd.h>
#include<semaphore.h>
#include <stdlib.h>
//semaphores
sem_t mutex1,mutex2,mutex3,mutex4;//用于原子操作
sem_t mread,mwrite,mRead,mWrite;//用于读写互斥
int writecount,readcount,Writecount,Readcount;//用于计数读写者数量
void * Reader(void *counter);//读者优先
void * writer(void *counter);
void * reader(void *counter);//写者优先
void * Writer(void *counter);
int a,b;//读写者数量
int start;//计时器开始,便于可视化
int *rtime,*wtime;//用于计时
//可视化
void visual()
{
int k=0;
int j=0;
printf("过程时间轴可视化:\n");
printf("R is reading,W is writing!\n");
for(j=0;j<a;j++)
{
printf("READER%d: ",j);
for(k=0;k<rtime[j];k++)
{
printf("-");
}
for(;k<rtime[j]+2;k++)
{
printf("R");
}
printf("\n");
}
for(j=0;j<b;j++)
{
printf("WRITER%d: ",j);
for(k=0;k<wtime[j];k++)
{
printf("-");
}
for(;k<wtime[j]+2;k++)
{
printf("W");
}
printf("\n");
}
printf("\n");
}
//菜单设计
void menu()
{
printf("-------------------MENU--------------------\n\n");
printf(" 1 读者优先 \n");
printf(" 2 写者优先 \n");
printf(" 3 退出 \n\n");
printf("-------------------------------------------\n");
printf(" option: ");
}
/*读者优先*/
void *Reader(void * counter){
int id = *((int*)counter);
sleep(1);
printf("READER %d: waiting to read\n", id);
sem_wait(&mutex4);//用于互斥操作readcount
Readcount++;
if(Readcount == 1)
sem_wait(&mwrite);//不允许写
sem_post(&mutex4);
printf("READER %d: start reading\n", id);
rtime[id]=time((time_t*)NULL)-start;//用于记录时间点
sleep(2);//模拟read过程
printf("READER %d: end reading\n", id);
sem_wait(&mutex4);//用于互斥操作readcount
Readcount--;
if(Readcount == 0)
sem_post(&mwrite);//无读进程等待,允许写
sem_post(&mutex4);
}
void *writer(void *counter){
int id = *((int*)counter);
sleep(1);
printf("WRITER %d: waiting to write\n", id);
sem_wait(&mwrite);//实现写者互斥
printf("WRITER %d: start writing\n", id);
wtime[id]=time((time_t*)NULL)-start;
sleep(2);
printf("WRITER %d: end writing\n", id);
sem_post(&mwrite);
}
/*写者优先*/
void* reader(void* counter) {
int id = *((int*)counter);
sleep(1);
printf("READER %d: waiting to read\n", id);
sem_wait(&mutex1);//防止对mread wait多次
sem_wait(&mread);//等待没有写进程排队再读
sem_wait(&mutex2);//互斥操作readcount
readcount++;
if(readcount == 1)
sem_wait(&mWrite);
sem_post(&mutex2);
sem_post(&mread);
sem_post(&mutex1);
printf("READER %d: start reading\n", id);
rtime[id]=time((time_t*)NULL)-start;//记录时间点
sleep(2);//模拟read
printf("READER %d: end reading\n", id);
sem_wait(&mutex2);//互斥操作readcount
readcount--;
if(readcount == 0)
sem_post(&mWrite);
sem_post(&mutex2);
}
void* Writer(void* counter) {
int id = *((int*)counter);
sleep(1);
printf("WRITER %d: waiting to write\n", id);
sem_wait(&mutex3);//互斥操作writecount
Writecount++;
if(Writecount == 1){
sem_wait(&mread);//不允许读
}
sem_post(&mutex3);
sem_wait(&mWrite);//写者互斥
printf("WRITER %d: start writing\n", id);
wtime[id]=time((time_t*)NULL)-start;
sleep(2);//模拟write
printf("WRITER %d: end writing\n", id);
sem_post(&mWrite);
sem_wait(&mutex3);//互斥操作writecount
Writecount--;
if(Writecount == 0) {
sem_post(&mread);//当无写者排队时,允许读者读
}
sem_post(&mutex3);
}
int main() {
int i;
//初始化信号量
sem_init(&mutex1, 0, 1);
sem_init(&mutex2, 0, 1);
sem_init(&mutex3, 0, 1);
sem_init(&mutex4, 0, 1);
sem_init(&mwrite, 0, 1);
sem_init(&mread, 0, 1);
sem_init(&mWrite, 0, 1);
sem_init(&mRead, 0, 1);
//选项
int option;
readcount = writecount = Writecount = Readcount = 0;
//线程
pthread_t *preader,*pwriter;
//读写者
int *readerid,*writerid;
//错误检查
int *retr,*retw;
while(1)
{
start=time((time_t*)NULL);
printf("请输入读者和写者的数量,用空格隔开: ");
scanf("%d %d",&a,&b);
//分配动态内存
readerid=malloc(sizeof(int) * a);
writerid=malloc(sizeof(int) * b);
retr=malloc(sizeof(int) * a);
retw=malloc(sizeof(int) * b);
preader=malloc(sizeof(pthread_t) * a);
pwriter=malloc(sizeof(pthread_t) * b);
rtime=malloc(sizeof(int) * a);
wtime=malloc(sizeof(int) * b);
//菜单
menu();
scanf("%d",&option);
switch (option)
{
case 1://读者优先
//创建线程
for (i = 0; i < a; i++)
{
readerid[i] = i;
retr[i]=pthread_create (&preader[i], NULL, Reader, &readerid[i]);
if(retr[i]!=0){
printf("Reader %d init failed.\n",i);
exit(1);
}
}
for (i = 0; i < b; i++)
{
writerid[i] = i;
retw[i]=pthread_create (&pwriter[i], NULL, writer, &writerid[i]);
if(retw[i]!=0){
printf("Writer %d init failed.\n",i);
exit(1);
}
}
//结束线程
for (i = 0; i < a; i++)
{
pthread_join(preader[i], NULL);
}
for (i = 0; i < b; i++)
{
pthread_join(pwriter[i], NULL);
}
visual();
break;
case 2://写者优先
//创建线程
for (i = 0; i < a; i++)
{
readerid[i] = i;
retr[i]=pthread_create (&preader[i], NULL, reader, &readerid[i]);
if(retr[i]!=0){
printf("Reader %d init failed.\n",i);
exit(1);
}
}
for (i = 0; i < b; i++)
{
writerid[i] = i;
retw[i]=pthread_create (&pwriter[i], NULL, Writer, &writerid[i]);
if(retw[i]!=0){
printf("Writer %d init failed.\n",i);
exit(1);
}
}
//结束线程
for (i = 0; i < a; i++)
{
pthread_join(preader[i], NULL);
}
for (i = 0; i < b; i++)
{
pthread_join(pwriter[i], NULL);
}
//可视化
visual();
break;
case 3://退出
printf("成功退出\n");
return 0;
break;
default:
printf("sorry,worry selection!");
break;
}
}
//销毁信号量
sem_destroy(&mutex1);
sem_destroy(&mutex2);
sem_destroy(&mutex3);
sem_destroy(&mutex4);
sem_destroy(&mread);
sem_destroy(&mRead);
sem_destroy(&mwrite);
sem_destroy(&mWrite);
return 0;
}
|
C
|
#include<stdio.h>
void NhapMang(int A[100], int N){
int i;
for(i=0; i<N; i++){
printf("Mang[%d] = ", i);
scanf("%d", &A[i]);
}
}
long GT(int n){
int i; long gt=1;
for(i=2; i<=n; i++){
gt *= i;
}
return gt;
}
int main(){
int A[100], n;
printf("Nhap so phan tu mang: ");
scanf("%d", &n);
NhapMang(A,n);
double Tgt=0; int i;
for(i=1; i<=n; i++){
Tgt += GT(A[i]);
}
printf("Tong giai thua cua giai thua cac phan tu mang la: %.0lf", Tgt);
}
|
C
|
/** Autor: Gabriel Dias **/
/**
* Dada uma matriz qualquer, verificar se existem elementos repetidos dentro dela.
**/
// Bibliotecas padrao
#include <stdio.h>
#include <locale.h>
// Define valores que sero usados no programa
#define MAX 100
#define TRUE 1
#define FALSE 0
int main() {
// Configura o idioma de acordo com a localizao
setlocale(LC_ALL, "portuguese");
// Variveis
int Matriz[MAX][MAX], num;
int numLinhas, numColunas;
int i, j; // Indices da matriz original
int k, l; //Indices da matriz que armazena os valores repetidos
int achou;
// Processamento
printf("Digite o numero de linhas da matriz A: ");
scanf(" %d", &numLinhas);
printf("\nDigite o numero de colunas da matriz A: ");
scanf(" %d", &numColunas);
// Preenche a matriz
for (i = 0; i < numLinhas; i++)
for (j = 0; j < numColunas; j++){
printf("Digite o elemento da posicao (%d, %d): ", i+1, j+1);
scanf("%d", &num);
Matriz[i][j] = num;
}
// Varivel que armazena um valor booleano indicando que achou ou no um valor repetido na matriz
achou = FALSE;
// Estrutura que verifica se h valores repetidos
for (i = 0; !achou && i < numLinhas; i++){
for (j = 0; !achou && j < numColunas; j++){
/* Procura o elemento da posicao (i,j) nas posicoes seguintes da matriz */
k = i;
l = j + 1;
while (!achou && k < numLinhas){
while (!achou && l < numColunas){
if (Matriz[i][j] == Matriz[k][l]){
achou = TRUE;
}
l++;
}
l = 0;
k++;
}
}
}
// Exibe mensagem
if (achou){
printf("\n\nH elementos repetidos na matriz.\n");
}else{
printf("No h elementos repetidos na matriz.\n");
}
system ("pause");
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* argument.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: liton <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/09/16 18:54:31 by liton #+# #+# */
/* Updated: 2017/09/17 03:16:30 by liton ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_select.h"
void support_formatting(int count)
{
int i;
i = -1;
if (global->fmt->nbl_save != global->fmt->nb_list)
{
while (++i < global->fmt->len_max)
ft_putchar_fd(' ', 2);
global->fmt->nbl_save = global->fmt->nb_list;
}
if (count != global->fmt->count && count != 0)
ft_putchar_fd('\n', 2);
}
void free_struct(void)
{
t_files *tmp;
while (global->file && global->file->first != 1)
global->file = global->file->next;
global->file = global->file->next;
while (global->file->first == 0)
{
tmp = global->file;
global->file = global->file->next;
ft_strdel(&tmp->name);
free(tmp);
tmp = NULL;
}
ft_strdel(&global->file->name);
free(global->file);
global->file = NULL;
free(global->fmt);
free(global->op);
free(global);
}
static char *argument(void)
{
char *arg;
int exit;
exit = 1;
arg = ft_strnew(0);
while (global->file && global->file->first != 1)
global->file = global->file->next;
while (exit)
{
if (global->file->reverse == 1)
{
arg = ft_strjoinfree(arg, global->file->name, 1);
arg = ft_strjoinfree(arg, " ", 1);
}
global->file = global->file->next;
if (global->file->first == 1)
exit = 0;
}
if (arg[0] != '\0')
arg[ft_strlen(arg) - 1] = '\0';
return (arg);
}
void enter(void)
{
char *arg;
arg = argument();
shell_off();
if (arg[0] != '\0')
ft_putendl_fd(arg, 1);
ft_strdel(&arg);
free_struct();
exit(0);
}
|
C
|
//
// Created by hasee on 2019/12/2.
//
#include "gcd_lcm.h"
int gcd(int a, int b)
{
if (a <= 0 || b <= 0)
return -1;
while (b != 0) {
int tmp = a % b;
a = b;
b = tmp;
}
return a;
}
int lcm(int a, int b)
{
return a * b / gcd(a, b);
}
|
C
|
#include<stdio.h>
#include<sys/wait.h>
#include<unistd.h>
#include<sys/types.h>
#include<stdlib.h>
#include<pthread.h>
void mysys(char *command){
pid_t pid;
if((pid = fork()) == 0){
execl("/bin/sh","sh","-c",command,NULL);
}
waitpid(pid,NULL,NULL);
}
int main(){
printf("---------------------------------\n");
mysys("echo HELLOW WORLD");
printf("---------------------------------\n");
mysys("ls /");
printf("---------------------------------\n");
return 0;
}
|
C
|
#include <stdio.h> //biblioteca padro para comandos i/o
#include <stdlib.h>//necessrio para o system ("pause")
main()
{
int op;
float v1, v2,conta;
printf("\nDigite o primeiro valor: \n");
scanf("%f", &v1);
printf("\nDigite o segundo valor: \n");
scanf("%f", &v2);
printf("\nDigite um numero para o curso, soma-1, subtracao-2, multiplicacao-3, divisao-4\n");
scanf("%d", &op);
switch (op)
{
case 1 :
conta= v1+v2;
printf ("resultado: %f\n", conta);
break;
case 2 :
conta= v1-v2;
printf ("resultado: %f\n",conta);
break;
case 3 :
conta= v1*v2;
printf ("resultado: %f\n",conta);
break;
case 4 :
conta= v1/v2;
printf ("Nota de sistema e: %f\n",conta);
break;
default :
printf ("Valor invalido!\n");
}
}
|
C
|
//power of 8
#include <stdio.h>
int main()
{
int n;
printf("Enter the number:");
scanf("%d",&n);
if(((n&(n-1))==0) && ((n&0xB6DB6DB6)==0))
printf("Power of 8\n");
else
printf("Not Power of 8\n");
}
|
C
|
#include "binary_trees.h"
/**
* binary_tree_height - Returns the height of the binary tree
* @tree: the binary tree
* Return: the height of the binary tree
*/
size_t binary_tree_height(const binary_tree_t *tree)
{
size_t height_left = 0, height_right = 0;
if (!tree)
return (0);
if (!tree->left && !tree->right)
return (0);
height_left = binary_tree_height(tree->left);
height_left++;
height_right = binary_tree_height(tree->right);
height_right++;
if (height_left < height_right)
return (height_right);
else
return (height_left);
}
|
C
|
//DANIEL VIDIRI NETO - 109970
//TAREFA 02 - URI1002
//DATA 04/08/2020
#include <stdio.h>
int main() {
double area, raio, n;
n = 3.14159;
scanf("%lf", &raio);
area = n * (raio * raio);
printf("A=%.4lf\n", area);
return 0;
}
|
C
|
////////////////////////////////////////////////////////////////////////////////
//INCLUDES
#include <stdio.h>
int main(void)
{
float sum = 0;
float height = 0;
float radius = 0;
int count = 0;
int i = 0;
printf("How many cylinders would you like to sum?\n");
scanf("%i", &count);
for(i = 0; i < count; i++)
{
printf("How high is cylinder %i?\n", i+1);
scanf("%f", &height);
printf("What is cylinder %i's radius?\n", i+1);
scanf("%f", &radius);
sum += height * 3.14159265 * radius * radius; //alternatively, use the pow math function.
}
printf("Total Sum is: %f\n", sum);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <limits.h>
#define SCHEME_CREATE_MAIN
#define SCHEME_ASSERT_STDINOUT_ARE_PIPED
#define SCHEME_FUNCTION graph_ttc_performance
#include "scheme.h"
int graph_ttc_performance(int argc, char ** argv, FILE * pipe_in, FILE * pipe_out, FILE * pipe_err)
{
char distance_attribute[300] = "dist_line_192";
int distance_multiple = 1;
int c;
while ((c = getopt(argc, argv, "a:i")) != -1)
switch (c)
{
case 'a':
strncpy(distance_attribute, optarg, 300);
break;
case 'i':
distance_multiple = -1;
break;
default:
abort();
}
struct Shape * line = NULL;
int distance_value = INT_MAX;
struct Shape * shape = NULL;
while ((shape = read_shape(pipe_in)))
{
if (get_attribute(shape, "vehicle_number") == NULL) { free_shape(shape); continue; }
if (line == NULL || strcmp(get_attribute(line, "vehicle_number"), get_attribute(shape, "vehicle_number")) != 0 || atoi(get_attribute(shape, distance_attribute)) < distance_value)
{
if (line != NULL && line->num_vertexs > 0) { write_shape(pipe_out, line); free_shape(line); }
line = new_shape();
line->gl_type = GL_LINE_STRIP;
set_attribute(line, "vehicle_number", get_attribute(shape, "vehicle_number"));
if (shape->num_vertex_arrays == 2)
{
struct VertexArray * cva = get_or_add_array(line, GL_COLOR_ARRAY); // just to create it
set_num_dimensions(line, 1, 4);
}
}
float v[3] = { atof(get_attribute(shape, distance_attribute)) * distance_multiple, atof(get_attribute(shape, "reported_at")), 0 };
//float c[4] = { 0, 0, 0, 1 };
//append_vertex2(line, v, c);
if (shape->num_vertex_arrays == 2) // maintain the color
append_vertex2(line, v, get_vertex(shape, 1, 0));
else
append_vertex(line, v);
struct Shape * marker = new_shape();
marker->gl_type = GL_LINES;
append_vertex(marker, v);
v[1] -= 100;
append_vertex(marker, v);
write_shape(pipe_out, marker);
free_shape(marker);
distance_value = atoi(get_attribute(shape, distance_attribute));
free_shape(shape);
}
if (line != NULL && line->num_vertexs > 0) { write_shape(pipe_out, line); free_shape(line); }
}
|
C
|
/*
============================================================================
Name : parcial1Labo1.c
Author : Luca
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "avion.h"
#include "marca.h"
#include "viaje.h"
#include "utn.h"
int main(void) {
setbuf(stdout,NULL);
Marca marcas[QTY_MARCAS]={
{1000,"Boening",0},
{1001,"Airbus",0},
{1002,"ATR",0},
{1003,"Bombardier",0}
};
Viaje viajes[QTY_VIAJES]={
{100,"Salta",1462.5,0},
{101,"Tucuman",1247.6,0},
{102,"Neuquen",1139.4,0},
{103,"Corrientes",670,0},
{104,"Chubut",1735.8,0}
};
Avion aviones[QTY_AVIONES];
int idAviones=1;
char auxMatricula[10];
int auxIndex;
int opcion;
if(initAvion(aviones, QTY_AVIONES)==1){
opcion = menu();
int contador;
contador = harcodearAviones(aviones);
idAviones = idAviones+contador;
}
do{
switch(opcion)
{
case 1:
altaAvion(aviones, QTY_AVIONES, &idAviones, marcas, viajes);
break;
case 2:
mostrarAviones(aviones, QTY_AVIONES, marcas, QTY_MARCAS, viajes, QTY_VIAJES);
printf("Ingrese matricula del avion a modificar:");
getString(auxMatricula, 10);
while(findAvionByMatricula(aviones, QTY_AVIONES, auxMatricula)==-2)
{
printf("\nLa matricula ingresada no existe\n");
printf("Ingrese nuevamente matricula del avion a modificar:\n");
getString(auxMatricula, 10);
}
auxIndex = findAvionByMatricula(aviones, QTY_AVIONES, auxMatricula);
modificarAvion(aviones, QTY_AVIONES, auxIndex);
break;
case 3:
mostrarAviones(aviones, QTY_AVIONES, marcas, QTY_MARCAS, viajes, QTY_VIAJES);
printf("Ingrese matricula del avion a eliminar:");
getString(auxMatricula, 10);
while(findAvionByMatricula(aviones, QTY_AVIONES, auxMatricula)==-2)
{
printf("\nLa matricula ingresada no existe\n");
printf("Ingrese nuevamente matricula del avion a modificar:\n");
getString(auxMatricula, 10);
}
auxIndex = findAvionByMatricula(aviones, QTY_AVIONES, auxMatricula);
if(auxIndex>=0 && bajaAvion(aviones, QTY_AVIONES, auxIndex)==1)
printf("El avion se elimino con exito. \n");
break;
case 4:
if(sortAvionesPorMatriculayMarca(aviones, QTY_AVIONES, marcas, QTY_MARCAS)==0)
{
mostrarAviones(aviones, QTY_AVIONES, marcas, QTY_MARCAS, viajes, QTY_VIAJES);
}
break;
case 5:
mostrarViajes(viajes, QTY_VIAJES);
break;
case 6:
mostrarMarcas(marcas, QTY_MARCAS);
break;
case 7:
mostrarAvionesBoening(aviones, QTY_AVIONES, marcas, QTY_MARCAS, viajes, QTY_VIAJES);
break;
case 8:
mostrarAvionMarcaSelec(aviones, QTY_AVIONES, marcas, QTY_MARCAS, viajes, QTY_VIAJES);
break;
case 9:
mostrarAvionesNeuquen(aviones, QTY_AVIONES, marcas, QTY_MARCAS, viajes, QTY_VIAJES);
break;
case 10:
break;
case 11:
informarAsientosModeloSelec(aviones, QTY_AVIONES, marcas, QTY_MARCAS, viajes, QTY_VIAJES);
break;
}
opcion = menu();
}while(opcion<12);
return EXIT_SUCCESS;
}
|
C
|
/**@file
* Interface of gamma game input parser.
*
* @author Antoni Koszowski <a.koszowski@students.mimuw.edu.pl>
* @copyright
* @date 17.05.2020
*/
#ifndef GAMMA_GAMMA_PARSER_H
#define GAMMA_GAMMA_PARSER_H
/**@brief Parses and interprets input.
* Parses input lines and then interprets it.
* In case that command was matched it is realized.
* @param input_line - input line to be parsed.
*/
void parse_input(char *input_line);
/**@brief Deletes gamma game.
* Deletes from memory structure storing gamma game.
*/
void delete_game();
#endif //GAMMA_GAMMA_PARSER_H
|
C
|
#include<stdio.h>
int insert(int a[],int n,int index,int element){
int i=0;
for(i=n;i>index;i--)
a[i]=a[i-1];
a[i]=element;
return n+1;
}
int delete(int a[],int n,int index){
for(int i=index; i<n; i++){
a[i]=a[i+1];
}
return n-1;
}
void display(int a[],int n){
for(int i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}
void main(){
printf("Enter the number of elements and elements of the array\n");
int n;
scanf("%d",&n);
int a[50],k,element,m;
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter element and position for insertion\n");
scanf("%d %d",&element,&k);
n = insert(a,n,k+1,element);
display(a,n);
printf("Enter position for deletion\n");
scanf("%d",&m);
n = delete(a,n,m+1);
display(a,n);
}
|
C
|
#include "redBlackTree.h"
#include <stdio.h>
#define N 50
int main( )
{
rbTree T;
position P;
int i;
int j = 0;
T = init( );
T = makeEmpty( T );
for( i = 1; i < N; i++ )
T = insert( i, T );
printf( "Inserts are complete\n" );
printTree(T);
printf("\nroot value is %d\n", retrieve(T));
for( i = 1; i < N; i++ )
if( ( P = find( i, T ) ) == NULL || retrieve( P ) != i )
printf( "Error at %d\n", i );
printf( "Min is %d, Max is %d\n", retrieve( findMin( T ) ),
retrieve( findMax(T)));
for( i = 16 ; i > 0; i -= 2) {
T = delete(i, T);
printf("\n");
}
printTree(T);
printf( "\nMin is %d, Max is %d\n", retrieve( findMin( T ) ),
retrieve( findMax( T ) ) );
return 0;
}
|
C
|
/**
* @file LineSeperator.h
* @author Idan Refaeli <idan.refaeli@mail.huji.ac.il>
* @version 1.0
* @date 03 Aug 2015
*
* @brief Perceptron program. Flagging given data by 1 or -1 using linear separator.
* Header file for perceptron.c.
*
* @section LICENSE
* This program is a free software
*
* @section DESCRIPTION
* The program gets a series of vectors, where the first of them are practice vectors. Using the
* practice vectors it calculates the separate vector and then use it to flag the other remaining
* vectors.
*
* Input : File containing practice vectors, vectors to flag, the dimension of the vector space
* and number of practice vectors.
* Process: The program calculates the separate vector and use it to flag the vectors to flag.
* Output : The flags of the vectors.
*/
#ifndef LINESEPARATOR_H_
#define LINESEPARATOR_H_
// ------------------------------ includes ------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
// -------------------------- const definitions -------------------------
#define NUM_OF_ARGUMENTS 2
#define FILE_ARGUMENT 1
#define MAX_MUM_OF_CHARS_IN_LINE 150
#define MAX_DIMENSION 75
#define POSITIVE_FLAG 1
#define NEGATIVE_FLAG -1
#define INNER_PRODUCT_ACCURACY 0.00001
const char COMMA[2] = ",";
// -------------------------- structs -----------------------------------
/**
* @brief struct representing a vector.
*/
typedef struct Vector
{
double _vector[MAX_DIMENSION]; // The vector's coordinates
int _flag; // The flag of the vector (-1 or 1)
} Vector;
// ------------------------------ functions -----------------------------
/**
* @brief Used to get the dimension of the vector space and the number of practice vectors from
* the given file.
* @param data - The file containing the data about the vectors.
* @return The dimension of the vector space.
*/
unsigned int getInfo(FILE* data);
/**
* @brief Get the next vector from the given data file and put it inside the given pointer's vector
* given.
* @param data - The file containing the data about the vectors.
* @param dimension - The dimension of the vector space.
* @param vector - pointer to the vector that will contain the new vector from the file.
* @return 1 if the operation succeeded, 0 if no more vectors left in the data file.
*/
int getVector(FILE* data, const unsigned int dimension, Vector* vector);
/**
* @brief Calculating the separating vector of the perceptron and putting it inside the given
* pointer's vector.
* @param data - The file containing the data about the vectors.
* @param dimension - The dimension of the vector space.
* @param numOfPracticeVectors - Number of practice vectors.
* @param separateVector - pointer to the vector that will be the separate vector.
* @return The separate vector.
*/
void getSeperateVector(FILE* data, const unsigned int dimension,
const unsigned int numOfPracticeVectors, Vector* separateVector);
/**
* @brief Used to flag all the vectors from the data file with the calculated separate vector.
* @param data - The file containing the data about the vectors.
* @param dimension - The dimension of the vector space.
* @param separateVector - pointer to the separate vector.
*/
void flagVectors(FILE* data, const unsigned int dimension, Vector* separateVector);
/**
* @brief Calculate and return the inner product of the 2 given vectors.
* @param v1 - pointer to the first vector
* @param v2 - pointer to the second vector
* @param dimension - The dimension of the vector space.
* @return The inner product.
*/
double innerProduct(const Vector* v1, const Vector* v2, const unsigned int dimension);
/**
* @brief Multiplying the given scalar and given vector and save the answer in the given vector
* @param v1 - The vector
* @param scalar - The scalar
* @param dimension - The dimension of the vector space.
*/
void scalarMultiply(Vector* v1, const double scalar, const unsigned int dimension);
/**
* @brief Adding 2 given vectors and save the answer in the first given vector.
* @param v1 - The first vector.
* @param v2 - The second vector.
* @param dimension - The dimension of the vector space.
*/
void addVectors(Vector* v1, const Vector* v2, const unsigned int dimension);
#endif /* LINESEPARATOR_H_ */
|
C
|
#include "stm32f4xx.h"
void LED_Init(void) {
RCC_AHB1PeriphClockCmd (RCC_AHB1Periph_GPIOD, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOD, &GPIO_InitStructure);
}
void SW_Init(void) {
RCC_AHB1PeriphClockCmd (RCC_AHB1Periph_GPIOA, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOD, &GPIO_InitStructure);
}
int main(void) {
LED_Init();
SW_Init();
while(1) {
if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == 1) {
GPIO_SetBits(GPIOD, GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15);
}
else {
GPIO_ResetBits(GPIOD, GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15);
}
}
return 0;
}
|
C
|
/*
* SwitchTime.c
*
* Created: 2020-06-15 오전 10:21:12
* Author: PKNU
*/
#include <avr/io.h>
#include <util/delay.h>
int main()
{
unsigned char Switch_flag = 0;
unsigned char Switch_flag_pre = 0x01; // 0000 0001 최초 delay
DDRA = 0x0F; // 0000 1111 0~3번 출력
DDRD = 0x00; // 0000 0000 D입력
PORTA = 0x00; // 0000 0000
while(1)
{
Switch_flag = PIND >> 4; // 0000 0001 -> 0000 0000
// 0000 0010 -> 0000 0000
// 0000 0100 -> 0000 0000
// 0000 1000 -> 0000 0000
// 0001 0000 -> 0000 0001
// 0010 0000 -> 0000 0010
// 0100 0000 -> 0000 0100
// 1000 0000 -> 0000 1000
if((Switch_flag == 0x01)||(Switch_flag==0x02)||(Switch_flag==0x04)||(Switch_flag==0x08))
{
Switch_flag_pre = Switch_flag;
}
PORTA ^= 0x0f; // 0000 1111 [BIT OR 연산자 0^1 = 1, 1^1 = 0]
if(Switch_flag_pre == 0x01)
_delay_ms(250);
else if(Switch_flag_pre == 0x02)
_delay_ms(500);
else if(Switch_flag_pre == 0x04)
_delay_ms(750);
else if(Switch_flag_pre == 0x08)
_delay_ms(1000);
}
return 0;
}
|
C
|
#include "special_arg.h"
#include "dev_list.h"
#include "wire_io.h"
#include "wire_log.h"
#include <string.h>
#include <errno.h>
#define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))
static int special_arg_net(char **items, unsigned items_size, unsigned item_size)
{
struct ifaddrs *ifaddr;
struct ifaddrs *ifa;
int ret;
int n;
int items_len = 0;
int item_idx;
ret = wio_getifaddrs(&ifaddr);
if (ret < 0) {
wire_log(WLOG_ERR, "Failed to get interface address info: %d (%m)", errno);
return 0;
}
for (ifa = ifaddr, n = 0; items_len < items_size && ifa != NULL; ifa = ifa->ifa_next, n++) {
if (ifa->ifa_addr == NULL)
continue;
int family = ifa->ifa_addr->sa_family;
if (family != AF_INET && family != AF_INET6)
continue;
char *colon = strchr(ifa->ifa_name, ':');
if (colon)
*colon = 0;
int found = 0;
for (item_idx = 0; item_idx < items_len; item_idx++) {
if (strcmp(ifa->ifa_name, items[item_idx]) == 0) {
found = 1;
break;
}
}
if (!found) {
strncpy(items[items_len], ifa->ifa_name, item_size);
items[items_len][item_size-1] = 0;
items_len++;
}
}
freeifaddrs(ifaddr);
return items_len;
}
static int find_dev_path(char *dev_path, unsigned dev_path_sz, const char *dev_name)
{
int ret;
char dev_num[32];
unsigned dev_major, dev_minor;
ret = wio_read_file_content(dev_name, dev_num, sizeof(dev_num) - 1);
if (ret <= 0) {
wire_log(WLOG_ERR, "Failed to open file %s: %d (%m)", dev_name, errno);
return -1;
}
// Null-terminate the string
dev_num[ret] = 0;
ret = sscanf(dev_num, "%u:%u", &dev_major, &dev_minor);
if (ret != 2) {
wire_log(WLOG_ERR, "Failed to parse dev_num content '%s'", dev_num);
return -1;
}
dev_list_t *dev_list = dev_list_get();
dev_list_t *n;
ret = -1;
for (n = dev_list; n; n = n->next) {
if (n->major == dev_major && n->minor == dev_minor) {
strncpy(dev_path, n->name, dev_path_sz);
dev_path[dev_path_sz-1] = 0;
ret = 0;
break;
}
}
dev_list_release(dev_list);
return ret;
}
static int special_arg_block(char **items, unsigned items_size, unsigned item_size)
{
#define BASE_PATH "/sys/block"
int num_items = 0;
int ret;
int i;
glob_t globbuf;
ret = wio_glob(BASE_PATH "/*/dev", GLOB_NOSORT, NULL, &globbuf);
if (ret < 0) {
wire_log(WLOG_ERR, "Failed to list files in " BASE_PATH ": %d (%m)", errno);
return 0;
}
for (i = 0; i < globbuf.gl_pathc && num_items < items_size; i++) {
if (strncmp(globbuf.gl_pathv[i], BASE_PATH "/loop", strlen(BASE_PATH "/loop")) == 0)
continue; // Skip loopback devices
ret = find_dev_path(items[num_items], item_size, globbuf.gl_pathv[i]);
if (ret == 0)
num_items++;
}
wio_globfree(&globbuf);
return num_items;
}
int special_arg_match(const char *name, char **items, unsigned items_size, unsigned item_size)
{
static const struct {
const char *name;
int (*func)(char **items, unsigned items_size, unsigned item_size);
} specials[] = {
{"%BLOCK", special_arg_block},
//TODO: {"%SES", special_arg_ses},
//TODO: {"%SCSI", special_arg_scsi},
{"%NET", special_arg_net},
};
if (name[0] != '%')
return 0;
int j;
for (j = 0; j < ARRAY_SIZE(specials); j++) {
if (strcmp(name, specials[j].name) == 0) {
return specials[j].func(items, items_size, item_size);
}
}
return 0;
}
|
C
|
/*
Environmental Data Sensing and Storing
mscs crysanthus@gmail.com
*/
#include <SoftwareSerial.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#include <Wire.h>
#include <BH1750FVI.h>
SoftwareSerial homeStatESP(6, 7); // RX, TX // ESP Module
DHT_Unified dhtSensor(2, DHT11); /// DHT sensor
BH1750FVI bhLightSensor; // BH1750 Ambient Light Sensor
/*sensor connected
VCC >>> 3.3V
SDA >>> A4
SCL >>> A5
addr >> A3
Gnd >>>Gnd
*/
uint32_t delayMS;
String asSensorData[3];
// SendCommand prototype
boolean SendCommand(String sATCmd, String sResponse, boolean bCRLF = true);
void setup()
{
Serial.begin(9600);
homeStatESP.begin(115200);
/* --- SENSORS
*/
// dht sensor
dhtSensor.begin();
sensor_t sensor;
delayMS = sensor.min_delay / 1000;
// light sensor
bhLightSensor.begin();
bhLightSensor.SetAddress(Device_Address_H);//Address 0x5C
bhLightSensor.SetMode(Continuous_H_resolution_Mode);
// coonect to ap
while (!JoinAP());
}
void loop() {
// Get Temp
sensors_event_t event;
dhtSensor.temperature().getEvent(&event);
if (isnan(event.temperature)) {
Serial.println("Error reading temperature!");
}
else {
asSensorData[0] = (String)int(event.temperature);
}
// Get Humd
dhtSensor.humidity().getEvent(&event);
if (isnan(event.relative_humidity)) {
Serial.println("Error reading humidity!");
}
else {
asSensorData[1] = (String)int(event.relative_humidity);
}
// Get Lux / Lumn
uint16_t lux = bhLightSensor.GetLightIntensity();
asSensorData[2] = (String)int(lux);
Serial.println(asSensorData[0] + "*C - " + asSensorData[1] + "% - " + asSensorData[2] + "lux");
PostData(asSensorData);
// Delay between measurements.
delay(60000);
}
/* ESP Init
*/
void StartESP() {
Serial.println("ESP init!");
SendCommand("AT+RST", "OK");
}
/* AT Commander
*/
boolean SendCommand(String sATCmd, String sResponse, boolean bCRLF = true) {
Serial.println("CMD rcvd!");
Serial.println(sATCmd);
bCRLF ? homeStatESP.println(sATCmd) : homeStatESP.print(sATCmd);
delay(8000);
return responseFind(sResponse); // find given response
}
/* AT Response find
*/
boolean responseFind(String sKey) {
long lTO = millis() + 5000; // Time Out
char cKey[sKey.length()];
sKey.toCharArray(cKey, sKey.length());
while (millis() < lTO) {
if (homeStatESP.available()) {
if (homeStatESP.find(cKey)) {
Serial.println(sKey);
return true;
}
}
}
return false; // timeout
}
boolean JoinAP() {
Serial.println("Joining AP ...");
String sAP = "AP NAME";
String sPP = "AP PASSWORD";
StartESP();
if (SendCommand("AT+CWJAP=\"" + sAP + "\",\"" + sPP + "\"", "OK")) {
Serial.println("Joined AP!");
return true;
}
else {
Serial.println("Failed joining AP ...");
return false;
}
}
/* Post to Web API
a Python Flask API waiting for data
*/
void PostData(String saData[]) {
String sServer = "WEB SERVER IP OR NAME"; // Without http part
String sPort = "5000";
String sURI = "/api/addstatsg?";
if (SendCommand("AT+CIPSTART=\"TCP\",\"" + sServer + "\"," + sPort, "OK")) {
Serial.println("TCP connection ready!");
/**HTTP GET Sample
GET /api/addstatsg?cert=xyz&temp=34&humd=45&lumn=55 HTTP/1.1
Host: 192.168.1.5:5000
*/
String sPostRequest = String("GET " + sURI);
sPostRequest += String("cert=xyz&");
sPostRequest += String("temp=" + saData[0] + "&");
sPostRequest += String("humd=" + saData[1] + "&");
sPostRequest += String("lumn=" + saData[2] + " HTTP/1.1\r\n");
sPostRequest += String("Host: " + sServer + ":" + sPort + "\r\n\r\n"); // ends with 2 x CRLF - Important -
/*This is by AT design
*/
SendCommand("AT+CIPSEND=", "", false);
if (SendCommand(String(sPostRequest.length()), ">")) {
Serial.println("TCP ready to receive data ...");
if (SendCommand(sPostRequest, "SEND OK")) {
Serial.println("Data packets sent ok!");
while (homeStatESP.available()) {
Serial.println(homeStatESP.readString());
}
// close the connection
CloseTCPConnection();
}
else {
CloseTCPConnection();
}
}
else {
CloseTCPConnection();
}
} else {
CloseTCPConnection();
}
}
/*Close TCP connection
*/
void CloseTCPConnection() {
while (!SendCommand("AT+CIPCLOSE", "OK")) {
Serial.print(".");
}
Serial.println("TCP connection closed!");
}
/*EOF
*/
|
C
|
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/time.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("chudik");
static const unsigned long chudFS_MAGIC_NUMBER = 0x13131313;
static void chudFS_put_super(struct super_block *sb)
{
printk(KERN_INFO "chudFS super block destroyed!\n");
}
static struct super_operations const chudFS_super_ops = {
.put_super = chudFS_put_super,
.statfs = simple_statfs ,
.drop_inode = generic_delete_inode ,
};
static struct inode *chudFS_make_inode(struct super_block *sb, int mode)
{
struct inode *ret = new_inode(sb);
if (ret) {
inode_init_owner(ret, NULL, mode);
ret->i_size = PAGE_SIZE;
ret->i_atime = ret->i_mtime = ret->i_ctime = current_time(ret);
}
return ret;
}
static int chudFS_fill_sb(struct super_block *sb, void *data, int silent)
{
struct inode *root = NULL;
sb->s_blocksize = PAGE_SIZE;
sb->s_blocksize_bits = PAGE_SHIFT;
sb->s_magic = chudFS_MAGIC_NUMBER;
sb->s_op = &chudFS_super_ops;
root = chudFS_make_inode(sb, S_IFDIR | 0755);
if (!root)
{
printk(KERN_ERR "inode allocation failed!\n");
return -ENOMEM;
}
root->i_op = &simple_dir_inode_operations;
root->i_fop = &simple_dir_operations;
sb->s_root = d_make_root(root);
if (!sb->s_root)
{
printk(KERN_ERR "root creation failed!\n");
return -ENOMEM;
}
return 0;
}
//^
static struct dentry *chudFS_mount(struct file_system_type *type,
int flags, char const *dev, void *data)
{
struct dentry *const entry = mount_bdev(type, flags, dev, data, chudFS_fill_sb);
if (IS_ERR(entry))
printk(KERN_ERR "chudFS mounting failed!\n");
else
printk(KERN_INFO "chudFS mounted\n");
return entry;
}
// ^
static struct file_system_type chudFS_type = {
.owner = THIS_MODULE,
.name = "chudFS",
.mount = chudFS_mount,
.kill_sb = kill_block_super,
};
static int __init chudFS_init(void)
{
int ret = register_filesystem(&chudFS_type);
if (ret != 0) {
printk(KERN_ERR "Cannot register filesystem!\n");
return ret;
}
printk(KERN_INFO "chudFS module loaded\n");
return 0;
}
static void __exit chudFS_exit(void)
{
int ret = unregister_filesystem(&chudFS_type);
if (ret != 0)
printk(KERN_ERR "Cannot unregister filesystem!\n");
printk(KERN_INFO "chudFS module unloaded\n");
}
module_init(chudFS_init);
module_exit(chudFS_exit);
|
C
|
/***********************************************************************
* $Id: stringtable.c,v 1.1 2012/12/05 07:59:55 dmf Exp $
* Derek Frank, dmfrank@usc.edu
*
* NAME
* stringtable.c - implementation file for the string table ADT
*
* DESCRIPTION
* Implementation for the string table ADT. The string table ADT will
* operate as a hash table. Uses separate chaining for collision
* resolution.
*
**********************************************************************/
#include <stdlib.h>
#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "stringtable.h"
/******************* Private Structs: not exported ********************/
////
// stringnode - struct
//
// A node that contains a pointer to a string on the heap, along
// with a collision resolution pointer and a cached hash number.
// Also a pointer to an internal static string identifier.
//
typedef struct stringnode {
cstring str; // pointer to a string on the heap
struct stringnode* next; // collision resolution pointer to next node
hashcode_t hashnum; // cached hash number
cstring tag; // internal static string
// - tag field to verify class membership
} stringnode;
////
// stringtable - struct
//
// Structure that consists of a pointer to the array of hash headers
// and a dimension. Also, a pointer to an internal static string
// identifier so that an assertion can be used to check the validity
// of the node. Also, the number of elements in the table is cached
// in this node in order to determine when the table needs
// doubling. Other fields if needed.
//
typedef struct stringtable {
stringnode_ref *headers; // array of hash headers
int dim; // dimension of header array
int size; // number of elements in the hash table
cstring tag; // internal static string
// - tag field to verify class membership
} stringtable;
/******************** Internal Static Strings - Tags ******************/
static char* stringnode_tag = "struct stringnode";
static char* stringtable_tag = "struct stringtable";
/****************** Type Checking-Assertion Functions *****************/
////
// is_stringnode
//
// Safety check for the RTTI (run time type identification). Usually
// called within an assert() of a function using a string node.
//
bool is_stringnode (void *object) {
stringnode_ref node = (stringnode_ref) object;
return node != NULL && node->tag == stringnode_tag;
}
////
// is_stringtable
//
// Safety check for the RTTI (run time type identification). Usually
// called within an assert() of a function using a string table.
//
bool is_stringtable (void *object) {
stringtable_ref table = (stringtable_ref) object;
return table != NULL && table->tag == stringtable_tag;
}
/******************** Constructors-Destructors ************************/
////
// new_stringnode - Constructor
//
// Creates a new string node and returns its handle.
//
stringnode_ref new_stringnode (hashcode_t num, cstring string) {
assert (string != NULL);
size_t sn_size = sizeof (stringnode);
stringnode_ref node = malloc (sn_size);
node->str = strdup (string); // contains a call to malloc()
assert (node->str != NULL); // null check
node->next = NULL;
node->hashnum = num;
node->tag = stringnode_tag; // internal static string
DEBUGF ('f', "malloc (%d) = %p-> hash number: %d: %p->\"%s\"\n",
sn_size, node, node->hashnum, node->str, node->str);
return node;
}
////
// new_stringtable - Constructor
//
// Creates a new string table and returns its handle. Uses as its
// initial capacity some arbitrary odd number, such as 31.
//
stringtable_ref new_stringtable (void) {
size_t st_size = sizeof (stringtable);
stringtable_ref hashtable = malloc (st_size);
int n = 31; // specified to be one less than a power of two
hashtable->headers = calloc (n, sizeof (stringnode_ref) );
hashtable->dim = n;
hashtable->size = 0; // empty
hashtable->tag = stringtable_tag; // internal static string
DEBUGF ('f', "malloc (%d) = %p-> size: %d %p-> dim: %d\n",
st_size, hashtable, hashtable->size, hashtable->headers,
hashtable->dim);
return hashtable;
}
////
// delete_stringnode - Destructor
//
// Uses free(3) to delete the string node. Implementation of the
// function is optional as it is a helper function to
// delete_stringtable().
//
void delete_stringnode (stringnode_ref node) {
if (node == NULL)
errprintf ("%s: %s: %s: %s: %s\n", get_execname(), "Error",
"stringtable.c", "delete_stringnode()",
"null string node reference");
assert (is_stringnode(node) );
free (node->str);
node->str = NULL;
node->next = NULL;
free (node);
node = NULL;
}
////
// delete_stringtable - Destructor
//
// Dismantles the entire hash table and uses free(3) to delete all
// internal nodes. Implementation of the function is optional.
//
void delete_stringtable (stringtable_ref table) {
if (table == NULL)
errprintf ("%s: %s: %s: %s: %s\n", get_execname(), "Error",
"stringtable.c", "delete_stringtable()",
"null string table reference");
assert (is_stringtable(table) );
stringnode_ref curr;
stringnode_ref temp;
int i;
for (i = 0; i < table->dim; ++i) {
curr = table->headers[i];
while (curr != NULL) {
temp = curr->next;
delete_stringnode (curr);
curr = temp;
}
table->headers[i] = NULL;
}
free (table->headers);
table->headers = NULL;
free (table);
table = NULL;
}
/******************** Miscellaneous-Helper Functions ******************/
////
// strhash
//
// Returns a hashcode for a given string. Uses a bit shift.
//
hashcode_t strhash (cstring string) {
hashcode_t hashcode = 0;
assert (string != NULL);
for (;;) {
hashcode_t byte = (unsigned char) *string++;
if (byte == '\0') break;
hashcode = (hashcode << 5) - hashcode + byte;
};
return hashcode;
}
////
// find
//
// A helper function to find the handle of a string node containing
// the given string.
//
stringnode_ref find (stringtable_ref table, cstring string) {
assert (is_stringtable (table) );
// print error message if the string table reference is null
if (table == NULL)
errprintf ("%s: %s: %s: %s: %s\n", get_execname(), "Error",
"stringtable.c", "find()",
"null string table reference");
// print error message if the character pointer (cstring) is null
if (string == NULL)
errprintf ("%s: %s: %s: %s: %s\n", get_execname(), "Error",
"stringtable.c", "find()", "null pointer");
stringnode_ref curr;
int i;
for (i = 0; i < table->dim; ++i) {
curr = table->headers[i];
if (curr != NULL) {
if (0 == strcmp (string, curr->str) ) break;
curr = curr->next;
while (curr != NULL) {
if (0 == strcmp (string, curr->str) ) break;
curr = curr->next;
}
}
}
return curr;
}
/********************* Access Functions *******************************/
////
// debugdump_stringtable
//
// Dumps out the hash table in debug format:
// 24 348883689 "hello"
// 4294967295 "there"
// 92 338729983 "67"
//
// In other words, print the hash header number in %8d format
// followed by spaces, then the hash number (%12u), and then the
// strings in %s format inside quotes in a column. In the above
// example, the two strings in bucket 24 have collided. It will
// always be true that the second number modulo the size of the hash
// table will be equal to the first number.
//
void debugdump_stringtable (stringtable_ref table, FILE* outfile) {
assert (is_stringtable (table) );
// print error message if the string table reference is null
if (table == NULL)
errprintf ("%s: %s: %s: %s: %s\n", get_execname(), "Error",
"stringtable.c", "debugdump_stringtable()",
"null string table reference");
// print error message if the FILE reference is null
if (outfile == NULL)
errprintf ("%s: %s: %s: %s\n", "Error", "stringtable.c",
"debugdump_stringtable()",
"null FILE reference");
int length = table->dim;
int i;
for (i = 0; i < length; ++i) {
stringnode_ref curr = table->headers[i];
if (curr != NULL) {
xfprintf (outfile, "%8d %12u \"%s\"\n",
i, curr->hashnum, curr->str);
curr = curr->next;
while (curr != NULL) {
xfprintf (outfile, " %12u \"%s\"\n",
curr->hashnum, curr->str);
curr = curr->next;
}
}
}
}
////
// peek_stringtable
//
// Returns a pointer to a character string, such as may be used for
// printing.
//
cstring peek_stringtable (stringnode_ref node) {
assert (is_stringnode (node) );
// print error message if the string node reference is null
if (node == NULL)
errprintf ("%s: %s: %s: %s: %s\n", get_execname(), "Error",
"stringtable.c", "peek_stringtable()",
"null string node reference");
return node->str;
}
////
// hashcode_stringtable
//
// Returns the cached hash number associated with this string node.
// Does not recompute the number.
//
hashcode_t hashcode_stringtable (stringnode_ref node) {
assert (is_stringnode (node) );
// print error message if the string node reference is null
if (node == NULL)
errprintf ("%s: %s: %s: %s: %s\n", get_execname(), "Error",
"stringtable.c", "hashcode_stringtable()",
"null string node reference");
return node->hashnum;
}
/********************** Manipulation Functions ************************/
////
// double_capacity
//
// Doubles the capacity of the header array in the string table.
// Also recomputes the modulo and moves the pointers to their
// correct locations with respect to the new size of the array.
// Array size should have the form of one minus a power of two.
// Since array size starts at 31 = 2^5 - 1, the doubled array should
// be no less than 63 = 2^6 - 1.
//
void double_capacity (stringtable_ref table) {
assert (is_stringtable (table) );
// print error message if the string table reference is null
if (table == NULL)
errprintf ("%s: %s: %s: %s: %s\n", get_execname(), "Error",
"stringtable.c", "double_capacity()",
"null string table reference");
int length = table->dim; // original hash header array dimension
int n = ( (length + 1) * 2) - 1; // new hash header array dimension
stringnode_ref *arr = calloc (n, sizeof (stringnode_ref) );
stringnode_ref curr;
stringnode_ref temp;
int i;
for (i = 0; i < length; ++i) {
curr = table->headers[i];
while (curr != NULL) {
hashcode_t place = curr->hashnum % n; // array placement
if (arr[place] == NULL) { arr[place] = curr; }
else {
temp = arr[place];
while (temp->next != NULL) temp = temp->next;
temp->next = curr;
}
temp = curr;
curr = curr->next;
temp->next = NULL;
}
table->headers[i] = NULL;
}
free (table->headers);
table->headers = arr;
table->dim = n;
curr = NULL;
temp = NULL;
arr = NULL;
}
////
// intern_stringtable
//
// Interns the argument string into the string table and returns a
// pointer to the internal node. The client is honor-bound not to
// preserve this pointer beyond the life of the hash table. An
// assertion is used in other funtions to verify membership. There
// is no difference between insert and lookup. If the key is not
// found, it is inserted then returned. If it is found, the
// existing node reference is returned.
//
// The argument string is copied onto the heap with strdup(3), since
// the second argument is a loan argument, not a transfer of
// ownership argument. You may of course use malloc(3) and
// strcpy(3) instead. The hash number is also cached in the node to
// avoid having to recompute it.
//
// Also takes care of collision resolution by separate chaining.
// Doubling the array header size when thestring table's loading
// factor exceeds 0.75 (number of nodes / number of headers).
//
stringnode_ref intern_stringtable (stringtable_ref table,
cstring string) {
assert (is_stringtable (table) );
// print error message if the string table reference is null
if (table == NULL)
errprintf ("%s: %s: %s: %s: %s\n", get_execname(), "Error",
"stringtable.c", "intern_stringtable()",
"null string table reference");
// print error message if the character pointer (cstring) is null
if (string == NULL)
errprintf ("%s: %s: %s: %s: %s\n", get_execname(), "Error",
"stringtable.c", "intern_stringtable()",
"null cstring");
stringnode_ref node = new_stringnode (strhash (string), string);
hashcode_t place = node->hashnum % table->dim; // array placement
stringnode_ref curr = table->headers[place];
if (curr != NULL) {
// already exists so free new node and return existing node
if (strcmp (curr->str, node->str) == 0) {
delete_stringnode (node);
node = NULL;
return curr;
}
while (curr->next != NULL) {
curr = curr->next;
// already exists so free new node a nd return existing node
if (strcmp (curr->str, node->str) == 0) {
delete_stringnode (node);
node = NULL;
return curr;
}
}
// insert node
curr->next = node;
++table->size;
}
// insert node
else {
table->headers[place] = node; ++table->size; }
curr = NULL;
// maintain collision resolution
double numNodes = table->size;
double numHeads = table->dim;
if ( (numNodes / numHeads) > 0.75) double_capacity (table);
return node;
}
|
C
|
#include <errno.h>
#include <stdio.h>
#include <fcntl.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc, char** argv) {
int n;
int m;
int fd;
int sockfd;
int portno;
char* retvalue;
char buffer[256];
//man 7 ip
//man unix
struct sockaddr_in serv_addr;
if(argc != 3) {
fprintf(stderr, "Usage: %s <address> <port>\n", argv[0]);
exit(1);
}
portno = atoi(argv[2]);
//man socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0) {
fprintf(stderr, "ERROR: %s\n", strerror(errno));
exit(1);
}
memset((char*) &serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
serv_addr.sin_port = htons(portno);
//man connect
if(connect(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0) {
fprintf(stderr, "ERROR: %s\n", strerror(errno));
exit(1);
}
printf("Digite o arquivo que deseja baixar: ");
memset(buffer, 0, sizeof(buffer));
do {
retvalue = fgets(buffer, sizeof(buffer), stdin);
} while(retvalue == NULL);
//man send
if(send(sockfd, buffer, strlen(buffer), 0) < 0) {
fprintf(stderr, "ERROR: %s\n", strerror(errno));
exit(1);
}
buffer[strlen(buffer) - 1] = 0;
fd = open(buffer, O_WRONLY | O_CREAT, 0755);
if(fd < 0) {
fprintf(stderr, "ERROR: %s\n", strerror(errno));
exit(1);
}
while(1) {
memset(buffer, 0, sizeof(buffer));
n = recv(sockfd, buffer, sizeof(buffer), 0);
if(n < 0) {
fprintf(stderr, "ERROR: %s\n", strerror(errno));
exit(1);
} else if(n == 0) {
close(fd);
break;
} else {
m = write(fd, buffer, n);
while(m < n) {
m += write(fd, buffer + m, n - m);
}
}
}
printf("Arquivo baixado com sucesso.\n");
close(sockfd);
return 0;
}
|
C
|
/// \file
/// Utilities for working with timespecs.
#pragma once
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#ifdef __cplusplus
extern "C" {
#endif
/// Return a timespec with zero seconds and zero nanoseconds.
struct timespec timespec_null();
/// Add \p rhs to \p lhs in-place.
void timespec_iadd(struct timespec * lhs, struct timespec const * rhs);
/// Subtract \p rhs from \p lhs in-place.
void timespec_isub(struct timespec * lhs, struct timespec const * rhs);
/// Multiply \p lhs by \p rhs in-place.
void timespec_imul(struct timespec * lhs, struct timespec * rhs);
/// Divide \p lhs by \p rhs in-place.
void timespec_idiv(struct timespec * lhs, long divisor);
/// Calculate the difference between \p start and \p stop and store the result in \p duration.
void timespec_duration(struct timespec * duration, struct timespec const * start,
struct timespec const * stop);
/// Return `true` if \p lhs is equal to \p rhs and return `false` otherwise.
bool timespec_is_equal(const struct timespec * lhs, const struct timespec * rhs);
/// Return `true` if \p lhs is less than \p rhs and return `false` otherwise.
bool timespec_is_less_than(const struct timespec * lhs, const struct timespec * rhs);
/// Compare two timespecs.
/// \return An integer representing the result of the comparison:
/// - -1 If \p lhs is less than \p rhs
/// - 0 If \p lhs is equal to \p rhs
/// - 1 If \p lhs is greather than \p rhs
int timespec_compare(void const * lhs, void const * rhs);
/// Convert \p t to a double in units of seconds.
double timespec_to_double_s(struct timespec * t);
/// Convert \p t to a double in units of nanoseconds.
double timespec_to_double_ns(struct timespec * t);
/// Convert \p d assuming its in units of seconds to a timespec.
struct timespec timespec_from_double_s(double d);
/// Convert \p d assuming its in units of nanoseconds to a timespec.
struct timespec timespec_from_double_ns(double d);
#ifdef __cplusplus
} // extern "C"
#endif
|
C
|
/* Author: lab
* Partner(s) Name:
* Lab Section:
* Assignment: Lab 10 Exercise 4
* Exercise Description: [optional - include for your own benefit]
*
* I acknowledge all content contained herein, excluding template or example
* code, is my own original work
*/
#include "timer.h"
#include <avr/io.h>
#ifdef _SIMULATE_
#include "simAVRHeader.h"
#endif
unsigned char T,L,S;
unsigned long N = 2;
enum BL_States { BL_SMStart, LedOff, LedOn } BL_State;
void TickFct_BlinkLed()
{
switch(BL_State)
{
case BL_SMStart:
BL_State = LedOff;
break;
case LedOff:
BL_State = LedOn;
break;
case LedOn:
BL_State = LedOff;
break;
}
switch(BL_State)
{
case BL_SMStart:
break;
case LedOff:
L = 0;
break;
case LedOn:
L = 0x08;
break;
}
}
enum N_States { N_start, inc, dec} N_state;
void Note()
{
//unsigned char tmpA2 = ~PINA & 0x02;
//unsigned char tmpA1 = ~PINA & 0x01;
switch(N_state)
{
case N_start:
if((~PINA & 0x01) == 0x01){
N_state = inc;
N++;
}
else if((~PINA & 0x02) == 0x02){
// N_state = dec;
if((N - 1) < 1){N = 1;}
else{N--;}
N_state = dec;
}
else{N_state = N_start;}
break;
case inc:
if((~PINA & 0x01) == 0x01){N_state = inc;}
else{N_state = N_start;}
break;
case dec:
if((~PINA & 0x02) == 0x02){N_state = dec;}
else{N_state = N_start;}
break;
default:
break;
}
switch(N_state)
{
case N_start:
break;
case inc:
break;
case dec:
break;
}
}
enum S_States { start, Off, On } State;
void Speaker()
{
unsigned char tmpA = ~PINA & 0x04;
switch(State)
{
case start:
State = Off;
break;
case Off:
if((tmpA))
{State = On;}
//S = 0x10;}
else{State = Off;}
break;
case On:
State = Off;
break;
}
switch(State)
{
case start:
break;
case Off:
S = 0;
break;
case On:
S = 0x10;
break;
}
}
enum States { Start, Out} state;
void Combine(){
//unsigned char tmpB = 0x00;
switch(state)
{case Start:
state = Out;
break;
case Out:
break;
}
switch(state)
{case Start:
//state = Out;
break;
case Out:
PORTB = T | L | S;
}
}
enum TL_States { TL_SMStart, T0, T1, T2 } TL_State;
void TickFct_ThreeLeds() {
//... // Standard switch statements for SM
switch(TL_State)
{
case TL_SMStart:
TL_State = T0;
break;
case T0:
TL_State = T1;
break;
case T1:
TL_State = T2;
break;
case T2:
TL_State = T0;
break;
}
switch(TL_State)
{
case TL_SMStart:
break;
case T0:
T = 0x01;
break;
case T1:
T = 0x02;
break;
case T2:
T = 0x04;
break;
}
}
int main(void) {
DDRB = 0xFF; PORTB = 0x00;
DDRA = 0x00; PORTA = 0xFF;
// PORTB = 0; // Init outputs
unsigned long BL_elapsedTime = 1000;
unsigned long S_elapsedTime = N;
unsigned long TL_elapsedTime = 300;
//unsigned long N_elapsedTime = 1;
const unsigned long timerPeriod = N;
//unsigned char tmpA = ~PINA & 0x01;
TimerSet(timerPeriod);
TimerOn();
BL_State = BL_SMStart;
TL_State = TL_SMStart;
state = Start;
State = start;
N_state = N_start;
while (1) {
if(BL_elapsedTime >= 1000)
{TickFct_BlinkLed();
BL_elapsedTime = 0;
}
if(S_elapsedTime >= N)
{
Speaker(); // Combine();
S_elapsedTime = 0;
}
if(TL_elapsedTime >= 300) // Tick the BlinkLed synchSM
{
TickFct_ThreeLeds();
TL_elapsedTime = 0;
}
// Note();
Combine();
Note();
while (!TimerFlag){} // Wait for timer period
TimerFlag = 0;
BL_elapsedTime += timerPeriod;
S_elapsedTime += timerPeriod;
TL_elapsedTime += timerPeriod;
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
long int b= 0, octal, place = 1, r;
int OCT[] = {0, 1, 10, 11, 100, 101, 110, 111};
printf("Enter the octal Value:\n");
scanf("%ld",&octal);
do
{
r = octal % 10;
b += (OCT[r]*place);
octal = octal / 10;
place *= 1000;
}
while(octal > 0);
printf("Binary Value is %ld", b);
}
|
C
|
/*
** EPITECH PROJECT, 2018
** PSU_zappy_2017
** File description:
** map_create.c
*/
#include "map.h"
void empty_tile(tile_t *tile, size_t food)
{
(*tile)[FOOD] = food;
(*tile)[LINEMATE] = 0;
(*tile)[DERAUMERE] = 0;
(*tile)[SIBUR] = 0;
(*tile)[MENDIANE] = 0;
(*tile)[PHIRAS] = 0;
(*tile)[THYSTAME] = 0;
(*tile)[PLAYER] = 0;
}
static void fill_tile(tile_t *tile)
{
(*tile)[FOOD] = (size_t) (random() % MAX_FOOD());
(*tile)[LINEMATE] = (size_t) (random() % MAX_LINEMATE());
(*tile)[DERAUMERE] = (size_t) (random() % MAX_DERAUMERE());
(*tile)[SIBUR] = (size_t) (random() % MAX_SIBUR());
(*tile)[MENDIANE] = (size_t) (random() % MAX_MENDIANE());
(*tile)[PHIRAS] = (size_t) (random() % MAX_PHIRAS());
(*tile)[THYSTAME] = (size_t) (random() % MAX_THYSTAME());
(*tile)[PLAYER] = 0;
}
static void fill_tiles(map_t *map, char fill)
{
for (size_t y = 0; y < map->height; ++y) {
map->tiles[y] = map->tiles[0] + map->width * y;
for (size_t x = 0; x < map->width; ++x)
(fill) ? fill_tile(map->tiles[y] + x) :
empty_tile(map->tiles[y] + x, 0);
}
}
static uint8_t malloc_map(map_t *map)
{
map->tiles = malloc(sizeof(tile_t *) * map->height);
if (!map->tiles) {
dprintf(2, "Invalid malloc\n");
return (0);
}
map->tiles[0] = calloc(sizeof(tile_t) * map->height
* (map->width + 0), sizeof(tile_t));
if (!map->tiles[0]) {
map_free(map);
dprintf(2, "Invalid malloc\n");
return (0);
}
return (1);
}
map_t *map_create(size_t width, size_t height, char fill)
{
map_t *map = malloc(sizeof(map_t));
if (!map) {
dprintf(2, "Invalid malloc\n");
return (NULL);
}
map->width = width;
map->height = height;
map->seed = (size_t) time(NULL);
srandom((unsigned int) map->seed);
if (!malloc_map(map))
return (NULL);
fill_tiles(map, fill);
return (map);
}
|
C
|
#include<stdio.h>
void main(){
int c;
int blank=0;
int tab=0;
int newline=0;
while((c=getchar())!=EOF){
if(c==' ')
blank++;
if(c=='\t')
tab++;
if(c=='\n')
newline++;
}
printf("no of blanks %d\n",blank);
printf("no of tabs %d\n",tab);
printf("no of new lines %d\n",newline);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.