language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include "holberton.h"
/**
* _strncat - concatenates only n bytes of source into destiny
*
* @dest: destiny string
*
* @src: source string
*
* @n: number of bytes to be concatenate
*
* Return: destiny
*
*/
char *_strncat(char *dest, char *src, int n)
{
int a;
int b;
for (a = 0; dest[a] != 0; a++)
{
}
for (b = 0; b < a && src[b] != 0; b++)
{
if (!(b == n))
{
dest[a + b] = src[b];
}
}
dest[a + b] = '\0';
return (dest);
}
|
C
|
/** \brief Realiza la suma de dos numeros y devuelve el resultado
* \param x Es un numero a ser ingresado
* \param y Es un numero a ser ingresado
* \return El resultado de la suma
*
*/
float suma(float x, float y);
/** \brief Realiza la resta de dos numeros y devuelve el resultado
* \param x Es un numero a ser ingresado
* \param y Es un numero a ser ingresado
* \return El resultado de la resta
*
*/
float resta(float x, float y);
/** \brief Realiza la division de dos numeros y devuelve el resultado
* \param x Es un numero a ser ingresado
* \param y Es un numero a ser ingresado
* \return El resultado de la division
*
*/
float division(float x, float y);
/** \brief Realiza la multiplicacion de dos numeros y devuelve el resultado
* \param x Es un numero a ser ingresado
* \param y Es un numero a ser ingresado
* \return El resultado de la multiplicacion
*
*/
float multiplicacion(float x, float y);
/** \brief Calcula el factorial de un numero y devuelve el resultado o un mensaje de error
* \param x Es un numero a ser ingresado
* \return resultado Resultado es 0 si el numero ingresado no es entero y positivo. Sino, devuelve el factorial del numero ingresado.
*
*/
int factorial(float x);
|
C
|
#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
#define MAXLINE 80
void escape(char s[] , char t[]);
void rev_escape(char s[] , char t[]);
//unsigned pow(unsigned a, unsigned base);
/* prunsigned longest input line */
char line[MAXLINE];
int main() {
char v[10000];
char s[10000];
int c;
int i =0;
while((c=getchar()) != EOF && i != 10000) {
v[i++] = c;
}
v[i] = '\0';
escape(s,v);
printf("this is the string %s \n", s);
rev_escape(v,s);
printf("this is the string %s \n", v);
return 0;
}
void escape(char s[], char t[]) {
int i;
int j;
for(j = i =0; t[i] != '\0';i++) {
switch(t[i]) {
case '\n':
s[j++] = '\\';
s[j++] = 'n';
break;
case '\t':
s[j++] = '\\';
s[j++] = 't';
s[j] = 'n';
break;
default:
s[j++] = t[i];
break;
}
}
s[j] = '\0';
}
void rev_escape(char s[], char t[]) {
int i;
int j;
for(j = i =0; t[i] != '\0';i++) {
switch(t[i]) {
case '\\':
switch (t[i+1]) {
case 'n':
s[j++] = '\n';
i++;
break;
case 't':
s[j++] = '\t';
i++;
break;
default:
s[j++] = t[i];
break;
}
break;
default:
s[j++] = t[i];
break;
}
}
s[j] = '\0';
}
|
C
|
#include <stdlib.h>
//#include <time.h>
#include "screen.h"
#include <signal.h>
#include "sound.h"
#include <stdio.h>
#include "comm.h"
int main(int argc, char **argv){
if(argc>1){ //if the user has given some command line argument
printf("Test tone generator\n");
int fR, fL, ch;
float duration;
printf("No. of channels (1 or 2): ");
scanf("%d", &ch);
if(ch==1){
printf("Normal frequency: ");
scanf("%d", &fL);
}
else if(ch==2){
printf("Give me left and right frequency: ");
scanf("%d %d", &fL, &fR);
}
else{
printf("Wrong num of channels");
return 1;
}
printf("Duration of sound: ");
scanf("%f", &duration);
testTone(ch, fL, fR, duration);
return 0;
}
FILE *f;
short sd[RATE];
for(;;){
int ret = system(RCMD);
if (ret == SIGINT) break;
f = fopen("test.wav", "r");
if(f==NULL){
printf("cannot open the file\n");
return 1;
}
clearscreen();
struct WAVHDR hdr;
fread(&hdr, sizeof(hdr), 1, f); // read WAV header
fread(&sd, sizeof(sd), 1, f); //read wav data
fclose(f);
displayWAVHDR(hdr);
displayWAVDATA(sd);
sendDATA(sd);
}
reset_color();
//getchar();
}
|
C
|
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int getMortarLocation(double* loc_val)
{
FILE *fp = fopen("g_result.txt", "r");
char buf[256];
char *array[20];
while (fgets(buf, sizeof(buf), fp))
{
if (strstr(buf, "$GPGLL"))
{
int count = 0;
char *token;
token = strtok(buf, ",");
while (token != NULL)
{
array[count++] = token;
token = strtok(NULL, ",");
if (count == 20)
break;
}
double tmp = 0;
double lat = atof(array[1]);
tmp = (double)((int)lat / 100);
lat = lat / 100;
lat = lat - tmp;
lat = lat*100.0;
lat = lat / 60.0;
lat = lat + tmp;
if (!strcmp(array[2],"S"))
lat = -lat;
loc_val[2] = lat;
double lon = atof(array[3]);
tmp = (double)((int)lon / 100);
lon = lon / 100;
lon = lon - tmp;
lon = lon*100.0;
lon = lon / 60.0;
lon = lon + tmp;
if (!strcmp(array[4],"W"))
lon = -lon;
loc_val[3] = lon;
printf("Latitude : %9.6lf\n",lat);
printf("Longtitude : %9.6lf\n", lon);
}
else if (strstr(buf, "$GPRMC"))
{
int count = 0;
char *token;
token = strtok(buf, ",");
while (token != NULL)
{
array[count++] = token;
token = strtok(NULL, ",");
if (count == 20)
break;
}
double tmp = 0;
double lat = atof(array[3]);
tmp = (double)((int)lat / 100);
lat = lat / 100;
lat = lat - tmp;
lat = lat*100.0;
lat = lat / 60.0;
lat = lat + tmp;
if (!strcmp(array[4],"S"))
lat = -lat;
loc_val[2] = lat;
double lon = atof(array[5]);
tmp = (double)((int)lon / 100);
lon = lon / 100;
lon = lon - tmp;
lon = lon*100.0;
lon = lon / 60.0;
lon = lon + tmp;
if (!strcmp(array[6],"W"))
lon = -lon;
loc_val[3] = lon;
printf("Latitude : %9.6lf\n",lat);
printf("Longtitude : %9.6lf\n", lon);
}
}
fclose(fp);
return 0;
}
|
C
|
/*
* 123.cpp
*
* Created on: 2010-12-18
* Author: 378073652
*/
int main(){
char a[30000],b[30000];
int c[10000],d[10000],e[1005],la,lb,i,j,sa=0,sb=0,max=0;
for(i=0;i<=1004;i++) e[i]=0;
cin>>a;
cin>>b;
la=strlen(a);
lb=strlen(b);
c[0]=atof(a);
for(i=0;i<la;i++){
if(a[i]==',')
{sa++;c[sa]=atof(a+i+1);}
}
d[0]=atof(b);
for(i=0;i<lb;i++){
if(b[i]==',')
{sb++;d[sb]=atof(b+i+1);}
}
for(i=0;i<=sa;i++){
for(j=c[i];j<d[i];j++){
e[j]=e[j]+1;
}
}
for(i=0;i<1004;i++){
if(e[i]>max) max=e[i];
}
cout<<sa+1<<" "<<max;
}
|
C
|
#ifndef _BTREE_H_
# define _BTREE_H_
typedef struct btree
{
struct btree *left;
struct btree *right;
void *item;
} btree_t;
btree_t *btree_create_node(void *item);
void btree_apply_prefix(btree_t *root, int (*applyf)(void *));
void btree_apply_infix(btree_t *root, int (*applyf)(void *));
void btree_apply_suffix(btree_t *root, int (*applyf)(void *));
void btree_insert_data(btree_t **root, void *item, int (*cmpf)());
void *btree_search_item(btree_t const *root,
void const *data_ref, int (*cmpf)());
# endif /* _BTREE_H_ */
|
C
|
#pragma once
#include <ksmooth/smoother.h>
typedef enum { KSMOOTH_KERNEL_GAUSSIAN } ksmooth_kernel;
typedef enum { KSMOOTH_OK, KSMOOTH_INVALID_BOUNDS } ksmooth_status;
// create new Nadaraya-Watson smoother
ksmooth_nw_smoother_t ksmooth_new_nw_smoother(ksmooth_kernel k);
// set concurrency level for smoother. If not called, default is number of cores on machine.
void ksmooth_set_concurrency(void* smoother);
// free resources associated with Nadaraya-Watson smoother
void ksmooth_destroy_nw_smoother(ksmooth_nw_smoother_t* s);
// smooth array of floats with given size and bandwidth. Returns 0 if OK.
int ksmooth_nw_fsmooth(ksmooth_nw_smoother_t* s, float* input, float* output, size_t size, long long bandwidth);
// smooth array of doubles with given size and bandwidth. Returns 0 if OK.
int ksmooth_nw_dsmooth(ksmooth_nw_smoother_t* s, double* input, double* output, size_t size, long long bandwidth);
|
C
|
/**
* This is the solution to the PlusMinus problem in Algorithms domain of HackerRank
* Question can be found here : https://www.hackerrank.com/challenges/plus-minus
*/
#include<stdio.h>
int main ()
{
int n;
scanf("%d",&n);
int arr[n],i;
float a,b,c,p=0,ne=0,z=0;
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
if(arr[i]<0)
ne++;
else if(arr[i]>0)
p++;
else if(arr[i]==0)
z++;
}
a=p/n;
b=ne/n;
c=z/n;
printf("%f\n%f\n%f",a,b,c);
}
|
C
|
#pragma once
#include "Vector3.h"
__declspec(align(16)) class Face
{
public:
DEFINE_NEW_DELETE_ALIGNED
Face(void);
Face(const int indices[3], const Vector3& faceNormal);
Face(int i0, int i1, int i2, const Vector3& faceNormal);
inline Vector3 GetFaceNormal(void) const
{
return faceNormal;
}
inline const int* GetIndices(void) const
{
return indices;
}
inline void SetFaceNormal(const Vector3& normal)
{
this->faceNormal = normal;
}
inline void SetIndex(int i, int value)
{
this->indices[i] = value;
}
private:
Vector3 faceNormal;
int indices[3];
};
|
C
|
/*Naresh i Technologies For Any Doubts contact Mr.Balu Email:balu.bhig@gmail.com */
#include <stdio.h>
#include <conio.h>
/*Naresh i Technologies For Any Doubts contact Mr.Balu Email:balu.bhig@gmail.com */
#define size 10
int main()
{
int arr[size];
int i,m;
int min(int*);
clrscr();
printf("\nEnter %d Values: ",size);
for(i=0;i<size;i++)
scanf("%d",&arr[i]);
/*Naresh i Technologies For Any Doubts contact Mr.Balu Email:balu.bhig@gmail.com */
m=min(arr);
printf("\nMin Value of List:%d",m);
getch();
return 0;
}
int min(int *arr)
{
int r,i;
r=arr[0];
for(i=1;i<size;i++)
/*Naresh i Technologies For Any Doubts contact Mr.Balu Email:balu.bhig@gmail.com */
{
if(arr[i]<r)
r=arr[i];
}
return r;
}
/*Naresh i Technologies For Any Doubts contact Mr.Balu Email:balu.bhig@gmail.com */
|
C
|
/* COMP 211, Spring 2019
* Homework 8
*
* Queues
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "comp211.h"
#include "hw8.h"
/* Make a non-linear collection of nodes.
*
* Given the string s, first make a linear sequence of qnodes corresponding to
* the sequence s. Then choose some 0 <= i <= j < strlen(s) and make the
* index-j node point to the index-i node.
*/
char* rand_string(int n) {
char* s = malloc(n*sizeof(char) + 1);
for (int i=0; i<n; ++i) {
s[i] = 'a' + rand()%26;
}
s[n] = '\0';
return s;
}
/* from_string(s) is a linear sequence of nodes that represents the characters
* in s.
*/
qnode* from_string(char s[]) {
qnode hd = {.key = '\0', .next = NULL};
qnode* p = &hd;
for (int i=0; i<strlen(s); ++i) {
qnode* q = malloc(sizeof(qnode));
q->key = s[i];
q->next = NULL;
p->next = q;
p = p->next;
}
return hd.next;
}
qnode* make_circular(char s[], int i, int j) {
qnode* q = from_string(s);
qnode* back_node = q;
for (int k=0; k<i; ++k) back_node = back_node->next;
qnode* front_node = back_node;
for (int k=i; k<j; ++k) front_node = front_node->next;
front_node->next = back_node;
return q;
}
void test_is_linear(char s[]) {
qnode* q = from_string(s);
dotestmsg(is_linear(q), "is_linear(%s)", s);
}
void test_not_linear(char s[], int i, int j) {
qnode* q = make_circular(s, i, j);
dotestmsg(!is_linear(q), "!is_linear(%s), %d -> %d", s, j, i);
}
/* Test queue operations.
*
* ops is a sequence of alphabetic characters and '-'. An empty queue q is
* created, and then for each character c in ops:
*
* - if c = '-', q is dequeued.
* - otherwise, c is enqueued.
*
* The contents of q are then compared to exp.
*/
void test_queue(char ops[], char exp[]) {
int n_ops = strlen(ops);
queue q = create();
for (int i=0; i<n_ops; ++i) {
if (ops[i] == '-') dequeue(&q);
else enqueue(&q, ops[i]);
}
int n = strlen(exp);
char cs[n+1];
as_array(&q, cs);
fprintf(stderr, "\n");
dotestmsg(is_empty(&q) == (n == 0), "is_empty(%s)", ops);
dotestmsg(size(&q) == n, "size(%s) = %d", ops, n)
dotestmsg(strncmp(cs, exp, n) == 0, "%s -> %s; got %s", ops, exp, cs);
fprintf(stderr, "\n");
}
#define N_OPS 16
#define N_RAND_TESTS 10
int main() {
{
test_is_linear("");
test_is_linear("a");
test_is_linear("ab");
for (int i=5; i<20; ++i) test_is_linear(rand_string(i));
fprintf(stderr, "\n");
}
{
test_not_linear("a", 0, 0);
test_not_linear("ab", 0, 0);
test_not_linear("ab", 0, 1);
test_not_linear("ab", 1, 1);
test_not_linear("abc", 0, 0);
test_not_linear("abc", 0, 1);
test_not_linear("abc", 1, 1);
test_not_linear("abc", 0, 2);
test_not_linear("abc", 1, 2);
test_not_linear("abc", 2, 2);
}
{
for (int i=0; i<N_RAND_TESTS; ++i) {
int n = 5 + rand()%20;
char* s = rand_string(n);
int k = rand()%n;
int j = rand()%(k+1);
test_not_linear(s, j, k);
}
fprintf(stderr, "\n");
}
{
test_queue("", "");
test_queue("a", "a");
test_queue("a-", "");
test_queue("ab", "ab");
test_queue("ab-", "b");
test_queue("ab--", "");
test_queue("a-b", "b");
test_queue("a-b-", "");
test_queue("abbc", "abbc");
test_queue("abbc-", "bbc");
test_queue("abbc--", "bc");
test_queue("abbc---", "c");
test_queue("abbc----", "");
test_queue("ab-bc", "bbc");
test_queue("a-b-bc", "bc");
test_queue("ab--bc", "bc");
/* This loop performs N_RAND_TESTS tests. Each test constructs an
* operation sequence of length N_OPS. Each character of the
* operation sequence is either '-' (probability 50%) or an alphabetic
* character. '-' is added to the operation sequence only if the
* queue represented by the sequence so far is non-empty.
*/
for (int j=0; j<N_RAND_TESTS; ++j) {
char ops[N_OPS + 1] = {'\0'};
char exp[N_OPS + 1] = {'\0'};
int size = 0;
int front = 0;
int back = 0;
for (int i=0; i<N_OPS; ++i) {
if (rand()%2 == 0 && size > 0) {
ops[i] = '-';
size = size - 1;
front = front + 1;
} else {
ops[i] = 'a' + (rand()%26);
size = size + 1;
exp[back] = ops[i];
back = back + 1;
}
}
for (int i=front; i<back; ++i) {
exp[i-front] = exp[i];
}
exp[back-front] = '\0';
test_queue(ops, exp);
}
}
return 0;
}
|
C
|
#include <stdio.h>
//逻辑与 &&
//逻辑或 ||
//逻辑非 !
int main(void)
{
int score;
int age;
printf("please input a number: \n");
scanf("%d %d", &score, &age);
//逻辑或 只要有一个条件成立 整个表达式就为真
if (score < 0 || score > 100)
{
printf("The score is out of range\n");
}
/*
* 判断年龄在13至17岁之内?
* age >= 13 && age <= 17
*/
if (age >= 13 && age <= 17)
{
printf("年龄在13至17岁之间\n");
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "IO_Map.h"
#include "PDD/UART_PDD.h"
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
#define SERIAL_BASE_UART_BASE_PTR (UART1_BASE_PTR) /**< which UART to use */
//#define SERIAL_BASE_UART_BASE_PTR (UART3_BASE_PTR) /**< which UART to use */
/*!
* Semaphore used to protect UART TX FIFO from multithreaded access.
*/
static SemaphoreHandle_t gSerialDebugWriteMutex = NULL;
int32_t NewCharPresent()
{
int32_t charPresent = 0;
if ((UART_PDD_ReadInterruptStatusReg(SERIAL_BASE_UART_BASE_PTR) & UART_S1_RDRF_MASK) )
{
/* Any data in receiver buffer */
charPresent = 1;
}
return charPresent;
}
/*!
* Read "count" size_t (read byte) units from the device (UART3)
* @param fd Unused file descriptor
* @param buf Buffer to read into
* @param count number of characters to read from the device.
* @return
*/
int _read (int fd, const void *buf, size_t count)
{
size_t CharCnt = 0x00;
(void)fd; /* Parameter is not used, suppress unused argument warning */
for (;count > 0x00; --count) {
if ((UART_PDD_ReadInterruptStatusReg(SERIAL_BASE_UART_BASE_PTR) & UART_S1_RDRF_MASK) == 0x00) { /* Any data in receiver buffer */
if (CharCnt != 0x00) { /* No, at least one char received? */
break; /* Yes, return received char(s) */
} else { /* Wait until a char is received */
vTaskDelay(1);
}
}
CharCnt++; /* Increase char counter */
/* Save character received by UARTx device into the receive buffer */
*(uint8_t*)buf = (unsigned char)UART_PDD_GetChar8(SERIAL_BASE_UART_BASE_PTR);
/* Stop reading if CR (Ox0D) character is received */
if (*(uint8_t*)buf == 0x0DU) { /* New line character (CR) received ? */
*(uint8_t*)buf = '\n'; /* Yes, convert LF to '\n' char. */
break; /* Stop loop and return received char(s) */
}
(uint8_t*)buf++; /* Increase buffer pointer */
}
return CharCnt;
}
/*!
* This function is low layer support for printf-like functions.
* @param fd Unused file descriptor
* @param buf Buffer of data to write to the device.
* @param count Number of size_t (read "byte") sized data units to write to
* the device.
* @note This was originally a processor expert function. I removed the '\r'
* before '\n' code. I would rather just have printf send what we ask it to and
* take care of line endings in the application code. (as far as I can tell,
* its not proper stdlib functionality anyway..)
* @return return number of characters written to the device.
*/
int _write (int fd, const void *buf, size_t count)
{
size_t CharCnt = 0x00;
volatile int32_t status;
/*
* The file descriptor for stdout is 1, stderr is 2
*/
if(fd == 1)
{
if(gSerialDebugWriteMutex == NULL)
{
/*
* A binary semaphore is created in the "taken" state, so once we
* create it we will leave it taken until we are done using the UART.
* Otherwise, if it has already been created, we need to take it.
*/
gSerialDebugWriteMutex = xSemaphoreCreateBinary();
}
else
{
xSemaphoreTake(gSerialDebugWriteMutex, portMAX_DELAY);
}
}
else if(fd == 2)
{
// This is standard error
// maybe disable interrupts
}
else
{
// not handled either
// Could possibly use this for ctx->gio operations??
}
for (;count > 0x00; --count) {
status = UART1_S1;
while(status & UART_S1_TDRE_MASK == 0)
{
;
}
/* Wait until UART is ready for saving a next character into the transmit buffer */
while ((UART_PDD_ReadInterruptStatusReg(SERIAL_BASE_UART_BASE_PTR) & UART_S1_TDRE_MASK) == 0)
{
/*
* If we are pending on a status register, we may consider lazily
* delaying until the uart is ready, it almost depends on the baud.
* Another option is implement the interrupt and allow the task to
* be woken from the ISR if it is a higher priority the whatever
* task is currently running.
* For now, spinlock...
*/
//vTaskDelay(1);
}
/* Save a character into the transmit buffer of the UART0 device */
UART_PDD_PutChar8(SERIAL_BASE_UART_BASE_PTR, (unsigned char)*(uint8_t*)buf);
(uint8_t*)buf++; /* Increase buffer pointer */
CharCnt++; /* Increase char counter */
}
if(fd == 1)
{
xSemaphoreGive(gSerialDebugWriteMutex);
}
else if(fd == 2)
{
// maybe restore interrupts to whatever state they were in previously
// if we disable them when coming in...
}
return CharCnt;
}
|
C
|
//////////////////////////////////////////////////////////////////////////////
// Filename: C:\work\ringbuf\drivers/test_v1_00_a/examples/test_v2_1_0_app.c
// Version: 1.00.a
// Description: test (new FSL core) Driver Example File
// Date: Fri Oct 10 21:57:52 2008 (by Create and Import Peripheral Wizard)
//////////////////////////////////////////////////////////////////////////////
#include "test.h"
#include "xparameters.h"
/*
* Follwing is an example driver function
* that is called in the main function.
*
* This example driver writes all the data in the input arguments
* into the input FSL bus through blocking writes. FSL peripheral will
* automatically read from the FSL bus. Once all the inputs
* have been written, the output from the FSL peripheral is read
* into output arguments through blocking reads.
*
* CAUTION:
*
* The sequence of writes and reads in this function should be consistent
* with the sequence of reads or writes in the HDL implementation of this
* coprocessor.
*
*/
// Instance name specific MACROs. Defined for each instance of the peripheral.
#define WRITE_TEST_0(val) write_into_fsl(val, XPAR_FSL_TEST_0_INPUT_SLOT_ID)
#define READ_TEST_0(val) read_from_fsl(val, XPAR_FSL_TEST_0_OUTPUT_SLOT_ID)
void test_app(
unsigned int* input_0, /* Array size = 8 */
unsigned int* output_0 /* Array size = 8 */
)
{
int i;
//Start writing into the FSL bus
for (i=0; i<8; i++)
{
WRITE_TEST_0(input_0[i]);
}
//Start reading from the FSL bus
for (i=0; i<8; i++)
{
READ_TEST_0(output_0[i]);
}
}
main()
{
unsigned int input_0[8];
unsigned int output_0[8];
#ifdef __PPC__
// Enable APU for PowerPC.
unsigned int msr_i;
msr_i = mfmsr();
msr_i = (msr_i | XREG_MSR_APU_AVAILABLE | XREG_MSR_APU_ENABLE) & ~XREG_MSR_USER_MODE;
mtmsr(msr_i);
#endif
//Initialize your input data over here:
input_0[0] = 12345;
input_0[1] = 24690;
input_0[2] = 37035;
input_0[3] = 49380;
input_0[4] = 61725;
input_0[5] = 74070;
input_0[6] = 86415;
input_0[7] = 98760;
//Call the macro with instance specific slot IDs
test(
XPAR_FSL_TEST_0_INPUT_SLOT_ID,
XPAR_FSL_TEST_0_OUTPUT_SLOT_ID,
input_0,
output_0
);
// You can also define your own function to access the peripheral
// Here you are calling the example function defined above
// Note the slot ID can not be passed over as function parameters
test_app(
input_0,
output_0
);
}
|
C
|
/**************************************************************************************
* Author: Hayden Krile
* Course: EGR 226 - 905
* Date: 03/19/2021
* Project: Lab9Part1
* File: main.c
* Description: This program connects to the MSP432 and uses three pushbuttons and interrupts
* that control the speed of a DC motor. The red button shuts down the motor,
* the black button slows the speed of the motor by 10%, and the white button
* speeds up the motor by 10%
***************************************************************************************/
#include "msp.h"
void ButtonPinSet(void);
void MotorPinSet(void);
void PORT3_IRQHandler(void);
void main(void)
{
WDT_A->CTL = WDT_A_CTL_PW | WDT_A_CTL_HOLD; // stop watchdog timer
//disable irq for the startup phase
__disable_irq();
//enable the pins
MotorPinSet();
ButtonPinSet();
//enable irq
__enable_irq();
//since interrupts are being used, no need for anything in the loop
while(1);
}
/*-----------------------------------------------------------
* Function: ButtonPinSetup
* Description: This function sets up the pins for pushbuttons
*
* Inputs:
* N/A
*
* Outputs:
* N/A
*---------------------------------------------------------*/
void ButtonPinSet(void){
//set P3.5-7 as GPIO with internal pull-up resistor
P3->SEL1 &= ~(BIT5|BIT6|BIT7);
P3->SEL0 &= ~(BIT5|BIT6|BIT7);
P3->DIR &= ~(BIT5|BIT6|BIT7);
P3->REN |= (BIT5|BIT6|BIT7);
P3->OUT |= (BIT5|BIT6|BIT7);
//enabling interrupts for pins 3.5-7
P3->IES |= (BIT5|BIT6|BIT7);
P3->IFG = 0;
P3->IE |= (BIT5|BIT6|BIT7);
//enable interrupts
NVIC_SetPriority(PORT3_IRQn, 3);
NVIC_EnableIRQ(PORT3_IRQn);
}
/*-----------------------------------------------------------
* Function: MotorPinSetup
* Description: This function sets up the pins for DC motor
*
* Inputs:
* N/A
*
* Outputs:
* N/A
*---------------------------------------------------------*/
void MotorPinSet(void){
//setup P2.4 as GPIO
P2->SEL0 |= BIT4;
P2->SEL1 &= ~BIT4;
P2->DIR |= BIT4;
//40000 cycles
TIMER_A0->CCR[0] = 40000;
TIMER_A0->CCTL[1] = TIMER_A_CCTLN_OUTMOD_7;
//by default, sets the duty cycle to 50%
TIMER_A0->CCR[1] = 20000;
TIMER_A0->CTL = 0x0254;
}
/*-----------------------------------------------------------
* Function: PORT3_IRQHandler
* Description: This function handles the interrupts generated
* from port three by the buttons
*
* Inputs:
* N/A
*
* Outputs:
* N/A
*---------------------------------------------------------*/
void PORT3_IRQHandler(void){
//initially sets the duty cycle to 50%
static float dutyCycle = .5;
float speedSet;
//if the red button is pushed
if (P3->IFG & 0x20){
//stop the motor
dutyCycle = 0;
TIMER_A0->CCR[1] = 0;
//clear the flag
P3->IFG &= ~0x20;
}
//if the black button is pushed
if (P3->IFG & 0x40){
//if the motor is already at 0
if(dutyCycle <= 0.1){
dutyCycle = 0;
TIMER_A0->CCR[1] = 0;
}
//decrease the motor speed by 10%
else{
dutyCycle = dutyCycle - 0.1;
speedSet = (40000*dutyCycle);
TIMER_A0->CCR[1] = speedSet;
}
//clear the flag
P3->IFG &= ~0x40;
}
//if the white button is pushed
if (P3->IFG & 0x80){
//if the previous input was 0.9 or 1
if(dutyCycle >= 0.9){
dutyCycle = 1;
TIMER_A0->CCR[1] = 40000;
}
//if not
else{
//increase the duty cycle by 10%
dutyCycle = dutyCycle + 0.1;
speedSet = (40000*dutyCycle);
TIMER_A0->CCR[1] = speedSet;
}
//clear the flag
P3->IFG &= ~0x80;
}
}
|
C
|
#ifndef motor_h
#define motor_h
bool DEBUG_motor = true;
bool motorChange = false;
int motorDir = 0; // 0=off, 1=Forward, 2=reverse
int motorpinA = 3; // PCF PIN
int motorpinB = 4; // PCF PIN
int motorInt = 7; // PCF PIN
int stallcnt = 0; // counter for stall
int stallReset = 500000; // reset stall count duration micros
#ifdef DEMO_UNIT
bool stalldetect = false; // use interupt to detect stalls
#else
bool stalldetect = true; // use interupt to detect stalls
#endif
int stalllimit = 5; // stall limit, num interrupts for stall detect
bool autoreverse = true; // autoreverse on stall
int autoreversepause = 200; // autoreverse delay
int autoreversetime = 1000; // autoreverse duratiton
int motor_lastmicros = 0;
#define MOTORDIR_OFF 0
#define MOTORDIR_F 1
#define MOTORDIR_R 2
void motor(int dir,int dur){
if(DEBUG_motor)Serial.print("[MOTOR]: ");
if(dir==MOTORDIR_OFF){
if(DEBUG_motor)Serial.println("OFF");
ioDeviceDigitalWriteS(switches.getIoAbstraction(), motorpinB, HIGH);
ioDeviceDigitalWriteS(switches.getIoAbstraction(), motorpinA, HIGH);
}
else if(dir==MOTORDIR_F){
if(DEBUG_motor)Serial.println("F");
ioDeviceDigitalWriteS(switches.getIoAbstraction(), motorpinB, LOW);
ioDeviceDigitalWriteS(switches.getIoAbstraction(), motorpinA, HIGH);
if(dur!=0){
delay(dur);
motor(0,0);
}
}
else if(dir==MOTORDIR_R){
if(DEBUG_motor)Serial.println("R");
ioDeviceDigitalWriteS(switches.getIoAbstraction(), motorpinB, HIGH);
ioDeviceDigitalWriteS(switches.getIoAbstraction(), motorpinA, LOW);
if(dur){
delay(dur);
motor(0,0);
}
}
}
void motorOff(){
motor(MOTORDIR_OFF,0);
}
void motorPulse(int dir,int count,int dur,int delayms){
for(int i=0;i<count;i++){
motor(dir,dur);
delay(delayms);
}
}
void ICACHE_RAM_ATTR onFeedback(uint8_t pin, bool heldDown) {
// first time in a while reset stallcount
if(micros()-motor_lastmicros > stallReset ){
stallcnt = 1; // reset stall check, timeout
}
// if(DEBUG_motor)
Serial.println("[MOTOR]: OVERCURRENT DETECTED: " + (String)stallcnt + " " + (String)((micros()-motor_lastmicros)/10000) + "ms" );
// if(DEBUG_motor)Serial.println(heldDown ? "STALLED" : " ignoring");
if(stalldetect && (stallcnt >= stalllimit) && motorDir>MOTORDIR_OFF){
if(DEBUG_motor)Serial.println("[MOTOR]: STALLED");
stallcnt = 0;
motor(MOTORDIR_OFF,0); // motor off
if(autoreverse){
delay(autoreversepause);
motor(motorDir == MOTORDIR_F?MOTORDIR_R:MOTORDIR_F,autoreversetime); // motor Back
motor(MOTORDIR_OFF,0);
}
motorDir = MOTORDIR_OFF;
} else stallcnt++;
motor_lastmicros = micros();
}
void motorTest(){
int dur = 1000;
motorOff();
motor(MOTORDIR_F,dur);
delay(500);
motor(MOTORDIR_R,dur);
motorOff();
}
#endif
|
C
|
/// Write a C program to find the largest of three numbers.
#include <stdio.h>
int main ()
{
int a,b,c;
printf("Enter Three Number :");\
scanf("%d %d %d",&a,&b,&c);
if(a>b&&a>c){
printf("%d is larger than three Number",a);
}
else if(b>a&&b>c){
printf("%d is large than three Number",b);
}
else{
printf("%d is large than three Number",c);
}
getch ();
}
|
C
|
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include "Table.h"
#include "Emulate.h"
extern struct emulation table[];
/*
The purpose of this file is to hold the function Emulate Tokens. The function is responsible for returning
to the main file a char** that holds tokens that have been emulated. Via pass by reference, the number of tokens and
the boolean integer "set" are brought back to the main. The pointer to noComments is the part of the Record
that comes before the first ";" symbol. This means that no comments will get processed by this algorithm.
The main variable being altered is "tokens". This is an array of character pointers of the size 200. This was
the largest size allocated to tokenizing seen in use with the X-Makina on Dr Hughes website, and is certainly
large enough to accomodate even heavy use. Since a record consists of only a few words, most of which
are instructions (which only take 3-5 bytes) exceeding 256 would require abnormally large subroutine/label/ operand names.
There is a risk for large records when considering the fact that comments will be stored somewhere. This comment already is
itself very large, but it has been separated by lines and does not exceed 123 characters and 20 whitespaces.
There is a smaller buffer referred to as smallBuff that holds emulation sizes.
*/
#define True 1
#define False 0
#define Neither 0x00
#define Right 0x01
#define Left 0x10
#define Both 0x11
#define MAX_RECORD_SIZE 100
#define MAX_EMULATE_SIZE 15
char** EmulateTokens(char *noComments, int *numOfTokens, int *set) {
char bigBuff[MAX_RECORD_SIZE]; // A char array to hold the Non-Comment tokens from the Record
char smallBuff[MAX_EMULATE_SIZE]; //buffer required for each token in the array
int sizeOfRecord = sprintf(bigBuff, "%s" , noComments); // Makes the character pointer into a character array, also returns size of array
char *toker = strtok(bigBuff, ", \n\t"); // toker holds the values during the tokenize process
char *tokens[MAX_RECORD_SIZE]; // The emulated Tokens to return
int newTokens = 0;
int i = 0; // For iterating
// Initiliaze as false
*set = False;
//Read through the input Record and store the tokens in a character pointer array
while (toker != NULL) {
tokens[i++] = toker;
toker = strtok(NULL, ", \n\t");
}
//Store the number of tokens. Number is one extra. Maybe change above lines to save
// Having to set tokens[i] as null since toker is null at the end anyway
*numOfTokens = i ;
tokens[i] = NULL;
if (*numOfTokens > 4) {
*set = True;
}
//Check each token
for (i = 0; i < *numOfTokens; i++) {
//Check every instruction in the table against current token
for (int k = 0; k < sizeOfTable(); k++) {
//If there is a match...
if (_stricmp(tokens[i], table[k].instruction) == 0) {
//Check how the handle the emulation. Dependent on the amount of arguments.
switch (table[k].position) {
case Neither:
tokens[i] = table[k].emulation;
break;
case Right:
printf("Tokens[i+2] = %s\n", tokens[i + 2]);
if ((tokens[i + 2] != NULL) | (tokens[i + 1] == NULL)) {
printf("Error found");
*set = True;
}
tokens[i++] = table[k].emulation;
break;
case Left:
if ((tokens[i + 2] != NULL) | (tokens[i + 1] == NULL)) {
printf("Error found");
*set = True;
}
//Assign the current string in the token array to equal the emulation table. Increment i
tokens[i] = table[k].emulation;
//Assign the next token to be the right side constant from the table.
tokens[i + 2] = table[k].rightSide;
newTokens++;
break;
case Both:
if ((tokens[i + 2] != NULL )|(tokens[i+1] == NULL)) {
printf("Error found");
set = True;
}
// May not be needed. Just trying to minimize number of tokens.
sprintf(smallBuff, "%s, %s", tokens[i + 1], tokens[i + 1]);
tokens[i++] = table[k].emulation; // skipping over to the next
tokens[i] = smallBuff;
break;
//default should not be hit.
default:
break;
}
}
}
}
//Correct the number of tokens.
*numOfTokens = *numOfTokens + newTokens;
//The tokens have been correctly assembled. Return to the main
return tokens;
}
|
C
|
//WAP to print natural numbers from 1 to n using while loop
#include<stdio.h>
int main()
{
int i,n;
printf("Enter the value of n : ");
scanf("%d",&n);
i=1;
printf("Natural numbers are : ");
while(i<=n)
{
printf("\n%d",i++);
}
return 0;
}
|
C
|
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <ctype.h>
#include <stdbool.h>
#include "game.h"
struct gameargs {//Structure of game data
char word[30];
int gameport;
char gameip[30];
};
struct client_info {//Structure of player data
int sockno;
char ip[INET_ADDRSTRLEN];
int gameport;
char gameip[30];
};
int n3[3000];//Number of players in game
int clients4[3000][100];//Sockets' numbers of players in game
char word[3000][30];//Word to guess of every game
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
//Thread for game to receive and sent messages with player
void *recvmg2(void *sock)
{
struct client_info cl = *((struct client_info *)sock);
char msg[500];
int len;
int i;
int j;
int portno = cl.gameport;
//Main loop to receive messages from player
while((len = recv(cl.sockno,msg,500,0)) > 0) {
//First char of message is a message type
//check type of message:
//'k' - end of game, close host socket, close host thread
//'p' - the same like 'k' but for player
//other - message to sent to other players
char msgtype = msg[0];
if(msgtype == 'k'){//Kill host
for (int k = 0; k < n3[portno]; ++k)
{
pthread_mutex_lock(&mutex2);
if(cl.sockno == clients4[portno][k]){
close(clients4[portno][k]);
}
pthread_mutex_unlock(&mutex2);
}
pthread_mutex_lock(&mutex2);
printf("%s disconnected\n",cl.ip);
//Update list of players in game
for(i = 0; i < n3[portno]; i++) {
if(clients4[portno][i] == cl.sockno) {
j = i;
while(j < n3[portno]-1) {
clients4[portno][j] = clients4[portno][j+1];
j++;
}
}
}
n3[portno]--;
printf("player %d killed\n",cl.sockno);
pthread_mutex_unlock(&mutex2);
pthread_exit(NULL);
}else if(msgtype=='p'){ //Kill player
for (int k = 0; k < n3[portno]; ++k)
{
pthread_mutex_lock(&mutex2);
if(cl.sockno == clients4[portno][k]){
close(clients4[portno][k]);
}
pthread_mutex_unlock(&mutex2);
}
}else{
msg[len] = '\0';
// START - sendtoall
//Messages for more players got code
//First char of message:
//':' - message to all players (for group chat)
//'w' - server message that someone won game
//'9' - host message to players to call out 'kill' by theirself
pthread_mutex_lock(&mutex2);
int ii;
char newmsg[500];
if(msg[0]==':'){
//Check that message is word to guess and someone won game
if(strcmp(msg,word[portno])==0){
strcpy(newmsg,"win");
char curruser[10];
strcpy(curruser,"");
sprintf(curruser,"%d",cl.sockno);
strcat(newmsg,curruser);
strcat(newmsg,":\n");
}else{
//if noone won, add who send message to message
char user[10];
char curruser[10];
strcpy(curruser,"");
sprintf(curruser,"%d",cl.sockno);
strcpy(user,"$");
strcat(user,curruser);
strcat(user,":");
strcpy(newmsg,user);
strcat(newmsg,msg);
}
}else{//message not for group chat
strcpy(newmsg,msg);
}
//Sending message to all players
for(ii = 0; ii < n3[portno]; ii++) {
if(clients4[portno][ii] != cl.sockno) {
printf("client - %d\n",clients4[portno][ii] );
if(send(clients4[portno][ii],newmsg,strlen(newmsg),0) < 0) {
perror("sending failure");
continue;
}
}else{
//Some messages are send also to sender of message
if((newmsg[0]=='$') || (newmsg[0]=='w') || (newmsg[0]=='9')){
printf("client - %d\n",clients4[portno][ii] );
if(send(clients4[portno][ii],newmsg,strlen(newmsg),0) < 0) {
perror("sending failure");
continue;
}
}
}
}
pthread_mutex_unlock(&mutex2);
// END - sendtoall
memset(msg,'\0',sizeof(msg));
}
}
pthread_mutex_lock(&mutex2);
printf("%s disconnected from %d\n",cl.ip,cl.sockno);
//Update list of players in game
for(i = 0; i < n3[portno]; i++) {
if(clients4[portno][i] == cl.sockno) {
j = i;
while(j < n3[portno]-1) {
clients4[portno][j] = clients4[portno][j+1];
j++;
}
}
}
n3[portno]--;
printf("player %d killed\n",cl.sockno);
pthread_mutex_unlock(&mutex2);
pthread_exit(NULL);
}
//Thread function of new game created by main server
//It is like game server
void *gamemain(void *inputargs)
{
struct gameargs args = *((struct gameargs*)inputargs);
struct sockaddr_in my_addr,their_addr;
int my_sock;
int their_sock;
socklen_t their_addr_size;
int portno;
pthread_t recvt;
struct client_info cl;
char ip[INET_ADDRSTRLEN];
portno = args.gameport;
n3[portno] = 0;
strcpy(word[portno],":");
strcat(word[portno],args.word);
strcat(word[portno],"\n");
my_sock = socket(AF_INET,SOCK_STREAM,0);
memset(my_addr.sin_zero,'\0',sizeof(my_addr.sin_zero));
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(portno);
my_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
their_addr_size = sizeof(their_addr);
if(bind(my_sock,(struct sockaddr *)&my_addr,sizeof(my_addr)) != 0) {
perror("game binding unsuccessful");
close(my_sock);
exit(1);
}
if(listen(my_sock,50) != 0) {
perror("game listening unsuccessful");
exit(1);
}
int gameover = 1;
//Main loop of game server
while(gameover) {
if((their_sock = accept(my_sock,(struct sockaddr *)&their_addr,&their_addr_size)) < 0) {
perror("game accept unsuccessful");
exit(1);
}
pthread_mutex_lock(&mutex2);
inet_ntop(AF_INET, (struct sockaddr *)&their_addr, ip, INET_ADDRSTRLEN);
printf("%s connected to %d\n",ip,portno);
cl.sockno = their_sock;
strcpy(cl.ip,ip);
cl.gameport = portno;
clients4[portno][n3[portno]] = their_sock;
//Creating new user name:
char u[20];
char usockno[10];
strcpy(u,"u");
sprintf(usockno,"%d",clients4[portno][n3[portno]]);
strcat(u,usockno);
strcat(u,":\n");
//Send to new user his name in group chat
send(clients4[portno][n3[portno]],u,sizeof(u),0);
n3[portno]++;
//Create thread to connect between game and player
pthread_create(&recvt,NULL,recvmg2,&cl);
pthread_mutex_unlock(&mutex2);
}
pthread_exit(NULL);
}
|
C
|
/*#15. Program for Making A user defined String compare Function. */
#include<stdio.h>
#define MAX 30
char mytolower(char ch)
{
if(ch<='A' && ch>='Z')
ch=(ch+32);
return(ch);
}
int mystrcmp(char str1[],char str2[])
{
int i;
for(i=0;str1[i]!='\0' || str2[i]!='\0';i++)
{
if(mytolower(str1[i])>mytolower(str2[i]))
return(-1);
else if(mytolower(str1[i])<mytolower(str2[i]))
return(1);
}
return(0);
}
int main()
{
char str1[MAX],str2[MAX];
printf("\n Enter the First String:");
gets(str1);
printf("\n Enter the Second String:");
gets(str2);
if(mystrcmp(str1,str2)==0)
printf("\n Both Strings are Equal!!");
else if(mystrcmp(str1,str2)>0)
printf("\n %s comes earlier than %s.",str1,str2);
else
printf("\n %s comes earlier than %s.",str2,str1);
return(0);
}
|
C
|
#ifndef BIP_BUF_H_
#define BIP_BUF_H_
/* Author: Domen Puncer Kugler <domen@cba.si>. License: WTFPL, see file LICENSE */
#include <types.h>
struct bip_buf {
u8 *data;
unsigned size;
volatile unsigned head; /* points to first free byte */
volatile unsigned tail; /* points to first used byte */
volatile unsigned tailwrap;
/* extreme case tail == head: all free;
* tail == head+1: all full (last byte can't be used)
* ____tailxxxxxxxxhead_____
* xxxxhead________tailxxxxx
*/
};
void bip_buf_init(struct bip_buf *cb, void *buf, unsigned size);
void* bip_buf_alloc(struct bip_buf *cb, unsigned len);
/* len here must be exactly the same as for _alloc() */
void bip_buf_alloc_commit(struct bip_buf *cb, unsigned len);
void* bip_buf_getdata(struct bip_buf *cb);
void bip_buf_free(struct bip_buf *cb, unsigned len);
#endif
|
C
|
/* lab7.c
* Denzel Murdaugh <--- replace with your word!
* Denzelm <--- replace with your user word!
* ECE 223 Spring 2016
* MP7
*
* NOTE: You must update all of the following comments!
*
* Propose:
*
* Assumptions:
*
* An outline for the interactive menu input is provided. Details need to be
* completed but the format of the commands and the output generated by the
* print statements must not be changed. You have to call the correct
* print statement in response to the input
*
* Bugs: Many details have not been implemented.
*
* See the ECE 223 programming guide
*
* Are you unhappy with the way this code is formatted? You can easily
* reformat (and automatically indent) your code using the astyle
* command. If it is not installed use the Ubuntu Software Center to
* install astyle. Then in a terminal on the command line do
* astyle --style=kr lab7.c
*
* See "man astyle" for different styles. Replace "kr" with one of
* ansi, java, gnu, linux, or google to see different options. Or, set up
* your own style.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <math.h>
#include <ctype.h>
#include <limits.h>
#include <time.h>
#include <unistd.h>
#include "hash.h"
#define TRUE 1
#define FALSE 0
#define MAXLINE 128
#define word_SIZE 16
#define MIN_WORD_LEN 3
#define MAX_WORD_LEN 30
// prototypes
int find_first_prime(int number);
// constants used to indicate type of probing.
// This should probably be in your hash table header file and not here
//enum probe_dec_t {LINEAR, DOUBLE};
int main(int argc, char * argv[])
{
int probe_dec = LINEAR;
char line[MAXLINE];
char command[MAXLINE];
char first_arg[MAXLINE];
char junk[MAXLINE];
char wordin[MAXLINE];
char docName[word_SIZE+1];
char base_doc_word[word_SIZE+1];
char doc_ascii_num[word_SIZE+1];
int num_docs = -1;
int num_words = 0;
int num_items;
int i = -1234567;
clock_t start, end;
FILE *fpt;
if (argc != 3 && argc != 4) {
fprintf(stderr, "Usage: ./lab7 <filename_base> <num_docs> {linear|double}\n");
exit(1);
}
num_docs = atoi(argv[2]);
if (num_docs < 1) {
fprintf(stderr, "Invalid number docs %d from %s\n", num_docs, argv[2]);
exit(2);
}
if (strlen(argv[1]) < 3 || strlen(argv[1]) > word_SIZE) {
fprintf(stderr, "Invalid base word for files %s\n", argv[1]);
exit(2);
}
strcpy(base_doc_word, argv[1]);
if (argc == 4) {
if (strcmp(argv[3], "linear") == 0) {
probe_dec = LINEAR;
printf("Open addressing with linear probe sequence\n");
} else if (strcmp(argv[3], "double") == 0) {
probe_dec = DOUBLE;
printf("Open addressing with double hashing\n");
} else {
fprintf(stderr, "invalid type of probing decrement: %s\n", argv[3]);
fprintf(stderr, "must be {linear | double}\n");
exit(1);
}
}
printf("Lab7 Number of documents is %d. Possible commands:\n", num_docs);
printf(" MAX word: the document that uses this word the largest number of times\n");
printf(" MIN word: the document that uses this word the fewest number of times\n");
printf(" DIST word: the distribution of the word in each document\n");
printf(" UNIQUE x: number of words unique to document x\n");
printf(" COUNT x: number of words found in document x\n");
printf(" PRINT x: print each word and number of times used in doc x\n");
printf(" PRINT: print table with words and count of times used\n");
printf("QUIT\n");
table_t *T=tableConstruct(17,probe_dec,num_docs);
T->subHash = (T->size % 2 == 0) ? T->size / 2 : (T->size + 1) / 2;
if(T->size<1)
printf("error here 0\n");
start = clock();
// First phase: read all documents and build hash table
// Use probe_dec to indicate the type of probing
// Set the initial size of the hash table to 17
// open file
int doc_number;
for(doc_number = 0; doc_number < num_docs; doc_number++)
{
strcpy(docName, base_doc_word);
sprintf(doc_ascii_num, "%d", doc_number);
strcat(docName, doc_ascii_num);
fpt = fopen(docName, "r");
if (fpt == NULL) {
fprintf(stderr, "Unable to open %s for reading\n", docName);
fprintf(stderr, "Base filename %s for %d docs\n", base_doc_word, num_docs);
exit(1);
}
if(T->size<1)
printf("error here 2\n");
// remember fgets includes newline \n unless line too long
while (fgets(line, MAXLINE, fpt) != NULL) {
int num_items = sscanf(line, "%s", wordin);
if (num_items != 1) // failed to read first word on line
continue;
int word_len = strlen(wordin);
if (word_len < MIN_WORD_LEN || word_len > MAX_WORD_LEN) {
fprintf(stderr, "Invalid input word (%s)\n", wordin);
exit(1);
}
float load;
// Add your code here to add wordin to hash table
if(probe_dec==LINEAR){
load=(float)T->num_keys/T->size;
if (load > 0.75){
T=rehashTable(T);
}
insertInHash(T,Hash(wordin,strlen(wordin),T->size),wordin,doc_number);
}
else{
load=(float)T->num_keys/T->size;
if (load > 0.75){
T=rehashTable(T);
T->subHash = T->size / 2;
}
insertIntoHashTable(T,Hash(wordin,strlen(wordin),T->size),wordin,doc_number);
}
num_words++;
}
fclose(fpt);
}
end = clock();
printf("Read %d words from %d documents in %g msecs\n", num_words,
num_docs, 1000.0*(end-start)/CLOCKS_PER_SEC);
/***************************************/
//display(T); //for testing
/****************************************/
// Second phase: gather input from user
start = clock();
// remember fgets includes newline \n unless line too long
while (fgets(line, MAXLINE, stdin) != NULL) {
num_items = sscanf(line, "%s %s %s", command, first_arg, junk);
int count = -99;
int which_doc = -999;
int var;
if (num_items == 2 && strcmp(command, "MAX") == 0) {
if (strlen(first_arg) < MIN_WORD_LEN) {
printf("Invalid word for MAX: %s\n", first_arg);
} else {
// add code to find count and which_doc
if(probe_dec==LINEAR){
var=searchElement(T,Hash(first_arg,strlen(first_arg),T->size));
}
else{
var=searchData(T,Hash(first_arg,strlen(first_arg),T->size));
if(var!=-1){
printf("found %s\n", T->entry[var].word);
}
}
if(var!=-1 && strcmp(T->entry[var].word,first_arg)==0){
for(i=0;i<T->num_docs;i++){
if(T->entry[var].doc_info[i]>count){
count=T->entry[var].doc_info[i];
which_doc=i;
}
}
printf("max found (%s) %d time%s in doc %d\n",
first_arg, count, count>1?"s":"",which_doc);
} else {
printf("max did not find (%s) in any doc\n", first_arg);
}
}
} else if (num_items == 2 && strcmp(command, "MIN") == 0) {
if (strlen(first_arg) < MIN_WORD_LEN) {
printf("Invalid word for MIN: %s\n", first_arg);
} else {
// add code to find count and which_doc
if(probe_dec==LINEAR){
var=searchElement(T,Hash(first_arg,strlen(first_arg),T->size));
}
else
var=searchData(T,Hash(first_arg,strlen(first_arg),T->size));
if(var!=-1 && strcmp(T->entry[var].word,first_arg)==0){
count=10000;
for(i=0;i<T->num_docs;i++){
if(T->entry[var].doc_info[i]<count && T->entry[var].doc_info[i]>0){
count=T->entry[var].doc_info[i];
which_doc=i;
}
}
printf("min Found (%s) %d time%s in doc %d\n",
first_arg, count, count>1?"s":"", which_doc);
} else {
printf("min did not find (%s) in any doc\n", first_arg);
}
}
} else if (num_items == 2 && strcmp(command, "DIST") == 0) {
if (strlen(first_arg) < MIN_WORD_LEN) {
printf("Invalid word for DIST: %s\n", first_arg);
} else {
// add code to determine if word is found and if so
// how many times in each document
if(probe_dec==LINEAR){
var=searchElement(T,Hash(first_arg,strlen(first_arg),T->size));
}
else
var=searchData(T,Hash(first_arg,strlen(first_arg),T->size));
// If the word is not found in any document
if(var==-1){
printf("dist did not find (%s) in any doc\n", first_arg);
}else{
// else if found, how many times in each document
for(i=0;i<num_docs;i++){
if(T->entry[var].doc_info[i]!=0){
count=T->entry[var].doc_info[i];
which_doc=i;
printf("Used %s %d time%s in doc %d\n",
first_arg, count, count>1?"s":" ", which_doc);
}
}
}
}
} else if (num_items == 2 && strcmp(command, "UNIQUE") == 0) {
doc_number = atoi(first_arg);
if (doc_number < 0 || doc_number >= num_docs) {
printf("Invalid document number: %d only %d docs\n",
doc_number, num_docs);
} else {
int count=0;
// add code to find count and a word at word_key
char *word_key = malloc(30);
int flag=1;
int j;
for(i=0;i<T->size;i++){
if(T->entry[i].marker!=1)
continue;
else{
for(j=0;j<num_docs;j++){
if(j!=doc_number){
if(T->entry[i].doc_info[j]>0){
flag=1;
break;
}
else{
flag=0;
}
}
}
if(flag==0){
strcpy(word_key,T->entry[i].word);
count++;
}
}
}
if (count>0) {
printf("Found %d unique word%s in doc %d\n",
count, count>1?"s":"", doc_number);
printf(" A unique word is %s\n", word_key);
} else {
printf("This document has no unique words %d\n", doc_number);
}
free(word_key);
}
} else if (num_items == 2 && strcmp(command, "COUNT") == 0) {
doc_number = atoi(first_arg);
if (doc_number < 0 || doc_number >= num_docs) {
printf("Invalid document number: %d only %d docs\n",
doc_number, num_docs);
} else {
// add code to find count and words used most and least
int min_word_count = INT_MAX;
int max_word_count = -1;
char *min_word_key =malloc(30), *max_word_key =malloc(30);
count=0;
for(i=0;i<T->size;i++){
if(T->entry[i].doc_info[doc_number]>0){
if(T->entry[i].doc_info[doc_number]<min_word_count){
min_word_count=T->entry[i].doc_info[doc_number];
strcpy(min_word_key,T->entry[i].word);
}
if(T->entry[i].doc_info[doc_number]>max_word_count){
max_word_count=T->entry[i].doc_info[doc_number];
strcpy(max_word_key,T->entry[i].word);
}
count++;
}
}
printf("Found %d word%s in doc %d\n",
count, count>1?"s":"", doc_number);
printf(" %s used most times %d\n", max_word_key, max_word_count);
printf(" %s used fewest times %d\n", min_word_key, min_word_count);
free(max_word_key);
free(min_word_key);
}
} else if (num_items == 1 && strcmp(command, "PRINT") == 0) {
// print the hash table
display(T);
} else if (num_items == 2 && strcmp(command, "PRINT") == 0) {
doc_number = atoi(first_arg);
if (doc_number < 0 || doc_number >= num_docs) {
printf("Invalid document number: %d only %d docs\n",
doc_number, num_docs);
} else {
// add code to find word and count
for(i=0;i<T->size;i++){
if(T->entry[i].doc_info[doc_number]>0){
printf("%d: %s %d\n", i, T->entry[i].word, T->entry[i].doc_info[doc_number]);
}
}
}
} else if (num_items == 1 && strcmp(command, "STATS") == 0) {
int tableSize = T->size;
int entries = T->num_keys;
float loadFactor = (float) entries / tableSize;
printf("Table size (%d), load factor (%g)\n", tableSize, loadFactor);
} else if (num_items == 1 && strcmp(command, "QUIT") == 0) {
freeHash(T);
break;
} else {
printf("# %s", line);
}
}
end = clock();
printf("Processed commands in %g msecs\n",
1000.0*(end-start)/CLOCKS_PER_SEC);
exit(0);
}
/* return first prime number at number or greater
*
* There is at least one prime p such that n <= p < 2n
* for n>=25, n <= p < 1.2n
*/
int find_first_prime(int number)
{
int i, foundfactor;
double upper;
assert(number > 1);
// if even move to next odd
if (number % 2 == 0)
number++;
do {
foundfactor = 0; // assume number is prime
upper = sqrt(number);
for (i = 3; i < upper + 1; i += 2)
if (number % i == 0) {
foundfactor = 1;
number += 2; // only test odds
break;
}
} while (foundfactor);
return number;
}
/* commands specified to vim. ts: tabstop, sts: soft tabstop sw: shiftwidth */
/* vi:set ts=8 sts=4 sw=4 et: */
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char *src = "ashdheadjsuwtjdijfkitailkdkdk";
char head[5] = "head";
char tail[5] = "tail";
char *temp1 = (char *)malloc(sizeof(char) * 100);
char *temp2 = (char *)malloc(sizeof(char) * 100);
int inttemp = 0;
printf("src = %s\n",src);
while(strncmp(src,head,4) != 0)
{
src++;
}
temp1 = src;
/*if(strncmp(src,head,4) == 0)
{
temp1 = src;
}*/
while(strncmp(src,tail,4) != 0)
{
src++;
inttemp++;
}
inttemp += 3;
strncpy(temp2,temp1,inttemp + 1);
/*if(strncmp(src,tail,4) == 0)
{
inttemp += 3;
strncpy(temp2,temp1,inttemp + 1);
}*/
//printf("temp1 = %s\n",temp1);
printf("temp2 = %s\n",temp2);
return 0;
}
|
C
|
#ifndef DOMAIN
#define DOMAIN
typedef struct
{
char name[50];
char continent[15];
long long population;
}Country;
Country create_country(char name[],char continent[],long long population);
char* get_name(Country* c);
char* get_continent(Country* c);
long long get_population(Country* c);
#endif
|
C
|
/**
* @file
* @author Kelemen Tamas <kiskele@krc.hu>
* @brief Macro definitions used in cli.c
*/
#ifndef CLI_H
#define CLI_H
#include "multipath.h"
#define strstart(src, pattern) strncmp(src, pattern, strlen(pattern)) ///< Src string begins with pattern
#define REGEX_IPV4 "([[:digit:]]{1,3})\\.([[:digit:]]{1,3})\\.([[:digit:]]{1,3})\\.([[:digit:]]{1,3})"
///< Regexp pattern to match a part of IPv4 address
#define REGEX_IPV6 "[0-9a-fA-F:\\.]{1,4}" ///< Regexp pattern to match a part of IPv6 address
int parse_cmd(char * cmd);
int exec_cmd(char * cmd, int sock, struct sockaddr * client, unsigned int csize);
/**
* @defgroup ReturnParser Parser Errors
* @brief Return values of parser()
* @{
*/
#define PARSE_OK 0 ///< Successfully parsed and parameters seems good
#define PARSE_ERR_NOCMD 1 ///< No such command
#define PARSE_ERR_REGEX 2 ///< Invalid regexp format specified in c source
#define PARSE_ERR_IP 3 ///< Wrong IP address entered
#define PARSE_ERR_MASK 4 ///< Wrong network mask entered
#define PARSE_ERR_PARAMS 5 ///< Wrong parameter list
/** @} */
/**
* @brief The parser() function sets in its 2nd parameter that witch command were recognised
* These values are the corresponding indexes of the successfully matched regular expressions or MPT_NOCMD if nothing was matched.
*/
typedef enum {
#define CLI_COMMAND(name, regex) name,
#include "../include/cmd.def"
#undef CLI_COMMAND
MPT_NOCMD ///< None of the commands above was matched
} CMDTYPE;
/**
* @defgroup MptHelp Predefined help outputs
* @{
*/
/**
* Help page of command mpt address
*/
#define HELP_ADDR "mpt addr[ess] {add | del} IP_ADDRESS[/PREF_LEN] dev INTERFACE\n\
Adds or deletes the IP_ADDRESS to the INTERFACE.\n\
IP_ADDRESS: The IP address (can be v4 or v6) to manipulate\n\
PREF_LEN: The prefix length of the manipulated address\n\
Default prefix length: 24 for IPv4, 64 for IPv6.\n\
INTERFACE: The name of the interface related to the manipulated address\n\n"
/**
* Help page of command mpt interface
*/
#define HELP_INT "mpt int[erface] INTEFACE {up | down}\n\
Turnes up or down the INTEFACE (Also the paths on the INTERFACE),\n\
INTEFACE: The name of the interface e.g. eth0\n\n"
/**
* Help page of command mpt reload
*/
#define HELP_RELOAD "mpt reload [FILENAME]\n\
Stops and deletes the specified (or all) connection(s).\n\
Then reloads and starts the given (or all) configuration(s)\n\
FILENAME: The config file of the connection to reload \n\
(Optional. Default: all configs)\n\n"
/**
* Help page of command mpt restart
*/
#define HELP_RESTART "mpt restart [FILENAME]\n\
Stops and starts the connection(s), without reloading the config file(s).\n\
WARM Restart, without changing the connections configuration data.\n\
FILENAME: The config file of the connection to restart. \n\
(Optional. Default: all connections\n\n"
/**
* Help page of command mpt delete
*/
#define HELP_DELETE "mpt delete FILENAME\n\
Stops and deletes the specified connection. \n\
FILENAME: The config file of the connection to delete. \n\n"
/**
* Help page of command mpt save
*/
#define HELP_SAVE "mpt save [FILENAME]\n\
Saves the connection(s) configuration. \n\
FILENAME: The config file from which the configuration was loaded in.\n\
(Optional. Defaukt: all connection configs are saved) \n\n"
/**
* Help page of command mpt create
*/
#define HELP_CREATE "mpt create FILENAME\n\
Communicates the creation of the connection to the peer.\n\
FILENAME: The name of the config file of the connection to create\n\n"
/**
* Help page of command mpt path
*/
#define HELP_PATH "mpt path {up | down} SRC_IP DST_IP\n\
Turnes up or down the specified path (if it is present in a connection)\n\
up|down: Change path status to up or down\n\
SRC_IP: IP address of the path local endpoint\n\
DST_IP: IP address of the path on the remote peer\n\n"
/**
* Help page of command mpt path
*/
#define HELP_STATUS "mpt show status\n\
Prints the status of the tunnel and connections\n\n"
/**
* Detailed help of all usable mpt commands
*/
#define HELP HELP_ADDR HELP_CREATE HELP_DELETE HELP_INT HELP_PATH HELP_RELOAD HELP_RESTART HELP_SAVE HELP_STATUS
/** @} */
/// Structure to save arguments of command mpt interface up|down
struct mpt_int {
char * interface; ///< Interface name
char * mark; ///< Mark interface up or down
};
/// Structure to save arguments of command mpt address add|del
struct mpt_addr {
char * op; ///< Operator can be add or del
char * ip; ///< IP Address
char * mask; ///< Network mask
char * dev; ///< Interface name
};
/// Structure to save arguments of command mpt path up|down
struct mpt_change_path {
char * op; ///< Operator can be up or down
bit_32 local_ip[4]; ///< Local IP address
bit_32 remote_ip[4]; ///< IP address of remote peer
};
#endif
|
C
|
#include <apue.h>
#include <myerror.h>
static void my_exit1(void);
static void my_exit2(void);
int main()
{
if (atexit(my_exit1) != 0)
err_sys("can't register my_exit1");
if ( atexit(my_exit2) != 0)
err_sys("can't register my_exit2");
if ( atexit(my_exit2) != 0)
err_sys("can't register my_exit2");
printf("main is done!\n");
return 0;
}
static void my_exit1()
{
printf("hello from my_exit1()\n");
}
static void my_exit2()
{
printf("hello from my_exit2()\n");
}
|
C
|
#include "mock_queue.h"
#include "stdio.h"
enum UIEvent* events;
uint32_t numberOfEvents = 0;
uint32_t currentEvent = 0;
void setEvents(uint32_t newNumberOfEvents, enum UIEvent* newEvents) {
events = newEvents;
numberOfEvents = newNumberOfEvents;
}
long xQueueGenericReceive( void * xQueue, void * pvBuffer, uint32_t xTicksToWait, const long xJustPeek ) {
printf("queueReceive called\n");
printf("returning event index: %d, value: %d", currentEvent, events[currentEvent]);
if (currentEvent < numberOfEvents) {
memcpy( ( void * ) pvBuffer, ( void * ) &events[currentEvent], sizeof(enum UIEvent) );
printf("sizeof: %d\n", sizeof(enum UIEvent));
currentEvent++;
} else {
enum UIEvent final = EXIT;
memcpy( ( void * ) pvBuffer, ( void * ) &final, sizeof(enum UIEvent) );
}
}
|
C
|
#include<stdio.h>
int main()
{
int turn,n;
for(n=1;n<4;n++)
{
while(1)
{
while(turn!=0);
printf("\nI am Process-1 and I am in Critical section");
turn=1;
printf("\nI am Process-1 and I am in Remainder section");
break;
}
while(1)
{
while(turn!=1);
printf("\nI am Process-2 and I am in Critical section");
turn=0;
printf("\nI am Process-2 and I am in Remainder section");
break;
}
}
return 0;
}
|
C
|
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>
void eprint()
{
char error_message[30] = "An error has occurred\n";
write(STDERR_FILENO, error_message, strlen(error_message));
}
int main(){
printf("Welcome to WIscosin SHell");
char command[100];
char path[100]="/bin/";
char *args[100];
char *temp=NULL;
char *found=NULL;
args[0]=(char *)malloc(sizeof(path));
args[1]=NULL;
// args[0]=strdup(path);
printf("The args is %s",args[0]);
args[0]=strdup("/bin/ls/\0");
printf("The args is %s",args[0]);
while(strcmp(command,"exit")!=0)
{
// printf("0");
printf("\nwish>");
gets(command);
// printf("\nPID is %d\n",pid);
printf("\nCommand is %s\n",command);
temp=strdup(command);
printf("\nTemp Command is %s\n",temp);
int pid=fork();
if(pid==-1)
{
eprint();
}
else if(pid==0)
{
printf("CHILD ||");
int i=0;
printf("\nfound | %s\n",found);
while((found=strsep(&temp," "))!=NULL)
{
printf("STARTED");
printf("found is | %s ",found);
args[i]=found;
i++;
}
strcat(path,args[0]);
args[0]=path;
i=0;
while(args[i]!=NULL)
{
printf("\nArgs[%d] is %s\n",i,args[i]);
i++;
}
// printf("\nArgs[1] is %s\n",args[1]);
// printf("\nArgs[2] is %s\n",args[2]);
// printf(path);
execv(args[0],args);
i=0;
while(args[i]!=NULL)
{
args[i]=NULL;
i++;
// args[1]=NULL;
}
exit(0);
}
else
{
wait(NULL);
printf("PARENT hu mei");
}
}
// else
// printf("Exiting");
return 1;
}
|
C
|
/************************************************************
* Program : HTTP Downloader
* Description : Program to get HTTP header info.
* Version : 0.04
************************************************************
* by Philip "5n4k3" Simonson
************************************************************
*/
/* standard headers */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <time.h>
/* linux network headers */
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#define CHUNK_SIZE 512
#define HTTP_INFOSIZE 2048
#define HTTP_LOCATION 512
#define HTTP_CTYPE 256
#define HTTP_PROTO 6
#define HTTP_URLSIZE 512
/* My Found enumeration */
enum _HTTPFOUND {
FOUND_LOC,
FOUND_CTYPE,
FOUND_COUNT
};
/* My HTTP header struct */
struct _HTTPHEADERstruct {
int info_size;
float version;
int result;
char domain[HTTP_URLSIZE];
char uri[HTTP_URLSIZE];
char proto[HTTP_PROTO];
char loc[HTTP_LOCATION];
char ctype[HTTP_CTYPE];
char *data;
char *info;
};
typedef struct _HTTPHEADERstruct HTTPHEADER;
/* My http function prototypes */
int handle_redirect(HTTPHEADER *header);
char *get_httpdata(int sockfd, size_t *total);
size_t http_download(const char *uri, const char *domain);
/* My info header function prototypes */
HTTPHEADER setup_headerinfo(void);
void destroy_headerinfo(HTTPHEADER *header);
void get_httpheader(HTTPHEADER *header, char *data, size_t size);
void get_headerinfo(HTTPHEADER *header);
int get_urlinfo(const char *url, char *uripath, char *domain);
/* My misc function prototypes */
int create_conn(const char *domain);
int get_filename(const char *path, char *fname, char *ext);
void timer(int sec);
void clear_filebuffer(FILE *fp);
size_t file_download(int sockfd, FILE *fout);
/* The request string you have to send to a HTTP server */
#define HTTP_REQUEST "GET %s HTTP/1.0\r\nHost: %s\r\n\r\n"
/* main() - entry point for program.
*/
int main(int argc, char **argv) {
HTTPHEADER header;
struct addrinfo hints, *servinfo;
int sockfd, newsockfd;
char request[BUFSIZ];
char *data;
size_t total_bytes;
int bytes, c;
int res;
if(argc != 3) {
fprintf(stderr, "Usage: %s <hostname> <urlpath>\n", argv[0]);
return 0;
}
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if(getaddrinfo(argv[1], "80", &hints, &servinfo) < 0) {
fprintf(stderr, "Error: getting host by addr.\n");
return 1;
}
if((sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
fprintf(stderr, "Error: Cannot create socket.\n");
return 1;
}
if(connect(sockfd, servinfo->ai_addr, servinfo->ai_addrlen) < 0) {
fprintf(stderr, "Error: Cannot connect to host %s.\n", argv[1]);
close(sockfd);
return 1;
}
freeaddrinfo(servinfo);
puts("Connected.");
memset(request, 0, sizeof(request));
snprintf(request, sizeof(request), HTTP_REQUEST, argv[2], argv[1]);
bytes = send(sockfd, request, strlen(request), 0);
if(bytes < 0) {
fprintf(stderr, "Error: Couldn't send request.\n");
close(sockfd);
return 1;
} else
puts("Request sent.");
header = setup_headerinfo();
if((data = get_httpdata(sockfd, &total_bytes)) == NULL) {
fprintf(stderr, "Cannot get website data.\n");
close(sockfd);
return 1;
}
get_httpheader(&header, data, total_bytes);
get_headerinfo(&header);
#if !defined(NDEBUG)
printf("Website Info...\n===================\n%s\n===================\n",
header.info);
printf("Version: %.1f\nResult: %d\nLocation: %s\n",
header.version, header.result, header.loc);
#endif
if(header.result == 404) {
puts("Uri path not found on server.");
free(data);
destroy_headerinfo(&header);
close(sockfd);
return 1;
}
while(header.result == 301 || header.result == 302) {
sockfd = handle_redirect(&header);
if(sockfd < 0) {
free(data);
destroy_headerinfo(&header);
return 1;
} else {
data = get_httpdata(sockfd, &total_bytes);
if(data == NULL) {
fprintf(stderr, "Cannot get website data.\n");
close(sockfd);
return 1;
} else {
get_httpheader(&header, data, total_bytes);
get_headerinfo(&header);
#if !defined(NDEBUG)
printf("Website Info...\n====================\n%s\n"\
"=====================\n", header.info);
printf("Version: %.1f\nResult: %d\nLocation: %s\n",
header.version, header.result, header.loc);
#endif
if(header.result == 404) {
puts("Uri path not found on server.");
break;
}
}
}
}
printf("Did you want to see the received transmission (Y/N)? ");
scanf("%c", &c);
clear_filebuffer(stdin);
if(c == 'y' || c == 'Y') {
printf("Domain requested data below...\n\n%s\n\nProcessing data...\n",
header.info);
printf("Response: %d\nLocation: %s\n\n", header.result,
header.loc);
} else {
puts("You didn't want to see the requested data?");
}
if(header.result != 404) {
printf("Did you want to download the file (Y/N)? ");
scanf("%c", &c);
clear_filebuffer(stdin);
if(c == 'y' || c == 'Y') {
if(strncmp(header.loc, "None", 4) == 0) {
total_bytes = http_download(argv[2], argv[1]);
} else {
get_urlinfo(header.loc, header.uri, header.domain);
total_bytes = http_download(header.uri, header.domain);
}
}
}
puts("Disconnected.");
destroy_headerinfo(&header);
free(data);
close(sockfd);
return 0;
}
/* get_httpdata() - function to get website data.
*/
char *get_httpdata(int sockfd, size_t *total) {
char buffer[CHUNK_SIZE];
char *data = NULL;
size_t size = 0;
size_t total_bytes = 0;
size_t bytes;
while((bytes = recv(sockfd, buffer, CHUNK_SIZE, 0)) > 0) {
if(total_bytes >= size) {
size += bytes;
data = realloc(data, size);
if(data == NULL)
return NULL;
}
memcpy(&data[total_bytes], buffer, bytes);
total_bytes += bytes;
}
if(bytes == 0) {
printf("Transfer of %u bytes received successfully.\n", total_bytes);
*total = total_bytes;
return data;
} else {
fprintf(stderr, "Transfer of %u bytes failed.\n", bytes);
free(data);
}
return NULL;
}
/* handle_redirect() - handles HTTP redirection.
*/
int handle_redirect(HTTPHEADER *header) {
char request[1024];
int sockfd, res;
memset(request, 0, sizeof(request));
if(get_urlinfo(header->loc, header->uri, header->domain) < 0)
return -1;
sockfd = create_conn(header->domain);
if(sockfd < 0)
return -1;
snprintf(request, sizeof(request), HTTP_REQUEST, header->uri, header->domain);
res = send(sockfd, request, strlen(request), 0);
if(res < 0) {
puts("Failed to send redirection request.");
close(sockfd);
return -1;
}
return sockfd;
}
/* create_conn() - creates a new connection to the requested host.
*/
int create_conn(const char *domain) {
struct addrinfo hints, *servinfo;
int sockfd;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if(getaddrinfo(domain, "80", &hints, &servinfo) < 0) {
fprintf(stderr, "Error: Cannot get address information.\n");
return -1;
}
if((sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
fprintf(stderr, "Error: Could not create a socket.\n");
return -1;
}
if(connect(sockfd, servinfo->ai_addr, servinfo->ai_addrlen) < 0) {
fprintf(stderr, "Error: Could not connect to server.\n"\
"Host might be unreachable...\n");
return -1;
}
freeaddrinfo(servinfo);
puts("Connected");
return sockfd;
}
/* get_filename() - gets filename from a full path.
*/
int get_filename(const char *path, char *fname, char *ext) {
char found = 0;
char *tmp, *dot;
const char *end;
end = path;
while(*end++ != 0);
if((tmp = strrchr(path, '/')) != NULL)
found = 1;
if((dot = strrchr(path, '.')) != NULL) {
if(found)
strncpy(fname, &tmp[1], dot-tmp-1);
else
strncpy(fname, path, dot-path);
strncpy(ext, &(*(dot+1)), end-dot);
} else {
return 1;
}
return 0;
}
/* http_download() - content-type not text/plain or text/html then
* download the content.
*/
size_t http_download(const char *uri, const char *domain) {
FILE *file = NULL;
char filename[261];
char fname[256];
char ext[5];
char request[512];
size_t total_bytes;
int bytes, res, sockfd;
memset(filename, 0, sizeof(filename));
memset(fname, 0, sizeof(fname));
memset(ext, 0, sizeof(ext));
memset(request, 0, sizeof(request));
res = get_filename(uri, fname, ext);
if(res != 0) {
fprintf(stderr, "Error: Could not get file name.\n");
return -1;
}
printf("Filename: %s.%s\n", fname, ext);
snprintf(filename, sizeof(filename), "%s.%s", fname, ext);
snprintf(request, sizeof(request), HTTP_REQUEST, uri, domain);
if((sockfd = create_conn(domain)) < 0) {
fprintf(stderr, "Error: Could not reconnect to host.\n");
return -1;
}
bytes = send(sockfd, request, strlen(request), 0);
if(bytes < 0) {
fprintf(stderr, "Error: Sending request string.\n");
return -1;
}
if((file = fopen(filename, "wb")) == NULL) {
fprintf(stderr, "Error: Cannot open file for writing.\n");
return -1;
}
total_bytes = file_download(sockfd, file);
if(total_bytes < 0) {
fprintf(stderr, "Error: Could not download the file.\n");
fclose(file);
return -1;
} else {
printf("Total bytes downloaded: %lu\nFile download was succesful!\n",
total_bytes);
}
fclose(file);
close(sockfd);
return total_bytes;
}
/* setup_headerinfo() - initializes the http header info structure.
*/
HTTPHEADER setup_headerinfo(void) {
HTTPHEADER header;
memset(&header, 0, sizeof(HTTPHEADER));
header.info = NULL;
header.data = NULL;
strncpy(header.proto, "http", 5);
return header;
}
/* destroy_headerinfo() - destroys the http header info structure.
*/
void destroy_headerinfo(HTTPHEADER *header) {
if(header == NULL)
return;
if(header->info != NULL)
free(header->info);
if(header->data != NULL)
free(header->data);
memset(header, 0, sizeof(HTTPHEADER));
}
/* get_httpheader() - strips the header out of the data.
*/
void get_httpheader(HTTPHEADER *header, char *data, size_t size) {
char *info = NULL;
if(data == NULL)
return;
data[size] = 0;
info = strstr(data, "\r\n\r\n");
header->info_size = info-data;
header->info = malloc(header->info_size+1);
memcpy(header->info, data, header->info_size);
header->info[header->info_size] = 0;
header->data = malloc((size-header->info_size)+1);
memcpy(header->data, &data[header->info_size],
size-header->info_size);
header->data[(size-header->info_size)+1] = 0;
}
/* get_headerinfo() - strips out the http response and location if
* one exists.
*/
void get_headerinfo(HTTPHEADER *header) {
char info[header->info_size];
char *tok = NULL;
char found[FOUND_COUNT];
strncpy(info, header->info, sizeof(info));
tok = strtok(info, "\r\n");
if(strncmp(tok, "HTTP/", 5) == 0)
sscanf(tok, "HTTP/%f %d %*[^\r]\r\n",
&header->version, &header->result);
while(tok != NULL) {
if(strncmp(tok, "Location:", 9) == 0) {
if(sscanf(tok, "Location: %s\r\n", header->loc) != 1)
found[FOUND_LOC] = 0;
else
found[FOUND_LOC] = 1;
}
if(strncmp(tok, "Content-Type:", 13) == 0) {
if(sscanf(tok, "Content-Type: %s\r\n", header->ctype) != 1)
found[FOUND_CTYPE] = 0;
else
found[FOUND_CTYPE] = 1;
}
tok = strtok(NULL, "\r\n");
}
if(!found[FOUND_LOC])
snprintf(header->loc, HTTP_LOCATION, "None");
if(!found[FOUND_CTYPE])
snprintf(header->ctype, HTTP_CTYPE, "Not Found");
}
/* get_urlinfo() - function to get the url from header location.
*/
int get_urlinfo(const char *url, char *uripath, char *domain) {
if(sscanf(url, "http://%[^/]%s", domain, uripath) != 2) {
fprintf(stderr, "Error: Couldn't extract uri and domain from url.\n");
return -1;
}
return 0;
}
/* timer() - function for a simple timer.
*/
void timer(int sec) {
clock_t start = clock();
while(1) {
int secs = (clock()-start) / CLOCKS_PER_SEC;
if(secs >= 5)
break;
}
}
/* clear_filebuffer() - function to clear input buffer.
*/
void clear_filebuffer(FILE *fp) {
int c;
while((c = getc(stdin)) != EOF && c != 0x0A);
}
/* file_download() - function to download a file.
*/
size_t file_download(int sockfd, FILE *fout) {
char data[CHUNK_SIZE];
int bytesRead, bytesWritten;
static size_t total_bytes = 0;
clock_t start = clock();
while((bytesRead = read(sockfd, data, sizeof(data))) > 0) {
bytesWritten = fwrite(data, 1, bytesRead, fout);
if(bytesWritten == bytesRead)
total_bytes += bytesWritten;
if(((clock()-start) / CLOCKS_PER_SEC) >= 5) {
printf("Total bytes downloaded: %lu\n", bytesWritten);
start = clock();
}
}
if(bytesRead == 0)
return total_bytes;
return -1;
}
|
C
|
#include<stdio.h>
int main()
{
int N,a,b,c,d,e,f;
scanf("%d",&N);
a=N/3600;
b=N%3600;
c=b/60;
d=b%60;
e=d/60;
f=d%60;
printf("%d:%d:%d",a,c,f);
return 0;
}
|
C
|
#include "server.h"
int encrypt_and_send(byte * msg , const int length){
if(encType == PLAIN) //send plain text
{
if(writeInPipe(outputChannel, (byte *) msg , length) < 0)
{
fprintf(stderr , " **** Communication phase write error **** \n\n");
return -1;
}
return 0;
}
if(encType == RSA512){
BIGNUM *message = BN_new();
byte fullMsg[RSA512_BYTE_LENGTH];
memset(fullMsg , 0 , sizeof(byte) * RSA512_BYTE_LENGTH);
memcpy(fullMsg , msg , sizeof(byte) * length);
message = BN_bin2bn((const unsigned char *) fullMsg, RSA512_BYTE_LENGTH , NULL);
rsaEXP(message , &client512Rsa); //Encrypt with server RSA public key
BN_bn2bin(message , fullMsg);
if(writeInPipe(outputChannel, (byte *) fullMsg , RSA512_BYTE_LENGTH) < 0)
{
fprintf(stderr , " **** Communication phase write error **** \n\n");
return -1;
}
printf("RSA512 : %s\n", BN_bn2hex(message));
BN_free(message);
return 0;
}
if(encType == RSA64){
BIGNUM *message = BN_new();
byte fullMsg[RSA64_BYTE_LENGTH];
memset(fullMsg , 0 , sizeof(byte) * RSA64_BYTE_LENGTH);
memcpy(fullMsg , msg , sizeof(byte) * length);
message = BN_bin2bn((const unsigned char *) fullMsg, RSA64_BYTE_LENGTH , NULL);
rsaEXP(message , &client64Rsa); //Encrypt with server RSA public key
BN_bn2bin(message , fullMsg);
if(writeInPipe(outputChannel, (byte *) fullMsg , RSA64_BYTE_LENGTH) < 0)
{
fprintf(stderr , " **** Communication phase write error **** \n\n");
return -1;
}
printf("RSA64 : %s\n", BN_bn2hex(message));
BN_free(message);
return 0;
}
}
int receive_and_decrypt(byte * msg){
int length = readFromPipe(inputChannel , msg);
if(length < 0)
{
fprintf(stderr , " **** error reading message **** \n\n");
return -1;
}
if(strncmp(msg , ClientCloseConnection , length) == 0 && length == strlen(ClientCloseConnection))
return length;
if(encType == PLAIN)
return length;
if(encType == RSA64){
BIGNUM *message = BN_new();
message = BN_bin2bn((const unsigned char *) msg, RSA64_BYTE_LENGTH , NULL);
printf("%s\n", BN_bn2hex(message));
rsaEXP(message , &server64Rsa); //Decrypt with private keyExchange
BN_bn2bin(message , msg);
BN_free(message);
return length;
}
if(encType == RSA512){
BIGNUM *message = BN_new();
message = BN_bin2bn((const unsigned char *) msg, RSA512_BYTE_LENGTH , NULL);
printf("%s\n", BN_bn2hex(message));
rsaEXP(message , &server512Rsa); //Decrypt with private keyExchange
BN_bn2bin(message , msg);
BN_free(message);
return length;
}
if(encType == Cipher_ALL5){
BIGNUM *tm = BN_new();
tm = BN_bin2bn((const unsigned char *) msg, length , NULL);
printf("ALL5 : %s\n", BN_bn2hex(tm));
byte message[length - HASH_BYTE_LENGTH];
byte hash[HASH_BYTE_LENGTH];
int recv_length = length;
if(cipherSpec.hash_function == hash_spongeBunny)
{
recv_length -= HASH_BYTE_LENGTH;
memmove(hash , msg + (sizeof(byte) * recv_length) , sizeof(byte) * HASH_BYTE_LENGTH); //copy the hash
memcpy(message , msg , sizeof(byte) * recv_length); //copy the cihpertext
ALL5_decrypt(&cipherStruct.all5, message, message, recv_length); //decrypt
byte rec_hash[HASH_BYTE_LENGTH];
spongeBunnyComputeHash(message , rec_hash , recv_length); //compute the hash of the plaintext
if(memcmp(rec_hash, hash, sizeof(byte) * HASH_BYTE_LENGTH) != 0)
{
recv_length = 0;
fprintf(stderr , "Wrong HASH !!!!!!! \n");
}
tm = BN_bin2bn((const unsigned char *) hash, HASH_BYTE_LENGTH , NULL);
printf("HASH : %s\n", BN_bn2hex(tm));
memcpy(msg , message , sizeof(byte) * recv_length);
} //no hash function
else
ALL5_decrypt(&cipherStruct.all5, msg, msg, recv_length); //decrypt
BN_free(tm);
return recv_length;
}
if(encType == Cipher_MAJ5){
BIGNUM *tm = BN_new();
tm = BN_bin2bn((const unsigned char *) msg, length , NULL);
printf("MAJ5 : %s\n", BN_bn2hex(tm));
int recv_length = length;
if(cipherSpec.hash_function == hash_spongeBunny)
{
byte message[length - HASH_BYTE_LENGTH];
byte hash[HASH_BYTE_LENGTH];
recv_length -= HASH_BYTE_LENGTH;
memmove(hash , msg + (sizeof(byte) * recv_length) , sizeof(byte) * HASH_BYTE_LENGTH); //copy the hash
memcpy(message , msg , sizeof(byte) * recv_length); //copy the cihpertext
MAJ5_decrypt(&cipherStruct.maj5, message, message, recv_length); //decrypt
byte rec_hash[HASH_BYTE_LENGTH];
spongeBunnyComputeHash(message , rec_hash , recv_length); //compute the hash of the plaintext
if(memcmp(rec_hash, hash, sizeof(byte) * HASH_BYTE_LENGTH) != 0)
{
recv_length = 0;
fprintf(stderr , "Wrong HASH !!!!!!! \n");
}
tm = BN_bin2bn((const unsigned char *) hash, HASH_BYTE_LENGTH , NULL);
printf("HASH : %s\n", BN_bn2hex(tm));
memcpy(msg , message , sizeof(byte) * recv_length);
} //no hash function
else
MAJ5_decrypt(&cipherStruct.maj5, msg, msg, recv_length); //decrypt
BN_free(tm);
return recv_length;
}
if(encType == Cipher_Bunny24){
BIGNUM *tm = BN_new();
tm = BN_bin2bn((const unsigned char *) msg, length , NULL);
printf("BUNNY24 : %s \n", BN_bn2hex(tm));
int recv_length = length - HASH_BYTE_LENGTH;
byte hash[HASH_BYTE_LENGTH];
byte mess[recv_length];
memmove(hash , msg + (sizeof(byte) * recv_length) , sizeof(byte) * HASH_BYTE_LENGTH); //copy the hash
memcpy(mess , msg , sizeof(byte) * recv_length);
int message_bit_length = recv_length * 8;
bit plain_bit_text[message_bit_length]; //plaintext in bits
bit crypt_bit_text[message_bit_length]; //ciphertext in bits
bit plain_byte_text[recv_length];
memset(plain_byte_text , 0 , sizeof(byte) * recv_length);
int i;
for(i = 0; i < message_bit_length; i++)
crypt_bit_text[i] = (msg[i / 8] & (1 << i % 8)) ? 1 : 0; //to bit
bunny24CBC_decrypt(plain_bit_text, crypt_bit_text , init_vector , cipherStruct.key , message_bit_length); // encrypt
for(i = 0; i < message_bit_length; i++)
plain_byte_text[i/8] |= (plain_bit_text[i] << (i % 8)); //to byte
strcpy(msg ,plain_byte_text);
msg[strlen(msg) + 1] = '\0';
byte rec_hash[HASH_BYTE_LENGTH];
memset(rec_hash , 0 , sizeof(byte) * HASH_BYTE_LENGTH);
spongeBunnyComputeHash(msg , rec_hash , strlen(msg) + 1); //compute the hash of the ciphertext
if(memcmp(rec_hash, hash, sizeof(byte) * HASH_BYTE_LENGTH) != 0)
fprintf(stderr , "Wrong HASH !!!!!!! \n");
tm = BN_bin2bn((const unsigned char *) rec_hash , HASH_BYTE_LENGTH , NULL);
printf("\nHASH : %s\n", BN_bn2hex(tm));
BN_free(tm);
return strlen(msg) + 1;
}
}
int loadServerRsaKey(){
server512Rsa.modulo = BN_new();
server512Rsa.exponent = BN_new();
server64Rsa.modulo = BN_new();
server64Rsa.exponent = BN_new();
readRsaKey(ServerRsa512PrivateKeyFile , NULL , &server512Rsa);
readRsaKey(ServerRsa64PrivateKeyFile , NULL , &server64Rsa);
}
int loadClientRsaKey(const char * clientName){
client512Rsa.modulo = BN_new();
client512Rsa.exponent = BN_new();
client64Rsa.modulo = BN_new();
client64Rsa.exponent = BN_new();
readRsaKey(ClientRsa64PublicKeyFile , clientName , &client64Rsa);
readRsaKey(ClientRsa512PublicKeyFile , clientName , &client512Rsa);
}
void clearRsaKey(){
BN_free(server512Rsa.modulo);
BN_free(server512Rsa.exponent);
BN_free(client64Rsa.modulo);
BN_free(client64Rsa.exponent);
BN_free(server64Rsa.modulo);
BN_free(server64Rsa.exponent);
BN_free(client512Rsa.modulo);
BN_free(client512Rsa.exponent);
}
int openFifo(const char * pathname){
/* Recreate the FIFO in pathname */
unlink(pathname);
if(mkfifo(pathname,0600) < 0 ) {
perror("mkfifo()");
return -1;
}
/* Open the channel */
return (openChannel(pathname));
}
serverState handshake(){
fprintf(stderr , "-----------------------------------------------------------\n **** Waiting for handshake ****\n\n");
char buffer[MSG_MAX_SIZE];
int length = readFromPipe(inputChannel ,(byte *) buffer);
printMsg("Client to server ---> " , buffer , length);
if(strncmp(buffer , ClientOpenConnection , length) != 0 || length != strlen(ClientOpenConnection))
{
fprintf(stderr, "Handshake read error\n");
return ERROR;
}
if(writeInPipe(outputChannel,(byte *) ServerOpenConnection , strlen(ServerOpenConnection)) < 0)
{
fprintf(stderr, "Handshake write error\n");
return ERROR;
}
printMsg("Server to client ---> " , ServerOpenConnection , strlen(ServerOpenConnection));
return HANDSHAKE;
}
serverState authentication(){
fprintf(stderr , " **** Authentication phase **** \n\n");
if(loadServerRsaKey() == -1)
{
fprintf(stderr , "Error while loading RSA keys\n" );
return ERROR;
}
BIGNUM *message = BN_new();
byte msg512[RSA512_BYTE_LENGTH];
memset(msg512 , 0 , RSA512_BYTE_LENGTH * sizeof(byte));
encType = RSA512;
fprintf(stderr , "< Client challenge, server authentication > \n");
receive_and_decrypt(msg512);
encType = PLAIN;
fprintf(stderr , "\n< Server response, server authentication >\n");
encrypt_and_send(msg512 , RSA512_BYTE_LENGTH);
message = BN_bin2bn((const unsigned char *) msg512, RSA512_BYTE_LENGTH , NULL);
printf("PLAIN : %s\n", BN_bn2hex(message));
BN_free(message);
fprintf(stderr , "\n **** client authentication **** \n\n");
char clientName[256];
fprintf(stderr , "\n< Client name , client authentication >\n");
int length = receive_and_decrypt(clientName);
clientName[length] = '\0';
fprintf(stderr , "PLAIN : %s\n" , clientName);
if(loadClientRsaKey(clientName) == -1)
{
fprintf(stderr , "Error while loading RSA keys\n" );
return ERROR;
}
message = BN_new();
BIGNUM *original = BN_new();
bit buffer[RSA64_BIT_LENGTH]; //buffer for the pseudo message
byte msg64[RSA64_BYTE_LENGTH]; //pseudo message converted in byte
memset(msg64 , 0 , RSA64_BYTE_LENGTH * sizeof(byte));
initFPRNG();
FPRNG(buffer, RSA64_BIT_LENGTH / 2); // generates random bits.
int i;
for(i = 0; i < RSA64_BIT_LENGTH / 2; i++)
msg64[i/8] |= (buffer[i] << (i % 8)); //to byte
original = BN_bin2bn((const unsigned char *) msg64, RSA64_BYTE_LENGTH , NULL);
encType = RSA64;
fprintf(stderr , "< Server challenge, client authentication > \n");
encrypt_and_send(msg64 , RSA64_BYTE_LENGTH);
encType = PLAIN;
fprintf(stderr , "\n< Client response, client authentication >\n");
receive_and_decrypt(msg64);
message = BN_bin2bn((const unsigned char *) msg64, RSA64_BYTE_LENGTH , NULL);
printf("PLAIN : %s\n", BN_bn2hex(message));
fprintf(stderr , "\n< Server plain challenge, client authentication > \n");
printf("PLAIN : %s\n", BN_bn2hex(original));
if(BN_cmp(original , message) != 0)
{
fprintf(stderr , "\n **** challenge Message error **** \n\n");
return CLOSING;
}
BN_free(message);
BN_free(original);
fprintf(stderr , "\n **** Authentication phase completed **** \n\n");
return AUTHENTICATED;
}
serverState keyExchange(){
encType = PLAIN;
fprintf(stderr , " **** Key Exhange phase **** \n\n");
char cChiper[1];
fprintf(stderr , "\n< Client cipher spec , client key exchange >\n");
receive_and_decrypt(cChiper);
fprintf(stderr , " %c \n" , cChiper[0]);
if(isInCipherSpec(ServerCipherSpecFile , cChiper) == -1) //if i have the cipher
{
fprintf(stderr , "\n< No cipher %c >\n" , cChiper[0]);
return ERROR;
}
fprintf(stderr , "\n< Client cipher accepted , key generation >\n");
switch(cChiper[0]){
case 'A': cipherSpec.symmetric_cipher = Cipher_Bunny24;
cipherSpec.public_cipher = RSA64;
cipherSpec.hash_function = hash_spongeBunny;
break;
case 'B': cipherSpec.symmetric_cipher = Cipher_Bunny24;
cipherSpec.public_cipher = RSA512;
cipherSpec.hash_function = hash_spongeBunny;
break;
case 'C': cipherSpec.symmetric_cipher = Cipher_ALL5;
cipherSpec.public_cipher = RSA64;
cipherSpec.hash_function = hash_spongeBunny;
break;
case 'D': cipherSpec.symmetric_cipher = Cipher_ALL5;
cipherSpec.public_cipher = RSA512;
cipherSpec.hash_function = hash_spongeBunny;
break;
case 'E': cipherSpec.symmetric_cipher = Cipher_MAJ5;
cipherSpec.public_cipher = RSA64;
cipherSpec.hash_function = hash_spongeBunny;
break;
case 'F': cipherSpec.symmetric_cipher = Cipher_MAJ5;
cipherSpec.public_cipher = RSA512;
cipherSpec.hash_function = hash_spongeBunny;
break;
default : break;
}
bit buffer24[24] , buffer64[64];
byte key24[3] , key64[8];
memset(key24 , 0 , sizeof(byte) * 3);
memset(key64 , 0 , sizeof(byte) * 8);
int i;
BIGNUM *tm;
tm = BN_new();
encType = cipherSpec.public_cipher;
if(cipherSpec.symmetric_cipher == Cipher_Bunny24)
{
FPRNG(buffer24 , 24);
for(i = 0; i < 24; i++)
key24[i/8] |= (buffer24[i] << (i % 8)); //to byte
tm = BN_bin2bn((const unsigned char *) key24, 3 , NULL);
printf("PLAIN : %s\n", BN_bn2hex(tm));
encrypt_and_send(key24 , 3);
cipherInit(&cipherStruct , buffer24 , 24 , init_vector , 24, Cipher_Bunny24);
}
else
{
FPRNG(buffer64 , 64);
for(i = 0; i < 64; i++)
key64[i/8] |= (buffer64[i] << (i % 8)); //to byte
tm = BN_bin2bn((const unsigned char *) key64, 8 , NULL);
printf("PLAIN : %s\n", BN_bn2hex(tm));
encrypt_and_send(key64 , 8);
cipherInit(&cipherStruct , buffer64 , 64 , init_vector , 24, cipherSpec.symmetric_cipher);
}
BN_free(tm);
fprintf(stderr , "\n **** Key Exhange completed **** \n\n");
return COMMUNICATION;
}
serverState communication(){
char msg[MSG_MAX_SIZE];
int length = 0;
do{
encType = cipherSpec.symmetric_cipher;
fprintf(stderr , "\n< Client message , communication > \n");
length = receive_and_decrypt(msg);
if(strncmp(msg , ClientCloseConnection , length) == 0 && length == strlen(ClientCloseConnection)){
fprintf(stderr , "%s" , ClientCloseConnection);
encType = PLAIN;
return CLOSING;
}
encType = PLAIN;
fprintf(stderr , "\n< Server response , communication >\n" );
encrypt_and_send(msg , length);
printMsg("" , msg ,(u_int16_t) length);
}while(1);
}
serverState closeConnection(){
encType = PLAIN;
fprintf(stderr , "\n< Server response , closing >\n" );
encrypt_and_send(ServerCloseConnection , strlen(ServerCloseConnection));
fprintf(stderr , "%s" , ServerCloseConnection);
return WAITING;
}
int main(int argc, char ** argv){
state = WAITING;
/* Mandatory arguments */
if( !argv[1] || !argv[2] || !argv[3] ) {
fprintf(stderr,"server [server->client fifo] [client->server fifo] [password file]\n");
exit(1);
}
/* Open the server->client fifo */
fprintf(stderr,"Opening server->client fifo...\n");
outputChannel = openFifo(argv[1]);
/* Open the client->server fifo */
fprintf(stderr,"Opening client->server fifo...\n");
inputChannel = openFifo(argv[2]);
do{
switch(state){
case WAITING : state = handshake();
if(state == ERROR) //handshake error
fprintf(stderr , "\n **** handshake falied **** \n\n");
else
fprintf(stderr , "\n **** handshake succeded **** \n\n");
break;
case HANDSHAKE : state = authentication();
break;
case AUTHENTICATED : state = keyExchange();
break;
case COMMUNICATION : state = communication();
break;
case CLOSING : state = closeConnection();
outputChannel = openFifo(argv[1]);
inputChannel = openFifo(argv[2]);
if(state == ERROR) //handshake error
fprintf(stderr , "\n **** closing falied **** \n\n");
else
fprintf(stderr , "\n **** closing succeded **** \n\n");
break;
case ERROR :
fprintf(stderr , "\nError during the communication, force shutodown of the client\n\n");
closeConnection();
state = WAITING;
outputChannel = openFifo(argv[1]);
inputChannel = openFifo(argv[2]);
fprintf(stderr , "\n **** closing succeded **** \n\n");
break; //close connection
default : break;
}
}while(1);
exit(0);
}
|
C
|
#include "libft.h"
/*Allocate (with malloc(3)) and returns a “fresh” string ending
with ’\0’ representing the integer n given as argument.
Negative numbers must be supported. If the allocation fails,
the function returns NULL.
*/
static size_t n_length(int n)
{
size_t i;
i = 1;
while (n /= 10)
i++;
return (i);
}
char *ft_itoa(int n)
{
char *str;
size_t len;
unsigned int tmp;
len = n_length(n);
tmp = n;
if (n < 0)
{
tmp = -n;
len++;
}
if ((str = (char *)malloc(sizeof(char) * (len + 1))) == NULL)
return (NULL);
str[len] = '\0';
str[--len] = tmp % 10 + '0';
while (tmp /= 10)
str[--len] = tmp % 10 + '0';
if (n < 0)
str[0] = '-';
return (str);
}
|
C
|
#include<iostream>
#include<algorithm>
#include<string>
#include<map>
#include<queue>
using namespace std;
const int N=3;
const int N2=9;
class puzzle
{
public:
int f[N2];
int space;
string path;
bool operator<(const puzzle &p)const
{
for(int i=0;i<N2;i++)
{
if(f[i]==p.f[i])continue;
return f[i]>p.f[i];
}
return false;
}
};
const int dx[4]={-1,0,1,0};
const int dy[4]={0,-1,0,1};
const char dir[4]={'u','l','d','r'};
bool istarget(puzzle p)
{
for(int i=0;i<N2;i++)if(p.f[i]!=i+1)return false;
return true;
}
string bfs(puzzle s)
{
queue<puzzle>Q;
map<puzzle,bool>V;
puzzle u,v;
s.path="";
Q.push(s);
V[s]=true;
while(!Q.empty())
{
u=Q.front();Q.pop();
if(istarget(u))return u.path;
int sx=u.space/N;
int sy=u.space%N;
for(int r=0;r<4;r++)
{
int tx=sx+dx[r];
int ty=sy+dy[r];
if(tx<0||tx>=N||ty<0||ty>=N)continue;
v=u;
swap(v.f[u.space],v.f[tx*N+ty]);
v.space=tx*N+ty;
if(!V[v])
{
V[v]=true;
v.path+=dir[r];
Q.push(v);
}
}
}
return "unsolvable";
}
int main()
{
puzzle in;
for(int i=0;i<N2;i++)
{
cin>>in.f[i];
if(in.f[i]==0)
{
in.f[i]=N2;
in.space=i;
}
}
string ans=bfs(in);
if(ans!="unsolvable")cout<<ans.length()<<endl;
else cout<<ans<<endl;
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
#define Euler 2.71828182846
int pG = 0, lG = 0;
int main(void)
{
char operador;
int a,b,c;
int i, N;
//pG = lG = 0;
scanf("%d", &N);
char vet [N];
for(i = 0 ; i < N; i++)
{
scanf("%d %c %d",&a,&operador,&b);
scanf("%d %c",&c,&operador);
if((double) c/Euler > a && c > b)
{
pG++;
vet[i] = 1;
}
else if(b*log(a) < log(2 * M_PI)/2.0 + (c + 1/2.0)*log(c) - c)
{
pG++;
vet[i] = 1;
}
else
{
lG++;
vet[i] = 0;
}
}
if(pG > lG)
printf("Campeao: Pedro!\n");
else if(lG > pG)
printf("Campeao: Lucas!\n");
else
printf("A partida terminou empatada!\n");
for(i = 0; i < N; i++ )
{
if (vet[i]==1)
printf("Rodada #%d: Pedro foi o vencedor\n", i+1);
else
printf("Rodada #%d: Lucas foi o vencedor\n", i+1);
}
}
|
C
|
#include <pthread.h>
#include <stdio.h>
#include <fcntl.h>
pthread_mutex_t lock_file = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond;
pthread_mutex_t lock_cond = PTHREAD_MUTEX_INITIALIZER;
static int cnt = 0;
void *cb(void *arg) {
pthread_mutex_lock(&lock_file);
int fd = open("test.log",O_WRONLY|O_APPEND|O_CREAT);
write(fd, "test\n", 5);
close(fd);
pthread_mutex_unlock(&lock_file);
pthread_mutex_lock(&lock_cond);
++cnt;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock_cond);
}
int main() {
pthread_t p1, p2, p3;
pthread_create(&p1, NULL, cb, NULL);
pthread_create(&p2, NULL, cb, NULL);
pthread_create(&p3, NULL, cb, NULL);
/*
void *ret;
pthread_join(p1, &ret);
pthread_join(p2, &ret);
pthread_join(p3, &ret);
*/
pthread_mutex_lock(&lock_cond);
while (cnt < 3)
pthread_cond_wait(&cond, &lock_cond);
pthread_mutex_unlock(&lock_cond);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s input\n", argv[0]);
exit(1);
}
FILE* in = fopen(argv[1], "r");
char* line = calloc(100, sizeof(char));
uint64_t *mem = calloc(100000, sizeof(uint64_t));
int i;
for (i = 0; i < 100000; i++) {
mem[i] = 0ULL;
}
uint64_t andmask, ormask;
int address = 0;
uint64_t val = 0ULL;
while (fgets(line, 100, in) != NULL) {
if (line[1] == 'a') {
andmask = 0ULL;
ormask = 0ULL;
for (i = 0; i <= 36; i++) {
char c = line[strlen(line) - 1 - i];
uint64_t i2 = 1ULL << (i - 1);
if (c == 'X') {
printf("Found unset bit 2^%d = %lu\n", i, i2);
andmask |= i2;
} else if (c == '0') {
} else if (c == '1') {
printf("Found set bit 2^%d = %lu\n", i, i2);
andmask |= i2;
ormask |= i2;
}
}
printf("Setting andmask = %lu, ormask = %lu\n", andmask, ormask);
} else if (line[1] == 'e') {
int success = sscanf(line, "mem[%d] = %lu\n", &address, &val);
if (success != 2) {
fprintf(stderr, "Error parsing %s", line);
exit(1);
}
val &= andmask;
val |= ormask;
printf("Writing %lu to %d\n", val, address);
mem[address] = val;
}
printf("%s", line);
}
uint64_t total = 0ULL;
for (i = 0; i < 100000; i++) {
if (mem[i] != 0) {
printf("%d %lu\n", i, mem[i]);
}
total += mem[i];
}
printf("TOTAL %lu\n", total);
free(mem);
free(line);
return 0;
}
|
C
|
#include <unistd.h>
#include <stdio.h>
#include "Settings.h"
#include "voiture.h"
#include "sharedmem.h"
#include "logger.h"
#include "randomLib.h"
#include "course.h"
// Essais et qualifs
void essai(SharedInfo shared, int index, int tempsTotalMax, Settings settings) {
Voiture voiture;
double vitesseMoyenne = *((double *) SettingsGet(settings, "vitesse_moyenne"));
NbrVector *longueurs = SettingsGet(settings, "longueur_sections");
double *longueurSections = longueurs->data;
int qte_sections = longueurs->length;
int delay = (int) *((double *) SettingsGet(settings, "delay"));
int sectionActuelle = 0;
char log[256];
double timeToAdd;
double lapTime = 0.0;
double tempsSection;
if (!(getVoitureCopy(index, &voiture, shared))) {
return;
}
while (voiture.TotalTime < tempsTotalMax) {
tempsSection = tempsRandom(longueurSections[sectionActuelle], vitesseMoyenne);
voiture.state.KmParcouruPneu += longueurSections[sectionActuelle];
voiture.state.totalKmParcouru += longueurSections[sectionActuelle];
if (crash_test(&voiture, settings)) {
voiture.out = 1;
sprintf(log, "[%s] Car is out", voiture.nomVoiture);
logInfo(shared, log);
break;
}
if (validerTempsSection(&voiture, sectionActuelle, tempsSection)) {
sprintf(log, "[%s] New best S%i: %.3fs", voiture.nomVoiture, sectionActuelle + 1, tempsSection);
logInfo(shared, log);
}
lapTime += tempsSection;
voiture.TotalTime += tempsSection;
sectionActuelle++;
if (sectionActuelle == qte_sections) {
sectionActuelle = 0;
if (voiture.bestLap < 0 || lapTime < voiture.bestLap) {
voiture.bestLap = lapTime;
sprintf(log, "[%s] New best lap: %.3fs", voiture.nomVoiture, lapTime);
logInfo(shared, log);
}
if ((timeToAdd = go_to_pit(&voiture, settings))) {
voiture.TotalTime += timeToAdd;
voiture.pitTime = timeToAdd;
sprintf(log, "[%s] Car entered the stand for %.0fs", voiture.nomVoiture, timeToAdd);
logInfo(shared, log);
if (!(setVoiture(index, &voiture, shared))) {
sprintf(log, "[%s] Car couldn't be set correctly", voiture.nomVoiture);
logWarning(shared, log);
break;
}
sleep(delay);
voiture.pit = 0;
if (!(setVoiture(index, &voiture, shared))) {
sprintf(log, "[%s] Car couldn't be set correctly", voiture.nomVoiture);
logWarning(shared, log);
break;
}
}
lapTime = 0;
sleep(delay);
}
if (!(setVoiture(index, &voiture, shared))) {
sprintf(log, "[%s] Car couldn't be set correctly", voiture.nomVoiture);
logWarning(shared, log);
break;
}
}
voiture.done = 1;
setVoiture(index, &voiture, shared);
}
// Course finale
void finale(SharedInfo shared, int index, int maxSections, Settings settings) {
Voiture voiture;
double vitesseMoyenne = *((double *) SettingsGet(settings, "vitesse_moyenne"));
NbrVector *longueurs = SettingsGet(settings, "longueur_sections");
double *longueurSections = longueurs->data;
int qte_sections = longueurs->length;
int sectionActuelle = 0;
double timeToAdd;
int delay = (int) *((double *) SettingsGet(settings, "delay"));
double distance = 0;
char log[256];
double lapTime = 0.0;
double tempsSection;
if (!(getVoitureCopy(index, &voiture, shared))) {
return;
}
while (voiture.qteSections < maxSections) {
tempsSection = tempsRandom(longueurSections[sectionActuelle], vitesseMoyenne);
voiture.state.KmParcouruPneu += longueurSections[sectionActuelle];
voiture.state.totalKmParcouru += longueurSections[sectionActuelle];
if (crash_test(&voiture, settings)) {
voiture.out = 1;
sprintf(log, "[%s] Car is out", voiture.nomVoiture);
logInfo(shared, log);
break;
}
if (validerTempsSection(&voiture, sectionActuelle, tempsSection)) {
sprintf(log, "[%s] New best S%i: %.3fs", voiture.nomVoiture, sectionActuelle + 1, tempsSection);
logInfo(shared, log);
}
lapTime += tempsSection;
distance += longueurSections[sectionActuelle];
voiture.TotalTime += tempsSection;
voiture.speed = distance / voiture.TotalTime;
sectionActuelle++;
voiture.qteSections++;
if (sectionActuelle == qte_sections) {
sectionActuelle = 0;
if (voiture.bestLap < 0 || lapTime < voiture.bestLap) {
voiture.bestLap = lapTime;
sprintf(log, "[%s] New best lap: %.3fs", voiture.nomVoiture, lapTime);
logInfo(shared, log);
}
if ((timeToAdd = go_to_pit(&voiture, settings))) {
voiture.TotalTime += timeToAdd;
voiture.pitTime = timeToAdd;
sprintf(log, "[%s] Car entered the stand for %.0fs", voiture.nomVoiture, timeToAdd);
logInfo(shared, log);
if (!(setVoiture(index, &voiture, shared))) {
sprintf(log, "[%s] Car couldn't be set correctly", voiture.nomVoiture);
logWarning(shared, log);
break;
}
sleep(delay);
voiture.pit = 0;
if (!(setVoiture(index, &voiture, shared))) {
sprintf(log, "[%s] Car couldn't be set correctly", voiture.nomVoiture);
logWarning(shared, log);
break;
}
}
lapTime = 0;
sleep(delay);
}
if (!(setVoiture(index, &voiture, shared))) {
sprintf(log, "[%s] Car couldn't be set correctly", voiture.nomVoiture);
logWarning(shared, log);
break;
}
}
voiture.done = 1;
setVoiture(index, &voiture, shared);
}
int validerTempsSection(Voiture *voiture, int sectionActuelle, double temps) {
if (voiture->sections[sectionActuelle] < 0 || temps < voiture->sections[sectionActuelle]) {
voiture->sections[sectionActuelle] = temps;
return 1;
//printf("%s | S%i : %lf s \n", voiture->nomVoiture ,sectionActuelle + 1, temps);
}
return 0;
}
double tempsRandom(double longueur, double vitesseMoyenne) {
double tempsMoyen = (longueur * 3600) / vitesseMoyenne;
double tempsDelta = tempsMoyen / 5;
return randomRange(tempsMoyen - tempsDelta, tempsMoyen + tempsDelta);
}
void resetVoiture(Voiture *voiture, int qte_sections) {
for (int i = 0; i < qte_sections; i++) {
voiture->sections[i] = -1;
}
voiture->speed = 0;
voiture->qteSections = 0;
voiture->bestLap = -1;
voiture->TotalTime = 0.0;
voiture->pit = 0;
voiture->state.usurePneu = 0;
voiture->state.KmParcouruPneu = 0;
voiture->out = 0;
voiture->done = 0;
}
int crash_test(Voiture *voiture, Settings settings) {
double tauxUsurepneu = *(double *) SettingsGet(settings, "taux_usure_pneu");
double usureP;
double usureM;
double probaCrash;
double crash;
usureP = (voiture->state.KmParcouruPneu * tauxUsurepneu) / 100;
voiture->state.usurePneu = usureP;
usureM = (voiture->state.totalKmParcouru * 0.0001);
probaCrash = usureP + usureM;
crash = randomRange(0, 100);
if (crash <= probaCrash) {
voiture->state.totalKmParcouru = 0;
return 1;
}
return 0;
}
double go_to_pit(Voiture *voiture, Settings settings) {
double minPit_time = *(double *) SettingsGet(settings, "min_pit_time");
double maxPit_time = *(double *) SettingsGet(settings, "max_pit_time");
if (voiture->state.usurePneu > 0.1) {
voiture->state.usurePneu = 0;
voiture->state.KmParcouruPneu = 0;
voiture->pit = 1;
voiture->pitTime = randomRange(minPit_time, maxPit_time);
return voiture->pitTime;
} else if (randomRange(0,100)<=1){
voiture->state.usurePneu = 0;
voiture->state.KmParcouruPneu = 0;
voiture->pit = 1;
voiture->pitTime = randomRange(minPit_time, maxPit_time);
return voiture->pitTime;
}
return 0;
}
|
C
|
// Noah Avizemer
// COP 3223, Fall 2018
// no886776
#include "assignment03.h"
#include <stdio.h>
//temp stores original value so that order can be switched
void sort_ascending(int *a, int *b, int *c)
{
int temp;
if(*b < *a && *b < *c)
{
temp = *b;
*b = *a;
*a = temp;
}
if (*c < *a && *c < *b)
{
temp = *c;
*c = *a;
*a = temp;
}
if (*c < *b)
{
temp = *c;
*c = *b;
*b = temp;
}
}
// temp stores original value allowing the pointers to be dereferenced and put in order
//= is added to logic to allow for repeats
void sort_ascending_with_repeats_allowed(int *a, int *b, int *c)
{
int temp;
if(*b <= *a && *b <= *c)
{
temp = *b;
*b = *a;
*a = temp;
}
if (*c <= *a && *c <= *b)
{
temp = *c;
*c = *a;
*a = temp;
}
if (*c <= *b)
{
temp = *c;
*c = *b;
*b = temp;
}
}
void sort_descending(int *a, int *b, int *c)
{
int temp;
if(*b >= *a && *b >= *c)
{
temp = *b;
*b = *a;
*a = temp;
}
if (*c >= *b && *c >= *a)
{
temp = *c;
*c = *a;
*a = temp;
}
if (*b <= *c)
{
temp = *c;
*c = *b;
*b = temp;
}
}
// sort_descending has = which allowed for repeats
void sort_descending_with_repeats_allowed(int *a, int *b, int *c)
{
sort_descending(a, b, c);
}
//dereferences the pointer and checks if value is between the other values
int *get_pointer_to_median(int *a, int *b, int *c)
{
if (*a <= *b && *a >= *c)
{
return a;
}
if (*a <= *c && *a >= *b)
{
return a;
}
if (*b <= *c && *b >= *a)
{
return b;
}
if (*b <= *a && *b >= *c)
{
return b;
}
if (*c <= *b && *c >= *a)
{
return c;
}
if (*c <= *a && *c >= *b)
{
return c;
}
}
//dereferences the pointer and adds 1 to the head
void grow_glowie(int *head)
{
*head = *head + 1;
}
// dereferences the pointer and subtracts 1 from the head
void shrink_glowie(int *head)
{
*head = *head - 1;
}
//dereferences the pointer and adds 1 to head and tail
void move_glowie_forward(int *tail, int *head)
{
*tail = *tail + 1;
*head = *head + 1;
}
//checks for the type of snack to execute the correct logic
int feed_glowworm(int *tail, int *head, int *is_alive, char *snack)
{
if (*snack == 'o' || *snack == 'O' || *snack == '@')
{
grow_glowie(head);
printf("Glowworm munches on a snack that causes it to grow! Om nom nom.\n");
*snack = ' ';
return 1;
}
else if (*snack == 's' || *snack == 'S')
{
shrink_glowie(head);
printf("Glowworm munches on a snack that causes it to shrink!\n");
*snack = ' ';
return 1;
}
else if(*snack == '-' || *snack == '=')
{
move_glowie_forward(tail, head);
printf("Glowworm feels energetic after its snack and inches forward!\n");
*snack = ' ';
return 1;
}
else if (*snack == 'x' || *snack == 'X' || *snack == '%')
{
*is_alive = 0;
printf("That snack poisoned the glowworm. SAD.\n");
*snack = ' ';
return 0;
}
else
{
printf("The glowworm looks at the snack skeptically.\n");
return 0;
}
}
//The code for when tail < head is from Dr.Szumlanski's print_glowie function
//When the tail > head, the body is printed first up to head - 1 so that it does not overlap with head
//The head is printed second after checking if glowie is alive
//The tail is printed last since it comes after the head
void print_magical_translocational_glowworm(int tail, int head, int platform_length, int is_alive)
{
int i;
int segments = head - tail - 2;
int spaces = tail;
if (tail > head)
{
for (i = 0; i < head - 1; i++)
{
printf("o");
}
if (is_alive == 1)
{
printf("OG");
}
else
{
printf("Xx");
}
for (i = head; i < tail - 1; i++)
{
printf(" ");
}
printf("~");
for (int i = tail; i < platform_length - 1; i++)
{
printf("o");
}
printf("\n");
}
else
{
for (i = 0; i < spaces; i++)
{
printf(" ");
}
printf("~");
for (i = 0; i < segments; i++)
{
printf("o");
}
if (is_alive == 1)
{
printf("OG\n");
}
else
{
printf("Xx\n");
}
}
for (i = 0; i < platform_length; i++)
{
printf("=");
}
printf("\n\n");
}
double difficulty_rating(void)
{
return 4;
}
double hours_invested(void)
{
return 5;
}
double prior_experience(void)
{
return 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "set.h"
#define SETSIZE 1
#define ZEROSIZE 0
set* set_init(void)
{
set *s;
s=(set *)calloc(SETSIZE, sizeof(set));
if(s==NULL){
ON_ERROR("Creation of Set Failed\n");
}
s->ua=arr_init();
s->sz=ZEROSIZE;
return s;
}
set* set_copy(set* s)
{
int i;
set *sa=set_init();
for(i=0; i<set_size(s); i++){
set_insert(sa, arr_get(s->ua, i));
}
return sa;
}
set* set_fromarray(arrtype* a, int n)
{
int i;
set *sa=set_init();
if(a==NULL){
return sa;
}
for(i=0; i<n; i++) {
set_insert(sa, a[i]);
}
return sa;
}
void set_insert(set* s, arrtype l)
{
if(s!=NULL){
if(!set_contains(s, l)){
arr_set(s->ua, set_size(s), l);
s->sz++;
}
}
}
int set_size(set* s)
{
if(s==NULL){
return 0;
}
return s->sz;
}
int set_contains(set* s, arrtype l)
{
int i;
arrtype unique_value;
for(i=0; i<set_size(s); i++){
unique_value=arr_get(s->ua, i);
if(memcmp(&unique_value, &l, sizeof(arrtype))==0){
return 1;
}
}
return 0;
}
void set_remove(set* s, arrtype l)
{
int i, k;
arrtype unique_value;
for(i=0; i<set_size(s); i++){
unique_value=arr_get(s->ua, i);
if(memcmp(&unique_value, &l, sizeof(arrtype))==0){
for(k=i; k<(set_size(s)-1); k++){
arr_set(s->ua, k, arr_get(s->ua, k+1));
}
s->sz--;
return;
}
}
}
arrtype set_removeone(set* s)
{
arrtype last_element = arr_get(s->ua, (set_size(s)-1));
s->sz--;
return last_element;
}
set* set_union(set* s1, set* s2)
{
int i;
set *sa=set_init();
if(s1==NULL && s2==NULL){
return sa;
}
if(s1==NULL){
sa=set_copy(s2);
return sa;
}
if(s2==NULL){
sa=set_copy(s1);
return sa;
}
sa=set_copy(s1);
for(i=0; i<set_size(s2); i++) {
set_insert(sa, arr_get(s2->ua, i));
}
return sa;
}
set* set_intersection(set* s1, set* s2)
{
set *sa= set_init();
int i;
if(s1==NULL || s2==NULL){
return sa;
}
for(i=0; i<set_size(s2); i++) {
if(set_contains(s1, arr_get(s2->ua, i))){
set_insert(sa, arr_get(s2->ua, i));
}
}
return sa;
}
void set_free(set **s)
{
if(s!=NULL){
set* a = *s;
arr_free(&a->ua);
free(a);
*s = NULL;
}
}
|
C
|
/*
License: zlib license
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/// \file
///
/// balancedgen_t generates uint32_t numbers. Each successive call
/// to next balancedgen_next will return numbers in a tree fashion
/// starting at MAX_BALANCEDID/2.
///
/// For instance, if MAX_BALANCEDID was equals to 8, the calls to
/// next_id would return in the sequence:
///
/// 4
/// / \
/// 2 6
/// / \ / \
/// 1 3 5 7
///
/// The sequence: 4, 2, 6, 1, 3, 5, 7.
/// It is also important to notice that neither 0 or MAX_BALANCEDID
/// are generated ids.
///
#ifndef IDGEN_BALANCEDID_H_
#define IDGEN_BALANCEDID_H_
#include<stdint.h>
#include<stdbool.h>
#include<stdlib.h>
///
/// The id = 0 will never be generated.
///
#define BALANCEDID_NULL_ID 0
///
/// The highest id that will be generated by the
/// 32 bits id generator: 2^31.
///
#define MAX_BALANCEDID (((uint32_t) 1) << 31)
//
// Returns true if the id is balancedgen_t valid/generated id.
//
#define balancedid_isvalid(id) ((id) != BALANCEDID_NULL_ID)
///
/// Frees a balancedgen_t* created using balancedgen_new() or
/// using C's malloc.
///
#define balancedgen_delete(ptr) free(ptr)
typedef struct {
/// the current tree depth
uint32_t _tree_level;
/// The index of the id that will be generated next. For
/// instace, at the second level (tree_depth = 1) two ids
/// (2^1) will be generated, thus 'index' tells whether
/// it's the first or the second id
uint32_t _index;
/// the base value that will be multiplied in order to
/// generate the new id
uint32_t _seed;
/// If done = 1, the generator has been exausted and should
/// be freed.
bool _done;
} balancedgen_t;
///
/// Returns an initialized balancedgen_t.
/// \return an initialized balancedgen_t.
///
balancedgen_t balancedgen_make();
///
/// Creates a new balancedgen_t and initialized.
/// \return a new balancedgen_t.
///
balancedgen_t* balancedgen_new();
///
/// Generates a new id. If the generator has been exhausted,
/// it'will return BALANCEDID_NULL_ID.
///
/// \param g a pointer to balancedid_s.
/// \return a uint32_t valid id or BALANCEDID_NULL_ID if the
/// generator has been exhausted.
///
uint32_t balancedgen_next(balancedgen_t *restrict g);
///
/// Make the balancedgen_t brand new again!
/// \param g a pointer to balancedgen_t.
///
void balancedgen_reset(balancedgen_t *restrict g);
#endif // IDGEN_BALANCEDID_H_
|
C
|
#include "bpnn_fit.h"
#include "bpnn_config.h"
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#define T bpnn_t
#define D IN_N
#define Q HIDDEN_N
#define L OUT_N
#include "CFICheck.h"
#include "enclave.h"
struct T
{
double *v[D];
double *w[Q];
double *r;
double *o;
double *b;
};
static bool get_parameter(T bpnn);
T bpnn_fit_new(void)
{
T bpnn;
bpnn = malloc(sizeof(*bpnn));
if (bpnn == NULL)
goto cleanup;
for (size_t i = 0; i < D; i++)
{
bpnn->v[i] = malloc(sizeof(double) * Q);
if (bpnn->v[i] == NULL)
goto cleanup;
}
for (size_t h = 0; h < Q; h++)
{
bpnn->w[h] = malloc(sizeof(double) * L);
if (bpnn->w[h] == NULL)
goto cleanup;
}
bpnn->r = malloc(sizeof(double) * Q);
if (bpnn->r == NULL)
goto cleanup;
bpnn->o = malloc(sizeof(double) * L);
if (bpnn->o == NULL)
goto cleanup;
bpnn->b = malloc(sizeof(double) * Q);
if (bpnn->b == NULL)
goto cleanup;
if (!get_parameter(bpnn))
{
puts("[BPNN] GET PARAMETER FAILED!\n");
goto cleanup;
}
return bpnn;
cleanup:
if (bpnn)
{
for (size_t i = 0; i < D; i++)
{
if (bpnn->v[i] != NULL)
free(bpnn->v[i]);
}
for (size_t h = 0; h < Q; h++)
{
if (bpnn->w[h] != NULL)
free(bpnn->w[h]);
}
if (bpnn->r != NULL)
free(bpnn->r);
if (bpnn->o != NULL)
free(bpnn->o);
if (bpnn->b != NULL)
free(bpnn->b);
free(bpnn);
}
return NULL;
}
void bpnn_fit(T bpnn, double *in, double *out)
{
assert(bpnn && in && out);
/* Compute b[h] */
for (size_t h = 0; h < Q; h++)
{
double alpha_h = 0;
for (size_t i = 0; i < D; i++)
alpha_h += bpnn->v[i][h] * in[i];
bpnn->b[h] = ACTIVATION_FUNC(alpha_h - bpnn->r[h]);
}
/* Compute out[j] */
for (size_t j = 0; j < L; j++)
{
double beta_j = 0;
for (size_t h = 0; h < Q; h++)
beta_j += bpnn->w[h][j] * bpnn->b[h];
out[j] = ACTIVATION_FUNC(beta_j - bpnn->o[j]);
}
}
void bpnn_fit_free(T *bpnn)
{
assert(bpnn && *bpnn);
for (size_t i = 0; i < D; i++)
free((*bpnn)->v[i]);
for (size_t h = 0; h < Q; h++)
free((*bpnn)->w[h]);
free((*bpnn)->r);
free((*bpnn)->o);
free((*bpnn)->b);
*bpnn = NULL;
}
//Weijie:
// n should be larger than 1
// buf size should be less than n
int readline(int fd, char *buf, size_t n)
{
for(int i = 0; i < n - 1; i++){
char a;
if (read(fd, &a, 1) != NULL) {
if (a != '\n') {
buf[i] = a;
} else {
buf[i] = '\n';
buf[i+1] = '\0';
return (i+1);
}
}
else {
buf[i+1] = '\0';
return (i+1);
}
}
buf[n] = '\0';
return n;
}
static bool get_parameter(T bpnn)
{
#define BUFFER_SIZE 128
/*
FILE *in = NULL;
in = fopen(SAVE_PARAM_PATH, "r");
if (in == NULL) {
//fprintf(stderr, "[BPNN] OPEN FILE %s FAILED.\n", SAVE_PARAM_PATH);
return false;
}
*/
int in_fd;
in_fd = open(SAVE_PARAM_PATH, O_RDONLY, S_IRUSR);
if (in_fd == -1)
{
puts("File cannot be opened!\n");
return false;
}
char buffer[BUFFER_SIZE];
if (read(in_fd, buffer, BUFFER_SIZE) != NULL)
{
puts("test\n");
puts(buffer);
}
puts("dbg0.5\n");
//for (size_t i = 0; (i < 5) && (fgets(buffer, BUFFER_SIZE, in) != NULL); i++) {
//for (size_t i = 0; (i < 5) && (read(in_fd, buffer, BUFFER_SIZE) != NULL); i++)
for (size_t i = 0; (i < 5) && (readline(in_fd, buffer, BUFFER_SIZE) > 0); i++)
{
puts("Buffer:\n");
puts(buffer);
if (buffer[0] == '#')
continue;
else if (buffer[0] == 'D' && buffer[1] == '=')
{
if (strtol(buffer + 2, NULL, 0) != D)
{
goto cleanup;
}
}
else if (buffer[0] == 'Q' && buffer[1] == '=')
{
if (strtol(buffer + 2, NULL, 0) != Q)
{
goto cleanup;
}
}
else if (buffer[0] == 'L' && buffer[1] == '=')
{
if (strtol(buffer + 2, NULL, 0) != L)
{
goto cleanup;
}
}
}
//puts("dbg1\n");
for (size_t i = 0; i < D; i++)
for (size_t h = 0; h < Q; h++)
{
//if (fgets(buffer, BUFFER_SIZE, in) != NULL) {
//if (read(in_fd, buffer, BUFFER_SIZE) != NULL)
if (readline(in_fd, buffer, BUFFER_SIZE) > 0)
{
bpnn->v[i][h] = strtod(buffer, NULL);
}
else
{
goto cleanup;
}
}
//puts("dbg2\n");
for (size_t h = 0; h < Q; h++)
for (size_t j = 0; j < L; j++)
{
//if (fgets(buffer, BUFFER_SIZE, in) != NULL) {
//if (read(in_fd, buffer, BUFFER_SIZE) != NULL)
if (readline(in_fd, buffer, BUFFER_SIZE) > 0)
{
bpnn->w[h][j] = strtod(buffer, NULL);
}
else
{
goto cleanup;
}
}
for (size_t h = 0; h < Q; h++)
{
//if (fgets(buffer, BUFFER_SIZE, in) != NULL) {
//if (read(in_fd, buffer, BUFFER_SIZE) != NULL)
if (readline(in_fd, buffer, BUFFER_SIZE) > 0)
{
bpnn->r[h] = strtod(buffer, NULL);
}
else
{
goto cleanup;
}
}
for (size_t j = 0; j < L; j++)
{
//if (fgets(buffer, BUFFER_SIZE, in) != NULL) {
//if (read(in_fd, buffer, BUFFER_SIZE) != NULL)
if (readline(in_fd, buffer, BUFFER_SIZE) > 0)
{
bpnn->o[j] = strtod(buffer, NULL);
}
else
{
goto cleanup;
}
}
//puts("dbg2.5\n");
//fclose(in);
close(in_fd);
return true;
cleanup:
//fprintf(stderr, "[BPNN] BPNN PARAM FILE NOT FIT!\n");
puts("clean up: BPNN PARAM FILE NOT FIT!\n");
//fclose(in);
close(in_fd);
return false;
}
#undef T
static bool test_set_get(double *in, double *out);
//static FILE *in_file = NULL;
//static FILE *out_file = NULL;
static int in_file_fd = 0;
static int out_file_fd = 0;
void enclave_main(void)
{
unsigned long long magic = 0;
puts("enclave begins...\n");
bpnn_t bpnn = bpnn_fit_new();
if (bpnn == NULL)
{
//fprintf(stderr, "bpnn new failed!\n");
puts("bpnn new failed!\n");
//return;
}
/*
in_file = fopen(IN_PATH, "r");
if (in_file == NULL) {
//fprintf(stderr, "open file %s failed.\n", IN_PATH);
puts("open file failed!\n");
return;
}
*/
in_file_fd = open(TEST_IN_PATH, O_RDONLY, S_IRUSR);
//puts("dbg3\n");
if (in_file_fd == -1)
{
puts("open file failed!\n");
//return;
}
/*
out_file = fopen(OUT_PATH, "r");
if (out_file == NULL) {
//fprintf(stderr, "open file %s failed.\n", OUT_PATH);
puts("open file failed!\n");
return;
}
*/
out_file_fd = open(TEST_OUT_PATH, O_RDWR, S_IRUSR);
if (out_file_fd == -1)
{
puts("open file failed!\n");
//return;
}
puts("start to run...\n");
double in[IN_N], out[OUT_N], outy[OUT_N];
while (test_set_get(in, out))
{
bpnn_fit(bpnn, in, outy);
for (size_t i = 0; i < IN_N; i++)
//printf("%lf ", in[i]);
puts("processing IN...\n");
for (size_t j = 0; j < OUT_N; j++)
//printf("%lf[%lf] ", out[j], outy[j]);
puts("processing OUT...\n");
//printf("\n");
}
bpnn_fit_free(&bpnn);
//fclose(in_file);
//fclose(out_file);
close(in_file_fd);
close(out_file_fd);
puts("success!\n");
//return;
enclave_exit();
}
static bool test_set_get(double *in, double *out)
{
assert(in && out);
#define BUFFER_SIZE 128
static char buffer[BUFFER_SIZE];
//if (in_file && out_file) {
if (in_file_fd && out_file_fd)
{
//if (fgets(buffer, BUFFER_SIZE, in_file) != NULL) {
//if (read(in_file_fd, buffer, BUFFER_SIZE) != NULL)
if (readline(in_file_fd, buffer, BUFFER_SIZE) > 0)
{
char *token = strtok(buffer, ",");
for (size_t i = 0; i < IN_N; i++)
{
if (token == NULL)
{
//fprintf(stderr, "the format of input is not correct!\n");
return false;
}
in[i] = strtod(token, NULL);
token = strtok(NULL, ",");
}
}
else
{
return false;
}
//if (fgets(buffer, BUFFER_SIZE, out_file) != NULL) {
//if (read(out_file_fd, buffer, BUFFER_SIZE) != NULL)
if (readline(out_file_fd, buffer, BUFFER_SIZE) > 0)
{
out[0] = strtod(buffer, NULL);
}
else
{
return false;
}
return true;
}
return false;
}
|
C
|
/* Mapped-memory Writer program
* Version: February 7, 2017
*/
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include "mmap.h"
/* return a uniformly generated random number in the range [low,high]
*/
int random_range (unsigned const low, unsigned const high) {
unsigned const range = high - low + 1;
return low + (int) (((double) range) * rand () / (RAND_MAX + 1.0));
}
/* Create and write to a shared file for communication with another process.
*
* argv[1] = file name
*
* Note: Error processing is omitted
*/
int main (int argc, char* const argv[]) {
int fd;
int nNumbers;
void* file_memory;
/* seed the random number generator */
srand (time (NULL));
/* open or create a file to hold an unsigned integer */
fd = open (argv[1], O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
/* write FILESIZE spaces */
for (int i=0; i<FILESIZE; i++) write (fd, " ", 1);
write (fd, "", 1); /* write a NULL at EOF */
/* create the memory-mapping
1st param=start addr of mapping into memory, NULL means chosen by OS
2nd param=length of map (bytes)
3rd param=protection
4th param=options, MAP_SHARED used for interprocess communications
5th param=file descriptor of mapped file
6th param=offset from start of file where mapping starts
*/
file_memory = mmap (NULL, FILESIZE, PROT_WRITE, MAP_SHARED, fd, 0);
close (fd);
nNumbers = atoi(argv[2]);
/* write nNumbers random integer to memory-mapped area */
for(int i = 0 ; i < nNumbers ; i++){
int jumps = 2;
int randomlyGenerated = random_range (-100, 100);
//printf("This time the generated value is %d.\n",randomlyGenerated);
sprintf((char*) file_memory, "%d ",randomlyGenerated);
if (abs(randomlyGenerated) / 100 >= 1)
jumps++;
if (abs(randomlyGenerated) / 10 >= 1)
jumps++;
if (randomlyGenerated <= 0)
jumps++;
for (int j = 0 ; j< jumps ; j++){
//(char*)
file_memory++;
}
}
/* release the memory */
munmap (file_memory, FILESIZE);
}
|
C
|
/*
* =====================================================================================
*
* Filename: test_Q_stricmp.c
*
* Description:
* =====================================================================================
*/
#include <stdio.h>
int Q_stricmpn(const char *s1, const char *s2, int n)
{
int c1, c2;
if( s1 == NULL )
{
if( s2 == NULL )
return 0;
else
return -1;
}
else if ( s2 == NULL )
{
return 1;
}
do
{
c1 = *s1++;
c2 = *s2++;
if (!n--)
return 0; // strings are equal until end point
if(c1 >= 'a' && c1 <= 'z')
c1 -= ('a' - 'A');
if(c2 >= 'a' && c2 <= 'z')
c2 -= ('a' - 'A');
if(c1 != c2)
return c1 < c2 ? -1 : 1;
} while (c1);
return 0; // strings are equal
}
int Q_stricmp(const char *s1, const char *s2)
{
return (s1 && s2) ? Q_stricmpn (s1, s2, 99999) : -1;
/*
#ifdef _MSC_VER
return stricmp(s1, s2);
#else
return strcasecmp(s1, s2);
#endif
*/
}
// retunrn s1 == s2 ? 1 : 0
int isCaseStringEqual(const char * s1, const char * s2)
{
if( s1 == NULL || s2 == NULL)
{
// should not compare null, this is not meaningful ...
return 0;
}
else
{
while( (*s1 != 0) || (*s2 != 0) )
{
if(*s1++ == *s2++)
{
continue;
}
else
{
// string are not equal
return 0;
}
}
}
return 1;
}
int main()
{
char * pToken1 = "autosprite";
char * pToken2 = "autosprite2";
/*
if ( !Q_stricmp( pToken1, "autosprite" ) ) {
printf( "%s === DEFORM_AUTOSPRITE \n", pToken1);
}
if ( !Q_stricmp( pToken1, "autosprite2" ) ) {
printf( "%s === DEFORM_AUTOSPRITE2 \n", pToken1);
}
if ( !Q_stricmp( pToken2, "autosprite" ) ) {
printf( "%s === DEFORM_AUTOSPRITE \n", pToken2);
}
if ( !Q_stricmp( pToken2, "autosprite2" ) ) {
printf( "%s === DEFORM_AUTOSPRITE2 \n", pToken2);
}
*/
if ( isCaseStringEqual( pToken1, "autosprite" ) ) {
printf( "%s === DEFORM_AUTOSPRITE \n", pToken1);
}
if ( isCaseStringEqual( pToken1, "autosprite2" ) ) {
printf( "%s === DEFORM_AUTOSPRITE2 \n", pToken1);
}
if ( isCaseStringEqual( pToken2, "autosprite" ) ) {
printf( "%s === DEFORM_AUTOSPRITE \n", pToken2);
}
if ( isCaseStringEqual( pToken2, "autosprite2" ) ) {
printf( "%s === DEFORM_AUTOSPRITE2 \n", pToken2);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define SIZE 256
int main(int argc,char *argv[])
{
FILE *fs;
FILE *fa;
char temp[SIZE];
size_t bytes;
if(argc<3)
{
fprintf(stderr,"Usage: %s filename\n",argv[0]);
exit(EXIT_FAILURE);
}
if((fs=fopen(argv[1],"rb"))==NULL)
{
fprintf(stderr,"I could not open the file \"%s\"\n",argv[1]);
exit(EXIT_FAILURE);
}
if((fa=fopen(argv[2],"wb"))==NULL)
{
fprintf(stderr,"I could not open the file \"%s\"\n",argv[2]);
exit(EXIT_FAILURE);
}
while((bytes=fread(temp,sizeof(char),SIZE,fs))>0)
fwrite(temp,sizeof(char),bytes,fa);
fclose(fs);
fclose(fa);
return 0;
}
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <signal.h>
#define SIGOK 10
pid_t pid_child;
void forever(){
while(1);
}
void createProcess (void (*F) (void)){
pid_t pid_child = fork();
if(pid_child){
return;
}else{
F();
}
}
int sendSignal(int sig){
if(pid_child)
kill(pid_child, SIGINT);
else kill(getpid(), SIGOK);
}
int sigok_handler(int sig){
kill(getppid(), SIGOK);
printf("exit %d\n", getpid());
exit(0);
}
int main(){
signal(SIGINT, sendSignal);
signal(SIGOK, sigok_handler);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
char str[100001],a[100001];
int t,min,deletions,flag,k,counter,initial,len;
char i,j;
scanf("%d",&t);
while(t--)
{
scanf(" %s",str);
flag=0;
for(k=1;str[k];k++)
if(str[k]!=str[k-1])
flag=1;
len=k;
a[0]=str[0];
counter=1;
deletions=0;
for(k=1;str[k];k++)
{
while(str[k]==str[k-1])
{
deletions++;
k++;
}
a[counter++]=str[k];
}
initial=deletions;
printf("%d\n",initial);
}
return 0;
}
|
C
|
/* CpSc 210
source: https://people.cs.clemson.edu/~rlowe/cs1070/examples/IO/Printf/printf1.c
printf() example for formated output.
This example demonstrates numerous options for formatting data
that is displayed from a program.
*/
#include <stdio.h>
#include <stdlib.h>
int main() {
int a=5;
int b=-1;
float x=5.12345;
double y=5.12345;
char c='x';
char str[]="This is a string";
/* Integer print */
printf("The sum of %d and %d is %d\n", a, b, a+b);
/* Fixed field sizes for integer print */
printf("The sum of %10d and %10d is %10d\n", a, b, a+b);
/* Floating point output */
printf("x=%f\n", x);
/* Fixed field sizes for floating point print */
printf("x=%5.2f, x=%10.6f\n", x, x);
/* Double precision output */
printf("y=%lf, %5.2lf, %10.6lf\n", y, y, y);
/* Character output */
printf("c='%c'\n", c);
printf("Characters 1 and 4 are: '%c', '%c'\n", str[0], str[3]);
/* String output */
printf("Str=\"%s\"\n", str);
printf("At least 6 characters of str=\"%6s\"\n", str);
printf("6 characters of str=\"%6.6s\"\n", str);
printf(" =\"%6.6s\"\n", "short");
printf("Right aligned in field, str=\"%30s\"\n",str);
printf("Left aligned in field, str=\"%-30s\"\n", str);
return 0;
}
|
C
|
/**
* 复制输入到输出
* gcc -o exe\copy2.exe copy2.c
*/
#include <windows.h>
#define BUFSIZE 256
int main(){
char buf[BUFSIZE];
int n;
while((n = read(0, buf, BUFSIZE)) > 0)
write(1, buf, n);
return 0;
}
|
C
|
#ifndef HEADER
#define HEADER
#include "header.h"
#endif
int main() {
socket_t server_socket;
int port = 9002;
soc_set_ip(&server_socket, "0.0.0.0");
soc_set_port(&server_socket, port);
// Create the server socket
server_socket.id = socket(AF_INET, SOCK_STREAM, 0);
// Define the server address
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(server_socket.port);
server_address.sin_addr.s_addr = INADDR_ANY;
// Bind the socket to our specified IP and port
bind(server_socket.id, (struct sockaddr *) &server_address, sizeof(server_address));
while(1) {
int number_of_allowed_connections = 5;
listen(server_socket.id, number_of_allowed_connections);
socket_t client_socket;
client_socket.id = accept(server_socket.id, NULL, NULL);
receive_file(&client_socket);
// printf("allow\n");
}
// Close the socket
soc_close(&server_socket);
return 0;
}
|
C
|
#include "cs.h"
/* create a Householder reflection [v,beta,s]=house(x), overwrite x with v,
* where (I-beta*v*v')*x = s*e1 and e1 = [1 0 ... 0]'.
* Note that this CXSparse version is different than CSparse. See Higham,
* Accuracy & Stability of Num Algorithms, 2nd ed, 2002, page 357. */
CS_ENTRY cs_house (CS_ENTRY *x, double *beta, CS_INT n)
{
const CS_ENTRY one = ONE;
CS_ENTRY u, v, s = ZERO ;
CS_INT i ;
double t;
if (!x || !beta) return (MINUS_ONE) ; /* check inputs */
/* s = norm(x) */
for (i = 0 ; i < n ; i++) MULT_ADD_CONJ(s, x [i], x [i]) ;
s = CS_SQRT (s) ;
if (IS_ZERO(s))
{
(*beta) = 0 ;
x [0] = one ;
}
else
{
/* s = sign(x[0]) * norm (x) ; */
if (IS_NONZERO(x [0]))
{
//s *= x [0] / CS_ABS (x [0]) ;
u = x[0];
SCALE_DIV(u, CS_ABS(x[0]));
v = s;
MULT(s, v, u);
}
//x [0] += s ;
//(*beta) = 1. / CS_REAL (CS_CONJ (s) * x [0]) ;
ASSEMBLE(x[0], s);
MULT(u, CS_CONJ(s), x[0]);
(*beta) = 1.0 / CS_REAL (u) ;
}
SCALE(s, -1.0);
return s ;
}
|
C
|
#include "logger.h"
#include <stdarg.h>
#define RED "\x1B[31;1m"
#define GRN "\x1B[32;1m"
#define YEL "\x1B[33;1m"
#define BLU "\x1B[34m"
#define MAG "\x1B[35;1m"
#define CYN "\x1B[36m"
#define WHT "\x1B[37;1m"
#define RESET "\x1B[0m"
static Logger logger = {.log_fd = {[LOG_RAW] = STDOUT_FILENO,
[LOG_ERROR] = STDERR_FILENO,
[LOG_WARNING] = STDERR_FILENO,
[LOG_INFO] = STDOUT_FILENO},
.level_mask = LOG_WARNING_LEVEL};
void LOG_Set_Level(int level_mask){
logger.level_mask = level_mask;
}
void LOG_Set_Output(Log_Type type, int fd){
logger.log_fd[type] = fd;
}
void LOG_Write(Log_Type type, const char *file, const char *function, int line, const char *fmt, ...){
static char str_type[4][32] = {[LOG_RAW] = MAG "[RAW]",
[LOG_ERROR] = RED "[ERROR]",
[LOG_WARNING] = YEL "[WARNING]",
[LOG_INFO] = GRN "[INFO]"};
if(!(logger.level_mask & LOG_MASK(type)))
return;
va_list args;
va_start(args, fmt);
int fd = logger.log_fd[type];
dprintf(fd, "%s %s:%s:%d\n\t" RESET WHT, str_type[type], file, function, line);
vdprintf(fd, fmt, args);
dprintf(fd, "\n" RESET);
va_end(args);
}
void LOG_Raw(const char *fmt, ...){
va_list args;
va_start(args, fmt);
vdprintf(logger.log_fd[LOG_RAW], fmt, args);
va_end(args);
}
|
C
|
#include <stdio.h>
int count=0;
void step(int n,char a,char b,char c)
{
if(n==1)
{
count++;
printf("%c->%c\n",a,c);
}
else
{
step(n-1,a,c,b); //moving the top n-1 discs to B rod
step(1,a,b,c); //moving the bottom last disc to C rod
step(n-1,b,a,c); //moving the discs in B rod to C rod
}
}
int main()
{
int n;
printf("enter the number of steps: ");
scanf("%d",&n);
step(n,'A','B','C');
printf("Number of steps used are:- %d",count);
return 0;
}
|
C
|
#include <stdio.h>
// Assignment - 1, Section - 2.
/** Please read the instructions in the comment and
write the code accordingly.
This assignment will test your understanding with console input and output.
Just in case if you do not know the meaning of the term 'console', we typically
indicate it to mean keyboard and terminal. Input console indicates to keyboard and
output console indicates terminal.
This will also test your ability to use variables.
*/
int main(){
// Please follow the instructions and write the code chronologically.
// 1. Declare a double type variable named rate and assign 0.06 to it
// 2. Declare an integer variable, name it duration.
// 3. Declare a double variable and name it principal_amount
// 4. Declare a double variable and name it total_interest
// 5. Prompt user to input duration in year. Read the year value in duration using
// scanf. Since duration is integer you must use %d.
// 6. Prompt user to input principal amount of loan. Read the value in the
// variable principal_amount. Think about the format specifier this time.
// principal_amount is not an integer, it is a double, so use the format specifier
// of double.
// 7. Now you will calculate the total interest, if R is rate, D is duration and P
// is principal then the total interest should be calculated as follows:
// I = (P * D * R)
// Use the above formula to calculate the total interest and finally print the
// amount into the console. Your output should be like the following:
// Output:
// Your total payable interest is $3000.000000 when principal_amount given as 1000.0, duration is 5
//
// required variable declarations
double rate = 0.06;
int duration;
double principal_amount;
double total_interest;
// prompting user to input duration.
printf("Enter duration (in years): ");
// scanning duration
scanf("%d", &duration);
// ***uncomment the following line when you check answers of Q2 & Q3 ***
// printf("duration = %d\n", duration);
// Now we should input principal
printf("Enter principal amount ($): ");
scanf("%lf", &principal_amount);
// ***uncomment the following line when you check answers of Q2 & Q3 ***
// printf("principal = %lf\n", principal_amount);
// Notice %lf is the format specifier for double
// calculating total_interest, this is simple interest actually
total_interest = (principal_amount * duration * rate);
// Now we need to print the output.
printf("Your total payable interest is $%f\n", total_interest);
return 0;
}
/**
Explanation of Q2:
When you input 2.5 for an integer field, scanf takes only the integer portion
of the real number, that is 2 and assigns that to the integer variable duration,
the part after decimal point is rejected by scanf, but you have input it,
isn't it? so that goes into the memory and remains there.
Now in the next scanf when you are suppose to input a double value
for principal_amount, then the scanf takes that 0.5 that was there from
the previous input and assigns that to principal_amount and never waits for
user to input the value.
Finally the interest is calculated using duration = 2, principal_amount = 0.5
and rate = 0.06 and we get interest as 0.00600.
*/
|
C
|
/**
* @file
*
* API for basic view LittlevGL implementation
*/
#ifndef SRC_UI_VIEWS_LVGL_VIEW_H_
#define SRC_UI_VIEWS_LVGL_VIEW_H_
#include "ui/views/basic_view.h"
#include "lvgl.h"
/**
* Initialize basic view structure
* @return 0(ERR_OK) on success, zero otherwise
*/
uint32_t lvgl_basic_view_create(ui_view_t* view_to_init);
/**
* Get LittlevGL root object (screen) for given basic view.
* Code of other view that customizes this basic view shall attach
* it's components to the screen of basic view
*/
lv_obj_t* lvgl_basic_view_get_screen(ui_view_t* basic_view);
/**
* Function that shall set current view as active (displayed on the basic screen)
*/
void lvgl_basic_view_activate(ui_view_t* view);
/**
* Free all resources associated with the view
*/
void lvgl_basic_view_destroy(ui_view_t* view);
#endif /* SRC_UI_VIEWS_LVGL_VIEW_H_ */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
char * generateRandXOR(char* hash, int r);
void R(char* in, char* out, int r);
void pass_hash(char *in, char *out);
void E(char *in, char *out);
void chopN(char *str, size_t n);
const int MAX_PASSWORD_LENGTH = 12;
int main()
{
char user_ID [32];
char user_pass [12];
char user_pass_hash [12];
char *temp_ID;
char *temp_pass;
char line[256];
int existing_user = 0;
int random_number;
const int MAX_PASSWORD_LENGTH = 12;
char* user_xor;
char* temp_xor;
//open files
FILE *file;
file = fopen("OLMHash.txt", "r");
//error opening file
if (file == NULL)
{
printf("Error opening file!\n");
exit(1);
}
//initial prompt
printf("Enter your user ID:\n");
scanf ("%s", user_ID);
printf("Enter your password:\n");
scanf ("%s", user_pass);
//generate a random 32 bit number that comes from server
srand(time(NULL)); // randomize seed
random_number = rand();
printf("%i\n", random_number);
//hash password
pass_hash(user_pass, user_pass_hash);
printf ("%s\n", user_pass_hash);
//put through XOR function with rand number
user_xor = generateRandXOR(user_pass, random_number);
//printf("%s\n", user_xor);
//send password to server
//server side
//get line from file
while (fgets(line, sizeof(line), file))
{
//get ID and passwod from line
temp_ID = strtok (line," ");
temp_pass = strtok (NULL,"\n");
//printf ("%s\n%s\n", temp_ID, temp_pass);
//user exists - ask for password and replace current
if (strcmp(user_ID, temp_ID) == 0)
{
existing_user = 1;
//put hash through XOR function with 32 bit rand number
temp_xor = generateRandXOR(temp_pass, random_number);
printf("%s\n", user_xor);
printf("%s\n", temp_xor);
//printf ("%s\n", user_pass_hash);
//printf ("%s\n", temp_pass);
//if pass correct - Access Granted
if (strcmp(user_xor, temp_xor) == 0)
{
//get new password
printf("Access Granted\n");
}
//if pass incorrect - Access Denied
if (strcmp(user_xor, temp_xor) != 0)
{
printf("Access Denied\n");
}
}
}
//not existing user - print user not found
if (existing_user == 0)
{
//user doesn't exist
printf("User ID not found\n");
}
//close files
fclose(file);
return 0;
}
//hash funbction
void pass_hash(char *in, char *out)
{
//adjust to upper case
int i;
for(i = 0; in[i]; i++)
{
in[i] = toupper(in[i]);
}
//adjust length - cut or add \0
if (strlen(in) > 12)
{
strncpy(out, in, 12);
}
if (strlen(in) < 12)
{
int j;
for (j = strlen(in); j < 12; j++)
{
in[j] = '@';
}
}
//encryption
char sub1[3];
char sub1_hash[32];
char sub2[3];
char sub2_hash[32];
char sub3[3];
char sub3_hash[32];
//split into three substrings
memcpy(sub1, in, 4);
chopN(in, 4);
memcpy(sub2, in, 4);
chopN(in, 4);
memcpy(sub3, in, 4);
//use E function
E(sub1, sub1_hash);
E(sub2, sub2_hash);
E(sub3, sub3_hash);
//concatenate strings
strcpy(out, sub1_hash);
strcat(out, sub2_hash);
strcat(out, sub3_hash);
}
/********************* E function *************************/
// DES replacement cipher
// The function E takes 4 bytes from *in as input and
// writes 4 bytes to *out
void E(char *in, char *out)
{
out[0]=(in[0]&0x80)^(((in[0]>>1)&0x7F)^((in[0])&0x7F));
out[1]=((in[1]&0x80)^((in[0]<<7)&0x80))^(((in[1]>>1)&0x7F)^((in[1])&0x7F));
out[2]=((in[2]&0x80)^((in[1]<<7)&0x80))^(((in[2]>>1)&0x7F)^((in[2])&0x7F));
out[3]=((in[3]&0x80)^((in[2]<<7)&0x80))^(((in[3]>>1)&0x7F)^((in[3])&0x7F));
}
void chopN(char *str, size_t n)
{
size_t len = strlen(str);
if (n > len)
return; // Or: n = len;
memmove(str, str+n, len - n + 1);
}
//xor the hash with the server's random number
char * generateRandXOR(char* hash, int r)
{
char * out = (char*)calloc(MAX_PASSWORD_LENGTH, sizeof(char));
R(hash, out, r);
R(&hash[4], &out[4], r);
R(&hash[8], &out[8], r);
return out;
}
//xor function for each bundle (4 bytes)
void R(char* in, char* out, int r)
{
out[3] = in[3] ^ (r & 255); //xor the first byte with r's first byte
r = r >> 8; //shift r by one byte
out[2] = in[2] ^ (r & 255);
r = r >> 8;
out[1] = in[1] ^ (r & 255);
r = r >> 8;
out[0] = in[0] ^ (r & 255);
}
|
C
|
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <s2e.h>
int main(int argc, char **argv)
{
if(argc < 2) {
puts("Usage: ./symio program_path [args]");
return 0;
}
int n;
char buf[1024];
puts("[Get crash input....]");
n = read(0, buf, sizeof(buf));
if (n < 0) {
puts("payload error");
return 0;
}
int pipe_fd[2];
pid_t pid;
//s2e_disable_forking();
s2e_make_concolic(buf, n, "crax");
if(pipe(pipe_fd) < 0) {
printf("pipe error\n");
exit(1);
}
write(pipe_fd[1], buf, n);
char *args[argc - 1];
int i;
for (i = 0; i < argc - 1; i++)
args[i] = argv[i + 1];
args[i] = NULL;
if(!(pid = fork())) {
dup2(pipe_fd[0], 0);
close(pipe_fd[0]);
close(pipe_fd[1]);
execve(args[0], args, NULL);
} else {
close(pipe_fd[0]);
close(pipe_fd[1]);
wait();
s2e_kill_state(0, "program terminated");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/*
* Definition of a struct that contains an int value
*/
typedef struct container* Container;
// TRIVIA: Guess what the struct size is
//
// Structs on my machine are 8 bytes aligned
// On my macOS (64 bit), pointers are 8 bytes.
// Integers are 4 bytes. Which means the total size
// of the struct is 12 bytes. if you print sizeof(struct container),
// you will notice that the size is 16 bytes. So, in my case,
// the struct will always be a mulitple of 8. Experiment
// with data types and combinations of variables in the struct
// to test this idea out
struct container {
int val;
Container next;
};
/*
* Function prototypes go here
*/
Container create_container(int val);
Container create_linked_containers(int numContainers, int startingValue);
void show_addresses(Container container);
void free_list(Container container);
int main(int argc, char* argv[]) {
Container head = create_linked_containers(10, 1);
Container curr = head;
while (curr != NULL) {
show_addresses(curr);
curr = curr->next;
}
free_list(head);
return EXIT_SUCCESS;
}
Container create_container(int val) {
Container newContainer = malloc(sizeof(*newContainer));
newContainer->val = val;
newContainer->next = NULL;
return newContainer;
}
Container create_linked_containers(int numContainers, int startingValue) {
Container head = create_container(startingValue);
Container current = head;
int i = 0;
int currentValue = startingValue + 1;
while (i < numContainers) {
current->next = create_container(currentValue);
i++;
current = current->next;
currentValue++;
}
return head;
}
void free_list(Container container) {
Container curr = container;
Container prev = NULL;
while (curr != NULL) {
prev = curr;
curr = curr->next;
free(prev);
}
}
// Get your hands dirty with actual pointer addresses and
// see how linkedlists are actually linked
void show_addresses(Container container) {
printf("===============================\n");
printf("Pointer pointing to container at: %p\n", container);
printf("Container contains: %d\n", container->val);
printf("Pointer containing address to the next pointer: %p\n", container->next);
printf("===============================\n");
}
|
C
|
/* name.h - fopen */
/* Constants that define the name mapping table sizes */
#define NAMPLEN 32 /* max size of a name prefix */
#define NAMRLEN 32 /* max size of a replacement */
#define NAMLEN 80 /* maximum size of a file name */
#define NNAMES 14 /* number of prefix definitions */
/* Definition of the name prefix table that defines all name mappings */
struct nament { /* definition of prefix mapping */
char npre[NAMPLEN]; /* prefix of a name */
char nrepl[NAMRLEN]; /* replacement for that prefix */
int ndev; /* device for this prefix */
};
struct nam { /* all name space variables */
int nnames; /* number of entries in nametab */
struct nament nametab[NNAMES];/* actual table of mappings */
} Nam;
#ifndef NAMESPACE
#define NAMESPACE SYSERR
#endif
#define fopen(n,m) open(NAMESPACE, n, m)
|
C
|
#include "displayRoad.h"
/* @function
* Creates an image that shows the road from
* the point of view of the car
*
* @param
* int horizonAbs : abscissa of the horizon point
* int horizonOrd : ordinate of the horizon point
* car carPosition : position of the car
* int horizonHeight : height of the horizonLine
* int roadWidth : width of the road in fraction of the imageSize (3 for 1/3 of the image)
* int imageSize : size of a side of the square image
*
* @return : pointer on the DonneesImageTab created
*/
DonneesImageTab *createRoadImage(int horizonAbs, int horizonOrd, Car carPosition, int horizonHeight, int roadWidth, int imageSize)
{
//Image of the road
DonneesImageTab *image = initTab(imageSize, imageSize);
//Index used to browse the image
int index;
//Print the ground
for(index = horizonHeight - 1; index >= 0; index--)
{
printLine(image, 0, index, imageSize-1, index, 10, 128, 10);
}
//Print the road
for(index = imageSize/2 - roadWidth/2; index < imageSize/2 + roadWidth/2; index++)
{
printLine(image, horizonAbs, horizonOrd, index, 0, 64, 64, 64);
}
//Print the road left line
for(index = imageSize/2 - roadWidth/2; index < imageSize/2 - roadWidth/2 + (roadWidth/20); index++)
{
printLine(image, horizonAbs, horizonOrd, index, 0, 192, 192, 192);
}
//Print the road right line
for(index = imageSize/2 + roadWidth/2; index > imageSize/2 + roadWidth/2 - (roadWidth/20); index--)
{
printLine(image, horizonAbs, horizonOrd, index, 0, 192, 192, 192);
}
//Print the horizon line
printLine(image, 0, horizonHeight, imageSize-1, horizonHeight, 0, 128, 255);
//And the sky
for(index = horizonHeight + 1; index < image->hauteurImage; index++)
{
printLine(image, 0, index, imageSize-1, index, 0, 128, 255);
}
//Print the horizon point
image->donneesTab[horizonAbs][horizonOrd][RED] = 255;
//Print the car
printSprite("sprites/car.bmp", image, carPosition.abscissa - (SPRITE_WIDTH / 2), 0);
return image;
}
/* @function
* Print a sprite on an image
*
* @param
* char *spriteName : path and name of the sprite
* DonneesImageTab *image : image to modify
* int spriteAbs : abscissa of the sprite (bottom left point)
* int spriteOrd : ordinate of the sprite (bottom left point)
*
* @return : \
*/
void printSprite(char *spriteName, DonneesImageTab *image, int spriteAbs, int spriteOrd)
{
//Get the sprite tab
DonneesImageRGB *bmpSprite = lisBMPRGB(spriteName);
DonneesImageTab *sprite = RGBToTab(bmpSprite);
//Browse the sprite
int absIndex, ordIndex;
for(absIndex = 0; absIndex < sprite->largeurImage; absIndex++)
{
for(ordIndex = 0; ordIndex < sprite->hauteurImage; ordIndex++)
{
//Coordinates of the pixel in the image
int realAbs = absIndex + spriteAbs;
int realOrd = ordIndex + spriteOrd;
//Check if in the image
if(realAbs >= 0 && realAbs < image->largeurImage
&& realOrd >= 0 && realOrd < image->hauteurImage )
{
int spriteR = sprite->donneesTab[absIndex][ordIndex][RED];
int spriteG = sprite->donneesTab[absIndex][ordIndex][GREEN];
int spriteB = sprite->donneesTab[absIndex][ordIndex][BLUE];
//Check if not background color
if(spriteR != SPRITE_BACKGROUND_R || spriteG != SPRITE_BACKGROUND_G
|| spriteB != SPRITE_BACKGROUND_B)
{
image->donneesTab[realAbs][realOrd][RED] = spriteR;
image->donneesTab[realAbs][realOrd][GREEN] = spriteG;
image->donneesTab[realAbs][realOrd][BLUE] = spriteB;
}
}
}
}
}
/* @function
* Print a line on a DonneesImageTab
*
* @param
* DonneesImageTab *image : image to modify
* int x1 : abscissa of the starting point
* int y1 : ordinate of the starting point
* int x2 : abscissa of the ending point
* int y2 : ordinate of the ending point
* int red : red value of the color of the line
* int green: green value of the color of the line
* int blue: blue value of the color of the line
*
* @return : \
*/
void printLine(DonneesImageTab *image, int x1, int y1, int x2, int y2, int red, int green, int blue)
{
int dx, dy;
dx = x2 -x1;
if(dx != 0)
{
if(dx > 0)
{
dy = y2 - y1;
if(dy != 0)
{
if(dy > 0)
{
// vecteur oblique dans le 1er quadran
if(dx >= dy)
{
// vecteur diagonal ou oblique proche de l’horizontale, dans le 1er octant
int e = dx;
dx = e * 2; // e est positif
dy = dy * 2;
while(1)
{
// déplacements horizontaux
image->donneesTab[x1][y1][RED] = red;
image->donneesTab[x1][y1][GREEN] = green;
image->donneesTab[x1][y1][BLUE] = blue;
x1 = x1 + 1;
if(x1 == x2)
{
break;
}
e = e - dy;
if(e < 0)
{
y1 = y1 + 1 ; // déplacement diagonal
e = e + dx ;
}
}
}
else
{
// vecteur oblique proche de la verticale, dans le 2d octant
int e = dy;
dy = e * 2; // e est positif
dx = dx * 2;
while(1)
{
// déplacements verticaux
image->donneesTab[x1][y1][RED] = red;
image->donneesTab[x1][y1][GREEN] = green;
image->donneesTab[x1][y1][BLUE] = blue;
y1 = y1 + 1;
if(y1 == y2)
{
break;
}
e = e - dx;
if(e < 0)
{
x1 = x1 + 1; // déplacement diagonal
e = e + dy;
}
}
}
}
else // dy < 0 (et dx > 0)
{
// vecteur oblique dans le 4e cadran
if (dx >= -dy)
{
// vecteur diagonal ou oblique proche de l’horizontale, dans le 8e octant
int e = dx;
dx = e * 2; // e est positif
dy = dy * 2;
while(1)
{ // déplacements horizontaux
image->donneesTab[x1][y1][RED] = red;
image->donneesTab[x1][y1][GREEN] = green;
image->donneesTab[x1][y1][BLUE] = blue;
x1 = x1 + 1;
if(x1 == x2)
{
break;
}
e = e + dy;
if(e < 0)
{
y1 = y1 - 1 ; // déplacement diagonal
e = e + dx ;
}
}
}
else
{
// vecteur oblique proche de la verticale, dans le 7e octant
int e = dy;
dy = e * 2; // e est négatif
dx = dx * 2;
while(1)
{
// déplacements verticaux
image->donneesTab[x1][y1][RED] = red;
image->donneesTab[x1][y1][GREEN] = green;
image->donneesTab[x1][y1][BLUE] = blue;
y1 = y1 - 1;
if(y1 == y2)
{
break;
}
e = e + dx;
if(e > 0)
{
x1 = x1 + 1 ; // déplacement diagonal
e = e + dy ;
}
}
}
}
}
else // dy = 0 (et dx > 0)
{
// vecteur horizontal vers la droite
do
{
image->donneesTab[x1][y1][RED] = red;
image->donneesTab[x1][y1][GREEN] = green;
image->donneesTab[x1][y1][BLUE] = blue;
x1 = x1 + 1;
}while (x1 < x2);
}
}
else // dx < 0
{
dy = y2 - y1;
if(dy != 0)
{
if(dy > 0)
{
// vecteur oblique dans le 2d quadran
if (-dx >= dy)
{
// vecteur diagonal ou oblique proche de l’horizontale, dans le 4e octant
int e = dx;
dx = e * 2; // e est négatif
dy = dy * 2;
while(1)
{ // déplacements horizontaux
image->donneesTab[x1][y1][RED] = red;
image->donneesTab[x1][y1][GREEN] = green;
image->donneesTab[x1][y1][BLUE] = blue;
x1 = x1 - 1;
if(x1 == x2)
{
break;
}
e = e + dy;
if(e >= 0)
{
y1 = y1 + 1; // déplacement diagonal
e = e + dx ;
}
}
}
else
{
// vecteur oblique proche de la verticale, dans le 3e octant
int e = dy;
dy = e * 2; // e est positif
dx = dx * 2;
while(1)
{
// déplacements verticaux
image->donneesTab[x1][y1][RED] = red;
image->donneesTab[x1][y1][GREEN] = green;
image->donneesTab[x1][y1][BLUE] = blue;
y1 = y1 + 1;
if(y1 == y2)
{
break;
}
e = e + dx;
if(e <= 0)
{
x1 = x1 - 1 ; // déplacement diagonal
e = e + dy ;
}
}
}
}
else // dy < 0 (et dx < 0)
{
// vecteur oblique dans le 3e cadran
if(dx <= dy)
{
// vecteur diagonal ou oblique proche de l’horizontale, dans le 5e octant
int e = dx;
dx = e * 2; // e est négatif
dy = dy * 2;
while(1)
{
// déplacements horizontaux
image->donneesTab[x1][y1][RED] = red;
image->donneesTab[x1][y1][GREEN] = green;
image->donneesTab[x1][y1][BLUE] = blue;
x1 = x1 - 1;
if(x1 == x2)
{
break;
}
e = e - dy;
if(e >= 0)
{
y1 = y1 - 1; // déplacement diagonal
e = e + dx;
}
}
}
else
{
// vecteur oblique proche de la verticale, dans le 6e octant
int e = dy;
dy = e * 2; // e est négatif
dx = dx * 2;
while(1)
{
// déplacements verticaux
image->donneesTab[x1][y1][RED] = red;
image->donneesTab[x1][y1][GREEN] = green;
image->donneesTab[x1][y1][BLUE] = blue;
y1 = y1 - 1;
if(y1 == y2)
{
break;
}
e = e -dx;
if(e >= 0)
{
x1 = x1 - 1; // déplacement diagonal
e = e + dy;
}
}
}
}
}
else // dy = 0 (et dx < 0)
{
// vecteur horizontal vers la gauche
do
{
image->donneesTab[x1][y1][RED] = red;
image->donneesTab[x1][y1][GREEN] = green;
image->donneesTab[x1][y1][BLUE] = blue;
x1 = x1 - 1;
}while(x1 > x2);
}
}
}
else // dx = 0
{
dy = y2 - y1;
if(dy != 0)
{
if(dy > 0)
{
// vecteur vertical croissant
do
{
image->donneesTab[x1][y1][RED] = red;
image->donneesTab[x1][y1][GREEN] = green;
image->donneesTab[x1][y1][BLUE] = blue;
y1 = y1 + 1;
}while(y1 < y2);
}
else
{
// dy < 0 (et dx = 0)
// vecteur vertical décroissant
do
{
image->donneesTab[x1][y1][RED] = red;
image->donneesTab[x1][y1][GREEN] = green;
image->donneesTab[x1][y1][BLUE] = blue;
y1 = y1 - 1;
}while(y1 > y2);
}
}
}
image->donneesTab[x1][y1][RED] = red;
image->donneesTab[x1][y1][GREEN] = green;
image->donneesTab[x1][y1][BLUE] = blue;
}
|
C
|
#include <stdio.h>
#include <ctype.h>
//TODO Global variables
int main(int argc, char* argv[])
{
//Driver Class
//Variable calls
compress();
decompress();
return 0;
}
void compress(){
//-------------------------------------------
//Variables
char fileString[1];
FILE *fptrIn;
FILE *fptrOut;
int repeated = 0;
//-------------------------------------------
//file opening
printf("File Compress\n");
if ((fptrIn = fopen("tobeconverted.txt","r+"))==NULL){
printf("Error opening file to be converted!\n");
exit(1);
}
if ((fptrOut = fopen("convertedFile.rle","w+" ))==NULL){
printf("Error opening file to write to!\n");
exit(1);
}
fscanf(fptrIn,"%[^n]", fileString);
//--------------------------------------------
//file writing
/* This function takes the ptr data from the In file
* and adds it all into c
* it then forces a single character from c into temp
* goes through an if statement to test whether the data is similar
* if it is, go ahead and add to repeated.
* when there isn't a repeated letter, then dump the repeated int and
* single letter that temp has in it into the temp buffer.
*/
char *c = fptrIn->_base; //i had to cheat and actually access the object._base
char temp = *c;
while (*c){ // increment a letter of c
if (temp != *c){ //check to see if the letters are different
//fprintf(fptrOut,"%d",repeated);
fputc(temp, fptrOut);//write the letter to the array
fprintf(fptrOut,"%d",repeated); //write the number of letters to the array
//writeCount++; // position in array hold[]
printf("%d", repeated); // print the int that is in repeated.
repeated=0; // reset repeated back to 0 to start counting again
temp = *c; //dump a new letter into temp
} else { // if they are the same
repeated++; // increment repeated int
putchar(*c++); // push next char.
}
}
//TODO fix the error where the last letters aren't being recorded
fputc(temp, fptrOut);//write the letter to the array
printf("%d", repeated); // print the int that is in repeated.
//------------------------------------------------
//File Closing
fclose(fptrIn);
fclose(fptrOut);
}
void decompress(){
//-------------------------------------------
//Variables
char fileString[1];
FILE *fptrIn;
FILE *fptrOut;
int repeated = 0;
//-------------------------------------------
//file opening
printf("File Decompress\n");
if ((fptrIn = fopen("convertedFile.rle","r+" ))==NULL){
printf("Error opening file to be converted!\n");
exit(1);
}
if ((fptrOut = fopen("tobeconverted.txt","w+"))==NULL){
printf("Error opening file to write to!\n");
exit(1);
}
fscanf(fptrIn,"%[^n]", fileString);
//--------------------------------------------
//file writing
/* This function takes the ptr data from the In file
* and adds it all into c
* it then forces a single character from c into temp
* it will iterate through each character
* a character value will be written so many times based on
* the results of *c
*
* a4b3d2
* check first letter
* char *letterIn = *c
* set to a letter char
* check second char
* 4
* int numIn = *c;
* for (int i = 0; i < numIn; i++){
* printf("%s", letterIn);
* }
*
*/
char *c = fptrIn->_base; //i had to cheat and actually access the object._base
char temp = *c;
char letterIn;
int numIn;
while (*c){ // increment a letter of c
//TODO check to see what the current temp is.
if (temp == 32){// is there a space?
putchar(*c++);
putchar(*c++);
fprintf(fptrOut," ");
temp = *c;
}
if (isalpha(temp)){
letterIn = temp;
putchar(*c++); // push next char
temp = *c;
}
if (isdigit(temp)) {
numIn = temp - '0';
temp = putchar(*c++); // push next char
temp = *c;
}
int i;
for (i = 0; i < numIn; i++){
fputc(letterIn, fptrOut);
}
}
//------------------------------------------------
//File Closing
fclose(fptrIn);
fclose(fptrOut);
}
/*
Sources
http://www.programiz.com/c-programming/examples/read-file
http://stackoverflow.com/questions/3213827/how-to-iterate-over-a-string-in-c
http://stackoverflow.com/questions/9840629/create-a-file-if-one-doesnt-exist-c
http://stackoverflow.com/questions/11573974/write-to-txt-file
http://www.cprogramming.com/tutorial/cfileio.html
https://qt-project.org/doc/qtcreator-2.6/creator-debug-mode.html
http://www.c4learn.com/c-programming/c-reference/fputc-function/
http://stackoverflow.com/questions/2229377/writing-an-integer-to-a-file-with-fputs
http://stackoverflow.com/questions/2736753/how-to-remove-extension-from-file-name
http://stackoverflow.com/questions/868496/how-to-convert-char-to-integer-in-c
*/
//void printToAray(char data){
// int i;
// //temp[writeCount] = data;
// //fputc(temp[writeCount], fptrOut);
// fputc(data, fptrOut);
// //writeCount++;
//// for (i = 0; i < sizeof(data); i++)
//// temp[i] = data[i];
//}
|
C
|
#include <stdio.h>
#include <ctype.h>
int count_words(const char* str)
{
int number_of_words = 0;
int is_prev_space = 1;
for (int i = 0; str[i] != '\0'; ++i)
{
if (is_prev_space && !isspace(str[i]))
number_of_words += 1;
is_prev_space = isspace(str[i]);
}
return number_of_words;
}
int main()
{
char str[201];
scanf("%200[^\n]", str);
printf("%i\n", count_words(str));
}
|
C
|
/*********************************************************************/
/* Homework Assignment 5, for EECS 22, Fall 2018 */
/* */
/* Author: Jordan Bonecutter */
/* */
/* IterativeFilter.c: file for iterative filters */
/* */
/*********************************************************************/
#include <stdio.h>
#include "IterativeFilter.h"
#include "Image.h"
#include "ImageList.h"
#include "Movie.h"
#include <assert.h>
MOVIE *doIterativeFilter(IMAGE *image, iterableFilter filter, int start, int end, int change)
{
assert(image);
MOVIE *movie = CreateMovie();
IMAGE *temp;
if (start > end)
{
for(float x = start; x >=end; x -= change)
{
temp = filter(temp, x);
AppendRGBImage(movie -> Frames, temp);
}
}
if (start < end)
{
for(float x = start; x <= end; x += change)
{
temp = filter(temp, x);
AppendRGBImage(movie -> Frames, temp);
}
}
return movie;
}
|
C
|
#include<stdio.h>
int main()
{
int i, initial=1, mid=1 , term, pri;
printf("Enter the number of terms :\n");
scanf("%d", &term);
for(i=1; i<=term; ++i)
{
printf("\n%d" ,initial);
pri=initial+mid;
initial=mid;
mid=pri;
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* lsttest_main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: anorman <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/03 15:25:24 by anorman #+# #+# */
/* Updated: 2019/06/07 17:30:29 by anorman ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdio.h>
static void del(void *content, size_t size)
{
free(content);
content = NULL;
}
int main(void)
{
t_list *lst1;
char *str;
str = ft_strdup("Helloworld");
free(str);
lst1 = ft_lstnew(str, 11);
ft_lstaddend(&lst1, ft_lstnew("more stuff", 11));
ft_lstaddend(&lst1, ft_lstnew("other", 6));
str = ft_lstcat(lst1);
printf("%s\n", str);
ft_lstprint(lst1, "\n");
ft_lstdel(&lst1, &del);
if (lst1)
printf("del failed");
str = ft_strdup("Helloworld");
free(str);
lst1 = ft_lstnew(str, 11);
ft_lstaddend(&lst1, ft_lstnew("more stuff", 11));
ft_lstaddend(&lst1, ft_lstnew("other", 6));
ft_lstdelmid(&lst1, lst1->next);
str = ft_lstcat(lst1);
printf("%s\n", str);
ft_lstprint(lst1, "\n");
ft_lstdel(&lst1, &del);
if (lst1)
printf("del failed");
return (0);
}
|
C
|
#include <stdio.h>
void main()
{
int a,b,c,d,e;
scanf("%d",&a);//һ10-9999Ҵչ4λ
{
b=a%10;
c=(a%100)/10;
d=(a%1000)/100;
e=(a%10000)/1000;
printf("a:%d change to:%d%d%d%d\n",a,b,c,d,e);
}
printf("\n");
}
|
C
|
#ifndef FILESYS_H
#define FILESYS_H
#define DEVNAME "/dev/fd0H1440" /*Ҫ豸ļ,ʾ1.44MB*/
#define DIR_ENTRY_SIZE 32 /*Ŀ¼С*/
#define SECTOR_SIZE 512 /*ÿС*/
#define FAT_ONE_OFFSET 0X200 /*һFATʼַ*/
#define FAT_TWO_OFFSET 0X1400 /*ڶFATʼַ*/
#define ROOTDIR_OFFSET 0X2600 /*Ŀ¼ʼַ*/
#define DATA_OFFSET 0x4200 /*ʼַ*/
/* λ */
#define ATTR_READONLY 0x01 // 00000001
#define ATTR_HIDDEN 0x02 // 00000010
#define ATTR_SYSTEM 0x04 // 00000100
#define ATTR_VLABEL 0x08 // 00001000
#define ATTR_SUBDIR 0x10 // 00010000
#define ATTR_ARCHIVE 0x20 // 00100000
/* ʱ5:6:5 */
#define MASK_HOUR 0xf800 // 1111100000000000
#define MASK_MIN 0x07e0 // 11111100000
#define MASK_SEC 0x001f // 11111
/* 7:4:5 */
#define MASK_YEAR 0xfe00 // 1111111000000000
#define MASK_MONTH 0x01e0 // 111100000
#define MASK_DAY 0x001f // 11111
/* ṹ嶨 */
struct BootDescriptor_t{
unsigned char Oem_name[9]; /*0x03 - 0x0a*/
int BytesPerSector; /*0x0b - 0x0c*/
int SectorsPerCluster; /*0x0d */
int ReservedSectors; /*0x0e - 0x0f*/
int FATs; /*0x10 */
int RootDirEntries; /*0x11 - 0x12*/
int LogicSectors; /*0x13 - 0x14*/
int MediaType; /*0x15 */
int SectorsPerFAT; /*0x16 - 0x17*/
int SectorsPerTrack; /*0x18 - 0x19*/
int Heads; /*0x1a - 0x1b*/
int HiddenSectors; /*0x1c - 0x1d*/
};
/* ṹ嶨˸Ŀ¼Ŀ¼ */
struct Entry{
unsigned char short_name[12]; /*ֽ0-10,11ֽڳȵ*/
unsigned char long_name[27]; /*δʹ,26ֽڳ */
unsigned short hour,min,sec; /*22 - 23ֽ*/
unsigned short year,month,day; /*24 - 25ֽ*/
unsigned short FirstCluster; /*26 - 27ֽ*/
unsigned int size; /*28 - 31ֽ*/
//λ
// 7 6 5 4 3 2 1 0
// N N A D V S H R N:δʹ
unsigned char readonly:1; /* R(ֻ) */
unsigned char hidden:1; /* H() */
unsigned char system:1; /* S(ϵͳļ) */
unsigned char vlabel:1; /* V() */
unsigned char subdir:1; /* D(Ŀ¼) */
unsigned char archive:1; /* A(浵) */
};
/* Ǻ */
//int fd_load();
int fd_ls();
int fd_cd(char *dir);
int fd_rm(char *file_name);
void findDate(unsigned short *year,
unsigned short *month,
unsigned short *day,
unsigned char info[2]);
void findTime(unsigned short *hour,
unsigned short *min,
unsigned short *sec,
unsigned char info[2]);
int ReadFat();
int WriteFat();
void ScanBootSector();
void ScanRootEntry();
int ScanEntry(char *entryname, struct Entry *pentry, int mode);
int GetEntry(struct Entry *entry);
void FileNameFormat(unsigned char* name);
unsigned short GetFatCluster(unsigned short prev);
void ClearFatCluster(unsigned short cluster);
#endif
|
C
|
#include "list.h"
t_node *cur;
t_node *start;
void init()
{
cur = NULL;
};
int add(int data)
{
int flag=0;
t_node *p = cur;
if(cur==NULL){
flag=1;
}
cur = (t_node *)malloc(sizeof(t_node));
if (!cur)
return -1;
cur->data = data;
cur->next = p;
if(flag){
start=cur;
}
return 0;
}
int delCur(){
t_node *p=cur;
cur=cur->next;
free(p);
}
int getCur(){
return cur->data;
}
int getStart(){
return start->data;
}
int hasNext(t_node *p){
if(p->next!=NULL){
return 1;
}
return 0;
}
int getElement(int n){
t_node *p=cur;
t_node *element=p;
int counter=0;
while(hasNext(p)){
if(counter<n){
counter++;
}
if(counter==n){
element=element->next;
}
p=p->next;
}
if(counter==n){
return element->data;
}
return -1;
}
|
C
|
#include <stdio.h>
#define NUM 4
int main (void)
{
int i, no;
int a[NUM];
printf("数据个数:%d\n", NUM );
for (i = 1;i <= NUM; i++)
{ printf("%d号:", i);
scanf("%d", &a[i-1]);
}
putchar('{');
for (i = 1; i<= NUM; i++)
printf("%d, ",a[i-1]);
putchar('}');
return 0;
}
|
C
|
/**
* \file
* Describes a path through a tree.
*/
#include "address.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ENDL "\n"
#define LOG(...) fprintf(stderr,__VA_ARGS__)
#define TRY(e) do{if(!(e)) { LOG("%s(%d): %s()"ENDL "\tExpression evaluated as false."ENDL "\t%s"ENDL,__FILE__,__LINE__,__FUNCTION__,#e); goto Error;}} while(0)
#define NEW(T,e,N) TRY((e)=malloc(sizeof(T)*(N)))
#define ZERO(T,e,N) memset((e),0,(N)*sizeof(T))
#define REALLOC(T,e,N) TRY((e)=realloc((e),sizeof(T)*(N)))
#ifdef _MSC_VER
#pragma warning (disable:4996) // deprecation warning for sprintf
#define snprintf _snprintf
#define PATHSEP '\\'
#else
#define PATHSEP '/'
#endif
struct _address_t
{ int* ids; // array of child indexes starting from the root of the tree.
unsigned sz, // the length of the path
cap, // the capacity allocated for the \a ids array. This allows \a ids to be dynamically extended as necessary
i; // A cursor ues for iteration that keeps track of where the iterator is on the path.
};
/** The child id at the current iterator position. */
unsigned address_id(address_t self)
{return self->ids[self->i];}
/** Initialize the iterator */
address_t address_begin(address_t self)
{ self->i=0;
return self->sz?self:0;
}
/** \returns 1 if a and b represent the same address, otherwise 0. */
unsigned address_eq(address_t a, address_t b)
{ unsigned i;
if(a->sz!=b->sz) return 0;
for(i=0;i<a->sz;++i)
if(a->ids[i]!=b->ids[i])
return 0;
return 1;
}
/** Move the iterator down the tree one step. */
address_t address_next(address_t self)
{ if(!self) return 0;
++self->i;
return (self->i<self->sz)?self:0;
}
/** Construct an address_t object */
address_t make_address()
{ address_t out=0;
NEW(struct _address_t,out,1);
ZERO(struct _address_t,out,1);
return out;
Error:
return 0;
}
/** Destroy an address_t object */
void free_address(address_t self)
{ if(!self) return;
if(self->ids) free(self->ids);
free(self);
}
/** Make a copy of an address_t object */
address_t copy_address(address_t self)
{ address_t it,out=0;
if(!self) return 0;
TRY(out=make_address());
for(it=address_begin(self);it;it=address_next(self))
address_push(out,address_id(it));
return out;
Error:
free_address(out);
return 0;
}
static int reserve(address_t self, unsigned capacity)
{ if(capacity>self->cap)
REALLOC(int,self->ids,self->cap=capacity);
return 1;
Error:
return 0;
}
/** Add a node to the end of the path. */
address_t address_push(address_t self, int i)
{ if(self->sz+1>=self->cap)
REALLOC(int,self->ids,self->cap=(unsigned)(1.2*self->cap+10));
self->ids[self->sz++]=i;
return self;
Error:
return 0;
}
/** Remove a node from the end of the path. */
address_t address_pop(address_t self)
{ if(self->sz==0) return 0;
self->sz--;
return self;
}
/** Render address to an unsigned integer (for printing).*/
uint64_t address_to_int(address_t self, uint64_t base)
{ uint64_t v=0;
size_t i;
for(i=0;i<self->sz;++i)
v=v*base+(1+self->ids[i]); // 1,2,3,4
return v;
}
address_t address_from_int(uint64_t v, size_t ndigits, uint64_t base)
{ size_t i;
address_t out=0;
TRY(out=make_address());
if(v==0)
return out;
TRY(reserve(out,ndigits));
out->sz=ndigits;
for(i=0;i<ndigits;++i)
{ out->ids[ndigits-i-1]=v?(v-1)%base:0; // 0 is root. digits 1-4 address nodes on the path.
v/=base;
}
return out;
Error:
free_address(out);
return 0;
}
/**
* Renders address to something like "1/2/0/0/4/"
* \param[in] path Buffer into which to render the string.
* \param[in] n size of the buffer \a path in bytes.
* \param[in] address The address to render.
*/
char* address_to_path(char* path, int n, address_t address)
{ unsigned k;
char *op=path;
for(address=address_begin(address);address&&n>=0;address=address_next(address))
{ k=snprintf(path,n,"%u%c",address_id(address)+1,PATHSEP);
path+=k;
n-=k;
}
// remove terminal path separator
if(path!=op) path[-1]='\0';
return (n>=0)?op:0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
/* https://github.com/RPISEC/MBE/blob/master/src/lab05/lab5B.c */
/* gcc -fno-stack-protector --static -o exp2 exp2.c */
int main(int argc, char **argv)
{
char buffer[128] = {0};
int size = atoi(argv[1]);
if(size > 64) {
printf("Too large\n");
exit(1);
}
printf("Insert ROP chain here:\n");
fgets(buffer, size*2, stdin);
return EXIT_SUCCESS;
}
|
C
|
typedef struct file{
char name[32];
struct file *next;
int sector;
char properties[4];
int size;
}file;
typedef struct ffolder{
char name[32];
int sector;
int insector;
int upsector;
int next;
int filesector;
char properties[3];
int size;
}ffolder;
typedef struct folder{
char name[32];
int sector;
struct folder *in;
struct folder *up;
struct folder *next;
struct file *fin;
char properties[3];
int size;
}folder;
typedef struct ffile{
char name[32];
int next;
int sector;
char properties[4];
int size;
}ffile;
folder *first=0,*temp=0,*ptr=0,*curptr=0;
file *fptr,*ftemp;
ffile fout;
long cursector=1;
int readfs(char *path){
ffolder fold;
FILE *f;
ffolder temp1;
f=fopen(path,"r+");
ptr=first;
while(1)
{
if(first==0)
{
fseek(f,cursector,0);
fread(&temp1,sizeof(temp1),1,f);
cursector=cursector+sizeof(temp1);
first=(folder*)malloc(sizeof(folder));
strcpy(first->name,temp1.name);
first->sector=temp1.sector;
first->up=0;
first->next=0;
strcpy(first->properties,temp1.properties);
first->in=0;
first->fin=0;
first->size=0;
ptr=first;
fold=temp1;
}
else
{
ptr=temp;
temp1=fold;
fseek(f,cursector,0);
if(fread(&fold,sizeof(fold),1,f)!=1)
return 0;
cursector=cursector+sizeof(fold);
temp=(folder*)malloc(sizeof(folder));
strcpy(temp->name,fold.name);
temp->sector=fold.sector;
temp->up=ptr;
temp->next=0;
strcpy(temp->properties,fold.properties);
temp->in=0;
temp->fin=0;
temp->size=0;
if(temp1.insector!=0)
{
if(ptr==0)
ptr=first;
ptr->in=temp;
}
else if(temp1.next!=0)
{
ptr->next=temp;
}
else if(temp1.filesector!=0)
{
while(fout.sector!=0)
{
fptr=ftemp;
ftemp=(file*)malloc(sizeof(file));
fread(&fout,sizeof(fout),1,f);
strcpy(ftemp->name,fout.name);
ftemp->size=fout.size;
ftemp->sector=fout.sector;
strcpy(ftemp->properties,fout.properties);
ftemp->size=fout.size;
ftemp->next=0;
if(ptr->fin==0)
{
ptr->fin=ftemp;
}
else if(fptr!=0)
{
fptr->next=ftemp;
}
}
}
else if(ptr->up!=0)
{
ptr=ptr->up;
}
ftemp=0;
cursector=ftell(f);
}
}
}
void showCurrentfolder(folder *cur){
while(cur->up!=0)
{
printf("%s",cur->name);
cur=cur->up;
printf("<-");
}
printf("%s",cur->name);
printf(":>");
}
int makedir(char *name){
temp=(folder*)malloc(sizeof(folder));
strcpy(temp->name,name);
temp->sector=0;
temp->up=curptr;
temp->next=0;
strcpy(temp->properties,"rwv");
temp->in=0;
temp->fin=0;
temp->size=0;
ptr=curptr->in;
if(ptr!=0)
{
if(strcmp(name,ptr->name)==0)
{
printf("a folder with same name already exists\n");
free(temp);
return 0;//a folder with same name exists
}
while(ptr->next!=0)
{
ptr=ptr->next;
if(strcmp(name,ptr->name)==0)
{
printf("a folder with same name already exists\n");
free(temp);
return 0;//a folder with same name exists
}
}
ptr->next=temp;
}
else
{
curptr->in=temp;
}
}
int changedir(char *name)
{
//puts(name);
ptr=curptr->in;
if(ptr!=0)
{
while(ptr!=0)
{
if(strcmp(name,ptr->name)==0)
{
curptr=ptr;//changed current folder
break;
}
ptr=ptr->next;
}
}
}
void showdir(){
int d=0,f=0;
file *fi;
printf("\n");
ptr=curptr->in;
if(ptr!=0)
while(ptr!=0)
{
printf("%s <dir>\n",ptr->name);
ptr=ptr->next;
d=d+1;
}
fi=curptr->fin;
if(fi!=0)
while(fi!=0)
{
printf("%s <file>\n",fi->name);
fi=(file*)fi->next;
f=f+1;
}
printf("\n");
printf("Total number of directories = %d \nand files = %d\n\n",d,f);
}
int writefs(char *path){
FILE *f;
long fbrk=0,fsector;
ffolder in;
ptr=first;
fptr=0;
f=fopen(path,"r+");
fseek(f,1,0);
cursector=fbrk=1;
while(1)
{
puts(ptr->name);
strcpy(in.name,ptr->name);
in.sector=cursector;
in.upsector=0;
in.next=0;
strcpy(in.properties,ptr->properties);
in.insector=0;
in.filesector=0;
in.size=ptr->size;
if(ptr->up!=0)
{
in.upsector=fbrk;
}
if(ptr->in!=0)
{
cursector=cursector+sizeof(ffolder);
in.insector=cursector;
temp=ptr->in;
while(temp!=0)
{
cursector=cursector+sizeof(ffolder);
temp=temp->next;
}
}
if(ptr->fin!=0)
{
in.filesector=cursector;
ftemp=ptr->fin;
fsector=cursector;
while(ftemp!=0)
{
cursector=cursector+sizeof(ffile);
}
}
if(ptr->next!=0)
{
in.next=cursector;
}
if(ptr->in!=0)
ptr=ptr->in;
else if(ptr->fin!=0)
fptr=ptr->fin;
else if(ptr->next!=0)
ptr=ptr->next;
else if(ptr->up==0)
{
fclose(f);
return 0;
}
else if(ptr->up->next!=0)
ptr=ptr->up->next;
else
{ fclose(f);
fptr=0;
return 0;
}
fwrite(&in,sizeof(in),1,f);
if(fptr!=0)
{
while(fptr!=0)
{
strcpy(fout.name,fptr->name);
fout.next=fsector;
strcpy(fout.properties,fptr->properties);
fout.size=fptr->size;
fsector=fsector+sizeof(ffile);
if(fptr->next!=0)
fout.next=fsector;
fptr=fptr->next;
fwrite(&fout,sizeof(fout),1,f);
}
}
}
fclose(f);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
int main(void)
{
unsigned long a = 0x11223344;
unsigned short b = 0x1234;
//以字节为单位
//主机序转网络序 32位
printf("htonl(%p): %p\n", a, htonl(a));
//主机序转网络序 16位
printf("htons(%p): %p\n", b, htons(b));
//网络序转主机序 32位
printf("ntohl(0x12345678): %p\n", ntohl(0x12345678));
//网络序转主机序 16位
printf("ntohs(0x1234): %p\n", ntohs(0x1234));
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include "tcb.h"
/**
* diese funktion printet uns mal die Pointer von dem verwendeten Stack
* reines Debugging
*/
int tcb_contextprint(){
long stackp = 0;
long basep = 0;
__asm__ __volatile__ ( "mov %%ebp, %%eax":"=a" (basep));
__asm__ __volatile__ ( "mov %%esp, %%eax":"=a" (stackp));
printf("SignalhandlerSpawn Stackpointer : %lu Basepointer: %lu\n",stackp,basep);
return 0;
}
/**
* Speichert den aktuellen Kontext in der übergebenen tcb-strukt
* wird der kontext geladen geht es hinter diesem Befehl weiter (wegen IP)
*/
int tcb_getcontext(tcb *t){
if (setjmp(t->env)){ // speichert die Umgebungsvar in den jmp_buf des zugewiesenen TCB
printf("Thread %d wird weiter in tcb %p bearbeitet\n",t->Thread_ID, t);
tcb_contextprint();
return 1; // wenn wir hier wieder kommen signalisieren wir das mit einer 1
}
// hier gehts dann weiter, wenn der TCB wieder geladen wird.
return 0; // Wenn wir etwas gespeichert haben zeigen wir das mit einer 0
}
/**
* setzt den aktuellen kontext aus der übergebenen Strucktur. Befehle nach diesem werden nicht ausgelöst, da
* der IP neu gesetzt wird
*/
int tcb_setcontext(tcb *t){
printf("ich springe nun nach : %p\n", t);
fflush(stdout);
longjmp(t->env,1); // ?? ob das klappt?
// nach dem Longjmp werden ja alle Pointer und Register geladen und es geht innerhalb des Threads weiter
// das return wird nicht erreicht, da nach dem Longjmp das
return 0;
}
/**
* Wechselt die TCB-kontexte. beim erneuten Laden taucht das Programm aus dieser methode auf (wie Yield quasi)
* Wenn das erste mal getkontext aufgerufen wird wird der state gespeichert und es wird der nächste gesetzt,
* wenn dann wieder zurückgekehrt wird wird das bemerkt und um eine Schleife zu verhindern wird dann kein Setkontext
* ausgeführt, der Caller sieht das so, als ob er diese FUnktion einfach ausführt.
*
*/
int tcb_swapcontext(tcb *ourTcb, tcb *newTcb){
printf("\t\t\t\tEnter Swapcontext with ourTcb:%i and newTcb:%i\n",ourTcb->Thread_ID, newTcb->Thread_ID);
if (!tcb_getcontext(ourTcb)){ //
tcb_setcontext(newTcb);
}
return 0;
}
/**
* erzeugt einen Neuen Kontext mit der übergebenen FUnktion. Wenn der Kontext aufgerufen wird wird die FUnktion ausgeführt.
void tcb_makecontext(tcb *t){
// malloc der stacksize zum erzeugen des Stacks
struct sigaction sa;
// Create the new stack
t->stack.ss_flags = 0;
t->stack.ss_size = STACKSIZE;
t->stack.ss_sp = malloc(STACKSIZE);
if ( t->stack.ss_sp == 0 ) {
perror( "Could not allocate stack." );
exit( 1 );
}
sigaltstack( &t->stack, 0 );
// Set up the custom signal handler
sa.sa_handler = &signalHandlerSpawn;
sa.sa_flags = SA_ONSTACK;
sigemptyset( &sa.sa_mask );
sigaction( SIGUSR1, &sa, 0 );
printf( "raise signal\n" );
raise( SIGUSR1 );
}
*/
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_added_algo.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kmbukuts <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/08/19 13:41:59 by kmbukuts #+# #+# */
/* Updated: 2019/09/16 11:27:31 by kmbukuts ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
void ft_sb(t_stack **b)
{
if (ft_how_big(*b) && stack_b_size("") > 1)
{
if (!ft_sorted_desc(*b))
return ;
ft_putendl("sb");
ft_swap_b(b);
}
}
void ft_normal_sa(t_stack **a, int *size)
{
if (ft_first_state(*a, *size))
{
ft_ra(a, size);
ft_rra(a, size);
ft_swap_a(a, *size);
ft_putendl("sa");
}
}
int ft_get_mid(int size)
{
if ((size % 2) == 0)
return (size / 2);
else
return ((size / 2) + 1);
}
void ft_get_biggest(t_stack **a)
{
t_stack *ptr;
int back;
int front;
int v;
ptr = *a;
front = 0;
back = 0;
if (stack_b_size("") == 0)
return ;
v = ft_find_biggest(ptr, ptr->v);
ptr = *a;
while (ptr->next && ptr->v != v)
{
front++;
ptr = ptr->next;
}
ptr = ptr->next;
while (ptr)
{
back++;
ptr = ptr->next;
}
ft_put_top(a, front, back);
}
void ft_put_top(t_stack **b, int front, int back)
{
if (front > back || back == 0)
{
while (back-- > -1)
{
if (!ft_sorted_desc(*b))
return ;
ft_reverse_b(b, stack_b_size(""));
ft_putendl("rrb");
}
}
else
{
while (front-- > 0)
{
if (!ft_sorted_desc(*b))
return ;
ft_shift_b(b, stack_b_size(""));
ft_putendl("rb");
}
}
}
|
C
|
#include "main.h"
/**
* end_func - terminates _printf() in the error cases
* @inv: the arguments inventory with most commonly used arguments
* Return: -1 always
*/
int end_func(inventory_t *inv)
{
int ret_value;
if (inv)
{
ret_value = inv->error ? -1 : inv->buf_index;
if (inv->i)
puts_mod(inv->buffer, inv->buf_index);
va_end(*(inv->args));
if (inv->buffer)
free(inv->buffer);
free(inv);
}
else
ret_value = -1;
return (ret_value);
}
|
C
|
#include "loadRanking.h"
/**
*Llegeix un fitxer ranking i posa a players[10][21], nivells[10], minuts[10] i segons[10]
*les dades guardades al fitxer.
*/
int readRankingInfo(char players[][21], int *nivells, int *minuts, int *segons) {
FILE *fp;
int i;
char line[200];
char *token;
fp = fopen("ranking.txt","r");
if (fp == NULL) return -1;
for (i = 0; i < 10; i++) {
fgets(line, 200, fp);
token = strtok(line,";");
strcpy(players[i],token);
token = strtok(NULL,";");
nivells[i] = atoi(token);
token = strtok(NULL,";");
minuts[i] = (token[0]-'0')*10+(token[1]-'0');
segons[i] = (token[3]-'0')*10+(token[4]-'0');
}
fclose(fp);
return 1;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_s_processor.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bhatches <bhatches@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/10 13:30:15 by bhatches #+# #+# */
/* Updated: 2021/01/16 16:06:08 by bhatches ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_processor.h"
int ft_s_prcssr_intrnl_flg_minus(t_spcfctr *spcfctr, char *arg, char flag_value)
{
int done;
int i;
done = 0;
i = spcfctr->wdth - spcfctr->prcsn;
while ((spcfctr->prcsn-- > 0 || ((spcfctr->flg & FLG_PRCSN) == FALSE))
&& (*arg != '\0'))
{
done += ft_putchar_fd(*arg, 1);
arg++;
if ((spcfctr->flg & FLG_PRCSN) == FALSE)
i--;
}
while (i-- > 0)
{
done += ft_putchar_fd(flag_value, 1);
}
return (done);
}
int ft_s_prcssr_intrnl_flg_zero(t_spcfctr *spcfctr, char *arg, char flag_value)
{
int done;
int i;
done = 0;
i = spcfctr->wdth - spcfctr->prcsn;
if ((spcfctr->flg & FLG_PRCSN) == FALSE)
i -= (int)ft_strlen(arg);
while (i-- > 0)
done += ft_putchar_fd(flag_value, 1);
while ((spcfctr->prcsn-- > 0 || ((spcfctr->flg & FLG_PRCSN) == FALSE))
&& (*arg != '\0'))
{
done += ft_putchar_fd(*arg, 1);
arg++;
}
return (done);
}
int ft_s_processor(t_spcfctr *spcfctr, va_list arg_ptr)
{
char *arg;
int done;
char flag_value;
arg = va_arg(arg_ptr, char*);
done = 0;
if (arg == NULL)
arg = "(null)";
flag_value = ft_cs_take_flag(spcfctr->flg);
if (spcfctr->prcsn >= (int)ft_strlen(arg) || spcfctr->prcsn < 0)
spcfctr->prcsn = (int)ft_strlen(arg);
if (spcfctr->flg & FLG_MINUS)
{
done += ft_s_prcssr_intrnl_flg_minus(spcfctr, arg, flag_value);
}
else
{
done += ft_s_prcssr_intrnl_flg_zero(spcfctr, arg, flag_value);
}
return (done);
}
|
C
|
#include "asm.h"
/*
* Address mode table.
* This table is indexed by the number
* that gets put in the r/m field,
* and holds a word containing a bit for
* each index register.
*/
int amodes[] = {
(1<<reg(BX)) + (1<<reg(SI)),
(1<<reg(BX)) + (1<<reg(DI)),
(1<<reg(BP)) + (1<<reg(SI)),
(1<<reg(BP)) + (1<<reg(DI)),
(1<<reg(SI)),
(1<<reg(DI)),
(1<<reg(BP)),
(1<<reg(BX))
};
char segovr[] = {
0x26,
0x2E,
0x36,
0x3E
};
/*
* Read an address.
* Return the addressing mode.
*/
addr(esp)
register struct expr *esp;
{
register c;
if ((c = getnb()) == '$') {
expr(esp, 0);
esp->e_mode = IM;
return (IM);
}
if (c == '(') {
addrx(esp);
esp->e_type = E_ACON;
esp->e_addr = 0;
return (esp->e_mode & MMASK);
}
unget(c);
expr(esp, 0);
if (esp->e_type == E_AREG) {
esp->e_mode = esp->e_addr;
if ((esp->e_mode & MMASK) == SEGR)
if ((c = getnb()) == ':') { /* segment override */
outab(segovr[reg(esp->e_addr)]);
addr(esp);
} else
unget(c);
return (esp->e_mode & MMASK);
}
if ((c = getnb()) == '(') {
addrx(esp);
if (esp->e_mode==IDX || esp->e_mode==ICL)
aerr("invalid index register");
return (esp->e_mode & MMASK);
}
unget(c);
esp->e_mode = DIR;
return (DIR);
}
/*
* Read in index register field
* of an address. The leading `(' has already
* been read. Set the mode into the `e_mode'
* field of the expression structure.
*/
addrx(esp)
struct expr *esp;
{
register struct sym *sp;
register c, i;
int mask, mode;
char id[NCPLN];
mode = 0;
do {
getid(id, -1);
if ((sp=lookup(id, 0))==NULL || sp->s_type!=E_AREG)
aerr("index by non-register");
else {
mask = 01 << reg(sp->s_addr);
if ((mode&mask) != 0)
aerr("invalid index register");
mode |= mask;
}
} while ((c = getnb()) == ',');
if (c != ')')
qerr("missing ')'");
if (mode == (01<<reg(CL))) {
esp->e_mode = ICL;
return;
}
if (mode == (01<<reg(DX))) {
esp->e_mode = IDX;
return;
}
for (i=0; i<8; ++i) {
if (mode == amodes[i]) {
esp->e_mode = X | i;
return;
}
}
aerr("invalid index");
esp->e_mode = D;
}
|
C
|
/* Steve Phillips
2009.07.15
"The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million."
The reasoning and the logic here is correct and precise, but I'm
running into memory issues. composite_array needs to be much
larger than size INPUT (INPUT^2?).
Run time: 8 secs for INPUT = 1000
Original answer checked whether each number (2 through 2M) was
prime; if so, added it to the sum, and went on to the next number.
I thought the following method would be more efficient. I was
wrong.
*/
#include <stdio.h>
#define TRUE 1
#define FALSE 0
#define INPUT 1000 // Should be 2000000
long user_input = INPUT;
long composite_array[INPUT*100];
long array_index = 0;
long sum = 0;
int in_array(long prod) {
int i;
for(i = 0; i < array_index; i++) {
if (composite_array[i] == prod) {
return 1;
}
}
return 0;
}
long create_composite_array(long num)
{
int i, j, product;
for(i = 2; i <= num/2; i++) {
for(j = num/2; j >= i; j--) {
product = i*j;
// printf("product: %d\n", product);
//if (product > num) {break;}
if (!in_array(product)) {
composite_array[array_index] = product;
++array_index;
}
}
}
return array_index; // so we know the used length of composite_array
}
// Returns 1 if num is prime ; Returns 0 otherwise
int is_prime(long num)
{
long i; // vvvvv array length vvvvv
// for(i = 0; i < (sizeof(composite_array)/sizeof(int))-1; i++) {
for(i = 0; i < array_index; i++) {
if (num == composite_array[i]) {
return 0;
}
}
return 1;
}
// Sum of all primes between 2 and num
long prime_lister(long num)
{
long i, j;
for(i = 2; i <= num; i++) {
if (is_prime(i)) {
sum += i;
// printf("prime: %d\n", i);
}
}
/* printf("Complete array:"); */
/* for(j = 0; j < array_index; j++) */
/* printf(" %d", composite_array[j]); */
printf("\nNumber of elements in composite_array: %d", array_index);
printf("\nSum of primes <= %d: %d\n", user_input, sum);
return sum;
}
int main(int argc, char **argv)
{
array_index = create_composite_array(user_input);
// printf("array_index = %d\n", array_index);
prime_lister(user_input); // prints sum of primes <= user_input
return 0;
}
|
C
|
/*
这段程序运行时,在刚开始阶段发现第一次从TEMPR task转到HMI task 的时候,有Char Array 乱码。之后的运行不再有这个问题。以后有debug工具后研究。
I (0) TEMPR: ventMachine name from HMI is QBDZ-001
I (10) TEMPR: In_Air_Temperature is 25.000000
W (200) HMI: ventMachine name from XXXX is �
��G�?|H�?
W (200) HMI: In_Air_Temperature is 20.100000
*/
typedef struct Vent_machine_Struct {
char Name[20];
bool Fan_Power_Control; //风扇开关控制
bool Fan_Power_Status; //风扇状态,用于程序逻辑判断
bool Heat_Exchanger_Status; //热交换器的状态,开机为热交换器水循环泵在工作。从外界获取状态前,计算空气流经前后温差初判
float In_Air_Temperature; //从室外吸进来的空气,经过管路加温后,到达软交换器之前的温度
float Out_Air_Temperature; //热交换后空气的温度
uint32_t Re_PowerOn_Delay; //开机延时,尤其是在低温保护后重启是需要延时,避免频繁关机和重启
} Vent_machine;
void temperatureMonitoring_control(void * params){
Vent_machine * myMachine = (Vent_machine *) params;
for(;;)
{
ESP_LOGI(TAG,"ventMachine name from HMI is %s\n",myMachine->Name );
strcpy(myMachine->Name, "wqjian");
//ESP_LOGI(TAG,"ventMachine name is %s\n",myMachine->Name );
ESP_LOGI(TAG, "In_Air_Temperature is %f\n", myMachine->In_Air_Temperature);
myMachine->In_Air_Temperature = 20.1 ;
vTaskDelay(pdMS_TO_TICKS(3000));
}
}
void HMI(void *params)
{
Vent_machine * myMachine = (Vent_machine *) params;
//从*params传递过来的是void *,新定义本task局部变量为pointer型,需要把 void * 型cast to 变量的type_define相同后,才能传递。
uint32_t pointADD = (int )myMachine; //新定义变量,用于检查前一步声明的指针的里面指明的地址。
ESP_LOGI("HMI"," myMachine adds is %x", pointADD);
while(true){
ESP_LOGW("HMI","ventMachine name from XXXX is %s\n",myMachine->Name );
strcpy(myMachine->Name, "QBDZ-001");
ESP_LOGW("HMI","In_Air_Temperature is %f\n", myMachine->In_Air_Temperature);
myMachine->In_Air_Temperature = 10.5 ;
vTaskDelay(pdMS_TO_TICKS(3000));
}
}
void app_main(void)
{
int *ptr ; // 声明一个指针
int myNumber =3; //声明一个变量
ptr = &myNumber; //把变量的地址取出,赋值给指针变量,作为指针的地址
ESP_LOGI(TAG,"*ptr = %d \n",*ptr); // log 指针变量的值
ESP_LOGI(TAG,"Adds of *ptr is %x \n", (int)ptr); //LOG 指针变量的地址,需要 cast to “int”,才符合 “%x” 的形式要求。
Vent_machine ventMachine; //声明struct
uint32_t ventMachineAdds = (int) &ventMachine; //新声明变量,取struct的地址,并cast to “int” 后,赋值给变量
ESP_LOGI("Main","ventMachineAdd is %x. \n",ventMachineAdds); //log 变量
Vent_machine ventMachine;
strcpy(ventMachine.Name, "QBDZ-001");
ventMachine.Fan_Power_Control = 1;
ventMachine.In_Air_Temperature =25;
xTaskCreate(&temperatureMonitoring_control,"Temp_Meas",2048, &ventMachine,1,NULL);
vTaskDelay(pdMS_TO_TICKS(200));
xTaskCreate(&HMI,"HMI", 2048, &ventMachine, 1 , NULL );
}
|
C
|
/*
* rt_lists.c
*
* Created on: 2 oct 2016
* Author: osannolik
*/
#include "rt_lists.h"
static volatile list_sorted_t delayed[RT_PRIO_LEVELS];
volatile list_sorted_t ready[RT_PRIO_LEVELS];
static void update_next_wakeup(void);
static list_item_t *list_sorted_next_item(list_item_t *item);
static list_item_t *list_sorted_get_iter_item(list_sorted_t *list);
static void update_next_wakeup(void)
{
uint32_t prio, wake_up_tick, minimum_wake_up_tick = RT_FOREVER_TICK;
list_sorted_t *delayed_list;
rt_task_t wake_up_task = NULL;
for (prio=0; prio<RT_PRIO_LEVELS; prio++) {
delayed_list = (list_sorted_t *) &(delayed[prio]);
if (LIST_LENGTH(delayed_list)>0) {
wake_up_tick = LIST_MIN_VALUE(delayed_list);
if (wake_up_tick <= minimum_wake_up_tick) {
minimum_wake_up_tick = wake_up_tick;
wake_up_task = (rt_task_t) LIST_MIN_VALUE_REF(delayed_list);
}
}
}
if (wake_up_task != NULL) {
next_wakeup_task = wake_up_task;
next_wakeup_tick = minimum_wake_up_tick;
} else {
next_wakeup_tick = RT_FOREVER_TICK;
}
}
static list_item_t *list_sorted_next_item(list_item_t *item)
{
list_item_t *next_item = item->next;
// Will get the next item but exclude the end item
if (next_item == &(((list_sorted_t *) item->list)->end))
return next_item->next;
else
return next_item;
}
static list_item_t *list_sorted_get_iter_item(list_sorted_t *list)
{
list_item_t *iter_item = NULL;
if (list->len > 0) {
iter_item = list->iterator;
list->iterator = list_sorted_next_item(iter_item);
}
return iter_item;
}
void list_sorted_init(list_sorted_t *list)
{
list->len = 0;
list->end.value = LIST_END_VALUE;
list->end.list = list;
list->end.prev = &(list->end);
list->end.next = &(list->end);
list->end.reference = NULL;
list->iterator = NULL;
}
void rt_lists_ready_init(void)
{
uint8_t prio;
for (prio=0; prio<RT_PRIO_LEVELS; prio++)
list_sorted_init((list_sorted_t *) &(ready[prio]));
}
void rt_lists_delayed_init(void)
{
uint8_t prio;
for (prio=0; prio<RT_PRIO_LEVELS; prio++)
list_sorted_init((list_sorted_t *) &(delayed[prio]));
}
void rt_list_task_ready(rt_task_t const task)
{
uint32_t task_prio = task->priority;
task->list_item.value = task_prio;
list_sorted_insert((list_sorted_t *) &(ready[task_prio]), &(task->list_item));
}
void rt_list_task_ready_next(rt_task_t const task)
{
uint32_t task_prio = task->priority;
list_item_t *list_item = &(task->list_item);
list_item->value = task_prio;
list_sorted_iter_insert((list_sorted_t *) &(ready[task_prio]), list_item);
}
void rt_list_task_delayed(rt_task_t const task, const uint32_t wake_up_tick)
{
list_sorted_t *delayed_list = (list_sorted_t *) &(delayed[task->priority]);
list_item_t *list_item = &(task->list_item);
if (wake_up_tick > rt_get_tick()) {
// Remove from ready list and add to delayed list
list_sorted_remove(list_item);
list_item->value = wake_up_tick;
list_sorted_insert(delayed_list, list_item);
update_next_wakeup();
// Trig a task switch
rt_pend_yield();
}
}
void rt_list_task_undelayed(rt_task_t const task)
{
// NOTE: Does not set task as Ready!
list_sorted_remove(&(task->list_item));
update_next_wakeup();
}
void *list_sorted_get_iter_ref(list_sorted_t *list)
{
list_item_t *next_item = list_sorted_get_iter_item(list);
if (next_item == NULL)
return NULL;
else
return (void *) next_item->reference;
}
uint32_t list_sorted_insert(list_sorted_t *list, list_item_t *item)
{
list_item_t *insert_at = &(list->end);
uint32_t input_value = item->value;
item->list = list;
if (input_value == LIST_END_VALUE) {
insert_at = list->end.prev;
} else {
// Find last maximum value and insert after that
while (insert_at->next->value <= input_value)
insert_at = insert_at->next;
}
insert_at->next->prev = item;
item->next = insert_at->next;
item->prev = insert_at;
insert_at->next = item;
if (list->len == 0)
list->iterator = item;
return ++(list->len);
}
uint32_t list_sorted_iter_insert(list_sorted_t *list, list_item_t *item)
{
// Insert the item to where the iterator points
// NOTE: It is the caller's responsibility to ensure that the position is correct (i.e. sorted)
list_item_t *insert_at = list->iterator;
if (list->len == 0) {
return list_sorted_insert(list, item);
} else {
item->list = list;
insert_at->next->prev = item;
item->next = insert_at->next;
item->prev = insert_at;
insert_at->next = item;
list->iterator = item;
return ++(list->len);
}
}
uint32_t list_sorted_remove(list_item_t *item)
{
list_sorted_t *from_list = item->list;
if (from_list != NULL) {
if (from_list->len == 1) {
// Removing the last item
from_list->iterator = NULL;
} else {
from_list->iterator = list_sorted_next_item(item);
}
item->next->prev = item->prev;
item->prev->next = item->next;
(from_list->len)--;
item->list = NULL;
}
return from_list->len;
}
|
C
|
#include <stdio.h>
int main(void)
{
char thing = 45;
printf("%c",thing);
return 0;
}
|
C
|
/*******************************************************************************
* File Name: Swd_PhysicalLayer.h
* Version 3.0
*
* Description:
* This header file contains the macro definitions, function declarations for the
* physical layer of the SWD protocol. These include -
* a.) Setting a output pin high or low
* b.) Reading the logic level of an input pin
* c.) Configuring the drive mode of the programming pin
*
* The pin manipulation routines are defined both as macros and functions.
* The macros are used in AcquireTargetDevice() function in DeviceAcquire.c
* as the function has strict timing requirements for execution.
* Using the macros instead of fuctions reduces execution overhead.
*
* The pin manipulation functions are used instead of macros in all other
* places to save code space.
*
* Note:
* The macros, functions defined here are specific to PSoC 5LP Host Programmer.
* Modify them as applicable for your Host Programmer.
*******************************************************************************/
#ifndef __SWD_PHYSICALLAYER_H
#define __SWD_PHYSICALLAYER_H
/* Host programmer registers, mask values are defined in "RegisterDefines.h" */
#include "RegisterDefines.h"
/***************************** USER ATTENTION REQUIRED **************************
***************************** HOST PROCESSOR SPECIFIC ***************************
**************** Macros for Host Pin Drive mode configuration *******************
*
* Uses the register definitions, mask values in "RegisterDefines.h" to
* configure the pin drive mode
*
* SWDIO pin on host side - CMOS output (host writes data to target PSoC 5LP),
* High Z digital input (host reads data from target
* PSoC 5LP or when host is not programming target
* PSoC 5LP (idle))
*
* SWDCK pin on host side - CMOS output (when host is programming target PSoC 5LP),
* High Z digital input (when host is not programming target PSoC 5LP (idle))
*
* XRES pin on host side - CMOS output (when host is programming target PSoC 5LP)
* High Z digital input (when host is not programming target PSoC 5LP (idle))
*
* Modify these as applicable to your Host Programmer
********************************************************************************/
#define SWDIO_DRIVEMODE_HIGHZIN pinMode (5, INPUT)
#define SWDIO_DRIVEMODE_CMOSOUT pinMode (5, OUTPUT)
#define SWDCK_DRIVEMODE_HIGHZIN pinMode (4, INPUT)
#define SWDCK_DRIVEMODE_CMOSOUT pinMode (4, OUTPUT)
#define XRES_DRIVEMODE_HIGHZIN pinMode (3, INPUT)
#define XRES_DRIVEMODE_CMOSOUT pinMode (3, OUTPUT)
/***************************** USER ATTENTION REQUIRED **************************
***************************** HOST PROCESSOR SPECIFIC ***************************
**************** Macros for driving output pins on host side ********************
*
* Uses the register definitions, mask values in "RegisterDefines.h" to drive
* output pins either to logic high (suffixed by 'HIGH') or
* logic low (suffixed by 'LOW')
*
* Modify these as applicable to your Host Programmer
********************************************************************************/
#define SWDIO_OUTPUT_HIGH digitalWrite (5, 1)
#define SWDIO_OUTPUT_LOW digitalWrite (5, 0)
#define SWDCK_OUTPUT_HIGH digitalWrite (4, 1)
#define SWDCK_OUTPUT_LOW digitalWrite (4, 0)
#define XRES_OUTPUT_HIGH digitalWrite (3, 1)
#define XRES_OUTPUT_LOW digitalWrite (3, 0)
/***************************** USER ATTENTION REQUIRED **************************
***************************** HOST PROCESSOR SPECIFIC ***************************
**************** Macro for reading input pin on host side ***********************
*
* Uses the register definitions, mask values in "RegisterDefines.h" to read
* the SWDIO pin in input mode
*
* This macro returns '0x01' if the SWDIO input pin is at logic high,
* or '0x00' if the SWDIO input pin is at logic low
*
* Modify this as applicable to your Host Programmer
********************************************************************************/
#define SWDIO_INPUT_READ digitalRead (5)
/********************************************************************************
* Function Prototypes
********************************************************************************/
/* The below fuctions are for pin manipulation, and their definitions in
* Swd_PhysicalLayer.c are the same as the corresponding macro defitnions above. */
void SetSwdckHigh(void);
void SetSwdckLow(void);
void SetSwdckCmosOutput(void);
void SetSwdckHizInput(void);
void SetSwdioHigh(void);
void SetSwdioLow(void);
void SetSwdioCmosOutput(void);
unsigned char ReadSwdio(void);
void SetSwdioHizInput(void);
void SetXresHigh(void);
void SetXresLow(void);
void SetXresCmosOutput(void);
void SetXresHizInput(void);
#endif /* __SWD_PHYSICALLAYER_H */
//[] END OF FILE
|
C
|
#include "arrayFlightCode.h"
int initFlights(FlightCode* list, int len){
int i;
int errorCode=-1;
if(list != NULL && len > 0)
{
for(i=0; i<len; i++)
{
list[i].isEmpty = EMPTY;
errorCode=0;
}
}
return errorCode;
}
void addFlightHardcode(FlightCode list[], int len)
{
int id[4]={1133,1218,1301,1353};
char flightCode[4][8]={"ARG1133","ARG1218","ARG1301","ARG1353"};
int isEmpty[4]={TAKEN,TAKEN,TAKEN,TAKEN};
for(int i=0; i<4; i++)
{
list[i].idFlyCode=id[i];
strcpy(list[i].flyCode,flightCode[i]);
list[i].isEmpty=isEmpty[i];
}
}
int addFlight(FlightCode list[], int len)
{
int errorCode=-1;
char countryCode[8];
char numberCodeAux[5];
int numberCode;
int itsOkay=0;
int index;
puts("Vuelos actuales:");
printFlightCodes(list, len);
puts("Aadir nuevo vuelo:");
getStringChar(countryCode,"Ingrese codigo de entre uno y tres letras descriptivas del pais(Ejemplo:ARG->Argentina)\nEl codigo restante se generara automaticamente:\n",
"Error ha excedido el limite\n",3,5,2);
do
{
srand(time(NULL));
numberCode=rand() % 901 + 1000;
itsOkay=verifyCodeFlight(list, numberCode, len);
}while(itsOkay==-1);
itoa(numberCode, numberCodeAux, 10);
index=searchFreePositionFlight(list, len);
if(list != NULL && len > 0 && index!=ERROR)
{
list[index].idFlyCode=numberCode;
strcpy(list[index].flyCode,strcat(countryCode, numberCodeAux));
list[index].isEmpty=TAKEN;
errorCode=0;
}
puts("Se ha aadido el siguiente vuelo:");
puts("_________________________");
puts("| ID: | Vuelo: |");
puts("|_______|________________|");
printFlightCode(list[index]);
return errorCode;
}
void removeFlight(FlightCode list[], int len)
{
int id;
int itsOkay=-1;
int option;
puts("Vuelos actuales:");
printFlightCodes(list, len);
getIntNumber(&id,"Ingrese el ID del vuelo que desea eliminar:\n","Error numero fuera de rango\n",1000,2000,5);
itsOkay=verifyCodeFlight(list, id, len);
if(itsOkay==-1)
{
puts("Esta seguro que desea eliminar el siguiente vuelo?");
puts("Recuerde que dejaran de mostrarse los pasajeros pertenecientes al vuelo eliminado");
for(int i=0;i<len;i++)
{
if(list[i].idFlyCode==id)
{
puts("_________________________");
puts("| ID: | Vuelo: |");
puts("|_______|________________|");
printFlightCode(list[i]);
getIntNumber(&option,"Ingrese:\n1- Eliminar vuelo\n2- Cancelar operacion\n","Error numero fuera de rango\n",1,2,5);
if(option==1)
{
list[i].isEmpty=EMPTY;
puts("Vuelo eliminado exitosamente");
break;
}
else
{
puts("Se ha cancelado la operacion con Exito");
break;
}
}
}
}
else
{
puts("El id ingresado no existe");
}
}
int verifyCodeFlight(FlightCode list[], int code, int len)
{
int errorCode=0;
for(int i=0; i<len; i++)
{
if(list[i].idFlyCode==code)
{
errorCode=-1;
break;
}
}
return errorCode;
}
int searchFreePositionFlight(FlightCode list[], int len)
{
int i;
int index=-1;
if(list != NULL && len > 0)
{
for(i=0; i<len; i++)
{
if(list[i].isEmpty==EMPTY)
{
index=i;
break;
}
}
}
return index;
}
void printFlightCode(FlightCode list)
{
printf("|%5d |%10s |\n",list.idFlyCode, list.flyCode);
puts("|_______|________________|");
}
void printFlightCodes(FlightCode list[], int len)
{
int i;
if(list!=NULL && len>0)
{
puts("_________________________");
puts("| ID: | Vuelo: |");
puts("|_______|________________|");
for(i=0; i<len; i++)
{
if(list[i].isEmpty==TAKEN)
{
printFlightCode(list[i]);
}
}
}
}
|
C
|
#include<stdio.h>
int main()
{
int a,b;
a=6,b=a-2;
if(a>b)
printf("%d is greater than %d.\n",a,b);
return(0);
}
|
C
|
/*
** pen.c for pen in /home/bougon_p/rendu/gfx_tekpaint
**
** Made by bougon_p
** Login <bougon_p@epitech.net>
**
** Started on Fri Jan 8 02:24:14 2016 bougon_p
** Last update Wed Jan 27 03:18:30 2016 THEIS Paul
*/
#include "paint.h"
void fill_line(t_data *data, int cond)
{
t_bunny_position *pos;
if ((pos = bunny_malloc(sizeof(t_bunny_position) * 2)) == NULL)
return ;
if (cond == 1)
draw_lines_right(data, pos);
else if (cond == 2)
draw_lines_left(data, pos);
bunny_free(pos);
}
void choose_direction(t_data *data, int next_bool)
{
if ((data->pen.previous_pos.y > data->pen.next_pos.y
&& data->pen.previous_pos.x < data->pen.next_pos.x)
|| (data->pen.previous_pos.y < data->pen.next_pos.y
&& data->pen.previous_pos.x > data->pen.next_pos.x))
fill_line(data, 1);
else
fill_line(data, 2);
data->pen.previous_pos = data->pen.next_pos;
data->pen.sec_pt = next_bool;
}
void check_pass(t_data *data)
{
if (data->pen.sec_pt == -1)
{
data->pen.previous_pos = data->pen.next_pos;
data->pen.sec_pt = 1;
}
else if (data->pen.sec_pt == 0 && data->pen.sec_pt != -1)
choose_direction(data, 1);
else if (data->pen.sec_pt == 1)
choose_direction(data, 0);
}
void draw_pen(void *_data)
{
t_data *data;
const t_bunny_position *mouse_pos;
t_posrec rec;
data = _data;
rec.color.full = data->tools.color.full;
mouse_pos = bunny_get_mouse_position();
data->pen.next_pos = *mouse_pos;
data->pen.next_pos.x -= data->crs.calc->pos.x;
data->pen.next_pos.y -= data->crs.calc->pos.y;
rec.x = mouse_pos->x - data->crs.calc->pos.x - data->tools.size / 2;
rec.y = mouse_pos->y - data->crs.calc->pos.y - data->tools.size / 2;
my_setsquare(data->crs.calc->pix, rec, data->tools.size, data->tools.size);
check_pass(data);
}
void the_erase(void *_data)
{
t_data *data;
const t_bunny_position *mouse_pos;
t_posrec rec;
t_color col;
data = _data;
col = data->tools.color;
data->tools.color.full = 0x00000000;
rec.color.full = data->tools.color.full;
mouse_pos = bunny_get_mouse_position();
data->pen.next_pos = *mouse_pos;
data->pen.next_pos.x -= data->crs.calc->pos.x;
data->pen.next_pos.y -= data->crs.calc->pos.y;
rec.x = mouse_pos->x - data->crs.calc->pos.x - data->tools.size / 2;
rec.y = mouse_pos->y - data->crs.calc->pos.y - data->tools.size / 2;
my_setsquare(data->crs.calc->pix, rec, data->tools.size, data->tools.size);
check_pass(data);
data->tools.color = col;
}
|
C
|
#ifndef ENCRYPT_H
#define ENCRYPT_H
#include <stdint.h>
#include "aes.h"
#include <string.h>
/** AES */
void Encrypt(unsigned char * arg, unsigned int cont){
//define qual tamanho de chave a ser usado baseado no DEFINE escolhido na aes.h
#ifdef AES128
printf("AES 128 em uso...\n");
uint8_t key[64] = { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c };
#elif defined(AES192)
printf("AES 192 em uso...\n");
uint8_t key[64] = { 0x8e, 0x73, 0xb0, 0xf7, 0xda, 0x0e, 0x64, 0x52, 0xc8, 0x10, 0xf3, 0x2b, 0x80, 0x90, 0x79, 0xe5,
0x62, 0xf8, 0xea, 0xd2, 0x52, 0x2c, 0x6b, 0x7b };
#elif defined(AES256)
printf("AES 256 em uso...\n");
uint8_t key[64] = { 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81,
0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4 };
#endif // AES128
//Inicializa o processo de encrypt
struct AES_ctx ctx;
AES_init_ctx(&ctx, key);
//Encripta o texto
AES_ECB_encrypt(&ctx, arg, cont);
}
//Processo inverso da funo Encrypt
void Decrypt(unsigned char * arg, unsigned int cont){
#ifdef AES128
uint8_t key[64] = { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c };
#elif defined(AES192)
uint8_t key[64] = { 0x8e, 0x73, 0xb0, 0xf7, 0xda, 0x0e, 0x64, 0x52, 0xc8, 0x10, 0xf3, 0x2b, 0x80, 0x90, 0x79, 0xe5};
#elif defined(AES256)
uint8_t key[64] = { 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81,
0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4 };
#endif // AES128
struct AES_ctx ctx;
AES_init_ctx(&ctx, key);
//nica mudana com relao ao encrypt esta
AES_ECB_decrypt(&ctx, arg, cont);
}
#endif // ENCRYPT_H
|
C
|
/* xblock.c - xbinsert, xbdelete */
#include <conf.h>
#include <kernel.h>
#include <dos.h>
#include <proc.h>
#include <mem.h>
/*------------------------------------------------------------------------
* xbinsert -- insert an XBLOCK into the current process memory list
*------------------------------------------------------------------------
*/
xbinsert(xmp, nbytes, pid)
XBLOCK *xmp;
int nbytes;
int pid;
{
struct pentry *pptr;
int xm, xb, xf;
XBLOCK *xbp, *xfp;
xm = (unsigned int)xmp;
pptr = &proctab[pid];
xb = (int)pptr->pmlist;
if (xb == 0)
panic("xbinsert: missing stack block");
xbp = (XBLOCK *)memp(xb);
xf = (int)xbp->xbfore;
if (xf == 0)
panic("xbinsert: invalid memory list");
xfp = (XBLOCK *)memp(xf);
xmp->xbback = (struct xblock*)xb;
xmp->xbfore = (struct xblock*)xf;
xmp->xblen = nbytes;
xbp->xbfore = (struct xblock*)xm;
xfp->xbback = (struct xblock*)xm;
pptr->pmalloc += nbytes;
}
/*------------------------------------------------------------------------
* xbdelete -- delete an XBLOCK from the current process memory list
*------------------------------------------------------------------------
*/
word
xbdelete(xmp, pid)
XBLOCK *xmp;
int pid;
{
struct pentry *pptr;
int xf, xm, xb, sb;
XBLOCK *xfp, *xbp;
int nbytes;
xm = seg(xmp);
pptr = &proctab[pid];
sb = (int)pptr->pmlist;
if (sb == 0)
panic("xbdelete: missing stack block");
if (sb == xm)
panic("xbdelete: cannot delete stack block");
nbytes = xmp->xblen;
pptr->pmalloc -= nbytes;
xb = (int)xmp->xbback;
if ( xb == 0 )
panic("xbdelete: empty back pointer");
xbp = (XBLOCK *)memp(xb);
if ( (int)xbp->xbfore != xm )
panic("xbdelete: inconsistent back pointer");
xf = (int)xmp->xbfore;
if (xf == 0)
panic("xbdelete: empty fore pointer");
xfp = (XBLOCK *)memp(xf);
if ((int)xfp->xbback != xm)
panic("xbdelete: inconsistent fore pointer");
xfp->xbback = (struct xblock*)xb;
xbp->xbfore = (struct xblock*)xf;
return(nbytes);
}
|
C
|
// C program for implementation of selection sort
#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[], int n)
{
int i, j, min_index;
for(i = 0; i < n - 1; i++){
min_index = i;
for(j = i + 1; j < n; j++){
if(arr[j] < arr[min_index]){
min_index = j;
}
}
swap(&arr[min_index], &arr[i]);
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Driver program to test above functions
int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
printf("Unsorted array: \n");
printArray(arr, n);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
|
C
|
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <libnetconf.h>
#ifdef __GNUC__
# define UNUSED(x) UNUSED_ ## x __attribute__((__unused__))
#else
# define UNUSED(x) UNUSED_ ## x
#endif
#define CAPABILITY_PREFIX "urn:ietf:params:netconf:"
#define ARGUMENTS "f:hl:p:c:vd"
void clb_print(NC_VERB_LEVEL level, const char* msg)
{
switch (level) {
case NC_VERB_ERROR:
fprintf(stderr, "libnetconf ERROR: %s\n", msg);
break;
case NC_VERB_WARNING:
fprintf(stderr, "libnetconf WARNING: %s\n", msg);
break;
case NC_VERB_VERBOSE:
fprintf(stderr, "libnetconf VERBOSE: %s\n", msg);
break;
case NC_VERB_DEBUG:
fprintf(stderr, "libnetconf DEBUG: %s\n", msg);
break;
}
}
void clb_error_print(const char* tag,
const char* type,
const char* severity,
const char* UNUSED(apptag),
const char* UNUSED(path),
const char* message,
const char* UNUSED(attribute),
const char* UNUSED(element),
const char* UNUSED(ns),
const char* UNUSED(sid))
{
fprintf(stderr, "NETCONF %s: %s (%s) - %s\n", severity, tag, type, message);
}
void usage(char* progname)
{
printf("Get NETCONF configuration and state data from the NETCONF server.\n\n");
printf("Usage: %s [-h] [-f \"<filter>\"] [-p <port>] [-l <user>] [-c] [hostname]\n", progname);
printf("-f \"<filter>\" Apply NETCONF subtree filter. Remember to correctly escape the argument.\n");
printf("-h Show this help\n");
printf("-p <port> Connect to a specific port, 830 is default port\n");
printf("-l <user> Connect as a specific user, current user is used by default\n");
printf("-v Verbose mode\n");
printf("-c get-config mode\n\n");
printf("Hostname is a domain name or IP address of the NETCONF server, \'localhost\' is a default value.\n\n");
}
int main(int argc, char* argv[])
{
int ret = EXIT_SUCCESS;
NC_VERB_LEVEL verbose = NC_VERB_WARNING;
struct nc_session *session;
struct nc_filter *filter = NULL;
char* host = "localhost";
unsigned short port = 830;
char* user = NULL;
char* data = NULL;
nc_rpc *rpc = NULL;
nc_reply *reply = NULL;
NC_REPLY_TYPE reply_type;
int c;
int f_flag_set = 0;
int get_config_flag=0;
char *filter_string;
while ((c = getopt(argc, argv, ARGUMENTS)) != -1) {
switch (c) {
case 'f':
f_flag_set = 1;
optind = optind+1;
printf("Enter filter subtree\n");
scanf("%ms \n",&filter_string);
filter = nc_filter_new(NC_FILTER_SUBTREE,filter_string);
break;
case 'h': /* Show help */
usage(argv[0]);
return EXIT_SUCCESS;
case 'p': /* port */
port = (unsigned short) atoi (optarg);
break;
case 'l': /* login */
user = optarg;
break;
case 'v': /* Verbose operation */
verbose = NC_VERB_VERBOSE;
break;
case 'd':
verbose = NC_VERB_DEBUG;
break;
case 'c':
get_config_flag=1;
break;
default:
fprintf(stderr, "unknown argument -%c", optopt);
break;
}
}
if (argc == optind) {
/* no host specified */
} else if (((argc - optind) == 1)) {
host = argv[optind];
}
else {
fprintf(stderr, "stray arguments\n");
return (EXIT_FAILURE);
}
/* set verbosity and function to print libnetconf's messages */
nc_verbosity(verbose);
nc_callback_print(clb_print);
nc_callback_error_reply(clb_error_print);
/* create NETCONF session */
fprintf(stdout, "Connecting to port %d at %s as %s%s.\n",
port,
host,
user ? "user " : "",
user ? user : "current user");
session = nc_session_connect(host, port, user, NULL);
if (session == NULL) {
fprintf(stderr, "Connecting to the NETCONF server failed.\n");
return (EXIT_FAILURE);
}
/* prepare <get> message */
if(get_config_flag == 0){
fprintf(stdout,"Preparing <get> message");
rpc = nc_rpc_get(filter);
}
else
{
fprintf(stdout,"Preparing <get-config> message");
rpc = nc_rpc_getconfig(NC_DATASTORE_RUNNING,filter);
}
if (rpc == NULL ) {
fprintf(stderr, "Creating <get> RPC message failed.\n");
ret = EXIT_FAILURE;
goto cleanup;
}
/* send <rpc> and receive <rpc-reply> */
switch (nc_session_send_recv(session, rpc, &reply)) {
case NC_MSG_UNKNOWN:
fprintf(stderr, "Sending/Receiving NETCONF message failed.\n");
ret = EXIT_FAILURE;
goto cleanup;
case NC_MSG_NONE:
/* error occurred, but processed by callback */
goto cleanup;
case NC_MSG_REPLY:
if ((reply_type = nc_reply_get_type(reply)) == NC_REPLY_DATA) {
fprintf(stdout, "%s\n", data = nc_reply_get_data(reply));
free(data);
} else {
fprintf(stderr, "Unexpected type of message received (%d).\n", reply_type);
ret = EXIT_FAILURE;
goto cleanup;
}
break;
default:
fprintf(stderr, "Unknown error occurred.\n");
ret = EXIT_FAILURE;
goto cleanup;
}
cleanup:
/* free messages */
nc_rpc_free(rpc);
nc_reply_free(reply);
/* free created filter */
nc_filter_free(filter);
/* close NETCONF session */
nc_session_free(session);
return (ret);
}
|
C
|
#include "hb_array.h"
#include "hb_memory/hb_memory.h"
#include <string.h>
//////////////////////////////////////////////////////////////////////////
typedef struct hb_array_t
{
void * data;
hb_size_t size;
} hb_array_t;
//////////////////////////////////////////////////////////////////////////
hb_result_t hb_array_create( const void * _data, hb_size_t _size, hb_array_t ** _array )
{
hb_array_t * array = HB_NEW( hb_array_t );
array->data = HB_ALLOC( _size );
array->size = _size;
memcpy( array->data, _data, _size );
*_array = array;
return HB_SUCCESSFUL;
}
//////////////////////////////////////////////////////////////////////////
void hb_array_destroy( hb_array_t * _array )
{
HB_FREE( _array->data );
HB_DELETE( _array );
}
//////////////////////////////////////////////////////////////////////////
const void * hb_array_data( hb_array_t * _array, hb_size_t * _size )
{
*_size = _array->size;
return _array->data;
}
//////////////////////////////////////////////////////////////////////////
|
C
|
#include <stdio.h>
void main(){
int x,pos,p,t=0,r=0;
scanf ("%d",&pos);
for(x=1;x<=pos;x++){
scanf("%d",&p);
if(p<50){
t++;
}
else if(p>50 && p<85){
r++;
}}
printf("%d %d",t,r);
}
|
C
|
//
// Created by fred on 2020-03-06.
//
#include "string.h"
#include "stdlib.h"
#include <stdio.h>
char * addBinary(char * a, char * b){
unsigned int length1 = strlen(a);
unsigned int length2 = strlen(b);
char res_arr[length1 + length2 + 1];
for (int i = 0; i < length1; i++) {
res_arr[i] = a[i] - '0';
}
for (int j = 0; j < length2; j++) {
res_arr[length1 + j] = a[j] - '0';
}
char* copy = malloc((length1 + length2 + 2)*sizeof(char));
strcpy(copy, res_arr);
copy[length1 + length2 + 1] = '\0';
return copy;
}
int main(int argc, char ** argv) {
char * temp = addBinary("12", "43");
printf("Greeting message: %s\n", temp);
//
// char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
// printf("Greeting message: %s\n", greeting );
// printf("%lu", strlen(greeting));
}
|
C
|
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void multiply(float a[3][3],float b[3][3],float c[3][3]){
int i,j,k;
float sum=0;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++){
sum=sum+a[i][k]*b[k][j] ;
}
c[i][j]=sum;
sum=0;
}
}
return;
}
void main(){
int gdriver=DETECT,gmode,errorcode;
float a[3][3],b[3][3],c[3][3],d[3][3],e[3][3],f[3][3],g[3][3],x,y;
int i,j;
clrscr();
initgraph(&gdriver,&gmode,"C:\\TURBOC3\\BGI\\");
errorcode=graphresult();
if(errorcode!=grOk)
{
printf("Graph Error:%d",grapherrormsg(errorcode));
printf("\nPress any key to hault!");
getch();
exit(1);
}
printf("\nEnter coordinate 1:") ;
scanf("%f%f",&a[0][0],&a[0][1]);
a[0][2]=1;
printf("\nEnter coordinate 2:") ;
scanf("%f%f",&a[1][0],&a[1][1]);
a[1][2]=1;
printf("\nEnter coordinate 3:") ;
scanf("%f%f",&a[2][0],&a[2][1]);
a[2][2]=1;
printf("Enter angle:");
scanf("%f",&y);
line(a[0][0],a[0][1],a[1][0],a[1][1]);
line(a[1][0],a[1][1],a[2][0],a[2][1]);
line(a[2][0],a[2][1],a[0][0],a[0][1]);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{ if(i==j)
{ b[i][j]=1;
d[i][j]=1;
}
else {
b[i][j]=0;
d[i][j]=0;
}
}
}
b[2][0]=-a[0][0];
b[2][1]=-a[0][1];
d[2][0]=a[0][0];
d[2][1]=a[0][1];
x=(3.14*y)/180;
c[0][0]=cos(x);
c[0][1]=sin(x);
c[0][2]=0;
c[1][0]=-sin(x);
c[1][1]=cos(x);
c[1][2]=0;
c[2][0]=0;
c[2][1]=0;
c[2][2]=1;
multiply(a,b,e);
multiply(e,c,f);
multiply(f,d,g);
for(i=0;i<3;i++)
{ for(j=0;j<3;j++)
printf("%f ",c[i][j]);
printf("\n");
}
line(g[0][0],g[0][1],g[1][0],g[1][1]);
line(g[1][0],g[1][1],g[2][0],g[2][1]);
line(g[2][0],g[2][1],g[0][0],g[0][1]);
getch();
closegraph();
}
|
C
|
/****************************************************************************
* The 'FASTQ_PAIR_ARRAY' structure group was used to store a array of
* paired FASTQ reads, including basic operation function as well.
*
* This file was written by Haibin Xu, December 2011.
****************************************************************************/
#include "fastq_pair_array.h"
FASTQ_PAIR_ARRAY *fastq_pair_array_create()
{
/* create a FASTQ pair array. If successful, return the point to it,
* otherwise, return NULL.
*/
FASTQ_PAIR_ARRAY *fq_pair_array;
if((fq_pair_array=(FASTQ_PAIR_ARRAY *)malloc(sizeof(FASTQ_PAIR_ARRAY)))==NULL)
return NULL;
if((fq_pair_array->array=
(FASTQ_PAIR_ARRAY_BLOCK *)malloc(sizeof(FASTQ_PAIR_ARRAY_BLOCK)))==NULL)
{
free(fq_pair_array);
return NULL;
}
fq_pair_array->last=fq_pair_array->array;
fq_pair_array->block_num=1;
fq_pair_array->fastq_pair_num=0;
fq_pair_array->array->previous=NULL;
fq_pair_array->array->next=NULL;
fq_pair_array->array->num=0;
fq_pair_array->index=NULL;
return fq_pair_array;
}
int fastq_pair_array_remove(FASTQ_PAIR_ARRAY *fq_pair_array)
{
/* free the FASTQ pair array. If successful, return 0, otherwise
* return 1.
*/
long i;
FASTQ_PAIR_ARRAY_BLOCK *fq_pair_array_block;
if(fq_pair_array==NULL)
return 1;
fq_pair_array_block=fq_pair_array->last;
for(;fq_pair_array_block!=NULL;)
{
for(i=0;i<fq_pair_array_block->num;i++)
fastq_pair_remove(fq_pair_array_block->block[i]);
fq_pair_array_block=fq_pair_array_block->previous;
}
if(fq_pair_array->index!=NULL)
free(fq_pair_array->index);
return 0;
}
int fastq_pair_array_append(FASTQ_PAIR *fq_pair, FASTQ_PAIR_ARRAY *fq_pair_array)
{
/* append a new FASTQ pair to the array. if successful, return 0, otherwise
* return 1.
*/
FASTQ_PAIR_ARRAY_BLOCK *block_temp;
if(fq_pair_array==NULL || fq_pair==NULL)
return 1;
if(fq_pair_array->last->num<FASTQ_PAIR_ARRAY_BLOCK_SIZE)
{
/* append to the last array_block */
fq_pair_array->last->block[fq_pair_array->last->num++]=fq_pair;
fq_pair_array->fastq_pair_num++;
}
else
{
/* add a new array_block, amd append to it */
if((block_temp=
(FASTQ_PAIR_ARRAY_BLOCK *)malloc(sizeof(FASTQ_PAIR_ARRAY_BLOCK)))==NULL)
return 0;
fq_pair_array->last->next=block_temp;
block_temp->previous=fq_pair_array->last;
fq_pair_array->last=block_temp;
fq_pair_array->block_num++;
block_temp->num=0;
block_temp->block[block_temp->num++]=fq_pair;
fq_pair_array->fastq_pair_num++;
}
return 0;
}
int fastq_pair_array_generate_index(FASTQ_PAIR_ARRAY *fq_pair_array)
{
/* generate the index for given FASTQ_PAIR, if successful, return 0, otherwise
* return 1.
*/
FASTQ_PAIR_ARRAY_BLOCK **temp_index;
FASTQ_PAIR_ARRAY_BLOCK *fq_array_block;
long i;
if(fq_pair_array==NULL)
return 1;
if(fq_pair_array->index!=NULL)
{
free(fq_pair_array->index);
fq_pair_array->index=NULL;
}
if((temp_index=(FASTQ_PAIR_ARRAY_BLOCK **)malloc(sizeof(FASTQ_PAIR_ARRAY_BLOCK *)*(fq_pair_array->block_num)))==NULL)
return 1;
fq_array_block=fq_pair_array->array;
for(i=0;i<fq_pair_array->block_num;i++)
{
temp_index[i]=fq_array_block;
fq_array_block=fq_array_block->next;
}
fq_pair_array->index=temp_index;
return 0;
}
FASTQ_PAIR **fastq_pair_array_get_pointer(FASTQ_PAIR_ARRAY *fq_pair_array, long position)
{
/* get double pointer to individual fastq_pair member at specific position
* in the array, if successful, return the double pointer, otherwise
* return NULL
*/
FASTQ_PAIR_ARRAY_BLOCK *fq_array_block;
long block_num, num;
long i;
if(fq_pair_array==NULL || position<=0 || position>fq_pair_array->fastq_pair_num)
return NULL;
block_num=position/FASTQ_PAIR_ARRAY_BLOCK_SIZE;
num=position%FASTQ_PAIR_ARRAY_BLOCK_SIZE;
if(num==0)
num=FASTQ_PAIR_ARRAY_BLOCK_SIZE;
else
block_num++;
if(fq_pair_array->index==NULL)
{
fq_array_block=fq_pair_array->array;
for(i=1;i<block_num;i++)
fq_array_block=fq_array_block->next;
return &fq_array_block->block[num-1];
}
else
return &fq_pair_array->index[block_num-1]->block[num-1];
return NULL;
}
int fastq_pair_array_merge(FASTQ_PAIR_ARRAY *fq_pair_array,
FASTQ_PAIR_ARRAY *temp_fq_pair_array,
long low, long middle, long high)
{
/* merge the two sorted part in array, low-middle and middle-high, into a
* single sorted order. If successful, return 0, otherwise return 1.
*/
long i, begin1, end1, begin2, end2;
FASTQ_PAIR **fq_pair_current1, **fq_pair_current2;
FASTQ_PAIR **temp_fq_pair_current;
if(fq_pair_array==NULL || temp_fq_pair_array==NULL ||
low > middle || middle > high ||
fq_pair_array->fastq_pair_num!=temp_fq_pair_array->fastq_pair_num)
return 1;
begin1=low;
end1=middle;
begin2=middle+1;
end2=high;
/* merge processing */
for(i = low; begin1 <= end1 && begin2 <= end2;i++)
{
fq_pair_current1=fastq_pair_array_get_pointer(fq_pair_array, begin1);
fq_pair_current2=fastq_pair_array_get_pointer(fq_pair_array, begin2);
temp_fq_pair_current=fastq_pair_array_get_pointer(temp_fq_pair_array, i);
if(fastq_pair_compare_tight(*fq_pair_current1, *fq_pair_current2)<=0)
{
*temp_fq_pair_current=*fq_pair_current1;
begin1++;
}
else
{
*temp_fq_pair_current=*fq_pair_current2;
begin2++;
}
}
/* moving the remaining data to temp_fq_pair_array */
if(begin1<=end1)
{
for(;begin1<=end1;)
{
temp_fq_pair_current=fastq_pair_array_get_pointer(temp_fq_pair_array, i++);
fq_pair_current1=fastq_pair_array_get_pointer(fq_pair_array, begin1++);
*temp_fq_pair_current=*fq_pair_current1;
}
}
if(begin2<=end2)
{
for(;begin2<=end2;)
{
temp_fq_pair_current=fastq_pair_array_get_pointer(temp_fq_pair_array, i++);
fq_pair_current2=fastq_pair_array_get_pointer(fq_pair_array, begin2++);
*temp_fq_pair_current=*fq_pair_current2;
}
}
/* moving the merged data to original position 'fq_pair_array' */
for(i=low;i<=high;i++)
{
fq_pair_current1=fastq_pair_array_get_pointer(fq_pair_array, i);
temp_fq_pair_current=fastq_pair_array_get_pointer(temp_fq_pair_array, i);
*fq_pair_current1=*temp_fq_pair_current;
}
return 0;
}
int fastq_pair_array_sort(FASTQ_PAIR_ARRAY *fq_pair_array, FASTQ_PAIR_ARRAY *temp_fq_pair_array,
long first, long last)
{
/* sort the FASTQ pair array. If successful, return 0, otherwise
* return 1
*/
long mid;
if(first<last)
{
mid=(first+last)/2;
fastq_pair_array_sort(fq_pair_array, temp_fq_pair_array, first, mid);
fastq_pair_array_sort(fq_pair_array, temp_fq_pair_array, mid+1, last);
fastq_pair_array_merge(fq_pair_array, temp_fq_pair_array, first, mid, last);
}
return 0;
}
int fastq_pair_array_printf(FASTQ_PAIR_ARRAY *fq_pair_array, FILE *fp_out1, FILE *fp_out2,
char *format, int serial_flag, int flag_uniq)
{
/* write the pair-end reads in the array in FASTA or FASTQ format into two
* output files(format='fa' or 'fq') or in FASTA format into a single output
* file(format="fa" and fp_out2==NULL) using the original description
* (serial_flag=0) or a new serial number(serial_flag=1). Output all sequences
* (flag_uniq==0), or unique ones(flag_uniq==1). If successful, return 0,
* otherwise return 1.
*/
long i, k;
FASTQ_PAIR **temp_fq_pair, **temp_fq_pair_old;
if(flag_uniq==0)
{
for(i=1;i<=fq_pair_array->fastq_pair_num;i++)
{
temp_fq_pair=fastq_pair_array_get_pointer(fq_pair_array, i);
if(serial_flag==0)
fastq_pair_printf(*temp_fq_pair, fp_out1, fp_out2, format, -1);
else
fastq_pair_printf(*temp_fq_pair, fp_out1, fp_out2, format, i);
}
}
else
{
temp_fq_pair_old=fastq_pair_array_get_pointer(fq_pair_array, 1);
/* the fastq_pair_array contain only one read-pair, output it */
if(fq_pair_array->fastq_pair_num==1)
{
if(serial_flag==0)
fastq_pair_printf(*temp_fq_pair_old, fp_out1, fp_out2,
format, -1);
else
fastq_pair_printf(*temp_fq_pair_old, fp_out1, fp_out2,
format, k++);
}
/* compare and output */
for(i=2, k=1;i<=fq_pair_array->fastq_pair_num;i++)
{
temp_fq_pair=fastq_pair_array_get_pointer(fq_pair_array, i);
if(fastq_pair_compare_loose(*temp_fq_pair_old, *temp_fq_pair)!=0)
{
if(serial_flag==0)
fastq_pair_printf(*temp_fq_pair_old, fp_out1, fp_out2,
format, -1);
else
fastq_pair_printf(*temp_fq_pair_old, fp_out1, fp_out2,
format, k++);
temp_fq_pair_old=temp_fq_pair;
if(i==fq_pair_array->fastq_pair_num)
{
if(serial_flag==0)
fastq_pair_printf(*temp_fq_pair, fp_out1, fp_out2,
format, -1);
else
fastq_pair_printf(*temp_fq_pair, fp_out1, fp_out2,
format, k++);
}
}
else
{
if(fastq_pair_get_left_length(*temp_fq_pair_old) <= fastq_pair_get_left_length(*temp_fq_pair) &&
fastq_pair_get_right_length(*temp_fq_pair_old) <= fastq_pair_get_right_length(*temp_fq_pair))
{
temp_fq_pair_old=temp_fq_pair;
if(i==fq_pair_array->fastq_pair_num)
{
if(serial_flag==0)
fastq_pair_printf(*temp_fq_pair, fp_out1, fp_out2,
format, -1);
else
fastq_pair_printf(*temp_fq_pair, fp_out1, fp_out2,
format, k++);
}
}
else
{
if(serial_flag==0)
fastq_pair_printf(*temp_fq_pair_old, fp_out1, fp_out2,
format, -1);
else
fastq_pair_printf(*temp_fq_pair_old, fp_out1, fp_out2,
format, k++);
temp_fq_pair_old=temp_fq_pair;
}
}
}
}
return 0;
}
|
C
|
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/times.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#define RD_BUFF_MAX 1024
#define CLIENT_MAX 10
struct myhttp_header {
char method[5];
char filename[200];
char protocol[10];
char type[100];
};
void error_handle(char *);
int read_from_client(int );
int write_to_client(int );
int parse_http_header(char *, struct myhttp_header *);
int check_http_header(struct myhttp_header *);
void send_header(int, char *, char * );
void send_response(int, struct myhttp_header *);
void error_handle(char *err)
{
perror(err);
exit(EXIT_FAILURE);
}
int parse_http_header(char *buff, struct myhttp_header *header)
{
char *line, *section, *tmp;
int i;
// fetch the first line
// line = strtok(buff, "\n");
//fprintf (stdout, "%s\n", line);
// parse line
section = strtok(buff, " ");
strcpy(header->method, section);
section = strtok(NULL, " ");
strcpy(header->filename, section);
section = strtok(NULL, " ");
strcpy(header->protocol, section);
// find request file type
section = strtok(NULL, "\n");
while (strstr(section, "Accept:") == NULL) {
section = strtok(NULL, "\n");
}
tmp = strtok(section, " ");
tmp = strtok(NULL, ",");
strcpy(header->type, tmp);
return 0;
}
int check_http_header(struct myhttp_header *header)
{
return 0;
}
void send_header(int sockfd, char * code, char * type)
{
char buf[100];
if (strcmp(code, "200") == 0) {
strcpy(buf, "HTTP/1.0 200 OK\r\n");
send(sockfd, buf, strlen(buf), 0);
sprintf(buf, "Content-Type: %s\r\n", type);
send(sockfd, buf, strlen(buf), 0);
}
else if (strcmp(code, "400") == 0) {
strcpy(buf, "HTTP/1.0 404 Bad Request\r\n");
send(sockfd, buf, strlen(buf), 0);
sprintf(buf, "Content-Type: %s\r\n", type);
send(sockfd, buf, strlen(buf), 0);
}
else if (strcmp(code, "403") == 0) {
strcpy(buf, "HTTP/1.0 403 Forbidden\r\n");
send(sockfd, buf, strlen(buf), 0);
sprintf(buf, "Content-Type: %s\r\n", type);
send(sockfd, buf, strlen(buf), 0);
}
else if (strcmp(code, "404") == 0) {
strcpy(buf, "HTTP/1.0 404 Not Found\r\n");
send(sockfd, buf, strlen(buf), 0);
sprintf(buf, "Content-Type: %s\r\n", type);
send(sockfd, buf, strlen(buf), 0);
}
sprintf(buf, "\r\n");
send(sockfd, buf, strlen(buf), 0);
}
void send_response(int sockfd, struct myhttp_header *header)
{
FILE *file;
char filename[200];
char filedata[8092];
char code[4];
off_t len;
int nbytes, i;
char *tmp;
char new[200];
if (strcmp(header->filename, "/") == 0) {
strcpy(filename, "index.html");
}
else {
strcpy(filename, ".");
strcat(filename, header->filename);
}
// replace the %20
if (strstr(filename, "%20") != NULL) {
tmp = strtok(filename, "%20");
strcpy(new, tmp);
strcat(new, " ");
while ((tmp = strtok(NULL, "%20")) != NULL) {
strcat(new, tmp);
strcat(new, " ");
}
new[strlen(new)-1] = 0;
strcpy(filename, new);
}
file =fopen(filename, "r");
if (file == NULL) {
if (errno == ENOENT) {
// not found
strcpy(code, "404");
}
else if (errno == EACCES) {
// permission denied
strcpy(code, "402");
}
else {
// undefined
strcpy(code, "404");
}
send_header(sockfd, code, header->type);
}
else {
strcpy(code, "200");
send_header(sockfd, code, header->type);
while ((nbytes = fread(filedata, sizeof(char), 8092, file)) > 0) {
write(sockfd, filedata, nbytes);
}
fclose(file);
}
}
int read_from_client (int sockfd)
{
char buffer[RD_BUFF_MAX];
int nbytes;
struct myhttp_header header;
nbytes = read (sockfd, buffer, RD_BUFF_MAX);
if (nbytes < 0)
{
error_handle("socket read failed");
return -1;
}
else if (nbytes == 0) {
return -1;
}
else {
// parse_http_header
parse_http_header(buffer, &header);
if (check_http_header(&header) < 0) {
// bad request
send_header(sockfd, "400", header.type);
return 0;
}
send_response(sockfd, &header);
close(sockfd);
return 0;
}
}
int write_to_client(int sockfd)
{
return 0;
}
// Main function
int main(int argc, char *argv[]) {
int myhttpd_sockfd, client_sockfd;
int myhttpd_version;
int myhttpd_port;
int myhttpd_timeout;
int i;
struct sockaddr_in myhttpd_sockaddr, client_sockaddr;
socklen_t size;
pthread_t newthread;
// verify arg first
if (argc != 4) {
error_handle("incorrect number of args");
}
if (strcmp(argv[1], "1") == 0) {
// http 1.0
myhttpd_version = 0;
if (atoi(argv[3]) != 0) {
error_handle("timeout for http 1.0 should be zero");
}
}
else if (strcmp(argv[1], "1.1") == 0) {
// http 1.1
myhttpd_version = 1;
if (atoi(argv[3]) <= 0) {
error_handle("timeout for http 1.1 should be greater than zero");
}
}
else {
perror("incorrect http version");
exit(1);
}
// port
myhttpd_port = atoi(argv[2]);
if (myhttpd_port <= 1024 || myhttpd_port >= 65536) {
error_handle("port number has to between 1024 and 65536 (not included)");
}
// timeout
myhttpd_timeout = atoi(argv[3]);
// init server socket (ipv4, tcp)
myhttpd_sockfd = socket(PF_INET, SOCK_STREAM, 0);
if (myhttpd_sockfd < 0) {
error_handle("myhttpd socket failed to create");
}
memset(&myhttpd_sockaddr, 0, sizeof(myhttpd_sockaddr));
myhttpd_sockaddr.sin_family = AF_INET;
myhttpd_sockaddr.sin_port = htons(myhttpd_port);
myhttpd_sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(myhttpd_sockfd, (struct sockaddr *)&myhttpd_sockaddr, sizeof(myhttpd_sockaddr)) == -1) {
close(myhttpd_sockfd);
error_handle("bind failed");
}
if (listen(myhttpd_sockfd, CLIENT_MAX) == -1) {
close(myhttpd_sockfd);
error_handle("listen failed");
}
while (1) {
size = sizeof(client_sockaddr);
client_sockfd = accept(myhttpd_sockfd, (struct sockaddr *)&client_sockaddr, &size);
if (client_sockfd == -1) {
error_handle("accept error");
}
if (pthread_create(&newthread , NULL, (void *)read_from_client, (void *)client_sockfd) != 0) {
perror("pthread create error");
}
}
close(myhttpd_sockfd);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/************************************************************************/
/* */
/************************************************************************/
/************************************************************************
原型: int atoi(const char *nptr);
函数说明: 参数nptr字符串,如果第一个非空格字符不存在或者不是数字也不是正负号则返回零,
否则开始做类型转换,之后检测到非数字(包括结束符 \0) 字符时停止转换,返回整型数。
************************************************************************/
int atoi(const char* str)
{
int value = 0;
int flag = 1; //判断符号
while (*str == ' ') //跳过字符串前面的空格
{
str++;
}
if (*str == '-') //第一个字符若是‘-’,说明可能是负数
{
flag = 0;
str++;
}
else if (*str == '+') //第一个字符若是‘+’,说明可能是正数
{
flag = 1;
str++;
}//第一个字符若不是‘+’‘-’也不是数字字符,直接返回0
else if (*str > '9' || *str < '0')
{
return 0;
}
//当遇到非数字字符或遇到‘\0’时,结束转化
while (*str != '\0' && *str <= '9' && *str >= '0')
{
value = value * 10 + *str - '0'; //将数字字符转为对应的整形数
str++;
}
if (flag == 0) //负数的情况
{
value = -value;
}
return value;
}
/************************************************************************/
/* */
/************************************************************************/
int main(int argc, char* argv[])
{
int val;
char str[20];
strcpy(str, "123456789");
val = atoi(str);
printf("字符串值 = %s, 整型值 = %d\n", str, val);
strcpy(str, "-321654987");
val = atoi(str);
printf("字符串值 = %s, 整型值 = %d\n", str, val);
strcpy(str, "helloworld");
val = atoi(str);
printf("字符串值 = %s, 整型值 = %d\n", str, val);
strcpy(str, "123helloworld");
val = atoi(str);
printf("字符串值 = %s, 整型值 = %d\n", str, val);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.