language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C | // 4.Write a program which accept number from user and count frequency of 4 in it.
// Input : 2395
// Output : 0
// Input : 1018
// Output : 0
// Input : 9440
// Output : 2
// Input : 922432
// Output : 1
#include <stdio.h>
int CountFour(int iNo)
{
int iDigit = 0;
int iCnt = 0;
while (iNo > 0)
{
iDigit = iNo % 10;
if (iDigit == 4)
{
iCnt++;
}
iNo = iNo / 10;
}
return iCnt;
}
int main()
{
int iValue = 0;
int iRet = 0;
printf("Enter The First Number");
scanf("%d", &iValue);
iRet = CountFour(iValue);
printf("%d\n", iRet);
return 0;
}
|
C | //inet函数族的使用
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
int main(void)
{
char buffer[32];
int ret = 0;
int host = 0;
int network = 0;
unsigned int address = 0;
char *str = NULL;
struct in_addr in;
in.s_addr = 0;
//输入一个以.分隔的字符串形式的IP地址
printf("please input your ip address:");
fgets(buffer,31,stdin);
buffer[31] = '\0';
//示例使用inet_aton()函数
if((ret = inet_aton(buffer,&in)) == 0) {
printf("inet_aton: \t invalid address\n");
}
else {
printf("inet_aton: \t 0x%x\n",in.s_addr);
}
//示例使用inet_addr()函数
if((address = inet_network(buffer)) == -1) {
printf("inet_addr: \t invalid address\n");
}
else {
printf("inet_addr: \t 0x%1x\n",address);
}
//示例使用inet_network()函数
if((address = inet_network(buffer)) == -1) {
printf("inet_network: \t invalid address\n");
}
else {
printf("inet_network: \t 0x%1x\n",address);
}
//示例使用inet_ntoa()函数
if((str = inet_ntoa(in)) == NULL) {
printf("inet_ntoa: \t invalid address\n");
}
else {
printf("inet_ntoa: \t %s \n",str);
}
//示例使用inet_lnaof()与inet_netof()函数
host = inet_lnaof(in);
network = inet_netof(in);
printf("inet_lnaof:\t0x%x\n",host);
printf("inet_netof:\t0x%x\n",network);
in = inet_makeaddr(network,host);
printf("inet_makeaddr:0x%x\n",in.s_addr);
return 0;
}
|
C | #include <ctype.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
bool finding_bracket(char* UKAZAT) //поиск скобки
{
int flag = 0;
while (*UKAZAT != 10) {
if (*UKAZAT == '(') {
flag = 1;
break;
}
UKAZAT++;
}
if (flag == 0) {
printf("Error at column 7: expected '('");
return false;
}
return true;
}
bool finding_bracket2(char* UKAZAT) //поиск второй скобки
{
int flag = 0;
while (*UKAZAT != 10) {
if (*UKAZAT == ')') {
flag = 1;
break;
}
UKAZAT++;
}
if (flag == 0) {
printf("Error at column 14: expected ')'");
return false;
}
return true;
}
bool finding_comma(char* UKAZAT) //поиск запятой
{
int flag = 0;
while (*UKAZAT != 10) {
if (*UKAZAT == ',') {
flag = 1;
break;
}
UKAZAT++;
}
if (flag == 0) {
printf("Error expected ','");
return false;
}
return true;
}
bool correct(char* Circle, char* UKAZAT, int N)
{ //проверка правильности вводимых данных
int g = 6, check = 0;
if (strncmp(Circle, UKAZAT, g) == 0) {
check++;
if (finding_bracket(UKAZAT) == true)
check++;
if (finding_comma(UKAZAT) == true)
check++;
if (finding_bracket2(UKAZAT) == true)
check++;
} else {
printf("error: Check the spelling of the command");
}
if (check == 4)
return true;
if (check != 4)
return false;
return true;
}
void translation_universal(char* UKAZAT, double* x1)
{ //переводим х из текста в число
char* point;
double c;
int i = 0;
while (isdigit(*UKAZAT) == 0) {
UKAZAT++;
if (isdigit(*UKAZAT) != 0) {
c = strtod(UKAZAT, &point);
x1[i] = c;
i++;
UKAZAT = point;
if (i == 3)
break;
} else {
printf("expected '<double>'\n");
system("pause");
break;
}
}
}
void calculation(double* A)
{
float pi = 3.1415;
float S;
float P;
P = 2 * pi * A[2];
S = pi * pow(A[2], 2);
printf("Perimetr = %f\n", P);
printf("Area = %f\n", S);
}
int main()
{
int N = 50;
double A[4];
char str[N];
char* UKAZAT = str;
char* UKAZAT2 = str;
char Circle[] = {"circle"};
fgets(str, N, stdin); //ввод данных
if (isalpha(*UKAZAT) != 0) { //передвигаем указатель на первую скобку
while (isalpha(*UKAZAT2) != 0)
UKAZAT2++;
}
if (correct(Circle, str, N) == true) {
//если проверка прошла успешно, передвигаем первый указатель
//на первую скобку
UKAZAT = UKAZAT2;
printf("correct\n");
}
translation_universal(UKAZAT, A);
calculation(A);
system("pause");
return 0;
}
|
C | //24. FUA para ler o código da peça 1, a quantidade de peças 1, o valor unitário da peça
//1, o código da peça 2, a quantidade de peças 2, o valor unitário da peça 2 e o
//percentual de IPI a ser acrescentado ao valor de cada peça. Calcule o valor a ser
//pago para cada peça e o valor total da compra. Escrever a quantidade, o código, o
//valor unitário, o valor unitário com IPI e o valor total para cada peça e também o
//valor total da compra.
#include <stdio.h>
int main(){
int qtpc1, qtpc2, cdpc1, cdpc2;
float vpc1, vpc2, percipi, valorvenda1, valorvenda2, valordesconto, total;
printf("Digite o código da peça 1: ");
scanf("%i", &cdpc1);
printf("Digite a quantidade de peças 1 vendidas: ");
scanf("%i", &qtpc1);
printf("Digite o valor unitário da peça 1: R$");
scanf("%f", &vpc1);
valorvenda1 = qtpc1*vpc1;
printf("\nValor total da venda da peça 1 foi: R$%.2f", valorvenda1);
printf("\n\nDigite o código da peça 2: ");
scanf("%i", &cdpc2);
printf("Digite a quantidade de peças 2 vendidas: ");
scanf("%i", &qtpc2);
printf("Digite o valor unitário da peça 2: R$");
scanf("%f", &vpc2);
valorvenda2 = qtpc2*vpc2;
printf("\nValor total da venda da peça 2 foi: R$%.2f", valorvenda2);
printf("\ndigite o percentual de desconto IPI: ");
scanf("%f", &percipi);
valordesconto = (valorvenda1 + valorvenda2*percipi)/100;
printf("\nO valor do desconto IPI das duas vendas foi de: R$%.2f", valordesconto);
total = (valorvenda1+valorvenda2) - valordesconto;
printf("\nO valor total da venda menos o desconto foi de: R$%.2f", total);
return 0;
} |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: awali-al <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/11/04 13:48:40 by sazouaka #+# #+# */
/* Updated: 2020/12/10 11:24:04 by awali-al ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../inc/ft_21sh.h"
#include "../../inc/builtins.h"
#include "../../inc/parse.h"
#include "../../inc/ast.h"
#include "../../inc/exec.h"
#include "../../inc/ft_free.h"
#include "../../inc/readline.h"
void ft_get_index(char *str, int *i)
{
*i = 0;
while (str[*i] != '\n' && str[*i] != '\0')
(*i)++;
}
static int getting_out(char **str)
{
*str ? ft_strdel(str) : 0;
return (0);
}
int get_next_line(const int fd, char **line)
{
char buff[BUFF_SIZE + 1];
static char *str;
char *tmp;
int i;
if (fd < 0 || read(fd, buff, 0) < 0 || line == NULL)
return (-1);
(str == NULL) ? (str = ft_strdup("")) : 0;
while ((i = read(fd, buff, BUFF_SIZE)))
{
buff[i] = '\0';
tmp = str;
str = ft_strjoin(str, buff);
ft_strdel(&tmp);
if (ft_strchr(str, '\n'))
break ;
}
if (ft_strlen(str) == 0 && i == 0)
return (getting_out(&str));
ft_get_index(str, &i);
*line = ft_strsub(str, 0, i);
tmp = ft_strdup(str + i + 1);
ft_strdel(&str);
str = tmp;
return (1);
}
|
C | // Verificador de soluciones para instancias de Braun et al.
// Parametros: <archivo_instancia> <archivo_sol>
// El archivo de instancias DEBE llevar el cabezal con datos (NT, NM).
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INFT 9999999999.0
#define NO_ASIG -1
#define SIZE_NOM_ARCH 1024
#define DEBUG 0
int main(int argc, char *argv[]){
if (argc != 3){
printf("Sintaxis: %s <archivo_instancias> <archivo_sol>\n", argv[0]);
exit(1);
}
int NT, NM;
FILE *fi, *fs;
char *arch_inst;
arch_inst = (char *)malloc(sizeof(char)*SIZE_NOM_ARCH);
strcpy(arch_inst,argv[1]);
printf("Archivo: %s\n",arch_inst);
char *arch_sol;
arch_sol= (char *)malloc(sizeof(char)*SIZE_NOM_ARCH);
strcpy(arch_sol,argv[2]);
printf("Archivo sol: %s\n",arch_sol);
// Leer archivo, almacenando matriz ETC
if((fi=fopen(arch_inst, "r"))==NULL){
printf("No se puede leer archivo de instancia %s\n",arch_inst);
exit(1);
}
int i,j;
/*NT=atoi(argv[3]);
NM=atoi(argv[4]);*/
fscanf(fi,"%d %d",&NT,&NM);
printf("NT: %d, NM: %d\n",NT,NM);
float **ETC = (float **) malloc(sizeof(float *) * NT);
int *priority = (int *) malloc(sizeof(int) * NT);
if (ETC == NULL){
printf("Error al reservar memoria para ETC, dimensiones %dx%d\n",NT,NM);
exit(2);
}
for (i=0;i<NT;i++){
ETC[i] = (float *) malloc(sizeof(float)*NM);
if (ETC[i] == NULL){
printf("Error al reservar memoria para fila %d de ETC\n",i);
exit(2);
}
}
for (i=0;i<NT;i++){
fscanf(fi, "%d", &priority[i]);
}
int max_etc=0;
for (i=0;i<NT;i++){
for (j=0;j<NM;j++){
fscanf(fi,"%f",&ETC[i][j]);
}
}
close(fi);
// Array de maquinas, almacena el MAT
float *mach = (float *) malloc(sizeof(float)*NM);
for (j = 0; j < NM; j++){
mach[j]=0.0;
}
// Array de asignaciones
int *asig= (int*) malloc(sizeof(float)*NT);
int nro_asig=0;
for (i = 0; i < NT; i++){
asig[i]=NO_ASIG;
}
if((fs=fopen(arch_sol, "r"))==NULL){
printf("No se puede leer archivo de solucion %s\n",arch_sol);
exit(1);
}
float wrr = 0.0;
int current_machine_tasks[NT];
for (j = 0; j < NM; j++) {
float flowtime;
flowtime = 0.0;
int task_cant;
task_cant = 0;
int task_id;
fscanf(fs,"%d ",&task_id);
fprintf(stdout, "\n%d >> ", j);
while (task_id > -1){
fprintf(stdout, " %d", task_id);
asig[task_id] = j;
current_machine_tasks[task_cant] = task_id;
flowtime += ETC[task_id][j];
if (task_cant == 0) {
wrr += priority[task_id];
} else {
wrr += (priority[task_id] * (flowtime / ETC[task_id][j]));
}
task_cant++;
// Prox. tarea
fscanf(fs,"%d ",&task_id);
}
/*
if (task_cant > 0) {
wrr += priority[current_machine_tasks[0]];
flowtime += ETC[current_machine_tasks[0]][j];
int i;
for (i = 1; i < task_cant; i++) {
wrr += (priority[current_machine_tasks[i]] * (flowtime / ETC[current_machine_tasks[i]][j]));
}
}
*/
}
fclose(fs);
printf("Sol: [");
for (i = 0; i < NT; i++){
printf("%d ", asig[i]);
}
printf("]\n");
int maq;
for(i = 0; i < NT; i++){
maq = asig[i];
mach[maq] = mach[maq]+ETC[i][maq];
}
float makespan = 0.0;
for (j = 0; j < NM; j++){
if (mach[j]>makespan){
makespan = mach[j];
}
}
printf("Makespan: %f\n",makespan);
printf("WRR : %f\n",wrr);
}
|
C | #include <stdio.h>
#include <stdlib.h>
int main()
{
int var1, var2, temp;
printf("Inserire la variabile 1: ");
scanf("%d", &var1);
printf("Inserire l'variabile 2: ");
scanf("%d", &var2);
temp = var1;
var1 = var2;
var2 = temp;
printf("La variabile 1 e' %d, la variabile 2 e' %d", var1,var2);
return 0;
}
|
C | //˵ͷջջʱֱָ̾Ϳ
//ڽԪزʱ½ĽڵָָջָͿ
#include<stdio.h>
#include<stdbool.h>
#include<malloc.h>
typedef int elementype;
typedef struct node{
elementype data;
struct node *next;
}stacknode, *linkstackptr;
typedef struct stack{
linkstackptr top; //ջָ
int count; //
}Linkstack;
/* ջSΪջTRUEFALSE */
int stackempty(Linkstack S)
{
if (S.count == 0)
return 1;
else
return 0;
}
bool push(Linkstack *S, elementype e) //ջ
{
linkstackptr s = (linkstackptr)malloc(sizeof(stacknode));
s -> data = e;
s -> next = S -> top; //ѵǰջֵµԪصĺ(ָָ)
S -> top = s; //µĽڵ㸳ֵջָ루ԪسΪջԪأ
S -> count++;
return true;
}
int pop(Linkstack *s, elementype *e) //ջ
{
linkstackptr p; //ʱڵ
if(stackempty(*s))
return 0;
else
{
*e = s -> top -> data;
p = s -> top; //ջָ뽻p
s -> top = s -> top -> next; //ʹջָһλ
free(p); //Ϊڵ㱻ɾҪͷʱڵ
s -> count--; //һ
return 1;
}
}
void visit(elementype p)
{
printf("%d ", p);
}
bool traversestack(Linkstack s)
{
linkstackptr p;
p = s.top;
while(p)
{
visit(p -> data);
p = p -> next;
}
printf("\n");
return true;
}
/* һջS */
bool InitStack(Linkstack *S)
{
S -> top = (linkstackptr)malloc(sizeof(stacknode));
if(!S -> top)
return false;
S -> top = NULL;
S -> count = 0;
return true;
}
/* SΪջ */
bool ClearStack(Linkstack *S)
{
linkstackptr p,q;
p = S -> top;
while(p)
{
q = p;
p = p -> next;
free(q); //ÿһڵͷ
}
S -> count = 0;
return true;
}
/* SԪظջij */
int StackLength(Linkstack S)
{
return S.count;
}
/* ջգeSջԪأOKERROR */
int GetTop(Linkstack S,elementype *e)
{
if (S.top == NULL)
return 0;
else
*e = S.top -> data;
return 1;
}
int main()
{
int j;
Linkstack s;
int e;
if(InitStack(&s) == true)
for(j = 1;j <= 10;j++)
push(&s,j);
printf("ջԪΪ");
traversestack(s);
pop(&s,&e);
printf("ջԪ e=%d\n",e);
printf("ջշ%d(1: 0:)\n",stackempty(s));
GetTop(s,&e);
printf("ջԪ e=%d ջijΪ%d\n",e,StackLength(s));
ClearStack(&s);
printf("ջջշ%d(1: 0:)\n",stackempty(s));
return 0;
}
|
C | #ifndef RANDOM_PALETTE
#define RANDOM_PALETTE
#include <tonc_video.h>
#include <tonc_memmap.h>
#define PALETTE_SIZE ( 248 )
typedef struct Palette {
COLOR colors[PALETTE_SIZE]; // max of 256 colors in palette
u8 index; // current index
u8 length; // keeps track of how many colors have been added
} Palette;
inline void Palette_initialize(Palette *palette, COLOR firstColor) {
palette->colors[0] = firstColor;
palette->index = 0;
palette->length = 1;
}
// TRUE if added, FALSE if palette is full
inline BOOL Palette_addColor(Palette *palette, COLOR newColor, BOOL overwrite) {
if(!overwrite)
{
// don't add if full and not overwriting
if(palette->length == PALETTE_SIZE)
return FALSE;
// not full and index is at end
palette->colors[palette->index] = newColor;
palette->length++;
}
else
{
// check if at end
if(palette->index == palette->length)
palette->index = 0;
palette->colors[palette->index] = newColor;
}
return TRUE;
}
#endif |
C | /*Chapter 9: Arrays, Practice example 2*/
/*Passing Array elements to a function*/
/*Demonstration of call by value*/
#include<stdio.h>
void display(int);
int main()
{
int i;
int marks[] = {55, 65, 75, 56, 78, 78, 90};
for (i = 0; i <7; i++)
{
display(marks[i]);
}
return 0;
}
void display(int m)
{
printf("%d ", m);
} |
C | #include <stdio.h>
int cubeByValue(int n);
void cubeByReference(int *nPtr);
int main(int argc, char *argv[]) {
int number = 5;
printf("Valor original do numero: %d\n", number);
cubeByReference(&number);
printf("Novo valor do numero: %d\n", number);
return 0;
}
int cubeByValue(int n){
return n * n * n;
}
void cubeByReference(int *nPtr){
*nPtr = (*nPtr) * (*nPtr) * (*nPtr);
} |
C | #include<stdio.h>
void Tower_of_Hanoi(int n,char x,char y,char z) {
if(n>0) {
Tower_of_Hanoi(n-1,x,z,y);
printf("\n%c to %c",x,y);
Tower_of_Hanoi(n-1,z,y,x);
}
}
int main() {
int n=3;
Tower_of_Hanoi(n,'A','B','C');
}
|
C |
#include <stdio.h>
#include <stdlib.h>
void resolution(FILE *p, int *X, int *Y)
{
fseek(p, 0, SEEK_SET);
fscanf(p, "%d", X);
fscanf(p, "%d", Y);
printf("X, Y = %d, %d\n", *X, *Y);
fseek(p, 0, SEEK_SET);
}
void lim_int(unsigned char **tab_interieur, unsigned char **contraste, int X, int Y, int *E, int *I)
{
int i, j;
for(i=0;i<X;i++)
for(j=0;j<Y;j++)
{
if(tab_interieur[i][j]==1)
*I += (int) contraste[i][j];
else if(tab_interieur[i][j]==0)
*E += (int) contraste[i][j];
}
}
float CRI(int E, int I)
{
if(I<E && I>0)
return (float) 1-(((float)I)/((float)E));
else if(I==0)
return (float) E;
else
return (float) 0;
}
int voisin(unsigned char** tab, int x, int y, int X, int Y)
{
int tmp[8]={0}, i=0, schlag=0;
if(y>0)
{
if(x>0)
tmp[0]=tab[x][y]-tab[x-1][y-1];
tmp[1]=tab[x][y]-tab[x][y-1];
if(x<X-1)
tmp[2]=tab[x][y]-tab[x+1][y-1];
}
if(x>0)
tmp[3]=tab[x][y]-tab[x-1][y];
if(x<X-1)
tmp[4]=tab[x][y]-tab[x+1][y];
if(y<Y-1){
if(x>0)
tmp[5]=tab[x][y]-tab[x-1][y+1];
tmp[6]=tab[x][y]-tab[x][y+1];
if(x<X-1)
tmp[7]=tab[x][y]-tab[x+1][y+1];
}
for(i=0;i<8;i++)
if(abs(tmp[i])>schlag)
schlag=tmp[i];
return schlag;
}
int interieur(unsigned char** tab, int x, int y, int X, int Y, int seuil)
//Retourn 1 si le pixel est intérieur, par rapport à ses voisins
{
int tmp[9]={0}, i, schlag=0;
if(y>0){
if(x>0)
tmp[0]=tab[x-1][y-1];
tmp[1]=tab[x][y-1];
if(x<X-1)
tmp[2]=tab[x+1][y-1];
}
if(x>0)
tmp[3]=tab[x-1][y];
tmp[4]=tab[x][y];
if(x<X-1)
tmp[5]=tab[x+1][y];
if(y<Y-1)
{
if(x>0)
tmp[6]=tab[x-1][y+1];
tmp[7]=tab[x][y+1];
if(x<X-1)
tmp[8]=tab[x+1][y+1];}
for(i=0;i<9;i++)
{
if(tmp[i]>seuil)
schlag+=0;
if(tmp[i]<seuil)
schlag+=1;
}
return (schlag%9 == 0);//schlag%9==0 <==> pixel est interieur
}
void sauveTab(FILE *p, int X, int Y, unsigned char **tab)
{
int i,j;
int debug=0;
fseek(p, 256, SEEK_SET);
debug += 256;
fseek(p, X*(Y/4), SEEK_CUR);
debug += X*(Y/4);
for(i=0;i<X/2;i++)
{
fseek(p, X/4, SEEK_CUR);
debug+=X/4;
for(j=0;j<Y/2;j++)
{
tab[i][j]=(unsigned char) fgetc(p);
debug++;
}
fseek(p, X/4, SEEK_CUR);
debug+=X/4;
}
printf("%d\n%d\n", debug, 256 + X*Y/4);
fseek(p, 0, SEEK_SET);
}
void pixToTab16(unsigned char*** tab, int X, int Y, FILE *input)
{
int i=0, DEBUG=256,X4 = X/4,Y4 = Y/4;
fseek(input, 256, SEEK_SET);
/*
for(i=0;i<16;i++)
for(j=0;j<X/4;j++)
for(k=0;k<Y/4;k++)
tab[i][j][k] = (unsigned char) fgetc(input);//tab[numtab][][]
*/
printf("DEBUG\n");
//for(i=0;i<16;i++){
for(i;i<X*Y;i++)
tab[(i/Y4)+4*(i/Y4)][i/Y4][i%Y4]=(unsigned char) fgetc(input);
}
int parseCarre(unsigned char **carre, int X, int Y)
{
int i,j,seuil, seuilmax=0, E=0, I=0, surface=0;
unsigned char **tab_interieur;
tab_interieur = (unsigned char**) malloc(sizeof(unsigned char*)*(X));
for(i=0;i<X/2;i++)
tab_interieur[i] = (unsigned char*) malloc(sizeof(unsigned char)*(Y));
for(seuil=50;seuil<=180;seuil++)
{
E=0;I=0;surface=0;
for(i=0;i<X;i++){
for(j=0;j<Y;j++){
tab_interieur[i][j]=(unsigned char) interieur(carre, i, j, X, Y, seuil);
surface += tab_interieur[i][j];
if(tab_interieur)I++;else E++;
}
}
if (CRI(E, I) > seuilmax)
seuilmax=CRI(E,I);
}
return seuilmax;
}
void binCarre(unsigned char **carre, int X, int Y, int seuil)
//Binarise un carre de X par Y avec seuil comme limite
{
int i,j;
for(i=0;i<X;i++)
for(j=0;j<Y;j++)
carre[i][j]=256*(seuil>carre[i][j]);
}
int main()
{
FILE *input, *output;
int dimX, dimY, i, j, seuilmax;
unsigned char ***tab;
input=fopen("muscle.lena","r");
output=fopen("output.lena","w");
resolution(input, &dimX, &dimY);
//-----------------------DEF TAB--------------------//
tab = (unsigned char***) malloc(sizeof(unsigned char**)*(16));
for(i=0;i<16;i++)
{
tab[i]=(unsigned char**) malloc(sizeof(unsigned char*)*(dimX/4));
for(j=0;j<dimX/4;j++)
{
tab[i][j] = (unsigned char*) malloc(sizeof(unsigned char)*(dimY/4));
}
}
printf("%d %d\n", dimX, dimY);
//--------------------Main program-----------------//
pixToTab16(tab, dimX, dimY, input);
for(i=0;i<16;i++)
{
seuilmax = parseCarre(tab[i], dimX, dimY);
}
}
|
C | #include <stdio.h>
char** os_argv;
char* os_argv_last;
void init_setproctitle()
{
char * p;
size_t size;
int i;
size = 0;
os_argv_last = os_argv[0];
for (i = 0; os_argv[i]; ++i)
{
if (os_argv_last == os_argv[i])
{
size += strlen(os_argv[i]) + 1;
printf("i:%d size:%d\n", i, size);
os_argv_last = os_argv[i] + strlen(os_argv[i]) + 1;
}
}
printf("len:%d os_argv_last:%s\n", os_argv_last - os_argv[0], os_argv_last);
// 移动到了环境变量的最后
os_argv_last += strlen(os_argv_last);
}
void save_argv(int argc, const char** argv)
{
os_argv = (char **) argv;
}
void setproctitle(char *title)
{
char *p;
os_argv[1] = NULL;
p = strncpy((char *) os_argv[0], (char *) title,
strlen(title));
p += strlen(title);
if (os_argv_last - (char *) p > 0) {
printf("后面部分清零\n");
memset(p, 0, os_argv_last - (char *) p);
}
}
int main(int argc, char** argv)
{
save_argv(argc, argv);
init_setproctitle();
setproctitle("xxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxx");
printf("%s\n", argv[0]);
while (1) ;
return 0;
}
|
C | /*
* File: EEPROM.c
* Author: True Administrator
*
* Created on February 22, 2017, 3:31 PM
*/
/* =============================================================================
This file contains the functions required to read and write to the EEPROM,
the registers used to store permanent data
================================================================================*/
#include <xc.h>
#include <stdio.h>
#include "main.h"
unsigned char ReadEE(unsigned char addressh, unsigned char address) {
//read data from permanent memory
EEADRH = addressh; //upperbits of the address
EEADR = address; //first 8 bits of the address
EECON1bits.EEPGD = 0;
EECON1bits.CFGS = 0;
EECON1bits.RD = 1;
return EEDATA;
}
void WriteEE(unsigned char addressh, unsigned char address, unsigned char data) {
//write data onto permanent memory so that user can see previous runs
EECON1bits.WREN = 1; //enable writes
EEADRH = addressh; //upper bits of data address
EEADR = address; //lower bits of data address
EEDATA = data; //data to be written
EECON1bits.EEPGD = 0; //point to DATA memory
EECON1bits.CFGS = 0; //access EEPROM
INTCONbits.GIE = 0; //disable interrupts
//required sequence
EECON2 = 0x55;
EECON2 = 0xAA;
EECON1bits.WR = 1; //Set WR bit to begin write
INTCONbits.GIE = 1; //enable interrupts
while (EECON1bits.WR == 1) {} //waiting for write to complete
EECON1bits.WREN = 0; //disable writes on write complete
}
void saveLog(unsigned char sortLog[]) {
unsigned int address = 0;
unsigned char addressh, addressl;
while(ReadEE(((address >> 8) & 0xFF), (address & 0xFF)) != 0xFF) {
address += 13; //we need to write to 13 addresses in memory to store the information for each run, so just address by 13
} //look for a byte of memory that is unwritten to
__lcd_clear();
for(unsigned int i = 0; i < 13; i++) {
addressh = (address >> 8) & 0xFF;
addressl = address & 0xFF;
__lcd_home();
__delay_ms(10);
printf("Saving Data... ");
__delay_ms(10);
WriteEE(addressh,addressl,sortLog[i]); //write to the EEPROM
address++;
}
viewSavedLogs();
}
void viewSavedLogs(void) {
//this code displays a prompt on the LCD Display to allow the user to see saved logs
__lcd_clear();
__delay_ms(1);
printf(" View saved logs");
__lcd_newline();
printf(" C:Next");
char key = keypadInterface();
while(key != 'C'){
key = keypadInterface(); //poll key C until it is pressed
}
__lcd_clear();
__delay_ms(1);
printf(" Press D to");
__lcd_newline();
printf("select a log");
__delay_1s();
unsigned char i = 0;
unsigned char sortLog[13];
while(1) {
for(unsigned char j = 0; j < 13; j++) {
sortLog[j] = ReadEE(0,i+j); //read data from the EEPROM and place it in the sortLog variable
}
__lcd_clear();
__delay_ms(1);
printf("%02x/%02x/%02x %02x:%02x", sortLog[0],sortLog[1],sortLog[2],sortLog[4],sortLog[5]); //sortLog[0:6] contains data about the date and time of the run
__lcd_newline();
printf("B:Prev C:Next");
key = keypadInterface();
if(key == 'C') {
unsigned char temp = i + 13;
if(ReadEE(0,temp) != 0xFF) { //this line checks to see if this is an empty spot in memory
i = temp; //if it is, lets point to it with i
}
}
else if(key == 'B' && i > 0) {
i -= 13; //need to go back to view a previous run, so need to decrease address by 13
}
else if(key == 'D') {
retrieveLog(1,sortLog); //view the sorting Log
}
}
}
|
C | /**
* @file inode.c
* @brief accessing the UNIX v6 filesystem -- core of the first set of assignments
*/
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "unixv6fs.h"
#include "inode.h"
#include "error.h"
#include "sector.h"
#include "bmblock.h"
/**
* @brief read all inodes from disk and print out their content to
* stdout according to the assignment
* @param u the filesystem
* @return 0 on success; < 0 on error.
*/
int inode_scan_print(const struct unix_filesystem *u)
{
#define INODE_SIZE 32
M_REQUIRE_NON_NULL(u);
int valeur=0;
int r=1;
uint8_t secteurs[SECTOR_SIZE];
int numinode=0;
for(int m=0; m<(u->s.s_isize); ++m) {
if((r=sector_read(u->f,(u->s.s_inode_start+m),secteurs))!=0) {
return r;
}
for(int i=0; i<SECTOR_SIZE; i+=INODE_SIZE) {
struct inode ino;
memset(&ino, 0, sizeof(ino));
ino.i_mode = ((uint16_t)secteurs[i+1])<<8 | (uint16_t)secteurs[i];
ino.i_nlink = secteurs[i+2];
ino.i_uid = secteurs[i+3];
ino.i_gid = secteurs[i+4];
ino.i_size0 = secteurs[i+5];
ino.i_size1 = ((uint16_t)secteurs[i+7])<<8 | (uint16_t)secteurs[i+6];
int k = i+8;
for(int j=0; j<ADDR_SMALL_LENGTH; ++j) {
ino.i_addr[j] = ((uint16_t)secteurs[k+1])<<8 | (uint16_t)secteurs[k];
k+=2;
}
uint16_t iatime[2] = {((uint16_t)secteurs[k+1])<<8 | (uint16_t)secteurs[k], ((uint16_t)secteurs[k+3])<<8 | (uint16_t)secteurs[k+2]};
for(int l=0; l<2; ++l) {
ino.i_atime[l]=iatime[l];
}
uint16_t imtime[2] = {((uint16_t)secteurs[k+5])<<8 | (uint16_t)secteurs[k+4], ((uint16_t)secteurs[k+7])<<8 | (uint16_t)secteurs[k+6]};
for(int l=0; l<2; ++l) {
ino.i_mtime[l]=imtime[l];
}
if(ino.i_mode & IALLOC) {
if(ino.i_mode & IFDIR) {
printf("inode %d (%s) len %d \n",numinode,SHORT_DIR_NAME,inode_getsize(&ino));
} else {
printf("inode %d (%s) len %d \n",numinode,SHORT_FIL_NAME,inode_getsize(&ino));
}
}
++numinode;
}
}
return valeur;
}
/**
* @brief prints the content of an inode structure
* @param inode the inode structure to be displayed
*/
void inode_print(const struct inode *inode)
{
printf("**********FS INODE START**********\n");
if( inode ==NULL) {
printf("NULL ptr \n");
} else {
printf("i_mode: %" PRIu16 "\n", inode->i_mode);
printf("i_nlink: %" PRIu8 "\n", inode->i_nlink);
printf("i_uid: %" PRIu8 "\n", inode->i_uid);
printf("i_gid: %" PRIu8 "\n", inode->i_gid);
printf("i_size0: %" PRIu8 "\n", inode->i_size0);
printf("i_size1: %" PRIu16 "\n", inode->i_size1);
printf("size: %d \n", inode_getsize(inode));
}
printf("**********FS INODE END**********\n");
}
/**
* @brief read the content of an inode from disk
* @param u the filesystem (IN)
* @param inr the inode number of the inode to read (IN)
* @param inode the inode structure, read from disk (OUT)
* @return 0 on success; <0 on error
*/
int inode_read(const struct unix_filesystem *u, uint16_t inr, struct inode *inode)
{
/* initialisations */
int sector_nbr=0;
int r=1;
uint8_t my_sector[SECTOR_SIZE];
int counter=0;
memset(inode, 0, sizeof(*inode));
/* propager les erreurs s'il y en a */
M_REQUIRE_NON_NULL(u);
M_REQUIRE_NON_NULL(inode);
/* si un des secteurs de u n'est pas lisible */
for(int i=0; i<(u->s.s_isize); ++i) {
if((r=sector_read(u->f,(u->s.s_inode_start+i),my_sector))!=0) return r;
}
/* si le numéro d'inode est invalide */
if ((inr<0)||(inr>(u->s.s_isize*INODES_PER_SECTOR-1))) {
return ERR_INODE_OUTOF_RANGE;
}
/* il faut lire secteur par secteur jusqu'a arriver au secteur contenant le bon inode */
while(counter<=inr) {
sector_read(u->f,(u->s.s_inode_start+sector_nbr),my_sector);
counter+=INODES_PER_SECTOR;
++sector_nbr;
}
/* affectation de tout les parametres */
int i= (inr-((sector_nbr-1)*INODES_PER_SECTOR))*INODE_SIZE;
inode->i_mode = ((uint16_t)my_sector[i+1])<<8 | (uint16_t)my_sector[i];
inode->i_nlink = my_sector[i+2];
inode->i_uid = my_sector[i+3];
inode->i_gid = my_sector[i+4];
inode->i_size0 = my_sector[i+5];
inode->i_size1 = ((uint16_t)my_sector[i+7])<<8 | (uint16_t)my_sector[i+6];
int k = i+8;
for(int j=0; j<ADDR_SMALL_LENGTH; ++j) {
inode->i_addr[j] = ((uint16_t)my_sector[k+1])<<8 | (uint16_t)my_sector[k];
k+=2;
}
uint16_t iatime[2] = {((uint16_t)my_sector[k+1])<<8 | (uint16_t)my_sector[k],
((uint16_t)my_sector[k+3])<<8 | (uint16_t)my_sector[k+2]
};
for(int l=0; l<2; ++l) {
inode->i_atime[l]=iatime[l];
}
uint16_t imtime[2] = {((uint16_t)my_sector[k+5])<<8 | (uint16_t)my_sector[k+4],
((uint16_t)my_sector[k+7])<<8 | (uint16_t)my_sector[k+6]
};
for(int l=0; l<2; ++l) {
inode->i_mtime[l]=imtime[l];
}
/* si l'inode n'est pas alloué erreur */
if(((inode->i_mode) & IALLOC)==0) return ERR_UNALLOCATED_INODE;
return 0;
}
/**
* @brief identify the sector that corresponds to a given portion of a file
* @param u the filesystem (IN)
* @param inode the inode (IN)
* @param file_sec_off the offset within the file (in sector-size units)
* @return >0: the sector on disk; <0 error
*/
int inode_findsector(const struct unix_filesystem *u, const struct inode *i, int32_t file_sec_off)
{
#define MAX_SIZE 7*256
M_REQUIRE_NON_NULL(u);
M_REQUIRE_NON_NULL(i);
/* taille du fichier en bytes car getsize renvoie la taille en byte*/
int32_t size_file = inode_getsize(i);
int r=1;
if((file_sec_off)*SECTOR_SIZE +1 >size_file) {
return ERR_OFFSET_OUT_OF_RANGE;
}
/* L'inode n'est pas allouée */
if((i->i_mode & IALLOC)==0) {
return ERR_UNALLOCATED_INODE;
}
if(size_file<=ADDR_SMALL_LENGTH*SECTOR_SIZE) {
return i->i_addr[file_sec_off];
}
if((size_file>(ADDR_SMALL_LENGTH)*SECTOR_SIZE)&&(size_file<=MAX_SIZE*SECTOR_SIZE)) {
uint16_t adresses[ADDRESSES_PER_SECTOR];
int secteur_indirect = file_sec_off/ADDRESSES_PER_SECTOR;
if((r = sector_read(u->f, i->i_addr[secteur_indirect], adresses))!=0) {
return r;
}
/* On retourne le numero du secteur voulu contenu dans l'element d'indice offset mod 256*/
return adresses[file_sec_off % ADDRESSES_PER_SECTOR];
} else {
return ERR_FILE_TOO_LARGE;
}
}
/**
* @brief set the size of a given inode to the given size
* @param inode the inode
* @param new_size the new size
* @return 0 on success; <0 on error
*/
int inode_setsize(struct inode *inode, int new_size)
{
if(new_size<0) return ERR_NOMEM;
inode->i_size0 = (uint8_t)(new_size >> 16);
inode->i_size1 = (uint16_t)((new_size <<8 )>>8);
return 0;
}
/**
* @brief alloc a new inode (returns its inr if possible)
* @param u the filesystem (IN)
* @return the inode number of the new inode or error code on error
*/
int inode_alloc(struct unix_filesystem *u)
{
M_REQUIRE_NON_NULL(u);
int next = bm_find_next(u->ibm);
if(next<0) return ERR_NOMEM;
bm_set(u->ibm, next);
return next;
}
/**
* @brief write the content of an inode to disk
* @param u the filesystem (IN)
* @param inr the inode number of the inode to read (IN)
* @param inode the inode structure, read from disk (IN)
* @return 0 on success; <0 on error
*/
int inode_write(struct unix_filesystem *u, uint16_t inr, struct inode *inode)
{
/* initialisations */
int index=0;
int r=1;
struct inode inodes[INODES_PER_SECTOR];
int counter=0;
int err = 0;
/* propager les erreurs s'il y en a */
M_REQUIRE_NON_NULL(u);
M_REQUIRE_NON_NULL(inode);
/* si un des secteurs de u n'est pas lisible */
for(int i=0; i<(u->s.s_isize); ++i) {
if((r=sector_read(u->f,(u->s.s_inode_start+i),inodes))!=0) return r;
}
/* si le numéro d'inode est invalide */
if ((inr<0)||(inr>(u->s.s_isize*INODES_PER_SECTOR-1))) {
return ERR_INODE_OUTOF_RANGE;
}
/* il faut lire secteur par secteur jusqu'a arriver au secteur contenant le bon inode */
while(counter<=inr) {
sector_read(u->f,(u->s.s_inode_start+index),inodes);
counter+=INODES_PER_SECTOR;
++index;
}
--index;
int sector_nbr=u->s.s_inode_start+index;
/* écriture du secteur contenant le nouvel inode */
inodes[inr]=*inode;
if((err = sector_write(u->f,sector_nbr,inodes))<0) return err;
return 0;
}
|
C | #include <stdlib.h>
#include "stack.h"
void push(struct stack* this,int input)
{
this->stk[++this->sp] = input;
}
int pop(struct stack* this)
{
return this->stk[this->sp--];
}
struct stack* new_stack()
{
struct stack* stk = malloc(sizeof(struct stack));
stk->sp = -1;
return stk;
}
void delete_stack(struct stack* stk)
{
free(stk);
}
|
C | //
// main.c
// Types
//
// Created by 何洲 on 2019/5/10.
// Copyright © 2019 何洲. All rights reserved.
//
#include <stdio.h>
int main(int argc, const char * argv[]) {
// char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
// char greeting[] = "Hello";
char *greeting = "Hello";
printf("%s\n", greeting);
return 0;
}
|
C | #include <sys/stat.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "events.h"
#include "proto_s3.h"
#include "sock.h"
#include "warnp.h"
#include "wire.h"
struct put_state {
int done;
int failed;
};
static int
callback_done(void * cookie, int failed)
{
struct put_state * C = cookie;
C->done = 1;
C->failed = failed;
return (0);
}
int
main(int argc, char * argv[])
{
struct sock_addr ** sas;
int s;
struct wire_requestqueue * Q;
struct stat sb;
FILE * f;
uint8_t * buf;
struct put_state C;
WARNP_INIT;
/* Check number of arguments. */
if (argc != 5) {
fprintf(stderr, "usage: s3_put %s %s %s %s\n", "<socketname>",
"<file>", "<bucket>", "<object>");
exit(1);
}
/* Stat file. */
if (stat(argv[2], &sb)) {
warnp("stat(%s)", argv[2]);
exit(1);
}
if (!S_ISREG(sb.st_mode) ||
sb.st_size > (off_t)PROTO_S3_MAXLEN ||
sb.st_size > (off_t)SIZE_MAX ||
sb.st_size < (off_t)0 ||
sb.st_size == 0) {
warn0("Bad file: %s", argv[2]);
exit(1);
}
if ((buf = malloc((size_t)sb.st_size)) == NULL) {
warnp("malloc");
exit(1);
}
/* Resolve the socket address and connect. */
if ((sas = sock_resolve(argv[1])) == NULL) {
warnp("Error resolving socket address: %s", argv[1]);
exit(1);
}
if (sas[0] == NULL) {
warn0("No addresses found for %s", argv[1]);
exit(1);
}
if ((s = sock_connect(sas)) == -1)
exit(1);
/* Create a request queue. */
if ((Q = wire_requestqueue_init(s)) == NULL) {
warnp("Cannot create packet write queue");
exit(1);
}
/* Read file. */
if ((f = fopen(argv[2], "r")) == NULL) {
warnp("fopen(%s)", argv[2]);
exit(1);
}
if (fread(buf, (size_t)sb.st_size, 1, f) != 1) {
warnp("fread(%s)", argv[2]);
exit(1);
}
if (fclose(f)) {
warnp("fclose(%s)", argv[2]);
exit(1);
}
/* Send request. */
C.done = 0;
if (proto_s3_request_put(Q, argv[3], argv[4], (size_t)sb.st_size, buf,
callback_done, &C)) {
warnp("proto_s3_request_put");
exit(1);
}
if (events_spin(&C.done)) {
warnp("events_spin");
exit(1);
}
/* Free the request queue. */
wire_requestqueue_destroy(Q);
wire_requestqueue_free(Q);
/* Free socket addresses. */
sock_addr_freelist(sas);
/* Success! */
exit(0);
}
|
C | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define D_LINE_TABLE_MAX 20
typedef struct LINE_TABLE_T
{
int LineBuffer[D_LINE_TABLE_MAX];
int LineTableLen;
}LineTable_t;
static LineTable_t LineTable = {{0}, 0};
void PrintLineTable(void)
{
printf("\nTable value :\t");
for (int i = 0; i < LineTable.LineTableLen; i++)
{
printf("%d\t", LineTable.LineBuffer[i]);
}
printf("\n");
}
void SwapLineTableData(int m, int n)
{
int i = 0;
int temp = 0;
int swapTemp = 0;
temp = (m + n) / 2;
for (i = 0; i < temp; i++)
{
swapTemp = LineTable.LineBuffer[i];
LineTable.LineBuffer[i] = LineTable.LineBuffer[LineTable.LineTableLen - i - 1];
LineTable.LineBuffer[LineTable.LineTableLen - i - 1] = swapTemp;
}
for (i = 0; i < n / 2; i++)
{
swapTemp = LineTable.LineBuffer[i];
LineTable.LineBuffer[i] = LineTable.LineBuffer[n - i - 1];
LineTable.LineBuffer[n - i - 1] = swapTemp;
}
for (i = 0; i < m / 2; i++)
{
swapTemp = LineTable.LineBuffer[LineTable.LineTableLen - m + i];
LineTable.LineBuffer[LineTable.LineTableLen - m + i] = LineTable.LineBuffer[LineTable.LineTableLen - i - 1];
LineTable.LineBuffer[LineTable.LineTableLen - i - 1] = swapTemp;
}
}
int main(void)
{
LineTable.LineTableLen = 10;
LineTable.LineBuffer[0] = 1;
LineTable.LineBuffer[1] = 2;
LineTable.LineBuffer[2] = 3;
LineTable.LineBuffer[3] = 4;
LineTable.LineBuffer[4] = 5;
LineTable.LineBuffer[5] = 11;
LineTable.LineBuffer[6] = 22;
LineTable.LineBuffer[7] = 33;
LineTable.LineBuffer[8] = 44;
LineTable.LineBuffer[9] = 55;
SwapLineTableData(5,5);
PrintLineTable();
LineTable.LineTableLen = 10;
LineTable.LineBuffer[0] = 1;
LineTable.LineBuffer[1] = 2;
LineTable.LineBuffer[2] = 3;
LineTable.LineBuffer[3] = 4;
LineTable.LineBuffer[4] = 15;
LineTable.LineBuffer[5] = 16;
LineTable.LineBuffer[6] = 22;
LineTable.LineBuffer[7] = 33;
LineTable.LineBuffer[8] = 44;
LineTable.LineBuffer[9] = 55;
SwapLineTableData(4,6);
PrintLineTable();
LineTable.LineTableLen = 10;
LineTable.LineBuffer[0] = 1;
LineTable.LineBuffer[1] = 2;
LineTable.LineBuffer[2] = 3;
LineTable.LineBuffer[3] = 4;
LineTable.LineBuffer[4] = 15;
LineTable.LineBuffer[5] = 16;
LineTable.LineBuffer[6] = 22;
LineTable.LineBuffer[7] = 13;
LineTable.LineBuffer[8] = 14;
LineTable.LineBuffer[9] = 15;
SwapLineTableData(7,3);
PrintLineTable();
return 0;
}
|
C | #ifndef OBJ_LOAD_H
#define OBJ_LOAD_H
#include "model.h"
#include <stdio.h>
/**
* Load OBJ model from file.
*/
int load_model(Model* model, const char* filename);
/**
* Count the elements in the model and set counts in the structure.
*/
void count_elements(Model* model, FILE* file);
/**
* Read the elements of the model and fill the structure with values.
*/
int read_elements(Model* model, FILE* file);
/**
* Determine the type of the element which is stored in a line of the OBJ file.
*/
ElementType calc_element_type(const char* text);
/**
* Read the data of the vertex.
*/
int read_vertex(Vertex* vertex, const char* text);
/**
* Read texture vertex data.
*/
int read_texture_vertex(TextureVertex* texture_vertex, const char* text);
/**
* Read normal vector data.
*/
int read_normal(Vertex* normal, const char* text);
/**
* Read triangle data.
*/
int read_triangle(Triangle* triangle, const char* text);
/**
* Check that the character is a numeric character.
*/
int is_numeric(char c);
#endif /* OBJ_LOAD_H */
|
C | #include <mctop.h>
#include <getopt.h>
const size_t msize = (2 * 1024 * 1024LL);
int
main(int argc, char **argv)
{
int on = 0;
if (argc > 1)
{
on = atoi(argv[1]);
}
printf("On node %d\n", on);
// NULL for automatically loading the MCT file based on the hostname of the machine
mctop_t* topo = mctop_load(NULL);
if (topo)
{
mctop_run_on_node(topo, on);
volatile uint** mem[mctop_get_num_nodes(topo)];
for (int i = 0; i < mctop_get_num_nodes(topo); i++)
{
mem[i] = numa_alloc_onnode(msize, i);
assert(mem[i] != NULL);
}
printf(" -- Mem intialized\n");
mctop_run_on_node(topo, on);
// mctop_print(topo);
volatile size_t i = 20e9;
while (i--)
{
__asm volatile ("nop");
}
for (int i = 0; i < mctop_get_num_nodes(topo); i++)
{
numa_free(mem[i], msize);
}
mctop_free(topo);
}
return 0;
}
|
C | /*
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <[email protected]> wrote this file. As long as you retain this notice you
* can do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return. Joerg Wunsch
* ----------------------------------------------------------------------------
*
* HD44780 LCD display driver
*
* $Id: hd44780.h 2002 2009-06-25 20:21:16Z joerg_wunsch $
*/
/*
* Send byte b to the LCD. rs is the RS signal (register select), 0
* selects instruction register, 1 selects the data register.
*/
void hd44780_outbyte(uint8_t b, uint8_t rs);
/*
* Read one byte from the LCD controller. rs is the RS signal, 0
* selects busy flag (bit 7) and address counter, 1 selects the data
* register.
*/
uint8_t hd44780_inbyte(uint8_t rs);
/*
* Wait for the busy flag to clear.
*/
void hd44780_wait_ready(bool islong);
/*
* Initialize the LCD controller hardware.
*/
void hd44780_init(void);
/*
* Prepare the LCD controller pins for powerdown.
*/
void hd44780_powerdown(void);
/* Send a command to the LCD controller. */
#define hd44780_outcmd(n) hd44780_outbyte((n), 0)
/* Send a data byte to the LCD controller. */
#define hd44780_outdata(n) hd44780_outbyte((n), 1)
/* Read the address counter and busy flag from the LCD. */
#define hd44780_incmd() hd44780_inbyte(0)
/* Read the current data byte from the LCD. */
#define hd44780_indata() hd44780_inbyte(1)
/* Clear LCD display command. */
#define HD44780_CLR \
0x01
/* Home cursor command. */
#define HD44780_HOME \
0x02
/*
* Select the entry mode. inc determines whether the address counter
* auto-increments, shift selects an automatic display shift.
*/
#define HD44780_ENTMODE(inc, shift) \
(0x04 | ((inc)? 0x02: 0) | ((shift)? 1: 0))
/*
* Selects disp[lay] on/off, cursor on/off, cursor blink[ing]
* on/off.
*/
#define HD44780_DISPCTL(disp, cursor, blink) \
(0x08 | ((disp)? 0x04: 0) | ((cursor)? 0x02: 0) | ((blink)? 1: 0))
/*
* With shift = 1, shift display right or left.
* With shift = 0, move cursor right or left.
*/
#define HD44780_SHIFT(shift, right) \
(0x10 | ((shift)? 0x08: 0) | ((right)? 0x04: 0))
/*
* Function set. if8bit selects an 8-bit data path, twoline arranges
* for a two-line display, font5x10 selects the 5x10 dot font (5x8
* dots if clear).
*/
#define HD44780_FNSET(if8bit, twoline, font5x10) \
(0x20 | ((if8bit)? 0x10: 0) | ((twoline)? 0x08: 0) | \
((font5x10)? 0x04: 0))
/*
* Set the next character generator address to addr.
*/
#define HD44780_CGADDR(addr) \
(0x40 | ((addr) & 0x3f))
/*
* Set the next display address to addr.
*/
#define HD44780_DDADDR(addr) \
(0x80 | ((addr) & 0x7f))
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* algo.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cmoller <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/07/09 08:53:56 by cmoller #+# #+# */
/* Updated: 2018/08/08 08:19:58 by cmoller ### ########.fr */
/* */
/* ************************************************************************** */
#include "pushswap.h"
int main(int argc, char **argv)
{
t_search **searches;
t_env env;
env.argc = argc;
env.argv = argv;
parse_args(&env);
searches = NULL;
if (!is_sorted(env.a->table, env.argc - 2))
{
searches = (t_search **)malloc(sizeof(t_search *) * 4);
searches[0] = quicksort_algo(env.a);
searches[1] = min_algo(env.a);
searches[2] = env.a->top > 4 ? NULL : recursive_algo(env.a);
searches[3] = NULL;
print_smallest_ops(searches);
}
if (searches)
free_searches(searches);
free(env.a->table);
free(env.b->table);
free(env.a);
free(env.b);
return (0);
}
|
C | #include <stdio.h>
#define MAXVAL 100
static int sp = 0;
static double val[MAXVAL];
void printStack()
{
int len = sp;
printf("stack content: ");
while(len--) {
printf(" %.8g", val[len]);
}
printf(" \n");
}
void push(double f)
{
if (sp < MAXVAL)
{
val[sp++] = f;
}
else
{
printf("error: stack full, can't push %g\n", f);
}
printStack();
}
double pop()
{
if (sp > 0)
{
return val[--sp];
}
else
{
printf("pop error: stack empty \n");
return 0.0;
}
}
double top()
{
if (sp > 0)
{
return val[sp - 1];
}
else
{
printf("top error: stack empty\n");
return 0.0;
}
}
void clear()
{
while (sp--)
{
pop();
}
}
|
C | /*-------------------------------------------------------------------------
*
* jsonb_op.c
* Special operators for jsonb only, used by various index access methods
*
* Copyright (c) 2014-2023, PostgreSQL Global Development Group
*
*
* IDENTIFICATION
* src/backend/utils/adt/jsonb_op.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "catalog/pg_type.h"
#include "miscadmin.h"
#include "utils/builtins.h"
#include "utils/jsonb.h"
Datum
jsonb_exists(PG_FUNCTION_ARGS)
{
Jsonb *jb = PG_GETARG_JSONB_P(0);
text *key = PG_GETARG_TEXT_PP(1);
JsonbValue kval;
JsonbValue *v = NULL;
/*
* We only match Object keys (which are naturally always Strings), or
* string elements in arrays. In particular, we do not match non-string
* scalar elements. Existence of a key/element is only considered at the
* top level. No recursion occurs.
*/
kval.type = jbvString;
kval.val.string.val = VARDATA_ANY(key);
kval.val.string.len = VARSIZE_ANY_EXHDR(key);
v = findJsonbValueFromContainer(&jb->root,
JB_FOBJECT | JB_FARRAY,
&kval);
PG_RETURN_BOOL(v != NULL);
}
Datum
jsonb_exists_any(PG_FUNCTION_ARGS)
{
Jsonb *jb = PG_GETARG_JSONB_P(0);
ArrayType *keys = PG_GETARG_ARRAYTYPE_P(1);
int i;
Datum *key_datums;
bool *key_nulls;
int elem_count;
deconstruct_array_builtin(keys, TEXTOID, &key_datums, &key_nulls, &elem_count);
for (i = 0; i < elem_count; i++)
{
JsonbValue strVal;
if (key_nulls[i])
continue;
strVal.type = jbvString;
/* We rely on the array elements not being toasted */
strVal.val.string.val = VARDATA_ANY(key_datums[i]);
strVal.val.string.len = VARSIZE_ANY_EXHDR(key_datums[i]);
if (findJsonbValueFromContainer(&jb->root,
JB_FOBJECT | JB_FARRAY,
&strVal) != NULL)
PG_RETURN_BOOL(true);
}
PG_RETURN_BOOL(false);
}
Datum
jsonb_exists_all(PG_FUNCTION_ARGS)
{
Jsonb *jb = PG_GETARG_JSONB_P(0);
ArrayType *keys = PG_GETARG_ARRAYTYPE_P(1);
int i;
Datum *key_datums;
bool *key_nulls;
int elem_count;
deconstruct_array_builtin(keys, TEXTOID, &key_datums, &key_nulls, &elem_count);
for (i = 0; i < elem_count; i++)
{
JsonbValue strVal;
if (key_nulls[i])
continue;
strVal.type = jbvString;
/* We rely on the array elements not being toasted */
strVal.val.string.val = VARDATA_ANY(key_datums[i]);
strVal.val.string.len = VARSIZE_ANY_EXHDR(key_datums[i]);
if (findJsonbValueFromContainer(&jb->root,
JB_FOBJECT | JB_FARRAY,
&strVal) == NULL)
PG_RETURN_BOOL(false);
}
PG_RETURN_BOOL(true);
}
Datum
jsonb_contains(PG_FUNCTION_ARGS)
{
Jsonb *val = PG_GETARG_JSONB_P(0);
Jsonb *tmpl = PG_GETARG_JSONB_P(1);
JsonbIterator *it1,
*it2;
if (JB_ROOT_IS_OBJECT(val) != JB_ROOT_IS_OBJECT(tmpl))
PG_RETURN_BOOL(false);
it1 = JsonbIteratorInit(&val->root);
it2 = JsonbIteratorInit(&tmpl->root);
PG_RETURN_BOOL(JsonbDeepContains(&it1, &it2));
}
Datum
jsonb_contained(PG_FUNCTION_ARGS)
{
/* Commutator of "contains" */
Jsonb *tmpl = PG_GETARG_JSONB_P(0);
Jsonb *val = PG_GETARG_JSONB_P(1);
JsonbIterator *it1,
*it2;
if (JB_ROOT_IS_OBJECT(val) != JB_ROOT_IS_OBJECT(tmpl))
PG_RETURN_BOOL(false);
it1 = JsonbIteratorInit(&val->root);
it2 = JsonbIteratorInit(&tmpl->root);
PG_RETURN_BOOL(JsonbDeepContains(&it1, &it2));
}
Datum
jsonb_ne(PG_FUNCTION_ARGS)
{
Jsonb *jba = PG_GETARG_JSONB_P(0);
Jsonb *jbb = PG_GETARG_JSONB_P(1);
bool res;
res = (compareJsonbContainers(&jba->root, &jbb->root) != 0);
PG_FREE_IF_COPY(jba, 0);
PG_FREE_IF_COPY(jbb, 1);
PG_RETURN_BOOL(res);
}
/*
* B-Tree operator class operators, support function
*/
Datum
jsonb_lt(PG_FUNCTION_ARGS)
{
Jsonb *jba = PG_GETARG_JSONB_P(0);
Jsonb *jbb = PG_GETARG_JSONB_P(1);
bool res;
res = (compareJsonbContainers(&jba->root, &jbb->root) < 0);
PG_FREE_IF_COPY(jba, 0);
PG_FREE_IF_COPY(jbb, 1);
PG_RETURN_BOOL(res);
}
Datum
jsonb_gt(PG_FUNCTION_ARGS)
{
Jsonb *jba = PG_GETARG_JSONB_P(0);
Jsonb *jbb = PG_GETARG_JSONB_P(1);
bool res;
res = (compareJsonbContainers(&jba->root, &jbb->root) > 0);
PG_FREE_IF_COPY(jba, 0);
PG_FREE_IF_COPY(jbb, 1);
PG_RETURN_BOOL(res);
}
Datum
jsonb_le(PG_FUNCTION_ARGS)
{
Jsonb *jba = PG_GETARG_JSONB_P(0);
Jsonb *jbb = PG_GETARG_JSONB_P(1);
bool res;
res = (compareJsonbContainers(&jba->root, &jbb->root) <= 0);
PG_FREE_IF_COPY(jba, 0);
PG_FREE_IF_COPY(jbb, 1);
PG_RETURN_BOOL(res);
}
Datum
jsonb_ge(PG_FUNCTION_ARGS)
{
Jsonb *jba = PG_GETARG_JSONB_P(0);
Jsonb *jbb = PG_GETARG_JSONB_P(1);
bool res;
res = (compareJsonbContainers(&jba->root, &jbb->root) >= 0);
PG_FREE_IF_COPY(jba, 0);
PG_FREE_IF_COPY(jbb, 1);
PG_RETURN_BOOL(res);
}
Datum
jsonb_eq(PG_FUNCTION_ARGS)
{
Jsonb *jba = PG_GETARG_JSONB_P(0);
Jsonb *jbb = PG_GETARG_JSONB_P(1);
bool res;
res = (compareJsonbContainers(&jba->root, &jbb->root) == 0);
PG_FREE_IF_COPY(jba, 0);
PG_FREE_IF_COPY(jbb, 1);
PG_RETURN_BOOL(res);
}
Datum
jsonb_cmp(PG_FUNCTION_ARGS)
{
Jsonb *jba = PG_GETARG_JSONB_P(0);
Jsonb *jbb = PG_GETARG_JSONB_P(1);
int res;
res = compareJsonbContainers(&jba->root, &jbb->root);
PG_FREE_IF_COPY(jba, 0);
PG_FREE_IF_COPY(jbb, 1);
PG_RETURN_INT32(res);
}
/*
* Hash operator class jsonb hashing function
*/
Datum
jsonb_hash(PG_FUNCTION_ARGS)
{
Jsonb *jb = PG_GETARG_JSONB_P(0);
JsonbIterator *it;
JsonbValue v;
JsonbIteratorToken r;
uint32 hash = 0;
if (JB_ROOT_COUNT(jb) == 0)
PG_RETURN_INT32(0);
it = JsonbIteratorInit(&jb->root);
while ((r = JsonbIteratorNext(&it, &v, false)) != WJB_DONE)
{
switch (r)
{
/* Rotation is left to JsonbHashScalarValue() */
case WJB_BEGIN_ARRAY:
hash ^= JB_FARRAY;
break;
case WJB_BEGIN_OBJECT:
hash ^= JB_FOBJECT;
break;
case WJB_KEY:
case WJB_VALUE:
case WJB_ELEM:
JsonbHashScalarValue(&v, &hash);
break;
case WJB_END_ARRAY:
case WJB_END_OBJECT:
break;
default:
elog(ERROR, "invalid JsonbIteratorNext rc: %d", (int) r);
}
}
PG_FREE_IF_COPY(jb, 0);
PG_RETURN_INT32(hash);
}
Datum
jsonb_hash_extended(PG_FUNCTION_ARGS)
{
Jsonb *jb = PG_GETARG_JSONB_P(0);
uint64 seed = PG_GETARG_INT64(1);
JsonbIterator *it;
JsonbValue v;
JsonbIteratorToken r;
uint64 hash = 0;
if (JB_ROOT_COUNT(jb) == 0)
PG_RETURN_UINT64(seed);
it = JsonbIteratorInit(&jb->root);
while ((r = JsonbIteratorNext(&it, &v, false)) != WJB_DONE)
{
switch (r)
{
/* Rotation is left to JsonbHashScalarValueExtended() */
case WJB_BEGIN_ARRAY:
hash ^= ((uint64) JB_FARRAY) << 32 | JB_FARRAY;
break;
case WJB_BEGIN_OBJECT:
hash ^= ((uint64) JB_FOBJECT) << 32 | JB_FOBJECT;
break;
case WJB_KEY:
case WJB_VALUE:
case WJB_ELEM:
JsonbHashScalarValueExtended(&v, &hash, seed);
break;
case WJB_END_ARRAY:
case WJB_END_OBJECT:
break;
default:
elog(ERROR, "invalid JsonbIteratorNext rc: %d", (int) r);
}
}
PG_FREE_IF_COPY(jb, 0);
PG_RETURN_UINT64(hash);
}
|
C | /* utility.c */
#include "zcc.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
void fexit(const char *format, ...) {
puts(format);
printf("\n");
exit(0);
}
static int isvar[][3] = {
/* IR_ADD */ { 1, 1, 1 },
/* IR_SUB */ { 1, 1, 1 },
/* IR_MUL */ { 1, 1, 1 },
/* IR_DIV */ { 1, 1, 1 },
/* IR_RETURN */ { 1, 0, 0 },
/* IR_CALL */ { 1, 0, 0 },
/* IR_ASSIGN */ { 1, 1, 0 },
/* IR_LABEL */ { 0, 0, 0 },
/* IR_JMP */ { 0, 0, 0 },
/* IR_CJMP */ { 1, 0, 0 },
/* IR_LT */ { 1, 1, 1 },
/* IR_LE */ { 1, 1, 1 },
/* IR_EQ */ { 1, 1, 1 },
/* IR_GT */ { 1, 1, 1 },
/* IR_GE */ { 1, 1, 1 },
/* IR_NEQ */ { 1, 1, 1 },
/* IR_INC */ { 1, 0, 0 },
/* IR_DEC */ { 1, 0, 0 },
/* IR_IND */ { 1, 1, 1 },
/* IR_OFFSET */ { 1, 1, 0 }
};
/* duplicate temp var. imm var not included */
var_st *dup_arg(ir_op_en op, int i, var_st *var) {
if(!isvar[op][i]) return var;
return dup_temp_var(var);
}
var_st *dup_temp_var(var_st *var) {
if(var->lvalue || var->value) return var;
var_st *nvar = malloc(sizeof(var_st));
memcpy(nvar, var, sizeof(var_st));
return nvar;
}
char* dup_str(char* s) {
if(!s) return NULL;
int len = strlen(s) + 1;
char *t = malloc(len);
strcpy(t, s);
return t;
}
value_un *dup_value(token_st *tk) {
value_un *r = malloc(sizeof(value_un));
if(tk->tk_class == TK_CONST_INT)
memcpy(r, tk->value, sizeof(value_un));
else if(tk->tk_class == TK_CONST_STRING) {
r->s = dup_str(tk->tk_str);
}
return r;
}
list_st* make_list() {
#define LIST_INIT_SIZE 10
list_st *list = malloc(sizeof(list_st));
list->room = LIST_INIT_SIZE;
list->len = 0;
list->elems = malloc(sizeof(void*) * LIST_INIT_SIZE);
return list;
}
void* list_append(list_st* list, void* elem) {
if(list->len >= list->room) {
list->room *= 2;
list->elems = realloc(list->elems, list->room * sizeof(void*));
}
list->elems[list->len++] = elem;
return NULL;
}
void* list_pop(list_st* list) {
assert(list->len > 0);
return list->elems[--list->len];
}
int list_isempty(list_st* list) {
return list->len == 0;
}
int list_index(list_st* list, void* elem) {
int i = 0;
for(; i < list->len; i++)
if(list->elems[i] == elem)
return i;
return -1;
} |
C | #ifndef COLA_H
#define COLA_H
/** Definicion del tipo de elemento almacenado en la cola **/
typedef struct {
char nombre[15];
char localizacion[15];
} TIPOELEMENTOCOLA;
/** Estructura para la cola **/
typedef void *TCOLA;
/**
* Reserva memoria para una cola de datos con el tipo [TIPOELEMENTOCOLA].
*
* @param q puntero a la cola a crear.
*/
void crearCola(TCOLA *q);
/**
* Destruye (libera la memoria reservada) la cola [q] y todos los elementos que almacena.
*
* @param q cola a destruir.
*/
void destruirCola(TCOLA *q);
/**
* Comprueba si la cola [q] esta vacia.
*
* @param q cola a comprobar si esta vacia.
* @return 1 si la cola esta vacia, 0 si no.
*/
int esColaVacia(TCOLA q);
/**
* Consulta el primer elemento de la cola [q], de haberlo, y lo almacena en [e], sin eliminarlo de la cola.
*
* @param q cola de la cual extraer el primer elemento.
* @param e variable donde almacenar el primer elemento de la cola.
*/
void consultarPrimerElementoCola(TCOLA q, TIPOELEMENTOCOLA *e);
/**
* Destruye (libera la memoria reservada) del primer elemento de la cola.
*
* @param q cola de la cual destruir el primer elemento.
*/
void suprimirElementoCola(TCOLA *q);
/**
* Anhade el elemento [e] a la cola [q].
*
* @param q cola a la cual anhadirle el elemento.
* @param e elemento a anhadir.
*/
void anadirElementoCola(TCOLA *q, TIPOELEMENTOCOLA e);
#endif // COLA_H |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* exec_port_cmd_arg_tab.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: curquiza <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/11/22 12:28:15 by curquiza #+# #+# */
/* Updated: 2019/11/22 12:28:16 by curquiza ### ########.fr */
/* */
/* ************************************************************************** */
#include "server.h"
static t_bool args_are_valid(char **args)
{
int arg_int;
while (*args)
{
if (ft_is_int(*args) == FALSE)
return (FALSE);
arg_int = ft_atoi(*args);
if (arg_int < 0 || arg_int > UCHAR_MAX)
return (FALSE);
args++;
}
return (TRUE);
}
char **port_get_arg_tab(char *cmd)
{
char **cmd_args;
char **arg_tab;
cmd_args = ft_strsplit(cmd, ' ');
if (!cmd_args || ft_tablen(cmd_args) != 2)
{
ft_tabdel(&cmd_args);
return (NULL);
}
arg_tab = ft_strsplit(cmd_args[1], ',');
ft_tabdel(&cmd_args);
if (!arg_tab || ft_tablen(arg_tab) != 6 || args_are_valid(arg_tab) == FALSE)
{
ft_tabdel(&arg_tab);
return (NULL);
}
return (arg_tab);
}
|
C | #include "../include/apue.h"
#define BSZ 48
void fun(char* str, int size)
{
for (int i = 0; i != size; ++i)
printf("%c", str[i]);
printf("\n");
}
#define TEST do { printf("测试:"); fun(buf, BSZ);} while (0)
int main()
{
FILE* fp;
char buf[BSZ];
memset(buf, 'a', BSZ - 2);
buf[BSZ - 2] = '\0';
buf[BSZ - 1] = 'X'; //buf aaaaaaaaaaaa0X
TEST;
if ((fp = fmemopen(buf, BSZ, "w+")) == NULL) //buf 00000000000000
{
err_sys("fmemopen failed");
}
TEST;
printf("initial buffer contents: %s\n", buf); // buf 000000000000
TEST;
fprintf(fp, "hello, world"); //io hello,world
printf("before flush: %s\n", buf); // buf 0000000000000
TEST;
fflush(fp);//io 0
TEST;
printf("after fflush: %s\n", buf); // buf hello,world
TEST;
printf("len of string in buf = %ld\n", (long)strlen(buf));
memset(buf, 'b', BSZ-2);
buf[BSZ-2] = '\0';
buf[BSZ-1] = 'X';//buf bbbbbbbbbbbb0X
TEST;
fprintf(fp, "hello, world"); //hello, world
TEST;
fseek(fp, 0, SEEK_SET); //写入0
TEST;
printf("after fseek: %s\n", buf); //0
TEST;
printf("len of string in buf = %ld\n", (long)strlen(buf)); //0
memset(buf, 'c', BSZ - 2);
buf[BSZ - 2] = '\0';
buf[BSZ - 1] = 'X'; //ccccccccc0X
TEST;
fprintf(fp, "hello, world"); //io hello
TEST;
fclose(fp); //hello world0ccccccc0X
TEST;
printf("after fclose: %s\n", buf);
TEST;
printf("len of string in buf = %ld\n", (long)strlen(buf));
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int printRandoms(int l)
{
int num = rand() % 10 + l;
printf("Number is ganerated.\n");
return num;
}
void guessNumber(int val)
{
int gus_no, chance = 1;
while (chance < 9) //No of chances: 8
{
printf("Now guess the number:-\n");
scanf("%d", &gus_no);
if (gus_no > val)
{
printf("You guess the larger number than the generated number.Please try again.\n");
chance++;
}
else if (gus_no < val)
{
printf("You guess the smaller number than the generated number.Please try again.\n");
chance++;
}
else if (gus_no == val)
{
printf("Congrats you win the challenge.\n");
break;
}
else
{
printf("Sorry you lose the game.\n");
}
}
}
int main(void)
{
printf("Welcome to the GUESS THE NUMBER challenge\nHere you have the guess the number between 1 t0 10 that should be generated by the system.\nIf you guess the number you win the challenge.\nNow get ready for the challenge.\n");
srand(time(0)); //Seeding with Time
int gen_no = printRandoms(1);
guessNumber(gen_no);
return 0;
}
|
C | #include <stdio.h>
int main()
{
char a[10],b[10];
int i,n,ele;
scanf("%[^\n]s",a);
for(i=0;a[i]!='\0';i++)
{
n++;
}
for(i=0;i<n;i++)
{
if(a[i]==' ')
{
ele=i;
}
}
for(i=ele+1;i<=n;i++)
{
a[i-1]=a[i];
}
for(i=0;i<=n;i++)
{
printf("%c",a[i]);
}
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* unicode_conv.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: amedvedi <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/06/08 12:56:30 by amedvedi #+# #+# */
/* Updated: 2018/06/08 12:56:31 by amedvedi ### ########.fr */
/* */
/* ************************************************************************** */
#include "libftprintf.h"
int get_bytes(wchar_t elem)
{
if ((elem >> 16) > 0)
return (4);
else if ((elem >> 11) > 0)
return (3);
else if ((elem >> 7) > 0)
return (2);
else
return (1);
}
static void two_bytes(wchar_t elem)
{
unsigned int v;
unsigned char o;
unsigned char o1;
unsigned char o2;
v = elem;
o2 = (v << 26) >> 26;
o1 = ((v >> 6) << 27) >> 27;
o = ((unsigned int)49280 >> 8) | o1;
ft_putchar(o);
o = (((unsigned int)49280 << 24) >> 24) | o2;
ft_putchar(o);
}
static void three_bytes(wchar_t elem)
{
unsigned int v;
unsigned char o;
unsigned char o1;
unsigned char o2;
unsigned char o3;
v = elem;
o3 = (v << 26) >> 26;
o2 = ((v >> 6) << 26) >> 26;
o1 = ((v >> 12) << 28) >> 28;
o = ((unsigned int)14712960 >> 16) | o1;
ft_putchar(o);
o = (((unsigned int)14712960 << 16) >> 24) | o2;
ft_putchar(o);
o = (((unsigned int)14712960 << 24) >> 24) | o3;
ft_putchar(o);
}
static void four_bytes(wchar_t elem)
{
unsigned char o;
unsigned char o1;
unsigned char o2;
unsigned char o3;
unsigned char o4;
o4 = (elem << 26) >> 26;
o3 = ((elem >> 6) << 26) >> 26;
o2 = ((elem >> 12) << 26) >> 26;
o1 = ((elem >> 18) << 29) >> 29;
o = ((unsigned int)4034953344 >> 24) | o1;
ft_putchar(o);
o = (((unsigned int)4034953344 << 8) >> 24) | o2;
ft_putchar(o);
o = (((unsigned int)4034953344 << 16) >> 24) | o3;
ft_putchar(o);
o = (((unsigned int)4034953344 << 24) >> 24) | o4;
ft_putchar(o);
}
void unicode_conv(wchar_t elem)
{
if ((elem >> 16) != 0)
four_bytes(elem);
else if ((elem >> 11) != 0)
three_bytes(elem);
else if ((elem >> 7) != 0)
two_bytes(elem);
else
ft_putchar(elem);
}
|
C | #include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
int main()
{
for (int i = 0; i < 2; i++) // loop will run n times (n=5)
{
if (i == 0)
{
if (fork() > 0)
{
write(STDOUT_FILENO, "Hello ", 6);
return 0;
}
else
{
write(STDOUT_FILENO, "my ", 3);
}
}
else
{
if (fork() == 0)
{
write(STDOUT_FILENO, "friends\n", 8);
}
}
}
for (int i = 0; i < 2; i++) // loop will run n times (n=5)
{
wait(NULL);
}
return 0;
}
|
C | /*
* articulo.c
*
* Created on: 24 Jun 2020
* Author: Carlos
*/
#include <stdio.h>
#include <stdlib.h>
#include "IOdata.h"
#include "articulo.h"
#include "LinkedList.h"
#include "parser.h"
#include "controller.h"
#define LENGTH 128
eArticulo* articulo_new()
{
eArticulo* this = (eArticulo*) malloc(sizeof(eArticulo));
if(this != NULL)
{
this->Id_Articulo = 0;
strcpy(this->articulo,"");
strcpy(this->medida,"");
this->precio = 0;
this->rubro.id_rubro = 0;
strcpy(this->rubro.nombre_rubro,"");
}
return this;
}
eRubro* eRubro_new()
{
eRubro* this = (eRubro*) malloc(sizeof(eRubro));
if(this != NULL)
{
this->id_rubro = 0;
strcpy(this->nombre_rubro,"");
}
return this;
}
void articulo_delete(eArticulo* this)
{
free(this);
}
void rubro_delete(eRubro* this)
{
free(this);
}
eArticulo* articulo_newParametros(char* idStr, char* articulo, char* medida, char* precio, char* rubro)
{
eArticulo* this = NULL;
this = articulo_new();
if(this != NULL)
{
if(articulo_setId(this, idStr) ==0 &&
articulo_setNombreArticulo(this,articulo) == 0 &&
articulo_setMedida(this,medida) == 0 &&
articulo_setPrecio(this,atof(precio)) == 0 &&
articulo_setRubros(this, rubro) ==0 )
{
return this;
}else
{
this = NULL;
}
}
return this;
}
///////////////////////////////////// SETTERS //////////////////////////////////////////
int articulo_setId(eArticulo* this,char* id)
{
int retCode = -1;
if(this != NULL && id != NULL)
{
retCode = 0;
this->Id_Articulo = atoi(id);
}
return retCode;
}
int articulo_setNombreArticulo(eArticulo* this,char* nArticulo)
{
int retCode = -1;
if(this != NULL && nArticulo != NULL)
{
strncpy(this->articulo,nArticulo,LENGTH);
retCode = 0;
}
return retCode;
}
int articulo_setMedida(eArticulo* this,char* medida)
{
int retCode = -1;
if(this != NULL && medida != NULL)
{
strncpy(this->medida,medida,LENGTH);
retCode = 0;
}
return retCode;
}
int articulo_setPrecio(eArticulo* this, float precio)
{
int retCode = -1;
if(this != NULL && precio >= 0)
{
this->precio = precio;
retCode = 0;
}
return retCode;
}
int eRubro_setId(eRubro* this,char* rubro)
{
int retCode = -1;
if(this != NULL && rubro != NULL)
{
retCode = 0;
this->id_rubro = atoi(rubro);
}
return retCode;
}
int articulo_setRubros(eArticulo* this, char* rubro)
{
int retCode = -1;
eRubro* thisRubro = NULL;
thisRubro = eRubro_new();
if(this != NULL && thisRubro != NULL && rubro != NULL)
{
if(eRubro_setId(thisRubro, rubro) == 0)
{
switch(atoi(rubro))
{
case 1:
strcpy(thisRubro->nombre_rubro,"CUIDADO DE ROPA");
this->rubro = *thisRubro;
retCode = 0;
break;
case 2:
strcpy(thisRubro->nombre_rubro,"LIMPIEZA Y DESINFECCION");
this->rubro = *thisRubro;
retCode = 0;
break;
case 3:
strcpy(thisRubro->nombre_rubro,"CUIDADO PERSONAL E HIGIENE");
this->rubro = *thisRubro;
retCode = 0;
break;
case 4:
strcpy(thisRubro->nombre_rubro,"CUIDADO DEL AUTOMOTOR");
this->rubro = *thisRubro;
retCode = 0;
break;
}
}
}
return retCode;
}
///////////////////////////////////// GETTERS //////////////////////////////////////////
int articulo_getId(eArticulo* this,int* id)
{
int retCode=-1;
if(this!=NULL && id != NULL)
{
*id=this->Id_Articulo;
retCode=0;
}
return retCode;
}
int articulo_getArticuloNombre(eArticulo* this,char* articuloNombre)
{
int retCode=-1;
if(this!=NULL && articuloNombre != NULL)
{
strcpy(articuloNombre,this->articulo);
retCode=0;
}
return retCode;
}
int articulo_getMedida(eArticulo* this,char* medida)
{
int retCode=-1;
if(this!=NULL && medida != NULL)
{
strcpy(medida,this->medida);
retCode=0;
}
return retCode;
}
int articulo_getPrecio(eArticulo* this,float* precio)
{
int retCode=-1;
if(this!=NULL && precio != NULL)
{
*precio=this->precio;
retCode=0;
}
return retCode;
}
int articulo_getRubro(eArticulo* this,int* idRubro, char* nombreRubro)
{
int retCode=-1;
if(this!=NULL && idRubro != NULL && nombreRubro != NULL)
{
*idRubro= this->rubro.id_rubro;
strcpy(nombreRubro,this->rubro.nombre_rubro);
retCode=0;
}
return retCode;
}
int getArticulos(int* id, char* bufferMedida,char* bufferArticulo, float* bufferPrecio, char* rubroNombre, int* idRubro, eArticulo* this)
{
int retCode = -1;
if(id != NULL && bufferMedida != NULL && bufferArticulo != NULL && bufferPrecio != NULL && this != NULL)
{
if( articulo_getId(this,id) == 0 &&
articulo_getArticuloNombre(this,bufferArticulo) == 0 &&
articulo_getMedida(this,bufferMedida) ==0 &&
articulo_getPrecio(this,bufferPrecio) == 0 &&
articulo_getRubro(this,idRubro,rubroNombre) == 0)
{
retCode = 0;
}
}
return retCode;
}
int ordenarPorArticulo(void* genericField1, void* genericfield2)
{
int retCode = -2;
eArticulo* pAux1 = NULL;
eArticulo* pAux2 = NULL;
char AuxName1[128];
char AuxName2[128];
pAux1 = (eArticulo*)genericField1;
pAux2 = (eArticulo*)genericfield2;
articulo_getArticuloNombre(pAux1,AuxName1);
articulo_getArticuloNombre(pAux2,AuxName2);
if(stricmp(AuxName1,AuxName2)>0)
{
retCode = 1;
}
else if(stricmp(AuxName1,AuxName2)<0)
{
retCode = -1;
}
else
{
retCode = 0;
}
return retCode;
}
void calculoDeDescuentos(void* this)
{
float precio;
float descuento;
int idRubro;
char nombreRubro[35];
if(this != NULL)
{
articulo_getPrecio(this,&precio);
articulo_getRubro(this,&idRubro,nombreRubro);
if(precio >= 0 && nombreRubro != NULL)
{
if(idRubro == 1)
{
if(precio > 120)
{
descuento = 0.20;
precio = precio - (precio*descuento);
articulo_setPrecio(this,precio);
}
}else if(idRubro == 2)
{
if(precio > 200)
{
descuento = 0.10;
precio = precio - (precio*descuento);
articulo_setPrecio(this,precio);
}
}
}
}
}
int articulosPorMontoA(void* this)
{
int retCode = 0;
float auxPrecio1;
int countMonto = 0;
if(this != NULL)
{
articulo_getPrecio(this,&auxPrecio1);
if(auxPrecio1 > 100)
{
countMonto = 1;
retCode = countMonto;
}
}
return retCode;
}
int articulosPorRubroA(void* this)
{
int retCode = 0;
int auxRubroId;
char auxNombreRubro[128];
int countMonto = 0;
if(this != NULL)
{
articulo_getRubro(this,&auxRubroId,auxNombreRubro);
if(auxRubroId == 1)
{
countMonto = 1;
retCode = countMonto;
}
}
return retCode;
}
/*
int ordenarPorPrecio(void* genericField1, void* genericfield2)
{
int retCode = 0;
int auxPrecio1;
int auxprecio2;
eArticulo* pAux1;
eArticulo* pAux2;
if(genericField1 !=NULL && genericfield2 !=NULL)
{
pAux1 = (eArticulo*)genericField1;
pAux2 = (eArticulo*)genericfield2;
articulo_getPrecio(pAux1,&auxPrecio1);
articulo_getPrecio(pAux2,&auxprecio2);
if(auxPrecio1 > auxprecio2)
{
retCode = 1;
}
else if(auxPrecio1 < auxprecio2)
{
retCode = -1;
}
else
{
retCode = 0;
}
}
return retCode;
}*/
|
C | #include <stdio.h>
#include <string.h>
#include <math.h>
long long gcdl(long long m, long long n){
long long tmp;
while(m>0){
tmp = m;
m = n%m;
n = tmp;
}
return n;
}
long long lcm(int m, int n){
return m*(n/gcdl(m,n));
}
int main(){
int t,n,m;
long long lcm1;
scanf("%d", &t);
while(t--){
scanf("%d %d", &n, &m);
lcm1 = lcm(n,m);
printf("%lld %lld\n", lcm1/n, lcm1/m);
}
return 0;
}
|
C | #include<stdio.h>
#include<math.h>
int main()
{
long int i,a,c,m,n,z,x[10000];
float y[10000],t;
a = 1664525; //multiplier
c = 1013904223; //increment
m = 4294967296; //modulus
z = 0; //#seed
n = 10000;
t=0;
for (i=0;i<n;i++)
{
x[i]=z;
z = (a*z+c)%m; //linear congruential random no generator
if(x[i]>t)
t=x[i]; //at last t is the maximum random no
}
for (i=0;i<n;i++)
{
y[i]=-0.5*log(x[i]/t); //generating random number using transformation mathod
printf("%f ",y[i]); //printing random numbers
}
}
|
C | #include <stdio.h>
#include "lists.h"
/**
* listint_len - print all the elements of a list
* @h: listint_t
* Return: number of nodes
*/
size_t listint_len(const listint_t *h)
{
int i = 0;
while (h)
{
h = h->next;
i++;
}
return (i);
}
|
C | #include<stdio.h>
int main()
{
int i,n;
while(scanf("%d", &n)==1){
int slug[n],level=0;
for(i=0;i<n;i++)
scanf("%d", &slug[i]);
for(i=0;i<n;i++){
if(slug[i] < 10){
if(level<1)
level = 1;}
else if(slug[i]>=10 && slug[i]<20){
if(level<2)
level =2;}
else{
if(level<3)
level = 3;}
}
printf("%d\n", level);
}
return 0;
}
|
C | #include "main.h"
/**
* clear_bit - sets a bit at an index to 0
* @n: the number
* @index: index of bit to be cleared
* Return: 1 or -1
*/
int clear_bit(unsigned long int *n, unsigned int index)
{
if (*n == 0 && index == 0)
{
*n &= ~(1 << index);
return (1);
}
else if (*n == 0 || index > 63)
return (-1);
*n &= ~(1 << index);
return (1);
}
|
C | #include <stdio.h>
#include <stdlib.h>
int main(){
int size=2;
typedef struct {
int x;
float y;
char c;
} record;
record *ptr,*ptr2;
ptr=(record *)calloc(size,sizeof(record));
ptr->x=12;ptr->y=13.12;ptr->c='i';
/*ptr2=ptr;
ptr->x=12;ptr->y=13.12;ptr->c='i';
printf("%d %f %c\n",ptr->x,ptr->y,ptr->c);
printf("%u\n",ptr);
ptr++;
ptr->x=10;ptr->y=15.12;ptr->c='j';
printf("%d %f %c\n",ptr->x,ptr->y,ptr->c);
printf("%u\n",ptr);
*/
//free (ptr2);
printf("%u\n",ptr);
printf("%d %f %c\n",ptr->x,ptr->y,ptr->c);
free(ptr);
//printf("%d %f %c\n",ptr2->x,ptr2->y,ptr2->c);
printf("%d %f %c\n",ptr->x,ptr->y,ptr->c);
//printf("%u\n",ptr2);
printf("%u\n",ptr);
return 0;
}
|
C | #include "strings.h"
#include <stdlib.h>
#include <stdio.h>
#define MAXPATH 261
#define MAXCNT 10
#define MAXSIZE (MAXPATH*MAXCNT)
int stok(char *str, char delim, char *ptr[], int size)
{
char *suf = str;
ptr[0] = str;
int i, j = 1;
while( ( i = schr(suf, delim, size) ) >= 0 ) {
suf[i] = '\0';
suf = suf + i + 1;
ptr[j] = suf;
j++;
}
return j;
}
int schr(char *str, char delim, int size)
{
int i, idx = -1;
for(i = 0; (i < size) && (str[i] != delim); i++);
if(str[i] == delim)
idx = i;
return idx;
}
void suntok(char *str, char delim, char *ptr[], int cnt)
{
int i;
for(i = 1; i < cnt; i++) {
*(ptr[i] - 1) = delim;
}
}
int slen(char *str)
{
int i;
for(i = 0; str[i] != '\0'; i++);
return i;
}
char toLowCase(char *str, int size)
{
for (int i = 0; i < size; i++) {
if( str[i] >= 'A' && str[i] <= 'Z')
str[i] = str[i] + ('a' - 'A');
}
}
int isIp(char *ptr[], int size, int t)
{
int l;
if (t == 3) {
for(l = 0; l <= 3; l++) {
int x;
x = atoi(ptr[l]);
if(x < 0 || x > 255) {
printf("IP is correct: no\n");
exit(EXIT_FAILURE);
}
}
return printf("IP is correct: yes\n");
}
else {
printf("IP is correct: no\n");
exit(EXIT_FAILURE);
}
}
void check(char *str, char *ptr[], int size)
{
int t, i, d;
if (scspn(str, size) > 0) {
printf("Is SCP: no\n");
return;
}
for(i = 0; (str[i] != '\0'); i++)
if(str[i] == ':')
d++;
if (d == 1)
printf("Is SCP: yes\n");
else {
printf("Is SCP: no\n");
return;
}
int j = stok(str, ':', ptr, size);
for(i = 0; (str[i] != '\0'); i++)
if(str[i] == '.')
t++;
if (t == 3) {
for(i = 0; i < str[i] != '\0'; i++)
if((str[i] >= '0' && str[i] <= '9') || (str[i] == '.'))
t = 3;
else {
t = 4;
break;
}
}
char *ptr2[228];
int k = stok(str, '.', ptr2, size);
isIp(ptr2, size, t);
suntok(str, '.', ptr2, k);
suntok(str, ':', ptr, j);
process(str, size);
output(str);
}
void process(char *str, int size)
{
toLowCase(str, size);
}
void input(char *str)
{
printf("input paths: ");
fgets(str, MAXSIZE, stdin);
}
void output(char *str)
{
printf("updated path is: %s\n", str);
}
int scspn(char str[], int size)
{
char nsym[] = {'\\', '+', '*', '?', '"', '<', '>', '|'};
int j;
for(j = 0; nsym[j] != '\0'; j++)
if (schr(str, nsym[j], size) >= 0)
return 1;
return 0;
}
|
C | /*
** EPITECH PROJECT, 2021
** mylist
** File description:
** string_list_concat
*/
#include <string.h>
#include <stdlib.h>
#include "mylist/string_list.h"
static char *set_size_and_returns(char *str, size_t nmemb, size_t *length)
{
if (length) {
*length = nmemb;
}
return str;
}
static size_t get_str_size(const string_list_t *list, const char *sep)
{
size_t size = 0;
const size_t nb_str = list_len(list);
const int has_separator = (nb_str > 1 && sep && *sep);
list_foreach(node, list) {
size += node->data.size;
}
if (has_separator)
size += (strlen(sep) * (nb_str - 1));
return size;
}
char *string_list_concat(const string_list_t *list, const char *separator,
size_t *length)
{
const size_t size = (list) ? get_str_size(list, separator) : 0;
char *str = (list) ? calloc(size + 1, sizeof(*str)) : NULL;
if (!str)
return set_size_and_returns(NULL, 0, length);
list_foreach(node, list) {
strcat(str, NODE_STR(node));
if (node->next && separator && *separator)
strcat(str, separator);
}
return set_size_and_returns(str, size, length);
} |
C | #include "menu.h"
#include "hash.h"
#include "lista.h"
#include "utils.h"
#include <stdbool.h>
struct comando
{
const char *nombre;
const char *documentacion;
ejecutar ejecutor;
hash_t *subcomandos;
};
struct menu
{
hash_t *comandos;
};
comando_t *comando_crear(const char *nombre, const char *documentacion, void (*ejecutar)(size_t argc, char *argv[], void *))
{
comando_t *comando = calloc(1, sizeof(comando_t));
if (!comando)
return NULL;
comando->nombre = nombre;
comando->documentacion = documentacion;
comando->ejecutor = ejecutar;
return comando;
}
void comando_destruir(void *comando)
{
if (comando)
free(comando);
}
menu_t *menu_crear()
{
menu_t *menu = calloc(1, sizeof(menu_t));
if (!menu)
return NULL;
menu->comandos = hash_crear(comando_destruir, 10);
if (!menu->comandos)
{
free(menu);
return NULL;
}
return menu;
}
void menu_agregar_comando(menu_t *menu, const char *nombre, const char *documentacion, void (*ejecutar)(size_t argc, char *argv[], void *))
{
comando_t *comando = comando_crear(nombre, documentacion, ejecutar);
if (!comando)
return;
hash_insertar(menu->comandos, nombre, comando);
}
//ni siquiera es necesario que las funciones de ejecucion sean bool. No uso en ningun lado el resultado
void menu_procesar_opcion(menu_t *menu, const char *linea, void *contexto)
{
bool *error = lista_elemento_en_posicion(*(lista_t **)contexto, 2);
char **argumentos = split(linea, ':');
if (!argumentos)
{
*error = true;
printf("No se pudo ejecutar la opción\n");
return;
}
comando_t *comando = hash_obtener(menu->comandos, argumentos[0]);
if (comando)
{
comando->ejecutor(vtrlen(argumentos), argumentos, contexto);
}
else
{
*error = true;
}
vtrfree(argumentos);
}
void menu_destruir(menu_t *menu)
{
hash_destruir(menu->comandos);
free(menu);
} |
C | #include<stdio.h>
#include<stdlib.h>
const long long row = 100, col = 100;
long long N, q, lastAnswer = 0;
long long i = 0;
long long *counter;
void query1 ( long long *array[q], long long x, long long y ) {
long long index = ( x ^ lastAnswer) % N;
array[index][counter[index]++] = y;
//printf("%lld. Value of array[%lld][%lld] : %lld\n", ++i, index, counter[index] - 1, array[index][counter[index] - 1] );
}
void query2 ( long long *array[q], long long x, long long y ) {
long long index = ( x ^ lastAnswer ) % N;
long long temp_col = y % counter[index];
lastAnswer = array[index][temp_col];
//printf("%lld. Array [%lld][%lld] --> last lastAnswer : %lld\n", ++i, index, temp_col, lastAnswer);
printf("%lld\n", lastAnswer );
}
int main () {
long long check_query, x, y;
scanf("%lld %lld\n", &N, &q);
long long *array[q];
for (long long i = 0; i < q; i++) {
array[i] = (long long *) malloc(N*sizeof(long long));
}
counter = (long long *) malloc(100000*sizeof(long long));
for (long long i = 0; i < N; i++ ){
counter[i] = 0;
}
for (long long i = 0; i < q; i++ ) {
scanf("%lld %lld %lld\n", &check_query, &x, &y);
switch (check_query) {
case 1 :
query1 (array, x, y);
break;
case 2 :
query2 (array, x, y);
break;
default :
printf("Wrong input ! ");
return 1;
}
}
return 0;
}
|
C | /*
Main program of calculator example.
Simply invoke the parser generated by bison, and then display the output.
*/
#include <stdio.h>
#include <string.h>
#include "expr.h"
#include "stmt.h"
#include "scope.h"
#include "param_list.h"
#include "type.h"
#include "decl.h"
/* Clunky: Declare the parse function generated from parser.bison */
extern int yyparse();
extern FILE *yyin;
extern char *yytext;
/* Clunky: Declare the result of the parser from parser.bison */
extern struct decl *parser_result;
int main( int argv, char *argc[] )
{
//yyin = fopen(argc[1],"r");
if(!strcmp(argc[1],"-print")){
yyin = fopen(argc[2],"r");
if(yyparse()==0) {
decl_print(parser_result,0);
scope_enter();
return 0;
}
}else if(!strcmp(argc[1],"-resolve"))
{
yyin = fopen(argc[2],"r");
if(yyparse()==0) {
scope_enter();
decl_resolve(parser_result,1);
printf("%d resolve errors found\n",get_incrementError(3));
if(get_incrementError(3) > 0)return 0;
return 1;
}
}
else if(!strcmp(argc[1],"-typecheck"))
{
yyin = fopen(argc[2],"r");
if(yyparse()==0) {
scope_enter();
decl_resolve(parser_result,0);
if(get_incrementError(3) > 0){
printf("Resolve Errors Founded, type Check Aborted\n");
return 0;
}
decl_typecheck(parser_result);
return 1;
}
}
else if(!strcmp(argc[1],"-codegen")){
yyin = fopen(argc[2],"r");
if(yyparse()==0) {
scope_enter();
decl_resolve(parser_result,0);
if(get_incrementError(3) > 0){
printf("Resolve Errors Founded, type Check Aborted\n");
return 0;
}
else printf("No resolve errors\n");
decl_typecheck(parser_result);
printf("%d typeckek errors found\n",get_incrementError(4));
if(get_incrementError(4) > 0)return 0;
FILE * fp;
fp = fopen (argc[3], "w+");
decl_codegen(parser_result,fp);
return 1;
}
}
return 1;
}
|
C | #include <dlfcn.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#define CCAT(x, y) x ## y
#define CCAT2(x, y) CCAT(x, y)
#define T1_CCAT(x) CCAT2(T1_PREFIX, x)
struct router {
short int res_code;
T1 res_buf;
};
void
router_construct(struct router* r)
{
r->res_code = 0;
T1_CCAT(construct)(&r->res_buf, NULL, 0);
}
void
router_deconstruct(struct router* r)
{
T1_CCAT(deconstruct)(&r->res_buf);
}
int
router_ready(struct router* r)
{
return r->res_code != 0;
}
T1*
router_get(struct router* r)
{
return &r->res_buf;
}
void
router_insert(struct router* r, const char* uri)
{
void *dlhandle;
const char* (*symbol)(const char*);
int rc;
const char* res;
char* dl;
dl = malloc(4096);
assert(dl != NULL);
snprintf(dl, 4096, "./%s", uri + 1);
printf("Opening: %s\n", dl);
dlhandle = dlopen(dl, RTLD_NOW | RTLD_LOCAL);
if (dlhandle == NULL) printf("%s\n", dlerror());
assert(dlhandle != NULL);
symbol = dlsym(dlhandle, "entry");
if (symbol == NULL) printf("%s\n", dlerror());
assert(symbol != NULL);
res = symbol(uri);
r->res_code = 200;
T1_CCAT(insert)(&r->res_buf, res, strlen(res));
free((void*)res);
rc = dlclose(dlhandle);
assert(rc == 0);
}
#undef T1_CCAT
#undef CCAT2
#undef CCAT
#undef T1_PREFIX
#undef T1
|
C | #include <stdio.h>
#include <time.h>
void cabecalho(){
FILE *arquivo = fopen("./data/graph.csv", "w");
if(arquivo == NULL){
printf("arquivo nao foi aberto\n");
}else{
fprintf(arquivo,"cliente,data,hora \n");
fclose(arquivo);
}
}
void escreveArquivo(char *cliente){
time_t timer;
char buffer[26];
struct tm* tm_info;
timer = time(NULL);
tm_info = localtime(&timer);
strftime(buffer, 26, "%Y-%m-%d, %H:%M:%S", tm_info);
FILE *arquivo = fopen("./data/graph.csv", "a");
if(arquivo == NULL){
printf("arquivo nao foi aberto\n");
}else{
fprintf(arquivo,"%s,%s\n", cliente, buffer);
fclose(arquivo);
}
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "point.h"
void initPoint(Point2D *p)
{
p->x=0;
p->y=0;
}
void setPoint(Point2D *p,int x,int y)
{
p->x=x;
p->y=y;
}
int comparePoint(Point2D *p1,Point2D *p2)
{
if(p1->x==p2->x && p1->y==p2->y)
return 1;
else
return 0;
}
double distEuclid(Point2D p1,Point2D p2)
{
double d=(p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y);
return sqrt(d);
}
int comparePts(void *p1,void *p2)
{
Point2D *pt1,*pt2;
pt1=(Point2D *)p1;
pt2=(Point2D *)p2;
if(pt1->x > pt2->x)
return 1;
else if(pt1->x < pt2->x)
return -1;
else
{
if(pt1->y > pt2->y)
return 1;
else if(pt1->y < pt2->y)
return -1;
else
return 0;
}
return 0;
}
|
C | #include <msp430.h>
// constants
const char slaveAddrLED = 0x0012; // LED address
const char slaveAddrLCD = 0x0014; // LCD address
const char slaveAddrRTC = 0x0068; // RTC address
const unsigned int lightThreshold = 130; // ADC value threshold to distinguish if light or dark
const unsigned int ADCcount = 4; // number of ADCs in the circuit
const unsigned int sendDataLength = 5; // length of sendData array
// global variables
int tempData[ADCcount]; // array where ADC values are stored
char sendData[sendDataLength]; // array that will be sent to LCD
unsigned int player1Score = 2, player2Score = 2;// players' scores
char sendSpecialChar; // special character that will be sent to LCD/LED
unsigned int globalIndex = 0; // global index used to send data via I2C
// LCD variables
int isLCDdata = 1; // 0 is YES, 1 is NO
// RTC variables
char minutes; // minutes - encoded in hex but value is int
char seconds; // seconds - encoded in hex but value is int
unsigned int rtcDataCount = 0; // start counter at 0
unsigned int getRTCdata = 1; // get RTC data flag
unsigned int lastMinutes = 0;
// functions
void getADCvalues();
void calculatePlayerScores();
void populateSendData();
void getTimeFromRTC();
int getRTCseconds();
char getRTCminutes(char);
void sendToLCD(char);
void sendToLED(char);
// helper functions
char checkKeypad();
int delay(int);
int _delay1ms();
char _getCharacter(char);
int _toInt(char);
char _toChar(int);
char _hexToChar(char);
int _adcConversion(unsigned int);
char _hexToChar(char);
/**
* main.c
*/
int main(void) {
WDTCTL = WDTPW | WDTHOLD; // stop watchdog timer
// Setup I2C ports
UCB1CTLW0 |= UCSWRST; // put into software reset
UCB1CTLW0 |= UCSSEL_3; // choose SMCLK
UCB1BRW = 10; // divide by 10 to get SCL = 100kHz
UCB1CTLW0 |= UCMODE_3; // put into I2C mode
UCB1CTLW0 |= UCMST; // put into Master mode
UCB1CTLW0 |= UCTR; // put into Tx/WRITE mode
UCB1CTLW1 |= UCASTP_2; // AUTO stop when UCB1CNT reached
UCB1TBCNT = 0x01; // send 1 byte of data
// configure I2C ports
P4SEL1 &= ~BIT7; // set P4.7 as SCL
P4SEL0 |= BIT7;
P4SEL1 &= ~BIT6; // set P4.6 as SDA
P4SEL0 |= BIT6;
//Setup Timer compare
//divide by 4 and 16 bit with SMClock
//triggers about 3 times a second
TB0CTL |= TBCLR; // Clear timers and dividers
TB0CTL |= TBSSEL__ACLK; // ACLK
TB0CTL |= MC__UP; // count up to value in TB0CCR0
TB0CTL |= CNTL_1; // use 12-bit counter
TB0CTL |= ID__8; // use divide by 8
TB0CCR0 = 0x2AA; // count up to approx 166ms (read values 3 times a second)
TB0CCTL0 &= ~CCIFG; // Clear Flag
// configure ADC ports
P5SEL1 |= BIT0; // set P5.0 for channel A8 (P1)
P5SEL0 |= BIT0;
P5SEL1 |= BIT1; // set P5.1 for channel A9 (P1)
P5SEL0 |= BIT1;
P5SEL1 |= BIT2; // set P5.2 for channel A10 (P2)
P5SEL0 |= BIT2;
P5SEL1 |= BIT3; // set P5.3 for channel A11 (P2)
P5SEL0 |= BIT3;
UCB1CTLW0 &= ~UCSWRST; // put out of software reset
PM5CTL0 &= ~LOCKLPM5; // Turn on I/O
// configure ADC
ADCCTL0 &= ~ADCSHT; // clear ADCSHT from def. of ADCSHT=01
ADCCTL0 |= ADCSHT_2; // conversion cycles = 16 (ADCSHT=10)
ADCCTL0 |= ADCON; // turn ADC on
ADCCTL1 |= ADCSSEL_2; // ADC clock source = SMCLK
ADCCTL1 |= ADCSHP; // sample signal source = sampling timer
ADCCTL2 &= ~ADCRES; // Clear ADCRES from def. of ADCRES=01
ADCCTL2 |= ADCRES_2; // resolution = 12-bit (ADCRES=10)
ADCMCTL0 |= ADCINCH_8; // ADC input channel = A8 (P5.0)
UCB1IE |= UCTXIE0; // Enable I2C TX0 IRQ (transmit reg is ready)
UCB1IE |= UCRXIE0; // Enable I2C RX0 IRQ (receive reg is ready)
// TB0CCTL0 |= CCIE; // local enable timer interrupt
__enable_interrupt(); // global enable
P4DIR |= BIT5; // Set P4.5 as output
P4OUT |= BIT5; // start ON
sendToLCD('y'); // reset LCD
unsigned int prevPlayer1Score, prevPlayer2Score;
unsigned int firstIteration = 0;
while(1) {
getADCvalues(); // populates global array tempData with ADC values
calculatePlayerScores(); // calculates players scores with tempData
if(player1Score == 0 || player2Score == 0) {
getTimeFromRTC(); // get time from RTC via I2C
populateSendData();
sendToLCD('n');
sendToLED('n');
char keypad;
do {
keypad = checkKeypad();
} while(keypad != '*');
player1Score = 2;
player2Score = 2;
sendToLCD('y'); // reset LCD
sendToLED('y'); // reset LED
continue;
}
getTimeFromRTC(); // get time from RTC via I2C
populateSendData(); // populate sendData global array
sendToLCD('n'); // send sendData to LCD
sendToLED('n');
delay(3000);
}
return 0;
}
/**
* Function that initiates communication to LED
* LED address is 0x0012
* Will send the value in `LEDout` (determined in `LEDpattern()`)
*/
void sendToLED(char reset) {
if(reset == 'y') {
UCB1I2CSA = slaveAddrLED; // slave address to 0x14 (LCD slave address)
sendSpecialChar = '*'; // '*' will be sent to LCD
UCB1CTLW0 |= UCTR; // Put into Tx mode
UCB1TBCNT = 0x01; // Send 1 byte of data at a time
UCB1CTLW0 |= UCTXSTT; // Generate START, triggers ISR right after
while((UCB1IFG & UCSTPIFG) == 0) {} // Wait for START, S.Addr, & S.ACK (Reg UCB1IFG contains UCSTPIFG bit)
UCB1IFG &= ~UCSTPIFG;
return;
}
unsigned int i;
for(i = 2; i < 4; i++) {
UCB1I2CSA = slaveAddrLED; // slave address to 0x12 (LED slave address)
sendSpecialChar = sendData[i]; //
UCB1CTLW0 |= UCTR; // Put into Tx mode
UCB1TBCNT = 0x01; // Send 1 byte of data at a time
UCB1CTLW0 |= UCTXSTT; // Generate START, triggers ISR right after
while((UCB1IFG & UCSTPIFG) == 0) {} // Wait for START, S.Addr, & S.ACK (Reg UCB1IFG contains UCSTPIFG bit)
UCB1IFG &= ~UCSTPIFG;
}
i = 0;
char sp = sendSpecialChar;
}
/**
* Populates global sendData array based on current values
* sendData is what will be sent to LCD (some to LED)
* `specialChar is defaulted to 1 == FALSE /|\ 0 == TRUE
*/
void populateSendData() {
char bottomNibble, topNibble;
char s = minutes;
bottomNibble = (s << 4);
bottomNibble = bottomNibble >> 4;
topNibble = 0x00 | s >> 4;
sendData[0] = getRTCminutes(topNibble);
sendData[1] = getRTCminutes(bottomNibble);
sendData[2] = _toChar(player1Score);
sendData[3] = _toChar(player2Score);
if(player1Score == 0) { // if player 1 has score 0, player 2 wins
sendData[4] = ']';
}
else if(player2Score == 0) { // if player 2 has score 0, player 1 wins
sendData[4] = '[';
}
else {
sendData[4] = '!';
}
}
/**
* Calculates scores for player 1 and player 2 based on ADC values
*/
void calculatePlayerScores() {
int i;
player1Score = 0; // reset score to count new score
player2Score = 0; // reset score to count new score
for(i = 0; i < ADCcount; i++) {
if(tempData[i] < lightThreshold) {
if(i < 2) { // player 1 score
player1Score++;
}
else { // player 2 score
player2Score++;
}
}
}
}
/**
* Generates start condition to LCD device
* Send contents in sendData[]
* refresh = 'y' -> send refresh bit to LCD
*/
void sendToLCD(char reset) {
if(reset == 'y') {
UCB1I2CSA = slaveAddrLCD; // slave address to 0x14 (LCD slave address)
sendSpecialChar = '*'; // '*' will be sent to LCD
UCB1CTLW0 |= UCTR; // Put into Tx mode
UCB1TBCNT = 0x01; // Send 1 byte of data at a time
UCB1CTLW0 |= UCTXSTT; // Generate START, triggers ISR right after
while((UCB1IFG & UCSTPIFG) == 0) {} // Wait for START, S.Addr, & S.ACK (Reg UCB1IFG contains UCSTPIFG bit)
UCB1IFG &= ~UCSTPIFG;
return;
}
isLCDdata = 0; // enable LCD data transmission
for(globalIndex = 0; globalIndex < sendDataLength; globalIndex++) {
UCB1I2CSA = slaveAddrLCD; // slave address to 0x14 (LCD slave address)
UCB1CTLW0 |= UCTR; // Put into Tx mode
UCB1TBCNT = 0x01; // Send 1 byte of data at a time
UCB1CTLW0 |= UCTXSTT; // Generate START, triggers ISR right after
while((UCB1IFG & UCSTPIFG) == 0) {} // Wait for START, S.Addr, & S.ACK (Reg UCB1IFG contains UCSTPIFG bit)
UCB1IFG &= ~UCSTPIFG; // Clear flag
}
isLCDdata = 1; // disable LCD data transmission flag
}
/**
* Function that gets time data from RTC
* This will only occur every second.
* It is dependent from the `getRTCdata` flag.
* Flag gets toggled in `ISR_TB0_CCR0()` ISR
*/
void getTimeFromRTC() {
// Request time in [ss/mm] format
UCB1I2CSA = slaveAddrRTC; // Set Slave Address
UCB1CTLW0 |= UCTR; // Put into Tx mode
UCB1TBCNT = 0x01; // Send 1 byte of data at a time
sendSpecialChar = 0x00; // send RTC register to start the read from
UCB1CTLW0 |= UCTXSTT; // Generate START
while((UCB1IFG & UCSTPIFG) == 0) {} // Wait for START, S.Addr, & S.ACK (Reg UCB1IFG contains UCSTPIFG bit)
UCB1IFG &= ~UCSTPIFG; // Clear flag
// Receive Requested Data from RTC
UCB1I2CSA = slaveAddrRTC; // Set Slave Address
UCB1CTLW0 &= ~UCTR; // Put into Rx mode
UCB1TBCNT = 0x02; // Receive 2 bytes of data at a time
UCB1CTLW0 |= UCTXSTT; // Generate START
while((UCB1IFG & UCSTPIFG) == 0) {}
UCB1IFG &= ~UCSTPIFG; // Clear flag
getRTCdata = 0; // stop getting data from RTC
}
/**
* Grabs the minute and second (encoded in hex) and returns the value in seconds
*/
int getRTCseconds() {
char bottomNibble, topNibble;
char s = seconds;
bottomNibble = (s << 4); // left shift to remove top nibble
bottomNibble = bottomNibble >> 4; // right shift to get correct value
topNibble = 0x00 | s >> 4; // grab top nibble
int secondsInt = _toInt(_hexToChar(topNibble)) * 10 + _toInt(_hexToChar(bottomNibble)); // compute seconds
s = minutes;
bottomNibble = (s << 4);
bottomNibble = bottomNibble >> 4;
topNibble = 0x00 | s >> 4;
int minutesInt = _toInt(_hexToChar(topNibble)) * 10 + _toInt(_hexToChar(bottomNibble)); // compute minutes
return minutesInt * 60 + secondsInt; // return time in seconds
}
/**
* Converts the nibble to a character
*/
char getRTCminutes(char nibble) {
return _hexToChar(nibble);
}
/**
* Populates the global array tempData with ADC value
*/
void getADCvalues() {
unsigned int i;
for(i = 0; i < ADCcount; i++) {
tempData[i] = _adcConversion(i);
}
}
/**
* Function that changes the ADC channel and retrieves the ADC value
* returns the ADC value
*/
int _adcConversion(unsigned int index) {
char adcChannel;
switch(index) {
case 0:
adcChannel = ADCINCH_8;
break;
case 1:
adcChannel = ADCINCH_9;
break;
case 2:
adcChannel = ADCINCH_10;
break;
case 3:
default:
adcChannel = ADCINCH_11;
break;
}
ADCCTL0 &= ~(ADCENC | ADCSC);
ADCMCTL0 = adcChannel;
ADCCTL0 |= ADCENC | ADCSC; // grab photocell ADC value
while((ADCIFG & ADCIFG0) == 0); // wait to receive all data
return ADCMEM0;
}
// checks for the button pressed on keypad
char checkKeypad() {
// configure inputs
P1DIR &= ~BIT0; // Configure P1.0 (LED1) as input
P1DIR &= ~BIT1; // Configure P1.1 (LED1) as input
P1DIR &= ~BIT2; // Configure P1.2 (LED1) as input
P1DIR &= ~BIT3; // Configure P1.3 (LED1) as input
// set inputs as 0
P1OUT &= ~BIT0; // Configure P1.0 (LED1) as input
P1OUT &= ~BIT1; // Configure P1.1 (LED1) as input
P1OUT &= ~BIT2; // Configure P1.2 (LED1) as input
P1OUT &= ~BIT3; // Configure P1.3 (LED1) as input
//configure outputs
P1DIR |= BIT4; // Configure P1.4 (LED1) as output
P1DIR |= BIT5; // Configure P1.5 (LED1) as output
P1DIR |= BIT6; // Configure P1.6 (LED1) as output
P1DIR |= BIT7; // Configure P1.7 (LED1) as output
// turn on outputs
P1OUT |= BIT4; // Configure P1.4 (LED1) as output
P1OUT |= BIT5; // Configure P1.5 (LED1) as output
P1OUT |= BIT6; // Configure P1.6 (LED1) as output
P1OUT |= BIT7; // Configure P1.7 (LED1) as output
// setup pull-up/down resistors
P1REN |= BIT0; // enable pull up/down resistor on P1.0
P1REN |= BIT1; // enable pull up/down resistor on P1.1
P1REN |= BIT2; // enable pull up/down resistor on P1.2
P1REN |= BIT3; // enable pull up/down resistor on P1.3
// configure all resistors as pull up
P1OUT &= ~BIT0;
P1OUT &= ~BIT1;
P1OUT &= ~BIT2; // P1.2
P1OUT &= ~BIT3; // P1.3
char buttonPressed = 0x00; // initialize as 0
char currentSnapshot = P1IN;
// first switch statement
switch(currentSnapshot) {
case 0xF8:
buttonPressed = 0x08;
break;
case 0xF4:
buttonPressed = 0x04;
break;
case 0xF2:
buttonPressed = 0x02;
break;
case 0xF1:
buttonPressed = 0x01;
break;
default:
return '\0';
}
//configure inputs
P1DIR &= ~BIT4; // Configure P1.4 as output
P1DIR &= ~BIT5; // Configure P1.5 as output
P1DIR &= ~BIT6; // Configure P1.6 as output
P1DIR &= ~BIT7; // Configure P1.7 as output
//configure outputs
P1DIR |= BIT0; // Configure P1.0 as output
P1DIR |= BIT1; // Configure P1.1 as output
P1DIR |= BIT2; // Configure P1.2 as output
P1DIR |= BIT3; // Configure P1.3 as output
// turn on outputs
P1OUT |= BIT0; // Configure P1.0 as output
P1OUT |= BIT1; // Configure P1.1 as output
P1OUT |= BIT2; // Configure P1.2 as output
P1OUT |= BIT3; // Configure P1.3 as output
// setup pull-up/down resistors
P1REN |= BIT4; // enable pull up/down resistor on P1.4
P1REN |= BIT5; // enable pull up/down resistor on P1.5
P1REN |= BIT6; // enable pull up/down resistor on P1.6
P1REN |= BIT7; // enable pull up/down resistor on P1.7
// configure all resistors as pull up
P1OUT &= ~BIT4;
P1OUT &= ~BIT5;
P1OUT &= ~BIT6;
P1OUT &= ~BIT7;
currentSnapshot = P1IN;
// second switch statement
switch(currentSnapshot) {
case 0x8F:
buttonPressed ^= 0x80;
break;
case 0x4F:
buttonPressed ^= 0x40;
break;
case 0x2F:
buttonPressed ^= 0x20;
break;
case 0x1F:
buttonPressed ^= 0x10;
break;
default:
return '\0';
}
return _getCharacter(buttonPressed);
}
// translates the button pressed to ASCII
char _getCharacter(char buttonPressed) {
char button;
switch(buttonPressed) {
case 0x88:
button = '1';
break;
case 0x84:
button = '2';
break;
case 0x82:
button = '3';
break;
case 0x81:
button = 'A';
break;
case 0x48:
button = '4';
break;
case 0x44:
button = '5';
break;
case 0x42:
button = '6';
break;
case 0x41:
button = 'B';
break;
case 0x28:
button = '7';
break;
case 0x24:
button = '8';
break;
case 0x22:
button = '9';
break;
case 0x21:
button = 'C';
break;
case 0x18:
button = '*';
break;
case 0x14:
button = '0';
break;
case 0x12:
button = '#';
break;
case 0x11:
button = 'D';
break;
default:
button = '\0';
break;
}
return button;
}
// Converts hex encoded value to Char
// Ex: '0x08' -> '8'
char _hexToChar(char hex) {
switch(hex) {
case 0x01:
return '1';
case 0x02:
return '2';
case 0x03:
return '3';
case 0x04:
return '4';
case 0x05:
return '5';
case 0x06:
return '6';
case 0x07:
return '7';
case 0x08:
return '8';
case 0x09:
return '9';
default:
return '0';
}
}
// Converts char to int
int _toInt(char c) {
return c - '0';
}
// Converts int to char
char _toChar(int i) {
return i + '0';
}
/**
* delay: Delay set for approx 1 ms
*/
int delay(int LongCount) {
while(LongCount > 0) {
LongCount--;
_delay1ms();
}
return 0;
}
/**
* Delay1ms: Delay set for approx 1 ms
*/
int _delay1ms() {
int ShortCount;
for(ShortCount = 0; ShortCount < 102; ShortCount++) {}
return 0;
}
// ISRs -------------------------------------------------------------
/**
* I2C Interrupt Service Routine
*/
#pragma vector=EUSCI_B1_VECTOR
__interrupt void EUSCI_B1_I2C_ISR(void) {
switch(UCB1IV) {
case 0x16: // ID16 = RXIFG0 -> Receive
if(rtcDataCount == 0) { // getting seconds
seconds = UCB1RXBUF;
rtcDataCount++;
}
else if(rtcDataCount == 1) {
minutes = UCB1RXBUF; // getting minutes
rtcDataCount = 0;
}
break;
case 0x18: // ID18 = TXIFG0 -> Transmit
if(isLCDdata == 0) {
UCB1TXBUF = sendData[globalIndex]; // send current sendData char to LCD
}
else {
UCB1TXBUF = sendSpecialChar; // send LED value
}
break;
default:
break;
}
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#define HEIGHT 105
#define WIDTH 160
#define IMMUTABLE_ROCK -1
#define ROCK 0
#define ROOM 1
#define CORRIDOR 2
#define MIN_NUMBER_OF_ROOMS 10
#define MAX_NUMBER_OF_ROOMS 25
#define MIN_ROOM_WIDTH 7
#define DEFAULT_MAX_ROOM_WIDTH 15
#define MIN_ROOM_HEIGHT 5
#define DEFAULT_MAX_ROOM_HEIGHT 13
int board[HEIGHT][WIDTH] = {{ROCK}};
int NUMBER_OF_ROOMS = MIN_NUMBER_OF_ROOMS;
int MAX_ROOM_WIDTH = DEFAULT_MAX_ROOM_WIDTH;
int MAX_ROOM_HEIGHT = DEFAULT_MAX_ROOM_HEIGHT;
struct Room {
int start_x;
int end_x;
int start_y;
int end_y;
};
int random_int(int min_num, int max_num, int add_to_seed);
void initialize_immutable_rock();
void print_board();
void print_cell();
void dig_rooms(int number_of_rooms_to_dig);
void dig_room(int index, int recursive_iteration);
int room_is_valid_at_index(int index);
void add_rooms_to_board();
void dig_cooridors();
void connect_rooms_at_indexes(int index1, int index2);
struct Room rooms[MAX_NUMBER_OF_ROOMS];
int main(int argc, char *args[]) {
// Parse arguments
int opt;
while((opt = getopt(argc, args, "hn:")) != -1) {
switch(opt) {
case 'n':
NUMBER_OF_ROOMS = atoi(optarg);
break;
case 'h':
printf("usage: generate_dungeon [-n <number of rooms>]\n\n");
exit(0);
}
}
printf("Generating dungeon... \n");
// Determine # of rooms
if (NUMBER_OF_ROOMS < MIN_NUMBER_OF_ROOMS) {
printf("Minimum number of rooms is %d\n", MIN_NUMBER_OF_ROOMS);
NUMBER_OF_ROOMS = MIN_NUMBER_OF_ROOMS;
}
if (NUMBER_OF_ROOMS > MAX_NUMBER_OF_ROOMS) {
printf("Maximum number of rooms is %d\n", MAX_NUMBER_OF_ROOMS);
NUMBER_OF_ROOMS = MAX_NUMBER_OF_ROOMS;
}
printf("Making %d rooms.\n", NUMBER_OF_ROOMS);
// Generate board
initialize_immutable_rock();
dig_rooms(NUMBER_OF_ROOMS);
dig_cooridors();
print_board();
return 0;
}
int random_int(int min_num, int max_num, int add_to_seed) {
int seed = time(NULL);
if (add_to_seed) {
seed += add_to_seed * 10;
}
max_num ++;
int delta = max_num - min_num;
srand(seed);
return (rand() % delta) + min_num;
}
void initialize_immutable_rock() {
int y;
int x;
int max_x = WIDTH - 1;
int max_y = HEIGHT - 1;
for (y = 0; y < HEIGHT; y++) {
board[y][0] = IMMUTABLE_ROCK;
board[y][max_x] = IMMUTABLE_ROCK;
}
for (x = 0; x < WIDTH; x++) {
board[0][x] = IMMUTABLE_ROCK;
board[max_y][x] = IMMUTABLE_ROCK;
}
}
void print_board() {
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
print_cell(board[y][x]);
}
printf("\n");
}
}
void print_cell(int cell) {
if (cell == ROCK || cell == IMMUTABLE_ROCK) {
printf(" ");
}
else if (cell == ROOM) {
printf(".");
}
else if (cell == CORRIDOR) {
printf("#");
}
else {
printf("F");
}
}
void dig_rooms(int number_of_rooms_to_dig) {
for (int i = 0; i < number_of_rooms_to_dig; i++) {
dig_room(i, 0);
}
add_rooms_to_board();
}
void dig_room(int index, int recursive_iteration) {
// The index + recusrive_iteration is just a way to gain variety in the
// random number. The hope is that it makes the program run faster.
int start_x = random_int(0, WIDTH - MIN_ROOM_WIDTH - 1, index + recursive_iteration * 10);
int start_y = random_int(0, HEIGHT - MIN_ROOM_HEIGHT - 1, index + recursive_iteration / 10);
int room_height = random_int(MIN_ROOM_HEIGHT, MAX_ROOM_HEIGHT, index + recursive_iteration - 5000);
int room_width = random_int(MIN_ROOM_WIDTH, MAX_ROOM_WIDTH, index + recursive_iteration + 5000);
int end_y = start_y + room_height;
if (end_y >= HEIGHT - 1) {
end_y = HEIGHT - 2;
}
int end_x = start_x + room_width;
if (end_x >= WIDTH - 1) {
end_x = WIDTH - 2;
}
int height = end_y - start_y;
int height_diff = MIN_ROOM_HEIGHT - height;
if (height_diff > 0) {
start_y -= height_diff + 1;
}
int width = end_x - start_x;
int width_diff = MIN_ROOM_WIDTH - width;
if (width_diff > 0) {
start_x -= width_diff;
}
rooms[index].start_x = start_x;
rooms[index].start_y = start_y;
rooms[index].end_x = end_x;
rooms[index].end_y = end_y;
if (!room_is_valid_at_index(index)) {
dig_room(index, recursive_iteration + 1);
}
}
int room_is_valid_at_index(int index) {
struct Room room = rooms[index];
int width = room.end_x - room.start_x;
int height = room.end_y - room.start_y;
if (height < MIN_ROOM_HEIGHT || width < MIN_ROOM_WIDTH) {
return 0;
}
for (int i = 0; i < index; i++) {
struct Room current_room = rooms[i];
int start_x = current_room.start_x - 1;
int start_y = current_room.start_y - 1;
int end_x = current_room.end_x + 1;
int end_y = current_room.end_y + 1;
if ((room.start_x >= start_x && room.start_x <= end_x) ||
(room.end_x >= start_x && room.end_x <= end_x)) {
if ((room.start_y >= start_y && room.start_y <= end_y) ||
(room.end_y >= start_y && room.end_y <= end_y)) {
return 0;
}
}
}
return 1;
}
void add_rooms_to_board() {
for(int i = 0; i < NUMBER_OF_ROOMS; i++) {
struct Room room = rooms[i];
for (int y = room.start_y; y <= room.end_y; y++) {
for(int x = room.start_x; x <= room.end_x; x++) {
board[y][x] = ROOM;
}
}
}
}
void dig_cooridors() {
for (int i = 0; i < NUMBER_OF_ROOMS; i++) {
int next_index = i + 1;
if (next_index == NUMBER_OF_ROOMS) {
next_index = 0;
}
connect_rooms_at_indexes(i, next_index);
}
}
void connect_rooms_at_indexes(int index1, int index2) {
struct Room room1 = rooms[index1];
struct Room room2 = rooms[index2];
int start_x = ((room1.end_x - room1.start_x) / 2) + room1.start_x;
int end_x = ((room2.end_x - room2.start_x) / 2) + room2.start_x;
int start_y = ((room1.end_y - room1.start_y) / 2) + room1.start_y;
int end_y = ((room2.end_y - room2.start_y) / 2) + room2.start_y;
int x_incrementer = 1;
int y_incrementer = 1;
if (start_x > end_x) {
x_incrementer = -1;
}
if (start_y > end_y) {
y_incrementer = -1;
}
int cur_x = start_x;
int cur_y = start_y;
while(1) {
int random_num = random_int(0, RAND_MAX, cur_x + cur_y) >> 3;
int move_y = random_num % 2 == 0;
if (board[cur_y][cur_x] != ROCK) {
if (cur_y != end_y) {
cur_y += y_incrementer;
}
else if(cur_x != end_x) {
cur_x += x_incrementer;
}
else if(cur_y == end_y && cur_x == end_x) {
break;
}
continue;
}
board[cur_y][cur_x] = CORRIDOR;
if ((cur_y != end_y && move_y) || (cur_x == end_x)) {
cur_y += y_incrementer;
}
else if ((cur_x != end_x && !move_y) || (cur_y == end_y)) {
cur_x += x_incrementer;
}
else {
break;
}
}
}
|
C | #include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#define logp(...) {printf("[%s:%d] ", __FILE__, __LINE__); printf(__VA_ARGS__);}
#define BUFLEN 1024
#define MAXADDRLEN 256
#define PORT 8888
int server()
{
int sock = -1;
int clisock = -1;
struct sockaddr_in bindaddr;
char buf[BUFLEN] = {0};
char addr[MAXADDRLEN] = {0};
socklen_t addrlen = 0;
int nrecv = 0;
struct sockaddr *saddr = NULL;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
logp("open socket failed!\n");
return -1;
}
bzero((void*)&addr, sizeof(addr));
bindaddr.sin_family = AF_INET;
bindaddr.sin_port = htons(PORT);
bindaddr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
logp("bind addr failed, %s\n", strerror(errno));
goto FAIL;
}
if (listen(sock, 5) != 0) {
logp("listen on sock error!\n");
goto FAIL;
}
saddr = (struct sockaddr *)&addr;
clisock = accept(sock, saddr, &addrlen);
if (clisock < 0) {
logp("accept on sock failed, %s!\n", strerror(errno));
goto FAIL;
}
logp("accept from %s\n", inet_ntoa(*(struct in_addr*)saddr));
while (1) {
nrecv = recv(clisock, buf, BUFLEN, 0);
if (nrecv > 0) {
printf("%d bytes recved, data: %s\n", nrecv, buf);
}
}
close(clisock);
FAIL:
close(sock);
return 0;
}
int client()
{
int sock = -1;
struct sockaddr_in addr;
char buf[BUFLEN] = {0};
int nsend = 0;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
logp("open socket failed!\n");
return -1;
}
bzero((void*)&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
logp("connect to sock error, %s!\n", strerror(errno));
goto FAIL;
}
strncpy(buf, "hello world!", BUFLEN);
while (1) {
nsend = send(sock, buf, BUFLEN, 0);
if (nsend > 0) {
printf("%d bytes send\n", nsend);
}
sleep(1);
}
FAIL:
close(sock);
return 0;
}
int main(int argc, char **argv)
{
if (argc < 2) {
goto FAIL;
}
if (strcmp(argv[1], "server") == 0) {
return server();
} else {
if (strcmp(argv[1], "client") == 0) {
return client();
} else {
goto FAIL;
}
}
FAIL:
printf("%s server/client\n", argv[0]);
return 0;
} |
C | /*******************************************************************************
* Circular Buffer
*******************************************************************************
* FileName: CircularBuffer.h
* Dependencies: Compiler.h
* Author: Fernando Lpez Lara - Laboratorio de Sistemas Integrados
* Revision: Juan Domingo Rebollo - Laboratorio de Sistemas Integrados
******************************************************************************/
/* Includes *******************************************************************/
#include "GenericTypeDefs.h"
#include "Compiler.h"
/* Definitions ****************************************************************/
#define CIRCULAR_BUFFER_LENGTH 512
#define USB_OUT_BUFFER_MAX_LENGTH 64
#define USB_IN_BUFFER_MAX_LENGTH 64
#define CIRC_BUFFER_ERROR_CODE 0x7E //Fernando - Printable symbol '~'
/* Data types and structures **************************************************/
typedef struct{
UINT16 nextRead; //Next data position to be read
UINT16 nextWrite; //Next data position to be written
UINT16 dataLength; //Counter for data available in the buffer
char dataBuffer[CIRCULAR_BUFFER_LENGTH]; //Data
}CIRCULAR_BUFFER;
/* Function prototypes ********************************************************/
void initCircularBuffer(CIRCULAR_BUFFER *circ_buffer);
char getCircularBuffer(CIRCULAR_BUFFER *circ_buffer);
char putCircularBuffer(CIRCULAR_BUFFER *circ_buffer, char *data);
UINT16 getCircularBufferLength(CIRCULAR_BUFFER *circ_buffer);
char copyArrayToCircularBuffer(CIRCULAR_BUFFER *circ_buffer, char *data, INT16 inputLength); |
C | /*
Name: renderer
Purpose:
The renderer module allows for the visual representation of an entire
model, or specific parts of the model based on the current state
of the objects within the model->
Author: Tyrone Lagore
Version: March 10, 2014
*/
#include "defines.h"
#include "renderer.h"
#include "offsets.h"
#include "bitmaps.h"
#include "font.h"
#include "raster.h"
#include <unistd.h>
/*
Name: render
Purpose: Renders the entire model to the screen
*/
void render(const struct Model * model, UINT32 * base32,
UINT16 curPlayer)
{
UINT8 *base8 = (UINT8*) base32;
UINT16 player;
if (model->gameCondition > MISSILE_IN_AIR)
{
render_missile_impact(&model->missile, base8);
render_current_player(base8,
switch_player(curPlayer));
}
if (model->gameCondition == STARTUP)
render_startup(base32, model);
else if(model->gameCondition == STAGING &&
model->tanks[curPlayer].deltaX != 0)
render_tank(&model->tanks[curPlayer],
curPlayer,
base32);
else if (model->gameCondition == MISSILE_IN_AIR)
render_missile(&model->missile,
model->missile.previousX,
model->missile.previousY,
base8);
else if (model->gameCondition >= TERRAIN_MIN_CODE
&& model->gameCondition <= TERRAIN_MAX_CODE)
render_indexed_terrain(base32,
model->terrain,
model->gameCondition - 1);
else if (model->gameCondition == TANK_STRUCK1
|| model->gameCondition == TANK_STRUCK2)
{
player = model->gameCondition - TANK_COLLISION_OFFSET;
render_tank(&model->tanks[player],
player, base32);
render_health
(model->tanks[player].health,
player,
base32);
}
render_wind (base32, model->wind);
}
void render_startup(UINT32 * base32, const struct Model * model)
{
UINT8 *base8 = (UINT8*) base32;
UINT16 i;
clear_screen(base32);
render_terrain(model->terrain, base32);
render_word(base8, PLAYER_X, PLAYER_Y, "player", 6);
render_current_player(base8, 0);
render_word(base8, P1_HPWORD_X, HPWORD_Y, "health", 6);
render_word(base8, P2_HPWORD_X, HPWORD_Y, "health", 6);
render_word(base8, P1_POW_WORD_X, POW_Y, "power", 5);
render_word(base8, P2_POW_WORD_X, POW_Y, "power", 5);
for (i = 0; i < NUM_PLAYERS; i++)
{
render_tank(&model->tanks[i],
i,
base32);
plot_hline(base32,
model->stages[i].x1,
model->stages[i].x2,
model->stages[i].y);
render_health(model->tanks[i].health,
i,
base32);
render_power(model->tanks[i].power,
i,
base32);
render_wind(base32, model->wind);
}
}
void render_missile(const struct Missile *missile, int oldX,
int oldY, UINT8 * base8)
{
UINT32 * base32 = (UINT32*) base8;
if ((int)(missile->y + missile->height) > 0)
{
if (oldY <= 0)
clear_area(base32,
oldX + FONT_BUFFER,
oldX + LONG,
0,
LONG);
clear_area(base32,
oldX,
oldX + missile->width,
oldY,
oldY + missile->height - 1);
plot_bitmap_8(base8,
missile->x,
missile->y,
missile_bitmap,
MISSILE_HEIGHT);
}else
{
clear_area(base32,
oldX,
oldX + LONG,
0,
LONG);
plot_bitmap_8(base8,
missile->x,
0,
missile_tracker_bitmap,
BOMB_TRACKER_HEIGHT);
if (missile->x < 611)
render_number(base8,
missile->x,
BOMB_TRACKER_HEIGHT + FONT_BUFFER,
missile->y + missile->height);
}
}
void render_terrain(const struct Terrain terrain[], UINT32 * base)
{
int i;
for (i = 0; i < NUM_TERRAIN; i++)
plot_square(base,
terrain[i].x,
terrain[i].y,
terrain[i].width,
terrain[i].height,
FILL);
}
void render_tank(const struct Tank *tank, UINT16 player,
UINT32 *base32)
{
UINT16 *base16 = (UINT16*) base32;
UINT16 oldX = tank->x - tank->deltaX;
clear_area(base32,
oldX + cannon_clear_offset[player],
oldX + tank->width + cannon_x_offset[player],
tank->y - CANNON_Y_OFFSET,
tank->y + tank->height);
plot_bitmap_32(base32,
tank->x,
tank->y,
tank_bitmap,
tank->height);
plot_bitmap_16(base16,
tank->x + cannon_x_offset[player],
tank->y - CANNON_Y_OFFSET,
cannon_bitmap[player][tank->angle],
CANNON_HEIGHT);
}
/*
If tanks don't start with 100 health, must be changed to
first draw the border square of the health.
*/
void render_health(const UINT16 health, int player, UINT32 * base)
{
UINT8 * base8 =(UINT8*)base;
switch (player)
{
case PLAYER_ONE:
clear_area(base,
P1_HEALTH_X+1, P1_HEALTH_X + HP_W_CLEAR - 1,
HEALTH_Y+1, HEALTH_Y + HP_H_CLEAR);
plot_square(base, P1_HEALTH_X, HEALTH_Y,
health, HP_HEIGHT, FILL);
render_number (base8, P1_HPNUM_X,
HEALTH_Y, health);
break;
case PLAYER_TWO:
clear_area(base, P2_HEALTH_X+1,
P2_HEALTH_X + HP_W_CLEAR,
HEALTH_Y+1, HEALTH_Y + HP_H_CLEAR);
plot_square(base, P2_HEALTH_X + HP_W_CLEAR - health,
HEALTH_Y, health, HP_HEIGHT, FILL);
render_number (base8, P2_HPFONT_X,
HEALTH_Y, health);
break;
}
}
void render_power(const UINT16 pow, int player, UINT32 *base32)
{
UINT8 *base8 = (UINT8*) base32;
switch (player)
{
case PLAYER_ONE:
clear_area(base32, P1_POW_X+1, P1_POW_X + POW_W_CLEAR,
POW_Y+1, POW_Y + POW_H_CLEAR);
plot_square(base32, P1_POW_X, POW_Y +
POW_H_CLEAR - (pow >> 1),POW_WIDTH,
(pow >> 1), FILL);
render_number (base8, P1_POWNUM_X,
POWNUM_Y, pow);
break;
case PLAYER_TWO:
clear_area(base32, P2_POW_X+1, P2_POW_X + POW_W_CLEAR,
POW_Y+1, POW_Y + POW_H_CLEAR);
plot_square(base32, P2_POW_X, POW_Y +
POW_H_CLEAR - (pow >> 1),POW_WIDTH,
(pow >> 1), FILL);
render_number (base8, P2_POWNUM_X,
POWNUM_Y, pow);
break;
}
}
void render_indexed_terrain(UINT32 * base32,
const struct Terrain terrain[], int index)
{
int currIndex;
int start = -2;
int finish = 3;
if (index == 0 || index == 1)
start = index == 0 ? start += 2 : start ++;
else if (index == 38 || index == 39)
finish = index == 39 ? finish -=2 : finish --;
clear_area(base32, terrain[index + start + 1].x,
terrain[index + start + 1].x + ((finish - start - 2) << 3),
0, LOWEST_TERRAIN_POINT);
currIndex = index + start;
while (start < finish)
{
if (currIndex > 0 && currIndex < 39)
plot_square(base32, terrain[currIndex].x,
terrain[currIndex].y, terrain[currIndex].width,
terrain[currIndex].height, FILL);
currIndex++;
start++;
}
}
void render_missile_impact(const struct Missile *missile, UINT8 *base8)
{
UINT32 *base32 = (UINT32*) base8;
if (missile->y + missile->height > 0 &&
missile->x + missile->width < SCREEN_WIDTH)
{
clear_area(base32,
missile->x,
missile->x + BYTE + 1,
0,
BOMB_TRACKER_HEIGHT + 1);
clear_area(base32, missile->x, missile->x + missile->width,
missile->y, missile->y + missile->height);
}
/*plot_bitmap_8 (base8, missile.x , missile.y,
small_explosion_bitmap, MISSILE_HEIGHT);*/
}
void render_tank_explosion(const struct Tank *tank, int player,
UINT32 *base32)
{
clear_area(base32,
tank->x + cannon_clear_offset[player],
tank->x + tank->width,
tank->y - CANNON_Y_OFFSET,
tank->y + tank->height);
}
/*
*/
void render_word (UINT8 * base8, UINT16 x,
UINT16 y, char word[], UINT16 length)
{
UINT32 * base32 = (UINT32*)base8;
UINT16 i;
UINT16 currX = x;
clear_area(base32, x, x + ((length + FONT_BUFFER) << 3),
y, y + FONT_HEIGHT - 1);
for (i = 0; i < length; i++)
{
plot_bitmap_8 (base8,
currX,
y,
font_letters[(int)(word[i] - LETTER_OFFSET)],
FONT_HEIGHT);
currX += BYTE + FONT_BUFFER;
}
}
/*
Name: render_wind
Purpose: Takes in the current speed of the wind and renders
an arrow based on the direction of the wind (if negative,
left, if postive, right) and renders the speed underneath
it.
*/
void render_wind (UINT32 * base, int wind)
{
clear_area (base, WIND_X, WIND_X + LONG, WIND_Y,
WIND_Y + ARROW_HEIGHT);
plot_bitmap_32(base,
WIND_X,
WIND_Y,
wind < 0 ? arrow_bitmap[LEFT_WIND] : arrow_bitmap[RIGHT_WIND],
ARROW_HEIGHT);
render_number((UINT8*)base,
WIND_X + BYTE + (BYTE >> 1),
(WIND_Y - (WORD)),
wind);
}
UINT16 switch_player (UINT16 currentPlayer)
{
return currentPlayer == 0 ? 1 : 0;
}
void render_current_player(UINT8 * base, UINT16 player)
{
render_number (base, PLAYER_NUM_X, PLAYER_Y - 1, player + 1);
}
/*
Name: render_number
Purpose: Given an x, y, and a number, the function will
plot the associated bitmap to the number to the
screen.
*/
void render_number (UINT8 * base, UINT16 x, UINT16 y,
int number)
{
int i = 0;
UINT16 num[3];
UINT32 *base32 = (UINT32*)base;
if (number < 0)
number = (~(number) + 1) ;
clear_area (base32, x, x + LONG + 1,
y, y + FONT_HEIGHT);
do
{
num[i] = number % 10;
number /= 10;
i++;
}while (number != 0);
clear_area (base32, x, x + ((i + FONT_BUFFER) << 3),
y, y + FONT_HEIGHT);
i--;
while (i >= 0)
{
plot_bitmap_8(base, x, y, font_numbers[num[i]], FONT_HEIGHT);
x+= BYTE + FONT_BUFFER;
i--;
}
}
|
C | #ifndef _VARIABLES_H
#define _VARIABLES_H
#include "banking.h"
// Lets keep these odd numbers so null terminate makes even
#define MAX_VAR_NAME 11
#define MAX_VAR_VAL 81
char* vars_get(char* name);
void vars_set(char* name, char* value);
void printVars();
DECLARE_BANKED(vars_get, BANK(4), char*, bk_vars_get, (char* name), (name))
DECLARE_BANKED_VOID(vars_set, BANK(4), bk_vars_set, (char* name, char* value), (name, value))
#endif |
C | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_4__ TYPE_2__ ;
typedef struct TYPE_3__ TYPE_1__ ;
/* Type definitions */
struct TYPE_4__ {double period_ratio_delta; int computed; } ;
struct TYPE_3__ {int /*<<< orphan*/ period; } ;
struct hist_entry {TYPE_2__ diff; TYPE_1__ stat; } ;
/* Variables and functions */
double period_percent (struct hist_entry*,int /*<<< orphan*/ ) ;
__attribute__((used)) static double compute_delta(struct hist_entry *he, struct hist_entry *pair)
{
double old_percent = period_percent(he, he->stat.period);
double new_percent = period_percent(pair, pair->stat.period);
pair->diff.period_ratio_delta = new_percent - old_percent;
pair->diff.computed = true;
return pair->diff.period_ratio_delta;
} |
C | /*#############################################################
* File Name : cnt.c
* Author : winddoing
* Created Time : 2021年05月10日 星期一 16时08分42秒
* Description :
*############################################################*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
static void cnt(int datalen)
{
static int len = 0;
static int cnt = 1;
char buf[64];
static FILE *file = NULL;
if (!file)
file = fopen("./send_data.log", "w+");
if (len != datalen) {
if (len) {
printf("data size: %d, cnt: %d\n", len, cnt);
memset(buf, 0, sizeof(buf));
sprintf(buf, "data size: %d bit, cnt: %d\n", len, cnt);
fwrite(buf, 1, strlen(buf), file);
}
len = datalen;
cnt = 1;
} else {
cnt++;
}
}
int main(int argc, const char *argv[])
{
cnt(2);
cnt(2);
cnt(2);
cnt(2);
cnt(5);
cnt(5);
cnt(5);
cnt(5);
cnt(5);
cnt(5);
cnt(7);
cnt(7);
cnt(7);
cnt(7);
cnt(4);
cnt(4);
cnt(9);
cnt(1);
cnt(1);
cnt(1);
cnt(0);
return 0;
}
|
C | #include "holberton.h"
/**
** print_square - print a diagonal.
** @size: input diagonal.
** Return: no return.
**/
void print_square(int size)
{
int columna;
int fila;
int numeral = 35;
if (size <= 0)
{
_putchar('\n');
}
else
{
for (columna = 1; columna <= size; columna++)
{
for (fila = 1; fila <= size; fila++)
{
_putchar(numeral);
}
_putchar('\n');
}
}
}
|
C | #include "types.h"
#include "stat.h"
#include "user.h"
#include "fcntl.h"
#include "fs.h"
void headbyte(char* path, long long int nBytes) {
int fd;
fd = open(path, O_RDWR);
if(fd < 0) {
printf(1, "Error: Cannot open fd %s\n", path);
return;
}
char chr[1];
while(read(fd, chr, sizeof(char))) {
if (nBytes == 0) {
break;
}
printf(1, "%c", chr[0]);
nBytes--;
}
close(fd);
}
void headline(char* path, long long int nLines) {
// printf(1, "Headline Called: %s\n", path);
int fd;
fd = open(path, O_RDWR);
// printf(1, "fd: %d\n", fd);
if(fd < 0) {
printf(1, "Error: Cannot open fd %s\n", path);
return;
}
char chr[1];
while(read(fd, chr, sizeof(char))) {
if (nLines == 0) {
break;
}
printf(1, "%c", chr[0]);
if (chr[0] == '\n'){
nLines--;
}
}
close(fd);
}
int main(int argc, char* argv[]) {
int i;
long long int inNum;
if(argc < 2) {
printf(1, "Usage: head <mode> <filename>");
exit();
}
if(argv[1][0] == '-') {
if(argv[1][1] == 'n') {
if(argc < 4) {
printf(1, "Error: Usage head -n <NUM> <filename>\n");
exit();
}
inNum=atoi(argv[2]);
for(i=3;i<argc;i++) {
headline(argv[i], inNum);
}
} else if(argv[1][1] == 'c') {
if(argc < 4) {
printf(1, "Error: Usage head -c <NUM> <filename>\n");
}
inNum=atoi(argv[2]);
for(i=3;i<argc;i++) {
headbyte(argv[i], inNum);
}
} else if(argv[1][1] == 'q') {
for(i=2;i<argc;i++) {
headline(argv[i], 10);
}
} else if(argv[1][1] == 'v') {
for(i=2;i<argc;i++) {
printf(1, "==> %s <==\n", argv[i]);
headline(argv[i], 10);
}
} else {
printf(1, "error: mode undefined\n");
}
} else {
for(i=1; i<argc; i++) {
headline(argv[i], 10);
}
}
exit();
}
|
C |
#include <p18f4550.h>
#include "PWM_timer0.h"
#define TOP_INT 65535
#define TOP_RAMPA 12000
#define LARGURA_TOTAL 53535
#define MAX_DUTY 240
#define MIN_DUTY 10
unsigned char *portA_p0;
unsigned char mask_A;
unsigned int true_duty0_A;
unsigned char *portB_p0;
unsigned char mask_B;
unsigned int true_duty0_B;
void PWMtimer0_48MHzCLK_config(char priority) {
T0CON &= 0b10111111;
T0CS = 0;
T0SE = 0;
PSA = 1;
// T0CON = 0b00000111;
if (priority == NO_PRIORITY) {
} else if (priority == HIGH_PRIORITY) {
IPEN = 1;
TMR0IP = 1;
} else if (priority == LOW_PRIORITY) {
IPEN = 1;
TMR0IP = 0;
}
}
void PWMtimer0_on(void) {
TMR0IE = 1;
TMR0ON = 1;
TMR0IF = 0;
}
void PWMtimer0_A_pin(char *port, char *tris, char pino) {
char *tris_p;
char mask = 1, i;
for (i = 0; i < pino; i++) {
mask *= 2;
}
mask_A = mask;
mask = ~mask;
portA_p0 = port;
tris_p = tris;
*tris_p &= mask;
}
//********************************************************************************
//********************************************************************************
// (2^16 * Pre-ESC)/48 MHz = TIME
//********************************************************************************
//********************************************************************************
void PWMtimer0_A(unsigned char duty) {
if (TMR0IF) {
unsigned int time;
if (duty <= MIN_DUTY) {
duty = MIN_DUTY;
} else if (duty >= MAX_DUTY) {
duty = MAX_DUTY;
}
if ((*portA_p0) & mask_A) {
*portA_p0 &= (~mask_A); // CLR PINO
time = LARGURA_TOTAL + 48 * duty;
TMR0H = (time >> 8);
TMR0L = (time & 0x00FF);
true_duty0_A = TOP_INT - 48 * duty;
} else {
*portA_p0 |= mask_A; // SET PINO
TMR0H = (true_duty0_A >> 8);
TMR0L = (true_duty0_A & 0x00FF);
}
TMR0IF = 0;
}
}
void PWMtimer0_B_pin(char *port, char *tris, char pino) {
char *tris_p;
char mask = 1, i;
for (i = 0; i < pino; i++) {
mask *= 2;
}
mask_B = mask;
mask = ~mask;
portB_p0 = port;
tris_p = tris;
*tris_p &= mask;
}
void PWMtimer0_B(unsigned char duty) {
if (TMR0IF) {
unsigned int time;
if (duty <= MIN_DUTY) {
duty = MIN_DUTY;
} else if (duty >= MAX_DUTY) {
duty = MAX_DUTY;
}
if ((*portB_p0) & mask_B) {
*portB_p0 &= (~mask_B); // CLR PINO
time = LARGURA_TOTAL + 48 * duty;
TMR0H = (time >> 8);
TMR0L = (time & 0x00FF);
true_duty0_B = TOP_INT - 48 * duty;
} else {
*portB_p0 |= mask_B; // SET PINO
TMR0H = (true_duty0_B >> 8);
TMR0L = (true_duty0_B & 0x00FF);
}
TMR0IF = 0;
}
}
|
C | #include "gl_pixel.h"
#include "log.h"
const size_t gl_pixel_npos = -1;
static const gl_pixel_config _pixel_configs[] = {
{GL_RED, 1, -1},
{GL_RG, 2, -1},
{GL_RGB, 3, -1},
{GL_BGR, 3, -1},
{GL_RGBA, 4, 3},
{GL_BGRA, 4, 3}
};
static const size_t _num_pixel_configs =
sizeof(_pixel_configs) / sizeof(gl_pixel_config);
const gl_pixel_config* gl_pixel_get_config(GLenum format) {
size_t i = 0;
for (i = 0; i < _num_pixel_configs; i++) {
if (format == _pixel_configs[i].format) {
return &_pixel_configs[i];
}
}
LOG_WARNING("failed to find pixel config");
return NULL;
}
size_t gl_pixel_position(
int width,
int height,
int xPos,
int yPos,
const gl_pixel_config* config)
{
if (NULL == config) {
LOG_WARNING("null pointer");
return gl_pixel_npos;
}
return config->colorsPerPixel * (yPos * width + xPos);
}
|
C | /*--------------------------------------------------------------------------*/
/*---------------- TREE STRUCTURE ------------------------------------------*/
/* definition of datatype reednode */
typedef struct REEDNode REEDNode;
/* definition of datatype reedtree */
typedef struct REEDTree REEDTree;
/* definition of a R-EED Node */
struct REEDNode {
long value; /* 0: leaf, 1: internal,
-1: uninitialised */
float error; /* cached error for inpainting */
long cx,cy; /* corner locations of the corresponding
subimage */
long nx,ny; /* dimensions of the corresponding
subimage */
struct REEDNode *parent; /* parent node */
struct REEDNode *children[ 2 ]; /* child nodes */
struct REEDTree *tree; /* tree this node belongs to */
unsigned long level; /* tree level the node is located at,
the root node has level 0 */
};
/* definition of a R-EED Tree */
struct REEDTree {
unsigned long level; /* number of level the tree has */
unsigned long max_level; /* maximum level of the tree */
unsigned long min_level; /* minimum level of the tree */
long *open_nodes; /* unused nodes per level */
struct REEDNode **nodes; /* all tree nodes, sorted by level */
};
/*--------------------------------------------------------------------------*/
int createREEDTree
( REEDTree *tree, /* pointer to tree */
const unsigned long level ) /* number of desired tree level */
/* create a r-eed tree return 0 on success, 1 else */
{
unsigned long i = 0, j = 0; /* loop variables */
unsigned long n = 0; /* number of nodes (level) */
tree->max_level = 0;
tree->min_level = 0;
/* validate pointer */
if( tree == NULL )
return 1;
/* allocate memory for all desired levels */
tree->nodes = (REEDNode**)malloc( sizeof( REEDNode* ) * level );
tree->open_nodes = (long*)malloc( sizeof( long ) * level );
if( tree->nodes == NULL )
return 1;
/* allocate nodes on each level */
for( i = 0; i < level; i++ ) {
/* estimate the desired number of nodes for the current level */
n = pow( 2.0, i );
tree->nodes[ i ] = (REEDNode*)malloc( sizeof( REEDNode ) * n );
if( tree->nodes[ i ] == NULL ) {
for( j = 0; j < i; j++ )
free( tree->nodes[ i ] );
free( tree->nodes );
tree->nodes = NULL;
return 1;
}
tree->open_nodes[i]=n;
/* initialize nodes on current level */
if( i == 0 ) {
/* root node */
tree->nodes[ i ][ 0 ].value = 0;
tree->nodes[ i ][ 0 ].parent = NULL;
tree->nodes[ i ][ 0 ].children[ 0 ] = NULL;
tree->nodes[ i ][ 0 ].children[ 1 ] = NULL;
tree->nodes[ i ][ 0 ].tree = tree;
tree->nodes[ i ][ 0 ].level = 0;
}
else {
for( j = 0; j < n; j++ ) {
/* current node */
tree->nodes[ i ][ j ].value = -1;
tree->nodes[ i ][ j ].parent = &tree->nodes[ i - 1 ][ j / 2 ];
tree->nodes[ i ][ j ].children[ 0 ] = NULL;
tree->nodes[ i ][ j ].children[ 1 ] = NULL;
tree->nodes[ i ][ j ].tree = tree;
tree->nodes[ i ][ j ].level = i;
/* assignment (as child) to parent node */
tree->nodes[ i - 1 ][ j / 2 ].children[ j % 2 ] =
&tree->nodes[ i ][ j ];
}
}
}
/* set the number of tree level */
tree->level = level;
return 0;
}
/*--------------------------------------------------------------------------*/
void set_node(REEDNode *node,
long value,
long cx, long cy,
long nx, long ny,
float error) {
node->value = value;
node->cx = cx;
node->cy = cy;
node->nx = nx;
node->ny = ny;
node->error = error;
}
/*--------------------------------------------------------------------------*/
void init_tree(const REEDTree *tree, long nx, long ny) {
long i,n,j; /* loop variables */
long cx,cy; /* corners of subimage */
long nx_new=0, ny_new=0; /* dimensions of subimage */
REEDNode node; /* current node */
REEDNode parent; /* parent node */
/* initialise root node with full image */
set_node(&(tree->nodes[0][0]),0,1,1,nx,ny,-1);
for( i = 1; i < (long)(tree->level); i++ ) {
n = pow( 2.0, i );
for( j = 0; j < n; j++ ) {
node = tree->nodes[i][j];
parent = *(node.parent);
/* split subimage in its largest dimension */
if ((j%2)==0) { /* left child */
cx=parent.cx; cy=parent.cy;
if (parent.nx>=parent.ny) {
nx_new=parent.nx/2+1;
ny_new=parent.ny;
} else {
nx_new = parent.nx;
ny_new = parent.ny/2+1;
}
} else { /* right child */
if (parent.nx>=parent.ny) {
cx=parent.cx+parent.nx/2;
nx_new=parent.nx-parent.nx/2;
cy = parent.cy; ny = parent.ny;
} else {
cy=parent.cy+parent.ny/2;
ny_new = parent.ny-parent.ny/2;
cx=parent.cx; nx=parent.nx;
}
}
set_node(&(tree->nodes[i][j]),-1,cx,cy,nx_new,ny_new,-1);
}
}
}
/*--------------------------------------------------------------------------*/
int destroyREEDTree
( REEDTree *tree ) /* pointer to tree */
/* destroy a r-eed tree
return 0 on success, 1 else */
{
unsigned long i = 0; /* loop variable */
/* validate pointer */
if( tree == NULL )
return 1;
if( tree->nodes == NULL ) {
tree->level = 0;
return 0;
}
/* destroy nodes array */
for( i = 0; i < tree->level; i++ )
free( tree->nodes[ i ] );
free( tree->nodes );
free( tree->open_nodes);
tree->nodes = NULL;
tree->level = 0;
return 0;
}
/*--------------------------------------------------------------------------*/
REEDNode* addREEDNodeByPos
( REEDTree *tree, /* pointer to parent node */
long level, /* level */
long pos) /* position in level */
/* add a child node by given parent node,
return 0 on success, 1 else. */
{
REEDNode *node = NULL; /* temporary node */
long n;
/* validate pointer */
if( tree == NULL )
return 0;
if( (level < 0) || (level > (long)(tree->level)-2))
return 0;
/* check if there are still open nodes */
if (tree->open_nodes[level] < 1) {
return 0;
}
/* check if position is valid */
n = pow( 2.0, level );
if ( !(pos >= 0 || pos < n))
return 0;
/*
if( !( level >= 0 || level <= tree->max_level ) ||
!(pos >= 0 || pos < n))
return 0;
*/
node = &(tree->nodes[level][pos]);
/* do nothing if node is already set */
if (node->value==1) {
return 0;
}
/* set desired child node as leaf node */
node->value = 1;
node->children[0]->value = 0;
node->children[1]->value = 0;
tree->open_nodes[level]--;
/* validate parent has capacities or is not initialised yet */
if( (node->parent != NULL) && node->parent->value != 1 ) {
node = node->parent;
/* automatically initialize all parents as internal nodes */
while( node != NULL ) {
/* set parents value to 1 */
node->value = 1;
tree->open_nodes[node->level]--;
if (tree->open_nodes[node->level]==0) tree->min_level=level+1;
/* verify children have either a value of 1 or 0 */
if( node->children[ 0 ]->value == -1 )
node->children[ 0 ]->value = 0;
if( node->children[ 1 ]->value == -1 )
node->children[ 1 ]->value = 0;
node = node->parent;
}
}
/* update tree levels */
if ((long)tree->max_level < level) {
tree->max_level=level;
}
if (tree->open_nodes[level]==0) tree->min_level=level+1;
return node;
}
typedef struct _BITBUFFER {
unsigned char *b;
long max_size;
long byte_pos;
long bit_pos;
} BITBUFFER;
/*--------------------------------------------------------------------------*/
void alloc_bitbuffer
(BITBUFFER* buffer, /* bitbuffer */
long n) /* size */
/* allocates memory for a bitbuffer of size n */
{
long i;
buffer->b = (unsigned char *) malloc (n * sizeof(unsigned char));
if (buffer->b == NULL)
{
printf("alloc_bitbuffer: not enough memory available\n");
exit(1);
}
buffer->max_size=n;
for (i=0;i<buffer->max_size;i++) {
buffer->b[i]=0;
}
buffer->byte_pos=0;
buffer->bit_pos=0;
return;
}
/*--------------------------------------------------------------------------*/
long bitbuffer_addbit(BITBUFFER* buffer, unsigned char bit) {
if ((buffer->byte_pos < buffer->max_size) && (buffer->bit_pos < 8)) {
if (bit) buffer->b[buffer->byte_pos] |= (1 << buffer->bit_pos);
else buffer->b[buffer->byte_pos] &= ~(1 << buffer->bit_pos);
(buffer->bit_pos)++;
if (buffer->bit_pos > 7) {
buffer->bit_pos = 0;
buffer->byte_pos++;
}
return 1;
}
return 0; /* adding not successful, memory full */
}
/*--------------------------------------------------------------------------*/
void bitbuffer_writefile(BITBUFFER* buffer, FILE* bitfile) {
fwrite (buffer->b, sizeof(unsigned char), buffer->byte_pos+1, bitfile);
}
/*--------------------------------------------------------------------------*/
void bitbuffer_printbits(BITBUFFER* buffer) {
long i,j;
printf("Bitbuffer stores %ld bits:\n",
(buffer->byte_pos)*8+buffer->bit_pos);
for (i=0;i<buffer->byte_pos;i++) {
for (j=0;j<8;j++) {
printf("%u",((buffer->b[i] & (1u << j)) > 0));
}
printf(" ");
}
i=buffer->byte_pos;
for (j=0;j<buffer->bit_pos;j++) {
printf("%u",((buffer->b[i] & (1u << j)) > 0));
}
printf("\n");
}
/*--------------------------------------------------------------------------*/
int store_tree
( const REEDTree *tree, /* pointer to tree */
FILE *fp) /* bitfile to write to */
/* write reed tree to bitfile,
return 0 on success, 1 else. */
{
unsigned long i = 0, j = 0; /* loop variables */
unsigned long n = 0; /* number of nodes on current level */
BITBUFFER buffer;
/* validate pointer */
if( tree == NULL || fp == NULL )
return 1;
if( tree->nodes == NULL && tree->level != 0 )
return 1;
/* 1. header */
fwrite((unsigned char*)&(tree->min_level),sizeof(char),1,fp);
fwrite((unsigned char*)&(tree->max_level),sizeof(char),1,fp);
/* printf("Writing tree (%ld %ld)\n",tree->min_level,tree->max_level); */
/* 2. data */
/* write information of valid nodes to buffer array */
alloc_bitbuffer(&buffer,(long)(pow(2.0,tree->max_level)/8)+1);
for( i = tree->min_level; i <= tree->max_level; i++ ) {
/* estimate number of nodes on current level */
n = pow( 2.0, i );
for( j = 0; j < n; j++ ) {
if( (tree->nodes[i][j].value) != -1 ) {
/*printf("wrote bit %ld for node %ld %ld\n",
tree->nodes[ i ][ j ].value,i,j);*/
/*bfputb( tree->nodes[ i ][ j ].value, fp );*/
bitbuffer_addbit(&buffer,
(unsigned char)(tree->nodes[i][j].value));
}
}
}
/* bitbuffer_printbits(&buffer); */
bitbuffer_writefile(&buffer,fp);
return 0;
}
/*--------------------------------------------------------------------------*/
int load_tree
( REEDTree *tree, /* pointer to tree */
FILE *fp) /* bitfile to write to */
/* write reed tree to bitfile,
return 0 on success, 1 else. */
{
unsigned long i = 0, j = 0; /* loop variables */
unsigned long n = 0; /* number of nodes on current level */
long bit = 0; /* single bit, being loaded from bitfile */
unsigned char byte;
long bit_pos;
/* validate pointer */
if( tree == NULL || fp == NULL )
return 1;
/* 1. header */
fread (&byte, sizeof(char), 1, fp);
tree->min_level = (long)byte;
fread (&byte, sizeof(char), 1, fp);
tree->max_level = (long)byte;
/*printf("loading tree (min %ld, max %ld)\n",tree->min_level,
tree->max_level);*/
/* 2. data */
/* split all nodes below minimum level */
for( i = 0; i < tree->min_level; i++ ) {
/* estimate number of nodes on current level */
n = pow( 2.0, i );
tree->open_nodes[i]=0;
for( j = 0; j < n; j++ ) {
tree->nodes[i][j].value=1;
}
}
bit_pos = 8;
/* load all nodes up to maximum level */
for( i = tree->min_level; i <= tree->max_level; i++ ) {
/* estimate number of nodes on current level */
n = pow( 2.0, i );
for( j = 0; j < n; j++ ) {
/* check for each node if it can exist (i.e. parent is split) */
if (tree->nodes[i][j].parent->value == 1) {
if (bit_pos > 7) {
fread (&byte, sizeof(char), 1, fp);
/*printf("read byte %u\n",byte);*/
bit_pos = 0;
}
bit = (long)((byte & (1u << bit_pos)) > 0);
/* printf("read bit %ld for node %ld %ld (bitpos %ld)\n",bit,i,j,
bit_pos); */
bit_pos++;
tree->nodes[i][j].value=bit;
if (bit == 1) {
tree->open_nodes[i]--;
}
}
}
}
/* set children on maximum level */
i = tree->max_level + 1;
/* estimate number of nodes on current level */
n = pow( 2.0, i );
for( j = 0; j < n; j++ ) {
/* check for each node if parent is split */
if (tree->nodes[i][j].parent->value == 1) {
tree->nodes[i][j].value=0;
}
}
return 0;
}
/*--------------------------------------------------------------------------*/
/*-------- TREE SPECIFIC FUNCTIONS -----------------------------------------*/
void alloc_vector_nodes
(REEDNode ***vector, /* vector */
long n1) /* size */
/* allocates memory for a vector of size n1 */
{
*vector = (REEDNode**) malloc (n1 * sizeof(REEDNode*));
if (*vector == NULL)
{
printf("alloc_vector: not enough memory available\n");
exit(1);
}
return;
}
/*--------------------------------------------------------------------------*/
void add_points(REEDNode *node, float **mask) {
mask[node->cx][node->cy] = 1.0;
mask[node->cx][node->cy+node->ny-1]=1.0;
mask[node->cx+node->nx-1][node->cy]=1.0;
mask[node->cx+node->nx-1][node->cy+node->ny-1]=1.0;
mask[node->cx+node->nx/2][node->cy+node->ny/2]=1.0;
}
|
C | /*switch .. case*/
#include<stdio.h>
void main()
{
int n;
printf("Choose: \n1.Unlimited [email protected]@1hr.\[email protected]\[email protected]\nSelect: ");
scanf("%d",&n);
switch(n)
{
case 1:
printf("Your unlimited pack is activated!");
break;
case 5:
case 2:
printf("Your 20mb data pack is activated!");
break;
case 3:
printf("Your 1GB data pack is activated!");
break;
default:
printf("Invalid Option!");
}
}
|
C | #define _GNU_SOURCE
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
void setCpuAffinity(int cpu) {
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(cpu, &mask);
int rc = sched_setaffinity(0, sizeof(mask), &mask);
if (rc == 0) {
printf("Set affinity successfully.\n");
} else {
printf("Set affinity failed.\n");
exit(1);
}
}
void contextSwitch() {
int pipeFd[2];
int pipeFd2[2];
int rc = pipe(pipeFd);
int rc2 = pipe(pipeFd2);
if(rc == -1 || rc2 == -1) {
printf("Creating pipe failed!\n");
exit(1);
}
setCpuAffinity(1);
int forkRc = fork();
if(forkRc == -1) {
printf("Creating child process failed!\n");
exit(1);
} else if(forkRc == 0) { // child process
setCpuAffinity(1);
close(pipeFd[1]);
close(pipeFd2[0]);
char buf[512];
read(pipeFd[0], buf, 512);
char *msg = "Hello, I'm child process";
write(pipeFd2[1], msg, strlen(msg));
printf("Child process, receive msg from pipe: %s.\n", buf);
} else {
close(pipeFd[0]);
close(pipeFd2[1]);
char *msg = "Hello, I'm main process";
write(pipeFd[1], msg, strlen(msg));
char buf[512];
read(pipeFd2[0], buf, 512);
printf("Parent process, receive msg from pipe: %s.\n", buf);
}
}
int main(int argc, char *argv[]) {
contextSwitch();
}
|
C | /*===================================================================================*/
/*************************************************************************************/
/**
* @file 23_shell_progarm.c
* @brief Exercise on execlp
* @details A small shell program that has a command prompt “ashish> ” and uses
* execlp() to execute any inputs provided by the user
* @see
* @author Nutan Ghatge, [email protected]
* @copyright Copyright (c) 2017 Elear Solutions Tech Private Limited. All rights
* reserved.
* @license To any person (the "Recipient") obtaining a copy of this software and
* associated documentation files (the "Software"):\n
* All information contained in or disclosed by this software is
* confidential and proprietary information of Elear Solutions Tech
* Private Limited and all rights therein are expressly reserved.
* By accepting this material the recipient agrees that this material and
* the information contained therein is held in confidence and in trust
* and will NOT be used, copied, modified, merged, published, distributed,
* sublicensed, reproduced in whole or in part, nor its contents revealed
* in any manner to others without the express written permission of
* Elear Solutions Tech Private Limited.
*/
/*************************************************************************************/
/*===================================================================================*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
/*************************************************************************************
* LOCAL MACROS *
*************************************************************************************/
/*************************************************************************************
* LOCAL TYPEDEFS *
*************************************************************************************/
/*************************************************************************************
* LOCAL PROTOTYPES *
*************************************************************************************/
/*************************************************************************************
* GLOBAL VARIABLES *
*************************************************************************************/
/*************************************************************************************
* LOCAL VARIABLES *
*************************************************************************************/
/*************************************************************************************
* PRIVATE FUNCTIONS *
*************************************************************************************/
/*************************************************************************************
* PUBLIC FUNCTIONS *
*************************************************************************************/
/*************************************************************************************
* Refer to the header file for a detailed description *
*************************************************************************************/
/*************************************************************************************
* MAIN *
*************************************************************************************/
int main() {
char line[100];
while (printf("ashish>"), gets(line) != NULL) {
if (fork() == 0) {
if ((execlp(line, line, (char *)0)) == -1) {
perror("execlp failed");
printf("%s: not found\n", line);
}
} else wait(0);
}
return EXIT_SUCCESS;
}
|
C | #include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include "header.h"
#include <signal.h>
/**
* main - most AMAAAZINGGG simple SHELL, I call it SHELLY
* @ac: argument counter.
* @av: argument vector.
* @env: environment array.
* Return: Always 0.
*/
int main(int ac, char **av, char **env)
{
ssize_t test;
const char *path;
(void)ac;
char *buffer, **argv, *token, *dest, *token1;
size_t buffersize = 100;
buffer = malloc(buffersize * sizeof(char));
_check(buffer, av);
token = malloc(buffersize * sizeof(char));
_check(token, av);
dest = malloc(buffersize * sizeof(char));
_check(dest, av);
argv = malloc(buffersize);
if (argv == NULL)
exit(EXIT_FAILURE);
_arrayMalloc(argv, buffersize, av);
signal(SIGINT, SIG_IGN);
path = getenv("PATH");
while (test >= 0)
{
printy("$ ");
if (test == -1)
{
_putchar('\n');
exit(EXIT_FAILURE);
}
test = getline(&buffer, &buffersize, stdin);
if (test == EOF)
{
_putchar('\n');
exit(0);
}
toky(token, argv, buffer);
bulties(argv, env);
token1 = _strdup((char *)path);
token1 = strtok(token1, ":");
dest = toky_1(token1, argv, dest);
parenting(dest, argv, av);
}
freeing(buffer, token, dest, argv, token1);
return (0);
}
|
C | /*
Authors: Matt Rutherford, Megan Molumby, Abubakr Hassan
Course: COP2220
Project #: 2
Title: Modularized Conversion Tool
Due Date: 10/5/2014
Prompts user to input values for fahrenheit, feet, and pounds. Checks user input to make sure it is an integer
and within a specified range and then displays the original and converted values in a table format.
*/
#include<stdio.h>
#include<stdlib.h>
#define HEADER_FORMAT "%15s%15s%15s%15s%15s%15s\n"
#define ROW_FORMAT "%15s%15d%15s%15.3f%15s%15.3f\n"
#define FEET_CONVERSION_VALUE 0.3048
#define POUND_CONVERSION_VALUE 0.4536
#define INCHES_CONVERSION_VALUE 12
#define FAHRENHEIT_CONVERSION_VALUE 32.000
#define KELVIN_CONVERSION_VALUE 459.67
#define STONES_CONVERSION_VALUE 0.0714285714
//Function Prototypes
void convertDistance(int feet, double *pMeters, double *pInches);
void convertTemperature(int fahrenheit, double *pCelsius, double *pKelvin);
void convertWeight(int pounds, double *pKilograms, double *pStones);
void displayReport(int fahrenheit, int feet, int pounds, double celsius, double meters, double kilograms, double kelvin, double inches, double stones);
int getInput(int *pFahrenheit, int *pFeet, int *pPounds);
void performConversions(int fahrenheit, int feet, int pounds, double *pCelsius, double *pMeters, double *pKilograms, double *pKelvin, double *pInches, double *pStones);
int withinRange(int input, int minRange, int maxRange);
int main()
{
//Variables to store our original and converted values
int temp, weight, distance;
double celcius, meters, kilograms, kelvin, inches, stones;
//Displays Name of Authors and Project
printf("%s", "Matt Rutherford, Meghan Molumby, Abubakr Hassan\n");
printf("%s", "Project 2 - Modularized Unit Conversion Tool\n");
//Calls getInput function and if we have bad input the conversions and display functions are not executed.
if (getInput(&temp, &distance, &weight) == 1)
{
//Performs unit conversions
performConversions(temp, distance, weight, &celcius, &meters, &kilograms, &kelvin, &inches, &stones);
//Displays original and converted values
displayReport(temp, distance, weight, celcius, meters, kilograms, kelvin, inches, stones);
}
system("pause");
return 0;
}
/*
Prompts user to enter integer values for Farenheit, Feet, and Pounds. Checks to see if user
entered an actual integer and if the value is within the specified range for each input. If it is not an integer value it will
display the appropriate error message.
*pFahrenheit - Pointer for the Fahrenheit value
*pFeet - Pointer for the Feet value
*pPounds - Pointer for the Pounds value
Returns the status of our flag variable
*/
int getInput(int *pFahrenheit, int *pFeet, int *pPounds)
{
//Flag variable for valid input, default value is set to false until we do our checking
int isValid = 0;
//Gets user input for fahrenheit
printf("%s", "\nEnter a Fahrenheit temperature (integer) [0 - 212]: ");
if (scanf_s("%d", pFahrenheit) == 1)
{
//Checks range for fahrenheit
if (withinRange(*pFahrenheit, 0, 212) == 1)
{
//Gets user input for feet
printf("%s", "Enter a distance in feet (integer) [0 - 100]: ");
if (scanf_s("%d", pFeet) == 1)
{
//Checks range for feet
if (withinRange(*pFeet, 0, 100) == 1)
{
//Gets user input for pounds
printf("%s", "Enter a weight in pounds (integer) [0 - 100]: ");
if (scanf_s("%d", pPounds) == 1)
{
//Checks range for pounds
if (withinRange(*pPounds, 0, 100) == 1)
{
//All input is good, set flag variable to a true value
isValid = 1;
}
}
else
{
printf("%s", "\nThe entered weight is invalid.\n");
}
}
}
else
{
printf("%s", "\nThe entered distance is invalid.\n");
}
}
}
else
{
printf("%s", "\nThe entered temperature is invalid.\n");
}
return isValid;
}
/*
Checks the range of the integer values entered by the user.
If the value is not within range the user is prompted with an error message displaying the min and max range for that value.
input - The input for checking if it is within range
minRange - The minimum range for our input
maxRange - The maximum range for our input
Returns the status of our flag variable
*/
int withinRange(int input, int minRange, int maxRange)
{
//Flag variable for within range, default value is set to true until we check the range
int isWithinRange = 1;
if (input < minRange || input > maxRange)
{
isWithinRange = 0;
printf("%s%d%s%d%s", "\nThe entered value is out of range [", minRange, " - ", maxRange, "].\n");
}
return isWithinRange;
}
/*
Calls functions to perform conversions for Temperature, Distance, and Weight
fahrenheit - The fahrenheit value for temeperature conversion
feet - The feet value for distance conversion
pounds - The pounds value for weight conversion
*pCelsius - Pointer for celsius value for temperature conversion
*pMeters - Pointer for meters value for distance conversion
*pKilograms - Pointer for kilograms value for weight conversion
*pKelvin - Pointer for kelvin value for temperature conversion
*pInches - Pointer for inches value for distance conversion
*pStones - Pointer for stones value for weight conversion
*/
void performConversions(int fahrenheit, int feet, int pounds, double *pCelsius, double *pMeters, double *pKilograms, double *pKelvin, double *pInches, double *pStones)
{
convertDistance(feet, pMeters, pInches);
convertTemperature(fahrenheit, pCelsius, pKelvin);
convertWeight(pounds, pKilograms, pStones);
}
/*
Converts feet value entered by user to Meters and Inches and then derefrences the pointers to store our new converted values.
feet - Value for feet used in the conversion
*pMeters - Pointer for meters used in the conversion
*pInches - Pointer for inches used in the conversion
*/
void convertDistance(int feet, double *pMeters, double *pInches)
{
*pMeters = (feet * FEET_CONVERSION_VALUE);
*pInches = (feet * INCHES_CONVERSION_VALUE);
}
/*
Converts Fahrenheit value entered by user to Celsius and Kelvin and then derefrences the pointers to store our new converted values.
fahrenheit - Value for fahrenheit used in the conversion
*pCelsius - Pointer for celsius used in the conversion
*pKelvin - Pointer for kelvin used in the conversion
*/
void convertTemperature(int fahrenheit, double *pCelsius, double *pKelvin)
{
*pCelsius = (fahrenheit - FAHRENHEIT_CONVERSION_VALUE) * 5 / 9;
*pKelvin = (fahrenheit + KELVIN_CONVERSION_VALUE) * 5/9;
}
/*
Converts Pounds value enetered by user to Kilograms and Stones and then derefrences the pointers to store our new converted values.
pounds - Value for pounds used in the conversion
*pKilograms - Pointer for kilograms used in the conversion
*pStones - Pointer for stones used in the conversion
*/
void convertWeight(int pounds, double *pKilograms, double *pStones)
{
*pKilograms = pounds * POUND_CONVERSION_VALUE;
*pStones = pounds * STONES_CONVERSION_VALUE;
}
/*
Displays formatted column headers and rows as well as displaying our original values along with our converted values to the user
fahrenheit - Fahrenheit value used for displaying result
feet - Feet value used for displaying result
pounds - Pounds value used for displaying result
celsius - Celsius value used for displaying result
meters - Meters value used for displaying result
kilograms - Kilograms value used for displaying result
kelvin - Kelvin value used for dispalying result
inches - Inches value used for dispalying result
stones - Stones value used for displaying result
*/
void displayReport(int fahrenheit, int feet, int pounds, double celsius, double meters, double kilograms, double kelvin, double inches, double stones)
{
printf("%s", "\n");
printf(HEADER_FORMAT, "Original", "Value", "Converted to", "Value", "Converted to", "Value");
printf(HEADER_FORMAT, "--------", "-----", "------------", "-----", "------------", "-----");
printf(ROW_FORMAT, "Fahrenheit", fahrenheit, "Celsius", celsius, "Kelvin", kelvin);
printf(ROW_FORMAT, "Feet", feet, "Meters", meters, "Inches", inches);
printf(ROW_FORMAT, "Pounds", pounds, "Kilograms", kilograms, "Stones", stones);
}
|
C | #include<stdio.h>
int main()
{
int number;
printf("enter the number");
scanf("%d",&number);
if(number==0)
{
printf("armstrong number between two intrevels");
}
else
{
printf("not print");
}
}
|
C | /*
* File: main.c
* Author: Leonardo Adamoli
*
* Created on April 22, 2018, 4:06 PM
*/
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include "PilhaCF.h"
/*
*
*/
int main(int argc, char** argv) {
PilhaCF pilha1, pilha2, pilhaAux;
int i, dado, resp;
setlocale(LC_ALL, "portuguese");
printf ("------ CRIAÇÃO DAS PILHAS ------\n");
criaPilha(&pilha1);
criaPilha(&pilha2);
criaPilha(&pilhaAux);
for (i = 0; i < MAX_NODOS; i++) { //Carrega a pilha 1
printf ("Informe o elemento %d da Pilha 1: ", i + 1);
scanf ("%d", &dado);
resp = empilha(&pilha1, dado);
if (resp == SUCESSO)
printf ("OPERAÇÃO REALIZADA COM SUCESSO!\n");
else
printf ("PILHA CHEIA!\n");
}
for (i = pilha1.topo; i >= 0; i--) { //Tira os elementos da pilha 1 e joga em uma pilhaAux
resp = desempilha(&pilha1, &dado);
resp = empilha(&pilhaAux, dado);
}
for (i = pilhaAux.topo; i >= 0; i--) { //Tira da pilhaAux e joga na pilha2, mantendo a ordem original da pilha 1
resp = desempilha(&pilhaAux, &dado);
resp = empilha(&pilha2, dado);
}
printf("\n");
printf ("------ CONTEÚDO DA PILHA 2 ------\n");
for (i = 0; i <= pilha2.topo; i++) //Exibe pilha 2
printf ("ELEMENTO %d: %d\n", i + 1, pilha2.v[i]);
return (EXIT_SUCCESS);
}
|
C | #include <stdio.h>
#include <sqlite3.h>
#include <string.h>
#include <stdlib.h>
#include "global.h"
#include "sorting.h"
char ex_value_sorting[6];
int strcmp_flag_sorting=0;
int sorting_mode=0;
char sorting_DESC[]=" ORDER BY price DESC;";
char sorting_ASC[]=" ORDER BY price ASC;";
char str_sorting[100]="SELECT * FROM AccBook";
char str_return[]="SELECT * FROM AccBook";
int cbSelect_sorting(void *data, int ncols, char** values, char** headers)
{
int i=0; //0 = ex date!= current date 1 is equal
printf("\n%s\n\n",(const char*) data);
if (strcmp_flag_sorting!=0&&strcmp(ex_value_sorting,values[0])==0)
{
i=1;
printf("\t\t\t");
}
for(i;i<ncols;i++){
printf("%s=%s\t\t\t", headers[i], values[i]);
if (i==ncols-1)
{
printf("\n"); //last line enter
}
}
strcmp_flag_sorting=1;
strcpy(ex_value_sorting,values[0]);
return 0;
}
void select_order()
{
sorting_mode=0;
printf("Please select sorting mode by 1. Sort the prices in expensive or 2. Sort the prices in cheap \n");
scanf("%d",&sorting_mode);//get sorting mode num 1 DESC 2 ASC
printf("Please input what you want.\n");
system("clear");
switch(sorting_mode)
{
case(1):
{
strcat(str_sorting,sorting_DESC);
break;
}
case(2):
{
strcat(str_sorting,sorting_ASC);
break;
}
default:
{
printf("you have to input number only 1.DESC or 2.ASC !\n ");
select_order();
}
}
}
int sorting()
{
strcmp_flag_sorting=0; //12.8 for modify error
select_order(); //1. DESC ,2. ASC
printf("%s\n",str_sorting);
printf("\n\t\t\t\tA . C . C . B . O . O . K\n");
const char* data= "=====================================================================================";
rc = sqlite3_exec(db, str_sorting, cbSelect_sorting, (void*)data, &zErr);
if (SQLITE_OK != rc){
fprintf(stderr,"rc=%d\n",rc);
fprintf(stderr,"sqlite3_exec error : %s\n",sqlite3_errmsg(db));
return -1;
}
// for(int i=0; i<100; i++)
// {
// str_sorting[i]=0;
// }
strcpy(str_sorting,str_return);
return 0;
}
|
C | /* /cmds/player/emote.c
* from the Nightmare IV LPC Library
* for those times when you are feeling emotional
* created by Descartes of Borg 950412
*/
#include <lib.h>
inherit LIB_DAEMON;
mixed cmd(string args) {
if( !creatorp(this_player()) && !avatarp(this_player()) ) {
if( (int)this_player()->GetStaminaPoints() < 1 )
return "You are too tired.";
}
if( !args || args == "" ) {
message("my_action", "You are feeling emotional.", this_player());
message("other_action", (string)this_player()->GetName() +
" looks emotional.", environment(this_player()),
({ this_player() }));
return 1;
}
if( args[0] != '\'' ) args = " " + args;
message("my_action", "You emote: " + (string)this_player()->GetName() +
args, this_player());
message("other_action", (string)this_player()->GetName() + args,
environment(this_player()), ({ this_player() }) );
return 1;
}
void help() {
message("help", "Syntax: <emote [message]>\n\n"
"Places any message you specify directly after your name. For "
"example, \"emote smiles.\" would have others see "
"\"Descartes smiles.\". Non-avatars lose a stamina point for "
"each emote to discourage abuse.", this_player());
}
|
C | /*
bbsclock.c
*/
#include <time.h>
/* copy time into arg sting in form (HH:MM:SS xM) */
gettime(_ttime)
char *_ttime;
{
long tloc ; char tchar ; int hour ;
struct tm *localtime() , *tadr ;
tloc = time((long *) 0) ; /* get time to tloc */
tadr = localtime (&tloc) ;
tchar = 'A' ; hour = tadr->tm_hour ;
if(hour > 12) { hour -= 12 ; tchar = 'P' ; }
sprintf(_ttime,"%.2d:%.2d:%.2d %cM",hour,tadr->tm_min,
tadr->tm_sec,tchar) ;
}
getdate(_mm,_dd,_yy,_month,_day,_year,_date,_week)
char *_mm, /* 2 digit */
*_dd, /* 2 digit */
*_yy, /* 2 digit */
*_month, /* long */
*_day, /* long */
*_year, /* long */
*_date, /* long month day, year */
*_week; /* day of week */
{
long tvar ;
struct tm *localtime() , *tadr ;
time(&tvar) ; /* get time to tvar */
tadr = localtime (&tvar) ;
switch (tadr->tm_wday)
{
case 0:
strcpy(_week,"Sunday ");
break;
case 1:
strcpy(_week,"Monday ");
break;
case 2:
strcpy(_week,"Tuesday ");
break;
case 3:
strcpy(_week,"Wednesday ");
break;
case 4:
strcpy(_week,"Thursday ");
break;
case 5:
strcpy(_week,"Friday ");
break;
case 6:
strcpy(_week,"Saturday ");
break;
default:
strcpy(_week,"Unknown ");
break;
}
switch (tadr->tm_mon)
{
case 0:
strcpy(_month,"January ");
break;
case 1:
strcpy(_month,"February ");
break;
case 2:
strcpy(_month,"March ");
break;
case 3:
strcpy(_month,"April ");
break;
case 4:
strcpy(_month,"May ");
break;
case 5:
strcpy(_month,"June ");
break;
case 6:
strcpy(_month,"July ");
break;
case 7:
strcpy(_month,"August");
break;
case 8:
strcpy(_month,"September ");
break;
case 9:
strcpy(_month,"October ");
break;
case 10:
strcpy(_month,"November ");
break;
case 11:
strcpy(_month,"December ");
break;
default:
strcpy(_month,"Unknown ");
break;
}
sprintf( _mm, "%.2d",tadr->tm_mon ) ;
sprintf( _dd, "%.2d",tadr->tm_mday) ;
sprintf( _yy, "%.2d",tadr->tm_year) ;
sprintf( _day, "%.2d",tadr->tm_mday) ;
sprintf(_year,"19%.2d",tadr->tm_year) ;
strcpy(_date, ""); /* clear date */
strcat(_date,_month); /* then concat the month,etc. */
strcat(_date, _day);
strcat(_date, ", ");
strcat(_date, _year);
} |
C | /*********************
** Brian Palmer
** CS344
** Project3
** smallsh.c
**********************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
/* Background Process Counter */
int pid_c = 0;
/* Exit Status Var */
char exit_status[256];
/* Source Flag */
int source_flag = 0;
char *source_file = NULL;
/* Target Flag */
int target_flag = 0;
char *target_file = NULL;
/* Foreground Only Flag */
int foreground_only = 0;
/* Foreground Toggle Catcher */
void catchSIGTSTP( int signo ) {
if (foreground_only != 0) {
char * message = "\nExiting foreground-only mode\n";
write(STDOUT_FILENO, message, 31);
foreground_only = 0;
} else {
char *message = "\nEntering foreground-only mode (& is now ignored)\n";
write(STDOUT_FILENO, message, 50);
foreground_only = 1;
}
sleep(5);
}
int main( void ) {
char user_input[ 2048 ];
pid_t pid_list[ 512 ] = { 0 };
char *token;
memset(exit_status, '\0', sizeof(exit_status));
/* holds exit status of subshells or terminating signals */
while( 1 ) {
/* Default Sig Interrupt Setup */
struct sigaction SIGINT_action = { 0 };
SIGINT_action.sa_handler = SIG_IGN;
sigfillset( &SIGINT_action.sa_mask );
SIGINT_action.sa_flags = 0;
sigaction( SIGINT, &SIGINT_action, NULL );
/* Default Sig Stop Setup */
struct sigaction SIGTSTP_action = { 0 };
SIGTSTP_action.sa_handler = catchSIGTSTP;
sigfillset( &SIGTSTP_action.sa_mask );
SIGTSTP_action.sa_flags = 0;
sigaction( SIGTSTP, &SIGTSTP_action, NULL );
char *args[ 512 ] = { NULL };
memset(user_input, '\0', sizeof( user_input ));
printf(": "); fflush(stdout);
fgets(user_input, sizeof(user_input), stdin);
int argi = 0;
if( (token = strtok(user_input, "\n ")) != NULL) {
args[ argi++ ] = token;
while( (token = strtok(NULL, "\n ")) != NULL ) {
if (strcmp(token, "<") == 0) {
source_flag = 1;
source_file = strtok(NULL, "\n ");
}
else if (strcmp(token, ">") == 0) {
target_flag = 1;
target_file = strtok(NULL, "\n ");
}
else {
args[ argi++ ] = token;
}
}
}
char *tword = NULL;
char modWord[ 256 ];
memset(modWord, '\0', sizeof(modWord));
/* Maybe Expand $$ */
int k;
for (k = 0; k < argi; k++) {
if(( tword = strstr(args[ k ], "$$") ) != NULL ) {
char *front = NULL;
front = strtok(args[ k ], "$");
if (front == NULL) {
sprintf(modWord, "%d%s", getpid(), tword + 2);
} else {
sprintf(modWord, "%s%d%s", front, getpid(), tword + 2);
}
args[ k ] = modWord;
}
}
/* No Command was entered; Do nothing */
if ( args[ 0 ] == NULL ) { }
/* A Comment was entered; Do nothing */
else if( user_input[ 0 ] == '#') { }
/* User entered the exit command */
else if( strcmp(args[ 0 ], "exit") == 0) {
if (strcmp( args[ argi - 1], "&") == 0) {
args[ argi - 1 ] = NULL;
}
int i;
for (i = 0; i < pid_c; i++) {
kill(pid_list[i], SIGTERM);
}
exit(0);
}
/* User entered the cd command */
else if( strcmp( args[ 0 ], "cd") == 0) {
if (strcmp( args[ argi - 1], "&") == 0) {
args[ argi - 1 ] = NULL;
}
char directory[ 256 ];
memset(directory, '\0', sizeof(directory));
if ( args[ 1 ] != NULL && args[ 1 ][ 0 ] == '/' ) {
strcat(directory, args[ 1 ]);
chdir(directory);
}
else {
/* Use chdir() in built in command */
strcpy(directory, getenv("HOME"));
if (args[1] != NULL) {
strcat(directory,"/");
strcat(directory, args[ 1 ]);
}
chdir(directory);
}
}
/* User entered the status command */
else if( strcmp( args[ 0 ], "status") == 0) {
/* command goes here */
if (strcmp( args[ argi - 1], "&") == 0) {
args[ argi - 1 ] = NULL;
}
printf("%s\n", exit_status); fflush(stdout);
}
/* Try calling command from PATH */
else {
pid_t spawn_pid = -5;
/* Background Job */
if (strcmp( args[ argi - 1 ], "&") == 0 && ! foreground_only) {
spawn_pid = fork();
if (spawn_pid < 0) {
perror("smallsh: in main()");
exit(1);
}
else if (spawn_pid == 0) {
/* If the source & target files are undefined, set to /dev/null */
if (source_file == NULL) {
source_file = "/dev/null";
}
if (target_file == NULL) {
target_file = "/dev/null";
}
int sourceFd = open(source_file, O_RDONLY);
int targetFd = open(target_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
dup2(targetFd, 1);
dup2(sourceFd, 0);
args[ argi - 1 ] = NULL;
if (execvp(args[0], args ) != 0) {
fprintf(stderr, "%s: no such file or directory\n", args[ 0 ]); fflush(stderr);
exit(1);
}
}
else {
printf("background pid is %d\n", spawn_pid); fflush(stdout);
pid_list[ pid_c++ ] = spawn_pid;
}
}
/* Foreground Job */
else {
/* Child Signal Setup */
struct sigaction SIGINT_action2 = { 0 };
SIGINT_action2.sa_handler = SIG_DFL;
sigfillset(&SIGINT_action2.sa_mask);
SIGINT_action2.sa_flags = 0;
int check_exit_status;
spawn_pid = fork();
if (spawn_pid == -1 ) {
perror("smallsh: in main()");
exit(1);
} else if (spawn_pid == 0) {
/* ^C Sig Action call */
sigaction( SIGINT, &SIGINT_action2, NULL);
int targetFd = -5,
sourceFd = -5;
if (source_flag) {
sourceFd = open( source_file, O_RDONLY );
if (sourceFd < 0) {
fprintf(stderr, "cannot open %s for input\n", source_file); fflush(stderr);
exit(1);
}
else {
dup2( sourceFd, 0 );
}
}
if (target_flag) {
targetFd = open( target_file, O_WRONLY | O_CREAT | O_TRUNC, 0644 );
if (targetFd < 0) {
fprintf(stderr, "cannot open %s for output\n", args[ 0 ]); fflush(stderr);
exit(1);
}
else {
dup2( targetFd, 1 );
}
}
/* If in foreground only mode, then remove the ampersand if it exists */
if ( foreground_only && strcmp( args[ argi - 1 ], "&" ) == 0) {
args[ argi - 1 ] = NULL;
}
if ( execvp( args[ 0 ], args ) < 0) {
fprintf(stderr, "%s: no such file or directory\n", args[ 0 ]); fflush(stderr);
exit(1);
}
}
else {
while( waitpid(spawn_pid, &check_exit_status, 0) < 0 );
if ( check_exit_status != 0 )
sprintf(exit_status, "exit value %d", 1);
else
sprintf(exit_status, "exit value %d", 0);
if (WIFEXITED( check_exit_status) == 0) {
sprintf(exit_status, "terminated by signal %d", WTERMSIG(check_exit_status));
printf("%s\n", exit_status);
}
}
}
}
/* Check for completed background jobs and clean up finished / terminated jobs.
* Up-date status with exit values and signal numbers */
int i;
int check_exit_status = 0;
for (i = 0; i < pid_c; i++ ) {
if( waitpid( pid_list[ i ], &check_exit_status, WNOHANG ) != 0 ) {
if ( WIFEXITED( check_exit_status ) && WTERMSIG( check_exit_status ) == 0) {
if ( WEXITSTATUS(check_exit_status) != 0 ) {
sprintf(exit_status, "exit value %d", 1);
//exit_status = 1;
printf("background pid %d is done: %s\n", pid_list[ i ], exit_status); fflush(stdout);
}
else {
sprintf(exit_status, "exit value %d", 0);
// exit_status = 0;
printf("background pid %d is done: %s\n", pid_list[ i ], exit_status); fflush(stdout);
}
// printf("background pid %d is done: exit value %d\n", pid_list[ i ], exit_status); fflush(stdout);
} else {
sprintf(exit_status, "terminated by signal %d", WTERMSIG(check_exit_status));
printf("background pid %d is done: %s\n", pid_list[ i ], exit_status); fflush(stdout);
}
int j;
for (j = i; j < pid_c - 1; j++)
pid_list[ j ] = pid_list[ j + 1 ];
pid_c--;
}
}
/* Reset file controllers */
source_file = NULL;
target_file = NULL;
source_flag = 0;
target_flag = 0;
}
return 0;
} |
C | #ifndef RANGE_H
#define RANGE_H
float scaleValue(float minIn,float maxIn,
float minOut,float maxOut,
float value) {
float rangeIn = maxIn-minIn;
float rangeOut = maxOut-minOut;
return (rangeOut/rangeIn)*(value-minIn)+minOut;
}
float scaleJoystickValue(float minOut,float maxOut,
float value) {
return scaleValue(-128,127,minOut,maxOut,value);
}
float clamp(float value,float min,float max) {
return value < min ? min :
value > max ? max :
value;
}
#endif
|
C | #include <stdio.h>
int main(void)
{
int num_one, num_two, den_one, den_two;
printf("Enter two fractions separated by a plus sign: ");
scanf("%d/%d+%d/%d", &num_one, &den_one, &num_two, &den_two);
printf("The sum is %d/%d\n", num_one * den_two + num_two * den_one,
den_one * den_two);
return 0;
}
|
C | /***************************************************************************
* Copyright (C) 2005 by Jon Barrett *
* [email protected] *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
/*************************************
*Currency Converter, by Jon Barrett *
* POS370 Programming Concepts *
* University of Phoenix *
*************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{ // This starts the main block of code.
float ConvertToColon=490.050; // conversion to Costa Rican Colon
float ConvertToRiyal=3.75130; // conversion rate of Saudi Riyal
float ConvertToDjibouti=183.790; // conversion rate of Djibouti Franc
float ConvertToYemeni=180.120; // conversion rate of Yemeni Rial
float ConvertToLaoKip=10899.00; // conversion rate of Lao Kip
float US_Dollar=1; // This is a set value of 1 dollar to represent the basic conversion.
/************************************************************
* The following block is the main block, that shows the *
*complete coversion rates from US Dollar to Foreign *
*Currency and vise-a-versa. This program was set up to *
*execute on one word, "currency." *
************************************************************/
printf("\nOne US Dollar to Costa Rican Colon is: \t%.3f\n", US_Dollar*ConvertToColon);
printf("\nOne US Dollar to Djibouti Franc is: \t%.3f\n", US_Dollar*ConvertToDjibouti);
printf("\nOne US Dollar to Saudi Riyal is: \t%.3f\n", US_Dollar*ConvertToRiyal);
printf("\nOne US Dollar to Yemeni Rial is: \t%.3f\n", US_Dollar*ConvertToYemeni);
printf("\nOne US Dollar to Lao Kip is: \t\t%.3f\n\n", US_Dollar*ConvertToLaoKip);
/************************************************************
*I used the "\n" and the "\t" to move the cursor to the *
*next line so it would be more ledgible when executed. *
*It also seperates the block of information and tabs the *
*output, "currency rate," to be more ledgible. *
************************************************************/
return EXIT_SUCCESS;
}
|
C | /*
* Nazim BL
* mikroC PRO for ARM
*/
//STM32f03 , Bluepill 72Mhz, external Quartz + PLLx9
unsigned int k=0,v1=0,v2=0,p1=0,p2=0;
const unsigned int VMAX=315;
unsigned int a=5,b=300,delta=1,diff=0;
long idc=0,vdc=0;
void setup();
void PWM_Setup(unsigned long fo);
void setVref(unsigned int vo);
unsigned long calPower(unsigned int vo);
void main() {
setup();
while(1){
p1=calPower(v1);
p2=calPower(v2);
if(p2>p1) a=v1;
else{
b=v2;
v2=a+0.618*(b-a);
}
diff=(v2-v1);
if(diff<delta)break;
setVref((v1+v2)/2);
}
}
void setup(){
ADC_Set_Input_Channel(_ADC_CHANNEL_0);
ADC_Set_Input_Channel(_ADC_CHANNEL_1);
v1=b-0.618*(b-a);
v2=a+0.618*(b-a);
//2Khz
PWM_Setup(2000);
}
void PWM_Setup(unsigned long fo){
k = PWM_TIM3_Init(fo);
PWM_TIM3_Set_Duty(0, _PWM_NON_INVERTED, _PWM_CHANNEL1);
PWM_TIM3_Start(_PWM_CHANNEL1, &_GPIO_MODULE_TIM3_CH1_PC6);
}
void setVref(unsigned int vo){
//duty cycle = (vo/VMAX)*100;
unsigned int ratio=vo/VMAX;
k=k*ratio;
PWM_TIM3_Set_Duty(k, _PWM_NON_INVERTED, _PWM_CHANNEL1);
PWM_TIM3_Start(_PWM_CHANNEL1, &_GPIO_MODULE_TIM3_CH1_PC6);
}
unsigned long calPower(unsigned int vo){
setVref(vo);
//add more precise condition
while(vdc!=vo){
vdc=ADC1_Get_Sample(0);
idc=ADC1_Get_Sample(1);
//add delay
}
return vdc*idc;
}
|
C | #include <stdio.h>
#include <string.h>
#include <malloc.h>
typedef int elemType;
typedef struct b_node{
elemType data;
struct b_node *lchild,*rchild;
}b_node,*b_tree;
//按数组顺序创建二叉树
void createTree(b_tree *T,elemType a[],int len,int index){ //修改一个指针 要用二级指针
if(index >= len)
return;
*T = (b_node *)malloc(sizeof(b_node));
if(a[index] == -1)
*T = NULL;
else{
(*T)->data = a[index];
(*T)->lchild = NULL;
(*T)->rchild = NULL;
createTree(&((*T)->lchild),a,len,2 * index); //从数组a[0]开始为 2*index+1
createTree(&((*T)->rchild),a,len,2 * index + 1); //2*index+2
}
}
//先序递归遍历二叉树
void preOrder(b_tree T){
if(T != NULL){
printf("%d ",T->data);
preOrder(T->lchild);
preOrder(T->rchild);
}
}
int main()
{
elemType a[] = {-999,1,2,3,4,5,6,7,8,9,10,11,12};
b_tree T = NULL;
int len = sizeof(a)/sizeof(elemType);
createTree(&T,a,len,1);
preOrder(T);
return 0;
}
|
C | #include<stdio.h>
#include<errno.h>
#include<fcntl.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/mman.h>
/**
* 存储映射I/O能将一个磁盘文件映射到内存空间的一个缓冲区上,
* 当从缓冲区中读取数据时,就相当于读文件中的相应字节
* 将数据存入缓冲区中时,相应字节就自动写入文件
*
* #include<sys/mman.h>
* void *mmap(void *addr, size_t len, int prot, int flag, int fd, off_t off);
* addr: 缓冲区的地址
* len: 要映射文件的长度
* prot: 缓冲区的打开方式(读/写/可执行)
* flag: 影响缓冲区的多种属性
* fd: 打开的文件描述符
* off: 偏移量
* 修改缓冲区的权限:
* int mprotect(void *addr, size_t len, int prot);
*
* 如果映射的页已修改,将该页冲洗到被映射的文件中
* int msync(void *addr, size_t len, int flags);
*
* 解除映射
* int munmap(void *addr, size_t len);
*/
#define COPYINCR (1024*1024*1024)
int main(int argc, char const *argv[])
{
int fdin, fdout;
void *src, *dst;
off_t fsz = 0;
size_t copysz;
struct stat sbuf;
if((fdin = open(argv[1], O_RDONLY)) < 0)
{
perror("can't open file for reading");
exit(12);
}
if((fdout = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IXUSR | S_IRGRP | S_IROTH)) < 0)
{
perror("can't creat file for writing");
exit(13);
}
/*获取输入文件的信息*/
if(fstat(fdin, &sbuf) < 0)
{
perror("fstat error");
exit(14);
}
/*指定输出文件的大小*/
if(ftruncate(fdout, sbuf.st_size) < 0)
{
perror("ftruncate error");
exit(15);
}
/*只要偏移量小于文件的大小*/
while(fsz < sbuf.st_size)
{
if((sbuf.st_size - fsz) > COPYINCR)
copysz = COPYINCR;
else
copysz = sbuf.st_size - fsz;
/*将输入文件映射到内存上*/
if( (src = mmap(0, copysz, PROT_READ, MAP_SHARED, fdin, fsz)) == MAP_FAILED)
{
perror("mmap error for input");
exit(16);
}
/*将输出文件映射到内存上*/
if( (dst = mmap(0, copysz, PROT_READ | PROT_WRITE, MAP_SHARED, fdout, fsz)) == MAP_FAILED)
{
perror("mmap error for output");
exit(17);
}
/**
* 将输入文件映射到内存的缓冲区上时,读取缓冲区就相当于读取文件
* 将输出文件映射到内存的缓冲区上时,写入缓冲区就相当于写入文件
*/
memcpy(dst, src, copysz);
/*解除映射*/
munmap(src, copysz);
munmap(dst, copysz);
fsz += copysz;
}
return 0;
}
|
C | #include <stdlib.h>
#include <stdio.h>
char *ft_itoa(int nbr)
{
char *string;
int sign;
int temp_nbr;
int size;
printf("\ntrying to convert %d\n", nbr);
sign = (nbr < 0) ? -1 : 1;
size = (sign < 0) ? 2 : 1;
temp_nbr = nbr;
while (temp_nbr /= 10)
size++;
if (!(string = (char*)malloc(sizeof(char)*(size + 1))))
return (NULL);
string[size] = '\0';
while (size >= 0)
{
string[--size] = ((nbr % 10) * sign) + 48;
nbr /= 10;
}
string[0] = (sign == -1) ? '-' : string[0];
return (string);
}
|
C | #include "../utility.h"
/**
* 函数名:newdonroot
* 功能描述:求出[a,b]区间内的非线性方程f(x)的一个实根
* 输入参数:x0(迭代初值以 * 返回值及迭代终值的初值指针)
* f(非线性方程左端函数)
* fd(非线性方程左端函数的导函数)
* eps(精度要求),max(最大迭代次数)
* 返回值:0(迭代失败)1(迭代成功)
*/
int newdonroot(double *x0,double(*f)(),double(*fd)(),double eps,int max)
{
double x,dis;
double y0;
double yd0;
int num=0;
do
{
y0=f(*x0);
yd0=fd(*x0); /* 计算函数值以及导数值*/
x=*x0-y0/yd0; /* 计算新的x值*/
num++;
dis=fabs(x-*x0); /* 计算精度*/
if(dis<fabs(y0))
{
dis=fabs(y0);
}
printf("%1.7f %1.7f %1.7f\n",*x0,x,dis);
*x0=x;
}
while(dis>eps&&num<max); /* 判断迭代是否结束*/
if(num==max)
{
return (0); /* 迭代失败*/
}
else
{
return (1); /* 迭代成功*/
}
}
|
C | // Metodo Selection Sort:
// Este es un algoritmo que permite ordenar un array de manera especial.
// Como toda estructura, tiene sus ventajas y desventajas, es un algoritmo que es facil de implementar,
// no requiere memoria adicional y tiene un funcionamiento de intercambio constante, por otra parte
// puede llegar a ser lento y poco eficiente si se tienen que analizar listas de numeros muy grandes
// ya que realiza numerosas comparaciones.
// Existen varios tipos, en este caso lo que hace este metodo es seleccionar al menor elemento del array e
// intercambiarlo a la primer posicion y asi sucesivamente con los demas elementos (en caso de que querramos
// ordenar el array de manera ascendente).
// Supongamos que tenemos un array de 5 elementos;
// En la posicion 0 tenemos el elemento (15), en la posicion 1 el elemento (7), en la posicion 2 el elemento (6);
// en la posicion 3 el elemento (16) y en la posicion 4 el elemento (2);
// Mediante for anidados, pregunta cual de todos los elementos del array es el mas pequeño,
// empezando desde el primer elemento, en este caso va a preguntar si hay algun elemento
// de nuestro array que sea menor a 15(primer elemento en posicion 0), ahora vemos que 7(segundo elemento en posicion 1)
// es menor, ahi se produce un cambio(cambian de posicion dejando al 7 en posicion 0)
// luego sigue preguntando, si 7 es menor a algun otro elemento,
// vemos que si, ya que (el valor del elemento de la posicion 2, es 6), se produce otro cambio, ahora sigue preguntando,
// llega hasta el ultimo elemento del array el cual es un 2(posicion 4) y ahi se produce el ultimo cambio, dejando asi
// el elemento mas pequeño en primera posicion.(Todos los cambios siempre son entre un elemento cualquiera
// y el que se encuentre en ese momento en posicion 0)
// esto pasa en la primer iteracion de nuestro bucle for, luego se va ordenando en cada iteracion usando el mismo mecanismo.
#include <stdio.h>
void selec_sort(int *vec) // paso el array por referencia para pasarlo al main.
{
int i,j,aux,menor; // declaro i y j para los ciclos for, menor para la posicion del menor elemento y
// aux para guardar el valor de la posicion a cambiar y que no se pierda
for (i = 0; i < 5; i++)
{
menor = i; // empieza el for e inicio menor en i, osea i = 0;
for (j = i + 1; j < 5; j++)
{
if (vec[j] < vec[i]) // compara el elemento de la posicion 1 con el de la posicion 0, y asi con las demas posiciones
{
menor = j; // cuando recorra las 5 posiciones del array, menor toma el valor del indice con el elemento mas chico
}
}
aux = vec[i]; // le asignamos a un auxilar el valor de i, osea el de la primer posicion en esta primer ronda
vec[i] = vec[menor]; // el valor de i, toma el valor de menor, osea el valor del elemento mas pequeño(dejando asi el elemento mas pequeño en primera posicion)
vec[menor] = aux; // ahora el valor pisado de i,el que estaba antes, recupera su valor ya que lo guardamos en una auxiliar.
}
}
void print_array(int *vec) // funcion para immprimir el array
{
for (int i = 0; i < 5; i++)
{
printf("%d\t", vec[i]);
}
}
int main()
{
int array[5] = {15, 7, 6, 16, 2}; // declaro el array con sus elementos
printf("Vector desordenado:\n");
print_array(&array);
printf("\n");
printf("Vector ordenado:\n");
selec_sort(&array); //llamo a la funcion
print_array(&array); //llamo a la funcion
}
|
C | #include "tile.h"
void initTile(Tile* t)
{
t->posX=0;
t->posY=0;
t->collision=0;
}
int getPosX(Tile t)
{
return t.posX;
}
int getPosY(Tile t)
{
return t.posY;
}
char getCollision(Tile t)
{
return t.collision;
}
void setPosX(Tile* t, int x)
{
t->posX=x;
}
void setPosY(Tile* t, int y)
{
t->posY=y;
}
void setCollision(Tile* t, char collision)
{
t->collision=collision;
}
|
C | /****************************************************************************************
* File name: Table.h
* Compiler Visual Studio 2019
* Author: Jonathan Slaunwhite , 040939090
* Course:CST 8152 Compilers, Lab Section:013
* Assignment 2
* Date: 2020-03-22
* Professor: Sv.Ranev
* Purpose: This is the table.h where all definitions are stored
* Version: 1.20.1
* Function list: st_table,as_table,Token
* aa_func02,aa_func03,aa_func05,aa_func08,aa_func10,aa_func12,
*
****************************************************************************************/
#ifndef TABLE_H_
#define TABLE_H_
#ifndef BUFFER_H_
#include "buffer.h"
#endif
#ifndef NULL
#include <_null.h> /* NULL pointer constant is defined there */
#endif
/* Source end-of-file (SEOF) sentinel symbol
* '\0' or one of 255,0xFF,EOF
*/
#define SEOF '\0' //SEOF source end of file
#define S_EOF (unsigned char)255 //unsigned source end of file 255
#define NL '\n' //new line
#define TB '\t' //tab
#define SEOFNEW 0xFF// i added this maybe is right ?? 123123123
#define quote '"'
//PLACE YOUR CONSTANT DEFINITIONS HERE IF YOU NEED ANY
//REPLACE *ESN* and *ESR* WITH YOUR ERROR STATE NUMBER
#define ES 11 /* Error state with no retract */
#define ER 12 /* Error state with retract */
#define IS -1 /* Inavalid state */
/* State transition table definition */
//REPLACE *CN* WITH YOUR COLUMN NUMBER
#define TABLE_COLUMNS 8//six rows in table st_table
/*transition table - type of states defined in separate table */
int st_table[][TABLE_COLUMNS] = {
//1467
/* State 0 */ {1,6,4,ES,ES,ES,9,ER},
/* State 1 */ {1,1,1,2,3,2,ES,ER},
/* State 2 */ {IS,IS,IS,IS,IS,IS,IS,IS},
/* State 3 */ {IS,IS,IS,IS,IS,IS,IS,IS},
/* State 4 */ {ES,4,4,7,5,5,IS,IS},
/* State 5 */ {IS,IS,IS,IS,IS,IS,IS,IS},
/* State 6 */ {ES,6,ES,7,ES,5,ES,ER},
/* State 7 */ {8,7,7,8,8,8,ES,ER},
/* State 8 */ {IS,IS,IS,IS,IS,IS,IS,IS},
/* State 9 */ {9,9,9,9,9,9,10,ES},
/* State 10 */ {IS,IS,IS,IS,IS,IS,IS,IS},
/* State 11 */ {IS,IS,IS,IS,IS,IS,IS,IS},
/* State 12 */ {IS,IS,IS,IS,IS,IS,IS,IS},
};
//.
//.YOUR TABLE INITIALIZATION HERE
//.
/* State N */ // {YOUR INITIALIZATION},
/* Accepting state table definition */
//REPLACE* N1*, * N2*, and* N3* WITH YOUR NUMBERS
#define ASWR 2 /* accepting state with retract */
#define ASNR 3 /* accepting state with no retract */
#define NOAS 0 /* not accepting state */
//int as_table[ ] = {YOUR INITIALIZATION HERE - USE ASWR, ASNR, NOAS };
int as_table[] = {
/*State 0*/ NOAS,
/*State 1*/ NOAS,
/*State 2*/ ASWR,
/*State 3*/ ASNR,
/*State 4*/ NOAS,
/*State 5*/ ASWR,
/*State 6*/ NOAS,
/*State 7*/ NOAS,
/*State 8*/ ASWR,
/*State 9*/ NOAS,
/*State 10*/ ASNR,
/*State 11*/ ASNR,
/*State 12*/ ASWR,
};
/* Accepting action function declarations */
/*
FOR EACH OF YOUR ACCEPTING STATES YOU MUST PROVIDE
ONE FUNCTION PROTOTYPE. THEY ALL RETURN Token AND TAKE
ONE ARGUMENT: A string REPRESENTING A TOKEN LEXEME.
*/
// Token aa_funcXX(char *lexeme);
Token aa_func02(char* lexeme);
Token aa_func03(char* lexeme);
Token aa_func05(char* lexeme);
Token aa_func08(char* lexeme);
Token aa_func10(char* lexeme);
Token aa_func11(char* lexeme);
Token aa_func12(char* lexeme);
//Replace XX with the number of the accepting state: 02, 03 and so on.
/* defining a new type: pointer to function (of one char * argument)
returning Token
*/
typedef Token(*PTR_AAF)(char* lexeme);
/* Accepting function (action) callback table (array) definition */
/* If you do not want to use the typedef, the equvalent declaration is:
* Token (*aa_table[])(char lexeme[]) = {
*/
PTR_AAF aa_table[] = {
/*
HERE YOU MUST PROVIDE AN INITIALIZATION FOR AN ARRAY OF POINTERS
TO ACCEPTING FUNCTIONS. THE ARRAY HAS THE SAME SIZE AS as_table[ ].
YOU MUST INITIALIZE THE ARRAY ELEMENTS WITH THE CORRESPONDING
ACCEPTING FUNCTIONS (FOR THE STATES MARKED AS ACCEPTING IN as_table[]).
THE REST OF THE ELEMENTS MUST BE SET TO NULL.
*/
/*State 0*/ NULL,
/*State 1*/ NULL,
/*State 2*/ aa_func02,
/*State 3*/ aa_func03,
/*State 4*/ NULL,
/*State 5*/ aa_func05,
/*State 6*/ NULL,
/*State 7*/ NULL,
/*State 8*/ aa_func08,
/*State 9*/ NULL,
/*State 10*/ aa_func10,
/*State 11*/ aa_func11,
/*State 12*/ aa_func12,
};
/* Keyword lookup table (.AND. and .OR. are not keywords) */
#define KWT_SIZE 10
char* kw_table[] =
{
"ELSE",
"FALSE",
"IF",
"PLATYPUS",
"READ",
"REPEAT",
"THEN",
"TRUE",
"WHILE",
"WRITE"
};
#endif
|
C | #include "msg.h"
static int CHUNK_SIZE;
static int mqid;
static char dir_name[10];
void get_file_name(int chunk_id, char * buffer) {
strcpy(buffer, dir_name);
buffer += strlen(buffer);
strcpy(buffer, "/chunk");
sprintf(buffer+6, "%d", chunk_id);
buffer += strlen(buffer);
strcpy(buffer, ".txt");
}
int store_chunk (msg message);
int copy_chunk (msg message);
int remove_chunk (msg message);
int command (msg message);
int status_update (msg message);
int ls_data (msg message);
void d_server() {
pid_t pid = getpid();
printf("D server at %d\n", pid);
char cwd[200];
getcwd(cwd, sizeof(cwd));
key_t key = ftok(cwd, 42);
mqid = msgget(key, S_IWUSR | S_IRUSR);
if(mqid == -1) {
perror("Msq not obtained");
return;
}
msg recv_buf;
msg send_buf;
send_buf.mbody.sender = getpid();
send_buf.mtype = 1;
send_buf.mbody.req = NOTIFY_EXISTENCE;
msgsnd(mqid, &send_buf, MSGSIZE, 0);
dir_name[0] = 'D';
sprintf(dir_name, "%d", pid);
mkdir(dir_name, 0777);
for(;;) {
ssize_t msgsize = msgrcv(mqid, &recv_buf, MSGSIZE, pid, 0);
if(msgsize == -1) {
perror("Recv ");
raise(SIGINT);
exit(1);
}
int status = 0;
if(recv_buf.mbody.req == STORE_CHUNK) status = store_chunk(recv_buf);
if(recv_buf.mbody.req == COPY_CHUNK) status = copy_chunk(recv_buf);
if(recv_buf.mbody.req == REMOVE_CHUNK) status = remove_chunk(recv_buf);
if(recv_buf.mbody.req == COMMAND) status = command(recv_buf);
if(recv_buf.mbody.req == STATUS_UPDATE) status = status_update(recv_buf);
if(recv_buf.mbody.req == LS_DATA) status = ls_data(recv_buf);
}
}
int main(int argc, char ** argv) {
if(argc < 2) {
printf("Usage - ./exec <CHUNK_SIZE>\nCHUNK_SIZE must be less than %d (bytes)\n", MSGSIZE/2);
return -1;
}
CHUNK_SIZE = atoi(argv[1]);
if(CHUNK_SIZE > 512) {
printf("Usage - ./exec <CHUNK_SIZE>\nCHUNK_SIZE must be less than %d (bytes)\n", MSGSIZE/2);
return -1;
}
d_server();
return 0;
}
int store_chunk (msg message) {
printf("\nStarting store chunk\n");
int chunk_id = message.mbody.chunk.chunk_id;
msg send;
send.mtype = message.mbody.sender;
send.mbody.sender = getpid();
send.mbody.req = STATUS_UPDATE;
char buffer[100];
get_file_name(chunk_id, buffer);
int fd = open(buffer, O_CREAT|O_EXCL|O_RDWR, 0777);
if(fd == -1) {
printf("Store chunk error - Chunk %d already present\n", chunk_id);
send.mbody.status = -1;
strcpy(send.mbody.error, "Store error - Chunk already present\n");
msgsnd(mqid, &send, MSGSIZE, 0);
return -1;
}
write(fd, message.mbody.chunk.data, CHUNK_SIZE);
close(fd);
printf("Stored chunk %d\n", chunk_id);
strcpy(send.mbody.error, "Store Success");
send.mbody.status = 0;
msgsnd(mqid, &send, MSGSIZE, 0);
return 0;
}
int copy_chunk (msg message) {
int chunk_id = message.mbody.chunk.chunk_id;
int new_chunk_id = message.mbody.status;
pid_t new_server = message.mbody.addresses[0];
printf("\nStarting copy chunk %d to %d\n", chunk_id, new_chunk_id);
msg update;
update.mtype = 1;
update.mbody.sender = getpid();
update.mbody.req = STATUS_UPDATE;
char buffer[100];
get_file_name(chunk_id, buffer);
int fd = open(buffer, O_RDONLY, 0777);
if(fd == -1) {
printf("Not found\n");
update.mbody.status = -1;
strcpy(update.mbody.error, "Copy error - Not found");
msgsnd(mqid, &update, MSGSIZE, 0);
return -1;
}
msg send;
send.mtype = new_server;
send.mbody.sender = getpid();
send.mbody.req = STORE_CHUNK;
send.mbody.chunk.chunk_id = new_chunk_id;
int num_read;
num_read = read(fd,send.mbody.chunk.data,CHUNK_SIZE);
close(fd);
send.mbody.chunk.data[num_read] = '\0';
msgsnd(mqid, &send, MSGSIZE, 0);
printf("Copy complete\n");
update.mbody.status = 0;
strcpy(update.mbody.error, "Copy chunk success");
msgsnd(mqid, &update, MSGSIZE, 0);
return 0;
}
int remove_chunk (msg message) {
printf("\nStarting remove chunk\n");
int chunk_id = message.mbody.chunk.chunk_id;
char buffer[100];
get_file_name(chunk_id, buffer);
int fd = open(buffer, O_RDONLY, 0777);
if(fd == -1) {
printf("Chunk not present\n");
return -1;
}
close(fd);
remove(buffer);
printf("Successfully removed %d\n", chunk_id);
return 0;
}
int ls_data (msg message) {
msg send_buf;
send_buf.mtype = message.mbody.sender;
send_buf.mbody.sender = getpid();
int arr[2];
pipe(arr);
int pid = getpid();
if(fork()){// parent
close(arr[1]); // close write end
send_buf.mbody.req = OUTPUT;
int n = read(arr[0],send_buf.mbody.chunk.data,MSGSIZE/2);
send_buf.mbody.chunk.data[n] = '\0';
close(arr[0]);
printf("read %d bytes %s\n",n,send_buf.mbody.chunk.data);
msgsnd(mqid,&send_buf,MSGSIZE,0);
return 0;
}
dup2(arr[1],1); //duplicate write end for child
close(arr[0]); //close the read end for child
char dirname[100];
char tmp[100];
sprintf(tmp,"%d",pid);
strcpy(dirname,tmp);
execlp("ls","ls",dirname,NULL);
printf("SHOULDNT BE HERE\n");
}
int status_update (msg message) {
printf("\nReceived update from %d - %s\n", message.mbody.sender, message.mbody.error);
return 0;
}
int command (msg message) {
msg send_buf;
send_buf.mtype = message.mbody.sender;
send_buf.mbody.sender = getpid();
char fname[100];
strcpy(fname,dir_name);
strcat(fname,"/chunk");
strcat(fname,message.mbody.paths[0]);
strcat(fname,".txt");
printf("Attempting to open %s\n",fname);
int fd;
if((fd = open(fname,O_RDONLY)) == -1){
send_buf.mbody.status=-1;
strcpy(send_buf.mbody.error,"COULDN'T OPEN FILE INSIDE D SERVER\n");
msgsnd(mqid,&send_buf,MSGSIZE,0);
printf("COULDN'T OPEN FILE %s\n",fname);
return -1;
}
char actual_cmd[100];
strcpy(actual_cmd,message.mbody.chunk.data);
char* token = strtok(actual_cmd," ");
char cmd[100];
strcpy(cmd, token);
char* args[20];
int m=1;
args[0]=cmd;
while(token!=NULL){
token=strtok(NULL," ");
args[m++] = token;
//printf("args[%d] is %s\n",m-1,token);
}
args[m-3] = NULL;// to remove the extra stuff like d pid and chunk id
int arr[2];
// printf("LISTING ALL ARGS TO CMD: %s\n",cmd);
// for(int i=0;args[i];i++)
// printf("%s\n",args[i]);
pipe(arr);
printf("About to execute %s on %s\n",cmd,fname);
if(fork()){// parent
close(arr[1]); // close write end
send_buf.mbody.req = OUTPUT;
int n = read(arr[0],send_buf.mbody.chunk.data,MSGSIZE/2);
send_buf.mbody.chunk.data[n] = '\0';
msgsnd(mqid,&send_buf,MSGSIZE,0);
return 0;
}
dup2(arr[1],1); //duplicate write end for child
close(arr[0]); //close the read end for child
dup2(fd,0);
execvp(cmd,args);
}
|
C | #ifndef LINEARHASH_H_
#define LINEARHASH_H_
#define EMPTY -1 /* ִ */
#define DELETE -2 /* */
typedef enum { FALSE, TRUE } bool_t;
typedef struct _linear_hash {
int *hash; /* int ؽ̺ */
int size; /* hash table ũ */
} hash_t;
bool_t createHash(hash_t *hsp, int size); /* ؽ ʱȭ Լ */
int hashFunction(hash_t *hsp, int key); /* ؽð Լ */
bool_t hashInput(hash_t *hsp, int insertData); /* ؽÿ */
int hashSearch(hash_t *hsp, int searchData); /* ؽÿ ã */
bool_t hashDelete(hash_t *hsp, int deleteData); /* ؽÿ */
void destroyHash(hash_t *hsp); /* ؽ Ҹ Լ */
void hashPrint(hash_t *hsp); /* Ʈ Լ-ؽ ̺ */
#endif /* LINEARHASH_H_ */
|
C | /*12.Write C code to count and print all numbers from LOW to HIGH by steps of
STEP. Test with LOW=0 and HIGH=100 and STEP=5.*/
#include <stdio.h>
int main(){
int i;
int low, high, step;
printf("enter value of low and high ");
scanf("%d%d", &low, &high);
printf("enter the step");
scanf("%d", &step);
while(low<high){
if(low%step==0){
i++;
}
low++;
}
printf(" %d: %d times ", step, i);
}
|
C | #include "arr_util.h"
#include <assert.h>
void test_create(){
int size =sizeof(int);
int length =10;
ArrayUtil arr = create(size,length);
assert(arr.length==length);
assert(arr.typeSize==size);
dispose(arr);
};
void test_resize(){
int size =4;
int length =10;
int newlength =20;
ArrayUtil arr = create(size,length);
arr = resize(arr,newlength);
assert(arr.length==newlength);
dispose(arr);
};
void test_areEqual(){
ArrayUtil a = create(4,10);
ArrayUtil b = create(4,10);
assert(areEqual(a,b));
ArrayUtil arr = create(4,10);
*((int*)arr.base+0) = 78;
*((int*)arr.base+1) = 79;
ArrayUtil arr1 = create(4,10);
*((int*)arr1.base+0) = 78;
*((int*)arr1.base+1) = 79;
assert(areEqual(arr,arr1));
dispose(arr);
dispose(arr1);
dispose(a);
dispose(b);
}
void test_findIndex(){
ArrayUtil arr = create(4,10);
*((int*)arr.base+0) = 78;
*((int*)arr.base+1) = 79;
*((int*)arr.base+2) = 90;
*((int*)arr.base+3) = 92;
int var = 92;
assert(findIndex(arr,&var)==3);
ArrayUtil darr = create(8,10);
*((double*)darr.base+0) = 78;
*((double*)darr.base+1) = 79;
double dvar = 78;
assert(findIndex(darr,&dvar)==0);
dispose(arr);
dispose(darr);
}
void test_areEqual_not(){
ArrayUtil a = create(4,10);
ArrayUtil b = create(8,10);
assert(!areEqual(a,b));
ArrayUtil arr = create(8,10);
*((double*)arr.base+0) = 78;
*((double*)arr.base+1) = 79;
ArrayUtil arr1 = create(8,10);
*((double*)arr1.base+0) = 78;
*((double*)arr1.base+1) = 79;
*((double*)arr1.base+2) = 80;
assert(!areEqual(arr,arr1));
dispose(arr);
dispose(arr1);
dispose(a);
dispose(b);
};
void test_findFirst_isEven(){
ArrayUtil util = create(4,10);
*((int*)util.base+0) = 79;
*((int*)util.base+1) = 80;
int actual = *((int*)(findFirst(util,isEven,NULL)));
int expected = 80;
assert(actual==expected);
}
void test_findFirst_isEven_not_found(){
ArrayUtil util = create(4,10);
*((int*)util.base+0) = 79;
*((int*)util.base+1) = 89;
void *val = findFirst(util,isEven,NULL);
void *expect = NULL;
assert(expect==val);
}
void test_findFirst_isDivisible(){
ArrayUtil util = create(4,10);
*((int*)util.base+0) = 79;
*((int*)util.base+1) = 84;
int divisor = 4;
void *hint = &divisor;
int actual = *((int*)(findFirst(util,isDivisible, hint)));
int expected = 84;
assert(actual==expected);
}
void test_findLast_isDivisible(){
ArrayUtil util = create(4,10);
*((int*)util.base+0) = 79;
*((int*)util.base+1) = 84;
*((int*)util.base+2) = 69;
*((int*)util.base+3) = 44;
*((int*)util.base+4) = 64;
int divisor = 4;
void *hint = &divisor;
int actual = *((int*)(findLast(util,isDivisible, hint)));
int expected = 64;
assert(actual==expected);
}
void test_count_isEven(){
ArrayUtil util = create(4,10);
*((int*)util.base+0) = 79;
*((int*)util.base+1) = 84;
*((int*)util.base+2) = 34;
*((int*)util.base+3) = 89;
int actual = count(util,isEven,NULL);
int expected = 2;
assert(actual==expected);
}
void test_count_isDivisible(){
ArrayUtil util = create(4,10);
*((int*)util.base+0) = 9;
*((int*)util.base+1) = 18;
*((int*)util.base+2) = 27;
*((int*)util.base+3) = 89;
int divisor = 9;
void *hint = &divisor;
int actual = count(util,isDivisible,hint);
int expected = 3;
assert(actual==expected);
};
void test_filter_isDivisible(){
int val = 65;
ArrayUtil util = create(sizeof(int),10);
int *base = (int *)util.base;
for (int i = 0; i < util.length; ++i,val++)
base[i] = val;
int maxItems = 8;
ArrayUtil destination = create(sizeof(int),maxItems);
int divisor = 2;
void *hint = &divisor;
int count = filter(util,isDivisible,hint,&(destination.base),maxItems);
assert(5 == count);
val = 66;
for (int i = 0; i < 3; ++i,val=val+2){
assert(val == *((int*)destination.base+i));
}
};
void test_filter_isSame(){
int val = 65;
ArrayUtil util = create(sizeof(char),10);
char *base = (char *)util.base;
for (int i = 0; i < util.length; ++i,val++)
base[i] = val;
int maxItems = 5;
ArrayUtil destination = create(sizeof(int),maxItems);
int search = 66;
void *hint = &search;
int count = filter(util,isSame,hint,&(destination.base),maxItems);
assert(1 == count);
assert(66 == *((char*)destination.base+0));
assert(destination.length==maxItems);
};
void test_map_mapper(){
ArrayUtil source = create(sizeof(int),10);
ArrayUtil destination = create(sizeof(int),10);
int val =65;
int *base = (int *)source.base;
for (int i = 0; i < source.length; ++i,val++)
base[i] = val;
int no = 2;
int *hint = &no;
map(source,destination,mapper,hint);
val = 67;
for (int i = 0; i < 3; ++i,val++){
assert(val== *((int*)destination.base+i));
}
};
void test_forEach_operation(){
ArrayUtil array = create(sizeof(int),10);
int val =5;
int *base = (int *)array.base;
for (int i = 0; i < array.length; ++i,val++)
base[i] = val;
int no = 2;
int *hint = &no;
forEach(array,multiply,hint);
assert(10== *((int*)array.base+0));
assert(12== *((int*)array.base+1));
assert(14== *((int*)array.base+2));
};
void test_reduce_sum(){
ArrayUtil array = create(sizeof(int),10);
int val =5;
int *base = (int *)array.base;
for (int i = 0; i < array.length; ++i,val++)
base[i] = val;
int iniail_val = 0;
void *red = reduce(array,sum,NULL,&iniail_val);
assert(*((int *)red) == 95);
}
|
C | #include <GL/glut.h>
#include "game.h"
#include "init.h"
const int width = 800;
const int height = 600;
int mouse_x;
int mouse_y;
int getMouseX() { return mouse_x; }
int getMouseY() { return mouse_y; }
void loop()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
draw();
glutSwapBuffers();
update();
}
void mouse_move_inverse_y(int x, int y)
{
mouse_x = x;
mouse_y = height - y;
mouse_move();
}
void key_press_aux(unsigned char key, int x, int y)
{
key_press(key);
}
void mouse_click_aux(int button, int state, int x, int y)
{
if(state == GLUT_DOWN)
{
if(button == GLUT_LEFT_BUTTON)
mouse_left_click();
else
mouse_right_click();
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitWindowSize(width, height);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutCreateWindow("simple game");
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glEnable(GL_DEPTH_TEST);
glOrtho(0.0f, width, 0.0f, height, -1.0f, 1.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// antialiasing
glEnable (GL_LINE_SMOOTH);
glEnable (GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glHint (GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
glHint (GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
glHint (GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
glutIdleFunc(loop);
glutKeyboardFunc(key_press_aux);
glutMouseFunc(mouse_click_aux);
glutPassiveMotionFunc(mouse_move_inverse_y);
init();
//glutSetCursor(GLUT_CURSOR_NONE);
mouse_x = mouse_y = 0;
glutMainLoop();
return 0;
}
|
C | #include <math.h>
#include <float.h>
#include <stdio.h>
#ifndef JSI_AMALGAMATION
#include "jsiInt.h"
#endif
bool Jsi_NumberIsSubnormal(Jsi_Number a) { return fpclassify(a) == FP_SUBNORMAL; }
bool Jsi_NumberIsNormal(Jsi_Number a) { return (fpclassify(a) == FP_ZERO || isnormal(a)); }
bool Jsi_NumberIsNaN(Jsi_Number n)
{
return isnan(n);
}
int Jsi_NumberIsInfinity(Jsi_Number a) {
#if JSI__MUSL==1 || defined(__FreeBSD__) || defined(__WIN32)
if (!isinf(a))
return 0;
return (a<0 ? -1 : 1);
#else
return isinf(a);
#endif
}
bool Jsi_NumberIsInteger(Jsi_Number n) { return (isnormal(n) ? (Jsi_Number)((int)(n)) == (n) : n==0.0); }
bool Jsi_NumberIsWide(Jsi_Number n) { return (isnormal(n) && (Jsi_Number)((Jsi_Wide)(n)) == (n)); }
Jsi_Number Jsi_NumberInfinity(int i)
{
Jsi_Number r = INFINITY;
if (i < 0) r = -r;
return r;
}
Jsi_Number Jsi_NumberNaN(void)
{
return NAN;
}
void Jsi_NumberItoA10(int value, char* buf, int bsiz)
{
snprintf(buf, bsiz, "%d", value);
return;
}
void Jsi_NumberUtoA10(unsigned int value, char* buf, int bsiz)
{
snprintf(buf, bsiz, "%u", value);
}
bool Jsi_NumberIsFinite(Jsi_Number value)
{
Jsi_Number r = INFINITY;
return (Jsi_NumberIsNaN(value)==0 && value != r && r != -value);
}
void Jsi_NumberDtoA(Jsi_Number value, char* buf, int bsiz, int prec)
{
if (Jsi_NumberIsNaN(value)) {
Jsi_Strcpy(buf,"NaN");
return;
}
snprintf(buf, bsiz, "%.*" JSI_NUMGFMT, prec, value);
}
bool Jsi_NumberIsEqual(Jsi_Number n1, Jsi_Number n2)
{
return (n1 == n2); // TODO: Do we need more?
/* int n1n = jsi_num_isNan(n1);
int n2n = jsi_num_isNan(n2);
if (n1n && n2n)
return 1;
if (n1n || n2n)
return 0;
return ((n2-n1)==0);*/
}
#ifndef JSI_LITE_ONLY
static Jsi_RC NumberConstructor(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
if (Jsi_FunctionIsConstructor(funcPtr)) {
Jsi_Number nv = 0.0;
Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0);
if (v) {
Jsi_ValueToNumber(interp, v);
nv = v->d.num;
}
_this->d.obj->ot = JSI_OT_NUMBER;
_this->d.obj->d.num = nv;
Jsi_ValueToObject(interp, _this);
Jsi_ValueMakeNumber(interp, ret, nv);
return JSI_OK;
}
Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0);
if (v) {
Jsi_ValueToNumber(interp, v);
Jsi_ValueDup2(interp, ret, v);
Jsi_ValueToObject(interp, *ret);
return JSI_OK;
}
Jsi_ValueMakeNumber(interp, ret, 0.0);
return JSI_OK;
}
#define ChkStringN(_this, funcPtr, dest) \
if (_this->vt == JSI_VT_OBJECT && _this->d.obj->ot == JSI_OT_FUNCTION && \
_this->d.obj->__proto__ == interp->Number_prototype->d.obj->__proto__ ) { \
skip = 1; \
dest = Jsi_ValueArrayIndex(interp, args, 0); \
} else if (_this->vt != JSI_VT_OBJECT || _this->d.obj->ot != JSI_OT_NUMBER) { \
Jsi_LogError("apply Number.%s to a non-number object", funcPtr->cmdSpec->name); \
return JSI_ERROR; \
} else { \
dest = _this; \
}
static Jsi_RC NumberToFixedCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
char buf[100];
int prec = 0, skip = 0;
Jsi_Number num;
Jsi_Value *v;
ChkStringN(_this, funcPtr, v);
Jsi_Value *pa = Jsi_ValueArrayIndex(interp, args, skip);
if (pa && Jsi_GetIntFromValue(interp, pa, &prec) != JSI_OK)
return JSI_ERROR;
if (prec<0) prec = 0;
Jsi_GetDoubleFromValue(interp, v, &num);
snprintf(buf, sizeof(buf), "%.*" JSI_NUMFFMT, prec, num);
Jsi_ValueMakeStringDup(interp, ret, buf);
return JSI_OK;
}
static Jsi_RC NumberToPrecisionCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
char buf[100];
int prec = 0, skip = 0;
Jsi_Number num;
Jsi_Value *v;
ChkStringN(_this, funcPtr, v);
if (Jsi_GetIntFromValue(interp, Jsi_ValueArrayIndex(interp, args, skip), &prec) != JSI_OK)
return JSI_ERROR;
if (prec<=0) return JSI_ERROR;
Jsi_GetDoubleFromValue(interp, v, &num);
snprintf(buf, sizeof(buf),"%.*" JSI_NUMFFMT, prec, num);
if (num<0)
prec++;
buf[prec+1] = 0;
if (buf[prec] == '.')
buf[prec] = 0;
Jsi_ValueMakeStringDup(interp, ret, buf);
return JSI_OK;
}
static Jsi_RC NumberToExponentialCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
char buf[100];
int prec = 0, skip = 0;
Jsi_Number num;
Jsi_Value *v;
ChkStringN(_this, funcPtr, v);
if (Jsi_GetIntFromValue(interp, Jsi_ValueArrayIndex(interp, args, skip), &prec) != JSI_OK)
return JSI_ERROR;
if (prec<0) prec = 0;
Jsi_GetDoubleFromValue(interp, v, &num);
snprintf(buf, sizeof(buf), "%.*" JSI_NUMEFMT, prec, num);
#ifdef __WIN32
char *e = strrchr(buf, 'e');
if (e && (e[1]=='+' || e[1]=='-')) {
e++;
int eNum = atoi(e);
if (e[0]=='-')
eNum = -eNum;
e++;
snprintf(e, (e-buf), "%02d", eNum);
}
#endif
/*int len = Jsi_Strlen(buf);
if (len >= 4 && strrchr(buf, '+') && buf[len-1] == '0') {
while (buf[len-1] == '0' && buf[len-2]=='0')
buf[--len] = 0;
}*/
Jsi_ValueMakeStringDup(interp, ret, buf);
return JSI_OK;
}
static Jsi_RC NumberToStringCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
char buf[500];
int radix = 10, skip = 0, argc = Jsi_ValueGetLength(interp, args);
Jsi_Number num;
Jsi_Value *v;
ChkStringN(_this, funcPtr, v);
Jsi_GetDoubleFromValue(interp, v, &num);
if (argc>skip && (Jsi_GetIntFromValue(interp, Jsi_ValueArrayIndex(interp, args, skip), &radix) != JSI_OK
|| radix<2))
return JSI_ERROR;
if (argc==skip)
return jsi_ObjectToStringCmd(interp, args, _this, ret, funcPtr);
switch (radix) {
case 16: snprintf(buf, sizeof(buf), "%"PRIx64, (Jsi_Wide)num); break;
case 8: snprintf(buf, sizeof(buf), "%" PRIo64, (Jsi_Wide)num); break;
case 10: snprintf(buf, sizeof(buf), "%" PRId64, (Jsi_Wide)num); break;
default: return jsi_ObjectToStringCmd(interp, args, _this, ret, funcPtr);
}
Jsi_ValueMakeStringDup(interp, ret, buf);
return JSI_OK;
}
static Jsi_CmdSpec numberCmds[] = {
{ "Number", NumberConstructor, 0, 1, "num:string=0", .help="Number constructor", .retType=(uint)JSI_TT_NUMBER, .flags=JSI_CMD_IS_CONSTRUCTOR },
{ "toFixed", NumberToFixedCmd, 0, 1, "num:number=0", .help="Formats a number with x numbers of digits after the decimal point", .retType=(uint)JSI_TT_STRING },
{ "toExponential", NumberToExponentialCmd, 1, 1, "num:number", .help="Converts a number into an exponential notation", .retType=(uint)JSI_TT_STRING },
{ "toPrecision", NumberToPrecisionCmd, 1, 1, "num:number", .help="Formats a number to x length", .retType=(uint)JSI_TT_STRING },
{ "toString", NumberToStringCmd, 0, 1, "radix:number=10", .help="Convert to string", .retType=(uint)JSI_TT_STRING },
{ NULL, 0,0,0,0, .help="Commands for accessing number objects" }
};
Jsi_RC jsi_InitNumber(Jsi_Interp *interp, int release)
{
if (release) return JSI_OK;
Jsi_Value *val, *global = interp->csc;
val = interp->Number_prototype = Jsi_CommandCreateSpecs(interp, "Number", numberCmds, NULL, JSI_CMDSPEC_ISOBJ);
Jsi_Value *NaN = Jsi_ValueMakeNumber(interp, NULL, Jsi_NumberNaN());
Jsi_Value *Inf = Jsi_ValueMakeNumber(interp, NULL, Jsi_NumberInfinity(1));
Jsi_ValueInsertFixed(interp, global, "NaN", NaN);
Jsi_ValueInsertFixed(interp, global, "Infinity", Inf);
interp->NaNValue = NaN;
interp->InfValue = Inf;
#define MCONST(name,v) Jsi_ValueInsert(interp, val, name, Jsi_ValueNewNumber(interp, v), JSI_OM_READONLY)
MCONST("MAX_VALUE", DBL_MAX);
MCONST("MIN_VALUE", DBL_MIN);
MCONST("NEGATIVE_INFINITY", Jsi_NumberInfinity(-1));
Jsi_ValueInsertFixed(interp, val, "POSITIVE_INFINITY", Inf);
Jsi_ValueInsertFixed(interp, val, "NaN", NaN);
return JSI_OK;
}
#endif
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsub.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fchuc <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/12/04 16:01:33 by fchuc #+# #+# */
/* Updated: 2015/12/04 16:03:15 by fchuc ### ########.fr */
/* */
/* ************************************************************************** */
/*
** Alloue (avec malloc) et retourne la copie “fraiche” d’un tronçon
** de la chaine de caracteres passee en parametre. Le tronçon
** commence a l’index start et a pour longueur len.
*/
#include "../includes/libft.h"
char *ft_strsub(char const *s, unsigned int start, size_t len)
{
int i;
char *substr;
substr = (char*)malloc(sizeof(char) * (len + 1));
if (s == NULL)
return (NULL);
if (substr == NULL)
return (NULL);
i = 0;
while (len > 0)
{
substr[i] = s[start + i];
i++;
len--;
}
substr[i] = '\0';
return (substr);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
int angles[6];
void parser(char *line){
// Takes in a char*, converts char* to int, comma separated
const char *delim = ",";
char *p = strtok(line, delim);
int counter = 0;
while (p != NULL){
// convert *p to int, store into angles[counter]
angles[counter] = atoi(p);
// fetch next one
p = strtok(NULL, delim);
counter++;
}
assert(counter==6);
}
int main(int argc, char **argv){
// printf("hi");
char line[] = "1,2,3,4,5,6";
parser(line);
for (int i = 0; i < 6; i ++){
printf("%d ,", angles[i]);
}
}
|
C | /*
GAudio 2.1.0.8, (C)2013 by Eric Du(E)
This program is a part of the GAudio SDK.
Use GAudio's echo effect
*/
#include <stdlib.h>
#include <conio.h>
#include <stdio.h>
#include "gaudio.h"
float circle = 0;
const float radius = 5;
void GAPIENTRY tellpos(gsource* source,int32_t position)
{
circle += 0.04f;
float x = radius * cosf(circle);
float z = radius * sinf(circle * 0.5f);
gaudio_source_set_float3(source,AUDIO_ENUM_POSITION,x,0,z);
}
int main(int argc,char* argv[])
{
printf("3d effect created by D.Eric\n");
#if(defined(WIN32) || defined(WIN64))
gaudio_init("addons");
#else
gaudio_init("/usr/local/lib/gaudio/");
#endif
//! load soundfont for midi/mid music file
gaudio_set_string(AUDIO_ENUM_SOUNDFONT,"instruments\\snd.cfg");
const char* filename = "..\\media\\intro.wav";
gsource* source = gaudio_source_create_from_file(filename,FALSE);
if(source == NULL)
{
printf("load file:%s error!\n",filename);
printf("bad source.\nerror code:%d.\n",gaudio_error_get());
gaudio_deinit();
return -1;
}
gaudio_source_set_int32(source,AUDIO_ENUM_LOOP,FALSE);
gaudio_source_set_position_callback(source,tellpos);
gaudio_listener_set_float3(AUDIO_ENUM_POSITION,0,0,0);
gaudio_listener_set_float3(AUDIO_ENUM_FORWARD,0,0,1);
printf("play filename:%s\n",filename);
gaudio_source_play3(source,FALSE);
printf("\nplaying, press any key to quit.\n");
getch();
gaudio_source_stop(source);
gaudio_source_destroy(source);
gaudio_deinit();
system("PAUSE");
return EXIT_SUCCESS;
}
|
C | #include<stdio.h>
// Type Casting
void main()
{
float a,b;
int c;
printf("enter 2 numbers\n");
scanf("%f",&a);
scanf("%f",&b);
c=a+b;
printf("the sum of the numbers is:%d\n",c);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include "strutil.h"
int main(void) {
char *str = "Hello, WORLD!";
char *lower = strutil_lowercase(str);
printf("Original: \"%s\"\n", str);
printf("Lowercase: \"%s\"\n", lower);
free(lower);
return 0;
}
|
C | #ifndef GARBAGECOLLECTOR_H_
# define GARBAGECOLLECTOR_H_
# include <pebble.h>
# include "../Scopper/Scopper.h"
/**
* A container for given pointers to keep them for cleaning by the MemoryManager
* @see alloc
* @see custom_alloc
* @see resource_handle
*/
typedef struct s_Resource
{
void *data;
void (*ptr)(void *);
struct s_Resource *next;
} Resource;
/**
* A container for the layers of memory that can be freed by the MemoryManager
*/
typedef struct s_ResourceLayer
{
Resource *resources;
struct s_ResourceLayer *next;
} ResourceLayer;
/**
* A container for the MemoryManager
*/
typedef struct s_MemoryManager
{
ResourceLayer *layers;
ResourceLayer *safe_layer;
} MemoryManager;
/**
* (Private Function)
* Creates a new layer in the MemoryManager. This function is called on window creation.
*/
void create_resource_layer();
/**
* (Private Function)
* Creates a new layer in the MemoryManager. This functions sets the safe_stack. I.E. the lowest layer on the stack. This function MUST NOT be called by the user.
*/
void set_safe_resource_layer();
/**
* Allocates some memory in the MemoryManager. This function is a REPLACEMENT for malloc() function that must not be called anymore
* @param size The size in bytes that must be allocated
* @return An allocated pointer of the given size
* @see clean
*/
void *alloc(size_t size);
/**
* Allocates some memory for an array. Just one allocation will be done.
* @param size The size of the type to be allocated.
* @param nbr The size of the array to allocate.
* @see clean
*/
void **array_alloc(size_t size, unsigned int nbr);
/**
* Allocate memory on the safe stack. The memory will be freed on clean() or program ending.
* @param size The size to allocate
* @param ptr The freeing function
* @return a pointer of the allocated memory size
*/
void *safe_alloc(size_t size, void (*ptr)(void *));
/**
* Same as alloc but takes a function pointer to a custom free function. This function should be called when user wants to uninitialize some data by a specific method
* @param size The size in bytes that must be allocated
* @param ptr A custom function to free the pointer
* @return An allocated pointer of the given size
* @see clean
*/
void *custom_alloc(size_t size, void (*ptr)(void *));
/**
* Takes a pointer in parameter and pass it to the MemoryManager. This function doesn't allocate memory but frees it with the custom pointer when it must be done.
* @param data A pointer of allocated memory
* @param ptr A custom function to free the pointer
* @return data variable
* @see clean
*/
void *resource_handle(void *data, void (*ptr)(void *));
/**
* Free any pointer allocated within Khelljyr's allocation functions. This function is a REPLACEMENT for free() function that must not be called anymore
* @param ptr The pointer to be freed
* @see alloc
* @see custom_alloc
* @see resource_handle
*/
void clean(void *ptr);
/**
* (Private Function)
* Cleans the upper stack of the MemoryManager. This function is called on each window destruction and must not be called by users.
* @param stack_value The value on stack that must be cleaned
*/
void clean_collector(MemoryManager *stack_value);
/**
* (Private Function)
* Cleans the MemoryManager, this function is called by Khelljyr on exit. It must not be called by users.
*/
void clean_resource_layer();
/**
* (Private Function)
* A Macro that returns a pointer to the MemoryManager structure for the framework
*/
# define MEMORYMANAGER_PTR ((MemoryManager *)scopper(NULL, 0))
/**
* A basic overload for array_alloc. It is more convenient to use it (no casts to do and slightly less to write)
* @see array_alloc
*/
# define ARRAY_ALLOC(TYPE, NBR) ((TYPE **)array_alloc(sizeof(TYPE), NBR))
#endif
|
C | #include <stdio.h>
#include "exchap9.h"
void question92(){
/* Déclarations */
int A[100], B[50]; /* tableaux */
int N, M; /* dimensions des tableaux */
int I; /* indice courant */
/* Saisie des données */
printf("Dimension du tableau A (max.50) : ");
scanf("%d", &N );
for (I=0; I<N; I++)
{
printf("Elément %d : ", I);
scanf("%d", A+I);
}
printf("Dimension du tableau B (max.50) : ");
scanf("%d", &M );
for (I=0; I<M; I++)
{
printf("Elément %d : ", I);
scanf("%d", B+I);
}
/* Affichage des tableaux */
printf("Tableau donné A :\n");
for (I=0; I<N; I++)
printf("%d ", *(A+I));
printf("\n");
printf("Tableau donné B :\n");
for (I=0; I<M; I++)
printf("%d ", *(B+I));
printf("\n");
/* Copie de B à la fin de A */
for (I=0; I<M; I++)
*(A+N+I) = *(B+I);
/* Nouvelle dimension de A */
N += M;
/* Edition du résultat */
printf("Tableau résultat A :\n");
for (I=0; I<N; I++)
printf("%d ", *(A+I));
printf("\n");
}
|
C | #include "../usart/usart.h"
#include <stdlib.h>
#include <util/delay.h>
#include <avr/io.h>
#include<avr/pgmspace.h>
#include<stdio.h>
#define duzina_ime 7
#define pass 9
int8_t proveri(char str1[], char str2[], int8_t duz1, int8_t duz2) {
if (duz1 != duz2)
return 0;
for(int i = 0; i < duz1; i++) {
if (str1[i] != str2[i])
return 0;
}
return 1;
}
int main() {
usartInit(9600);
char pom [64];
char ime [duzina_ime] = "MyName";
char sifra [pass] = "password";
int8_t provera = 0;
int8_t duzina = 0;
while(1) {
usartPutString_P(PSTR("Unesite korisnicko ime:\r\n"));
while(!usartAvailable());
_delay_ms(100);
duzina = usartGetString(pom);
pom[duzina] = '\0';
provera = proveri(ime, pom, duzina+1, duzina_ime);
if(provera == 1) {
usartPutString_P(PSTR("Unesite loziku:\r\n"));
while(!usartAvailable());
_delay_ms(100);
duzina = usartGetString(pom);
pom[duzina] = '\0';
provera = proveri(sifra, pom, duzina+1, pass);
if (provera == 1) {
usartPutString_P(PSTR("Dobrodosao/la"));
usartPutString(ime);
usartPutString_P(PSTR("!\r\n"));
} else
usartPutString_P(PSTR("Logovanje je neuspesno!"));
} else
usartPutString_P(PSTR("Logovanje je neuspesno!"));
}
return 0;
}
|
C | #include <stdio.h>
int main()
{
int i=0;
for (printf("one\n");i < 3 && printf("");i++)
{
printf ("SUNNY\n");
}
return 0;
}
|
C | /* area.c. Program to compute area contributing to each Pixel in DEM
for cell outflow based on angles.
David G Tarboton
Utah State University
SINMAP package version 0.1 9/2/97 */
#include "lsm.h"
void main(int argc,char **argv)
{
char pfile[MAXLN],afile[MAXLN], *ext;
int err,row=0,col=0,nmain;
if(argc < 2)
{
printf("Usage:\n %s filename [outletrow outletcol]\n",argv[0]);
printf("(The optional outletrow and outletcol are outlet coordinates\n");
printf("for the area to be computed. If they are not given, or are \n");
printf("0 0 the whole file is computed.)\n");
printf("The following are appended to the file names\n");
printf("the files are opened:\n");
printf("ang D inf flow directions(Input)\n");
printf("sca Specific Catchment Area (Output)\n");
exit(0);
}
ext=strrchr(argv[1],'.');
if(ext == NULL)
{
sprintf(pfile,"%s%s",argv[1],"ang");
sprintf(afile,"%s%s",argv[1],"sca");
}
else
{
nmain=strlen(argv[1])-strlen(ext);
strncpy(afile,argv[1],nmain);
strcat(afile,"sca");
strcat(afile,ext);
strncpy(pfile,argv[1],nmain);
strcat(pfile,"ang");
strcat(pfile,ext);
}
if(argc >2)
{
sscanf(argv[2],"%d",&row);
sscanf(argv[3],"%d",&col);
}
if(err=area(pfile,afile,row,col) != 0)
printf("area error %d\n",err);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.