language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include "queue.h"
#include "../list/list.h"
#include <assert.h>
#include <pthread.h>
#include <stdlib.h>
struct queue {
pthread_mutex_t mtx;
struct list * list;
};
struct queue *queue_init(DeleteValueFunction destroy_value)
{
struct queue *queue = malloc(sizeof(struct queue));
queue->list = list_init(NULL, destroy_value);
pthread_mutex_init(&(queue->mtx), NULL);
return queue;
}
int queue_size(struct queue *queue)
{
pthread_mutex_lock(&(queue->mtx));
int size = list_size(queue->list);
pthread_mutex_unlock(&(queue->mtx));
return size;
}
void enqueue(struct queue *queue, void *value)
{
pthread_mutex_lock(&(queue->mtx));
list_append(queue->list, value);
pthread_mutex_unlock(&(queue->mtx));
}
void *dequeue(struct queue *queue)
{
pthread_mutex_lock(&(queue->mtx));
void *rv = list_first_value(queue->list);
list_remove_front(queue->list);
pthread_mutex_unlock(&(queue->mtx));
return rv;
}
void queue_delete(struct queue *queue)
{
list_delete(queue->list);
free(queue);
}
|
C
|
/****
* 10550 - Combination Lock
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int s, v0, v1, v2;
int t;
while (scanf("%d %d %d %d", &s, &v0, &v1, &v2) != EOF && (s+v0+v1+v2) != 0)
{
t = 120;
t += (40 + s - v0) % 40;
t += (40 + v1 - v0) % 40;
t += (40 + v1 - v2) % 40;
t *= 9;
printf("%d\n", t);
}
return 0;
}
|
C
|
#include <stdarg.h>
void setv(int num, ...) {
va_list l;
void (*f)(void);
(void) num;
/* in this test we have only one var arg */
va_start(l, num);
f = va_arg(l, void *);
f();
va_end(l);
}
void foo(void) {
/* OK, assert reached */
test_assert(1);
}
int main(void) {
int a;
setv(1, foo);
return 0;
}
|
C
|
#include <stdio.h>
int main() {
double val;
printf("Entrez un réel : ");
scanf("%lf", &val);
if (val >= -1 && val < 1) {
printf("\n%lf appartient à [-1; 1[", val);
} else {
printf("\n%lf n'appartient pas à [-1; 1[", val);
}
}
|
C
|
#include <stdio.h>
#include<ctype.h>
int main()
{
int n=0,i=0,j=0,flag;
char a[81],b[80]={0},x;
scanf("%s\n",a);
x=getchar();
while(a[i]!='\0')
{
if(x==a[i]){//相同则比较下一个
i++;
x=getchar();
continue;
}
flag=1;
a[i]=toupper(a[i]);
for(j=0;j<n;j++)
{
if(b[j]==a[i]){
flag=0;
break;
}
}
if(flag){//如果b没有该字母则加进去
n++;
b[j]=a[i];
}
i++;
}
puts(b);
return 0;
}
|
C
|
#include <stdio.h>
int printPowers(int top);
int power(int number,int times);
int main(int argc, char const *argv[]) {
int number;
scanf("%d", &number);
return printPowers(number);
}
int power(int number,int times){
if(times<1){
return 1;
}
return power(number,times-1)*number;
}
int printPowers(int top){
if (top<0){
return 1;
}
for(int i=0;i<=top;i++){
if(i<top){
printf("%d ", power(2,i));
}
else{
printf("%d\n", power(2,i));
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int up (int tablero[4][4],int *score){
int i, j, k, t, invalido;
invalido=0;
int nuevo[4][4]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int test[4][4]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
for(j=0;j<4;j++){
for(i=0;i<4;i++){
test[i][j]=tablero[i][j];
}
}
for(j=0;j<4;j++){
k=0;
for(i=0;i<4;i++){
if (tablero[i][j]!=0){
nuevo[k][j]=tablero[i][j];
k+=1;
}
}
}
for(j=0;j<4;j++){
for(i=0;i<3;i++){
if (nuevo[i][j]==nuevo[i+1][j]){
nuevo[i][j]=nuevo[i][j]*2;
nuevo[i+1][j]=0;
*score+=nuevo[i][j];
}
}
}
for(i=0;i<4;i++){
for(j=0;j<4;j++){
tablero[i][j]=0;
}
}
for(j=0;j<4;j++){
k=0;
for(i=0;i<4;i++){
if (nuevo[i][j]!=0){
tablero[k][j]=nuevo[i][j];
k+=1;
}
}
}
t=0;
for(j=0;j<4;j++){
for(i=0;i<4;i++){
if(test[i][j]!=tablero[i][j]){
t=1;
}
}
}
if (t==0){
printf("\a\x1B[31m wrong move, try again \x1B[0m\n\n\n");
invalido=1;
}
return invalido;
}
int down (int tablero[4][4],int *score){
int i, j, k, t, invalido;
invalido=0;
int nuevo[4][4]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int test[4][4]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
for(j=0;j<4;j++){
for(i=0;i<4;i++){
test[i][j]=tablero[i][j];
}
}
for(j=0;j<4;j++){
k=3;
for(i=3;i>=0;i--){
if (tablero[i][j]!=0){
nuevo[k][j]=tablero[i][j];
k-=1;
}
}
}
for(j=0;j<4;j++){
for(i=3;i>0;i--){
if (nuevo[i][j]==nuevo[i-1][j]){
nuevo[i][j]=nuevo[i][j]*2;
nuevo[i-1][j]=0;
*score+=nuevo[i][j];
}
}
}
for(i=0;i<4;i++){
for(j=0;j<4;j++){
tablero[i][j]=0;
}
}
for(j=0;j<4;j++){
k=3;
for(i=3;i>=0;i--){
if (nuevo[i][j]!=0){
tablero[k][j]=nuevo[i][j];
k-=1;
}
}
}
t=0;
for(j=0;j<4;j++){
for(i=0;i<4;i++){
if(test[i][j]!=tablero[i][j]){
t=1;
}
}
}
if (t==0){
printf("\a\x1B[31m wrong move, try again \x1B[0m\n\n\n");
invalido=1;
}
return invalido;
}
int left (int tablero[4][4],int *score){
int i, j, k, t, invalido;
invalido=0;
int nuevo[4][4]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int test[4][4]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
for(j=0;j<4;j++){
for(i=0;i<4;i++){
test[i][j]=tablero[i][j];
}
}
for(i=0;i<4;i++){
k=0;
for(j=0;j<4;j++){
if (tablero[i][j]!=0){
nuevo[i][k]=tablero[i][j];
k+=1;
}
}
}
for(i=0;i<4;i++){
for(j=0;j<3;j++){
if (nuevo[i][j]==nuevo[i][j+1]){
nuevo[i][j]=nuevo[i][j]*2;
nuevo[i][j+1]=0;
*score+=nuevo[i][j];
}
}
}
for(i=0;i<4;i++){
for(j=0;j<4;j++){
tablero[i][j]=0;
}
}
for(i=0;i<4;i++){
k=0;
for(j=0;j<4;j++){
if (nuevo[i][j]!=0){
tablero[i][k]=nuevo[i][j];
k+=1;
}
}
}
t=0;
for(j=0;j<4;j++){
for(i=0;i<4;i++){
if(test[i][j]!=tablero[i][j]){
t=1;
}
}
}
if (t==0){
printf("\a\x1B[31m wrong move, try again \x1B[0m\n\n\n");
invalido=1;
}
return invalido;
}
int right (int tablero[4][4],int *score){
int i, j, k, t, invalido;
invalido=0;
int nuevo[4][4]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int test[4][4]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
for(j=0;j<4;j++){
for(i=0;i<4;i++){
test[i][j]=tablero[i][j];
}
}
for(i=0;i<4;i++){
k=3;
for(j=3;j>=0;j--){
if (tablero[i][j]!=0){
nuevo[i][k]=tablero[i][j];
k-=1;
}
}
}
for(i=0;i<4;i++){
for(j=3;j>0;j--){
if (nuevo[i][j]==nuevo[i][j-1]){
nuevo[i][j]=nuevo[i][j]*2;
nuevo[i][j-1]=0;
*score+=nuevo[i][j];
}
}
}
for(i=0;i<4;i++){
for(j=0;j<4;j++){
tablero[i][j]=0;
}
}
for(i=0;i<4;i++){
k=3;
for(j=3;j>=0;j--){
if (nuevo[i][j]!=0){
tablero[i][k]=nuevo[i][j];
k-=1;
}
}
}
t=0;
for(j=0;j<4;j++){
for(i=0;i<4;i++){
if(test[i][j]!=tablero[i][j]){
t=1;
}
}
}
if (t==0){
printf("\a\x1B[31m wrong move, try again \x1B[0m\n\n\n");
invalido=1;
}
return invalido;
}
void print (int tablero[4][4], int score, int tile){
int i, j;
for(i=0;i<4;i++){
for(j=0;j<4;j++){
if (tablero[i][j]==0){
printf("\x1B[37m %d \x1B[0m", tablero[i][j]);
}
if (tablero[i][j]==2){
printf("\x1B[36m %d \x1B[0m", tablero[i][j]);
}
if (tablero[i][j]==4){
printf("\x1B[34m %d \x1B[0m", tablero[i][j]);
}
if (tablero[i][j]==8){
printf("\x1B[32m %d \x1B[0m", tablero[i][j]);
}
if (tablero[i][j]==16){
printf("\x1B[33m %d \x1B[0m", tablero[i][j]);
}
if (tablero[i][j]==32){
printf("\x1B[35m %d \x1B[0m", tablero[i][j]);
}
if (tablero[i][j]==64){
printf("\x1B[31m %d \x1B[0m", tablero[i][j]);
}
if (tablero[i][j]==128){
printf("\x1B[36m %d \x1B[0m", tablero[i][j]);
}
if (tablero[i][j]==256){
printf("\x1B[34m %d \x1B[0m", tablero[i][j]);
}
if (tablero[i][j]==512){
printf("\x1B[32m %d \x1B[0m", tablero[i][j]);
}
if (tablero[i][j]==1024){
printf("\x1B[33m %d \x1B[0m", tablero[i][j]);
}
if (tablero[i][j]==2048){
printf("\x1B[31m %d \x1B[0m", tablero[i][j]);
}
if (tablero[i][j]==4096){
printf("\x1B[35m %d \x1B[0m", tablero[i][j]);
}
if (tablero[i][j]==8192){
printf("\x1B[37m %d \x1B[0m", tablero[i][j]);
}
if (tablero[i][j]==16384){
printf("\x1B[36m %d \x1B[0m", tablero[i][j]);
}
if (i==0&&j==3){
printf("\x1B[33m score:\n\n\x1B[0m");
}
if (i==1&&j==3){
printf("\x1B[31m %d\n\n\x1B[0m", score);
}
if (i==2&&j==3){
printf("\x1B[33m highest tile:\n\n\x1B[0m");
}
if (i==3&&j==3){
printf("\x1B[31m %d\n\n\x1B[0m", tile);
}
}
}
}
void help(){
printf("\x1B[33m\n\n");
printf("\n\n swipe to move all the tiles\n");
printf("\n\n");
printf(" 0 0 0 0\n");
printf("\n\n");
printf(" 0<---------0----------0----------2\n");
printf("\n\n");
printf(" 0<---------0----------4 0\n");
printf("\n\n");
printf(" 0<---------0----------0----------2\n");
printf("\n\n");
printf("\n\n when 2 tiles with the same\n");
printf(" number touch, they merge into one\n");
printf("\n\n");
printf(" 0 0 0 0\n");
printf("\n\n");
printf(" 0 2 + 2 = 4\n");
printf("\n\n");
printf(" 0 0 0 0\n");
printf("\n\n");
printf(" 0 0 + 8 = 16\n");
printf("\n\n");
printf(" it's over when the board fills up\n");
printf("\n\n");
printf("\n\n join all the numbers\n");
printf(" and get at least to the 2048 tile\n");
printf("\n\n");
printf(" 0 2048 4 0\n");
printf("\n\n");
printf(" 8 2 32 4\n");
printf("\n\n");
printf(" 4 128 0 0\n");
printf("\n\n");
printf(" 16 64 8 16\n");
printf("\n\n");
printf(" good luck!\n");
printf("\n\n");
printf("\n\n\x1B[0m");
}
int htile (int tablero[4][4]){
int i, j, tile;
tile=0;
for(i=0;i<4;i++){
for(j=0;j<4;j++){
if (tablero[i][j]>tile){
tile=(tablero[i][j]);
}
}
}
return tile;
}
int main(void){
int e,randrow,randcol,randnum,game,game0,score,tile,i,j;
char key;
printf("\n\x1B[33m welcome to 2048\n\x1B[0m");
printf("\x1B[33m press w,a,s,d to move\n\x1B[0m");
printf("\x1B[33m for help press h\n\x1B[0m");
printf("\n\n\n");
game0=1;
score=0;
while(game0==1){
int board[4][4]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
srand(time(NULL));
randrow=(rand()%4);
randcol=(rand()%4);
randnum=2;
if(board[randrow][randcol]==0){
board[randrow][randcol]=randnum;
}
game=1;
while(game==1){
e=0;
tile=htile(board);
print(board, score, tile);
printf("\n ");
scanf("%s", &key);
printf("\n\n");
switch(key){
case 'w':
e=up(board,&score);
break;
case 's':
e=down(board,&score);
break;
case 'a':
e=left(board,&score);
break;
case 'd':
e=right(board,&score);
break;
case 'h':
help();
e=1;
break;
default:
printf("\a\x1B[31m wrong move, try again \x1B[0m\n\n\n");
e=1;
break;
}
if (e==0){
randrow=(rand()%4);
randcol=(rand()%4);
randnum=(rand()%10);
if (randnum!=4){
randnum=2;
}
while(board[randrow][randcol]!=0){
randrow=(rand()%4);
randcol=(rand()%4);
}
board[randrow][randcol]=randnum;
game=0;
for(i=0;i<4;i++){
for(j=0;j<4;j++){
if (board[i][j]==0){
game=1;
}
}
}
if(game==0){
tile=htile(board);
print(board, score, tile);
printf("you lose\a\n");
printf("want to play again? press 1\n");
game0=0;
scanf("%d", &game0);
printf("\n\n");
}
}
}
}
}
|
C
|
#include "stdio.h"
int main() {
int x, contagem_linhas, contagem_colunas = 0;
scanf("%d", &x);
while(contagem_colunas < x) {
contagem_linhas = 0;
while(contagem_linhas < contagem_colunas + 1) {
printf("# ");
contagem_linhas++;
}
printf("\n");
contagem_colunas++;
}
}
|
C
|
#include <stdio.h>
#include <math.h>
void main(){
double x1,y1,x2,y2;
scanf("%lf %lf %lf %lf", &x1, &y1, &x2, &y2);
printf("%.4lf\n", sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1)));
}
|
C
|
#include "stack.h"
#include <stdio.h>
int main()
{
int capacity = 10;
struct Stack *stack = create_stack(capacity);
push(stack, 1);
push(stack, 2);
push(stack, 3);
push(stack, 4);
for (int i=0; i<4; i++) {
printf("%d ", top(stack));
pop(stack);
}
printf("\n");
dispose_stack(&stack);
stack = create_stack(capacity);
for (int i=0; i<capacity; i++)
push(stack, i*2);
for (int i=0; i<capacity; i++) {
printf("%d ", top(stack));
pop(stack);
}
printf("\n");
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <windows.h>
int x;
int y=0;
int pbitzahl;
int zahlpb;
void pbit(int temp[],int lang){
int anz;
int i,j,p,f;
anz=lang+zahlpb;
int final[anz];
int ok=1;
p=0;
for(i=0;i<lang;i++){
f=1;
for(j=0;j<zahlpb;j++){
if((p+1)==f){
ok=0;
final[p]=0;
p++;
}
f=f*2;
}
final[p]=temp[i];
p++;
}
i=0;
j=0;
while(i<(anz-7)){
printf("| ");
j=0;
while(j<7){
printf("%i ",final[i]);
i++;
f=1;
while(f<anz){
if(i==f){
j--;
}
f=f*2;
}
j++;
}
printf("|\n");
}
}
void buchstaben_in_dual(int dec,int lang,int temp[]){
int i,rest,zahl,o;
int laenge = (lang*7);
o=(7*y);
o--;
for(i=0;i<7;i++){
if(i==0){
rest=dec%2;
zahl=dec/2;
}
else{
rest=zahl%2;
zahl=zahl/2;
}
temp[o]=rest;
o--;
}
if(y==(laenge/7)){
printf("\n");
i=0;
pbit(temp,laenge);
}
}
int main()
{
system("color 7");
char wort[200000];
int dec,i,lang1;
system("cls");
printf("Geben sie ein Buchstebe ein :");
scanf("%[^\n]s",&wort);
lang1 = strlen(wort);
i=1;
zahlpb = 1;
printf("\n");
while(i<(lang1*7)){
i= i*2;
zahlpb++;
}
pbitzahl = i;
int dual[lang1*10];
printf("Anzahl der Buchstaben: = %i",lang1);
printf("\n\n>>\n>>\n>>\n");
for(i=0;i<lang1;i++){
y++;
dec = wort[i];
buchstaben_in_dual(dec,lang1,dual);
}
printf("\n\n>>\n>>\n>>\n\nENDE\n");
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "List.h"
struct node_ {
int number;
Node next;
};
Node newNode(int number) {
Node node = malloc (sizeof(struct node_));
node->number = number;
node->next = NULL;
return node;
}
void deleteNode(Node node) {
free(node);
}
void printNode(Node node) {
printf("[%d] ", node->number);
}
void join(Node first, Node second) {
first->next = second;
}
void printList(Node start) {
Node node = start;
while (node != NULL) {
printNode(node);
printf("=> ");
node = node->next;
}
printf("[X]\n");
}
void deleteList(Node start) {
Node node = start;
while (node != NULL) {
Node next = node->next;
deleteNode(node);
node = next;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
int id;
char path[1024];
struct node* next;
}node;
void main() {
node* n1 = (node*)malloc(sizeof(node));
n1->id = 1;
strcpy(n1->path, "/home/ten/t1");
n1->next = NULL;
printf("id: %d\n", n1->id);
printf("path: %s\n", n1->path);
}
|
C
|
/*
Ficheiro: estruturas.h
Autor: Bruno Miguel da Silva Mendes ist195544/al95544
Descricao: Ficheiro em que se definem todas as estruturas e constantes
*/
/*DEFENICAO DE CONSTANTES*/
#define STR_MAX 64
#define MAX_PROD 10000
#define MAX_ENC 500
#define MAX_PESO 200
/*ESTRUTURAS*/
/*
Produto: int, char*, int, int, int
Representa um produto constituida por id, descricao, preco, peso e quantidade.
*/
typedef struct {
int id;
char desc[STR_MAX];
int preco;
int peso;
int qtd;
} Produto;
/*
Pid: int, int
Representa um pseudo apontador para um produto em que guarda a quantidade
do produto cujo id esta guardado na variavel id.
*/
typedef struct {
int id;
int qtd;
} Pid;
/*
Encomenda: int, int, Pid*
Representa uma encomenda constituida por peso, quantidade de produtos na encomenda e um
vetor de pseudo apontadores para produtos que constituem esta encomenda.
*/
typedef struct {
int peso;
int size;
Pid pid[MAX_PROD];
} Encomenda;
|
C
|
/*˳Ա*/
#include "stdio.h"
#include "stdlib.h"
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 100
typedef int Status;
typedef int ElemType;
typedef struct
{
ElemType data[MAXSIZE];
int length;
} SqList;
/*ʼԱ*/
Status InitList (SqList *L)
{
L->length = 0;
return OK;
}
/*Ԫ*/
Status visit(ElemType c)
{
printf("%d ",c);
return OK;
}
/*Ա*/
Status ListTraverse( SqList L ){
int i;
for( i=0; i<L.length; i++ ){
// visit(L.data[i]);
printf("%d ",L.data[i]);
}
printf("ϣ\n");
return OK;
}
/*Ա*/
Status ClearList ( SqList *L ){
L->length = 0;
printf("Աɹ\n");
return OK;
}
/*жԱǷΪ*/
Status ListIsEmpty ( SqList L ){
if( L.length == 0 ){
printf("ԱΪգ\n");
return TRUE;
}else{
printf("ԱΪգ\n");
return FALSE;
}
}
/*Ա*/
int ListLength ( SqList L ){
printf("ǰԱΪ%d\n",L.length);
return L.length;
}
/*eLеiԪصֵ*/
Status GetElem ( SqList L, int i, ElemType *e )
{
if ( L.length == 0 || i < 1 || i > L.length )
{
printf("Error!\n");
return ERROR;
}
else
{
*e = L.data[i-1];
return OK;
}
}
/*LеiλòµԪe*/
Status ListInsert ( SqList *L, int i, ElemType e ){
if ( L->length == MAXSIZE ){
printf("Ա\n");
return ERROR;
}
if ( i<1 || i>L->length+1 ){
printf("λд\n");
return ERROR;
}
if ( i <= L->length ){
int k;
for( k=L->length-1; k>=i-1; k-- ){
L->data[k+1] = L->data[k];
}
}
L->data[i-1] = e;
L->length++;
printf("ɹڵ%dλϲ%d\n",i,e);
return OK;
}
/*LеiλɾԪe*/
Status ListDelete ( SqList *L, int i, ElemType *e ){
if ( L->length == 0 ){
printf("ԱΪգ\n");
return ERROR;
}
if ( i<1 || i>L->length ){
printf("ɾλд\n");
return ERROR;
}
*e = L->data[i-1];
if ( i < L->length ){
int k;
for( k=i; k<L->length; k++ ){
L->data[k-1] = L->data[k];
}
}
L->length --;
printf("ɹڵ%dλɾ%d\n",i,*e);
return OK;
}
/*ѯһeڵλ*/
Status LocateElem( SqList L, ElemType e ){
if( L.length == 0 ){
return 0;
}
int i;
for( i=0; i<L.length; i++ ){
if( L.data[i] == e ){
printf("ɹѯһeλΪ%d\n",i+1);
break;
}
}
if( i >= L.length ){
printf("ڸԪ\n");
return 0;
}
return i+1;
}
/*ԱLbеLaеԪز뵽La*/
void unionL( SqList *La, SqList Lb ){
int La_len,Lb_len,i;
ElemType e;
La_len = ListLength(*La);
Lb_len = ListLength(Lb);
printf("%d,%d\n",La_len,Lb_len);
for( i=1; i<=Lb_len; i++ ){
GetElem( Lb, i, &e );
if(!LocateElem( *La,e )){
ListInsert( La, ++La_len, e);
}
}
}
int main(){
SqList L;
ElemType e;
Status i;
int j;
i = InitList (&L);
printf ("ʼLL.length=%d\n",L.length);
ListInsert ( &L, 1, 3 );
GetElem ( L,1,&e);
printf ("1ԪصֵΪ%d\n",e);
ListInsert ( &L, 1, 2 );
GetElem ( L,1,&e);
printf ("1ԪصֵΪ%d\n",e);
GetElem ( L,2,&e);
printf ("2ԪصֵΪ%d\n",e);
ListLength (L);
LocateElem( L,3 );
ListTraverse(L);
ListIsEmpty(L);
//һ10Lb
SqList Lb;
i = InitList(&Lb);
for( j=6; j<=15; j++ ){
i = ListInsert(&Lb,1,j);
}
ListTraverse(L);
ListTraverse(Lb);
unionL(&L,Lb);
ListTraverse(L);
ListDelete ( &L, 1, &e );
ListLength (L);
ListTraverse(L);
ClearList(&L);
ListTraverse(L);
ListIsEmpty(L);
return 0;
}
|
C
|
#ifndef MOVIE_H
#define MOVIE_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Pelicula - Movie */
typedef struct Movies{
char *title;
char *director;
char **actors;
int numActors;
int year;
int id;
} Movie;
/* Catalogo de peliculas - MovieCollection */
typedef struct {
Movie *movies; // Arreglo de peliculas.
int size; // Numero de peliculas guardadas.
} MovieCollection;
void movie__extendMovieCollection(MovieCollection *catalog, int movie);
void movie__freeMovie(Movie *movie);
#endif // MOVIE_H
|
C
|
/* -*- c -*-
Thermalsensingm.nc - Module to sample LightTSR and LightPAR sensors.
Copyright (C) 2011 Ross Wilkins
This File is part of Cogent-House
Cogent-House is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Cogent-House is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see
<http://www.gnu.org/licenses/>.
===================
Light Sensing Module
===================
The module samples the TelosB's on board LightTSR and LightPAR
sensors. The raw adc values are then converted in to real engineering
values.
:author: Ross Wilkins
:email: ross.wilkins87@googlemail.com
:date: 05/01/2011
*/
module LightSensingM
{
provides
{
interface Read<uint16_t> as ReadPAR;
interface Read<uint16_t> as ReadTSR;
}
uses
{
interface Read<uint16_t> as GetPAR;
interface Read<uint16_t> as GetTSR;
}
}
implementation
{
//will initially need to be read from config in next version
//par=(int)3.662109375*data;
float parCoeffs[] = {0, 3.662109375};
//tsr=(int)0.3662109375*data;
float tsrCoeffs[] = {0, 0.3662109375};
task void readPARTask()
{
//get temp
call GetPAR.read();
}
task void readTSRTask()
{
//get temp
call GetTSR.read();
}
command error_t ReadPAR.read()
{
post readPARTask();
return SUCCESS;
}
command error_t ReadTSR.read()
{
post readTSRTask();
return SUCCESS;
}
//Convert raw adc to temp
event void GetPAR.readDone(error_t result, uint16_t data) {
int par;
par=horner(sizeof(parCoeffs)/sizeof(float)-1,parCoeffs,(float)data);
signal ReadPAR.readDone(SUCCESS, par);
}
//Convert raw adc to temp
event void GetTSR.readDone(error_t result, uint16_t data) {
int tsr;
tsr=horner(sizeof(tsrCoeffs)/sizeof(float)-1,tsrCoeffs,(float)data);
signal ReadTSR.readDone(SUCCESS, tsr);
}
}
|
C
|
#include <stdio.h>
#include "tool.h"
int main()
{
int m,n,c,d;
int first[20][20];
int second[20][20];
printf("vvedit' rayd and stovp\n");
scanf( "%i %i",&m,&n);
printf("vvedit' elementi first matr\n");
for(c=0;c<m;c++){
for(d=0;d<n;d++){
scanf("%i",&first[c][d]);}}
printf("vvedit' elementi second matr\n");
for(c=0;c<m;c++){
for(d=0;d<n;d++){
scanf("%i",&second[c][d]);}}
printf("Summa matr\n");
sum_matr (m, n, first, second);
}
|
C
|
#ifndef HEAD
#define HEAD "header.h"
#include HEAD
#endif
tablePtr JOIN(tablePtr table1, tablePtr table2)
{
tablePtr tableNew;
int colNum1;
int colNum2;
int rowNum1;
int rowNum2;
int row1;
int row2;
int i;
int j;
tableNew = (tablePtr)malloc(sizeof(table));
//table2為NULL表示複製table1即可
if(table2 == NULL){
tableNew->nextTable = NULL;
tableNew->tableName[0] = '\0';
tableNew->colNumber = table1->colNumber;
tableNew->rowNumber = table1->rowNumber;
tableNew->dataRowList = (dataRowPtr *)malloc(sizeof(dataRowPtr) * tableNew->rowNumber);
for(i = 0; i < tableNew->rowNumber; i++){
tableNew->dataRowList[i] = (dataRowPtr)malloc(sizeof(dataRow));
tableNew->dataRowList[i]->dataList = (dataPtr *)malloc(sizeof(dataPtr) * tableNew->colNumber);
for(j = 0; j < tableNew->colNumber; j++){
tableNew->dataRowList[i]->dataList[j] = table1->dataRowList[i]->dataList[j];
}
}
tableNew->colInfoList = (colInfoPtr *)malloc(sizeof(colInfoPtr) * tableNew->colNumber);
for(i = 0; i < tableNew->colNumber; i++){
tableNew->colInfoList[i] = table1->colInfoList[i];
}
tableNew->activeDataRowList = (int *)malloc(sizeof(int) * tableNew->rowNumber);
for(i = 0; i < tableNew->rowNumber; i++){
tableNew->activeDataRowList[i] = 1;
}
}
//join table1 & table2
else{
tableNew->nextTable = NULL;
tableNew->tableName[0] = '\0';
tableNew->colNumber = table1->colNumber + table2->colNumber;
tableNew->rowNumber = table1->rowNumber * table2->rowNumber;
tableNew->dataRowList = (dataRowPtr *)malloc(sizeof(dataRowPtr) * tableNew->rowNumber);
for(i = 0; i < tableNew->rowNumber; i++){
tableNew->dataRowList[i] = (dataRowPtr)malloc(sizeof(dataRow));
tableNew->dataRowList[i]->dataList = (dataPtr *)malloc(sizeof(dataPtr) * tableNew->colNumber);
row1 = i / table2->rowNumber;
row2 = i % table2->rowNumber;
for(j = 0; j < table1->colNumber; j++){
tableNew->dataRowList[i]->dataList[j] = table1->dataRowList[row1]->dataList[j];
}
for(j = 0; j < table2->colNumber; j++){
tableNew->dataRowList[i]->dataList[j + table1->colNumber] = table2->dataRowList[row2]->dataList[j];
}
}
tableNew->colInfoList = (colInfoPtr *)malloc(sizeof(colInfoPtr) * tableNew->colNumber);
for(i = 0; i < table1->colNumber; i++){
tableNew->colInfoList[i] = table1->colInfoList[i];
}
for(i = 0; i < table2->colNumber; i++){
tableNew->colInfoList[i + table1->colNumber] = table2->colInfoList[i];
}
tableNew->activeDataRowList = (int *)malloc(sizeof(int) * tableNew->rowNumber);
for(i = 0; i < tableNew->rowNumber; i++){
tableNew->activeDataRowList[i] = 1;
}
}
return tableNew;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/resource.h>
static void wait_for_input(const char *msg)
{
char buf[32];
printf(" * %s\n", msg);
printf(" -- Press ENTER to continue ...\n"); fflush(stdout);
fgets(buf, 32, stdin);
}
#define NUM_PAGES 8
int main(void)
{
void *addr;
size_t map_len = NUM_PAGES * getpagesize();
size_t i;
int rc;
struct rlimit r;
rc = getrlimit(RLIMIT_MEMLOCK, &r);
if (rc < 0) {
perror("getrlimit");
exit(EXIT_FAILURE);
}
printf("memlock limit: %zu (current), %zu (maximum)\n",
r.rlim_cur, r.rlim_max);
printf("map_len: %zu\n", NUM_PAGES * map_len);
wait_for_input("Call mmap()");
addr = mmap(NULL, NUM_PAGES * map_len, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (addr == MAP_FAILED) {
perror("mmap");
exit(EXIT_FAILURE);
}
wait_for_input("Access mapped page");
for (i = 0; i < NUM_PAGES; i++)
memcpy(addr + i*getpagesize(), "anaaremere", 10);
wait_for_input("Call mlock()");
rc = mlock(addr, NUM_PAGES * map_len);
if (rc < 0) {
perror("mlock");
exit(EXIT_FAILURE);
}
wait_for_input("mlock() has been called");
return 0;
}
|
C
|
#include<stdio.h>
#include "SimLList.h"
#define INT_MAX 32000
struct GraphAdjListInt* initializeGraphAdjListInt();
void displayGraphAdjListInt(struct GraphAdjListInt *);
void initializeSingleSource(struct GraphAdjListInt *);
void displayWeightOfGraph(struct GraphAdjListInt *);
struct AdjListInt{
struct SimpleLinkedListInt *list;
int data;
int discovery; //DISCOVERY TIME
int finish; //FINISH TIME
int parent;
};
struct AdjMatInt{
int data;
int distance;
int *list;
};
struct GraphAdjListInt{
int V;
int *weight;
int E;
struct AdjListInt **adj;
};
struct GraphAdjListInt* initializeGraphAdjListInt(){
int i,j,x,y,weight,flagWeighted,flagDirected;
struct GraphAdjListInt* G=NULL;
G=(struct GraphAdjListInt*)malloc(sizeof(struct GraphAdjListInt));
if(G==NULL){
printf("Memory Error: LINE::30");
return NULL;
}
printf("Enter the no. of Vertice: ");
scanf("%d",&G->V);
printf("\nEnter the no. of Edges: ");
scanf("%d",&G->E);
G->adj=(struct AdjListInt**)malloc(sizeof(struct AdjListInt)*G->V);
if(G->adj==NULL){
printf("Memory Error: LINE::39");
return NULL;
}
for(i=0;i<G->V;i++){
G->adj[i]=(struct AdjListInt*)malloc(sizeof(struct AdjListInt));
if(G->adj[i]==NULL){
printf("Memory Error: LINE::50");
return NULL;
}
}
G->weight=(int *)malloc(sizeof(int) * G->V*G->V);
if(G->weight==NULL){
printf("Memory Error: LINE::44");
return NULL;
}
for (i = 0; i < G->V; i++)
{
for (j = 0; j <G->V ; j++)
{
*(G->weight + G->V*i+j)=-1;
}
}
initializeSingleSource(G);
printf("\n1->For Weighted\n2->For Unweighted\nPress Key.. ");
scanf("%d",&flagWeighted);
printf("\n1->For Directed\n2->For Undirected\nPress Key.. ");
scanf("%d",&flagDirected);
for(i=0;i<G->E;i++){
if(flagWeighted==2){
printf("Enter the vertices at the end of %d Edges ",i+1);
scanf("%d %d",&x,&y);
}
else if(flagWeighted==1){
printf("Enter the vertices at the end of %d Edges with Weight",i+1);
scanf("%d %d %d",&x,&y,&weight);
}
else{
printf("LINE 59::Wrong Input For Weighted OR Unweighted");
return NULL;
}
if(x>G->V||y>G->V){
printf("Wrong Input. Please Try Again:");
i--;
continue;
}
x--;
y--;
if(flagWeighted==1){
*(G->weight+G->V*x+y)=weight;
if(flagDirected==2){
*(G->weight+G->V*y+x)=weight;
}
}
uniqueInsertAtEndSimpleLinkedListInt(&G->adj[x]->list,y);
if(flagDirected==2)
uniqueInsertAtEndSimpleLinkedListInt(&G->adj[y]->list,x);
}
return G;
}
void initializeSingleSource(struct GraphAdjListInt *G){
int i;
for(i=0;i<G->V;i++){
G->adj[i]->data=i;
G->adj[i]->parent=-1;
G->adj[i]->discovery=-1;
G->adj[i]->finish=-1;
}
}
void displayGraphAdjListInt(struct GraphAdjListInt *G){
struct SimpleLinkedListInt *temp=NULL;
int i;
printf("\n");
for(i=0;i<G->V;i++){
printf("%d :: ",i+1);
temp=G->adj[i]->list;
while(temp!=NULL){
printf("->%d",temp->data+1);
temp=temp->next;
}
printf("\n");
}
printf("\n-------------------------------\n");
}
void displayWeightOfGraph(struct GraphAdjListInt *G){
int i,j;
printf("\n-----------------Display Weight----------------------\n");
for (i = 0; i < G->V; i++)
{
for (j = 0; j <G->V ; j++)
{
printf("%2d ",*(G->weight + G->V*i+j));
}
printf("\n");
}
printf("\n-----------------------------------------------------\n");
}
|
C
|
// Threading to print array in normal and reverse order using two different threads
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
struct node {
int *p;
int n;
};
void * func1(void *p) {
struct node * q = (struct node *)p;
for(int i=0;i<q->n;i++) {
printf("Normal : %d\n", q->p[i]);
}
}
void * func2(void *p) {
struct node * q = p;
for(int i=0;i<q->n;i++) {
printf("Reverse : %d\n", q->p[q->n-1-i]);
}
}
int main() {
struct node n1, n2;
pthread_t t1, t2;
int arr[10] = {1,2,3,4,5,6,7,8,9,10};
n1.p = arr;
n1.n = 10;
n2.p = arr;
n2.n = 10;
pthread_create(&t1, NULL, func1, (void *)&n1);
pthread_create(&t1, NULL, func2, (void *)&n2);
sleep(1);
return 0;
}
|
C
|
#include "../include/buffer.h"
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
/* variables used at main() */
char *current_line;
int is_over = 0;
int chars_in_line = 0;
int line_count = 1;
/* prints error at stderr when line_length is bigger than col_limit */
void printerror(char* file_name, int error_line) {
fprintf(stderr, "center: %s: line %d: line too long.\n", file_name, error_line);
}
/* verifies if current_line is completely blank */
int allblank(char *current_line) {
char a = (unsigned char) *current_line;
while(1) {
a = (unsigned char) *current_line;
if (a == '\n' || a == EOF || *current_line == 0) break;
if (!isspace(a)) return 0;
current_line++;
}
return 1;
}
char *trimwhitespace(char *str) {
char *end;
/* trim leading spaces */
while(isspace((unsigned char)*str)) str++;
if (*str == 0)
return str;
/* trim trailing spaces */
end = str + strlen(str) - 1;
while(end > str && isspace((unsigned char)*end)) end--;
/* new null terminator */
*(end + 1) = 0;
return str;
}
int main (int argc, char** argv) {
Buffer *b = buffer_create(sizeof(char));
FILE* input_text = fopen(argv[1], "r");
FILE* output_file = fopen(argv[2], "w");
int col_limit = atoi(argv[3]);
int line_length = 0;
int greater_half = 0;
/* boolean that check if current and last lines are blank */
int curr_blank = 0;
int last_blank = 0;
while(!is_over) {
chars_in_line = read_line(input_text, b);
if (chars_in_line == 0) is_over = 1;
current_line = b->data;
current_line = trimwhitespace(current_line); /* trims whitespaces at beggining and end of the line */
line_length = strlen(current_line);
/* print error when line_length > col_limit */
if (line_length > col_limit) printerror(argv[1], line_count);
/* calculates the longer half so it centers the line with one extra space to the left if col_limit is odd */
if (col_limit % 2 == 1) greater_half = 1 + (col_limit/2);
else greater_half = col_limit/2;
/*
checks for blank lines
if two lines following lines are blank, does not print a second blank line
*/
curr_blank = allblank(current_line);
if (curr_blank == 0 || last_blank == 0) {
if (curr_blank == 1 && is_over) break;
fprintf (output_file,"%*s\n", greater_half + line_length / 2, current_line);
}
last_blank = curr_blank;
line_count++;
}
(void)argc; /* to avoid warning because of unused argument */
return 0;
}
|
C
|
#include <project.h>
UT_TEST(01_test_without_opt)
{
char *cmd;
cmd = "-1";
reset_sandbox();
sandbox_cmd("touch aaa bbb ccc");
UT_ASSERT(strequ(ft_ls(cmd), "aaa\nbbb\nccc\n"));
UT_ASSERT(strequ(ls(cmd), ft_ls(cmd)));
reset_sandbox();
sandbox_cmd("touch - file");
cmd = "-1 -- - file";
UT_ASSERT(strequ(ls(cmd), ft_ls(cmd)));
reset_sandbox();
sandbox_cmd("mkdir - dir");
cmd = "-1 -- - dir";
UT_ASSERT(strequ(ls(cmd), ft_ls(cmd)));
/*
printf("\n===== ls ========\n");
printf(ls(cmd));
printf("===== ft_ls =======\n");
printf(ft_ls(cmd));
printf("==================\n");
*/
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* columns.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kdrumm <kdrumm@student.42.us> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/05/05 16:19:31 by kdrumm #+# #+# */
/* Updated: 2017/05/05 16:34:25 by kdrumm ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_db.h"
void delete_column(t_table *t)
{
char *response;
int c;
response = ask_user("Which column would you like to delete?");
c = find_matching_column(t, response);
if (c == -1)
return ;
t->column_ids[c] = -1;
fill_with_zeros(t, c);
}
static int first_empty_column(t_table *t)
{
int i;
i = 0;
while (i < g_width)
{
if (t->column_ids[i] == 0 || t->column_ids[i] == -1)
return (i);
i++;
}
return (-1);
}
void fill_with_zeros(t_table *t, int c)
{
int r;
r = 0;
while (t->row_ids[r])
{
t->columns[c].content_array[r] = "0";
r++;
}
}
void add_column(t_table *t, char *name)
{
int index;
t_column *col;
index = first_empty_column(t);
if (index < 0)
{
ft_putstr("Columns are full\n");
return ;
}
t->column_ids[index] = id_gen_c(t);
col = &(t->columns[index]);
col->name = name;
col->content_array = (char **)malloc(sizeof(char *) * TABLE_SIZE);
fill_with_zeros(t, index);
}
|
C
|
#include "inc/StepperMotor.h"
//absolute_time_t abs_time;
uint64_t abs_time;
StepperMotor_t *stepperMotors[MAX_MOTOR_QUANTITY];
int motorsQuantity = 0;
/**
* Make one step in chosen direction.
* It is made by setting low state on CLK driver pin.
* @TODO Describe how to set STEP on stepper motor driver (include description to differ drivers)
*
* Possible imporovement -> make this function in separate parts, firstly put LOW state on the begining of the control loop, then
* set HIGH state at the end after waiting some us.
*/
void MakeStep(StepperMotor_t *motor)
{
gpio_put(motor->dirPin, motor->dir);
gpio_put(motor->stepPin, 0);
sleep_us(5);
gpio_put(motor->stepPin, 1);
}
/**
* Motor initialization.
* @TODO Describe what this inicializzation doing.
*/
void InitMotor(StepperMotor_t *motor, uint stepPin_, uint dirPin_, uint enPin_,
double current_, double nVoltage_, unsigned int revSteps_,
unsigned int microstep_, unsigned int decaySetting_, double nTorque_,
float gearRatio_)
{
motor->stepPin = stepPin_;
motor->dirPin = dirPin_;
motor->enPin = enPin_;
motor->current = current_;
motor->microstep = microstep_;
motor->decaySetting = decaySetting_;
motor->nVoltage = nVoltage_;
motor->nTorque = nTorque_;
motor->gearRatio = gearRatio_;
motor->revSteps = revSteps_;
motor->speed.deg = 0; //Set initial motor speed to 0 rad/s
motor->speed.rad = 0; //Set initial motor speed to 0 deg/s
motor->degPerStep = 360.0/(motor->revSteps * motor->gearRatio * motor->microstep); //Rotation of joint per one motor step.
motor->stepPerDeg = 1/motor->degPerStep; //Count of steps needed to rotate joint by one degree.
motor->radPerStep = (2*M_PI)/(motor->revSteps * motor->gearRatio * motor->microstep);
motor->stepPerRad = 1/motor->radPerStep;
motor->position.jointDeg = 0.0;
motor->position.jointRad = 0.0;
motor->position.shaftDeg = 0.0;
motor->position.shaftRad = 0.0;
motor->stepTime = 0;
motor->rotationMode = MOVE_CONTINOUSLY;
motor->dir = CLOCKWISE;
//Initialize stepper motor controler outputs
gpio_init(motor->stepPin); //Initialize gpio
gpio_init(motor->dirPin);
gpio_init(motor->enPin);
gpio_set_dir(motor->stepPin, GPIO_OUT); //Set gpio as outputs
gpio_set_dir(motor->dirPin, GPIO_OUT);
gpio_set_dir(motor->enPin, GPIO_OUT);
gpio_put(motor->stepPin, 0); //Set initial value to low
gpio_put(motor->dirPin, 0);
gpio_put(motor->enPin, 0);
SetMotorSpeedRad(motor, motor->speed.rad);
stepperMotors[motorsQuantity] = motor; //Add motor pointer to motors array
motorsQuantity ++;
}
/**
* Rotete stepper motor by given angle in degrees.
*/
void RotateMotor_angleDeg(StepperMotor_t *motor, double angleDeg, RotationDir_e dir)
{
unsigned int steps = GetStepsFromAngleDeg(angleDeg, motor->revSteps, motor->microstep);
motor->dir = dir;
for(int i = 0; i < steps; i++)
{
MakeStep(motor);
sleep_us(500);
}
}
/**
* Rotate stepper motor by given angle in radians.
*/
void RotateMotor_angleRad(StepperMotor_t *motor, double angleRad, RotationDir_e dir)
{
unsigned int steps = GetStepsFromAngleRad(angleRad, motor->revSteps, motor->microstep);
motor->dir = dir;
for(int i = 0; i < steps; i++)
{
MakeStep(motor);
sleep_us(500);
}
}
/**
* Rotate stepper motor by given steps count.
*/
void RotateMotor_steps(StepperMotor_t *motor, double steps, RotationDir_e dir)
{
motor->dir = dir;
for(int i = 0; i < steps; i ++)
{
MakeStep(motor);
sleep_us(500);
}
}
/**
* Get steps count from given angle in degrees.
*/
unsigned int GetStepsFromAngleDeg(double angleDeg, unsigned int revSteps, unsigned int microstep)
{
return ((angleDeg / 360) * revSteps * microstep);
}
/**
* Get steps count from given angle in radians.
*/
unsigned int GetStepsFromAngleRad(double angleRad, unsigned int revSteps, unsigned int microstep)
{
return ((angleRad / (2 * M_PI)) * revSteps * microstep);
}
/**
* Set stepper motor angular velocity [deg/s].
*/
void SetMotorSpeedDeg(StepperMotor_t *motor, double speed)
{
motor->speed.deg = speed;
motor->speed.rad = (speed / 360) * (2*M_PI);
motor->deltaT = (motor->degPerStep / motor->speed.deg) * 1000000;
}
/**
* Set stepper motor angular velocity [rad/s].
*/
void SetMotorSpeedRad(StepperMotor_t *motor, double speed)
{
motor->speed.rad = speed;
motor->speed.deg = (speed / 2*M_PI) * 360;
motor->deltaT = (motor->radPerStep / motor->speed.rad) * 1000000;
}
/**
* Function controling all defined motors.
* IMPORTANT: This function should be put in while loop or intrrupt callback,
* which is refreshed more often then every 10us(?).
*
* Function check which mode is set in which motor, and control motor rotation.
*/
void ControlLoop()
{
for(int i = 0; i < motorsQuantity; i++)
{
abs_time = time_us_64();
switch(stepperMotors[i]->rotationMode)
{
case MOVE_BY_ANGLE:
// Check the error (setAngle - actualAngle)
break;
case MOVE_CONTINOUSLY:
// Do not check the error and continously rotate the shaft.
if((abs_time - stepperMotors[i]->stepTime) >= stepperMotors[i]->deltaT)
{
MakeStep(stepperMotors[i]);
stepperMotors[i]->stepTime = abs_time;
UpdatePosAfterStep(stepperMotors[i]);
}
break;
case MOVE_FOR_TIME:
// Rotate motor shaft by given time in some variable in stepperMotor structure.
break;
case MOVE_TO_SET_VALUE:
/*
double error = stepperMotors[i]->setValue.deg - stepperMotors[i]->position.jointDeg;
if((abs_time - stepperMotors[i]->stepTime) >= stepperMotors[i]->deltaT)
{
}
*/
break;
case DISABLED:
// Do not move the motor shaft, keep torque on shaft.
break;
case DISABLED_NO_TORQUE:
// Do not move the motor shaft, do not keep torque on shaft.
break;
}
}
}
/**
* Update motor position, after every step.
*/
void UpdatePosAfterStep(StepperMotor_t *motor)
{
double degPerStep = motor->degPerStep;
double radPerStep = motor->radPerStep;
if(motor->dir == CLOCKWISE)
{
motor->position.jointDeg += degPerStep;
motor->position.jointRad += radPerStep;
motor->position.shaftDeg += degPerStep * motor->gearRatio;
motor->position.shaftRad += radPerStep * motor->gearRatio;
if(motor->position.jointDeg > 360.0)
{
motor->position.jointDeg -= 360.0;
motor->position.jointRad -= 2*M_PI;
}
if(motor->position.shaftDeg > 360.0)
{
motor->position.shaftDeg -= 360.0;
motor->position.shaftRad -= 2*M_PI;
}
}
else if(motor->dir == COUNTER_CLOCKWISE)
{
motor->position.jointDeg -= degPerStep;
motor->position.jointRad -= radPerStep;
motor->position.shaftDeg -= degPerStep * motor->gearRatio;
motor->position.shaftRad -= radPerStep * motor->gearRatio;
if(motor->position.jointDeg < 0.0)
{
motor->position.jointDeg += 360.0;
motor->position.jointRad += 2*M_PI;
}
if(motor->position.shaftDeg < 0.0)
{
motor->position.shaftDeg += 360.0;
motor->position.shaftRad += 2*M_PI;
}
}
}
/**
* Change rotate direction.
*/
void ChangeRotateDirection(StepperMotor_t *motor, RotationDir_e dir)
{
motor->dir = dir;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "arch/arch.h"
#include "arch/section.h"
#include "parsers.h"
#include "utils.h"
#include "simMips.h"
extern char* REG_NAMES[36];
int parse_hex_value(char* hex_str, uint* hex_value, uint hex_leng, int neg_flag)
{
uint i;
/* prevent new line bug */
if (sscanf(hex_str, "%s", hex_str) != 1)
return 0;
/* if str begins with 0x, shift it */
if (strlen(hex_str) > 1) {
if (*(hex_str) == '0' && *(hex_str+1) == 'x')
hex_str += 2;
}
if (*(hex_str) == '-') {
if (!neg_flag)
return 0;
else
i = 1;
} else {
i = 0;
}
if (strlen(hex_str) > hex_leng)
/* invalid address: 32 bits, 4 bytes, 8 hex chars */
return 0;
for (; i < strlen(hex_str); i++) {
if (!isxdigit(*(hex_str+i)))
return 0;
}
if (sscanf(hex_str, "%x", hex_value) != 1)
return 0;
return 1;
}
int parse_addr(char* addr_str, uint* addr)
{
/* 32 bits */
return parse_hex_value(addr_str, addr, 8, 0);
}
int parse_reg_value(char* reg_val_str, uint* reg_value)
{
/* 32 bits */
return parse_hex_value(reg_val_str, reg_value, 8, 1);
}
int parse_addr_value(char* addr_value_str, uint* addr_value)
{
/* legacy code, specs has changed since */
/* 8 bits */
/*return parse_hex_value(addr_value_str, (uint*) addr_value, 2);*/
/* 32 bits */
return parse_addr(addr_value_str, addr_value);
}
int parse_register(char* reg_str)
{
int reg_index = -1;
/* prevent new line bug */
if (sscanf(reg_str, "%s", reg_str) != 1)
return 0;
if (*reg_str == '$') {
/* + 1 char shift for the '$' character */
reg_str++;
}
if (strlen(reg_str) == 1 && isdigit(*reg_str)) {
return atoi(reg_str);
}
else if (strlen(reg_str) == 2 && isdigit(*reg_str) && isdigit(*(reg_str+1))) {
reg_index = atoi(reg_str);
if (reg_index < 36 && reg_index >= 0)
return atoi(reg_str);
else
return -1;
}
else {
for (int i = 0; i < 36; i++) {
if (strcmp(*(REG_NAMES+i), reg_str) == 0)
return i;
}
}
return reg_index;
}
void parse_token(char* delim, char* token, char** args, int* i)
{
char* str2;
char* subtoken;
for (str2 = token; ; str2 = NULL, (*i)++) {
if (!(subtoken = strtok(str2, delim)))
break;
*(args+*i) = subtoken;
*(args+*i+1) = delim;
}
swap_str(args+*i-1, args+*i);
}
int parse_args(struct command* cmd, char* str_arg, char** args)
{
char* str1;
char* token;
char* found_colon, *found_tild;
char* delim = " ";
int i;
for (i = 0, str1 = str_arg; i < MAX_ARGS - 1; str1 = NULL, i++) {
if (!(token = strtok(str1, delim)))
break;
*(args+i) = token;
/* case end of args when parsing file */
if (*(args+i)) {
if (strcmp("\n", *(args+i)) == 0) {
*(args+i) = NULL;
break;
}
}
/* search for additional args pattern */
if ((found_colon = strchr(token, ':')) && strlen(token) > 1)
parse_token(":", token, args, &i);
if ((found_tild = strchr(token, '~')) && strlen(token) > 1)
parse_token("~", token, args, &i);
}
/* check usage */
if (i < cmd->min || ( i > cmd->max && cmd->max != -1))
return 0;
return 1;
}
|
C
|
#include "volk.h"
#include <stdio.h>
int main() {
VkResult r = volkInitialize();
if (r == VK_SUCCESS){
uint32_t version = volkGetInstanceVersion();
printf("Vulkan version %d.%d.%d initialized.\n",
VK_VERSION_MAJOR(version),
VK_VERSION_MINOR(version),
VK_VERSION_PATCH(version)
);
}
return 0;
}
|
C
|
/*
* stm32dev_general.h
*
* Created on: 26-jul.-2015
* Author: Robbe
*/
#ifndef STM32DEV_INCLUDE_GENERAL_STM32DEV_GENERAL_H_
#define STM32DEV_INCLUDE_GENERAL_STM32DEV_GENERAL_H_
#include <stdio.h>
#include <math.h>
/* Macro's */
#define MAX(a,b) (((a)>(b))?(a):(b))
#define MIN(a,b) (((a)<(b))?(a):(b))
#define COUNTOF(__BUFFER__) (sizeof(__BUFFER__) / sizeof(*(__BUFFER__)))
/* Function prototypes */
void
stm32dev_general_convertToCapital(char* str);
char*
stm32dev_general_getDec(uint64_t dec);
char*
stm32dev_general_getDecSigned(int64_t dec);
uint32_t
stm32dev_general_getDecfromBCD(uint32_t bcd);
uint32_t
stm32dev_general_getBCDfromDec(uint16_t dec);
/* Structures */
typedef struct xypair_t{
uint8_t x;
uint8_t y;
}xypair_t;
typedef struct xycorners_t{
xypair_t topLeft;
xypair_t topRight;
xypair_t bottomLeft;
xypair_t bottomRight;
}xycorners_t;
#endif /* STM32DEV_INCLUDE_GENERAL_STM32DEV_GENERAL_H_ */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define NUM_TESTS 6
typedef struct
{
char* test_name;
char* input;
char* fake_server_params;
char* expected_result;
} Test;
static
const Test tests[NUM_TESTS] = {
{
"OkResponse",
"localhost 1234 abracadabra test",
"1234 send_good",
"client_id: test_client_id\nclient_type: 2002\nexpires_in: 3600\nuser_id: 101010\nusername: testuser@mail.ru\n"
},
{
"ErrorResponse",
"localhost 1234 abracadabra xxx",
"1234 send_bad",
"error: CUBE_OAUTH2_ERR_BAD_SCOPE\nmessage: bad scope\n"
},
{
"Server stop answering",
"localhost 1234 abracadabra test",
"1234 die",
"Unable to read response header\n"
},
{
"Not enough arguments",
"localhost 1234 abracadabra",
NULL,
"Not enough arguments\nUsage: cube hostname port token scope\n"
},
{
"Unknown host",
"unknownhost 1234 abracadabra test",
NULL,
"No such host\n"
},
{
"Server unavailable",
"localhost 1234 abracadabra test",
NULL,
"Connection error\n"
}
};
int main() {
FILE* fp;
FILE* sfp;
char buf[1024];
int i;
for (int i = 0; i < NUM_TESTS; ++i) {
char start_buf[100];
if (tests[i].fake_server_params) {
sprintf(start_buf, "./fake_server %s", tests[i].fake_server_params);
sfp = popen(start_buf, "w");
if (!sfp) {
printf("Failed to run tests\n");
exit(1);
}
//To be sure that server have started and ready to accept connections
sleep(1);
}
sprintf(start_buf, "./cube %s", tests[i].input);
fp = popen(start_buf, "r");
if (!fp) {
printf("Failed to run tests\n");
exit(1);
}
char* pos = buf;
int readed;
while (fgets(pos, sizeof(buf)-1, fp)) {
pos += strlen(pos);
}
if (!strcmp(buf, tests[i].expected_result)) {
printf("OK - TEST: %s - SUCCEEDED\n", tests[i].test_name);
} else {
printf("ERROR - TEST: %s - failed\n", tests[i].test_name);
printf("\tExpected: %s\n", tests[i].expected_result);
printf("\tGot: %s\n", buf);
}
pclose(fp);
if (tests[i].fake_server_params) {
pclose(sfp);
}
}
return 0;
}
|
C
|
#include "hsh.h"
/**
* main - run our shell!!!
* @argc: the arguments count
* @argv: the arguments passed in
* @env: the environment variables
* Return: depends, but it does the thing
*/
int main(int argc, char *argv[], char **env)
{
int history_count = 0;
int status;
pid_t fork_pid;
char *tokenized_input[MAX_ARGS] = {NULL};
char *stdoutval = malloc(256);
int char_count;
if (argc == 0)
exit(1);
do {
if (isatty(STDIN_FILENO))
promptuser(tokenized_input);
if (!isatty(STDIN_FILENO))
{
char_count = read(STDIN_FILENO, stdoutval, 256);
if (char_count > 0)
tokenize_str(tokenized_input, stdoutval, " ");
}
if (_strsareequal(tokenized_input[0], "exit"))
exit(0);
history_count++;
fork_pid = fork();
if (fork_pid == -1)
{
exit(1);
}
if (fork_pid == 0)
{
handleinput(argv[0], tokenized_input, env, history_count);
freedoublepointer(tokenized_input);
}
else
wait(&status);
} while (isatty(STDIN_FILENO));
return (0);
}
void freedoublepointer(char **freeablebuffs)
{
int idx = 0;
while(freeablebuffs[idx] != NULL)
{
free(freeablebuffs[idx++]);
}
}
/**
* promptuser - Prompt the user for input!
* @tokenized_input: the char** to place the tokenized input
*/
void promptuser(char **tokenized_input)
{
size_t BUFF_SIZE = 256;
char *buffer = malloc(BUFF_SIZE);
char *PROMPT = "$ ";
int char_input_count;
write(1, PROMPT, _strlen(PROMPT));
char_input_count = read(STDIN_FILENO, buffer, BUFF_SIZE);
if (char_input_count == -1)
{
printf("Bad input");
exit(1);
}
/* let's split the arguments into an array */
tokenize_str(tokenized_input, buffer, " ");
free(buffer);
}
/**
* handleinput - Take the commands and environ and act on it!
* @command: The command entered to run this shell
* @input: A tokenized array of the user input
* @environ: the environment variables
* @h_count: the history count so far
*/
void handleinput(char *command, char *input[], char *environ[], int h_count)
{
char *tokenized_paths[256] = {NULL};
char *found_path = NULL;
int idx = 0;
struct stat filestatus;
char *path_vars;
char *error;
if (input[0][0] == '/' || input[0][0] == '.')
{
if (execve(input[0], input, environ) == -1)
{
error = _strmcat(4, "-", command, ": ", input[0]);
perror(error);
free(error);
}
}
if (_strsareequal(input[0], "env"))
{
for (idx = 0; environ[idx] != NULL; idx++)
{
printf("%s\n", environ[idx]);
}
exit(0);
}
/* otherwise it must be a command */
/* try and run through the path and see if the command can be run */
path_vars = _findkeyvalue("PATH", environ);
tokenize_str(tokenized_paths, path_vars, ":");
while (tokenized_paths[idx] != NULL)
{
found_path = _strmcat(3, tokenized_paths[idx], "/", input[0]);
if (stat(found_path, &filestatus) == 0) /* file found!! */
{
if (execve(found_path, input, environ) == -1)
{
error = _strmcat(4, "-", command, ": ", input[0]);
perror(error);
free(error);
}
free(found_path);
}
idx++;
}
printf("%s: %d: %s: not found\n", command, h_count, input[0]);
}
/**
* tokenize_str - takes a string and splits it on some char into and array
* @ret: The place to put the tokenized strings
* @input: the string to tokenize
* @needle: the char we split the string on
*/
void tokenize_str(char *ret[], char *input, char *needle)
{
char *token;
int idx;
token = strtok(input, needle);
ret[0] = _strremovechar(token, '\n');
token = strtok(NULL, needle);
idx = 1;
while (token != NULL)
{
ret[idx] = _strremovechar(token, '\n');
token = strtok(NULL, needle);
idx++;
}
}
|
C
|
#include <stdio.h>
int main() {
int a, b;
int A, B, C;
scanf("%d %d", &a, &b);
A = b/100;
B = b/10;
C = b-B*10;
B = B-A*10;
printf("%d\n", a*C);
printf("%d\n", a*B);
printf("%d\n", a*A);
printf("%d\n", a*b);
return 0;
}
|
C
|
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include "kernel/tty.h"
const char *samplesource =
"size_t tty_print(const char *data)\n"
"{\n"
"\tsize_t len = 0;\n"
"\n"
"\twhile(data[len])\n"
"\t\ttty_putchar(data[len++]);\n"
"\n"
"\treturn len;\n"
"}\n"
;
void kernel_main(void)
{
tty_init();
tty_setcolor(VGA_WHITE, VGA_BLACK);
puts("Hello, World!");
for (size_t i = 0; i < 8; ++i) {
tty_setcolor(i, VGA_BLACK);
printf("Colored Text on Black\t");
tty_setcolor(VGA_BLACK, i);
printf("Black Text on Colored Background\t\n");
}
putchar('\n');
tty_setcolor(VGA_LIGHT_GREY, VGA_BLACK);
puts(samplesource);
printf("%x\n", 0xabcdf00f);
printf("%X\n", 0xabcdf00f);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define DICT_SIZE 15
#define WORD_LEN 10
#define LINE_LEN 18
#define ROWS 15
#define COLUMNS 15
#define TRUE 1
#define FALSE 0
#define start_column 0
#define start_row 1
#define end_column 2
#define end_row 3
int get_line_size(char *line) {
char *ch_iter = line; // so as not to lose beginning of line
int counter = 0;
// go until you see new line or null char
while(*ch_iter != '\n' && *ch_iter != '\0') {
ch_iter++; // next char
counter++; // increment counter
}
return counter;
}
void copy_string(char *source, char *destination) {
// get iterators over original pointers
char *src_iter = source;
char *dst_iter = destination;
// until null char
while (*src_iter != '\0') {
// copy pointers
*dst_iter = *src_iter;
// advance to next char
src_iter++;
dst_iter++;
}
// terminate string
*dst_iter = '\0';
}
void remove_newline(char *line) {
char *ch_iter = line;
// go until you see new line
while(*ch_iter != '\n') {
ch_iter++; // next char
}
*ch_iter = '\0'; // overwrite new line
}
void print_dictionary(char *dict[]) {
int i;
for(i = 0 ; i < DICT_SIZE ; i++) {
printf("%s\n", dict[i]);
}
}
void print_coord(int coord[DICT_SIZE][4]) {
int i, j;
for(i = 0 ; i < DICT_SIZE ; i++) {
for(j = 0 ; j < 4 ; j++) {
printf("%d ", coord[i][j]);
}
printf("\n");
}
}
/*BEFORE HOCAS FUNCTIONS*/
char get_letter();
void fill_puzzle(char puzzle[COLUMNS][ROWS]);
void print_puzzle(char puzzle[COLUMNS][ROWS]);
void setup(char puzzle[COLUMNS][ROWS], char *dict[DICT_SIZE], int coord[DICT_SIZE][4]);
int string_compare(char* string1, char* string2);
int string_length(char* string);
int guess_check(char* guess, int column_u, int row_u, char puzzle[COLUMNS][ROWS]);
void make_uppercase(char* guess, char *dict[DICT_SIZE]);
void reverse_string(char* string);
/*MAIN---MAIN---MAIN---MAIN---MAIN---MAIN---MAIN---MAIN---MAIN---MAIN---MAIN---MAIN---MAIN*/
int main(){
char guess[COLUMNS];
int column_u, row_u;
char game[15];
char check=0;/*checking a win condition*/
int counter=0;
srand(time(NULL));
int i,j;
char puzzle[COLUMNS][ROWS];
char *dict[DICT_SIZE];
int coord[DICT_SIZE][4];
char line[LINE_LEN];
FILE *fp = fopen("word_hunter.dat", "r");
int line_counter = 0;
int dict_counter = 0;
while(fgets(line, LINE_LEN, fp) != NULL) {
if(line_counter%5 == 0) {
dict[dict_counter] = (char*) malloc(sizeof(char) * get_line_size(line));
remove_newline(line);
copy_string(line, dict[dict_counter]);
} else if (line_counter%5 == 1){
coord[dict_counter][0] = atoi(line);
} else if (line_counter%5 == 2){
coord[dict_counter][1] = atoi(line);
} else if (line_counter%5 == 3){
coord[dict_counter][2] = atoi(line);
} else if (line_counter%5 == 4){
coord[dict_counter][3] = atoi(line);
dict_counter++;
}
line_counter++;
}
fclose(fp);
/*print_dictionary(dict);*/
/*print_coord(coord);*/
fill_puzzle(puzzle);/*filling it in with random values*/
setup(puzzle,dict,coord);
do{
print_puzzle(puzzle);
printf("Enter your guess: ");
scanf("%s%c",guess,&check);/*putting space here makes problems*/
if( check != '\n')
{
scanf("%s",game);/*cleaning the stdin stream at the same if not "game"*/
if(string_compare(guess,"exit") && string_compare(game,"game")) break;
else printf("Invalid input. Please enter only 1 word at a time\n");
}
else
{
do{
printf("\nEnter coordinates\n");
printf("Column and row respectively:");
scanf("%d %d", &column_u, &row_u);
if( (column_u<0 && column_u>=COLUMNS) || (row_u<0 && row_u>=ROWS) ) printf("Out of bounds! Enter a valid choice.\n");
}while( (column_u<0 && column_u>=COLUMNS) || (row_u<0 && row_u>=ROWS) );/*this condition is not working for some reason*/
if( guess_check(guess, column_u, row_u, puzzle) )
{
printf("Your guess is right!\n");
make_uppercase(guess,dict);
setup(puzzle, dict, coord);
counter++;
printf("Correctly guessed words %d/%d \n", counter, DICT_SIZE);
}
else
{
printf("Incorrect or already correctly guessed guess. Try again\n");
}
printf("\n");
}
}while(counter<DICT_SIZE);
// WRITE HERE...
printf("Congratulations! You have finished the WordHunter game!\n");
return 0;
}
char get_letter()
{
int range = ('z' - 'a') +1;/*+1 for modulus*/
char new_rand_char = 'a' + random()%range;
return new_rand_char;
}
void fill_puzzle(char puzzle[COLUMNS][ROWS])
{
int i,j;
for(i=0;i<COLUMNS;i++)
{
for(j=0;j<ROWS;j++)
{
puzzle[i][j] = get_letter();
}
}
}
void print_puzzle(char puzzle[COLUMNS][ROWS])
{
int i,j;
for(i=0;i<COLUMNS;i++)
{
for(j=0;j<ROWS;j++)
{
printf("%c ", puzzle[i][j]);
}
printf("\n");
}
}
void setup(char puzzle[COLUMNS][ROWS], char *dict[DICT_SIZE], int coord[DICT_SIZE][4])
{
int i,j,k,word_index = 0;
for(i=0;i<DICT_SIZE;i++)
{
if( coord[i][start_column] == coord[i][end_column] )/*horizontal*/
{
if(coord[i][start_row] < coord[i][end_row])/*left_to_right*/
{
for(j=coord[i][start_row]; j<=coord[i][end_row]; j++)
{
puzzle[coord[i][start_column]][j] = dict[i][word_index];
word_index++;
}
}
else/*right_to_left*/
{
/*when start row is smaller than end row*/
for(j=coord[i][start_row]; j>=coord[i][end_row]; j--)
{
puzzle[coord[i][start_column]][j] = dict[i][word_index];
word_index++;
}
}
word_index=0;
}
else if(coord[i][start_row] == coord[i][end_row])/*vertical*/
{
if(coord[i][start_column] < coord[i][end_column])/*up-down*/
{
for(j=coord[i][start_column]; j<=coord[i][end_column]; j++)
{
puzzle[j][coord[i][start_row]] = dict[i][word_index];
word_index++;
}
}
else/*down-up*/
{
for(j=coord[i][start_column]; j>=coord[i][end_column]; j--)
{
puzzle[j][coord[i][start_row]] = dict[i][word_index];
word_index++;
}
}
word_index=0;
}
else/*diagonal ones*/
{
if(coord[i][start_column]<coord[i][end_column])/*up-down*/
{
if(coord[i][start_row]<coord[i][end_row])/*left_to_right*/
{
k=coord[i][start_row];
for(j=coord[i][start_column];j<=coord[i][end_column];j++)
{
puzzle[j][k]=dict[i][word_index];
word_index++;
k++;
}
}
else/*right_to_left*/
{
k=coord[i][start_row];
for(j=coord[i][start_column];j<=coord[i][end_column];j++)
{
puzzle[j][k]=dict[i][word_index];
word_index++;
k--;
}
}
word_index=0;
}
else/*down-up*/
{
if(coord[i][start_row]<coord[i][end_row])/*left_to_right*/
{
k=coord[i][start_row];
for(j=coord[i][start_column];j>=coord[i][end_column];j--)
{
puzzle[j][k]=dict[i][word_index];
word_index++;
k++;
}
}
else/*right_to_left*/
{
k=coord[i][start_row];
for(j=coord[i][start_column];j>=coord[i][end_column];j--)
{
puzzle[j][k]=dict[i][word_index];
word_index++;
k--;
}
}
word_index=0;
}
}
/*did for the same rows and columns continue for diagonals only*/
}
}
int string_compare(char* string1, char* string2)
{
int res=FALSE;
int i;
int string1_length = string_length(string1);
int string2_length = string_length(string2);
if(string1_length == string2_length)
{
res = TRUE;
for(i=0; i<string1_length; i++)
{
if(string1[i]!=string2[i])
{
res = FALSE;
break;
}
}
}
return res;
}
int string_length(char* string)
{
int i;
for(i = 0; string[i]!= 0 && string[i]!='\r' ; i++);/*second condition used because carriage return left in every word of the dictionary*/
return i;
}
int guess_check(char* guess, int column_u, int row_u, char puzzle[COLUMNS][ROWS])
{
int i,j;
int word_index=0;
int res = FALSE;
int flag=0, reversed_flag=0;
int guess_length = string_length(guess);
if(guess[0]==puzzle[column_u][row_u] || guess[guess_length-1]==puzzle[column_u][row_u])/*in regular order*/
{
if(guess[guess_length-1]==puzzle[column_u][row_u])
{
reverse_string(guess);/*setting it up for checking*/
reversed_flag=1;
}
if ( (row_u+guess_length-1 < ROWS) && res==FALSE)/*east*//*&& (puzzle[column_u][row_u+guess_length-1]==guess[] can also be put here for better efficiency, and also in all the following parts*/
{
for(i=row_u, word_index=0; i<row_u+guess_length;i++, word_index++)
{
if(puzzle[column_u][i] != guess[word_index])
{
flag = 1;
break;
}
}
if(flag==0) res = TRUE;
flag = 0;/*updating the flag if it changed*/
}
if( (row_u-guess_length+1 >= 0) && res==FALSE )/*west*/
{
for(i=row_u, word_index=0; i>=row_u-guess_length+1; i--, word_index++)
{
if(puzzle[column_u][i] != guess[word_index])
{
flag = 1;
break;
}
}
if(flag==0)res = TRUE;
flag = 0;
}
if( (column_u+guess_length-1 <COLUMNS) && res==FALSE )/*south*/
{
for(i=column_u, word_index=0; i<column_u+guess_length; i++, word_index++)
{
if(puzzle[i][row_u]!=guess[word_index])
{
flag = 1;
break;
}
}
if(flag==0) res = TRUE;
flag = 0;
}
if( (column_u-guess_length+1>=0) && res==FALSE )/*north*/
{
for(i=column_u, word_index=0; i>=column_u-guess_length+1;i--, word_index++)
{
if(puzzle[i][row_u] != guess[word_index])
{
flag = 1;
break;
}
}
if(flag==0) res=TRUE;
flag = 0;
}
/*diagonal ones left*/
if(row_u+guess_length-1<ROWS && column_u+guess_length-1<COLUMNS && res==FALSE)/*south_east*/
{
for(i=column_u,j=row_u,word_index=0;i<column_u+guess_length;i++,j++,word_index++)
{
if(puzzle[i][j]!=guess[word_index])
{
flag = 1;
break;
}
}
if(flag==0) res = TRUE;
flag = 0;
}
if(row_u-guess_length+1>=0 && column_u+guess_length-1<COLUMNS && res==FALSE)/*south_west*/
{
for(i=column_u,j=row_u,word_index=0;i<column_u+guess_length;i++,j--,word_index++)
{
if(puzzle[i][j]!=guess[word_index])
{
flag = 1;
break;
}
}
if(flag==0) res = TRUE;
flag = 0;
}
if(row_u-guess_length+1>=0 && column_u-guess_length+1>=0 && res == FALSE)/*north_west*/
{
for( i=column_u, j=row_u, word_index=0;i>=column_u-guess_length+1;i--,j--,word_index++)
{
if(puzzle[i][j]!=guess[word_index])
{
flag = 1;
break;
}
}
if(flag==0) res = TRUE;
flag = 0;
}
if(row_u+guess_length-1 < ROWS && column_u-guess_length+1>=0 && res==FALSE)/*north_east*/
{
for( i=column_u, j=row_u, word_index=0; i>=column_u-guess_length+1; i--,j++,word_index++)
{
if(puzzle[i][j]!=guess[word_index])
{
flag = 1;
break;
}
}
if(flag==0) res = TRUE;
flag = 0;
}
}
if(guess[0]==puzzle[column_u][row_u] && guess[guess_length-1]==puzzle[column_u][row_u] && res == FALSE)/*meaning both last and the first letter are the same so it would need to check twice and if any one of them is correct than this is correct*/
{
res = guess_check( guess, column_u, row_u, puzzle );/*if first and last letter the same guess already reversed so now just checking for the other way around*/
/*this function will again reverse this string to original state and than because of the reverse_string in the 439th line reverse it again in the state it was when it was sent to this function meaning that after this function is executed guess will still be reversed because it was sent reversed*/
}
if(reversed_flag==1) reverse_string(guess);/*putting it back in its original state*/
/*putting it back in its original state is important since the table needs to be updated according to it*/
return res;
}
void make_uppercase(char* guess, char *dict[DICT_SIZE])/*this function also ensures user from guessing the same word twice*/
{
int index,i;
for(index=0;index<DICT_SIZE;index++)
{
if( string_compare(guess, dict[index])==TRUE )
{
for(i=0; dict[index][i]!=0 && dict[index][i]!='\r'; i++) dict[index][i] -= 32;/*from lowercase to uppercase*/
}
}
}
void reverse_string(char* string)
{
int i;
int length = string_length(string);
char temp;
for(i=0; i<length/2; i++)
{
temp = string[i];
string[i]=string[length-i-1];
string[length-i-1]=temp;
}
return;
}
|
C
|
#ifndef HOLBERTON_H
#define HOLBERTON_H
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
/**
* struct op - Struct op
*
* @op: The operator
* @f: The function associated
*/
typedef struct op
{
char *op;
void (*f)(va_list valist);
} op_t;
int _putchar(char c);
int sum_them_all(const unsigned int n, ...);
void print_numbers(const char *separator, const unsigned int n, ...);
void print_strings(const char *separator, const unsigned int n, ...);
void print_all(const char * const format, ...);
#endif /* HOLBERTON_H */
|
C
|
/*
* autor: cristobal liendo
* fecha: 17/1/18
* descripcion: pide "n" cantidad de numeros distinots de cero, imprime los numeros
* y termina con el valor de 0. se despliega la cantidad de valores
* leidos
* (el ejercicio no dice cuantos numeros se van a introducir, he ahi
* la eleccion de single linked-lists)
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct node_t {
int data;
struct node_t *next;
} node_t;
node_t *insert(int data, node_t **head);
void print_list(node_t *head);
void free_list(node_t **head);
int main() {
node_t *head = NULL;
int number, total = 0;
printf("Ingresa los numeros a guardar, para terminar ingresa el numero 0:\n");
do {
printf("Numero: ");
scanf("%d", &number);
if (number != 0) {
total++;
insert(number, &head);
}
} while (number != 0);
printf("\nNumeros almacenados:\n");
print_list(head);
free_list(&head);
printf("\nTotal: %d\n", total);
return 0;
}
node_t *insert(int data, node_t **head) {
node_t *new_node = malloc(sizeof(node_t));
if (new_node == NULL) {
printf("Error de memoria. Abortando.\n");
exit(0);
}
new_node->data = data;
new_node->next = *head;
*head = new_node;
return new_node;
}
void print_list(node_t *head) {
node_t *current = head;
while (current != NULL) {
printf("Numero: %d\n", current->data);
current = current->next;
}
}
void free_list(node_t **head) {
node_t *next = *head;
while (next != NULL) {
next = (*head)->next;
free(*head);
*head = next;
}
}
|
C
|
# include <stdio.h>
typedef struct {
int x, y;
} Coo;
# define now [now.x][now.y]
int main(void){
int net[10][10] = {0};
net[5][5] = 1;
Coo now = {5, 5}
printf("%d\n", net[now]);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <signal.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#define BUFF_SIZE 100
static volatile int run_flag = 1;
void sig_handler(int sig)
{
run_flag = 0;
}
int main(int argc, char** argv)
{
signal(SIGINT, sig_handler);
if(argc != 2)
{
printf("Error: incorrect number of arguments\n");
exit(1);
}
char *username = argv[1];
char *cmd = (char*) malloc(sizeof(char)*BUFF_SIZE);
char *dir = (char*) malloc(sizeof(char)*BUFF_SIZE);
char *lineptr = (char*)malloc(sizeof(char)*BUFF_SIZE);
size_t len = 0;
FILE *fp;
sprintf(dir,"%s_trash",username);
mkdir(dir, 0777);
while(run_flag)
{
sprintf(cmd,"ls test_%s_*.csv > filename_list.txt", username);
system(cmd);
printf("Generated filename_list.txt\n");
sleep(1);
fp = fopen("filename_list.txt", "r");
if(fp==NULL)
fprintf(stderr,"ERROR: Failed opening\n");
else{
printf("Successfully opened.\n");
fprintf(stdout, "\tReading file contents:\n");
while(getline(&lineptr,&len,fp) != -1)
{
fprintf(stdout, "%s",lineptr);
lineptr[strlen(lineptr)-1] = '\0';
sprintf(cmd,"mv %s %s/%s",lineptr,dir,lineptr);
system(cmd);
}
sleep(2);
}
fclose(fp);
}
exit(0);
}
|
C
|
#include <stdio.h>
#include <gmp.h>
char *prog;
typedef struct elliptic_curve_t
{
mpz_t A,B,p;
} elliptic_curve;
typedef struct point_t
{
mpz_t x,y;
} point;
void elliptic_curve_init(elliptic_curve* e)
{
mpz_init(e->A);
mpz_init(e->B);
mpz_init(e->p);
}
void point_init(point* p)
{
mpz_init(p->x);
mpz_init(p->y);
}
int is_Singular(elliptic_curve e)
{
// Check condition
mpz_t a3, b2;
mpz_init(a3);
mpz_init(b2);
mpz_powm_ui(a3 , e.A , 3, e.p);
mpz_powm_ui(b2 , e.B , 2 , e.p);
mpz_mul_ui(a3 , a3 , 4);
mpz_addmul_ui(a3 , b2 , 27);
mpz_mod(a3 , a3 , e.p);
if(mpz_sgn(a3))
return 0;
return 1;
}
void generate_random_seed(mpz_t seed)
{
__uint8_t input[20];
FILE *fp;
if((fp = fopen("/dev/urandom","r")) == NULL)
{
fprintf(stderr, "%s: can't read /dev/urandom \n", prog);
}
else
{
for(int i = 0; i < 19; i++)
{
input[i] = getc(fp);
}
mpz_import(seed, sizeof(input), 1, sizeof(input[0]), 0, 0, input);
}
}
void generate_random_number(mpz_t x, int num_bits)
{
gmp_randstate_t state;
gmp_randinit_default(state);
mpz_t seed;
mpz_init(seed);
generate_random_seed(seed);
gmp_randseed(state, seed);
mpz_urandomb(x, state , num_bits);
gmp_randclear(state);
}
void elliptic_curve_random_generate(elliptic_curve* e, int n) // n = number of bits
{
// Randomly choose a prime p
mpz_t p;
mpz_init(p);
int val = 0;
// while(val != 2){
// generate_random_number(p, n);
// val = mpz_probab_prime_p(p, 40);
// }
generate_random_number(p, n);
int cnt = 0;
while(1){
val = mpz_probab_prime_p(p, 40);
if(val >= 1){
break;
}
if(mpz_even_p(p)){
mpz_add_ui(p, p, 1);
//printf("1\n");
}else{
mpz_add_ui(p, p, 2);
//printf("2\n");
}
}
mpz_out_str(stdout,10,p);
mpz_set(e->p, p);
printf("\n");
mpz_t A, B;
mpz_init(A);
mpz_init(B);
do{
// Randomly choose A
generate_random_number(A, n);
// Randomly choose B
generate_random_number(B, n);
mpz_set(e->A, A);
mpz_set(e->B, B);
}while(is_Singular(*e));
return ;
}
void slope(elliptic_curve e, point p1, point p2 , mpz_t lambda)
{
mpz_t temp;
mpz_init(temp);
if(mpz_cmp(p1.x , p2.x) == 0 && mpz_cmp(p1.y , p2.y) == 0)
{
mpz_powm_ui(lambda , p1.x , 2 , e.p);
mpz_mul_ui(lambda , lambda , 3);
mpz_add(lambda , lambda , e.A);
mpz_mod(lambda , lambda , e.p);
mpz_mul_ui(temp , p1.y , 2);
mpz_mod(temp , temp , e.p);
mpz_invert(temp , temp , e.p);
mpz_mul(lambda , lambda , temp);
mpz_mod(lambda , lambda , e.p);
return ;
}
mpz_sub(temp , p2.x , p1.x);
mpz_mod(temp , temp , e.p);
mpz_invert(lambda, temp , e.p);
mpz_sub(temp , p2.y , p1.y);
mpz_mod(temp , temp , e.p);
mpz_mul(lambda , lambda , temp);
mpz_mod(lambda , lambda , e.p);
return ;
}
point elliptic_curve_operation(elliptic_curve e, point p1, point p2) // operation = addition
{
point result;
point_init(&result);
mpz_mod(p1.x , p1.x , e.p);
mpz_mod(p1.y , p1.y , e.p);
mpz_mod(p2.x , p2.x , e.p);
mpz_mod(p2.y , p2.y , e.p);
mpz_t temp;
mpz_init(temp);
mpz_add(temp , p1.y , p2.y);
mpz_mod(temp ,temp , e.p);
if(mpz_cmp(p1.x , p2.x) == 0 && mpz_sgn(temp) == 0)
{
mpz_set_str(result.x , "0", 10);
mpz_set_str(result.y , "0", 10);
return result;
}
mpz_t lambda, lambda_squared;
mpz_init(lambda);
mpz_init(lambda_squared);
slope(e, p1, p2 , lambda);
mpz_powm_ui(lambda_squared , lambda, 2 , e.p);
mpz_sub(result.x , lambda_squared , p1.x);
mpz_sub(result.x , result.x , p2.x);
mpz_mod(result.x , result.x , e.p);
mpz_sub(result.y , p1.x, result.x);
mpz_mul(result.y , result.y , lambda);
mpz_sub(result.y , result.y , p1.y);
mpz_mod(result.y , result.y , e.p);
return result;
}
int main(int argc, char *argv[])
{
prog = argv[0];
elliptic_curve e1,e2;
int num_bits;
printf("Enter number of bits: ");
scanf("%d", &num_bits);
elliptic_curve_init(&e1);
elliptic_curve_init(&e2);
elliptic_curve_random_generate(&e1, num_bits);
point p1, p2, p3;
point_init(&p1);
point_init(&p2);
point_init(&p3);
mpz_set_str(e2.A , "1" , 10);
mpz_set_str(e2.B , "6" , 10);
mpz_set_str(e2.p , "11" , 10);
mpz_set_str(p1.x , "2" , 10);
mpz_set_str(p1.y , "7" , 10);
mpz_set_str(p2.x , "2" , 10);
mpz_set_str(p2.y , "7" , 10);
printf("\n");
for(int i = 0 ; i < 12 ; i++)
{
printf("Point %d :\n" , i+1);
p3 = elliptic_curve_operation(e2 , p1 , p2);
mpz_out_str(stdout,10,p3.x);
printf("\n");
mpz_out_str(stdout,10,p3.y);
printf("\n\n");
p2 = p3;
}
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2018
** setup_shape.c
** File description:
** setup shape functions
*/
#include "my_radar.h"
sfRectangleShape *create_rectangle_entity(s_plane_t plane)
{
sfRectangleShape *rec = sfRectangleShape_create();
sfVector2f size = {40, 40};
sfVector2f origin = {20, 20};
sfRectangleShape_setSize(rec, size);
sfRectangleShape_setOutlineThickness(rec, 2);
sfRectangleShape_setOutlineColor(rec, sfCyan);
sfRectangleShape_setTexture(rec, plane.texture, sfTrue);
sfRectangleShape_setOrigin(rec, origin);
sfRectangleShape_setRotation(rec, init_rotate(plane.pos, plane.end));
sfRectangleShape_setPosition(rec, plane.pos);
return (rec);
}
sfCircleShape *create_circle_entity(s_tower_t tower, float radius)
{
sfCircleShape *shape = sfCircleShape_create();
sfVector2f origin = {radius * 10, 10 * radius};
sfCircleShape_setRadius(shape, 10 * radius);
sfCircleShape_setOutlineThickness(shape, 2);
sfCircleShape_setOutlineColor(shape, sfGreen);
sfCircleShape_setTexture(shape, tower.texture, sfTrue);
sfCircleShape_setOrigin(shape, origin);
sfCircleShape_setPosition(shape, tower.pos);
return (shape);
}
sfConvexShape *create_convex_entity(s_area_t area)
{
sfConvexShape *shape = sfConvexShape_create();
sfConvexShape_setPointCount(shape, area.point_count);
for (int i =0; i < area.point_count; i++)
sfConvexShape_setPoint(shape, i, area.points[i]);
sfConvexShape_setOutlineThickness(shape, 2);
sfConvexShape_setOutlineColor(shape, sfYellow);
sfConvexShape_setTexture(shape, area.texture, sfTrue);
return (shape);
}
|
C
|
/******************************************************************************/
/* 100k Threads */
/* Description - Handling threads for the first time */
/* Author - Dean Oron */
/* Date - 02.05.20 */
/* Reviewer - Amir SAraf */
/* Open Lab 86 */
/******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <ulimit.h>
#define SIZE (100000)
void *MyThread(void *index);
void PrintArr(int *arr);
int global_arr[SIZE];
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int main()
{
int i = 0;
int status = 1;
pthread_t thread;
for (i = 0; i < SIZE; ++i)
{
status = pthread_create(&thread, NULL, MyThread, &i);
while(status != 0)
{
status = pthread_create(&thread, NULL, MyThread, &i);
printf("keep try %d\n", status);
}
/*pthread_join(thread, NULL);*/
printf("create returns %d\n", status);
}
sleep (1);
PrintArr(global_arr);
return (0);
}
void *MyThread(void *index)
{
int *i = (int *)index;
pthread_detach(pthread_self()); /* for exercise 3 */
printf("the index is %d \n", *i);
global_arr[*i] = *i;
return NULL;
}
void PrintArr(int *arr)
{
int i = 0;
for(i = 0; i < SIZE; ++i)
{
sleep(0.1);
printf("%d\n", arr[i]);
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <malloc.h>
typedef struct{
char nama[50];
float nilai;
}nilaiMatKul;
typedef struct elm *alamatelmt;
typedef struct elm{
nilaiMatKul kontainer;
alamatelmt next;
}elemen;
typedef struct{
elemen *first;
elemen *last;
}queue;
void createEmpty(queue *Q);
int isEmpty(queue Q);
int countElement(queue Q);
void add(char nama[], float nilai, queue *Q);
void addPriority(char nama[], float nilai, int prior, queue *Q);
void del(queue *Q1, queue *Q2);
void printQueue(queue Q, int number);
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
#include <string.h>
#define BUFFER_MAX_SIZE 1000
/*
Create hashtable of word freaquency from text file. The words will be
stripped off punctuations specified in delim.
Parameters: table: pointer to Glib hashtable that stores word frequency
filename: char string that represents file name to read from
*/
void create_hashtable_from_file(GHashTable **table, char *filename) {
FILE *text;
gchar word[BUFFER_MAX_SIZE];
gchar *delim = " \n,.;:()'/\"";
gchar *sub = "";
gpointer value;
text = fopen(filename, "r");
if (!text) {
exit(1);
}
while (fscanf(text, "%1000s", word) == 1) {
gchar *key = g_strdelimit(word, delim, *sub);
value = g_hash_table_lookup(*table, key);
if (value) {
gpointer new_value = GINT_TO_POINTER(GPOINTER_TO_INT(value) + 1);
g_hash_table_insert(*table, g_strdup(key), new_value);
} else {
g_hash_table_insert(*table, g_strdup(key), GINT_TO_POINTER(1));
}
}
fclose(text);
}
/*
Print out frequency of each word on stdout
Parameters: key: word that appears in the text file
value: number of times that the word appears
user_data: unused data field for GHFunc declaration
*/
void print_word_count(gpointer key, gpointer value, gpointer user_data) {
printf("%s: %d\n", (char *)key, GPOINTER_TO_INT(value));
}
/*
Main body of the program.
Creates a hashtable from input text, and then displays the word count from
hashtable on stdout.
*/
int main() {
GHashTable *table = g_hash_table_new(g_str_hash, g_str_equal);
char *filename = "alice_in_wonderland.txt";
create_hashtable_from_file(&table, filename);
g_hash_table_foreach(table, print_word_count, NULL);
return 0;
}
|
C
|
#include "stack.h"
#define RED "\033[31m"
#define GREEN "\033[32m"
#define YELLOW "\033[33m"
#define BLUE "\033[34m"
#define MAGENTA "\033[35m"
#define CYAN "\033[36m"
#define WHITE "\033[37m"
#define RESET "\033[m"
static void put_colorval(int val, t_op op)
{
if (op == sa || op == sb || op == ss)
ft_putstr_fd(BLUE, 2);
else if (op == pa || op == pb)
ft_putstr_fd(YELLOW, 2);
else if (op == ra || op == rb || op == rr)
ft_putstr_fd(GREEN, 2);
else if (op == rra || op == rrb || op == rrr)
ft_putstr_fd(RED, 2);
ft_putnbr_fd(val, 2);
ft_putstr_fd(RESET, 2);
}
static t_stack *put_first_two(t_stack **s, t_op op)
{
t_stack *s_ptr;
s_ptr = *s;
if (s_ptr == NULL)
return (NULL);
if (op == sa || op == sb || op == ss || op == pa || op == pb
|| op == rra || op == rrb || op == rrr)
put_colorval(s_ptr->val, op);
else
ft_putnbr_fd(s_ptr->val, 2);
if (s_ptr->next != *s)
ft_putstr_fd(", ", 2);
s_ptr = s_ptr->next;
if (s_ptr == *s)
return (NULL);
if (op == sa || op == sb || op == ss
|| (s_ptr->next == *s && (op == ra || op == rb || op == rr)))
put_colorval(s_ptr->val, op);
else
ft_putnbr_fd(s_ptr->val, 2);
if (s_ptr->next != *s)
ft_putstr_fd(", ", 2);
if (s_ptr->next == *s)
return (NULL);
return (s_ptr->next);
}
static void put_lastval(int val, t_op op)
{
if (op == ra || op == rb || op == rr)
put_colorval(val, op);
else
ft_putnbr_fd(val, 2);
return ;
}
static void print_color_stack(t_stack **s, t_op op)
{
t_stack *s_ptr;
ft_putchar_fd('[', 2);
s_ptr = put_first_two(s, op);
while (s_ptr)
{
if (s_ptr->next == *s)
put_lastval(s_ptr->val, op);
else
ft_putnbr_fd(s_ptr->val, 2);
if (s_ptr->next != *s)
ft_putstr_fd(", ", 2);
s_ptr = s_ptr->next;
if (s_ptr == *s)
break ;
}
ft_putstr_fd("]\n", 2);
}
void print_color_stacks(t_stack **a, t_stack **b, t_op op)
{
if (op == sa || op == ss || op == pa || op == ra || op == rr
|| op == rra || op == rrr)
print_color_stack(a, op);
else
print_stack(a);
if (op == sb || op == ss || op == pb || op == rb || op == rr
|| op == rrb || op == rrr)
print_color_stack(b, op);
else
print_stack(b);
return ;
}
|
C
|
#include <stdio.h>
#define INFO1(a) \
{ \
printf(a); \
}
#define INFO2(a,b) \
{ \
printf(a); \
printf(b); \
}
#define GET_INFO_MACRO(_0,_1,NAME,...) NAME
#define INFO(...) GET_INFO_MACRO(__VA_ARGS__, INFO2, INFO1) (__VA_ARGS__)
int main(int argc, char **argv)
{
INFO("info1\n");
INFO("info2a\n", "info2b\n");
}
|
C
|
#include<stdio.h>
#include<string.h>
int main()
{
char a[20], b[20] = { 0 };
int i, j, k, count, n;
count = 0;
k = 0;
scanf("%s", a);
n = strlen(a);
for (i = 0; i < n; i++)
{
j = i;
while (a[j] == a[i])
{
count++;
j++;
}
if (count > 1)
{
b[k] = count + '0';
b[++k] = a[i];
}
else
b[k] = a[i];
k++;
count = 0;
i = j - 1;
}
printf("%s", b);
return 0;
}
|
C
|
// An emirp (prime spelled backwards) is a prime number that results in a different prime when its decimal digits are reversed.
// More details about emirps can be found at: https://en.wikipedia.org/wiki/Emirp
// This question was asked to me in Zoho Programming Round 2. Hope you find it useful!
#include<stdio.h>
#include<conio.h>
int p=-1, b[500], a[500];
void gen_prime(int start, int end) {
int i, j;
for(i=start;i<=end;i++) {
for(j=2;j<=i/2;j++) {
if(i%j == 0) {
break;
}
}
if(j==i/2+1) {
// printf("\nprime no: %d",i);
a[++p]=i;
}
}
}
int reverse(int n) {
int d, new_no = 0;
while(n>0) {
d=n%10;
new_no=new_no*10 + d;
n/=10;
}
return new_no;
}
void print_arr(int arr[], int p) {
int i;
for(i=0;i<=p;i++) {
printf("%d\t", arr[i]);
}
}
int check_prime(int n) {
int i;
for(i=2;i<=n/2;i++) {
if(n%i == 0) {
break;
}
}
if(i==n/2+1) {
// printf("%d\t",n);
return 1;
} else {
return 0;
}
}
void main() {
int c_ptr=-1, b_ptr=-1, is_prime, c[500], i, j, check, n,new_no;
clrscr();
printf("\nenter N: ");
scanf("%d",&n);
gen_prime(13, n);
// printf("\na array elements: \n");
// print_arr(a,p);
for(i=0;i<=p;i++) {
new_no=reverse(a[i]);
if(new_no != a[i]) {
is_prime = check_prime(new_no);
if(is_prime == 1) {
c[++c_ptr]=a[i];
}
}
b[++b_ptr]=new_no;
}
//printf("\nb array eles: \n");
//print_arr(b,b_ptr);
printf("\nemirps are: \n");
print_arr(c,c_ptr);
printf("\n\nHit some key to exit...");
getch();
}
|
C
|
/**
* In this main function, the functionalities
* of the implemntation file are used to read/
* write a file reveresed.
*
* @author Jamie Penzien
*/
#include "file_utils.h"
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char** argv ) {
//Visual display that the program has begun
printf("================================================================================\n");
printf("\t\t\tWelcome to the file reversal program.\n");
printf("================================================================================\n");
//Creating variables that will be used with the functions
char *buffer;
char *filename1;
char *filename2;
int filesize;
//The readable file will be the first command line argument after calling the program
filename1 = argv[1];
//The writable file will be the second command line argument after calling the program
filename2 = argv[2];
//The size of the file will be returned from the read_file function
//The buffer will be loaded with the contents of the first file
filesize = read_file( filename1, &buffer );
//Using the contents of the buffer, that info will be written backwards
//into the second file
write_file( filename2, buffer, filesize );
//notifying the use the program has ended
printf("\n================================================================================\n");
printf("\t\t\t\t\tDone\n");
return 0;
}
|
C
|
#include "changes.h"
#include "checksums.h"
#include <string.h>
#include <stdio.h>
#define MAX_ERROR 1000000.0
bool is_valid_barcode(char *digits)
{
if (digits[0] < 0 || digits[0] > 9)
return false;
return digits[12] == ean13_checksum(digits);
}
float best_valid_barcode(const Change *changes, int max_changes,
char *digits)
{
if (is_valid_barcode(digits))
return 0.0;
float best_error = MAX_ERROR;
char best_digits[13];
memcpy(best_digits, digits, 13);
char attempt[13];
for (int i = 0; changes[i].index >= 0; i++) {
memcpy(attempt, digits, 13);
attempt[changes[i].index] = changes[i].digit;
if (changes[i].index >= 2 && changes[i].index <= 6)
attempt[0] = ean13_first_digit(attempt);
float error = changes[i].error;
if (max_changes > 1)
error +=
best_valid_barcode(&changes[i + 1], max_changes - 1,
attempt);
else if (!is_valid_barcode(attempt))
continue;
if (error < best_error) {
best_error = error;
memcpy(best_digits, attempt, 13);
// printf("best_error=%.6f\n", best_error);
}
}
memcpy(digits, best_digits, 13);
return best_error;
}
|
C
|
#include "List.h"
List* List_create() {
List* this = malloc(sizeof(List));
this->first = NULL;
this->last = NULL;
return this;
}
void List_destroy(List* this) {
ListNode* it = this->first;
while (it) {
ListNode* next = it->next;
ListNode_destroy(it);
it = next;
}
free(this);
}
void List_pushBack(List* this, void* data) {
ListNode* newNode = ListNode_create(this->last, data);
if (!this->first) {
this->first = newNode;
}
this->last = newNode;
}
void List_pushFront(List* this, void* data) {
ListNode* newNode = ListNode_create(NULL, data);
newNode->next = this->first;
if (!this->last) {
this->last = newNode;
}
this->first = newNode;
}
void List_eraseByData(List* this, void* data) {
ListNode* it = this->first;
while (it) {
if (it->data == data) {
if (it->previous) {
it->previous->next = it->next;
}
if (it->next) {
it->next->previous = it->previous;
}
if (it == this->first) {
this->first = it->next;
}
if (it == this->last) {
this->last = it->previous;
}
ListNode_destroy(it);
return;
}
it = it->next;
}
}
int List_getIndexForData(List* this, void* data) {
int i = 0;
ListNode* it = this->first;
while (it) {
if (it->data == data) {
return i;
}
++i;
it = it->next;
}
return -1;
}
ListNode* List_getNodeForData(List* this, void* data) {
ListNode* it = this->first;
while (it) {
if (it->data == data) {
return it;
}
it = it->next;
}
return NULL;
}
ListNode* ListNode_create(ListNode* previous, void* data) {
ListNode* this = malloc(sizeof(ListNode));
this->previous = previous;
this->next = NULL;
this->data = data;
if (previous) {
previous->next = this;
}
return this;
}
void ListNode_destroy(ListNode* this) {
free(this);
}
|
C
|
void Reverse(char* array)
{
char cTemp = 0;
int nCharLength = 0;
char *pBegin = array, *pEnd = array;
while(*pEnd++ != '\0') //-- get the length of the incoming array
{
nCharLength++;
}
pEnd -= 2; //-- at this point pEnd is pointing at NULL
//-- I need to back the ponter up to the last char
while(pEnd >= pBegin)
{
cTemp = *pEnd; //-- dereference pEnd and store it in cTemp
*pEnd-- = *pBegin; //-- dereference pBegin and store it in dereferenced pEnd
//-- decrement pEnd
*pBegin++ = cTemp; //-- copy cTemp into dereferenced pBegin and increment pBegin
}
}
|
C
|
#ifndef PIECESELECT_H
#define PIECESELECT
#include "functions.h"
#include <sstream>
inline int pieceSelect(string player){
int x, y; //mouse location
bool xOut; // check close
SDL_Event mouseEvent;
SDL_Surface *display = SDL_SetVideoMode( 840, 840, 32, SDL_SWSURFACE );
// Surfaces used to display pieces
SDL_Surface *shamrock = NULL;
SDL_Surface *ND = NULL;
SDL_Surface *ship = NULL;
SDL_Surface *ring = NULL;
SDL_Surface *guinness = NULL;
SDL_Surface *francis = NULL;
SDL_Surface *rockne = NULL;
SDL_Surface *lep = NULL;
SDL_Surface *jersey = NULL;
int piece;
SDL_Surface *ok = loadImage("data/OK.bmp");
// load prompt
TTF_Font *font = TTF_OpenFont("/usr/share/fonts/sil-padauk/Padauk.ttf", 28);
stringstream buffer;
buffer << "Player " << player << " select your piece : ";
const char *output = buffer.str().c_str();
SDL_Surface *userPrompt = TTF_RenderText_Shaded(font,output,textColor,bColor);
// load images
ND = loadImage("data/ND.bmp");
shamrock = loadImage("data/shamrock.bmp");
ship = loadImage("data/ship.bmp");
ring = loadImage("data/ring.bmp");
guinness = loadImage("data/guinness.bmp");
francis = loadImage("data/francis.bmp");
rockne = loadImage("data/rockne.bmp");
lep = loadImage("data/lep.bmp");
jersey = loadImage("data/jersey.bmp");
SDL_WM_SetCaption( "Monopoly - Piece Selection" , "Piece Selection"); // SET WINDOW CAPTION
// apply the surfaces
blit(125,60,userPrompt,display);
blit(120,120,shamrock,display);
blit(120*3,120,ND,display);
blit(120*5, 120, ship, display);
blit(120,120*3,ring,display);
blit(120*3,120*3,guinness,display);
blit(120*5, 120*3, francis, display);
blit(120,120*5,rockne,display);
blit(120*3,120*5,lep,display);
blit(120*5, 120*5, jersey, display);
blit(700, 760,ok,display);
SDL_Flip(display);
// load pieces to display
while (xOut == false){
while (SDL_PollEvent( &mouseEvent )){
if(mouseEvent.type == SDL_QUIT ){ // if x-out
xOut = true;
}
else if (mouseEvent.type == SDL_MOUSEBUTTONDOWN){ // detect mouse clicks
// If left click
if(mouseEvent.button.button == SDL_BUTTON_LEFT){
// get mouse locations
x = mouseEvent.button.x;
y = mouseEvent.button.y;
if( (x > 120 && x < 120*2 ) && (y > 120 && y < 120*2) ){ // if shamrock
SDL_FreeSurface(shamrock);
SDL_FreeSurface(ND);
SDL_FreeSurface(ship);
SDL_FreeSurface(francis);
SDL_FreeSurface(jersey);
SDL_FreeSurface(rockne);
SDL_FreeSurface(guinness);
SDL_FreeSurface(lep);
ND = loadImage("data/ND.bmp");
shamrock = loadImage("data/shamrockPressed.bmp");
ship = loadImage("data/ship.bmp");
ring = loadImage("data/ring.bmp");
guinness = loadImage("data/guinness.bmp");
francis = loadImage("data/francis.bmp");
rockne = loadImage("data/rockne.bmp");
lep = loadImage("data/lep.bmp");
jersey = loadImage("data/jersey.bmp");
blit(125,60,userPrompt,display);
blit(120,120,shamrock,display);
blit(120*3,120,ND,display);
blit(120*5, 120, ship, display);
blit(120,120*3,ring,display);
blit(120*3,120*3,guinness,display);
blit(120*5, 120*3, francis, display);
blit(120,120*5,rockne,display);
blit(120*3,120*5,lep,display);
blit(120*5, 120*5, jersey, display);
blit(700, 760,ok,display);
//piece = ;
SDL_Flip(display);
}
else if( (x > 120*3 && x < 120*4) && (y>120 && y < 120*2) ){ // ND
SDL_FreeSurface(shamrock);
SDL_FreeSurface(ND);
SDL_FreeSurface(ship);
SDL_FreeSurface(francis);
SDL_FreeSurface(jersey);
SDL_FreeSurface(rockne);
SDL_FreeSurface(guinness);
SDL_FreeSurface(lep);
ND = loadImage("data/NDPressed.bmp");
shamrock = loadImage("data/shamrock.bmp");
ship = loadImage("data/ship.bmp");
ring = loadImage("data/ring.bmp");
guinness = loadImage("data/guinness.bmp");
francis = loadImage("data/francis.bmp");
rockne = loadImage("data/rockne.bmp");
lep = loadImage("data/lep.bmp");
jersey = loadImage("data/jersey.bmp");
blit(125,60,userPrompt,display);
blit(120,120,shamrock,display);
blit(120*3,120,ND,display);
blit(120*5, 120, ship, display);
blit(120,120*3,ring,display);
blit(120*3,120*3,guinness,display);
blit(120*5, 120*3, francis, display);
blit(120,120*5,rockne,display);
blit(120*3,120*5,lep,display);
blit(120*5, 120*5, jersey, display);
blit(700, 760,ok,display);
SDL_Flip(display);
}
else if( (x > 120*5 && x < 120*6) && (y>120 && y < 120*2) ){ // ship
SDL_FreeSurface(shamrock);
SDL_FreeSurface(ND);
SDL_FreeSurface(ship);
SDL_FreeSurface(francis);
SDL_FreeSurface(jersey);
SDL_FreeSurface(rockne);
SDL_FreeSurface(guinness);
SDL_FreeSurface(lep);
ND = loadImage("data/ND.bmp");
shamrock = loadImage("data/shamrock.bmp");
ship = loadImage("data/shipPressed.bmp");
ring = loadImage("data/ring.bmp");
guinness = loadImage("data/guinness.bmp");
francis = loadImage("data/francis.bmp");
rockne = loadImage("data/rockne.bmp");
lep = loadImage("data/lep.bmp");
jersey = loadImage("data/jersey.bmp");
blit(125,60,userPrompt,display);
blit(120,120,shamrock,display);
blit(120*3,120,ND,display);
blit(120*5, 120, ship, display);
blit(120,120*3,ring,display);
blit(120*3,120*3,guinness,display);
blit(120*5, 120*3, francis, display);
blit(120,120*5,rockne,display);
blit(120*3,120*5,lep,display);
blit(120*5, 120*5, jersey, display);
blit(700, 760,ok,display);
SDL_Flip(display);
}
else if( (x > 120 && x < 120*2) && (y>120*3 && y < 120*4) ){ // ring
SDL_FreeSurface(shamrock);
SDL_FreeSurface(ND);
SDL_FreeSurface(ship);
SDL_FreeSurface(francis);
SDL_FreeSurface(jersey);
SDL_FreeSurface(rockne);
SDL_FreeSurface(guinness);
SDL_FreeSurface(lep);
ND = loadImage("data/ND.bmp");
shamrock = loadImage("data/shamrock.bmp");
ship = loadImage("data/ship.bmp");
ring = loadImage("data/ringPressed.bmp");
guinness = loadImage("data/guinness.bmp");
francis = loadImage("data/francis.bmp");
rockne = loadImage("data/rockne.bmp");
lep = loadImage("data/lep.bmp");
jersey = loadImage("data/jersey.bmp");
blit(125,60,userPrompt,display);
blit(120,120,shamrock,display);
blit(120*3,120,ND,display);
blit(120*5, 120, ship, display);
blit(120,120*3,ring,display);
blit(120*3,120*3,guinness,display);
blit(120*5, 120*3, francis, display);
blit(120,120*5,rockne,display);
blit(120*3,120*5,lep,display);
blit(120*5, 120*5, jersey, display);
blit(700, 760,ok,display);
SDL_Flip(display);
}
else if( (x > 120*3 && x < 120*4) && (y>120*3 && y < 120*4) ){ // guinness
SDL_FreeSurface(shamrock);
SDL_FreeSurface(ND);
SDL_FreeSurface(ship);
SDL_FreeSurface(francis);
SDL_FreeSurface(jersey);
SDL_FreeSurface(rockne);
SDL_FreeSurface(guinness);
SDL_FreeSurface(lep);
ND = loadImage("data/ND.bmp");
shamrock = loadImage("data/shamrock.bmp");
ship = loadImage("data/ship.bmp");
ring = loadImage("data/ring.bmp");
guinness = loadImage("data/guinnessPressed.bmp");
francis = loadImage("data/francis.bmp");
rockne = loadImage("data/rockne.bmp");
lep = loadImage("data/lep.bmp");
jersey = loadImage("data/jersey.bmp");
blit(125,60,userPrompt,display);
blit(120,120,shamrock,display);
blit(120*3,120,ND,display);
blit(120*5, 120, ship, display);
blit(120,120*3,ring,display);
blit(120*3,120*3,guinness,display);
blit(120*5, 120*3, francis, display);
blit(120,120*5,rockne,display);
blit(120*3,120*5,lep,display);
blit(120*5, 120*5, jersey, display);
blit(700, 760,ok,display);
SDL_Flip(display);
}
else if( (x > 120*5 && x < 120*6) && (y>120*3 && y < 120*4) ){ // francis
SDL_FreeSurface(shamrock);
SDL_FreeSurface(ND);
SDL_FreeSurface(ship);
SDL_FreeSurface(francis);
SDL_FreeSurface(jersey);
SDL_FreeSurface(rockne);
SDL_FreeSurface(guinness);
SDL_FreeSurface(lep);
ND = loadImage("data/ND.bmp");
shamrock = loadImage("data/shamrock.bmp");
ship = loadImage("data/ship.bmp");
ring = loadImage("data/ring.bmp");
guinness = loadImage("data/guinness.bmp");
francis = loadImage("data/francisPressed.bmp");
rockne = loadImage("data/rockne.bmp");
lep = loadImage("data/lep.bmp");
jersey = loadImage("data/jersey.bmp");
blit(125,60,userPrompt,display);
blit(120,120,shamrock,display);
blit(120*3,120,ND,display);
blit(120*5, 120, ship, display);
blit(120,120*3,ring,display);
blit(120*3,120*3,guinness,display);
blit(120*5, 120*3, francis, display);
blit(120,120*5,rockne,display);
blit(120*3,120*5,lep,display);
blit(120*5, 120*5, jersey, display);
blit(700, 760,ok,display);
SDL_Flip(display);
}
else if( (x > 120 && x < 120*2) && (y>120*5 && y < 120*6) ){ // rockne
SDL_FreeSurface(shamrock);
SDL_FreeSurface(ND);
SDL_FreeSurface(ship);
SDL_FreeSurface(francis);
SDL_FreeSurface(jersey);
SDL_FreeSurface(rockne);
SDL_FreeSurface(guinness);
SDL_FreeSurface(lep);
ND = loadImage("data/ND.bmp");
shamrock = loadImage("data/shamrock.bmp");
ship = loadImage("data/ship.bmp");
ring = loadImage("data/ring.bmp");
guinness = loadImage("data/guinness.bmp");
francis = loadImage("data/francis.bmp");
rockne = loadImage("data/rocknePressed.bmp");
lep = loadImage("data/lep.bmp");
jersey = loadImage("data/jersey.bmp");
blit(125,60,userPrompt,display);
blit(120,120,shamrock,display);
blit(120*3,120,ND,display);
blit(120*5, 120, ship, display);
blit(120,120*3,ring,display);
blit(120*3,120*3,guinness,display);
blit(120*5, 120*3, francis, display);
blit(120,120*5,rockne,display);
blit(120*3,120*5,lep,display);
blit(120*5, 120*5, jersey, display);
blit(700, 760,ok,display);
SDL_Flip(display);
}
else if( (x > 120*3 && x < 120*4) && (y>120*5 && y < 120*6) ){ // lep
SDL_FreeSurface(shamrock);
SDL_FreeSurface(ND);
SDL_FreeSurface(ship);
SDL_FreeSurface(francis);
SDL_FreeSurface(jersey);
SDL_FreeSurface(rockne);
SDL_FreeSurface(guinness);
SDL_FreeSurface(lep);
ND = loadImage("data/ND.bmp");
shamrock = loadImage("data/shamrock.bmp");
ship = loadImage("data/ship.bmp");
ring = loadImage("data/ring.bmp");
guinness = loadImage("data/guinness.bmp");
francis = loadImage("data/francis.bmp");
rockne = loadImage("data/rockne.bmp");
lep = loadImage("data/lepPressed.bmp");
jersey = loadImage("data/jersey.bmp");
blit(125,60,userPrompt,display);
blit(120,120,shamrock,display);
blit(120*3,120,ND,display);
blit(120*5, 120, ship, display);
blit(120,120*3,ring,display);
blit(120*3,120*3,guinness,display);
blit(120*5, 120*3, francis, display);
blit(120,120*5,rockne,display);
blit(120*3,120*5,lep,display);
blit(120*5, 120*5, jersey, display);
blit(700, 760,ok,display);
SDL_Flip(display);
}
else if( (x > 120*5 && x < 120*6) && (y>120*5 && y < 120*6) ){ // jersey
SDL_FreeSurface(shamrock);
SDL_FreeSurface(ND);
SDL_FreeSurface(ship);
SDL_FreeSurface(francis);
SDL_FreeSurface(jersey);
SDL_FreeSurface(rockne);
SDL_FreeSurface(guinness);
SDL_FreeSurface(lep);
ND = loadImage("data/ND.bmp");
shamrock = loadImage("data/shamrock.bmp");
ship = loadImage("data/ship.bmp");
ring = loadImage("data/ring.bmp");
guinness = loadImage("data/guinness.bmp");
francis = loadImage("data/francis.bmp");
rockne = loadImage("data/rockne.bmp");
lep = loadImage("data/lep.bmp");
jersey = loadImage("data/jerseyPressed.bmp");
blit(125,60,userPrompt,display);
blit(120,120,shamrock,display);
blit(120*3,120,ND,display);
blit(120*5, 120, ship, display);
blit(120,120*3,ring,display);
blit(120*3,120*3,guinness,display);
blit(120*5, 120*3, francis, display);
blit(120,120*5,rockne,display);
blit(120*3,120*5,lep,display);
blit(120*5, 120*5, jersey, display);
blit(700, 760,ok,display);
SDL_Flip(display);
}
else if( (x > 700 & x < 823) && (y > 760 && y < 783) ) { // ok
return 1;
}
}
else if(mouseEvent.button.button == SDL_BUTTON_RIGHT){
// do nothing
}
}
}
}
}
#endif
|
C
|
#include<stdio.h>
#include<math.h>
int even(int N)
{
scanf("%d",&N);
for(int i=1; i<=N; i++)
{
if(i%2==0)
{
printf("%d^2 = %d\n",i,(int)pow(i,2));
}
}
}
int main()
{
int N;
even(N);
return 0;
}
|
C
|
#include <stdio.h>
void main(){
int x = 50, y = 30;
printf("x y ? %d\n", x == y);
printf("x y ٸ ? %d\n", x != y);
printf("x y ū ? %d\n", x > y);
printf("x y ? %d\n", x < y);
printf("x y ? %d\n", x = y);
}
|
C
|
/*
* trace_fatal.c: Utility functions for producing traces when a program experiences a fatal error.
*
* Created on: Jul 15, 2013
* Author: Yitzik Casapu, Infinidat
*
* Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sysexits.h>
#include <assert.h>
#include <stdlib.h>
#include "array_length.h"
#include "trace_fatal.h"
#include "trace_user.h"
int trace_log_assertion_failure(const char *file, const char *func, int line, const char *expr)
{
FATAL("Assertion", expr, "failed at", file, line, func);
return 0; /* Note: returning a non-zero value here can be used to avoid exiting on the assertion. */
}
static trace_fatal_signal_custom_handler custom_fatal_sig_handler = NULL;
static void __attribute__((noreturn)) fatal_signal_handler(int sig, siginfo_t *info, void *unused __attribute__((unused)))
{
const pid_t pid = getpid();
const void *const fault_addr = info->si_addr;
const int code = info->si_code;
FATAL("Process", pid, "has received", sig, strsignal(sig), code, "at", fault_addr);
if ((NULL != custom_fatal_sig_handler) && (custom_fatal_sig_handler(info) < 0)) {
const int err = errno;
ERR("Custom fatal signal handler", custom_fatal_sig_handler, "has failed with", err, strerror(err));
}
if ((SI_USER == code) && (pid != info->si_pid)) {
/* The signal was sent deliberately from outside the process */
WARN("The signal", sig, strsignal(sig), "was received from process", info->si_pid);
}
/* Now we re-raise the signal. Since we installed this handler with SA_NODEFER the function will not return. */
raise(sig);
FATAL("Failed to re-raise", sig, strsignal(sig));
abort();
}
int trace_register_fatal_sig_handlers(trace_fatal_signal_custom_handler custom_handler)
{
const int fatal_signals[] = { SIGABRT, SIGSEGV, SIGBUS, SIGILL, SIGFPE };
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_sigaction = fatal_signal_handler;
act.sa_flags = SA_SIGINFO | SA_RESETHAND | SA_NODEFER;
int rc = 0;
for (unsigned i = 0; i < ARRAY_LENGTH(fatal_signals); i++) {
const int sig = fatal_signals[i];
if(sigaction(sig, &act, NULL) < 0) {
ERR("Error registering a handler for signal", sig, strsignal(sig));
rc = -1;
}
}
if (NULL != custom_handler) {
custom_fatal_sig_handler = custom_handler;
}
return rc;
}
|
C
|
#include<stdio.h>
//baekjoon 4101
int main()
{
int a, b;
scanf("%d%d", &a, &b);
while (a != 0 && b != 0)
{
if (a > b) printf("Yes\n");
else printf("No\n");
scanf("%d%d", &a, &b);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>
/*
* This is the counter value which is to
* be incremented by all the threads created
* by your program
*/
int counter = 0;
pthread_mutex_t m_lock = PTHREAD_MUTEX_INITIALIZER;
void *count_incrementor(void* id){
long long thread_id=(long long int) id;
//sleep(1);
pthread_mutex_lock(&m_lock);
//printf("T:%lld \t",thread_id);
fflush(stdout);
counter++;
pthread_mutex_unlock(&m_lock);
pthread_exit((void *)0);
}
int main(int argc, char const *argv[])
{
/* Write you code to create n threads here*/
/* Each thread must increment the counter once and exit*/
long long int NUMBER_OF_THREADS;
int thread_create_status;
void* status;
if(argc >1)
{
NUMBER_OF_THREADS=atoi(argv[1]);
//printf("NUMBER_OF_THREADS: %lld\n",NUMBER_OF_THREADS);
if(NUMBER_OF_THREADS==0)
return 0;
}
else
{
printf("Please enter the thread count in argument.\n");
return 0;
}
pthread_t threads[NUMBER_OF_THREADS];
for(long long int i=0;i<NUMBER_OF_THREADS;i++)
{
thread_create_status=pthread_create(&threads[i],NULL, count_incrementor,(void *) i);
if(thread_create_status){
printf("Error in creating thread: %lld",i);
exit(-1);
}
}
for(long long int i=0;i<NUMBER_OF_THREADS;i++)
{
pthread_join(threads[i], &status);
}
pthread_mutex_destroy(&m_lock);
/* Make sure you reap all threads created by your program
before printing the counter*/
printf("%d\n", counter);
//sleep(10000);
return 0;
}
|
C
|
/*
*
* Name : RAMOS, JESTER DARYLHANS
* Section: S15B
* Submission Date: 12/3/2018
*
* Implement the program for the hypotrochoid (also known as spirograph).
*
*/
#include <stdio.h>
#include "mp_math.h"
int
main()
{
/* t = theta
x = x coordinates
y = y coordinates
a = big circle radius
b = small circle radius
h = determines location of point (inside or outside)
*/
double t,x,y,a,b,h,radangle,refangle,r,rtangle,rt;
scanf ("%lf %lf %lf", &a, &b, &h);
r = (a-b)/b;
for (t = 0; t <= a*360 ; t++){
rt=r*t;
refangle=t;
// Guarantees that refangle is within 0 - 360 degrees
while (refangle>360)
refangle=refangle-360;
// Guarantees that rt is within 0 - 360 degrees
while (rt>360)
rt=rt-360;
// Converts refangle into radians
radangle = deg_to_rad(refangle);
// Converts rt into radians
rtangle = deg_to_rad(rt);
x = ((a-b) * cosine(radangle) + (h * cosine(rtangle)));
y = ((a-b) * sine(radangle) - (h * sine(rtangle)));
printf ("%.6lf \t %.6lf\n", x, y);
}
return 0;
}
|
C
|
/*
* Network computing
* Assignment 2: A HTTP thread server program
* Written by Tran Quoc Hoan
* programmed by milestones method (step by step)
* Usage: ./HttpThread serverIP
*/
#include <pthread.h>
#include <stdio.h>
#include <string.h> /* for memset() function */
#include <time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <netdb.h>
#include "ServerUtils.h"
void *send_recv_thread( void *arg ) {
pthread_detach ( pthread_self() );
int acc = (int) arg;
sock_handle( acc );
close( acc );
pthread_exit((void*) 0);
}
int main ( int argc, char* argv[] ) {
/* Usage */
if ( argc != 2 ) {
fprintf ( stderr, "Usage: %s <Server Name or IPaddress>\n", argv[0] );
return 0;
}
/* address information */
int listenfd;
pthread_t thread;
struct addrinfo servaddr, *rcv;
int reuseaddr = 1; // true
/* Get the address info */
memset( &servaddr, 0, sizeof( struct addrinfo ) );
servaddr.ai_family = AF_INET;
servaddr.ai_socktype = SOCK_STREAM;
if ( getaddrinfo( argv[1], PORT, &servaddr, &rcv ) != 0 )
err_handle( "getaddrinfo" );
/* Create the socket */
listenfd = socket( rcv->ai_family, rcv->ai_socktype, rcv->ai_protocol );
if ( listenfd == -1 ) err_handle( "socket" );
/* Enable the socket to reuse the address immediately */
if ( setsockopt( listenfd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof( int ) ) == -1 )
err_handle( "setsockopt" );
/* Bind to the address */
if ( bind( listenfd, rcv->ai_addr, rcv->ai_addrlen ) == -1 )
err_handle( "bind" );
freeaddrinfo( rcv );
/* Listen */
if ( listen( listenfd, LISTENQ ) == -1 )
err_handle( "listen" );
/* Main loop */
while (1) {
struct sockaddr_in comming_addr;
size_t size = sizeof( struct sockaddr_in );
int confd = accept( listenfd, (struct sockaddr*)&comming_addr, &size );
if ( confd == -1 ) err_handle( "accept" );
printf("Comming connection from %s on port %d \r\n", inet_ntoa(comming_addr.sin_addr), htons(comming_addr.sin_port));
if ( pthread_create( &thread, NULL, send_recv_thread, (void *)confd ) != 0 ) {
perror( "pthread_create" );
}
}
close( listenfd );
return 1;
}
|
C
|
/**
* @file buddy.h
* @brief The header file contains the buddy data type definition.
*/
#ifndef _BUDDY_H
#define _BUDDY_H
/** @brief The maximum length of JIDs */
#define MAX_JID_LENGTH (32)
/** @brief The number of buddies to store */
#define MAX_BUDDIES (4)
/**
* @brief The length of each text message including the terminating
* zero character
*/
#define MAX_MESSAGE_LENGTH (81)
#define INVALID_BUDDY_ID MAX_BUDDIES
/**
* @brief The current status of the buddy
* @details The buddy status empty indicates an empty buddy slot.
* Empty buddies usually won't be propagated.
*/
typedef enum {
BUDDY_STATUS_EMPTY = 0, BUDDY_STATUS_UNAVAILABLE,
BUDDY_STATUS_AVAILABLE, BUDDY_STATUS_SUBSCRIBED
} buddy_status_t;
/**
* @brief Defines a struct containing all relevant information to
* manage a buddy
*/
typedef struct
{
char jid[MAX_JID_LENGTH];
/** The last message received */
char message[MAX_MESSAGE_LENGTH];
buddy_status_t status;
uint8_t activity; /* 0 nonactive. higher: more active */
bool requestsPresenceSubscription; /* whether the buddy wants to subscribe to our presence */
bool hasPresenceSubscription; /* whether the buddy is subscribed to our presence */
bool gotNewMessage; /* whether we got a message that the user (presumably) hasn't seen yet */
} buddy_t;
#endif
|
C
|
// #TODO: translate net-byte-order
// Omar Juma
// Updated last: February 17, 2015
// CSCI 367, Winter 2015
// Program 2
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
fd_set readfds;
main( int argc, char **argv) {
struct hostent *ptrh; /* pointer to a host table entry */
struct protoent *ptrp; /* pointer to a protocol table entry */
struct sockaddr_in sad; /* structure to hold an IP address */
int sd; /* socket descriptor */
int port; /* protocol port number */
char *host; /* pointer to host name */
char message[512]; /* User input guess */
char buf[1024]; /* buffer for data from the server */
char nick[16];
char messaget[512];
int n;
char question[1024];
char serial[100];
char topic[1024];
char value[16];
memset((char *)&sad,0,sizeof(sad)); /* clear sockaddr structure */
sad.sin_family = AF_INET; /* set family to Internet */
if( argc != 3 ) {
fprintf(stderr,"Error: Wrong number of arguments\n");
fprintf(stderr,"usage:\n");
fprintf(stderr,"./client server_address server_port\n");
exit(EXIT_FAILURE);
}
port = atoi(argv[2]); /* convert to binary */
if (port > 0) /* test for legal value */
sad.sin_port = htons((u_short)port);
else {
fprintf(stderr,"Error: bad port number %s\n",argv[2]);
exit(EXIT_FAILURE);
}
host = argv[1]; /* if host argument specified */
/* Convert host name to equivalent IP address and copy to sad. */
ptrh = gethostbyname(host);
if ( ptrh == NULL ) {
fprintf(stderr,"Error: Invalid host: %s\n", host);
exit(EXIT_FAILURE);
}
memcpy(&sad.sin_addr, ptrh->h_addr, ptrh->h_length); // not needed
/* Map TCP transport protocol name to protocol number. */
if ( ((long int)(ptrp = getprotobyname("tcp"))) == 0) {
fprintf(stderr, "Error: Cannot map \"tcp\" to protocol number");
exit(EXIT_FAILURE);
}
/* Create a socket. */
sd = socket(PF_INET, SOCK_STREAM, ptrp->p_proto);
if (sd < 0) {
fprintf(stderr, "Error: Socket creation failed\n");
exit(EXIT_FAILURE);
}
memset(message, 0, 512);
printf("Please select a nickname: ");
scanf("%s", nick);
printf("\n");
printf("%s\n", nick);
snprintf(message, sizeof(message), "N\n%s\n\n", nick);
printf("%s\n", message);
/* Connect the socket to the specified server. */
if (connect(sd, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
fprintf(stderr,"connect failed\n");
exit(EXIT_FAILURE);
}
printf("Connected to game server: %s\n", host);
sleep(1);
write(sd, &message, strlen(message));
while(1){
n = read(sd, buf, sizeof(buf));
memset(message, 0, 512);
memset(messaget, 0, 512);
memset(question, 0, 1024);
memset(serial, 0, 1024);
memset(topic, 0, 1024);
memset(value, 0, 1024);
switch(buf[0]){
case 'R' :
printf("Unable to join.\n");
close(sd);
exit(EXIT_FAILURE);
case 'Q' :
sscanf(buf, "Q\n%[^\n]\n%[^\n]\n%[^\n]\n%[^\n]\n\n", serial, topic, value, question);
printf("serial: %s\n", serial);
printf("TOPIC: %s\nQUESTION: %s\nAnswer: ", topic, question);
/*
FD_ZERO(&readfds);
FD_SET(sd, &readfds);
FD_SET(0, &readfds);
printf("Answer: ");
if (select(sd+1, &readfds, NULL, NULL, NULL) < 0) {
error("ERROR: Error in select!");
}
printf("Select returned\n");
if (FD_ISSET(0, &readfds)){ */
//fgets(messaget, 512, stdin);
scanf("%s", messaget);
printf("Message: %s\n", messaget);
snprintf(message, 512, "A\n%s\n%s\n\n", serial, messaget);
printf("Message: %s\n", message);
write(sd, message, strlen(message));
/*
}
if (FD_ISSET(sd, &readfds)){
break;
} */
break;
case 'L' :
printf("You took too long!\n");
break;
case 'K' :
sscanf(buf, "K\n%s\n\n", value);
printf("Resulting point difference: %s\n", value);
break;
default :
break;
}
memset(buf, 0, 1024);
}
close(sd);
exit(EXIT_SUCCESS);
}
|
C
|
int fib();
// address: 0x10704
int main(int argc, char *argv[], char *envp[]) {
int local0; // m[o6 - 20]
int o0; // r8
printf("Input number: ");
scanf("%d", &local0);
o0 = fib();
printf("fibonacci(%d) = %d\n", local0, o0);
return 0;
}
// address: 0x106c4
int fib() {
int o0; // r8
int o1; // r9
int o1_1; // r9{28}
int o2; // r10
int o2_1; // r10{29}
int o3; // r11
if (o0 <= 1) {
} else {
o2 = 1;
o3 = 1;
if (o0 > 2) {
o1 = o0 - 2;
do {
o1_1 = o1;
o2_1 = o2;
o2 = o2_1 + o3;
o1 = o1_1 - 1;
o3 = o2_1;
} while (ADDFLAGS(o1_1, -1, o1_1 - 1));
}
o0 = o2;
}
return o0;
}
|
C
|
/* Program in c to perform insertion,deletion and display operation of circular queue */
#include<stdio.h>
#define SIZE 6
struct queue
{
int f,r,list[SIZE];
}a;
void insertion(struct queue *,int);
void deletion( struct queue *);
void display( struct queue *);
int main()
{
a.f=0;
a.r=0;
int i,x;
while(1)
{
printf("\n1.INSERTION\n2.DELETION\n3.DISPLAY\n4.EXIT\n");
scanf("%d",&i);
switch(i)
{
case 1:
printf("enter the number you want to insert:\n");
scanf("%d",&x);
insertion(&a,x);
break;
case 2:
deletion(&a);
break;
case 3:
display(&a);
break;
case 4:
exit (0);
default:
printf("wrong input\n");
}
}
return 0;
}
//function to perform insertion operation of circular queue
void insertion(struct queue *a,int x)
{
if((a->r+1)%SIZE==a->f)
printf("insertion not possible as because queue is almost full\n");
else
{
a->list[a->r]=x;
a->r=(a->r+1)%SIZE;
}
}
//function to perform deletion operation of circular queue
void deletion( struct queue *a)
{
int t;
if(a->f==a->r)
printf("queue is underflow");
else
{
t=a->list[a->f];
printf("deleted item is %d\n",t);
a->f=(a->f+1)%SIZE;
}
}
//function to perform display operation of circular queue
void display(struct queue *a)
{
if(a->r!=a->f)
{
printf("the elements of circular queue:\n");
int i;
for(i=a->f;i<a->r;i++)
printf("%d\t",a->list[i]);
}
else
printf("\nqueue is underflow");
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_info5.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cpaquet <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/16 12:06:53 by cpaquet #+# #+# */
/* Updated: 2018/03/22 13:41:43 by cpaquet ### ########.fr */
/* */
/* ************************************************************************** */
#include "filler.h"
static int ft_player(t_filler *info)
{
if (ft_strstr(LINE, "cpaquet.filler"))
{
if (LINE[10] != '1' && LINE[10] != '2')
{
ft_error("Error : Player");
return (-1);
}
(LINE[10] == '1' ? ME = 'O' : 0);
(LINE[10] == '1' ? ADV = 'X' : 0);
(LINE[10] == '2' ? ME = 'X' : 0);
(LINE[10] == '2' ? ADV = 'O' : 0);
}
else
return (0);
return (1);
}
static int ft_get_size(t_filler *info, char flag)
{
if (flag == 'B')
{
BOARD_L = ft_atoi(&LINE[8]);
BOARD_C = ft_atoi(ft_strchr(&LINE[8], ' '));
if (BOARD_L <= 0 || BOARD_C <= 0)
ft_error("Error : BOARD");
if (!BOARD)
if (!(BOARD = ft_strnew(BSIZE)))
return (-1);
if (!BOARD2)
if (!(BOARD2 = ft_strnew(BSIZE)))
return (-1);
}
else if (flag == 'P')
{
PIECE_L = ft_atoi(LINE + 6);
PIECE_C = ft_atoi(ft_strchr(LINE + 6, ' '));
if (PIECE_L <= 0 || PIECE_C <= 0)
ft_error("Error : PIECE");
if (!(PIECE = ft_strnew(PSIZE)))
return (-1);
}
return (1);
}
static int ft_get_board(t_filler *info)
{
int i;
i = 0;
while (ft_isdigit(LINE[0]))
{
if (ft_check_b_line(info) != 1 || i > BOARD_L)
{
ft_error("Error : BOARD");
return (-1);
}
ft_strcpy(BOARD + (i * BOARD_C), LINE + 4);
if (i == BOARD_L)
break ;
i++;
ft_strdel(&LINE);
get_next_line(0, &LINE);
}
if (i != BOARD_L)
{
ft_error("Error : BOARD");
return (-1);
}
return (1);
}
static int ft_get_piece(t_filler *info)
{
int i;
i = 0;
while (LINE[0] == '.' || LINE[0] == '*')
{
if (ft_check_p_line(info) == -1)
{
ft_error("Error : PIECE1");
return (-1);
}
ft_strcpy(PIECE + (i * PIECE_C), LINE);
i++;
ft_strdel(&LINE);
if (i == PIECE_L)
break ;
get_next_line(0, &LINE);
}
if (i != PIECE_L)
{
ft_error("Error : PIECE2");
return (-1);
}
return (1);
}
int ft_get_info(t_filler *info)
{
while (get_next_line(0, &LINE) > 0)
{
if (ft_player(info) == -1)
return (-1);
if (ft_strstr(LINE, "Plateau") != NULL)
if (ft_get_size(info, 'B') == -1)
return (-1);
if (ft_isdigit(LINE[0]) == 1)
if (ft_get_board(info) == -1)
return (-1);
if (ft_strstr(LINE, "Piece") != NULL)
if (ft_get_size(info, 'P') == -1)
return (-1);
if (LINE[0] == '.' || LINE[0] == '*')
{
if (ft_get_piece(info) == 1)
break ;
else
return (-1);
}
ft_strdel(&LINE);
}
if (ME == 0 || !BOARD || !BOARD2 || !PIECE || PIECE_L == 0 || BOARD_L == 0)
return (-1);
return (1);
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef int uint32 ;
/* Variables and functions */
int TEX_SIZE ;
int stb_rand () ;
int** texture ;
void build_base_texture(int n)
{
int x,y;
uint32 color = stb_rand() | 0x808080;
for (y=0; y<TEX_SIZE; ++y)
for (x=0; x<TEX_SIZE; ++x) {
texture[y][x] = (color + (stb_rand()&0x1f1f1f))|0xff000000;
}
}
|
C
|
#include "highscore.h"
#include <stdio.h>
#include <stdlib.h>
int readHighscore()
{
int score;
FILE *datei = fopen("highscore.txt", "r");
if (datei == NULL) {
return 0;
}
fscanf(datei, "%i", &score);
fclose(datei);
return score;
}
void saveScore(int score)
{
FILE *datei = fopen("highscore.txt", "w");
fprintf(datei, "%i", score);
fclose(datei);
}
void saveHighscore(int score)
{
if (score > readHighscore()) {
saveScore(score);
}
}
|
C
|
#include "menu.h"
#include "comandos.h"
#include "stack.h"
#include "bot.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>
/**
* Imprime o menu e interpreta os comandos inseridos pelo utilizador.
* @param e Estado atual.
* @param topo Última jogada efetuada.
* @return Estado após execução do comando inserido.
*/
ESTADO menu (ESTADO e, struct JOGADA* topo) { // interpretador
char opcao[1024], arg1='\0', arg2='\0';
char input[1024];
ESTADO v;
FILE *file;
char ficheiro[1024];
char linha[20];
int permitido=0; // quando = 1, permite ao bot jogar
topo = NULL;
// número de jogadas efetuadas no ponto atual do jogo
int jogadas_efetuadas = 0; // novajogada incrementa este valor
while (toupper(opcao[0]) != 'Q') {
// Jogada do bot
if ((e.modo =='1' || e.modo =='2' || e.modo =='3') && (e.bot == e.peca)) {
printf("\n====> Jogada do Bot <====\n");
e = bot(e);
e = score(e);
topo = push(e,topo);
jogadas_efetuadas++;
}
printf(" \n"
" =========== \n"
" | REVERSI | \n"
" =========== \n"
" \n"
" ============================== ============================== \n"
" | N Novo Jogo | | L Carregar Jogo | \n"
" ============================== ============================== \n"
" ============================== ============================== \n"
" | E Guardar Jogo | | J Jogar | \n"
" ============================== ============================== \n"
" ============================== ============================== \n"
" | S Jogadas Validas | | H Sugestao de Jogada | \n"
" ============================== ============================== \n"
" ============================== ============================== \n"
" | U Desfazer Jogada | | A Novo Jogo contra Bot | \n"
" ============================== ============================== \n"
" \n"
" ============================= \n"
" | C Jogo para o campeonato | \n"
" ============================= \n"
" \n"
" ======================= \n"
" | Q Sair do Jogo | \n"
" ======================= \n");
// Desenha um cursor antecedido do próximo jogador a efetuar a jogada.
if(e.peca == VALOR_O)
printf("\nO ➢ ");
else {
if(e.peca == VALOR_X)
printf("\nX ➢ ");
else printf("\n ➢ ");
}
// guarda em 'input' o input
fgets(input, 1000, stdin);
sscanf(input, "%s", opcao);
opcao[0] = toupper(opcao[0]);
switch (opcao[0]) {
case 'N':
sscanf(input, "%*s %c", &arg1);
arg1 = toupper(arg1);
if (chrtovalor(arg1) == VALOR_X || chrtovalor(arg1) == VALOR_O) {
e = novoJogo(chrtovalor(arg1),'M',' ');
topo = resetJogadas(topo, &jogadas_efetuadas);
topo = push(e, topo);
} else
printf("Peça inválida\n");
break;
case 'L': // <-- acaba quando se dá um nome que não existe
sscanf(input, "%*s %s", &arg1);
e = continuaJogo(e, &arg1);
jogadas_efetuadas = 0;
break;
case 'E':
sscanf(input, "%*s %s", &arg1);
if (e.peca == VAZIA)
printf("\nCrie um novo jogo ou continue um jogo já existente.\n");
else if (arg1 == '\0')
printf("\nPrecisa de indicar um nome para guardar o ficheiro.\n");
else {
guardar(e, &arg1);
topo = resetJogadas(topo, &jogadas_efetuadas); // jogadas_efetuadas = 0 e lista de jogadas limpa
topo = push(e, topo);
}
break;
case 'J':
sscanf(input, "%*s %c %c", &arg1, &arg2);
if (!arg1 || !arg2) {
printf("\nFalta de argumentos.\n");
printa(e);
}
else {
if (validarJogada(e, arg1, arg2) == 1) {
printf("\nJogada inválida.\n");
printa(e);
}
else {
if (e.peca == VAZIA) printf("\nCrie um novo jogo ou continue um jogo já existente.\n");
else {
if (e.modo != ' ') {
e = jogar(e, arg1, arg2); // coloca a peça no sítio
topo = novaJogada(e, arg1, arg2, topo);
jogadas_efetuadas++;
}
}
}
}
break;
/* Esta opção faz duas coisas:
* 1. Inicia um novo jogo
* 2. Define as componentes do novo estado
*/
case 'A': {
// Lê argumentos dados.
sscanf(input, "%*s %c %c", &arg1, &arg2);
arg1 = toupper(arg1);
// Verifica se a peça e a dificuldade dadas são válidas.
if(arg1 != 'X' && arg1 != 'O')
printf("Peça inválida\n");
else {
if(arg2 != '1' && arg2 != '2' && arg2 != '3')
printf("Dificuldade inválida\n");
else {
// Cria um novo jogo
e = novoJogo(VALOR_X,'A',arg2);
// Define a peça do bot
if (arg1 == 'X') {
e.bot = VALOR_X;
}
else
e.bot = VALOR_O;
}
}
break;
}
case 'C':
sscanf(input, "%*s %s", ficheiro);
file = fopen(ficheiro, "r");
if (file != NULL) {
while (fgets(linha, sizeof(linha), file)) {
fputs(linha, stdout);
}
fclose(file);
}
else {
file = fopen(ficheiro, "w");
if (file != NULL) {
fputs("A X 3\n", file);
fputs("- - - - - - - -\n", file);
fputs("- - - - - - - -\n", file);
fputs("- - - - - - - -\n", file);
fputs("- - - X O - - -\n", file);
fputs("- - - O X - - -\n", file);
fputs("- - - - - - - -\n", file);
fputs("- - - - - - - -\n", file);
fputs("- - - - - - - -\n", file);
fclose(file);
}
else {
printf("Erro. \n");
}
}
break;
case 'S':
if (e.peca == VAZIA)
printf("\nCrie um novo jogo ou continfue um jogo já existente.\n");
else {
v = calcJogadasValidas(e);
posicoesValidas(e, v);
}
break;
case 'H':
if (e.peca == VAZIA)
printf("\nCrie um novo jogo ou continue um jogo já existente.\n");
else sugestao(e);
break;
case 'U':
e = score(e);
if (jogadas_efetuadas == 0)
printf("Não há mais jogadas para retroceder.");
else if (e.peca == VAZIA)
printf("\nCrie um novo jogo ou continue um jogo já existente.\n");
else {
topo = undo(&e, topo);
jogadas_efetuadas--;
}
break;
case 'Q':
printf("\nSaiu do jogo.\n"
"\n ### Trabalho realizado por ###"
"\n"
"\nAna Sofia Gomes Miguel Rodrigues"
"\n Carolina Vila Chã\n");
break;
case 'D':
printf("\n======================================================================================================="
"\n| INPUT || AÇÃO |"
"\n======================================================================================================="
"\n| N <peça> || Inicia um novo jogo em que o primeiro a jogar é o jogador com a peça indicada. |"
"\n| L <ficheiro> || Continua um jogo previamente guardado no ficheiro pedido. |"
"\n| E <ficheiro> || Escreve em ficheiro (guarda) o estado atual do jogo. |"
"\n| J <L> <C> || Joga a peça atual na posição (L,C). O comando J 1 1 coloca a peça atual no |"
"\n| canto superior esquerdo, se tal for possível |"
"\n| S || Imprime um ponto ‘.’ nas posições em que a jogada é válida. |"
"\n| H || Mostra uma sugestão de jogada. É colocado um ‘?’ no sitio sugerido. |"
"\n| U || Desfaz a última jogada. Permite desfazer até ao estado inicial do jogo, ou |"
"\n| até ao último 'E' ou 'L' efetuado. |"
"\n| A <peça> <nível> || Cria um novo jogo contra ‘bot’ em que o computador joga com a peça contra um |"
"\n| bot de nível (3 níveis possíveis). Neste modo quem joga primeiro é sempre o |"
"\n| jogador com a peça ‘X’. |"
"\n| Q || Sair do jogo. |"
"\n======================================================================================================="
"\n");
break;
default:
printf("\nOpção inválida.\n");
break;
}
//TESTE (VERIFICA PEÇA DO BOT E MODO)
switch(e.bot) {
case VALOR_O: printf("Peça Bot: O\n"); break;
case VALOR_X: printf("Peça Bot: X\n"); break;
default: printf("Peça Bot: V\n"); break;
}
/*
printf("Modo: %c\n", e.modo);
*/
// dar reset aos argumentos
arg1='\0';
arg2 = '\0';
}
return e;
}
|
C
|
// ===========================================================
//
// Lab6_Register.cpp
// Description: AMBA Register
// Name: <team member names here>
// Date: <today's date here>
// Class: CMPE-110
// Section: <Lab: section, day, and time here>
//
// ===========================================================
#include "stdio.h"
int main() {
unsigned char amba=0;
//initial value of the amba register
printf("After initialization, amba = 0x%X\n",amba);
//set 'Mode bit' and 'Enable bit' high
amba = amba | ((1 << 7) | (1 << 6)); //you need to change this line!
printf("After mode and enable bits set, amba = 0x%X\n",amba);
//also set the 'prescale' bits so 'clock divide by' is 16
amba = amba | (1 << 2); //you need to change this line!
printf("After setting prescale bits, amba = 0x%X\n",amba);
//clear the 'Mode bit', leaving other bits alone
amba = amba &(~(1 << 6)); //you need to change this line!
printf("After clearing the mode bit, amba = 0x%X\n",amba);
return 0;
}
|
C
|
#include <stdio.h>
#include<stdlib.h>
void merge_sort(int *a, int n);
void merge(int *a, int start, int mid, int end);
int main()
{
int length, *arr, i;
printf("Enter the array length:");
scanf("%d", &length);
arr = (int *)malloc(length * sizeof(int));
printf("Enter the array elements:\n");
for (i = 0; i < length; ++i)
{
scanf("%d", arr + i);
}
merge_sort(arr, length);
printf("The sorted array is :\n");
for(i = 0; i < length; ++i)
{
printf("%d\n", *(arr + i));
}
return 0;
}
void merge_sort(int *a, int n)
{
int m = (n >> 1) + (n & 1);
int i;
int start, mid, end;
for (i = 1; i <= m; i <<= 1)
{
--n;
start = 0;
mid = i - 1;
end = mid + i;
(end > n) && (end = n);
while(mid < end)
{
merge(a, start, mid, end);
start = end + 1;
mid = start + i - 1;
end = mid + i;
(end > n) && (end = n);
}
}
}
void merge(int *a, int start, int mid, int end)
{
int *temp1 = (int *) malloc((mid - start + 1) * sizeof(int));
int *temp2 = (int *) malloc((end - mid) * sizeof(int));
int i, j, length1, length2;
for(i = 0, j = start; j <= mid; ++i, ++j)
{
temp1[i] = a[j];
}
length1 = i;
for(i = 0, j = (mid + 1); j <= end; ++i, ++j)
{
temp2[i] = a[j];
}
length2 = i;
int k = start;
i = 0;
j = 0;
while(i < length1 && j < length2)
{
if (temp2[j] < temp1[i])
{
a[k++] = temp2[j++];
}
else
{
a[k++] = temp1[i++];
}
}
while(i < length1)
{
a[k++] = temp1[i++];
}
while(j < length2)
{
a[k++] = temp2[j++];
}
}
|
C
|
/* 图的数据结构-邻接矩阵 -- 接口函数 -- 从标准输入流,读入一幅图 */
//0.用户设置数据类型
typedef int Vertex
typedef int WeightType
typedef int DataType
//1. 数据结构的实现 -- 邻接矩阵
typedef struct Gnode *PtrTOGNode; // 很聪明的通过typedef制造出一个指针类
struct GNode{
int Nv; /* 顶点数 */
int Ne; /* 边数 */
WeightType G[MaxVertaxNum][MaxVertaxNum] // 表示两点是否相邻 WeightType 权重类型
DataType Data[MaxVertaxNum] // 顶点数据
};
typedef PtrTOGNode MGraph // MGraph是指向使用邻接矩阵的图结构
// 2.1 接口函数 -- CreatGraph -- 创建无边图
typedef int Vertex
//创造一个数组需要 从heap申请对象的空间(malloc),规划内部空间(声明),以及初始化空间。
MGraph CreatGraph (int VertexNum){
Vertex V , W ;
MGraph Graph ;
Graph = (MGraph)malloc(sizeof(struct GNode)) //为什么需要强制类型转换??
/*
malloc的空间默认当作char数组使用。
一旦你申明结构类型(告诉编译器如何划分内存),那么一个变量就被“创造出来了”
*/
Graph -> Nv = VertexNum ; //当你声明数据解构的类型后,编译器自然会安排哪里放Nv 哪里放Ne
Graph -> Ne = 0 ;
for (V=0; V<Graph->Nv; V++){
for (W=0; W<Graph->Nv; W++) {
Graph->G[V][w] = 0;
}
}
return Graph;
}
//2.2 接口函数 -- SetVertexData -- 设置顶点数据
//2.2.1 顶点类型
/* 为什么将函数的输入,额外定义一个数据结构
从C的函数传参开始,我们就有了传值而不是传变量的“规范”。
因为 任何程序的实现都是分层的,不同的层实现不同的作用,需要不同的变量。(接口不同)
每一层都使用接口规范定义的变量,就像java的私有变量。
*/
typedef struct VertexNode* PtrToVertexNode;
struct VertexNode{
Vertex vertex;
DataType value;
};
typedef PtrToVertexNode VertexNode;
//2.2.2 接口函数 -- SetVertexData -- 导入顶点数据
void SetVertexDData(MGraph Graph,VertexNode vertexNode){
Graph->Date[vertexNode->vertex]=vertexNode->value;
}
//2.3 接口函数 -- InsertEdge -- 插入边
typedef struct ENode *PtrToENode
struct ENode {
Vertex V ;
Vertex W ;
WeightType weight ;
};
typedef PtrToENode Edge
void InsertEdge(MGraph Graph,Edge E){
Graph->G[E->V][E->W]=E->weight
}
// 3.从标准输入流,读入一幅图 分两层
// 数据读入层(标准数据流-->VertexNode/ENode)|| 建立图 creat(Nv) setVertexDate(VerexNode) insertEdge(Edge)
vold BuildGraph(){
int Nv ;
Vertex V ;
MGraph Graph ;
Edge E ; VertexNode vertexNode;
scanf("%d",&Nv);
Graph = CreatGraph(Nv);
scanf("%d",&Graph->Ne);
if( Graph->Ne != 0){
E = (Edge)malloc(sizeof(struct Edge)) ;
for ( int i = 0; i < Graph->Nv; ++i) {
/* 从标准输入流读入边 */
scanf("%d %d %d",&E->V,&E->W,&E->weight);
/* 插入边*/
InsertEdge(Graph,E);
}
}
////////////////////////////////////////////////////////////////////////////////
vertexNode = (VertexNode)malloc(sizeof(struct VertexNode));
for ( i = 0; i <Graph->Nv ; ++i) {
/* 从标准输入流读入顶点数据 */
scanf("%d %d",&vertexNode->vertex,&vertexNode->value);
/* 设置顶点数据*/
SetVertexDData(Graph,vertexNode);
}
return Graph;
}
/*
* 从思考的角度应该是从大框架到小细节,从前往后编程,如:python,
* 但是就C而言这样会导致前面的一些引用无法被编译器认可,因此只能从小到大
*/
|
C
|
#include <stdio.h>
#include <stdlib.h>
/*
Napraviti program koji od korisnika zahteva
da unese broj elemenata u dinamicki alociranom nizu,
a zatim da se taj niz popuni elementima. Nakon toga izracunati
prosecnu vrednost elemenata u nizu.
*/
int main()
{
int a;
float avg = 0.0;
printf("unesite broj elemenata u nizu: ");
scanf("%i",&a);
int* niz = malloc(a*(sizeof (int)));
printf("Unesite niz:\n");
int i;
for(i=0;i<a;i++){
scanf("%i",niz + i);
avg += (float)niz[i];
}
avg = avg/(float)a;
printf("Prosecna vrednost elemenata u nizu je: %.2f\n",avg);
free(niz);
return 0;
}
|
C
|
/*************************************************************************
> File Name: copy_block.c
> Author: Wangyao
> Mail: Yaowang_future@163.com
> Created Time: 2014年12月10日 星期三 19时52分17秒
**********************************************************************/
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <time.h>
int main(int argc,char **argv)
{
clock_t start,end;
double last;
start=clock();
char block[1024];
int in,out;
int nread;
in=open("file.in",O_RDONLY);
out=open("file.out",O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR);
while((nread=read(in,block,sizeof(block)))>0)
write(out,block,nread);
end=clock();
last=(double)(end-start)/CLOCKS_PER_SEC;
printf("total time is %lf\n",last);
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2018
** test_eggs.c
** File description:
** test egg commands
*/
#include <criterion/criterion.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include "graphical/commands.h"
#include "graphical/protocols.h"
#include "world.h"
#include "linked_list.h"
#include "unit_tests.h"
Test(send_laying_egg, simple_test)
{
int player_num = 34;
int fd = open("tmp_laying_egg", O_CREAT | O_RDWR, 0644);
char buffer[80] = {0};
const size_t size = PKT_HDR_LEN + SRV_PLAYER_EGG_LAYING_LEN;
char result[PKT_HDR_LEN + SRV_PLAYER_EGG_LAYING_LEN + 1] = {0};
pkt_header_t hdr = {SRV_EGG_LAYING, PROTOCOL_VERSION,
SRV_PLAYER_EGG_LAYING_LEN, 0};
srv_player_egg_laying_t egg = {player_num};
cmd_info_t cmd[MAX_SENDERS] = {{0}};
cmd[INT_SENDER_POS] = (cmd_info_t){&player_num, sizeof(int)};
cr_assert_neq(fd, -1);
wrap_graph_protocol_commands(&send_laying_egg, fd, cmd);
memcpy(result, &hdr, PKT_HDR_LEN);
memcpy(result + PKT_HDR_LEN, &egg, SRV_PLAYER_EGG_LAYING_LEN);
read(fd, buffer, size);
for (size_t i = 0 ; i < size ; i++)
cr_assert_eq(buffer[i], result[i]);
close(fd);
}
Test(send_layed_egg, simple_test)
{
int egg_num = 34;
int fd = open("tmp_layed_egg", O_CREAT | O_RDWR, 0644);
char buffer[80] = {0};
const size_t size = PKT_HDR_LEN + SRV_PLAYER_EGG_LAYED_LEN;
char result[PKT_HDR_LEN + SRV_PLAYER_EGG_LAYED_LEN + 1] = {0};
pkt_header_t hdr = {SRV_EGG_LAYED, PROTOCOL_VERSION,
SRV_PLAYER_EGG_LAYED_LEN, 0};
srv_player_egg_layed_t egg = {23, 34, 34, 34};
player_t player = {0, 23, 1, 10, {0}, 34, 34, 1, 0, 0, 0};
cmd_info_t cmd[MAX_SENDERS] = {{0}};
cmd[PLAYER_SENDER_POS] = (cmd_info_t){&player, sizeof(player_t)};
cmd[INT_SENDER_POS] = (cmd_info_t){&egg_num, sizeof(int)};
cr_assert_neq(fd, -1);
wrap_graph_protocol_commands(&send_layed_egg, fd, cmd);
memcpy(result, &hdr, PKT_HDR_LEN);
memcpy(result + PKT_HDR_LEN, &egg, SRV_PLAYER_EGG_LAYED_LEN);
read(fd, buffer, size);
for (size_t i = 0 ; i < size ; i++)
cr_assert_eq(buffer[i], result[i]);
close(fd);
}
Test(send_hatching_egg, simple_test)
{
int egg_num = 34;
int fd = open("tmp_hatching_egg", O_CREAT | O_RDWR, 0644);
char buffer[80] = {0};
const size_t size = PKT_HDR_LEN + SRV_PLAYER_EGG_HATCHING_LEN;
char result[PKT_HDR_LEN + SRV_PLAYER_EGG_HATCHING_LEN + 1] = {0};
pkt_header_t hdr = {SRV_EGG_HATCHING, PROTOCOL_VERSION,
SRV_PLAYER_EGG_HATCHING_LEN, 0};
srv_player_egg_hatching_t egg = {34};
cmd_info_t cmd[MAX_SENDERS] = {{0}};
cmd[INT_SENDER_POS] = (cmd_info_t){&egg_num, sizeof(int)};
cr_assert_neq(fd, -1);
wrap_graph_protocol_commands(&send_hatching_egg, fd, cmd);
memcpy(result, &hdr, PKT_HDR_LEN);
memcpy(result + PKT_HDR_LEN, &egg, SRV_PLAYER_EGG_HATCHING_LEN);
read(fd, buffer, size);
for (size_t i = 0 ; i < size ; i++)
cr_assert_eq(buffer[i], result[i]);
close(fd);
}
Test(send_egg_connection, simple_test)
{
int egg_num = 34;
int fd = open("tmp_egg_connection", O_CREAT | O_RDWR, 0644);
char buffer[80] = {0};
const size_t size = PKT_HDR_LEN + SRV_PLAYER_EGG_CONNECTION_LEN;
char result[PKT_HDR_LEN + SRV_PLAYER_EGG_CONNECTION_LEN + 1] = {0};
pkt_header_t hdr = {SRV_PLAYER_CONNECT_EGG, PROTOCOL_VERSION,
SRV_PLAYER_EGG_CONNECTION_LEN, 0};
srv_player_egg_connection_t egg = {34};
cmd_info_t cmd[MAX_SENDERS] = {{0}};
cmd[INT_SENDER_POS] = (cmd_info_t){&egg_num, sizeof(int)};
cr_assert_neq(fd, -1);
wrap_graph_protocol_commands(&send_egg_connection, fd, cmd);
memcpy(result, &hdr, PKT_HDR_LEN);
memcpy(result + PKT_HDR_LEN, &egg, SRV_PLAYER_EGG_CONNECTION_LEN);
read(fd, buffer, size);
for (size_t i = 0 ; i < size ; i++)
cr_assert_eq(buffer[i], result[i]);
close(fd);
}
Test(send_egg_hatched_death, simple_test)
{
int egg_num = 34;
int fd = open("tmp_egg_hatched", O_CREAT | O_RDWR, 0644);
char buffer[80] = {0};
const size_t size = PKT_HDR_LEN + SRV_HATCHED_EGG_DEATH_LEN;
char result[PKT_HDR_LEN + SRV_PLAYER_EGG_CONNECTION_LEN + 1] = {0};
pkt_header_t hdr = {SRV_PLAYER_DEATH_EGG, PROTOCOL_VERSION,
SRV_HATCHED_EGG_DEATH_LEN, 0};
srv_player_egg_hatching_t egg = {34};
cmd_info_t cmd[MAX_SENDERS] = {{0}};
cmd[INT_SENDER_POS] = (cmd_info_t){&egg_num, sizeof(int)};
cr_assert_neq(fd, -1);
wrap_graph_protocol_commands(&send_egg_hatched_death, fd, cmd);
memcpy(result, &hdr, PKT_HDR_LEN);
memcpy(result + PKT_HDR_LEN, &egg, SRV_HATCHED_EGG_DEATH_LEN);
read(fd, buffer, size);
for (size_t i = 0 ; i < size ; i++)
cr_assert_eq(buffer[i], result[i]);
close(fd);
}
|
C
|
#include <stdio.h>
int main() {
double a = 10.0;
double *a_ptr = &a;
char c = 0;
char *c_ptr = &c;
printf("%p: %c\n", c_ptr, *c_ptr);
// *a_ptr *= 2;
// printf("%p: %lf\n", a_ptr, *a_ptr);
// printf("%p: %lf\n", &a, a);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
float num1,num2;
char c[5];
printf("Enter a no: ");
scanf("%f", &num1);
printf("Enter operator: ");
scanf("%s", &c);
if(strcmp(c,"+")==0||strcmp(c,"-")==0||strcmp(c,"/")==0||strcmp(c,"*")==0)
{
printf("Enter another no: ");
scanf("%f", &num2);
if(strcmp(c,"+")==0){
printf("%f", num1+num2);
}
else if(strcmp(c,"-")==0){
printf("%f", num1-num2);
}
else if(strcmp(c,"/")==0){
printf("%f", num1/num2);
}
else if(strcmp(c,"*")==0){
printf("%f", num1*num2);
}
}
else if(strcmp(c,"sin")==0||strcmp(c,"log")==0){
if(strcmp(c,"sin")==0){
printf("%f",sin(num1));
}
else if(strcmp(c,"log")==0){
printf("%f",log(num1));
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
/*1. Отримує та друкує інформацію про параметри свого процесу за допомогою системних
викликів getpid(), getgid(), getsid() тощо.
2. Виконує розгалудження процесу за допомогою системного виклику fork().
3. Для процесу-батька та процесу-нащадка окремо роздруковує їхні ідентифікатори у
циклі.
4. Виконати очікування процесом-батьком завершення нащадка.
5. Повідомляє про завершення процесів — батька та нащадка.
6. Пояснити отримані результати*/
int main(){
gid_t currGid = getgid();
pid_t currPid = getpid();
pid_t currParentPid = getppid();
uid_t currUid = getuid();
printf("Process ID: %i\n", currPid);
printf("Process Parent ID: %i\n", currParentPid);
printf("User ID: %i\n", currUid);
printf("Group ID: %i\n", currGid);
printf("Cloning...\n");
if(fork() > 0){ // parent
printf("Parent Process ID: %i\n", currPid);
wait(NULL);
}else{ //child
printf("Child Process ID: %i\n", getpid());
exit(0);
}
printf("Parent and child finished\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct knot {
char exp[200];
struct knot* left;
struct knot* right;
} knot;
int e (int a, int b);
int ou (int a, int b);
int imp (int a, int b);
int neg (int a);
int val (char exp[]);
int meio (char exp[]);
int valsalva (char exp[], knot* root);
knot* insert (knot* root, char exp[]);
void emordem(knot *q, FILE* fp);
void emordemval(knot *q, FILE* fp);
void preord(knot *root);
int* vetxyzw (int* vet, char exp[]);
void emordemln (knot *q, FILE* fp);
int x=0, y=0, z=0, t=0;
int tau=1;
int sat=0;
int main () {
FILE *fp;
FILE *fi;
fi = fopen("Expressoes.in", "r");
fp = fopen("Expressoes.out", "w");
int vet[4] = {0,0,0,0};
char exp[200];
int casos=0;
fscanf(fi, "%d", &casos);
//scanf("%d", &casos);
int c=0;
for (c=1; c<=casos; c++){
vet[0]=0;
vet[1]=0;
vet[2]=0;
vet[3]=0;
fprintf (fp, "Tabela #%d\n", c);
fflush(stdin);
fscanf(fi, "%s", exp);
//gets(exp);
vetxyzw (vet, exp);
knot *n = (knot*) malloc(sizeof(knot));
strcpy (n->exp,exp);
n->right = n->left = NULL;
valsalva (exp, n);
fprintf(fp, "-");
emordemln(n, fp);
fprintf(fp, "\n");
if (vet[0]) fprintf (fp, "|x");
if (vet[1]) fprintf (fp, "|y");
if (vet[2]) fprintf (fp, "|z");
if (vet[3]) fprintf (fp, "|t");
emordem (n, fp);
fprintf(fp, "|");
fprintf(fp, "\n");
for (x=0; x<=vet[0]; ++x){
for (y=0; y<=vet[1]; ++y){
for (z=0; z<=vet[2]; ++z){
for (t=0; t<=vet[3]; ++t){
fprintf(fp, "-");
emordemln(n, fp);
fprintf(fp, "\n");
emordemval(n, fp);
fprintf(fp, "|");
fprintf(fp, "\n");
if (val(exp)==1) sat=1;
else tau=0;
}
}
}
}
fprintf(fp, "-");
emordemln(n, fp);
fprintf(fp, "\n");
if (sat==1) fprintf (fp, "satsfativel e ");
else fprintf (fp, "insatisfatvel e ");
if (tau==1) fprintf (fp, "tautologia");
else fprintf (fp, "refutvel");
fprintf (fp, "\n");
fprintf (fp, "\n");
x=0, y=0, z=0, t=0;
tau=1;
sat=0;
//emordemval (n);
//fprintf ("final: %d", val (exp));
//fprintf("meio: %d", meio(exp));
free(n);
}
fclose(fp);
fclose(fi);
return 0;
}
int* vetxyzw (int* vet, char exp[]){
int i=0;
for (i=0; i<strlen(exp); i++){
if (exp[i]=='x') vet[0]=1;
if (exp[i]=='y') vet[1]=1;
if (exp[i]=='z') vet[2]=1;
if (exp[i]=='t') vet[3]=1;
}
}
void emordemln (knot *q, FILE* fp){
int s;
if(q != NULL) {
emordemln(q->left, fp);
for (s=0; s<(strlen(q->exp)+1); s++){
fprintf(fp, "-");
}
emordemln(q->right, fp);
}
}
void emordem(knot *q, FILE* fp) {
if(q != NULL) {
emordem(q->left, fp);
if (strlen(q->exp)!=1){
fprintf(fp, "|%s",q->exp);
}
emordem(q->right, fp);
}
}
void emordemval(knot *q, FILE* fp) {
int s;
if(q != NULL) {
emordemval(q->left, fp);
fprintf(fp, "|");
for (s=0; s<strlen(q->exp)-1; s++){
fprintf(fp, " ");
}
fprintf(fp, "%d",val(q->exp));
emordemval(q->right, fp);
}
}
knot* insert (knot* root, char exp[]){
if (root==NULL) {
knot *novo = (knot*) malloc(sizeof(knot));
if (novo==NULL) exit(1);
strcpy(novo->exp, exp);
novo->right = novo->left = NULL;
return novo;
}//((x+y).(y+z))
else if (strlen(exp)<strlen(root->exp)){
root->left = insert (root->left, exp);
}
else if (strlen(exp)>strlen(root->exp)){
root->right = insert (root->right, exp);
}
else if (strcmp(exp,root->exp)<0) {
root->left = insert (root->left, exp);
}
else if (strcmp(exp,root->exp)>0){
root->right = insert (root->right, exp);
}
return (root);
//emordem (root);//
}
int valsalva (char exp[], knot* root){
int tam = strlen(exp);
char exp2[200], exp3[200]; int i=0;
//bases recursivas
//int x=0, y=0, z=0, t=0;//funcao para variar valores
if (strcmp (exp, "x")==0) return x;
if (strcmp (exp, "y")==0) return y;
if (strcmp (exp, "z")==0) return z;
if (strcmp (exp, "t")==0) return t;
//casos recursivos
char op = exp[meio(exp)];
switch(op){
//negacao
case '-':
for (i=0; i<tam-1 ;i++) exp2[i]=exp[i+2];
exp2[i-2]='\0';
//salva exp2
insert (root, exp2);
//fprintf ("%s\n", exp2);
//fprintf("%d\n", neg(val(exp2)));
return neg(valsalva(exp2, root));
break;
//e
case '.':
for (i=0;i<meio(exp);i++) exp2[i]=exp[i+1];
exp2[i-1]='\0';
//salva exp2
insert (root, exp2);
//fprintf("%s\n", exp2);
for (i=0;i<(tam-meio(exp));i++) exp3[i]=exp[i+meio(exp)+1];
exp3[i-2]='\0';
//salva exp3
insert (root, exp3);
//fprintf("%s\n", exp3);
return e(valsalva(exp2, root),valsalva(exp3, root));
break;
//ou
case '+':
for (i=0;i<meio(exp);i++) exp2[i]=exp[i+1];
exp2[i-1]='\0';
//salva exp2
insert (root, exp2);
//fprintf("%s\n", exp2);
for (i=0;i<(tam-meio(exp));i++) exp3[i]=exp[i+meio(exp)+1];
exp3[i-2]='\0';
//salva exp3
insert (root, exp3);
//fprintf("%s\n", exp3);
return ou(valsalva(exp2, root),valsalva(exp3, root));
break;
//imp
case '>':
for (i=0;i<meio(exp);i++) exp2[i]=exp[i+1];
exp2[i-1]='\0';
//salva exp2
insert (root, exp2);
//fprintf("%s\n", exp2);
for (i=0;i<(tam-meio(exp));i++) exp3[i]=exp[i+meio(exp)+1];
exp3[i-2]='\0';
//salva exp3
insert (root, exp3);
//fprintf("%s\n", exp3);
return imp(valsalva(exp2, root),valsalva(exp3, root));
break;
//extra parenteses
}
}
int val (char exp[]){
int tam = strlen(exp);
char exp2[200], exp3[200]; int i=0;
//bases recursivas
//int x=0, y=0, z=0, t=0;//funcao para variar valores
if (strcmp (exp, "x")==0) return x;
if (strcmp (exp, "y")==0) return y;
if (strcmp (exp, "z")==0) return z;
if (strcmp (exp, "t")==0) return t;
//casos recursivos
char op = exp[meio(exp)];
switch(op){
//negacao
case '-':
for (i=0; i<tam-1 ;i++) exp2[i]=exp[i+2];
exp2[i-2]='\0';
//salva exp2
//fprintf ("%s", exp2);
//fprintf("%d\n", neg(val(exp2)));
return neg(val(exp2));
break;
//e
case '.':
for (i=0;i<meio(exp);i++) exp2[i]=exp[i+1];
exp2[i-1]='\0';
//salva exp2
//fprintf("%s", exp2);
for (i=0;i<(tam-meio(exp));i++) exp3[i]=exp[i+meio(exp)+1];
exp3[i-2]='\0';
//salva exp3
//fprintf("%s", exp3);
return e(val(exp2),val(exp3));
break;
//ou
case '+':
for (i=0;i<meio(exp);i++) exp2[i]=exp[i+1];
exp2[i-1]='\0';
//salva exp2
//fprintf("%s", exp2);
for (i=0;i<(tam-meio(exp));i++) exp3[i]=exp[i+meio(exp)+1];
exp3[i-2]='\0';
//salva exp3
//fprintf("%s", exp3);
return ou(val(exp2),val(exp3));
break;
//imp
case '>':
for (i=0;i<meio(exp);i++) exp2[i]=exp[i+1];
exp2[i-1]='\0';
//salva exp2
//fprintf("%s", exp2);
for (i=0;i<(tam-meio(exp));i++) exp3[i]=exp[i+meio(exp)+1];
exp3[i-2]='\0';
//salva exp3
//fprintf("%s", exp3);
return imp(val(exp2),val(exp3));
break;
//extra parenteses
}
}
int e (int a, int b){
return (a&&b);
}
int ou (int a, int b){
return (a||b);
}
int imp (int a, int b){
if (a==0 || (a!=0 && b!=0)) return 1;
else return 0;
}
int neg (int a){
return !a;
}
int meio (char exp[]){
int l=0, i=0;
int tam = strlen(exp);
while (i<tam){
if (exp[i]=='(') l++;
if (exp[i]==')') l--;
if (l==1){
if (exp[i+1]=='-'||exp[i+1]=='+'||exp[i+1]=='.'||exp[i+1]=='>'){
return i+1;
}
if (exp[i+2]=='+'||exp[i+2]=='.'||exp[i+2]=='>'){
return i+2;
}
}
i++;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <fexpression.h>
int main(int argc, char** argv)
{
/* initialization */
obj_init();
fexp_init();
/* create some objects */
object* s1 = send(String, s_string_fromwchar, L"Some String");
send(s1, s_print);
wprintf(L"\n");
object* s2 = send(String, s_string_fromwchar, L"Some Other String");
send(s2, s_print);
wprintf(L"\n");
object* f = (object*)fexp_nil;
f = send(f, s_fexp_cons, s1);
f = send(f, s_fexp_cons, s2);
send(f, s_print);
wprintf(L"\n");
/* check their types */
wprintf(L"s1(%p) string_vt(%p) String(%p)\n", send(s1, s_type), string_vt, send(String, s_type));
wprintf(L"s2(%p) string_vt(%p) String(%p)\n", send(s2, s_type), string_vt, send(String, s_type));
wprintf(L"f(%p) fexp_vt(%p) Fexp(%p)\n", send(f, s_type), fexp_vt, send(Fexp, s_type));
return EXIT_SUCCESS;
}
|
C
|
/*************************************************************************
> FileName: aes.c
> Author : DingJing
> Mail : dingjing@live.cn
> Created Time: 2020年12月23日 星期三 20时01分16秒
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
#define DSP_DES_CBC_KEY "123456789"
int main (int argc, char* argv[])
{
unsigned char aes_key[AES_BLOCK_SIZE] = {0};
unsigned char ivc[AES_BLOCK_SIZE] = {0};
unsigned char enc_out[256] = {0};
unsigned char tmp[128] = {0};
int ret = snprintf((char *)tmp, sizeof(tmp), "%s", "hello world");
int encslength = ((ret + AES_BLOCK_SIZE) / AES_BLOCK_SIZE) * AES_BLOCK_SIZE;
memset(ivc, 0, sizeof(ivc));
AES_KEY enc_key;
memcpy(aes_key, DSP_DES_CBC_KEY, sizeof(DSP_DES_CBC_KEY));
AES_set_encrypt_key(aes_key, 128, &enc_key);
AES_cbc_encrypt((unsigned char*)tmp, enc_out, encslength, &enc_key, ivc, AES_ENCRYPT);
printf("AES_ENCRYPT: %s\n", enc_out);
memset(ivc, 0, sizeof(ivc));
unsigned char decrypt_string[256] = {0};
AES_set_decrypt_key(aes_key, 128, &enc_key);
AES_cbc_encrypt(enc_out, decrypt_string, encslength, &enc_key, ivc, AES_DECRYPT);
printf("AES_DECRYPT: %s\n", decrypt_string);
return 0;
}
|
C
|
#include "key.h"
void KEY_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOB_CLK_ENABLE();
/*Configure GPIO pins : PB12 PB13 */
GPIO_InitStruct.Pin = GPIO_PIN_12|GPIO_PIN_13;
GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/* EXTI interrupt init*/
HAL_NVIC_SetPriority(EXTI15_10_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(EXTI15_10_IRQn);
}
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
HAL_Delay(50);
switch(GPIO_Pin)
{
case GPIO_PIN_12:
if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_12) == GPIO_PIN_RESET)
HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_14);
break;
case GPIO_PIN_13:
if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_13) == GPIO_PIN_RESET)
HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_15);
break;
}
}
|
C
|
/*
3. Write a program to implement Bellman-Ford Algorithm
using Dynamic Programming and verify the time complexity.
*/
#include <stdio.h>
#include <stdlib.h>
#include<limits.h>
int Bellman_Ford(int G[10][10] , int V, int E, int edge[100][2])
{
int i,u,v,k,distance[20],parent[10],S,flag=1;
for(i=0;i<V;i++)
distance[i] = INT_MAX , parent[i] = -1 ;
printf("Enter source: ");
scanf("%d",&S);
distance[S-1]=0 ;
for(i=0;i<V-1;i++)
{
for(k=0;k<E;k++)
{
u = edge[k][0] , v = edge[k][1] ;
if(distance[u]+G[u][v] < distance[v])
distance[v] = distance[u] + G[u][v] , parent[v]=u ;
}
}
for(k=0;k<E;k++)
{
u = edge[k][0] , v = edge[k][1] ;
if(distance[u]+G[u][v] < distance[v])
flag = 0 ;
}
if(flag)
for(i=0;i<V;i++)
printf("Vertex %d -> cost = %d parent = %d\n",i+1,distance[i],parent[i]+1);
return flag;
}
int main()
{
int V,edge[100][2],G[10][10],i,j,k=0;
printf("Enter no. of vertices: ");
scanf("%d",&V);
if(V>10)
exit(0);
printf("Enter graph in matrix form:\n");
for(i=0;i<V;i++)
for(j=0;j<V;j++)
{
scanf("%d",&G[i][j]);
if(G[i][j]!=0)
edge[k][0]=i,edge[k++][1]=j;
}
if(Bellman_Ford(G,V,k,edge))
printf("\nNo negative weight cycle\n");
else printf("\nNegative weight cycle exists\n");
return 0;
}
|
C
|
#ifndef FOREACH_H_
#define FOREACH_H_
// source: http://stackoverflow.com/questions/14732803/preprocessor-variadic-for-each-macro-compatible-with-msvc10
#define SEMICOLON ;
#define NOTHING
#define EXPAND(x) x
#define FOR_EACH_NARG(...) FOR_EACH_NARG_(__VA_ARGS__, FOR_EACH_RSEQ_N())
#define FOR_EACH_NARG_(...) EXPAND(FOR_EACH_ARG_N(__VA_ARGS__))
#define FOR_EACH_ARG_N(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, N, ...) N
#define FOR_EACH_RSEQ_N() 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
#define CONCATENATE(x,y) x##y
#define FOR_EACH_1(what, sep, x, ...) what(x)
#define FOR_EACH_2(what, sep, x, ...)\
what(x) sep \
EXPAND(FOR_EACH_1(what, sep, __VA_ARGS__))
#define FOR_EACH_3(what, sep, x, ...)\
what(x) sep \
EXPAND(FOR_EACH_2(what, sep, __VA_ARGS__))
#define FOR_EACH_4(what, sep, x, ...)\
what(x) sep \
EXPAND(FOR_EACH_3(what, sep, __VA_ARGS__))
#define FOR_EACH_5(what, sep, x, ...)\
what(x) sep \
EXPAND(FOR_EACH_4(what, sep, __VA_ARGS__))
#define FOR_EACH_6(what, sep, x, ...)\
what(x) sep \
EXPAND(FOR_EACH_5(what, sep, __VA_ARGS__))
#define FOR_EACH_7(what, sep, x, ...)\
what(x) sep \
EXPAND(FOR_EACH_6(what, sep, __VA_ARGS__))
#define FOR_EACH_8(what, sep, x, ...)\
what(x) sep \
EXPAND(FOR_EACH_7(what, sep, __VA_ARGS__))
#define FOR_EACH_9(what, sep, x, ...)\
what(x) sep \
EXPAND(FOR_EACH_8(what, sep, __VA_ARGS__))
#define FOR_EACH_10(what, sep, x, ...)\
what(x) sep \
EXPAND(FOR_EACH_9(what, sep, __VA_ARGS__))
#define FOR_EACH_11(what, sep, x, ...)\
what(x) sep \
EXPAND(FOR_EACH_10(what, sep, __VA_ARGS__))
#define FOR_EACH_12(what, sep, x, ...)\
what(x) sep \
EXPAND(FOR_EACH_11(what, sep, __VA_ARGS__))
#define FOR_EACH_13(what, sep, x, ...)\
what(x) sep \
EXPAND(FOR_EACH_12(what, sep, __VA_ARGS__))
#define FOR_EACH_14(what, sep, x, ...)\
what(x) sep \
EXPAND(FOR_EACH_13(what, sep, __VA_ARGS__))
#define FOR_EACH_15(what, sep, x, ...)\
what(x) sep \
EXPAND(FOR_EACH_14(what, sep, __VA_ARGS__))
#define FOR_EACH_16(what, sep, x, ...)\
what(x) sep \
EXPAND(FOR_EACH_15(what, sep, __VA_ARGS__))
#define FOR_EACH_17(what, sep, x, ...)\
what(x) sep \
EXPAND(FOR_EACH_16(what, sep, __VA_ARGS__))
#define FOR_EACH_18(what, sep, x, ...)\
what(x) sep \
EXPAND(FOR_EACH_17(what, sep, __VA_ARGS__))
#define FOR_EACH_19(what, sep, x, ...)\
what(x) sep \
EXPAND(FOR_EACH_18(what, sep, __VA_ARGS__))
#define FOR_EACH_20(what, sep, x, ...)\
what(x) sep \
EXPAND(FOR_EACH_19(what, sep, __VA_ARGS__))
#define FOR_EACH_(N, what, sep, ...) EXPAND(CONCATENATE(FOR_EACH_, N)(what, sep, __VA_ARGS__))
/**
* Repeatedly invokes macro [what] on each of the variable arguments [...], separating each invocation
* by [sep].
*/
#define FOR_EACH_SEP(sep, what, ...) FOR_EACH_(FOR_EACH_NARG(__VA_ARGS__), what, sep, __VA_ARGS__)
/**
* Repeatedly invokes macro [what] on each of the variable arguments [...].
*/
#define FOR_EACH(what, ...) FOR_EACH_SEP(NOTHING, what, __VA_ARGS__)
// separated by COMMA
#define FOR_EACH_COMMA_1(what, x, ...) what(x)
#define FOR_EACH_COMMA_2(what, x, ...)\
what(x) , \
EXPAND(FOR_EACH_COMMA_1(what, __VA_ARGS__))
#define FOR_EACH_COMMA_3(what, x, ...)\
what(x) , \
EXPAND(FOR_EACH_COMMA_2(what, __VA_ARGS__))
#define FOR_EACH_COMMA_4(what, x, ...)\
what(x) , \
EXPAND(FOR_EACH_COMMA_3(what, __VA_ARGS__))
#define FOR_EACH_COMMA_5(what, x, ...)\
what(x) , \
EXPAND(FOR_EACH_COMMA_4(what, __VA_ARGS__))
#define FOR_EACH_COMMA_6(what, x, ...)\
what(x) , \
EXPAND(FOR_EACH_COMMA_5(what, __VA_ARGS__))
#define FOR_EACH_COMMA_7(what, x, ...)\
what(x) , \
EXPAND(FOR_EACH_COMMA_6(what, __VA_ARGS__))
#define FOR_EACH_COMMA_8(what, x, ...)\
what(x) , \
EXPAND(FOR_EACH_COMMA_7(what, __VA_ARGS__))
#define FOR_EACH_COMMA_9(what, x, ...)\
what(x) , \
EXPAND(FOR_EACH_COMMA_8(what, __VA_ARGS__))
#define FOR_EACH_COMMA_10(what, x, ...)\
what(x) , \
EXPAND(FOR_EACH_COMMA_9(what, __VA_ARGS__))
#define FOR_EACH_COMMA_11(what, x, ...)\
what(x) , \
EXPAND(FOR_EACH_COMMA_10(what, __VA_ARGS__))
#define FOR_EACH_COMMA_12(what, x, ...)\
what(x) , \
EXPAND(FOR_EACH_COMMA_11(what, __VA_ARGS__))
#define FOR_EACH_COMMA_13(what, x, ...)\
what(x) , \
EXPAND(FOR_EACH_COMMA_12(what, __VA_ARGS__))
#define FOR_EACH_COMMA_14(what, x, ...)\
what(x) , \
EXPAND(FOR_EACH_COMMA_13(what, __VA_ARGS__))
#define FOR_EACH_COMMA_15(what, x, ...)\
what(x) , \
EXPAND(FOR_EACH_COMMA_14(what, __VA_ARGS__))
#define FOR_EACH_COMMA_16(what, x, ...)\
what(x) , \
EXPAND(FOR_EACH_COMMA_15(what, __VA_ARGS__))
#define FOR_EACH_COMMA_17(what, x, ...)\
what(x) , \
EXPAND(FOR_EACH_COMMA_16(what, __VA_ARGS__))
#define FOR_EACH_COMMA_18(what, x, ...)\
what(x) , \
EXPAND(FOR_EACH_COMMA_17(what, __VA_ARGS__))
#define FOR_EACH_COMMA_19(what, x, ...)\
what(x) , \
EXPAND(FOR_EACH_COMMA_18(what, __VA_ARGS__))
#define FOR_EACH_COMMA_20(what, x, ...)\
what(x) , \
EXPAND(FOR_EACH_COMMA_19(what, __VA_ARGS__))
#define FOR_EACH_COMMA_(N, what, ...) EXPAND(CONCATENATE(FOR_EACH_COMMA_, N)(what, __VA_ARGS__))
/**
* Repeatedly invokes macro [what] on each of the variable arguments [...], separating each invocation
* by a comma (,).
*/
#define FOR_EACH_SEP_COMMA(what, ...) FOR_EACH_COMMA_(FOR_EACH_NARG(__VA_ARGS__), what, __VA_ARGS__)
#endif /* FOREACH_H_ */
|
C
|
#include <math.h>
#include <stdio.h>
main()
{
int ii, jj, kk, n=5;
double dx1, dx2, dx3, Y, ddata, err, error;
double dx1a, dx2a, dx3a, maxerr;
FILE *fp = fopen("pred.dat", "r");
double pi2 = 3.14159, pi1=0.5*3.14159;
error = 0.0;
maxerr = 0.0;
for (ii = 0; ii < n; ii++)
{
dx1 = 1.0 / (n-1) * ii;
dx1a = pi2 * dx1 - pi1;
for (jj = 0; jj < n; jj++)
{
dx2 = 1.0 / (n-1) * jj;
dx2a = pi2 * dx2 - pi1;
for (kk = 0; kk < n; kk++)
{
dx3 = 1.0 / (n-1) * kk;
dx3a = pi2 * dx3 - pi1;
Y=sin(dx1a)+7.0*sin(dx2a)*sin(dx2a)+0.1*dx3a*dx3a*dx3a*dx3a*sin(dx1a);
fscanf(fp, "%lg \n", &ddata);
err = (Y - ddata) * (Y - ddata);
if (err > maxerr) maxerr = err;
error += err;
printf("%5d : %12.4e %12.4e %12.4e \n", ii*n*n+jj*n+kk+1, Y, ddata, err);
}
}
}
printf("L-1 norm squared error = %e\n", maxerr);
printf("L-2 norm squared error = %e\n", error);
fclose(fp);
}
|
C
|
#include "main.h"
/**
* _get_binary - get the integer from _printf %b
* then convert into binary
* @args: argument corresponding to %b
* Return: lenght of character printed
*/
int _get_binary(va_list args)
{
unsigned int b = va_arg(args, unsigned int);
int len, i;
char *str_binary = NULL;
if (b == 0)
return (_putchar('0'), 1);
str_binary = malloc(sizeof(char) * 32);
if (str_binary == NULL)
{
free(str_binary);
return (0);
}
for (i = 0; b != 0; i++)
{
str_binary[i] = b % 2 + '0';
b /= 2;
}
for (len = 0; str_binary[len]; len++)
;
for (len--; str_binary[len]; len--)
_putchar(str_binary[len]);
free(str_binary);
return (i);
}
|
C
|
int count_nodes(struct node *p)
{
if(p==NULL)
{
return(0);
}
else
{
return(1+count_nodes(p->left)+count_nodes(p->right));
}
}
|
C
|
#pragma once
//////////////////////////////////////////////////////////////////////////
#define RECV_BUF_MAX_COUNT (64*1024)
#define RECV_BUF_NODE_COUNT (200)
//////////////////////////////////////////////////////////////////////////
typedef struct _b_recv_buf_node_type
{
int DataLen;
unsigned char Buf[RECV_BUF_MAX_COUNT];
}Recv_Buf_Node_Type;
//һܻ
typedef struct _recv_buf_queue_
{
int front; //ͷָ
int rear; //βָ
int number; //ǰеĽ
Recv_Buf_Node_Type Node[RECV_BUF_NODE_COUNT]; //洢
}Recv_Buf_Queue;
void InitRecvQueue(Recv_Buf_Queue &RecvQueue);//ʼ
void ClearRecvQueue(Recv_Buf_Queue &RecvQueue);//ն
BOOL RecvQueueEmpty(Recv_Buf_Queue &RecvQueue);//ж϶ǷΪ
BOOL RecvQueueFull(Recv_Buf_Queue &RecvQueue);//ж϶Ƿ
int GetRecvHead(Recv_Buf_Queue &RecvQueue,Recv_Buf_Node_Type &Node);//õͷ
int GetRecvNodeNumber(Recv_Buf_Queue &RecvQueue);//õǰеĽ
int RecvEnQueue(Recv_Buf_Queue &RecvQueue,Recv_Buf_Node_Type &Node);//
int RecvDeQueue(Recv_Buf_Queue &RecvQueue,Recv_Buf_Node_Type &Node);//
|
C
|
#ifndef UTIL_H
#define UTIL_H
#include "../project.h"
// need to put all of function definitions in here and a comment saying what they do. Easier for us as well.
int getabsname(MINODE *mip, char name[]);
int get_block(int fd, int blk, char buf[ ]);
int put_block(int fd, int blk, char buf[ ]);
int tst_bit(char *buf, int bit);// test to see whether a bit is "on" == 1
int set_bit(char *buf, int bit);// set a bit
int clr_bit(char *buf, int bit);// clear a bit
// Uses name[] to search from the root of fd (file descriptor) to find the inode from the given pathname and
// returns memory location of the of the inode.
int getino(int fd, char *name);
/*
This function searches the data blocks of a DIR inode (inside an Minode[])
for name. You may assume a DIR has only 12 DIRECT data blocks. Return its inode number
*/
// Note: Will search for child name in given mip
int search(MINODE *mip, char *name);
/*
Once you have the ino of an inode, you may load the inode into a slot
in the Minode[] array. To ensure uniqueness, you must search the Minode[]
array to see whether the needed INODE already exists:
If you find the needed INODE already in a Minode[] slot, just inc its
refCount by 1 and return the Minode[] pointer.
If you do not find it in memory, you must allocate a FREE Minode[i], load
the INODE from disk into that Minode[i].INODE, initialize the Minode[]'s
other fields and return its address as a MINODE pointer,
*/
MINODE *iget(int dev, int ino);
/*
This function releases a Minode[] pointed by mip.
ALGORITHM
(1). dec refCount by 1.
(2). if (after dec) refCount > 0 ==> return;
(3). if (Minode[].dirty == 0) ==> no need to write back, so return;
(4). (refCount < 0 AND dirty==1) case ==> must write the INODE back to disk.
(5). To write an INODE back to disk:
Use minode's (dev, ino) to determine which INODE on disk,i.e. Use Mailman's
algorithm to determine the disk block and inode's offset in that block.
Read that block into a buf[ ], let INODE *ip point at the INODE in buf[ ].
Copy mip->INODE into *ip in buf[ ];
Write the block (in buf[ ]) back to disk.
*/
int iput(MINODE *mip);
/*
Given the parent DIR (MINODE pointer) and myino, this function finds
the name string of myino in the parent's data block. This is the SAME
as SEARCH() by myino, then copy its name string into myname[ ].
*/
int findmyname(MINODE *mip, int myino, char myname[]);
/*
For a DIR Minode, extract the inode numbers of . and ..
Read in 0th data block. The inumbers are in the first two dir entries.
*/
int findino(MINODE *mip, int *myino,int *parentino);
int tokenize(char path[],char returnval[][128],char * tok);// takes a path and a token and tokenizes the string based on the token.
int print_dir_entries(MINODE *mip);
#endif
|
C
|
#include <stdio.h>
//adding comment which must be removed in preprocessing step
int main()
{
int a=10;
int b=20;
printf("value of a is %d and of b is %d \n", a , b);
return 0;
}
|
C
|
//Author: Thomas Noelcke
//CS 372 Spring 2017
//
//Description: This is the client side of an instant messanger chat client.
//Client takes two arguments the host name for the computer the server is running on
//and the port number for the sever. This program will then ask you to enter in your handle
//a single work 10 character name. then you will be connected to the server and a chat session will begin
//the chat session can be ended at any time by typing \quit.
//#includes
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
//headers
int setUpConnection(char* host, int portNumber);
int sendMessage(int socketFD, char* handle);
int reciveMessage(int socketFD);
char* getHandle();
char* getInput();
void introduction();
int main(int argc, char** argv) {
introduction();
if(argc != 3){
fprintf(stderr, "Usage: chatclient <server-hostname> <port#>\n");
exit(1);
}
int portNum = atoi(argv[2]);
char host[100];
memset(host, '\0', sizeof(host));
strcpy(host, argv[1]);
//sets up the socket and gets the socket file descriptor so data can be sent and recived from the
//socket later.
int socketFD = setUpConnection(host, portNum);
char* handle = getHandle();
int userQuit = 0;
int serverQuit = 0;
while(userQuit == 0 && serverQuit == 0){
serverQuit = reciveMessage(socketFD);
userQuit = sendMessage(socketFD, handle);
}
}
void introduction(){
printf("Hello, This is a chat client for an instant messanger\n");
printf("you will be connected with another user and will send messages to eachother.\n");
printf("The Host you are connecting to will send the first message. After you recive it you");
printf("May send a message. You will then alternate. Type \\quit into your message to disconect\n");
printf("You will be asked to enter a handle it needs to be 10 characters or less with no spaces\n");
}
//this function sets up a connection with the server.
int setUpConnection(char* host, int portNumber){
int socketFD;
struct sockaddr_in serverAddress;
struct hostent* serverHostInfo;
//sets up the server address struct
memset((char*)&serverAddress, '\0', sizeof(serverAddress)); //clear out the address struct
serverAddress.sin_family = AF_INET; //create a network-capable socket
serverAddress.sin_port = htons(portNumber); //stor the portnumber with out regards to indianess
memcpy((char*)&serverAddress.sin_addr.s_addr, (char*)serverHostInfo->h_addr, serverHostInfo->h_length); //copy in the address
//set up the socket
socketFD = socket(AF_INET, SOCK_STREAM, 0); //create the socket
if(socketFD < 0){
fprintf(stderr, "Error Openening The Socket\n");
exit(1);
}
//connects to the server.
if(connect(socketFD, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) < 0){
fprintf(stderr, "Error Connecting to the server");
exit(1);
}
return socketFD;
}
//recives and dispalys a message form the server.
//If the server sends the message \quit this function returns
// 1. this connection is then closed.
int reciveMessage(int socketFD){
char buffer[513]; // max message size is 500 characters so 500 characters plus the handle + > + " " + \0 = 513 characters
memset(buffer, '\0', sizeof(buffer));
int charsRead = recv(socketFD, buffer, sizeof(buffer) - 1, 0);
if (charsRead < 0){
fprintf(stderr, "error reading from the socket\n");
exit(1);
}
if(strstr(buffer, "\\quit") != NULL){
return 1;
}
printf("%s\n", buffer);
return 0;
}
//sends a message to the server. If the user types quit it sends that
//message to the server cause the server to terminate the connection
//this function then returns 1 if that happnes.
int sendMessage(int socketFD, char* handle){
char message[514];
memset(message, '\0', sizeof(message));
strcpy(message, handle);
char* buffer;
printf("%s", handle);
buffer = getInput();
int size = 0;
if(strlen(buffer) < 500){
size = strlen(buffer);
} else {
size = 500;
}
strncat(message, (const char*) buffer, size);
strcat(message, "\n");
int charsWriten = send(socketFD, message, strlen(message), 0);
if(charsWriten < 0){
fprintf(stderr,"error writing to the socket\n");
exit(1);
}
if(strstr(buffer, "\\quit") != NULL){
free(buffer);
return 1;
}
free(buffer);
return 0;
}
//gets the user handle and returns it. Makes sure the handle is less than 10 characters
//DOES NO MEMORY CLEAN UP YOU ARE RESPOSIBLE FOR MAKING SURE THAT
//THE MEMORY IS FREED.
char* getHandle(){
int isValid = 0;
char* handle = NULL;
while(isValid == 0){
//propts the user and gets the handle
printf("Please enter your Handle:");
handle = getInput();
//checks that the handle is valid and ends the loop if it is
if(handle == NULL){
printf("That is an invalid handle Try again.\n");
} else if(strlen(handle) > 10) {
printf("Your handle is too long. Try again.\n");
} else {
isValid = 1;
}
}
char* toReturn = malloc(sizeof(char) * (strlen(handle) + 3));
strcpy(toReturn, handle);
strcat(toReturn, "> ");
return toReturn;
}
char* getInput(){
//make sure every thing has been displayed to the screen
fflush(stdout);
char* line;
line = NULL;
size_t lineSize = 0;
int num = getline(&line, &lineSize, stdin);
// the user didn't enter any thing.
if(line[0] == 10){
return NULL;
}
//discards newline.
line[num - 1] = '\0';
return line;
}
|
C
|
#include <stdio.h>
#define THREE 3
#define TWO 2
int main() {
int l, b, c;
c = 0;
scanf("%d %d", &l, &b);
while (l <= b) {
l *= THREE;
b *= TWO;
c++;
}
printf("%d\n", c);
}
|
C
|
/******************* celsious to farenheet ************************/
#include <stdio.h>
main()
{
float celsious,fahr,step=20,upper=200;
// celsious to farenheet
celsious = 0;
printf("\ftemperature convertion \n");
printf("celsious\t\tfarenheet\n");
while(celsious<=upper) {
f128ahr=((9*celsious)/5)+32;
printf("%6.2f\t\t\t%6.2f\t \n ",celsious,fahr);
celsious=celsious+20;
}
}
|
C
|
#include <stdio.h>
#define MAX_TREES 100
typedef struct BinNode *Position;
typedef struct BinNode *BinTree;
typedef struct Colletcion *BinQueue;
struct BinNode {
int Element;
Position LeftChild;
Position NextSibiling;
};
struct Colletcion {
int CurrentSize;
BinTree TheTrees[MAX_TREES];
};
BinTree CombineTrees(BinTree T1, BinTree T2)
{
if(T1->Element > T2->Element)
return CombineTrees(T2, T1);
T2->NextSibiling = T1->LeftChild;
T1->LeftChild = T2;
return T1;
}
BinQueue Merge(BinQueue H1, BinQueue H2)
{
BinTree T1, T2, Carry = NULL;
int i, j;
#if 0//Capacity is undefined.
if(H1->CurrentSize+H2->CurrentSize > Capacity) {
printf("Merge would exceed capcity\n");
return NULL;
}
#endif
H1->CurrentSize += H2->CurrentSize;
for(i=0, j=0; j<=H1->CurrentSize; i++, j*=2) {
T1 = H1->TheTrees[i];
T2 = H2->TheTrees[i];
switch (!!T1 + 2*(!!T2) + 4*(!!Carry)) {
case 0:
case 1:
break;
case 2:
H1->TheTrees[i] = T2;
H2->TheTrees[i] = NULL;
break;
case 4:
H1->TheTrees[i] = Carry;
Carry = NULL;
break;
case 3:
Carry = CombineTrees(T1, T2);
H1->TheTrees[i] = H2->TheTrees[i] = NULL;
break;
case 5:
Carry = CombineTrees(T1, Carry);
H1->TheTrees[i] = NULL;
break;
case 6:
Carry = CombineTrees(T2, Carry);
H2->TheTrees[i] = NULL;
break;
case 7:
H1->TheTrees[i] = Carry;
Carry = CombineTrees(T1, T2);
H2->TheTrees[i] = NULL;
break;
default:
break;
}
}
return H1;
}
static int IsEmpty(BinQueue H);
#define INFINITY 0xFFFFFFFFFFFFFFFF
int DeleteMin(BinQueue H)
{
int i, j;
int MinTree;
BinQueue DeletedQueue;
Position DeletedTree, OldRoot;
int MintItem;
if(IsEmpty(H)) {
printf("Empty binomial queue\n");
return -1;
}
MintItem = INFINITY;
for(i=0; i<MAX_TREES; i++) {
if(H->TheTrees[i] && H->TheTrees[i]->Element < MintItem) {
MintItem = H->TheTrees[i]->Element;
MinTree = i;
}
}
DeletedTree = H->TheTrees[MinTree];
OldRoot = DeletedTree;
DeletedTree = DeletedTree->LeftChild;
free(OldRoot);
DeletedQueue = Initialize();
DeletedQueue->CurrentSize = (1 << MinTree) - 1;
for(j=MinTree-1; j>=0; j--) {
DeletedQueue->TheTrees[j] = DeletedTree;
DeletedTree = DeletedTree->NextSibiling;
DeletedQueue->TheTrees[j]->NextSibiling = NULL;
}
H->TheTrees[MinTree] = NULL;
H->CurrentSize -= DeletedQueue->CurrentSize + 1;
Merge(H, DeletedQueue);
return MinTree;
}
|
C
|
/* Merge sort in C */
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
//Função para mesclar matrizes L e R em A.
//lefCount = número de elementos em L
//rightCount = número de elementos em R.
void Merge(int *A,int *L,int leftCount,int *R,int rightCount) {
int i,j,k;
//i - para marcar o índice de aubarray esquerdo (L)
//j - para marcar o índice do sub-raay direito (R)
//k - para marcar o índice do subarray mesclado (A)
i = 0; j = 0; k =0;
while(i<leftCount && j< rightCount) {
if(L[i] >= R[j]) A[k++] = L[i++];// >= para decrescente (garante que o anterior é sempre maior que o anterior)
else A[k++] = R[j++];
}
while(i < leftCount) A[k++] = L[i++];
while(j < rightCount) A[k++] = R[j++];
}
//Função recursiva para classificar uma matriz de inteiros.
void MergeSort(int *A,int n) {
int mid,i, *L, *R;
if(n < 2) return; //condição de base. Se o array tiver menos de dois elementos, não faça nada.
mid = n/2;// encontre o índice médio.
//criar subarrays esquerdo e direito
//Os elementos intermediários (do índice 0 até o meio-1) devem fazer parte da sub-matriz esquerda
//e (n-mid) elementos (do meio ao n-1) farão parte do sub-array direito
L = (int*)malloc(mid*sizeof(int));
R = (int*)malloc((n- mid)*sizeof(int));
for(i = 0;i<mid;i++) L[i] = A[i]; //criando subarray esquerdo
for(i = mid;i<n;i++) R[i-mid] = A[i];//criando subarray direito
MergeSort(L,mid); //ordenando o subarray esquerdo
MergeSort(R,n-mid); //classificando o subarray certo
Merge(A,L,mid,R,n-mid); //Mesclando L e R em A como lista classificada.
free(L);
free(R);
}
void MergeD(int *A,int *L,int leftCount,int *R,int rightCount) {
int i,j,k;
//i - para marcar o índice de aubarray esquerdo (L)
//j - para marcar o índice do sub-raay direito (R)
//k - para marcar o índice do subarray mesclado (A)
i = 0; j = 0; k =0;
while(i<leftCount && j< rightCount) {
if(L[i] < R[j]) A[k++] = L[i++]; // < para crescente (garante que o anterior é sempre menor que o anterior)
else A[k++] = R[j++];
}
while(i < leftCount) A[k++] = L[i++];
while(j < rightCount) A[k++] = R[j++];
}
void MergeSortD(int *A,int n) {
int mid,i, *L, *R;
if(n < 2) return;
mid = n/2;
L = (int*)malloc(mid*sizeof(int));
R = (int*)malloc((n- mid)*sizeof(int));
for(i = 0;i<mid;i++) L[i] = A[i];
for(i = mid;i<n;i++) R[i-mid] = A[i];
MergeSortD(L,mid);
MergeSortD(R,n-mid);
MergeD(A,L,mid,R,n-mid);
free(L);
free(R);
}
void CriaArray(int *A,int tam){
int i;
srand(time(NULL));
for(i=0;i<tam;i++){
*A = rand()% 100;
A++;
}
}
int main() {
int j,tam,mid;
printf("Digite O Tamanho do vetor : ");
scanf("%d",&tam);
int A[tam]; // creating an array of integers.
CriaArray(A,tam); // Criando array aleatorio
int i,numberOfElements=0;
mid = tam/2;
int E[mid],D[tam-mid];
for(i = 0;i<mid;i++) E[i] = A[i]; //criando subarray esquerdo
for(i = 0;i<tam-mid;i++) D[i] = A[mid+i]; // criando subarray direito
// Decrescente
numberOfElements = sizeof(E)/sizeof(E[0]); // É criado dois vetores apartir do vetor A
MergeSort(E,numberOfElements); // Para poder fazer metade crescente e outra decrescente
for(i = 0;i<mid;i++) A[i] = E[i]; // ou vice-versa
// Crescente
numberOfElements = sizeof(D)/sizeof(D[0]);
MergeSortD(D,numberOfElements);
for(i = 0;i<tam-mid;i++) A[mid+i]= D[i];
numberOfElements = sizeof(A)/sizeof(A[0]);
for(i = 0;i < numberOfElements;i++) printf("%d ",A[i]);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int i=34;
printf("int=%d i=%d 34=%d \n",sizeof(int),sizeof(i),sizeof(34));
char ch='a';
printf("char=%d ch=%d 'a'=%d \n",sizeof(char),sizeof(ch),sizeof('a')); //here we get 1 1 4 because 'a' store in ch as ASCII and the ASCII of 'a' is 97 and it is integer;
float f=34.7;
printf("float=%d f=%d 34.7=%d \n",sizeof(float),sizeof(f),sizeof(34.7)); // here we get 4 4 8 because only 34.7 take as a double,if we store it as float than wright 34.7f;
float ff=35.2f;
printf("float=%d ff=%d 35.2f=%d \n",sizeof(float),sizeof(ff),sizeof(35.2f));
double d=34.7;
printf("double=%d d=%d 34.7=%d \n",sizeof(double),sizeof(d),sizeof(34.7));
return 0;
}
|
C
|
/*
Student Name:Bishal Rai
Subject:Programming Fundamental
Roll No:13
Lab Sheet No:20
Program:To enter length and breadth and display area of rectangle using function
Date:18/01/2017
*/
#include<stdio.h>
void area();
int main()
{
area();
return 0;
}
void area()
{
int l,b,a;
printf("Enter the length:");
scanf("%d",&l);
printf("Enter the breadth:");
scanf("%d",&b);
a=l*b;
printf("The area of rectangle is:%d",a);
}
|
C
|
#include<stdio.h>
int main()
{
float n,a,d,e,f,g,h,i,j,k,l,m,p;
int b,c,o,q,r,s,t,u,v,w,x,y,z,zz,bb,cc,mm,pp,qq,rr,ll,dd;
scanf("%f",&n);
printf("NOTAS:\n");
if(n>100){
a=n/100;
b=n/100;
c=b*100;
d=(n-c);
printf("%d nota(s) de R$ 100.00\n",b);
}
else if(d>=50){
a=d/50;
o=d/50;
q=b*50;
e=(d-q);
printf("%d nota(s) de R$ 50.00\n",o);
}
else if(e>=20){
a=e/20;
r=e/20;
s=b*20;
f=(e-s);
printf("%d nota(s) de R$ 20.00\n",r);
}
else if(f>=10){
a=f/10;
ll=f/10;
dd=b*10;
g=(f-dd);
printf("%d nota(s) de R$ 10.00\n",b);
}
else if(g>=5){
a=g/5;
t=g/5;
u=b*5;
h=(g-u);
printf("%d nota(s) de R$ 5.00\n",t);
}
else if(h>=2){
a=h/5;
v=h/5;
w=b*5;
i=(h-w);
printf("%d nota(s) de R$ 2.00\n",v);
}
printf("MOEDAS:\n");
if(i>=1.00){
a=i/1;
x=i/1;
y=b*1;
j=(i-y);
printf("%d moeda(s) de R$ 1.00\n",x);
}
else if(j>=0.50){
a=j/0.50;
z=j/0.50;
zz=b*0.50;
k=(j-zz);
printf("%d moeda(s) de R$ 0.50\n",z);
}
else if(k>=0.25){
a=k/0.25;
bb=k/0.25;
cc=b*0.25;
l=(k-cc);
printf("%d moeda(s) de R$ 0.25\n",bb);
}
else if(l>=0.05){
a=l/0.05;
mm=l/0.05;
pp=b*0.05;
m=(l-pp);
printf("%d moeda(s) de R$ 0.05\n",mm);
}
else if(m>=0.01){
a=m/0.05;
qq=m/0.05;
printf("%d moeda(s) de R$ 0.01\n",qq);
}
return 0;
}
|
C
|
#ifndef _LIB_H
#define _LIB_H
// Add commands into this file. Please leave a short description.
// `cat` function. Copies stdin to stdout.
int cat(int argc, char *argv[]);
// `chmod` function. Changes files rights.
int chmod_lb(int argc, char *argv[]);
// chown function. Change the owner and the group owner of a file.
int chown_lb(int argc, char *argv[]);
// `cp` function. Copy a file into an other.
int cp(int argc, char *argv[]);
// `mv` function. move or rename a file
int mv(int argc, char *argv[]);
// `echo` function. Prints arguments.
int echo(int argc, char *argv[]);
// 'head' function. Prints the first 10 lines of a file.
int head(int argc, char*argv[]);
// `ls` function. List files and directories.
int ls(int argc, char *argv[]);
// `mkdir` function. Create a directory.
int mkdir_lb(int argc, char *argv[]);
// `pwd` function. Print the path of the current directory.
int pwd(int argc, char *argv[]);
// `rev` function. Reverse stdin to stdout.
int rev(int argc, char *argv[]);
// `rm` function. Remove file.
int rm(int argc, char *argv[]);
// `connect_lb` function. Connect to a server to execute remote commands.
int connect_lb(int argc, char *argv[]);
// `serveur_lb` function. Create a server.
int serveur_lb(int argc, char *argv[]);
#endif /* _LIB_H */
|
C
|
/*
** victory.c for sudoku in /home/brout_m/RENDU/CPE/sudoki-bi
**
** Made by marc brout
** Login <brout_m@epitech.net>
**
** Started on Sun Feb 28 21:29:36 2016 marc brout
** Last update Sun Feb 28 21:54:13 2016 marc brout
*/
#include "game.h"
void print_victory(t_bunny_pixelarray *back,
t_bunny_pixelarray *victory,
int x)
{
t_bunny_position pback;
t_bunny_position pvic;
unsigned int *pix;
unsigned int *vic;
pvic.y = -1;
pback.y = 200;
pix = back->pixels;
vic = victory->pixels;
while (++pvic.y < victory->clipable.clip_height && ++pback.y)
{
pvic.x = -1;
pback.x = x;
while (++pvic.x < victory->clipable.clip_width && ++pback.x <
back->clipable.clip_width)
pix[pback.x + pback.y * back->clipable.clip_width] =
vic[pvic.x + pvic.y * victory->clipable.clip_width];
}
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
char name[] = "你好";
printf("%s\n, arr size: %ld, str len: %d\n", name, sizeof(name), strlen(name));
return 0;
}
|
C
|
#pragma once
#pragma once
#include "stdio.h"
#include "stdlib.h"
#define HASHSIZE 10 // ɢб
#define NULLKEY -32768
typedef struct
{
int *elem; // Ԫش洢ַ̬
int count; // ǰԪظ
}HashTable;
int m = 0;
int Init(HashTable *H)
{
int i;
m = HASHSIZE;
H->elem = (int *)malloc(m * sizeof(int)); //ڴ
H->count = m;
for (i = 0; i<m; i++)
{
H->elem[i] = NULLKEY;
}
return 1;
}
int Hash(int k)
{
return k % m;//
}
void Insert(HashTable *H, int k)
{
int addr = Hash(k);
while (H->elem[addr] != NULLKEY)
{
addr = (addr + 1) % m;//Ŷַ
}
H->elem[addr] = k;
}
int Search(HashTable *H, int k)
{
int addr = Hash(k); //ϣַ
while (H->elem[addr] != k)//Ŷַͻ
{
addr = (addr + 1) % m;
if (H->elem[addr] == NULLKEY || addr == Hash(k))
return -1;
}
return addr;
}
void Result(HashTable *H)//ɢбԪʾ
{
int i;
for (i = 0; i<H->count; i++)
{
printf("%d ", H->elem[i]);
}
printf("\n");
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.