language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "FUNCIONES.h"
/** \brief muestra el menu en la consola
*
* \param recibe un string para imprimir por consola
* \param recibe un valor para marcar un rango de limite de inicio
* \param recibe un valor para marcar un rango de limite de final
* \return retorna la opcion del menu
*
*/
int menu_generico(char *mensaje,int desde,int hasta)
{
char no_definido[]="no definido";
int opcion;
int flag=0;
do
{
if(flag)
{
system("cls");
printf("error,ingrese una opcion valida\n");
system("pause");
system("cls");
printf("1- Ingresar 1er operando (A=%s)\n",no_definido);
printf("2- Ingresar 2do operando (B=%s)\n",no_definido);
}
puts(mensaje);
fflush(stdin);
scanf("%d",&opcion);
flag=1;
}while(opcion<desde||opcion>hasta);
return opcion;
}
/** \brief calcula la suma de los operando
*
* \param numero_ingre_A correspondiente a la variable A
* \param numero_ingre_B correspondiente a la variable B
* \return retorna el resultado de la suma
*
*/
float sumar_los_num(float num_1,float num_2)
{
return num_1+num_2;
}
/** \brief calcula la resta de los operando
*
* \param numero_ingre_A correspondiente a la variable A
* \param numero_ingre_B correspondiente a la variable B
* \return retorna el resultado de la resta
*
*/
float restar_los_num(float num_1,float num_2)
{
return num_1-num_2;
}
/** \brief calcula la multiplicacion de los operando
*
* \param numero_ingre_A correspondiente a la variable A
* \param numero_ingre_B correspondiente a la variable B
* \return retorna el resultado de la multiplicacion
*
*/
float multiplicar_los_num(float num_1,float num_2)
{
return num_1*num_2;
}
/** \brief calcula la division de los operando
*
* \param numero_ingre_A correspondiente a la variable A
* \param numero_ingre_B correspondiente a la variable B
* \return retorna el resultado de la division
*
*/
float dividir_los_num(float dividendo,float divisor)
{
return dividendo/divisor;
}
/** \brief calcula el factorial del operando
*
* \param numero_ingre_A correspondiente a la variable A
* \return retorna el resultado del factorial
*
*/
int factorial_del_num(int num)
{
int valor;
if(num==0)
return 1;
valor=num*factorial_del_num(num-1);
return valor;
}
|
C
|
#include "boundary_val.h"
#include "NSDefinitions.h"
#include <string.h>
/**
* The boundary values of the problem are set.
*/
void boundaryvalues(int imax, int jmax, double dx, double dy, int wl, int wr,
int wt, int wb, double **U, double **V, double **F, double **G,
double **P, double **T, int** Flag, double ***C,int s_max,
double cl,
double cr,
double cb,
double ct) {
int i = 0;
int j = 0;
int k = 0;
/******************************************************************/
/*U & V & T boundary values
/******************************************************************/
for (i = 1; i <= imax; i++) {
/* lower bounder */
switch (wb) {
case NO_SLIP:
U[i][0] = -U[i][1];
V[i][0] = 0.0;
break;
case FREE_SLIP:
U[i][0] = U[i][1];
V[i][0] = 0.0;
break;
case OUTFLOW:
U[i][0] = U[i][1];
V[i][0] = V[i][1];
break;
}
/* upper bounder */
switch (wt) {
case NO_SLIP:
U[i][jmax + 1] = -U[i][jmax];
V[i][jmax] = 0.0;
break;
case FREE_SLIP:
U[i][jmax + 1] = U[i][jmax];
V[i][jmax] = 0.0;
break;
case OUTFLOW:
U[i][jmax + 1] = U[i][jmax];
V[i][jmax] = V[i][jmax - 1];
break;
}
T[i][0] = T[i][1];
T[i][jmax+1] = T[i][jmax];
}
for (j = 1; j <= jmax; j++) {
/* left border */
switch (wl) {
case NO_SLIP:
U[0][j] = 0.0;
V[0][j] = -V[1][j];
break;
case FREE_SLIP:
U[0][j] = 0.0;
V[0][j] = V[1][j];
break;
case OUTFLOW:
U[0][j] = U[1][j];
V[0][j] = V[1][j];
break;
}
/* right border */
switch (wr) {
case NO_SLIP:
U[imax][j] = 0.0;
V[imax + 1][j] = -V[imax][j];
break;
case FREE_SLIP:
U[imax][j] = 0.0;
V[imax + 1][j] = V[imax][j];
break;
case OUTFLOW:
U[imax][j] = U[imax - 1][j];
V[imax + 1][j] = V[imax][j];
break;
}
T[0][j] = T[1][j];
T[imax+1][j] = T[imax][j];
}
/* set the values of the inner obstacles */
/* treat obstacle boundaries, see 1.4 to 1.6 */
for (j = 1; j <= jmax; j++)
for (i = 1; i <= imax; i++) {
switch (Flag[i][j]) {
case B_N:
V[i][j] = 0;
U[i - 1][j] = -U[i - 1][j + 1];
U[i][j] = -U[i][j + 1];
break;
case B_S:
V[i][j - 1] = 0;
U[i - 1][j] = -U[i - 1][j - 1];
U[i][j] = -U[i][j - 1];
break;
case B_W:
U[i - 1][j] = 0;
V[i][j - 1] = -V[i - 1][j - 1];
V[i][j] = -V[i - 1][j];
break;
case B_O:
U[i][j] = 0;
V[i][j - 1] = -V[i + 1][j - 1];
V[i][j] = -V[i + 1][j];
break;
case B_NO:
U[i][j] = 0;
U[i - 1][j] = -U[i - 1][j + 1];
V[i][j] = 0;
V[i][j - 1] = -V[i + 1][j - 1];
break;
case B_NW:
U[i - 1][j] = 0;
U[i][j] = -U[i][j + 1];
V[i][j] = 0;
V[i][j - 1] = -V[i - 1][j - 1];
break;
case B_SO:
U[i][j] = 0;
U[i - 1][j] = -U[i - 1][j - 1];
V[i][j - 1] = 0;
V[i][j] = -V[i + 1][j];
break;
case B_SW:
U[i - 1][j] = 0;
U[i][j] = -U[i][j - 1];
V[i][j - 1] = 0;
V[i][j] = -V[i - 1][j];
break;
}
}
/** boundaries for temperature **/
for (i = 1; i <= imax; ++i) {
for (j = 1; j <= jmax; ++j) {
if (Flag[i][j] == B_N) {
T[i][j] = T[i][j + 1];
}
else if (Flag[i][j] == B_W) {
T[i][j] = T[i - 1][j];
}
else if (Flag[i][j] == B_S) {
T[i][j] = T[i][j - 1];
}
else if (Flag[i][j] == B_O) {
T[i][j] = T[i + 1][j];
}
else if (Flag[i][j] == B_NO) {
T[i][j] = (T[i + 1][j] + T[i][j + 1]) / 2;
}
else if (Flag[i][j] == B_NW) {
T[i][j] = (T[i - 1][j] + T[i][j + 1]) / 2;
}
else if (Flag[i][j] == B_SO) {
T[i][j] = (T[i + 1][j] + T[i][j - 1]) / 2;
}
else if (Flag[i][j] == B_SW) {
T[i][j] = (T[i - 1][j] + T[i][j - 1]) / 2;
}
}
}
/******************************************************************/
/* Concentration boundary values
/******************************************************************/
for (k = 0; k < s_max; ++k)
{
/** left and right wall **/
for (j = 0; j <= jmax; ++j)
{
if(cl == 0.0)
C[k][0][j] = -C[k][1][j];
else if(cl > 0.0)
C[k][0][j] = 2*cl - C[k][1][j];
if(cr == 0.0)
C[k][imax+1][j] = C[k][imax][j];
else if(cr > 0.0)
C[k][imax+1][j] = 2*cr-C[k][imax][j];
else if(cb < 0.0)
C[k][i][0] = 0.0;
}
/** top and bottom wall **/
for(i = 0; i <= imax; ++i)
{
if(cb == 0.0)
C[k][i][0] = C[k][i][1];
else if(cb > 0.0)
C[k][i][0] = 2*cb - C[k][i][1];
if(ct == 0.0)
C[k][i][jmax+1] = C[k][i][jmax];
else if(ct > 0.0)
C[k][i][0] = 2*ct - C[k][i][jmax];
}
}
/** boundaries for substances **/
for (k = 0; k < s_max; ++k) {
for (i = 1; i <= imax; ++i) {
for (j = 1; j <= jmax; ++j) {
if (Flag[i][j] == B_N)
{
C[k][i][j]=C[k][i][j+1];
}
else if (Flag[i][j] == B_W)
{
C[k][i][j]=C[k][i-1][j];
}
else if (Flag[i][j] == B_S)
{
C[k][i][j]=C[k][i][j-1];
}
else if (Flag[i][j] == B_O)
{
C[k][i][j]=C[k][i+1][j];
}
else if (Flag[i][j] == B_NO)
{
C[k][i][j]=(C[k][i+1][j]+C[k][i][j+1])/2;
}
else if (Flag[i][j] == B_NW)
{
C[k][i][j]=(C[k][i-1][j]+C[k][i][j+1])/2;
}
else if (Flag[i][j] == B_SO)
{
C[k][i][j]=(C[k][i+1][j]+C[k][i][j-1])/2;
}
else if (Flag[i][j] == B_SW)
{
C[k][i][j]=(C[k][i-1][j]+C[k][i][j-1])/2;
}
}
}
}
}
void spec_boundary_val(char *problem, int imax, int jmax, int s_max, double dx, double dy,
double Re, double deltaP, double **U, double **V, double **P, double **T,
double ***C) {
int s;
int j = 0;
if (strcmp(problem, "karman") == 0 || strcmp(problem, "advection") == 0) {
for (j = 1; j <= jmax; ++j) {
/* set karman inflow */
U[0][j] = 1.0;
V[0][j] = 0.0;
}
}
else if (strcmp(problem, "pollution") == 0) {
for (j = 1; j <= jmax; ++j) {
/* set karman inflow */
U[0][j] = 0.25;
V[0][j] = 0.0;
}
}
else if (strcmp(problem, "karman_diffusion") == 0) {
for (j = 1; j <= jmax; ++j) {
/* set karman inflow */
U[0][j] = 1.0;
V[0][j] = 0.0;
}
}
else if (strcmp(problem, "step") == 0)
{
/* set step inflow - only upper half */
for (j = (jmax + 2) / 2 + 1; j < jmax + 1; ++j) {
U[0][j] = 1.0;
V[0][j] = 0.0;
}
for (j = 1; j < (jmax + 2) / 2; ++j) {
U[0][j] = 0.0;
V[0][j] = 0.0;
}
}
// Rayleigh-Benard flow: top T = -0.5 bottom T = 0.5
// left and right walls adiabatic,
// lower wall heated, upper wall cooled.
//
else if ( strcmp(problem, "rayleigh") ==0)
{
for(j=0; j<=jmax+1; j++)
{
T[0][j] = 0.5;
T[imax+1][j] = -0.5;
}
for(j=0;j<=imax+1;j++)
{
T[j][0] = T[j][1];
T[j][jmax+1] = T[j][jmax] ;
}
return;
}
else if (strcmp(problem, "fluidTrap")==0)
{
for(j=0; j<=jmax+1; j++)
{
T[0][j] = 2*(2.5)-T[1][j];
T[imax+1][j] = 2*(-2.5)-T[imax][j];
}
for(j=0;j<=imax+1;j++)
{
T[j][0] = T[j][1];
T[j][jmax+1] = T[j][jmax] ;
}
return;
}
else if (strcmp(problem, "rayleigh_plane")==0)
{
for(j=0; j<=jmax+1; j++)
{
T[0][j] = T[1][j];
T[imax+1][j] = T[imax][j];
}
for(j=0;j<=imax+1;j++)
{
T[j][0] = 1.8;
T[j][jmax+1] = -1.8;
}
return;
}
}
|
C
|
/********************************ͷļ**********************************************/
#include<reg52.h> //reg52.hļΪͷļ
/********************************궨**********************************************/
#define uint unsigned int //ͺ궨Ϊuint
#define uchar unsigned char //ַͺ궨Ϊuchar
/************************************λ**********************************************/
sbit duan=P2^6; //P2.6˿Ϊduan,ƶ
sbit wei=P2^7; //P2.7˿Ϊweiλ
/********************************ַ**********************************************/
uchar code duanma[]={ //һַduanma[]ROM
0x3f,0x06,0x5b,0x4f, //ڹܶݱ
0x66,0x6d,0x7d,0x07, //LEDܵкҪֵб
0x7f,0x6f,0x77,0x7c, //ȡߵƽϨȡ͵ƽ
0x39,0x5e,0x79,0x71}; // duanma[0]͵0x3f
uchar code weima[]={ //һַweima[]ROM
0xfe,0xfd,0xfb,0xf7, //ڹλݱ
0xef,0xdf,0xbf,0x7f}; //ܵб룬ȡ͵ƽϨȡߵƽ
uchar a,b,c; //ַʵʲa,b,c
uint num; //ͱʵʲnum
/********************************Ӻ**********************************************/
void delay(uint z); //ʱ
void display(uchar bai,uchar shi,uchar ge);//ʾ
/**********************************************************************************/
void main() //ֵֻһ
{
num=520; //numֵ520
while(1) //while1ѭڷ0Ϊ棨ȥ
{ //ִ{}
//ֻΪ00Ϊ٣Ҳִ{}
display(a,b,c); //ʾʵʲa,b,cʽbai,shi,ge
} //Ҫôѭѭɨܣʵʱʾnum
}
/********************************ʱ***********************************************/
void delay(uint z) //ֵdelay()ͱzΪֲʽ
{
uint x,y; //ͱx,yñΪֲβ
for(x=z;x>0;x--) //forѭ forʽ1ʽ2ʽ3
for(y=110;y>0;y--); // {䣨ڲΪգ}
} //forѭǶ
//y0ִһx--xһٸxռΪxyﵽʱĿ
//ִй̣1.ʽ1
// 2.ʽ2ֵΪ棨0Ϊ棩
//ִfor䣬Ȼִеfor䣬ֱִе
// 3.ʽ3 4.ڶظִ
/********************************ʾ**********************************************/
void display(uchar bai,uchar shi,uchar ge)//ֲֵʽbai,shi,ge
{
a=num/100; //num100ֽ̣numİλa
b=num%100/10; //num100ٳ10ֽ̣ʮλb
c=num%10; //num10ֽλc
P1=duanma[bai]; //P1duanma[]bai+1λΪ
duan=1; //
duan=0; //رն
P1=weima[5]; //P1weima[]6λΪλ룬ѡ6
wei=1; //λ
wei=0; //رλ
delay(1); //z=1ʱΪʱ
P1=0xff; //P1ȫߵƽλﵽĿ
wei=1; //λ
wei=0; //رλ
P1=duanma[shi]; //P1duanma[]shi+1λΪ
duan=1; //
duan=0; //رն
P1=weima[6]; //weima[]7λΪ룬ѡ7
wei=1; //λ
wei=0; //رλ
delay(1); //ʱ
P1=0xff; //P1ȫߵƽȴλʵ
wei=1; //λ
wei=0; //رλ
P1=duanma[ge]; //ͬϣѭɨ衣
duan=1; //ʵͬһʱֻʾһ
duan=0; //ϽһһһʱȻϨ
P1=weima[7]; //̬ܶɨ
wei=1; //Ӷʵ˿Ϊͬʱʾ
wei=0;
delay(1);
P1=0xff;
wei=1;
wei=0; //עⰡֽӷҪȸֵٿ
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* list.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: volyvar- <volyvar-@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/28 18:47:12 by volyvar- #+# #+# */
/* Updated: 2020/12/08 21:32:28 by volyvar- ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
void ft_list_add(t_env **head, char *name, char *content)
{
t_env *tmp;
t_env *go;
if (!(tmp = (t_env *)malloc(sizeof(t_env))))
ft_malloc_error();
tmp->name = NULL;
tmp->content = NULL;
if (name && !(tmp->name = ft_strdup(name)))
ft_malloc_error();
if (content && !(tmp->content = ft_strdup(content)))
ft_malloc_error();
tmp->next = NULL;
if (*head == NULL)
*head = tmp;
else
{
go = *head;
while (go->next)
go = go->next;
go->next = tmp;
}
}
t_env *ft_find_in_list(t_env *env, char *name)
{
t_env *tmp;
tmp = env;
while (tmp)
{
if (!ft_strcmp(tmp->name, name))
return (tmp);
tmp = tmp->next;
}
return (NULL);
}
void ft_list_delete_element_name(t_env **head, char *name)
{
t_env *tmp;
t_env *prev;
prev = NULL;
tmp = *head;
while (tmp)
{
if (!ft_strcmp(tmp->name, name))
{
if (prev == NULL)
*head = tmp->next;
else
prev->next = tmp->next;
ft_strdel(&(tmp->name));
ft_strdel(&(tmp->content));
free(tmp);
tmp = NULL;
return ;
}
prev = tmp;
tmp = tmp->next;
}
}
int ft_find_list_len(t_env *head)
{
t_env *tmp;
int len;
len = 0;
tmp = head;
while (tmp)
{
len++;
tmp = tmp->next;
}
return (len);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, const char *argv[])
{
pid_t pid;
pid = fork();
if(pid < 0)
{
perror("fork1");
exit(1);
}
else if(pid == 0)
{
pid_t pid1;
pid1 = fork();
if(pid1 < 0)
{
perror("fork2");
exit(1);
}
else if(pid1 == 0)
{
sleep(1);
printf("grandson's id is %d\n",getpid());
printf("son's id is %d\n",getppid());
exit(0);
}
else
{
exit(0);
}
}
else
{
wait(NULL);
while(1);
exit(0);
}
return 0;
}
|
C
|
/*
* The MIT License
*
* Copyright 2018 Andrea Vouk.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* This file is part of the C4C library (https://github.com/QwertyQaz414/C4C).
*/
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
/* 1.1 Optional: Define custom implementations of c4c macros. */
/*
#define C4C_FUNCTION(rettype, name, ...) \
rettype __stdcall name(__VA_ARGS__)
*/
/* 1.2 Optional: Enable/Disable/Change certain features by defining C4C_FEATURE macros. */
/* Define this to disable struct typedeffing. */
/*
#define C4C_FEATURE_STRUCT_NO_ALIAS
*/
/* 2. Declare the container interface in a .h file. */
#define C4C_PARAM_STRUCT_NAME MY_STACK
#define C4C_PARAM_PREFIX my_stack
#define C4C_PARAM_CONTENT_TYPE int
#define C4C_PARAM_CAPACITY 64
#define C4C_PARAM_OPT_NO_VALUE -1
#include "c4c/stack/lifo_decl.inl"
/* 3. Declare the container implementation in a .c file or wherever you
* want it to be in. Make sure the macro params for the implementation have the
* same values as the interface ones.
*/
#define C4C_PARAM_STRUCT_NAME MY_STACK
#define C4C_PARAM_PREFIX my_stack
#define C4C_PARAM_CONTENT_TYPE int
#define C4C_PARAM_CAPACITY 64
#define C4C_PARAM_OPT_NO_VALUE -1
#include "c4c/stack/lifo_impl.inl"
/* 4. Magic happens. You can now use the container for your type :) */
int main(int argc, char* argv[])
{
/* variables */
int popt;
int t1, t2, t3;
MY_STACK stack;
/* init some custom types */
t1 = 1;
t2 = 10;
t3 = 100;
/* print max stack size */
printf("stack max size: %d\n", (int)my_stack_capacity());
/* prepare the stack for usage */
my_stack_clear(&stack);
/* push your custom types in the stack (if there is enough space) */
assert(my_stack_push(&stack, t1) && "t1 discarded: the stack is full");
assert(my_stack_push(&stack, t2) && "t2 discarded: the stack is full");
assert(my_stack_push(&stack, t3) && "t3 discarded: the stack is full");
/* pop the content until the stack is empty */
while (1) {
popt = my_stack_pop(&stack);
/* check if popt has a valid value */
if (popt != my_stack_null_val()) {
printf("popt (a: %d)\n", popt);
} else {
printf("popt is %d thus the stack is surely empty.\n", my_stack_null_val());
break;
}
}
getchar();
return EXIT_SUCCESS;
}
|
C
|
#include "hash_tables.h"
/**
* hash_table_get - Retrieves a value associated with a key.
* @ht: Hash Table to look in
* @key: Key for value
* Return: Value associted with key, or NULL if key is not found
*/
char *hash_table_get(const hash_table_t *ht, const char *key)
{
unsigned long int idx = 0;
hash_node_t *pair;
if (!ht)
return (0);
idx = key_index((const unsigned char *)key, ht->size);
pair = ht->array[idx];
while (pair && pair->key && strcmp(key, pair->key) != 0)
pair = pair->next;
if (!pair || !pair->key || strcmp(key, pair->key) != 0)
return (NULL);
else
return (pair->value);
}
|
C
|
#include<stdio.h><math.h>
int main() {
double valueA, valueB, valueC, delta, x1, x2;
scanf("%lf %lf %lf", &valueA, &valueB, &valueC);
delta = (valueB * valueB) - (4 * valueA * valueC);
x1 = (-valueB + sqrt(delta)) / (2 * valueA);
x2 = (-valueB - sqrt(delta)) / (2 * valueA);
if (delta < 0 || valueA == 0){
printf("Impossivel calcular\n");
} else {
printf("R1 = %.5lf\n", x1);
printf("R2 = %.5lf\n", x2);
}
return 0;
}
|
C
|
#include<stdio.h>
void main()
{
int a[10][10],i,j,sum=0,m,n;
printf("Enter the row and columns matrix:");
scanf("%d%d",&m,&n);
printf("Enter the element of matrix:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("The matrix is\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(i==j)
sum = sum + a[i][j];
}
}
printf("Sum of the diagonal elements of a matrix is:%d\n",sum);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int i,j;
int main_exit;
void menu();
struct date{
int month,day,year;
};
struct {
char name[60];
int acc_no,age;
char address[60];
char citizenship[15];
double phone;
char acc_type[10];
float amt;
struct date dob;
struct date deposit;
struct date withdraw;
}add,upd,check,rem,transaction;
float interest(float t,float amount,int rate)
{
float SI;
SI=(rate*t*amount)/100.0;
return (SI);
}
void records()
{
FILE *view;
view=fopen("record.dat","r");
int test=0;
clear_screen();
printf("\n\n\n\n\t\t\t\t\t\t\t\xB1\xB1\xB1\xB1\ CLIENTS RECORD \xB1\xB1\xB1\xB1");
printf("\n\n\t\t\t\tACC. NO.\t\tNAME\t\t\tADDRESS\t\t\tPHONE\n");
while(fscanf(view,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d",&add.acc_no,add.name,&add.dob.month,&add.dob.day,&add.dob.year,&add.age,add.address,add.citizenship,&add.phone,add.acc_type,&add.amt,&add.deposit.month,&add.deposit.day,&add.deposit.year)!=EOF)
{
printf("\n\t\t\t\t%6d\t\t %10s\t\t%10s\t\t\t%.0lf",add.acc_no,add.name,add.address,add.phone);
test++;
}
fclose(view);
if (test==0)
{
clear_screen();
printf("\n\n\n\t\t\t\t\tNO RECORDS!!\n");}
view_list_invalid:
printf("\n\nEnter 1 to go to the main menu and 0 to exit:");
scanf("%d",&main_exit);
system("cls");
if (main_exit==1)
menu();
else if(main_exit==0)
close();
else
{
printf("\nInvalid!\a");
goto view_list_invalid;
}
}
void new_acc()
{
int choice;
FILE *ptr;
ptr=fopen("record.dat","a+");
account_no:
system("cls");
clear_screen();
printf("\n\n\n\t\t\t\t\t\t\t\xB1\xB1\xB1\ ADD RECORD \xB1\xB1\xB1\xB1");
printf("\n\n\t\tEnter today's date(mm/dd/yyyy):");
scanf("%d/%d/%d",&add.deposit.month,&add.deposit.day,&add.deposit.year);
printf("\n\t\tEnter the account number:");
scanf("%d",&check.acc_no);
while(fscanf(ptr,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n",&add.acc_no,add.name,&add.dob.month,&add.dob.day,&add.dob.year,&add.age,add.address,add.citizenship,&add.phone,add.acc_type,&add.amt,&add.deposit.month,&add.deposit.day,&add.deposit.year)!=EOF)
{
if (check.acc_no==add.acc_no)
{printf("Account no. already in use!");
fordelay(1000000000);
goto account_no;
}
}
add.acc_no=check.acc_no;
clear_screen();
printf("\n\n\n\t\tEnter the name:");
scanf("%s",add.name);
printf("\n\t\tEnter the date of birth(mm/dd/yyyy):");
scanf("%d/%d/%d",&add.dob.month,&add.dob.day,&add.dob.year);
printf("\n\t\tEnter the age:");
scanf("%d",&add.age);
printf("\n\t\tEnter the address:");
scanf("%s",add.address);
printf("\n\t\tEnter the citizenship number:");
scanf("%s",add.citizenship);
printf("\n\t\tEnter the phone number: ");
scanf("%lf",&add.phone);
printf("\n\t\tEnter the amount to deposit:$");
scanf("%f",&add.amt);
printf("\n\t\tType of account:\n\t\t\t\t\tSaving\n\t\t\t\t\tCurrent\n\t\t\t\t\tFixed1(for 1 year)\n\t\t\t\t\tFixed2(for 2 years)\n\t\t\t\t\tFixed3(for 3 years)\n\t\tEnter your choice:");
scanf("%s",add.acc_type);
fprintf(ptr,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.citizenship,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
fclose(ptr);
printf("\n\t\tAccount created successfully!");
add_invalid:
printf("\n\t\tEnter 1 to go to the main menu and 0 to exit:");
scanf("%d",&main_exit);
system("cls");
if (main_exit==1)
restart();
else if(main_exit==0)
close();
else
{
printf("\n\n\n\n\n\n\n\t\t\t\t\t\t\t\nInvalid!\a");
goto add_invalid;
}
}
void fordelay(int j)
{ int i,k;
for(i=0;i<j;i++)
k=i;
}
void restart(void){
menu();
}
int choice;
void clear_screen(void){
system("cls");
printf("\n\n\n\n\t\t\t\t\t\xB2\xB2\xB2\xB2\xB2\xB2 WELCOME TO FIRST COMMUNITY BANK \xB2\xB2\xB2\xB2\xB2\xB2");
}
void balance(void){
int blc;
int s;
blc = 1000000;
clear_screen();
printf("\n\n\t\t\t\t\t\tYOUR BALANCE IS $ %d", blc);
printf("\n\n\t\t\t\TO CONTINUE WITH MAIN MENU PRESS 1, TO EXIT PRESS ANY KEY");
scanf("%d",&s);
if (s==1){
menu();
}
else{
clear_screen();
printf("\n\n\t\t\t\t\t\t\tTHANK YOU!");
fordelay(100000000000);
system("cls");
}
}
void edit(void)
{
int choice,test=0;
FILE *old,*newrec;
old=fopen("record.dat","r");
newrec=fopen("new.dat","w");
clear_screen();
printf("\n\n\n\n\t\tEnter the account no. of the customer whose info you want to change:");
scanf("%d",&upd.acc_no);
while(fscanf(old,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d",&add.acc_no,add.name,&add.dob.month,&add.dob.day,&add.dob.year,&add.age,add.address,add.citizenship,&add.phone,add.acc_type,&add.amt,&add.deposit.month,&add.deposit.day,&add.deposit.year)!=EOF)
{
if (add.acc_no==upd.acc_no)
{ test=1;
printf("\n\n\n\n\t\tWhich information do you want to change?\n\t\t\t1.Address\n\t\t\t2.Phone\n\n\t\tEnter your choice(1 for address and 2 for phone): ");
scanf("%d",&choice);
clear_screen();
if(choice==1)
{printf("\n\n\t\tEnter the new address: ");
scanf("%s",upd.address);
fprintf(newrec,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,upd.address,add.citizenship,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
clear_screen();
printf("\n\n\n\t\t\t\t\t\t\tChanges saved!\n\n");
}
else if(choice==2)
{
printf("\n\n\t\tEnter the new phone number: ");
scanf("%lf",&upd.phone);
fprintf(newrec,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.citizenship,upd.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
clear_screen();
printf("\n\n\n\t\t\t\t\t\t\tChanges saved!");
}
}
else
fprintf(newrec,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.citizenship,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
}
fclose(old);
fclose(newrec);
remove("record.dat");
rename("new.dat","record.dat");
if(test!=1)
{ clear_screen();
printf("\n\n\n\n\t\t\t\t\t\t\tRecord not found!!\a\a\a");
edit_invalid:
printf("\n\n\tEnter 0 to try again,1 to return to main menu and 2 to exit:");
scanf("%d",&main_exit);
clear_screen();
if (main_exit==1)
menu();
else if (main_exit==2)
close();
else if(main_exit==0)
edit();
else
{printf("\n\n\n\n\t\t\t\t\t\t\tInvalid!\a");
goto edit_invalid;}
}
else
{printf("\n\n\nEnter 1 to go to the main menu and 0 to exit:");
scanf("%d",&main_exit);
clear_screen();
if (main_exit==1)
menu();
else
close();
}
}
void transact(void)
{ int choice,test=0;
FILE *old,*newrec;
old=fopen("record.dat","r");
newrec=fopen("new.dat","w");
clear_screen();
printf("\n\n\n\t\t\tEnter the account no. of the customer: ");
scanf("%d",&transaction.acc_no);
while (fscanf(old,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d",&add.acc_no,add.name,&add.dob.month,&add.dob.day,&add.dob.year,&add.age,add.address,add.citizenship,&add.phone,add.acc_type,&add.amt,&add.deposit.month,&add.deposit.day,&add.deposit.year)!=EOF)
{
if(add.acc_no==transaction.acc_no)
{ test=1;
if(strcmpi(add.acc_type,"fixed1")==0||strcmpi(add.acc_type,"fixed2")==0||strcmpi(add.acc_type,"fixed3")==0)
{
printf("\a\a\a\n\n\t\tYOU CANNOT DEPOSIT OR WITHDRAW CASH IN FIXED ACCOUNTS!!!!!");
fordelay(1000000000);
clear_screen();
menu();
}
printf("\n\n\t\tDo you want to\n\t\t\t1.Deposit\n\t\t\t2.Withdraw?\n\n\t\tEnter your choice(1 for deposit and 2 for withdraw):");
scanf("%d",&choice);
if (choice==1)
{
printf("\n\n\t\tEnter the amount you want to deposit:$ ");
scanf("%f",&transaction.amt);
add.amt+=transaction.amt;
fprintf(newrec,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.citizenship,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
clear_screen();
printf("\n\n\n\n\t\t\t\t\t\tDeposited successfully!");
}
else
{
printf("\n\n\t\tEnter the amount you want to withdraw:$ ");
scanf("%f",&transaction.amt);
add.amt-=transaction.amt;
fprintf(newrec,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.citizenship,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
clear_screen();
printf("\n\n\n\t\t\t\t\t\tWithdrawn successfully!");
}
}
else
{
fprintf(newrec,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.citizenship,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
}
}
fclose(old);
fclose(newrec);
remove("record.dat");
rename("new.dat","record.dat");
if(test!=1)
{
printf("\n\n\n\t\t\t\t\t\t\tRecord not found!!");
transact_invalid:
printf("\n\n\n\t\tEnter 0 to try again,1 to return to main menu and 2 to exit:");
scanf("%d",&main_exit);
clear_screen();
if (main_exit==0)
transact();
else if (main_exit==1)
menu();
else if (main_exit==2)
close();
else
{
printf("\n\n\n\t\t\t\t\t\t\tInvalid!");
goto transact_invalid;
}
}
else
{
printf("\n\n\t\tEnter 1 to go to the main menu and 0 to exit:");
scanf("%d",&main_exit);
clear_screen();
if (main_exit==1)
menu();
else
close();
}
}
void erase(void)
{
FILE *old,*newrec;
int test=0;
old=fopen("record.dat","r");
newrec=fopen("new.dat","w");
clear_screen();
printf("\n\n\n\t\tEnter the account no. of the customer you want to delete: ");
scanf("%d",&rem.acc_no);
while (fscanf(old,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d",&add.acc_no,add.name,&add.dob.month,&add.dob.day,&add.dob.year,&add.age,add.address,add.citizenship,&add.phone,add.acc_type,&add.amt,&add.deposit.month,&add.deposit.day,&add.deposit.year)!=EOF)
{
if(add.acc_no!=rem.acc_no)
fprintf(newrec,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.citizenship,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
else
{test++;
clear_screen();
printf("\n\n\n\t\t\t\t\t\tRecord deleted successfully!\n");
}
}
fclose(old);
fclose(newrec);
remove("record.dat");
rename("new.dat","record.dat");
if(test==0)
{
printf("\n\n\n\t\t\t\t\t\t\t\tRecord not found!!\a\a\a");
erase_invalid:
printf("\n\n\tEnter 0 to try again,1 to return to main menu and 2 to exit:");
scanf("%d",&main_exit);
if (main_exit==1)
menu();
else if (main_exit==2)
close();
else if(main_exit==0)
erase();
else
{printf("\n\n\n\t\t\t\t\t\t\tInvalid!\a");
goto erase_invalid;}
}
else
{printf("\n\n\t\tEnter 1 to go to the main menu and 0 to exit:");
scanf("%d",&main_exit);
clear_screen();
if (main_exit==1)
menu();
else
close();
}
}
void close(void)
{
clear_screen();
printf("\n\n\n\n\t\t\t\t\t\t\tTHANK YOU, BUILT BY SULEIMAN ZEILA!");
}
void menu(){
clear_screen();
printf("\n\n\n\n\t\t\t\t\t\t\tMAIN MENU");
printf("\n\n\t\t\t\t\t\tPRESS 1: TO CHECK YOUR BALANCE");
printf("\n\t\t\t\t\t\tPRESS 2: TO CREATE A NEW ACCOUNT");
printf("\n\t\t\t\t\t\tPRESS 3: TO CHECK CLIENTS RECORD");
printf("\n\t\t\t\t\t\tPRESS 4: TO UPDATE A RECORD");
printf("\n\t\t\t\t\t\tPRESS 5: TO MAKE A TRANSACTION");
printf("\n\t\t\t\t\t\tPRESS 6: TO DELETE AN ACCOUNT");
printf("\n\n\n\t\t\t\t\t\t\tWHAT IS YOUR CHOICE? ");
scanf("%d", &choice);
switch(choice){
case 1:
balance();
break;
case 2:
new_acc();
break;
case 3:
records();
break;
case 4:
edit();
break;
case 5:
transact();
break;
case 6:
erase();
}
}
void loading(void){
clear_screen();
printf("\n\n\n\t\t\t\t\t\tYOU ENTERED THE CORRECT PIN!");
printf("\n\n\n\n\n\n\n\n\t\t\t\t\t\t\tPLEASE WAIT");
int x=0;
while(x<3){
fordelay(100000000*1.1);
printf(".");
fordelay(100000000*1.9);
x++;
}
}
int main(){
int pin;
char correct_pin = 0000;
system("color 9B");
printf("\n\n\n\n\t\t\t\t\t\xB2\xB2\xB2\xB2\xB2\xB2 WELCOME TO FIRST COMMUNITY BANK \xB2\xB2\xB2\xB2\xB2\xB2");
printf("\n\n\n\t\t\t\t\t\tPLEASE ENTER YOUR PIN NUMBER: ");
scanf("%d",&pin);
if(pin == correct_pin){
system("cls");
printf("\n\n\n\n\t\t\t\t\t\xB2\xB2\xB2\xB2\xB2\xB2 WELCOME TO FIRST COMMUNITY BANK \xB2\xB2\xB2\xB2\xB2\xB2");
fordelay(100000000);
printf("\n\n\n\t\t\t\t\t\tYOU ENTERED THE CORRECT PIN!");
fordelay(100000000*0.8);
loading();
loading();
loading();
menu();
}
else{
clear_screen();
printf("\n\n\n\t\t\t\t\t\tYOU ENTERED A WRONG PIN!!!");
}
return 0;
}
|
C
|
#include <stdio.h>
int
main (int argc,
char *argv[])
{
int num1 = 10;
int num2 = 12;
int result1, result2;
result1 = (num1 == num2); // 동등 비교
result2 = (num1 <= num2); // 대소 비교
printf ("같은가? %d \n", result1);
printf ("같거나 작은가? %d \n", result2);
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <print.h>
#include <gets.h>
#include <fork.h>
#include <exit.h>
#include <execve.h>
#include <wait.h>
#include <pipe.h>
#include <close.h>
#include <dup.h>
#include <open.h>
#include <access.h>
#include <env.h>
#include <chdir.h>
#include <getcwd.h>
#include <umask.h>
#include "command.h"
#define CMDMAX 16
#define PATHMAX 1024
/**
* XXX Could be malloc'd when malloc would be implemented
*/
static struct cmd cmds[CMDMAX];
static char args[ARGMAX][LINESZ];
static int pipes[CMDMAX - 1][2];
struct builtin {
char *name;
int (*f)(struct cmd *c);
};
static int changedir(struct cmd *c);
static int getdir(struct cmd *c);
static int changeumask(struct cmd *c);
static int quit(struct cmd *c);
static struct builtin const builtins[] = {
{"cd", changedir},
{"pwd", getdir},
{"umask", changeumask},
{"quit", quit},
{NULL, NULL}
};
static inline void initcmd(struct cmd *c)
{
c->next = NULL;
c->in = STDIN_FILENO;
c->out = STDOUT_FILENO;
c->argc = 0;
}
static int getcmdstring(char c[LINESZ])
{
if(gets(c, LINESZ) == NULL) {
return 0;
}
return 0;
}
static int parsecmdstring(struct cmd **c, char s[LINESZ])
{
struct cmd *_c = &cmds[0];
char *ptr = s;
size_t i, j, k, len = strlen(s);
size_t p = 0;
initcmd(_c);
for(i = 0, j = 0, k = 0; i < len && j < ARGMAX - 1 && k < ARGMAX; ++i) {
switch(s[i]) {
case ' ':
case '\n':
/* New command's argument */
if(ptr != &s[i]) {
s[i] = '\0';
strcpy(args[k], ptr);
_c->argv[j] = args[k];
++k;
++j;
}
while(i + 1 < len && s[i + 1] == ' ')
++i;
ptr = s + i + 1;
break;
case '|':
/* Pipe between two commands */
if(ptr != &s[i]) {
s[i] = '\0';
strcpy(args[k], ptr);
_c->argv[j] = args[k];
++k;
}
if(pipe(pipes[p]) < 0)
return -1;
_c->out = pipes[p][1];
_c->next = _c + 1;
_c->argv[j] = (char *)NULL;
++_c;
initcmd(_c);
_c->in = pipes[p][0];
++p;
j = 0;
while(i + 1 < len && s[i + 1] == ' ')
++i;
ptr = s + i + 1;
break;
case '>':
/* Output to file */
if(ptr != &s[i]) {
s[i] = '\0';
strcpy(args[k], ptr);
_c->argv[j] = args[k];
++k;
}
while(i + 1 < len && s[i + 1] == ' ')
++i;
ptr = s + i + 1;
++i;
while(i < len && s[i] != ' ' && s[i] != '\n')
++i;
s[i] = '\0';
_c->out = open(ptr, O_WRONLY | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO);
if(_c->out < 0)
return -1;
i = len;
break;
case '<':
/* Input from file */
if(ptr != &s[i]) {
s[i] = '\0';
strcpy(args[k], ptr);
_c->argv[j] = args[k];
++k;
}
while(i + 1 < len && s[i + 1] == ' ')
++i;
ptr = s + i + 1;
++i;
while(i < len && s[i] != ' ' && s[i] != '\n')
++i;
s[i] = '\0';
_c->in = open(ptr, O_RDONLY | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO);
if(_c->in < 0)
return -1;
i = len;
break;
}
}
_c->argv[j] = (char *)NULL;
*c = &cmds[0];
return 0;
}
static int pathexist(char const *path)
{
if(access(path, X_OK) != 0)
return 0;
return 1;
}
static int forkcmd(struct cmd *c)
{
pid_t p;
int status;
p = fork();
switch(p) {
case -1:
return -1;
case 0:
if(c->out != STDOUT_FILENO) {
close(STDOUT_FILENO);
dup(c->out);
}
if(c->in != STDIN_FILENO) {
close(STDIN_FILENO);
dup(c->in);
}
execve(c->argv[0], c->argv, NULL);
exit(-1);
default:
if(c->out != STDOUT_FILENO)
close(c->out);
if(c->in != STDIN_FILENO)
close(c->in);
if(c->next != NULL)
runcmd(c->next);
waitpid(p, &status, 0);
}
return 0;
}
static int changedir(struct cmd *c)
{
if(c->argv[1] == NULL) {
/* TODO go to home dir */
return -1;
}
return chdir(c->argv[1]);
}
static int getdir(struct cmd *c)
{
char p[PATHMAX];
(void)c;
if(getcwd(p, PATHMAX) == NULL) {
print("Cannot get working dir\n");
return -1;
}
print(p);
print("\n");
return 0;
}
static int changeumask(struct cmd *c)
{
size_t i;
int nb;
mode_t m = 0;
char ms[6];
if(c->argv[1] == NULL) {
m = umask(0);
umask(m);
for(i = 0; i < 5 && m > 1; ++i) {
ms[i] = m % 8 + '0';
m /= 8;
}
ms[i] = '\0';
print(ms);
print("\n");
return 0;
}
for(i = 0; c->argv[1][i] != 0; ++i) {
nb = c->argv[1][i] - '0';
m = m * 8 + nb;
}
umask(m);
return 0;
}
static int quit(struct cmd *c)
{
(void)c;
exit(0);
return 0;
}
static int getcmdpath(struct cmd *c)
{
char *prog = c->argv[0];
char *path;
char fp[PATHMAX];
char *ptr, *begin;
size_t len;
size_t i;
if(prog[0] == '.' || prog[0] == '/')
return 0;
for(i = 0; builtins[i].name != NULL; ++i) {
if(strcmp(prog, builtins[i].name) == 0) {
c->f = builtins[i].f;
return 0;
}
}
c->f = forkcmd;
path = getenv("PATH");
if(path == NULL)
return -1;
begin = path + sizeof("PATH=") - 1;
for(ptr = begin; *ptr != '\0'; ++ptr) {
if(*ptr != ':')
continue;
len = ptr - begin;
if(len >= PATHMAX - 1)
return -1;
strncpy(fp, begin, len);
fp[len] = '/';
fp[len + 1] = '\0';
strncat(fp, prog, PATHMAX - 1);
if(pathexist(fp)) {
strcpy(prog, fp);
return 0;
}
begin = ptr + 1;
}
return -1;
}
int getcmd(struct cmd **c)
{
int ret;
char s[LINESZ];
ret = getcmdstring(s);
if(ret < 0)
return ret;
return parsecmdstring(c, s);
}
int runcmd(struct cmd *c)
{
if(c->argv[0] == NULL)
return -1;
getcmdpath(c);
return c->f(c);
}
|
C
|
#define ERROR(msg) \
fprintf(stderr, "ERROR: %s\n", msg); \
fprintf(stderr, "Line %i of function %s in file %s\n", __LINE__, __func__, __FILE__); \
exit(EXIT_FAILURE);
struct str_t {
char* start;
char* end;
};
struct str_offs {
size_t start;
size_t end;
};
void stringPrint ( char* chrs, str_offs s, FILE* fout=stdout, int nchars=10 ) {
int n = s.end - s.start;
int i = 0;
int p = 0;
for (p=0; p<nchars-n; p++)
fputc (' ', fout );
for (; p<nchars; p++,i++)
fputc ( chrs[s.start+i], fout );
}
|
C
|
#include<avr/io.h>
#define F_CPU 8000000UL
#include <util/delay.h>
#define RS 6 //PD6
#define EN 7 //PD7
#define databits PORTC //lower nibble
#define row1 cmd(0x80)
#define row2 cmd(0xc0)
void adc_init()
{
//select AVCC reference voltage , left alignment of data and ADC4
ADMUX=((1<<REFS0)|(1<<ADLAR)|(1<<MUX2));
//enable ADC, set prescaler to divide the clock by 64 and auto triggering mode
ADCSRA=((1<<ADEN)|(1<<ADFR)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0));
}
void conversion()
{
//start conversion
ADCSRA|=(1<<ADSC);
}
void port_init()
{
DDRC = 0xcf;
DDRD = (1 << RS)|(1 << EN);
}
void LCD_STROBE(void)
{
PORTD |= (1 << EN);
_delay_us(1);
PORTD &= ~(1 << EN);
}
void data(unsigned char c)
{
PORTD |= (1 << RS);
_delay_us(50);
databits = (c >> 4);
LCD_STROBE();
databits = (c);
LCD_STROBE();
}
void cmd(unsigned char c)
{
PORTD &= ~(1 << RS);
_delay_us(50);
databits = (c >> 4);
LCD_STROBE();
databits = (c);
LCD_STROBE();
}
void clear(void)
{
cmd(0x01);
_delay_ms(5);
}
void lcd_init()
{
_delay_ms(15);
cmd(0x30);
_delay_ms(1);
cmd(0x30);
_delay_us(100);
cmd(0x30);
cmd(0x28); // Function set (4-bit interface, 2 lines, 5*7Pixels)
cmd(0x28); // Function set (4-bit interface, 2 lines, 5*7Pixels)
cmd(0x0c); // Make cursorinvisible
clear(); // Clear screen
cmd(0x6); // Set entry Mode(auto increment of cursor)
}
void print(char *p)
{
while(*p) data(*p++);
}
void main()
{
char a[5],b[5];
int c,d;
DDRB=0x01;
_delay_ms(50);
TCCR1B|=(1<<CS10)|(1<<CS12);//prescale 1024
port_init();
adc_init();
lcd_init();
PORTB=0x01;//applying vcc to RC circuit
TCNT1=0x00;//start the timer
while(1)
{
conversion();
while(!( ADIF));
if(ADCH==161)//63% of the input voltage
{
c=TCNT1;
d=ADCH;
itoa(c,a,10);//integer to ASCII
itoa(d,b,10);//integer to ASCII
row1;
print(a);//showing timer value
row2;
print(b);//showing adc value
}
}
}
|
C
|
/********************************************************
*
* 采用shmget semget shmat方法对内存进行操作
*
* 假设一共有5块共享内存
* 每块内存100B
* key值从9900~9904
*
* 创建信号量集
* 第0个信号量定义为empty
* 第1个信号量定义为full
* 第2个信号量定义为mutex
*
* Written by Risan 2018-2
*******************************************************/
#include "library.h"
int main(){
int segs[MEM_MAX],semset_id;
int seg_id_buf_in,seg_id_buf_out;
//创建5块共享内存
segs[0] = shmget(MEM_KEY_0,MEM_SEG_SIZE,IPC_CREAT|0777);
segs[1] = shmget(MEM_KEY_1,MEM_SEG_SIZE,IPC_CREAT|0777);
segs[2] = shmget(MEM_KEY_2,MEM_SEG_SIZE,IPC_CREAT|0777);
segs[3] = shmget(MEM_KEY_3,MEM_SEG_SIZE,IPC_CREAT|0777);
segs[4] = shmget(MEM_KEY_4,MEM_SEG_SIZE,IPC_CREAT|0777);
//创建全局变量内存,存放指向内存的指针,和读取内存的指针
seg_id_buf_in = shmget(MEM_KEY_BUF_IN,MEM_SEG_SIZE,IPC_CREAT|0777);
seg_id_buf_out = shmget(MEM_KEY_BUF_OUT,MEM_SEG_SIZE,IPC_CREAT|0777);
int i;
for ( i= 0; i<MEM_MAX ; i++) {
if(segs[i] == -1){
err("shmget",1);
}
}
//创建3个信号量
semset_id = semget(SEMSET_KEY,nsems,0666|IPC_CREAT|IPC_EXCL);
if (semset_id == -1)
err("semget",3);
set_sem_value(semset_id,empty,5);
set_sem_value(semset_id,full,0);
set_sem_value(semset_id,mutex,1);
//声明内存内存指针
char* memptr_in;
char* memptr_out;
memptr_in = shmat(seg_id_buf_in,NULL,0); //获取内存指针
memptr_out = shmat(seg_id_buf_out,NULL,0);
strcpy(memptr_in,"0"); //写入“0”到内存当中
strcpy(memptr_out,"0");
printf("完成缓冲池和信号量的配置\n");
//检查信号量的值
printf("empty 是 %d,full 是 %d,mutex 是 %d,in 是 %s,out 是 %s\n",semctl(semset_id,0,GETVAL,0),semctl(semset_id,1,GETVAL,0),semctl(semset_id,2,GETVAL,0),memptr_in,memptr_out);
return 0;
}
|
C
|
#include "lexer_tr.h"
#include <stdio.h>
#include <assert.h>
#include <math.h>
#include "alloc.h"
#include "object.h"
#include "utils.h"
#include "primtype.h"
#include "symbol_tr.h"
#include "string_tr.h"
struct lexer_s
{
RHA_OBJECT;
object_t start_symbol; // start symbol of grammar rules
list_tr lhs; // left hand sides of grammar rules
list_tr rhs; // right hand sides of grammar rules
list_tr prec; // precedences of grammar rules
list_tr left; // left-associativeness of grammar rules
list_tr action; // syntax analysis table, part 'action'
list_tr jump; // syntax analysis table, part 'jump'
};
#define CHECK(x) CHECK_TYPE(lexer, x)
primtype_t lexer_type = 0;
extern primtype_t plain_type;
void lexer_init(void)
{
if (!lexer_type) {
lexer_type = primtype_new("lexer", sizeof(struct lexer_s), lexer_obj);
(void) lexer_new();
}
}
lexer_tr lexer_new()
{
lexer_tr p = object_new(lexer_type);
p->start_symbol = string_new(); // start symbol of grammar rules
p->lhs; // left hand sides of grammar rules
p->rhs; // right hand sides of grammar rules
p->prec; // precedences of grammar rules
p->left; // left-associativeness of grammar rules
p->action; // syntax analysis table, part 'action'
p->jump; // syntax analysis table, part 'jump'
return i;
}
lexer lexer_add(lexer_tr p, list_tr l)
{
CHECK(p);
return i->value;
}
lexer lexer_parse(lexer_tr i, string_tr)
{
CHECK(p);
return i->value;
}
string_t lexer_to_string(lexer_tr p)
{
CHECK(p);
//return sprint("%d", p);
}
#undef CHECK
|
C
|
#define _POSIX_SOURCE 700
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#define N 10
void* affiche(void* arg){
printf("Numero de creation : %d, numero d'identité : %d\n", (int)arg, (int)pthread_self());
pthread_exit((void*)(2*(int)arg));
return NULL;
}
int main(){
int status;
pthread_t tid[N];
int i,j;
int* pt_ind;
for(i=0; i<N; i++){
pt_ind = (int*)malloc(sizeof(i));
*pt_ind = i;
pthread_create(&tid[i], NULL, affiche, (void*)*pt_ind);
}
for(j=0; j<N; j++){
pthread_join(tid[j], (void**)&status);
printf("Numero d'identité : %d, Numero de terminaison %d\n",(int)tid[j], (int)status);
}
free(pt_ind);
return 0;
}
|
C
|
#include <stdio.h>
#include <assert.h>
/* This is an example of the "new" GNU portable assembly language.
It is a nice example of wonks gone wild. This really isn't very
useful any more. Don't be a wonk.
*/
int ADD(int i, int j)
{
int res = 0;
__asm (
"ADD %[result], %[input_i], %[input_j]"
: [result] "=r" (res)
: [input_i] "r" (i),
[input_j] "r" (j)
);
return res;
}
/* This is an example of non-portable inline assembly language.
Nothing could be simpler!
*/
int UDIV(int i, int j)
{
asm (
"udiv w0, w0, w1\n"
);
}
/* This is an example of non-portable inline assembly language.
Nothing could be simpler!
*/
int MOD(int i, int j)
{
asm (
"udiv w2, w0, w1\n"
"mul w2, w2, w1\n"
"sub w0, w0, w2\n"
);
}
int main(void)
{
int a = 1;
int b = 2;
int c = 0;
c = ADD(a,b);
printf("Result of %d + %d = %d\n", a, b, c);
c = UDIV(9,8);
printf("Result of %d / %d = %d\n", 9, 8, c);
assert(c == (9 / 8));
c = MOD(9,8);
printf("Result of %d MOD %d = %d\n", 9, 8, c);
assert(c == (9 % 8));
}
|
C
|
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <values.h>
#include <math.h>
#define K 7
#define RATEn 1
#define RATEd 2
typedef float TARGET_TYPE;
typedef unsigned long TARGET_INDEX;
int g[RATEd*K]= {1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1}; /*Matrice contenente le connessioni tra celle del registro e sommatori.*/
TARGET_INDEX bit;
int8_t* bit_aus;
TARGET_INDEX N_bit_aus;
int8_t* bit_out;
void conv_cod(int8_t* buffer,int8_t* codice)
{
int temp,sommatore,k;
for (sommatore=0;sommatore<RATEd;sommatore++)
{
temp=0;
for (k=0;k<K;k++)
temp=(temp+(buffer[K-k-1]&&g[sommatore*K+k]))%2;
codice[sommatore]=temp;
}
}
void viterbi_encode(TARGET_INDEX N, TARGET_TYPE bit_in[N])
{
N_bit_aus=((N+K-RATEn)+(N+K-RATEn)%RATEn)+K-RATEn;
bit_out = malloc((N_bit_aus-K+1)*sizeof(int8_t));
bit_aus= malloc(N_bit_aus*sizeof(int8_t));
for (bit=0;bit<K-RATEn;bit++)
bit_aus[bit]=0;
for (bit=0;bit<N;bit++)
bit_aus[bit+K-RATEn]=bit_in[bit];
for (bit=N+K-RATEn;bit<N_bit_aus;bit++)
bit_aus[bit]=0;
for (bit=0;bit<N_bit_aus-K+1;bit+=RATEn)
conv_cod(&bit_aus[bit],&bit_out[bit*RATEd/RATEn]);
free(bit_aus);
free(bit_out);
}
void main()
{
viterbi_encode(N, bit_in);
}
|
C
|
#include "main.h"
void ShowManagementMenu(void)
{
printf("\n\t===========MENU===========\n");
printf("\t0.Show Managament Menu\n");
printf("\t1.Add Book\n");
printf("\t2.Delete Book\n");
printf("\t3.Change Book\n");
printf("\t4.Find Book\n");
printf("\t5.Show Book list\n");
//printf("\t7.Borrow Book\n");
//printf("\t8.Return Book\n");
printf("\t9.Exit Program\n");
printf("\n");
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* conversions.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: coclayto <coclayto@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/19 17:54:23 by releanor #+# #+# */
/* Updated: 2020/04/28 16:54:21 by coclayto ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
int conversions(va_list args, char spec, t_struct *params)
{
if (spec == 'c' || spec == 'C')
type_char(args, params);
else if (spec == 's' || spec == 'S')
type_str(args, params);
else if (spec == 'p' || spec == 'P')
type_ptr(args, params);
else if (spec == 'd' || spec == 'i' || spec == 'D' || spec == 'I')
type_int(args, params);
else if (spec == 'u' || spec == 'U')
type_u(args, params, spec);
else if (spec == 'x' || spec == 'X')
type_hex(args, params, spec);
else if (spec == 'f' || spec == 'F')
type_float(args, params);
else if (spec == 'o' || spec == 'O')
type_oct(args, params);
return (conversions2(args, spec, params));
}
int conversions2(va_list args, char spec, t_struct *params)
{
if (spec == '%')
percent(params);
else if (spec == 'r')
create_nonprint_str(args, params);
else if (spec == 'b')
type_b(args, params);
else
bzerostruct(params, 0);
return (params->i);
}
|
C
|
/*
*
等号左边不能是表达式。只能是变量,否则编译报错
if add the () in SUB, then , it can succeed
*
*/
#include <stdio.h>
//#define SUB(x,y) x-y
#define SUB(x,y) (x-y)
#define ACCESS_BEFORE(element,offset,value) *SUB(&element,offset) =value
int main(int *argc,char **argv)
{
int i;
int array[10] = {1,2,3,4,5,6,7,8,9,10};
ACCESS_BEFORE(array[5],4,6);
for (i = 0;i < 10; ++i){
printf("%d\n",array[i]);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "linked_list.h"
struct _node {
int value;
struct _node *next;
};
typedef struct _node node;
struct _linked_list {
node *first;
};
linked_list *linked_list_new() {
linked_list *l = malloc(sizeof(linked_list));
l->first = NULL;
return l;
}
int linked_list_empty(linked_list *l) { return l->first == NULL; }
void linked_list_insert_end(linked_list *l, int value) {
node *new = malloc(sizeof(node)); // alocação de memória para um novo nó;
new->next = NULL; // próximo é NULL
new->value = value; // atribuição do valor
if (l->first == NULL) { // se a lista está vazia
l->first = new; // o primeiro elemento é criado
return; // interrompe a execução
}
node *element = l->first; // iteração sobre a lista
while (element->next != NULL) { // até que o próximo elemento seja NULL
element = element->next;
}
element->next = new; // guardamos o novo elemento no lugar dele
}
int linked_list_insert_at(linked_list *l, int value, int index) {
node *new = malloc(sizeof(node));
new->value = value;
new->next = NULL;
if (l->first == NULL) {
l->first = new;
return 0;
}
if (index == 0) {
new->next = l->first;
l->first = new;
return 0;
}
node *el = l->first;
int i = 0;
while (i < index - 1 && el->next != NULL) {
el = el->next;
i++;
}
node *next = el->next;
new->next = next;
el->next = new;
return i;
}
int linked_list_size(linked_list *l) {
node *current = l->first;
int size = 0;
while (current != NULL) {
size++;
current = current->next;
}
return size;
}
int linked_list_get(linked_list *l, int index) {
int i = 0; // contador
node *element = l->first; // iterador
while (i < index) { // supor que index é menor o tamanho da lista
element = element->next; // avança na list
i++; // avança no contador
}
return element->value; // devolve o elemento n posição 'i'
}
void linked_list_remove(linked_list *l, int index) {
if (index == 0) {
node *first = l->first;
l->first = first->next;
free(first);
first = NULL;
return;
}
int i = 0;
node *previous = l->first;
while (i < index - 1) {
previous = previous->next;
i++;
}
// o loop termina no elemento anterior ao que queremos remover
node *el = previous->next;
previous->next = el->next;
free(el);
}
void linked_list_delete(linked_list **_l) {
linked_list *l = *_l; // guardamos o endereço da lista
node *n = l->first; // começamos a iterar sobre a lista
while (n != NULL) { // até que o elemento seja NULL
node *next = n->next; // guardamos o endereço do próximo
free(n); // desalocamos o espaço do atual
n = next; // avançamos na lista
} //
free(l); // desalocamos a lista
*_l = NULL; // limpamos o endereço da variável local
}
void print_list(linked_list *list) {
if (linked_list_empty(list)) {
printf("[]\n");
} else {
printf("[");
int size = linked_list_size(list);
for (int i = 0; i < size - 1; i++) {
printf(" %d,", linked_list_get(list, i));
}
printf(" %d", linked_list_get(list, size - 1));
printf(" ]\n");
}
}
int main() {
linked_list *list = linked_list_new();
linked_list_insert_end(list, 2);
print_list(list);
linked_list_insert_end(list, 3);
print_list(list);
linked_list_insert_end(list, 5);
print_list(list);
linked_list_insert_end(list, 6);
print_list(list);
linked_list_insert_at(list, 4, 2); // inserir no meio
print_list(list);
linked_list_insert_at(list, 1, 0); // inserir no começo
print_list(list);
int size = linked_list_size(list);
linked_list_insert_at(list, size + 1, size); // inserir no fim
print_list(list);
linked_list_remove(list, 0); // remover do começo
print_list(list);
size = linked_list_size(list);
linked_list_remove(list, size - 1); // remover do fim
print_list(list);
linked_list_remove(list, 2); // remover do meio
print_list(list);
linked_list_delete(&list);
return 0;
}
|
C
|
#include "revert_string.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void RevertString(char *str)
{
char ch=' ';
int N=(strlen(str));
for (int i=0; i<N/2; i++)
{
ch=str[i];
str[i]=str[N-i-1];
str[N-i-1]=ch;
}
|
C
|
#include <stdlib.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include "fft_block.h"
#include "portaudio.h"
#define FFT_BLOCK_DEFAULT_FFT_LENGTH 32768
#define FFT_BLOCK_DEFAULT_SAMPLE_RATE 48000
/**
* One static instance of the fft block context is allowed
* It can be referenced by the global pointer _this
*
* Same goes for the gnuplot_ctrl. It can be referenced
* inside this source file using the _ctrl reference
**/
static fft_block_ctx gCTX;
static fft_block_ctx *_this = &gCTX;
static unsigned int b_initialized = 0;
/* ------------------------ Function Prototypes --------------------------- */
void hanning(double *samples, const unsigned length);
void convert_mag(const fftw_complex *in, double *out, const unsigned length);
/* ------------------------------------------------------------------------ */
int fft_block_init
(
unsigned int samplerate
,unsigned int fftlength
)
{
unsigned i;
if(b_initialized || samplerate != 48000)
{
return -1;
}
/* Avoid double initializing */
b_initialized = 1;
/* Init SIZES */
_this->num_samples = 0;
_this->pcm_length = fftlength;
_this->fft_length = fftlength / 2 + 1; /* real to complex concatenation */
/* Init PORTAUDIO */
_this->p_pcm_samples = (double *) malloc(sizeof(double) * _this->pcm_length);
_this->p_fft_mag = (double *) malloc(sizeof(double) * _this->fft_length );
/* Init FFTW */
_this->fft_out_cmplx = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * _this->fft_length );
_this->p_freq_bins = (double *) malloc(sizeof(double) * _this->fft_length );
_this->plan = fftw_plan_dft_r2c_1d(fftlength
,_this->p_pcm_samples
,_this->fft_out_cmplx
,FFTW_ESTIMATE
);
printf("%d",fftlength);
/** ------------------------------------------------------
* Fill Frequency bins
* ------------------------------------------------------
* Each bin will be: (Sample Rate) / (FFT Length) Hz wide
* ie: Sample Rate: 48 kHz, FFT Length: 8192
* 48000 / 8192 = 5.86 Hz
* ======================================================
**/
for(i = 0; i < _this->fft_length; ++i)
{
_this->p_freq_bins[i] = (i * ((float) FFT_BLOCK_DEFAULT_SAMPLE_RATE) / _this->pcm_length);
}
return 0;
}
void fft_block_close()
{
if(!b_initialized)
{
return;
}
/* Free dynamic memory. 4 malloc's == 4 free's */
free(_this->p_pcm_samples);
free(_this->p_fft_mag);
free(_this->p_freq_bins);
fftw_free(_this->fft_out_cmplx);
/* Now we can initialize again */
b_initialized = 0;
}
int fft_block_process
(
const float* input
,float *output
,unsigned long framesPerBuffer
,void *userData
)
{
unsigned long i;
int PeakValue = 40;
if(!b_initialized)
{ /* Trying to process before initializing */
return paAbort;
}
for(i = 0; i < framesPerBuffer; ++i)
{
/* Copy input to p_pcm_samples and passthrough to output */
*output++ = _this->p_pcm_samples[_this->num_samples++] = *input++;
/* Check if we've buffered enough samples */
if(_this->num_samples == _this->pcm_length)
{
/* Apply Hanning Window */
hanning(_this->p_pcm_samples, _this->pcm_length);
/* Perform FFT */
fftw_execute(_this->plan);
/* Convert complex numbers into magnitudes */
convert_mag(_this->fft_out_cmplx, _this->p_fft_mag, _this->fft_length);
for (int j =0;j<framesPerBuffer;j++) {
if (_this->p_freq_bins[j]<400 && _this->p_freq_bins[j]>250 && _this->p_fft_mag[j]>PeakValue) {
PeakValue = _this->p_fft_mag[j];
printf("Peak Value : %f, found at f = %f\n",_this->p_fft_mag[j],_this->p_freq_bins[j]);
FILE *f = NULL;
f = fopen("log_c.txt", "a");
if (!f)
exit(EXIT_FAILURE);
fprintf(f, "%f \n%f\n", _this->p_freq_bins[j], _this->p_fft_mag[j]);
fclose(f);
}
}
/* Wrap around to start of p_pcm_samples */
_this->num_samples -= _this->pcm_length;
}
}
/* Everything worked fine */
return paContinue;
}
/**
* Apply Hanning window to samples to smooth edges of sample blocks
* More info here: http://en.wikipedia.org/wiki/Hann_function
**/
void hanning
(
double *samples
,const unsigned length
)
{
unsigned i;
double mult;
int N = length - 1;
for (i = 0; i < length; ++i) {
/* Calculate Hanning multiplier w(n) and scale the sample by it */
mult = 0.5 * (1.0 - cos(2 * M_PI * i / N));
samples[i] = mult * samples[i];
}
}
/**
* Convert complex numbers to magnitudes. This is done
* by taking the square root of the sum of squares of
* real and imaginary parts. 20 * log(n) => dB
**/
void convert_mag
(
const fftw_complex *in
,double *out
,const unsigned length
)
{
unsigned int i;
double real, imag;
for(i = 0; i < length; ++i)
{
real = in[i][0];
imag = in[i][1];
/* Calculate magnitude */
out[i] = 20.0f * log(sqrt(real*real + imag*imag));
}
}
|
C
|
#include "holberton.h"
#include <stdio.h>
/**
* print_diagsums - reset
* @a: int
* @size: int
* Return : char return the size of the char.
**/
void print_diagsums(int *a, int size)
{
int i, ii;
int o = 0;
int sum = 0;
int sum2 = 0;
for (i = 0; i < size; i++)
{
for (ii = 0; ii < size; ii++)
{
if (i == ii)
{
sum = sum + a[o];
}
if ((i + ii) == (size - 1))
{
sum2 = sum2 + a[o];
}
o++;
}
}
sum2 = sum;
printf("%d, %d\n", sum, sum2);
}
|
C
|
/*****************************************************************************/
/* */
/* FTPUT.c */
/* "The Project Utility Functions: ftput()" */
/* */
/*****************************************************************************/
/* */
/* Description: */
/* */
/* ftput() converts a double-precision floating-point number to ASCII and */
/* displays it right justified in field of specified width, with */
/* specified decimal places. */
/* */
/*****************************************************************************/
#include "STDDEFS.h"
#include "PROJUTIL.h"
void ftput( row, col, double_val, dec_place, buf, field_len )
short row, col;
double double_val; /* value to be displayed */
short dec_place, field_len; /* decimal places and length of field */
char buf[];
{
char* fcvt(); /* fcvt() returns a pointer to a temporary string buffer. */
short dec, sign; /* pointers to decimal and sign returned from fcvt() */
short pos; /* position counter for "for" loop */
/*****************************************************************************/
/* Copy contents of temporary string buffer to buf. */
/*****************************************************************************/
strcpy( buf, fcvt( double_val, dec_place, &dec, &sign ) );
/*****************************************************************************/
/* Move digits on right of decimal point and '\0' one place to right and */
/* insert decimal point. */
/*****************************************************************************/
for( pos = strlen( buf ); pos >= dec; --pos )
{
buf[ pos + 1 ] = buf[ pos ];
}
buf[ dec ] = '.';
strrjust( buf, field_len );
tput( row, col, buf );
}
|
C
|
void complement(char chain[])
{
int j;
for(j=0;j<strlen(chain);j++){
if(chain[j]=='A'){
chain[j]='T';
}else if(chain[j]=='T'){
chain[j]='A';
}else if(chain[j]=='C'){
chain[j]='G';
}else if(chain[j]=='G'){
chain[j]='C';
}
}
}
int main()
{
int n;
char chain[256];
int i,j;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%s",chain);
complement(chain);
printf("%s\n",chain);
}
return 0;
}
|
C
|
#include "lists.h"
/**
* pop_listint - Return the value at the top of the list and free the node
* @head: The top of the list
* Return - The value stored in the node
*/
int pop_listint(listint_t **head)
{
listint_t *helper;
int value;
if (*head == NULL)
return (0);
helper = *head;
value = (*head)->n;
*head = (*head)->next;
free(helper);
return (value);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "arraylist.h"
typedef struct arraylist list_t;
void test1(int);
int main(int argc, char **argv)
{
int default_size = 4;
test1(default_size);
return 0;
}
void test1(int default_size)
{
list_t l = new_list(default_size);
printf("%d, %ld, %p\n",
l.size, l.capacity, l.arr);
int i;
for (i = 0; i <= default_size; i++) {
printf("adding %d\n", i);
int tmp = i;
add(&l, &tmp);
}
printf("capacity, size = %ld, %d\n", l.capacity, l.size);
for (i = 0; i <= default_size; i++) {
printf("%d ", *(int *)l.arr[i]);
}
printf("\n");
printf("removed elem: %d\n", *(int *)remove_by_index(&l, 2));
for (i = 0; i < l.size; i++) {
printf("%d ", *(int *)l.arr[i]);
}
printf("\n");
free_list(&l);
}
|
C
|
#include "config.h"
#include "batteryRead.h"
extern bool isLowBattery()
{ /* Returns 1 for low, 0 for OK */
return (bool)((consecutiveLowReadings >= 3 ? 1 : 0) || low_bat_flag); // lowReadings count is for smoke daughterboard, low batt flag is for motherboard
}
extern void batteryTest()
{
if (isLowBattery())
return; // Once battery is detected low, it stays low
startReadingFVR();
while (!isFVReadDone()); // Spin for ~100us
uint16_t voltage = (uint16_t)getVoltage();
ADCON1 = 0;
ADCON0bits.ADON = 0; // Disable Analog
FVRCONbits.FVREN = 0; // Disable FVR
if (voltage >= lowVoltageThr)
{
if (consecutiveLowReadings < 3)
consecutiveLowReadings ++;
else
consecutiveLowReadings = 0;
}
return;
}
static void startReadingFVR()
{
FVRCONbits.FVREN = 0b1; // enable fvr
while(!FVRCONbits.FVRRDY); // spin until ready
ADCON1bits.ADPREF = 0b00; // read fixed voltage reg
ADCON1bits.ADCS = 0b100; // Fosc/4 for a 1Mhz clock is in the recommended range
// See table 16-1 on page 154
ADCON1bits.ADFM = 0b1; // result is right justified in ADRESH
ADCON0bits.CHS = 0b11111; //FVR Buffer 1
ADCON0bits.ADON = 1; // enable analog
__delay_us(20); // this setup delay is necessary for the ADC hardware
// start read
ADCON0bits.GO = 1;
}
static bool isFVReadDone()
{
return (bool)!ADCON0bits.GO_nDONE;
}
static uint16_t getVoltage()
{
uint8_t lo = ADRESLbits.ADRESL;
uint8_t hi = (uint8_t)(ADRESHbits.ADRESH & 0x03);
uint16_t result = (uint16_t)((hi << 8) | (lo & 0xFC)); // We only care about 8 MSB in this 10-bit measurement
return result;
}
|
C
|
#include "confile.h"
//---------------------------------------------------------------------------
char* getParameterValue(char *line)
{
if ( line == NULL ) return NULL;
char *p = strchr(line, '=');
if( p==NULL )
return NULL;
p++;
if( *p != '\"' )
return NULL;
p++;
char *p_end = strchr( p, '\"' );
if( p_end == NULL )
return NULL;
*p_end = 0;
return p;
}
char* getParameterName(char *line)
{
if ( line == NULL ) return NULL;
char *p = strchr(line, '=');
if( p==NULL ) return NULL;
*p = 0;
return line;
}
char* read_config(char *ConName,char* value)
{
FILE *fp=NULL;
char buffer[1024];
char *ptr_ParameterName=NULL, *ptr_ParameterValue=NULL;
memset(buffer, 0, sizeof(buffer));
if((fp=fopen(CONFIG_FILE,"r"))==NULL)
{
return NULL;
}
while( fgets(buffer,180,fp)!=NULL )
{
if( buffer[0]=='\0'
|| buffer[0]=='\n'
|| buffer[0]=='#'
|| buffer[0]=='%'
|| buffer[0]==';' ) continue;
if( buffer[(int)strlen(buffer)-1]==10 )
buffer[strlen(buffer)-1]=0;
ptr_ParameterValue = getParameterValue(buffer);
ptr_ParameterName = getParameterName(buffer);
if(ptr_ParameterName==NULL)
continue;
if( strcmp( ptr_ParameterName,ConName) == 0 )
{
strcpy(value,ptr_ParameterValue );
fclose(fp);
return value;
}
else//wrong para
{
continue;//read the next line
}
}
fclose(fp);
return NULL;
}
|
C
|
// Benötige Bibliotheken
#include <msp430.h>
#include <stdint.h>
// Eigenen Header-Datei
#include "patterns.h"
// Globale Variablen
extern const uint8_t patterns[] = { 0x81, 0x42, 0x24, 0x18, 0x3c, 0x66, 0xc3 };
extern const uint8_t patterns_length = 7;
// Lokale Variablen
static const uint8_t *pattern_pointer;
// Prototypen lokaler Funktionen
static void set_output(uint8_t pattern);
// Globale Funktionen
void patterns_init() {
P1DIR = 0xFF; // Alle Pin als Ausgänge
P1OUT = 0x00; // Alle Ausgänge auf Low
pattern_pointer = patterns;
}
void patterns_show() {
set_output(*pattern_pointer);
pattern_pointer++;
if (pattern_pointer >= patterns + patterns_length) {
pattern_pointer = patterns;
}
__delay_cycles(200000);
}
// Lokale Funktionen
static void set_output(uint8_t pattern) {
P1OUT = pattern;
}
|
C
|
/**
* @file pio_insper.h
* @author Rafael Corsi
* @date 22/3/2016
* @brief Funções para configurar o PIO do SAME70
*/
#ifndef PIO_INSPER_H
#define PIO_INSPER_H
/*****************
* Includes
*****************/
/**
* @brief STDINT possui as definições dos tipos de variáveis
* e constantes
*/
#include <stdint.h>
/**
* @brief Inclui as definições prévias do uc em uso
*/
#include <same70_xplained.h>
/*****************
* Defines
*****************/
/**
* Esses defines serão utilizados para configurar
* o modo de operação dos I/Os, quando em modo
* de entrada
*/
/* Default pin configuration (no attribute). */
#define PIO_DEFAULT (0u << 0)
/* The internal pin pull-up is active. */
#define PIO_PULLUP (1u << 0)
/* The internal glitch filter is active. */
#define PIO_DEGLITCH (1u << 1)
/* The pin is open-drain. */
#define PIO_OPENDRAIN (1u << 2)
/* The internal debouncing filter is active. */
#define PIO_DEBOUNCE (1u << 3)
/*****************
* PROTOTYPES
*****************/
/**
* \brief Configure one or more pin(s) of a PIO controller as outputs, with
* the given default value.
*
* \param p_pio Pointer to a PIO instance.
* \param ul_mask Bitmask indicating which pin(s) to configure.
* \param ul_default_level Default level on the pin(s).
* \param ul_pull_up_enable Indicates if the pin shall have its pull-up
* activated.
*/
void _pio_set_output( Pio *p_pio,
const uint32_t ul_mask,
const uint32_t ul_default_level,
const uint32_t ul_pull_up_enable);
/**
* \brief Configure one or more pin(s) or a PIO controller as inputs.
* Optionally, the corresponding internal pull-up(s) and glitch filter(s) can
* be enabled.
*
* \param p_pio Pointer to a PIO instance.
* \param ul_mask Bitmask indicating which pin(s) to configure as input(s).
* \param ul_attribute PIO attribute(s).
*/
void _pio_set_input( Pio *p_pio,
const uint32_t ul_mask,
const uint32_t ul_attribute);
/**
* \brief Configure PIO internal pull-up.
*
* \param p_pio Pointer to a PIO instance.
* \param ul_mask Bitmask of one or more pin(s) to configure.
* \param ul_pull_up_enable Indicates if the pin(s) internal pull-up shall be
* configured.
*/
void _pio_pull_up( Pio *p_pio,
const uint32_t ul_mask,
const uint32_t ul_pull_up_enable);
/**
* \brief Configure PIO pin internal pull-down.
*
* \param p_pio Pointer to a PIO instance.
* \param ul_mask Bitmask of one or more pin(s) to configure.
* \param ul_pull_down_enable Indicates if the pin(s) internal pull-down shall
* be configured.
*/
void _pio_pull_down( Pio *p_pio,
const uint32_t ul_mask,
const uint32_t ul_pull_down_enable);
/**
* \brief Set a high output level on all the PIOs defined in ul_mask.
* This has no immediate effects on PIOs that are not output, but the PIO
* controller will save the value if they are changed to outputs.
*
* \param p_pio Pointer to a PIO instance.
* \param ul_mask Bitmask of one or more pin(s) to configure.
*/
void _pio_set( Pio *p_pio,
const uint32_t ul_mask);
/**
* \brief Set a low output level on all the PIOs defined in ul_mask.
* This has no immediate effects on PIOs that are not output, but the PIO
* controller will save the value if they are changed to outputs.
*
* \param p_pio Pointer to a PIO instance.
* \param ul_mask Bitmask of one or more pin(s) to configure.
*/
void _pio_clear( Pio *p_pio,
const uint32_t ul_mask);
/**
* \brief Return 1 if one or more PIOs of the given Pin are configured to
* output a high level (even if they are not output).
* To get the actual value of the pin, use PIO_Get() instead.
*
* \param p_pio Pointer to a PIO instance.
* \param ul_mask Bitmask of one or more pin(s).
*
* \retval 1 At least one PIO is configured to output a high level.
* \retval 0 All PIOs are configured to output a low level.
*/
uint32_t _pio_get_output_data_status(const Pio *p_pio,
const uint32_t ul_mask);
#endif
|
C
|
/*
** show_alloc_mem.c for show_alloc_mem in /home/dupard_e/rendus/PSU_2015_malloc
**
** Made by Erwan Dupard
** Login <dupard_e@epitech.net>
**
** Started on Fri Jan 29 15:27:29 2016 Erwan Dupard
** Last update Fri Feb 12 14:19:13 2016 Barthelemy Gouby
*/
#include "ressources.h"
t_block *g_data;
/* void show_alloc_mem() */
/* { */
/* t_block *iterator; */
/* int i = 0; */
/* printf("break : %p\n", sbrk(0)); */
/* iterator = g_data; */
/* while (iterator) */
/* { */
/* printf("%p - %p : %lu bytes\n", */
/* iterator->data, */
/* (iterator->next ? iterator->next : sbrk(0)), */
/* iterator->size); */
/* iterator = iterator->next; */
/* i++; */
/* } */
/* } */
void show_alloc_mem()
{
t_block *iterator;
int i = 0;
printf("break : %p\n", sbrk(0));
iterator = g_data;
while (iterator)
{
printf("block at %p data from %p to %p : %lu bytes free:%i\n",
iterator,
iterator->data,
iterator->data + iterator->size - 1,
iterator->size,
iterator->free);
iterator = iterator->next;
i++;
}
printf("heap size: %li\n", (char*)sbrk(0) - (char*) g_data);
printf("maybe: %li\n", (char*) g_last->data - (char*) g_data + g_last->size);
printf("heap end: %p\n", sbrk(0));
printf("expected heap end: %p\n", g_last->data + g_last->size);
}
|
C
|
#ifndef LIST_MOVES_H
#define LIST_MOVES_H
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
typedef struct
{
uint8_t row;
uint8_t col;
} Position;
typedef struct
{
Position start;
Position end;
} Move;
typedef struct node
{
Move move;
struct node *next;
} node_t;
void printList(node_t *n);
void push(node_t **head_ref, Move move);
void insertAfter(node_t *prev_node, Move move);
void append(node_t **head_ref, Move move);
void appendList(node_t **head_ref, node_t **tail);
void sizeList(node_t* moves, int* size);
#endif
|
C
|
#ifndef _RBTREE
#define _RBTREE
#define RED 0
#define BLACK 1
typedef struct _rbnode{
char color;
char *word, *mean;
struct _rbnode *parent, *left, *right;
}rbnode;
typedef struct {
rbnode *root , *nil;
}rbtree;
int rbtree_init(rbtree *t);
void rbtree_print(rbtree *t);
rbnode *rbtree_search(rbtree *t, rbnode *x, char* word);
rbnode *rbtree_begin(rbtree *t);
rbnode *rbtree_end(rbtree *t);
rbnode *rbtree_next(rbtree *t, rbnode *x);
rbnode *rbtree_prev(rbtree *t, rbnode *x);
void *rbtree_insert(rbtree *t, rbnode *x, char* word, char* mean);
void *rbtree_erase(rbtree *t, rbnode *x, char* word);
void *rbtree_free(rbtree *t);
#endif
|
C
|
/********** Exercicio 2 **********/
#include <stdio.h>
#include <sys/shm.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
int main (void) {
int seg;
char *memo;
char msgIN[80];
printf("Digite a mensagem: \n");
scanf("%s", msgIN);
seg = shmget (8752, sizeof(int) * 80, IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
if (seg == -1) {
printf("Erro\n");
return -1;
}
memo = (char*) shmat(seg,0,0);
// msg : mem compartilhada / msgIN : memoria dos sistema
sprintf(memo, msgIN);
shmdt(memo);
return 0;
}
/*
Explicação:
Ao alocarmos a memória compartilhada (“shmget”) e atribuirmos sua chave para
8752, tudo o que salvamos naquela memória fica gravado, mesmo após liberar a
memória (shmdt), porém não podemos usar o comando “shmctl” pois dessa forma
iríamos desalocar a memória compartilhada e, como vamos usá-la no programa
seguinte, não faria sentido desaloca-la.
Execução e saída:
Digite a mensagem:
Hello!
*/
|
C
|
#pragma once
#include <gsl/gsl_sf_zeta.h>
#include <cmath>
double real_trigamma_cmplxarg(double x, double y, int m, int l){
//compute the real part of the trigamma function at z = x + iy using
//my accelerated series formula
//argument should have positive real part (x > 0)
//m gives the number of zeta function terms to use
//l gives the number of terms to use in the residual series
double result = 0;
//if x is small, the result will be large and thus, inaccurate. Use the
//polygamma shift formula to give a larger value of x for the computation
if(x < 1000){
return ((x*x - y*y)/(x*x + y*y)/(x*x + y*y)) + real_trigamma_cmplxarg(x + 1, y, m, l);
}
else{
double phase, ypow = 1.0, xpow, denom;
//compute finite sum of Hurwitz zeta functions
for (int i = 1; i < m; ++i){
phase = 2*(i/2) == i ? -1.0 : 1.0;
result += phase*(2*i - 1)*ypow*gsl_sf_hzeta(2*i, x);
ypow = ypow*y*y;
}
//compute the infinite sum of residuals
phase = 2*(m/2) == m ? 1.0 : -1.0;
for (int n = 0; n < l; ++n){
xpow = pow(x + n, 2*m);
denom = ((x + n)*(x + n) + y*y)*((x + n)*(x + n) + y*y);
result += phase*ypow*((2*m - 1)*y*y + (2*m + 1)*(x + n)*(x + n)) / xpow / denom;
}
return result;
}
}
|
C
|
#include <glib.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include "shell_data.h"
/*
Internal function that returns the index of cpid in garr
*/
static int get_garray_index(GArray* garr, pid_t cpid);
/*
Initializes sd.
Must be the first function called before sd is used.
*/
void shell_data_init(struct shell_data *sd)
{
sd->num_com = 0;
sd->pwd = NULL;
shell_data_update_pwd(sd);
sd->bakgnd_proc = g_array_new(true, true, sizeof(pid_t));
}
/*
Updates the pwd for sd
*/
void shell_data_update_pwd(struct shell_data *sd)
{
if (sd->pwd) {
free (sd->pwd);
}
sd->pwd = strdup(getenv("PWD"));
}
/*
Adds a pid to the end of the array if it doesn't exist already.
*/
void shell_data_add_pid(struct shell_data *sd, pid_t cpid)
{
/* Make sure no one tries to add elements twice. */
if (get_garray_index(sd->bakgnd_proc, cpid) != -1)
g_array_append_vals(sd->bakgnd_proc, &cpid, 1);
}
/*
Removes cpid if it doesn't exist.
*/
void shell_data_rem_pid(struct shell_data *sd, pid_t cpid)
{
int index = get_garray_index(sd->bakgnd_proc, cpid);
if (index != -1) {
g_array_remove_index_fast(sd->bakgnd_proc, index);
}
}
void shell_data_clear(struct shell_data *sd)
{
}
/*
Inefficient algorithm as its complexity is O(N), but I don't forsee
thousands of elements for this homework assignment, so it should do just fine.
Returns -1 if element not found.
*/
int get_garray_index(GArray* garr, pid_t cpid)
{
int i;
for (i = 0; i < garr->len; ++i) {
if (g_array_index(garr, pid_t, i) == cpid) {
return i;
}
}
return -1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int peakElement(int *arr, int n)
{
int start = 0;
int end = n;
if(n==1)
return 0;
while(start<=end)
{
int mid = start + (end-start)/2;
if(mid==0 && arr[mid]>arr[mid+1])
return mid;
if(mid==n-1 && arr[mid]>arr[mid-1])
return mid;
if(arr[mid]>arr[mid-1] && arr[mid]>arr[mid+1])
return mid;
else if(arr[mid]<arr[mid-1])
end = mid-1;
else
start = mid + 1;
}
return -1;
}
int main()
{
int num;
printf("Enter the size of array : ");
scanf("%d",&num);
int *arr = (int *)malloc(num*sizeof(int));
printf("Enter array contents : ");
for(int i=0;i<num;i++)
scanf("%d",&arr[i]);
int index = peakElement(arr,num);
printf("Index of peak element : %d",index);
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
int main() {
int a, b;
a = 121;
b = 7;
printf("Resultado: %f\n", (float)a/b);
printf("- Raiz de %d: %lf\n", a, sqrt(a));
return 0;
}
|
C
|
#include <string.h>
#include "include/qqcompress.h"
unsigned char* qq_compress(unsigned char* sour, int* destlen, int sourlen)
{
unsigned long bufflen = 2048;
unsigned char* buff = (unsigned char*) sqlite3_malloc(bufflen * sizeof(unsigned char));
if (NULL == buff)
{
LOGE("qq_compress OOM");
return NULL;
}
memset(buff, 0, bufflen * sizeof(unsigned char));
int ret = compress(buff, &bufflen, sour, sourlen);
if (Z_OK != ret)
{
switch (ret)
{
case Z_MEM_ERROR:
LOGE("qq_uncompress failure: there was not enough memory");
break;
case Z_BUF_ERROR:
LOGE("qq_uncompress failure there was not enough room in the output buffer");
break;
default:
break;
}
free(buff);
return NULL;
}
if (NULL != destlen)
{
*destlen = bufflen;
}
return buff;
}
unsigned char* qq_uncompress(unsigned char* sour, int* destlen, int sourlen)
{
unsigned long bufflen = 2048;
unsigned char* buff = (unsigned char*) sqlite3_malloc(bufflen * sizeof(unsigned char));
if (NULL == buff)
{
LOGE("qq_uncompress OOM");
return NULL;
}
memset(buff, 0, bufflen * sizeof(unsigned char));
int ret = uncompress(buff, &bufflen, sour, sourlen);
if (Z_OK != ret)
{
switch (ret)
{
case Z_MEM_ERROR:
LOGE("qq_uncompress failure: there was not enough memory");
break;
case Z_BUF_ERROR:
LOGE("qq_uncompress failure: there was not enough room in the output buffer");
break;
case Z_DATA_ERROR:
LOGE("qq_uncompress failure: the input data was corrupted or incomplete");
break;
default:
break;
}
free(buff);
return NULL;
}
if (NULL != destlen)
{
*destlen = bufflen;
}
return buff;
}
|
C
|
#include <stdio.h>
main() {
/* Initialise a double precision floating point, larger than the previous long */
double nc;
/* This program would break if it was a while loop with no input so we're using a for loop */
/* Starting at 0, while EOF hasn't been received, keep incrementing nc by 1 */
for (nc = 0; getchar() != EOF; ++nc)
; /* Since the loop logic is all we need, we can leave the loop body empty! */
/* The standalone semicolon actually returns a null value. It's only on a seperate line for visibility */
/* Output the count telling printf to expect a float and display only 1 decimal place */
printf("%.0f\n", nc);
}
|
C
|
#include "qli.h"
void
Fputs(const char *s, FILE *stream){
if(EOF == fputs(s, stream)){
err_sys("fputs error");
}
}
long
Read(int fd, char *buf, size_t nbytes){
long n;
if(-1 == (n = read(fd, buf, nbytes))){
err_sys("read error");
}
return n;
}
void
Write(int fd, char *buf, size_t nbytes){
if(nbytes != write(fd, buf, nbytes)){
err_sys("write error");
}
}
FILE *
Fopen(const char *path, const char *mode){
FILE * file;
if(NULL == (file = fopen(path, mode))){
err_sys("fopen error");
}
return file;
}
void
Fclose(FILE *fp){
if(fclose(fp) != 0){
err_sys("fclose error");
}
}
int
read_line(FILE * file, char * str, long count){
if(NULL == str || NULL == file) return EOF;
if(NULL == fgets(str, count, file)) return EOF;
int len = strlen(str);
if('\n' == str[len-1]){
str[len-1] = 0;
return len-1;
}
return len;
}
long
length_end_with(FILE *file, char ch){
long len = 0;
fpos_t pos;
fgetpos(file, &pos);
while(!feof(file) && ch != fgetc(file)){
++len;
}
if(feof(file)){
len = -1;
}
fsetpos(file, &pos);
return len;
}
char *
copy_end_with(FILE *file, int ch){
char *str;
long i, len = length_end_with(file, ch);
if(len < 0){
return NULL;
}
str = Calloc(len + 1, sizeof(char));
for(i = 0; i < len; ++i){
str[i] = fgetc(file);
}
return str;
}
static int
index_of(const char *src, char c){
if(NULL == src){
return -1;
}
int i = 0;
while(src[i]){
if(c == src[i]){
return i;
}
++i;
}
return -1;
}
int
file_pos_char(FILE *file, long pos){
int ch;
long old = ftell(file);
fseek(file, pos, SEEK_SET);
ch = fgetc(file);
fseek(file, old, SEEK_SET);
return ch;
}
long
file_bytes(FILE *file){
long res, pos = ftell(file);
fseek(file, 0, SEEK_END);
res = ftell(file);
fseek(file, pos, SEEK_SET);
return res;
}
long
sunday(FILE *file, const char *pat){
if(NULL == file || NULL == pat){
return -1;
}
const long old = ftell(file);
int str_len = strlen(pat), next_index = 0;
char *read_str = Calloc(str_len, sizeof(char));
int i, temp;
while(!feof(file)){
read_str[next_index] = fgetc(file);
temp = next_index;
for(i = 0; i <= str_len; ++i, ++temp){
if(str_len == i){
int res = ftell(file) - str_len;
fseek(file, old, SEEK_SET);
return res;
}
if(pat[i] != read_str[(temp + 1) % str_len]){
break;
}
}
next_index = (next_index + 1) % str_len;
}
fseek(file, old, SEEK_SET);
return -1;
}
void
file_over(FILE *file, const char *str){
fseek(file, sunday(file, str)+strlen(str), SEEK_SET);
}
char *
copy_to_eof(FILE *file){
char *str;
long i, len = file_bytes(file) - ftell(file);
str = Calloc(len + 1, sizeof(char));
for(i = 0; i < len; ++i){
str[i] = fgetc(file);
}
return str;
}
FILE *
Tmpfile(){
FILE *f = tmpfile();
if(NULL == f){
err_sys("tmpfile error");
}
return f;
}
char *
copy_to_index(FILE *file, const long index){
long start = ftell(file);
if(index <= start){
return NULL;
}
long i;
char *str = Calloc(index-start+1, sizeof(char));
for(i = 0; i < index-start; ++i){
str[i] = fgetc(file);
}
fseek(file, start, SEEK_SET);
return str;
}
|
C
|
//4. Escreva uma função que devolva o comprimento (ou seja, o número de elementos) da fila.
|
C
|
/*
* frogjump.c
*
* Created on: Oct 27, 2018
* Author: foobar
*/
int num_jumps(int x, int y, int D) {
if (x > y) return 0;
if (D <= 0) return 0;
printf("start: %d, end: %d, hop-length: %d\n", x,y,D);
int net_distance = y - x;
if (D > net_distance) return 1;
int out = net_distance / D;
if (net_distance %D > 0) out++;
printf("net_distance: %d, hops: %d\n", net_distance, out);
return out;
}
|
C
|
#include<stdio.h>
#include<windows.h>
int VsizeXY = 3;
int speed = 1;
int vx = 17, vy = 7;
void gotoxy(int x, int y){
COORD coord, d;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void drawhud();
void drawboard(){
int hor, vert, y = 5, num;
int pxy;
pxy = 3 * VsizeXY;
for(vert = 0; vert < pxy+1; vert++){
gotoxy(15, y++);
for(hor = 0; hor < pxy+1; hor++){
if(vert % 3 == 0){
if(vert == 0 && hor == 0)
printf("%c", 0xC9);
else if(vert == 0 && hor == pxy)
printf("%c", 0xBB);
else if(vert == pxy && hor == 0)
printf("%c", 0xC8);
else if(vert == pxy && hor == pxy)
printf("%c", 0xBC);
else if(vert == 0 && hor % 3 == 0 && hor != 0 && hor != pxy)
printf("%c", 0xCB);
else if(vert == pxy && hor % 3 == 0 && hor != 0 && hor != pxy)
printf("%c", 0xCA);
else if(hor % 3 == 0)
printf("%c", 0xCE);
else
printf("%c", 0xCD);
}
else{
if(hor % 3 == 0)
printf("%c", 0xBA);
else
printf(" ");
}
}
printf("\n");
}
y = 3;
for(num = 1; num <= VsizeXY; num++){
gotoxy(13, y+=3);
printf("%2d", num);
}
y = 13;
for(num = 1; num <= VsizeXY; num++){
gotoxy(y+=3, 4);
printf("%d", num);
}
}
bool cheats = false;
char cheat = ' ';
bool pause = false;
void hiddencheat(int key){
switch(key){
case 'r': cheat = 'r'; break;
case 'b': cheat = 'b'; break;
case 'g': cheat = 'g'; break;
}
drawhud();
}
void drawhud(){
gotoxy(VsizeXY*3+18, 6);
printf("BLUE - %c", 2);
gotoxy(VsizeXY*3+18, 7);
printf("RED - %c", 3);
gotoxy(VsizeXY*3+18, 8);
printf("GREEN - %c", 1);
gotoxy(VsizeXY*3+18, 10);
printf("Controls:");
gotoxy(VsizeXY*3+18, 11);
printf("%c - w", 30);
gotoxy(VsizeXY*3+18, 12);
printf("%c - s", 31);
gotoxy(VsizeXY*3+18, 13);
printf("%c - a", 17);
gotoxy(VsizeXY*3+18, 14);
printf("%c - d", 16);
gotoxy(VsizeXY*3+18, 15);
printf("space");
gotoxy(VsizeXY*3+18, 17);
printf("Toggle Color - n");
gotoxy(VsizeXY*3+18, 31);
printf("fps: %5d", speed);
gotoxy(VsizeXY*3+18, 32);
if(cheats == true)
printf("c%c", cheat);
else if(cheat != true)
printf(" ");
gotoxy(vx, vy);
}
|
C
|
//#include "stdafx.h"
#include <stdio.h>
void initArray(int array[], int n);
int getMaxSequence(int array[], int n);
void main()
{
// put your code here
const int n = 10; //array dimension
int array[n];
initArray(array, n);
printf("Result is: %d\n", getMaxSequence(array, n));
}
void initArray(int array[], int n)
{
printf("Type %d integer numbers:\n", n);
for (int i = 0; i < n; i++)
{
scanf("%d", &array[i]);
}
}
int getMaxSequence(int array[], int n)
{
int temp = array[0];
int countTemp = 0;
int countMax = 0;
for(int i = 1; i < n; i++)
{
if(array[i] == temp)
{
countTemp++;
}
else
{
temp = array[i];
countTemp = 0;
}
if(countTemp > countMax)
{
countMax = countTemp;
}
}
return countMax;
}
|
C
|
/* =========================================================================
* First Come First Serve Scheduling
*
* DESCRIPTION
* ===========
* This is a simple C program to simulate the first come first serve
* scheduling. The purpose of this program is to calculate the waiting time,
* average waiting time and turn around time for a user input process queue.
*
* =========================================================================
*/
#include <stdio.h>
void fcfs(int ); /* to implement first come first serve scheduling */
void turn_around(int, int [], int []); /* to calculate turn around time */
int main()
{
static int size; /* size of the queue */
printf("Enter the total number of processes: ");
scanf("%d", &size);
if(size == 0) goto empty_queue; /* no process in the queue */
fcfs(size); /* first come first serve */
return 0; /* end of run */
empty_queue: printf("\nProcess queue is empty. End of run.\n");
}
/* fcfs : to implement first come first serve scheduling */
void fcfs(int size)
{
int i, j;float result=0.0;
int arrival[size], burst[size], waiting[size];
for(i=0; i<size; ++i) waiting[i]=0; /* initialize all values with 0 */
/* input the arrival time and burst time for each process */
for(i=0; i<size; ++i) {
printf("\nEnter arrival time for process %d : ", i+1);
scanf("%d", &arrival[i]);
printf("Enter burst time for process %d : ", i+1);
scanf("%d", &burst[i]);
}
/* first come first serve */
for(i=1; i<size; ++i) {
result=0.0;
for(j=0; j<i; ++j) result+= burst[j];
waiting[i]=result - arrival[i]; /* waiting time = starting time - arrival time */
}
/* print the waiting time */
printf("\nWaiting Time:\t");
for(i=0; i<size; ++i)
printf("%d\t", waiting[i]);
result=0.0;
/* average waiting time */
for(i=0; i<size; ++i) result+=waiting[i];
result=result/size;
printf("\nAverage Waiting Time:\t%f", result);
/* turn around time */
turn_around(size, burst, waiting);
printf("\n");
}
/* turn_around : to calculate turn around time for each process */
void turn_around(int size, int burst[], int waiting[])
{
int i;
int turn_around_time[size];
for(i=0; i<size; ++i)
turn_around_time[i]= burst[i] + waiting[i]; /* turn around time = burst time + waiting time */
printf("\nTurn Around Time:\t");
for(i=0; i<size; ++i)
printf("%d\t", turn_around_time[i]);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct NodeStruct{
struct NodeStruct* child;
int value;
};
typedef struct NodeStruct Node;
Node* reverse(Node* head);
void insert(Node* head, int val);
Node* newNode(int val);
int pop(Node* head);
Node* add(Node* h1, Node* h2);
Node* deepCopy(Node* list);
int main(int argc, char** argv) {
Node* h1 = newNode(3);
insert(h1, 5);
insert(h1, 5);
Node* h2 = newNode(2);
insert(h2, 1);
insert(h2, 1);
int p = 0;
//printf("%d\n", rev->value);
//printf("%d %d %d\n", rev->value, rev->child->value, rev->child->child->value);
Node* added = add(h1, h2);
//while((p = pop(added)) != added->value) printf("%d\n", p);
printf("%d\n", added->child->value);
}
Node* reverse(Node* list) {
Node* copy = deepCopy(list);
Node* ret = newNode(pop(copy));
while(copy->child != NULL)
insert(ret, pop(copy));
insert(ret, copy->value);
//printf("Test 3%d\n", ret->child->child->value);
return ret;
}
Node* deepCopy(Node* list) {
Node* curr = list;
Node* ret = newNode(curr->value);
while(curr->child) {
curr = curr->child;
insert(ret, curr->value);
}
return ret;
}
Node* add(Node* h1, Node* h2) {
Node* c1 = deepCopy(h1);
Node* c2 = deepCopy(h2);
Node* raw = NULL;
int carry = 0;
while(c1) {
int p1 = pop(c1);
int p2 = pop(c2);
int sum = p1 + p2 + carry;
printf("p1:%d p2:%d carry:%d sum:%d\n",p1, p2, carry, sum);
//Check for sum overflow
if(sum > 9) {
carry = 1;
sum = sum % 10;
} else {
carry = 0;
}
//Check if list was established and insert
if(raw == NULL) {
raw = newNode(sum);
} else {
insert(raw, sum);
}
//Check if end
if(c1->child == NULL) {
sum = c1->value + c2->value + carry;
if(sum > 9) {
insert(raw, sum%10);
insert(raw, 1);
} else {
insert(raw, sum);
}
break;
}
}
Node* rev = reverse(raw);
return rev;
}
Node* newNode(int val) {
Node* n = malloc(sizeof(Node*));
n->value = val;
n->child = NULL;
return n;
}
int pop(Node* n) {
if(n == NULL)
return -1;
if(n->child == NULL) {
int ret = n->value;
free(n);
return ret;
} else if (n->child->child == NULL) {
int ret = n->child->value;
n->child = NULL;
return ret;
}
return pop(n->child);
}
void insert(Node* n, int val) {
if(n->child == NULL) {
n->child=newNode(val);
return;
}
insert(n->child, val);
}
void delete(Node** n) {
free(*n);
}
|
C
|
#include<stdio.h>
int main(){
int first,second;
printf("Enter first number >");
scanf("%d",&first);
printf("Enter second number >");
scanf("%d",&second);
if(first > second){
printf("Maximum Number = %d\n",first);
printf("Minumum number = %d",second);
}else{
printf("Maximum Number = %d\n",second);
printf("Minumum number = %d",first);
}
return 0;
}
|
C
|
/**
*
* kk.c
*
* Ryan Wallace
* Computer Science 124
* Harvard University
* Programming Assingment 3
* April 23, 2016
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include <stdbool.h>
#include <limits.h>
#define LONGLONG_LEN 21
int parent (int i) {
return (i/2);
}
int left (int i) {
return 2 * i;
}
int right (int i) {
return 2 * i + 1;
}
void heapify (unsigned long long* H, int N, int* size) {
unsigned long long l = left (N);
unsigned long long r = right (N);
int largest;
if (l <= *size && H[l] > H[N]) {
largest = l;
}
else {
largest = N;
}
if (r <= *size && H[r] > H[largest]) {
largest = r;
}
if (largest != N) {
unsigned long long buffer = H[largest];
H[largest] = H[N];
H[N] = buffer;
heapify (H, largest, size);
}
return;
}
void insert (unsigned long long* H, unsigned long long v, int* size) {
*size += 1;
H[*size] = v;
int N = *size;
while (N != 1 && H[parent (N)] < H[N]) {
unsigned long long buffer = H[parent (N)];
H[parent (N)] = H[N];
H[N] = buffer;
N = parent (N);
}
return;
}
unsigned long long extract (unsigned long long* H, int* size) {
unsigned long long max = H[1];
H[1] = H[*size];
(*size)--;
heapify (H, 1, size);
return max;
}
unsigned long long KK (unsigned long long* A, int lines) {
// construct the Max-Heap
unsigned long long* H = calloc (lines + 1, sizeof (unsigned long long));
int* size = malloc (sizeof (int));
*size = 0;
for (int i = 1; i <= lines; i++) {
insert (H, A[i], size);
}
// perform the Karmarkar-Karp algorithm
while (*size > 1) {
unsigned long long max1 = extract (H, size);
unsigned long long max2 = extract (H, size);
insert (H, max1 - max2, size);
}
return (extract (H, size));
}
int main (int argc, char** argv) {
if (argc != 2) {
printf("use: ./kk inputfile\n");
return 1;
}
// reads in input file to A
int lines = 100;
char filename[512];
strcpy (filename, argv[1]);
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("error opening inputfile\n");
return 1;
}
unsigned long long A[lines + 1];
for (int line = 1; line <= lines; line++) {
char buffer[LONGLONG_LEN];
if (fgets (buffer, sizeof(buffer), fp) != NULL) {
A[line] = atoll(buffer);
}
else {
printf ("error reading inputfile\n");
return 1;
}
}
// Karmarkar-Karp
unsigned long long R = KK (A, lines);
printf("Residue: %llu\n", R);
return 0;
}
|
C
|
/* MEDIA ARITMETICA VS MEDIA PONDERATA
* Si realizzi un software capace di calcolare, utilizzando le funzioni,
* sia la media aritmetica che la media ponderata
* */
#include <stdio.h>
#include <stdlib.h>
float mediaAritmetica(float numeri[], int nNumeri){
float somma=0;
for (int i = 0; i < nNumeri; ++i) {
somma=somma+numeri[i];
}
return somma/nNumeri;
}
float mediaPonderata(float numeri[], float pesi[], int nNumeri){
float sommaPesata=0;
float sommaPesi=0;
for (int i = 0; i < nNumeri; ++i) {
sommaPesata=sommaPesata+numeri[i]*pesi[i];
sommaPesi=sommaPesi+pesi[i];
}
return sommaPesata/sommaPesi;
}
int main() {
printf("MEDIA ARITMETICA VS MEDIA PONDERATA\n");
int nNumeri;
printf("Quanti numeri si vogliono mediare? ");
scanf("%d", &nNumeri);
float numeri[nNumeri], pesi[nNumeri];
printf("\n --------INSERIMENTO NUMERI-------\n");
for (int i = 0; i < nNumeri; ++i) {
printf("Inserire numero da mediare: ");
scanf("%f",&numeri[i]);
printf("Inserire peso: ");
scanf("%f",&pesi[i]);
printf("\n");
}
printf("\n --------------RISULTATI----------\n");
printf("Media Ponderata: %f \n",mediaAritmetica(numeri,nNumeri));
printf("Media Aritmetica: %f \n",mediaPonderata(numeri,pesi,nNumeri));
system("pause");
return 0;
}
|
C
|
/*
* File: diskget.c
* Author: Siqi Li
*
* Created on March 19, 2015, 6:14 PM
*/
#include <stdio.h>
#include <stdlib.h>
#include "rootdir.h"
int main(int argc, char **argv) {
FILE *fp, *outf;
int size, cluster;
if (argc < 3) {
fprintf(stderr, "usage: diskget [IMA filename] [filename]\n");
return (EXIT_SUCCESS);
}
if ((fp = fopen(argv[1], "rb")) == NULL) {
perror(argv[1]);
return (EXIT_FAILURE);
}
if ((outf = fopen(argv[2], "wb")) == NULL) {
perror(argv[1]);
return (EXIT_FAILURE);
}
if (!rd_get_file_info_by_name(fp, argv[2], &size, &cluster)) {
puts("File not found.");
return (EXIT_SUCCESS);
}
rd_read_file(fp, cluster, size, outf);
fclose(fp);
fclose(outf);
return (EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int h,u,d,f;
double fatigue;
int i;
int stuff;
int distance;
scanf("%d%d%d%d",&h,&u,&d,&f);
while(h!=0)
{
distance=0;
i=-1;
fatigue=f;
fatigue=fatigue/100;
fatigue=u*fatigue;
fatigue=fatigue*1000;
stuff=fatigue;
do
{
i++;
if(u*1000-stuff*i>0)
{
distance=distance+u*1000-stuff*i;
}
if(distance>h*1000)
{
break;
}
distance=distance-d*1000;
}
while(distance<=h*1000&&distance>=0);
if(distance>0)
{
printf("success ");
}
else
{
printf("failure ");
}
printf("on day %d\n",i+1);
scanf("%d%d%d%d",&h,&u,&d,&f);
}
return 0;
}
|
C
|
#pragma once
#include "types.h"
#include "utils.h"
#include <math.h>
#include <float.h>
#include <lauxlib.h>
#define Vector_mt "vector"
#define VEC2_ZERO (vec2){ 0.0f, 0.0f }
#define MAT3_ZERO { { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f } }
#define MAT3_IDENTITY { { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }
#define NULL_RECT (rect2){0.0f, 0.0f, 0.0f, 0.0f}
#define EPSILON 0.0001f
inline float real_abs(float n) {
return (n > 0) ? n : -n;
}
inline float vec2_len(vec2 v) {
return sqrt(v[0] * v[0] + v[1] * v[1]);
}
inline void vec2_normalize(vec2 v) {
float len = vec2_len(v);
if (len > EPSILON) {
float invLen = 1.0f / len;
v[0] *= invLen;
v[1] *= invLen;
}
}
inline float vec2_dot(const vec2 a, const vec2 b) {
return a[0] * b[0] + a[1] * b[1];
}
inline float vec2_cross(const vec2 a, const vec2 b) {
return a[0] * b[1] + a[1] * b[0];
}
inline void transform_identity(mat3 t) {
memset(t, 0, sizeof(mat3));
t[0][0] = t[1][1] = t[2][2] = 1.0f;
}
inline void tranform_ortho(mat3 t, float left, float right, float bottom, float top) {
memset(t, 0, sizeof(mat3));
t[0][0] = 2.f / (right - left);
t[1][1] = 2.f / (top - bottom);
t[2][0] = -(right + left) / (right - left);
t[2][1] = -(top + bottom) / (top - bottom);
t[2][2] = -1.f;
}
inline void transform_mul(mat3 d, mat3 t, mat3 m) {
d[0][0] = (t[0][0] * m[0][0]) + (t[1][0] * m[0][1]) + (t[2][0] * m[0][2]);
d[1][0] = (t[0][0] * m[1][0]) + (t[1][0] * m[1][1]) + (t[2][0] * m[1][2]);
d[2][0] = (t[0][0] * m[2][0]) + (t[1][0] * m[2][1]) + (t[2][0] * m[2][2]);
d[0][1] = (t[0][1] * m[0][0]) + (t[1][1] * m[0][1]) + (t[2][1] * m[0][2]);
d[1][1] = (t[0][1] * m[1][0]) + (t[1][1] * m[1][1]) + (t[2][1] * m[1][2]);
d[2][1] = (t[0][1] * m[2][0]) + (t[1][1] * m[2][1]) + (t[2][1] * m[2][2]);
d[0][2] = (t[0][2] * m[0][0]) + (t[1][2] * m[0][1]) + (t[2][2] * m[0][2]);
d[1][2] = (t[0][2] * m[1][0]) + (t[1][2] * m[1][1]) + (t[2][2] * m[1][2]);
d[2][2] = (t[0][2] * t[2][0]) + (t[1][2] * m[2][1]) + (t[2][2] * m[2][2]);
}
inline void transform_set(mat3 t, float x, float y, float angle, float sx, float sy, float ox, float oy, float kx, float ky) {
float c = cosf(angle), s = sinf(angle);
// |1 x| |c -s | |sx | | 1 ky | |1 -ox|
// | 1 y| |s c | | sy | |kx 1 | | 1 -oy|
// | 1| | 1| | 1| | 1| | 1 |
// move rotate scale skew origin
t[0][0] = c * sx - ky * s * sy; // = a
t[0][1] = s * sx + ky * c * sy; // = b
t[1][0] = kx * c * sx - s * sy; // = c
t[1][1] = kx * s * sx + c * sy; // = d
t[2][0] = x - ox * t[0][0] - oy * t[1][0];
t[2][1] = y - ox * t[0][1] - oy * t[1][1];
t[0][2] = t[1][2] = 0.0f;
t[2][2] = 1.0f;
}
inline float residual(float p) {
return p - floor(p);
}
inline int overlap(rect2 a, rect2 b) {
return !((int)a[0] > (int)b[2]
|| (int)a[1] > (int)b[3]
|| (int)a[2] < (int)b[0]
|| (int)a[3] < (int)b[1]);
}
int openlib_Math(lua_State* L);
|
C
|
/* Sketch to read David Wind Vane
de ON7EQ Dec 2011
To disable interrupts:
cli(); // disable global interrupts
and to enable them:
sei(); // enable interrupts
NTC readout routine
http://arduino.cc/playground/ComponentLib/Thermistor2
===================================================================
Thermistor Schematic
===================================================================
(+5v ) ---- (10k-Resister) -------|------- (Thermistor) ---- (GND)
|
Analog Pin 'NTCpin'
===================================================================
DAVIS Vantage Pro & Vantage Pro 2 Wind Sensor (speed & direction
===================================================================
On RJ-45 plug terminals:
Black = pulse from anemometer. Connect to Digital 2 pin, and use a 4k7 resistor as pull up to + 5v.
use a 10 to 22nF capacitor from pin D2 to ground to debounce the reed switch of anemometer
Red = Ground
Green = Wiper of Wind direction vane - connect to A0. Use a 1 ... 10 µF / 16v capacitor between A0 and ground (observe C polarity) to avoid jitter
Yellow = + 5v (reference of potentiometer)
*/
// include EEPROM write - required to memorize antenna / band config.
#include <EEPROM.h>
#include <math.h>
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
int Direction ; // Wind direction
#define PotPin (A0) // define the input pin for the wind vane potentiometer
int PotValue = 0; // variable to store the value coming from the potentiometer
int DirCorr = 0; // Correction on direction ( - 360 to + 360)
#define CalPin (A1) // define the input pin to initiate direction calibration @ startup. Ground pin to calibrate
byte DirCorrB1 = 0; // 2 bytes of DirCorr
byte DirCorrB2 = 0;
volatile unsigned long RPMTops; // RPM tops counter in interrupt routine
volatile unsigned long ContactTime; // Timer to avoid conatct bounce in interrupt routine
float RPM; // RPM count
float TEMP; // Temp
#define RPMsensor (2) //The pin location of the anemometer sensor
#define NTCpin (A4) // Pin for NTC 10k
float temp = (0);
// build LCD specific characters 'degrees'
byte degree [8] = {
B00100,
B01010,
B00100,
B00000,
B00000,
B00000,
B00000,
};
// This function will calculate temperature from 10k NTC readout
double Thermister(int RawADC) {
double Temp;
Temp = log(((10240000/RawADC) - 10000));
Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
Temp = Temp - 273.15; // Convert Kelvin to Celcius
// Temp = (Temp * 9.0)/ 5.0 + 32.0; // Convert Celcius to Fahrenheit
return Temp;
}
////////////////////////////////////////////////////////////////////
void setup() {
// Clean EEPROM
// EEPROM.write (1, 0);
// EEPROM.write (2, 0);
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
lcd.clear();
// Print a message to the LCD.
lcd.print(" DAVIS Readout");
lcd.setCursor(0, 1);
lcd.print(" v2.0 de ON7EQ");
delay (2000);
// CALIBRATE if button depressed at startup !
if ((analogRead(CalPin)<512)) calibrate ();
// else retrieve CAL vales from EEPROM
DirCorrB1 = EEPROM.read(1);
DirCorrB2 = EEPROM.read(2);
DirCorr = (DirCorrB1) + (DirCorrB2);
// print screen template
lcd.clear();
// Print variables
lcd.setCursor(0, 0);
lcd.print("Dir ");
lcd.setCursor(12, 0);
lcd.print("Temp");
pinMode(RPMsensor, INPUT);
attachInterrupt(0, rpm, FALLING);
lcd.createChar(0, degree);
lcd.setCursor(7, 0);
lcd.write(0);
// speed
lcd.setCursor(0, 1);
lcd.print("Spd 0km/h");
}
/////////////////////////////////////////////////////////////////////////////////
void loop() {
// Wind Direction
PotValue = analogRead(PotPin); // read the value from the potmeter
Direction = map(PotValue, 0, 1023, 0, 359);
Direction = Direction + DirCorr + 3; // Correct for offset & 5° precision
convert: // Convert to 360°
if (Direction < 0) {
Direction = Direction + 360;
goto convert;
}
if (Direction > 360) {
Direction = Direction - 360;
goto convert;
}
if (Direction == 360) Direction = 0;
lcd.setCursor(4, 0); // print the value from the potmeter
if (Direction < 100) lcd.print("0");
if (Direction < 10) lcd.print("0");
lcd.print(((Direction/5)*5), DEC); // 5° precision is enough to print te direction value
lcd.setCursor(9, 0);
if ((Direction)<23) {
lcd.print(" N");
}
if ((Direction>22) && (Direction<68)) {
lcd.print("NE");
}
if ((Direction>67) && (Direction<113)) {
lcd.print(" E");
}
if ((Direction>112) && (Direction<158)) {
lcd.print("SE");
}
if ((Direction>157) && (Direction<203)) {
lcd.print(" S");
}
if ((Direction>202) && (Direction<247)) {
lcd.print("SW");
}
if ((Direction>246) && (Direction<292)) {
lcd.print(" W");
}
if ((Direction>291) && (Direction<337)) {
lcd.print("NW");
}
if ((Direction>336) && (Direction<=360)) {
lcd.print(" N");
}
// measure & print the temp
lcd.setCursor(11, 1);
TEMP = ((Thermister(1023 - analogRead(NTCpin))) + 0.0);
if (TEMP >= 0) lcd.print(" "); // If temp positive, print space, else a '-' will show up
if (abs(TEMP)<10) lcd.print(" ");
lcd.print(TEMP, DEC);
// measure RPM
RPMTops = 0; //Set NbTops to 0 ready for calculations
sei(); //Enables interrupts
delay (3000); //Wait 3 seconds to average
cli(); //Disable interrupts
// convert to km/h
if ((RPMTops >= 0) and (RPMTops <= 21)) RPM = RPMTops * 1.2;
if ((RPMTops > 21) and (RPMTops <= 45)) RPM = RPMTops * 1.15;
if ((RPMTops > 45) and (RPMTops <= 90)) RPM = RPMTops * 1.1;
if ((RPMTops > 90) and (RPMTops <= 156)) RPM = RPMTops * 1.0;
if ((RPMTops > 156) and (RPMTops <= 999)) RPM = RPMTops * 1.0;
// print the speed
lcd.setCursor(4, 1);
if (RPM < 100) lcd.print(" ");
if (RPM < 10) lcd.print(" ");
lcd.print(int(RPM), DEC);
}
//// This is the function that interrupt calls to measure RPM
void rpm () {
if ((millis() - ContactTime) > 15 ) { // debounce of REED contact. With 15ms speed more than 150 km/h can be measured
RPMTops++;
ContactTime = millis();
}
}
//// end of RPM measure
//// This is the function that calibrates the vane
void calibrate () {
lcd.setCursor(0, 1);
lcd.print("Hold to calibr !");
delay (2000); //Wait 2 second
if ((analogRead(CalPin)>512)) setup(); // CAL not really required ... abort !
lcd.setCursor(0, 1);
lcd.print("Now calibrating ... ");
delay (1000); //Wait 1 second
PotValue = analogRead(PotPin); // read the value from the potmeter
DirCorr = map(PotValue, 0, 1023, 359, 0);
lcd.setCursor(0, 1);
lcd.print("CAL value = ");
lcd.print(DirCorr, DEC);
lcd.print(" ");
delay (2000); //Wait 2 seconds
//
DirCorrB1 = DirCorr / 255;
if (DirCorrB1 == 1){
DirCorrB1 = 255;
DirCorrB2 = DirCorr - 255 ;
}
else {
DirCorrB1 = DirCorr;
DirCorrB2 = 0;
}
//
// DirCorrB1 = DirCorr;
// DirCorrB2 = 0;
EEPROM.write (1, DirCorrB1);
EEPROM.write (2, DirCorrB2);
wait:
lcd.setCursor(0, 1);
lcd.print("CAL OK - Release ! ");
if ((analogRead(CalPin)<512)) goto wait;
lcd.setCursor(0, 1);
lcd.print("Now rebooting... ");
delay (1000);
setup ();
}
|
C
|
/*
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2,2]
示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [4,9]
说明:
输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
我们可以不考虑输出结果的顺序。
进阶:
如果给定的数组已经排好序呢?你将如何优化你的算法?
如果 nums1 的大小比 nums2 小很多,哪种方法更优?
如果 nums2 的元素存储在磁盘上,磁盘内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/intersection-of-two-arrays-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
int compare(const void* a, const void* b)
{
int arg1 = *(const int*)a;
int arg2 = *(const int*)b;
if(arg1 < arg2)
return -1;
if(arg1 > arg2)
return 1;
}
int* intersect(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize)
{
int i = 0;
int j = 0;
int idx = 0;
int min = (nums1Size > nums2Size) ? nums2Size : nums1Size;
int* res = malloc(sizeof(int) * min);
qsort(nums1, nums1Size, sizeof(int), compare);
qsort(nums2, nums2Size, sizeof(int), compare);
while(i < nums1Size && j < nums2Size)
{
if(nums1[i] < nums2[j])
{
i++;
}
else if(nums1[i] > nums2[j])
{
j++;
}
else
{
res[idx] = nums1[i];
idx++;
i++, j++;
}
}
*returnSize = idx;
return res;
}
int main(void)
{
int a[] = {4, 9, 5};
int b[] = {9, 4, 9, 8, 4};
int* res;
int len;
res = intersect(a, sizeof(a) / 4, b, sizeof(b) / 4, &len);
for(int i = 0; i < len; i++)
{
printf("%d\t", res[i]);
}
return 0;
}
|
C
|
// ???를 대신할 수 있는 매개변수 선언을 추가해라.
// void ComplexFuncOne(???, ???) {.....}
// void ComplexFuncTwo(???, ???) {.....}
// int main(void) {
// int* arr1[3];
// int* arr2[3][5];
// int** arr3[5];
// int*** arr4[3][5];
//
// ComplexFuncOne(arr1, arr2);
// ComplexFuncTwo(arr3, arr4);
// return 0;
// }
void ComplexFuncOne(int** ar1, int* (*ar2)[5]);
void ComplexFuncTwo(int*** ar3, int*** (*ar4)[5])
|
C
|
#include <stdio.h>
#include <malloc.h>
int n = 0;
int mark = 0;
void BackBag(int *weights, int i, int T, int length, int *bag) {
if (T == 0) {
mark = 1;
int j = 0;
while (j < n - 1) {
printf("%d ", bag[j++]);
}
printf("%d\n", weights[i - 1]);
return;
}
else if (T < 0) { return; }
while (i < length && T >= 0) {
bag[n++] = weights[i];
BackBag(weights, i + 1, T - weights[i], length, bag);
n--;
i++;
}
}
int main()
{
int n, weight;
scanf("%d%d", &n, &weight);
int *weights, *bag;
weights = (int*)malloc(sizeof(int)*n);
bag = (int*)malloc(sizeof(int)*n);
int i = -1;
while (++i < n)
scanf("%d", &weights[i]);
BackBag(weights, 0, weight, n, bag);
if (!mark)
printf("No solution");
return 0;
}
|
C
|
////
// __| | | _ _| __ / __| \ |
// \__ \ __ | | / _| . |
// ____/ _| _| ___| ____| ___| _|\_|
//
// Copyright (c) 2017 Jacob Hauberg Hansen
//
// This library is free software; you can redistribute and modify it
// under the terms of the MIT license. See LICENSE for details.
//
#pragma once
#include <stdbool.h> // bool
#include <math.h> // fabsf
/**
* @brief Determine whether two floating point values are approximately equal.
*/
static inline
bool
z_fequal(float const a, float const b)
{
static double const precision = 1.0 / 2048;
return fabsf(b - a) < precision;
}
/**
* @brief Linearly interpolate between two values.
*/
static inline
float
z_lerp(float const a, float const b, float const t)
{
return (1.0f - t) * a + t * b;
}
static inline
double
z_lerpf(double const a, double const b, double const t)
{
return (1.0 - t) * a + t * b;
}
|
C
|
/*
* vd.cpp
*
* Created on: Sep 27, 2012
* Author: fabricio
*/
#include "vd.h"
//After calculating energy we should call for init method.
void vd_init(){
int i;
countVD=0;
countMax=0;
countReader=0;
countSample=0;
for (i=0; i<SUB_WINDOW_SIZE; i++) subWindowIn[i]=0.0;
}
//When either start or end is found, we should call this method to change the search.
void changeSearch(){
startEnd = !startEnd;
}
//When starting the algorithm we should reset the search in order to begin by searching the start of voice
void resetSearch(){
startEnd = 0;//false;
}
//When the start of voice is found we should call this method.
void setStart(){
startFound = 1;//true;
}
//When the end of voice is found we should call this method.
void setEnd(){
endFound = 1;//true;
}
/*Method used to reset the flag that indicates when we find the start of voice. It is normally called
when all the available samples are read*/
void resetStart(){
startFound = 0;//false;
}
//Method used to reset the flag that indicates when we find the end of voice.
void resetEnd(){
endFound = 0;//false;
}
//After reading all the available sample contained into startSample, this method should be called.
void sampStart(){
int i,k;
countStart=0;
for (i=0; i<START_TIME; i++){
for(k=0; k<SUB_WINDOW_SIZE; k++){
startSample[i][k]=0.0;
}
}
}
//After reading all the available sample contained into endSample, this method should be called.
void sampEnd(){
int i,k;
countEnd=0;
for (i=0; i<END_TIME; i++){
for(k=0; k<SUB_WINDOW_SIZE; k++){
endSample[i][k]=0.0;
}
}
}
//Avail is a flag to be set to true when samples are available.
void availSample(){
avail = 1; // true;
}
//This method sets avail flag to false.
void vd_resetAvail(){
avail = 0; //false;
}
int vd_checkSample(){
if(countReader==countMax){
vd_resetAvail();
}
return avail;
//check origin of data to decide whether samples are still availlable or not.
}
double vd_getSample() {
double sampleRead;
if(startFound){
sampleRead=startSample[countReader][countSample];
}
else {
sampleRead=endSample[countReader][countSample];
}
countSample++;
if(countSample == SUB_WINDOW_SIZE) {
countSample = 0;
countReader++;
}
return sampleRead;//return samples once their availability is confirmed.
}
/*Main method of VD class. It calculates energy of subwindows and makes decision on whether the start/end
is found or not*/
int calcVD(double sampleIn){
int k,j;
double energy = 0.0;
subWindowIn[countVD]=sampleIn;
countVD++;
if(countVD==SUB_WINDOW_SIZE){
for(k=0; k<SUB_WINDOW_SIZE; k++){
energy+=subWindowIn[k]*subWindowIn[k];
}
if (!startEnd){ //Searching for the start
if(energy > HIGHER_ENERGY){
countStart++;
//Stocking the subwindow once its energy is higher than the higher energy threshold
for(j=0; j<SUB_WINDOW_SIZE; j++){
startSample[countStart-1][j]=subWindowIn[j];
}
vd_init();
if(countStart>=START_TIME) {
setStart();
changeSearch();
availSample();
countMax = START_TIME;
}
}
else {
vd_init();
sampStart();
}
}
else {
if(energy>LOWER_ENERGY){ //Sinaliza amostras prontas e zera countEnd
countEnd++;
for(k=0; k<SUB_WINDOW_SIZE; k++){
endSample[countEnd-1][k]=subWindowIn[k];
}
availSample();
countMax = countEnd;
}
else{
countEnd++;
for(k=0; k<SUB_WINDOW_SIZE; k++){
endSample[countEnd-1][k]=subWindowIn[k];
}
vd_init();
if (countEnd>=END_TIME){
setEnd();
changeSearch();
}
}
}
}
return avail;
}
|
C
|
#include <stdio.h>
int main()
{
char pass1[20],pass2[20];
int i,flag=1,i1,i2;
printf("Enter password: ");
gets(pass1);
printf("Enter password again: ");
gets(pass2);
for(i1=0;pass1[i1]!='\0';i1++);
for(i2=0;pass2[i2]!='\0';i2++);
if(i1==i2)
{
for(i=0;pass1[i]!='\0';i++)
{
if(pass1[i]!=pass2[i])
{
flag=0;
break;
}
}
if(flag==1)
printf("Password match");
else
printf("Not same");
}
else
printf("Password not match");
return 0;
}
|
C
|
/******************************************
*
* IMPLEMENTAÇÃO DO SERVIDOR DE CHAT
*
*******************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
#include "type.h"
#define MAXCONNECT 5
// VARIAVEIS GLOBAIS
USER* lobby; // LISTA DE USUARIOS DO SISTEMA
ROOM* room; // LISTA DE CHATS DO SISTEMA
pthread_mutex_t mutex;
void send_message_to_user(char* messageToSend, int id){
char message[MESSAGE_SIZE];
sprintf(message,"%s\n",messageToSend);
write(id, message, MESSAGE_SIZE);
}
// CRIA SALAS DE CHAT
void create_room(char* name, int id_usuario){
printf("Enter Create ROOM \n");
pthread_mutex_lock(&mutex);
// CRIA SALA
ROOM* r = (ROOM*) malloc ( sizeof(ROOM) );
strcpy(r->name, name);
r->id = id_usuario;
r->list = (USER*) malloc( sizeof(USER) );
// ADICIONA NA LISTA DE SALAS
ROOM* aux = room;
ROOM* aux2 = room;
int happen = 0;
while(aux != NULL){
aux2 = aux;
aux = aux->prox;
if(! strcmp(aux2->name, name) ){
send_message_to_user("Chat já existe",id_usuario);
happen = 1;
}
}
if(happen == 0){
aux2->prox = r;
r->prox = NULL;
}
pthread_mutex_unlock(&mutex);
send_message_to_user("Sala de Chat Criada", id_usuario);
printf("END Create ROOM\n");
}
void change_name_user(char* name, int id){
printf("--- Mundando nome usuario ---\n");
USER* aux = lobby;
while(aux->prox != NULL){
if(aux->id == id){
strcpy(aux->name, name);
break;
}
aux = aux->prox;
}
send_message_to_user("Nome Alterado", id);
}
// ADICIONA USUARIO NO SISTEMA
void add_user_to_lobby(char* name, int id){
printf("Adding user: %s %d\n",name, id);
pthread_mutex_lock(&mutex);
USER* new_user = (USER*) malloc( sizeof(USER) );
strcpy(new_user->name, name);
new_user->id = id;
new_user->inRoom = 0;
// ADICIONA NA LISTA DE SALAS
USER* aux = lobby;
while(aux->prox != NULL)
aux = aux->prox;
aux->prox = new_user;
new_user->prox = NULL;
pthread_mutex_unlock(&mutex);
}
void show_rooms(int id){
ROOM* aux = room;
send_message_to_user("\n ---- Chats Disponíveis ---- ",id);
while(aux != NULL){
send_message_to_user(aux->name,id);
aux = aux->prox;
}
send_message_to_user("",id);
}
// REMOVE USUARIO DO SERVIDOR E DO CHAT
void remove_user(int id){
printf("ELIMINANDO USUARIO DE TUDO");
pthread_mutex_lock(&mutex);
USER* aux = lobby;
USER* aux2 = lobby;
while(aux != NULL){
if(aux->id == id){
aux2->prox = aux->prox;
free(aux);
break;
}
aux2 = aux;
aux = aux->prox;
}
ROOM* raux = room;
while(raux != NULL){
aux = raux->list;
aux2 = raux->list;
while(aux != NULL){
if(aux->id == id){
aux2->prox = aux->prox;
free(aux);
break;
}
aux2 = aux;
aux = aux->prox;
}
raux = raux->prox;
}
printf("ENDING REMOVE\n");
pthread_mutex_unlock(&mutex);
}
// RETIRA USUARIO DO CHAT
void leave_from_chat(char* name, int id){
pthread_mutex_lock(&mutex);
printf("Starting Leaving from chat %s\n",name);
USER* aux;
USER* aux2;
int found = 0;
USER* user = lobby;
while(user != NULL){
if(user->id == id)
break;
user = user->prox;
}
ROOM* raux = room;
while(raux != NULL){
if(! strcmp(raux->name, name)){
aux = raux->list;
aux2 = raux->list;
while(aux != NULL){
if(aux->id == id){
aux2->prox = aux->prox;
free(aux);
user->inRoom = 0;
user->friends = NULL;
found = 1;
break;
}
aux2 = aux;
aux = aux->prox;
}
}
if(found == 1)
break;
raux = raux->prox;
}
if(raux == NULL){
send_message_to_user("Acho eu não vi essa sala por aqui, Digite certo", id);
}else{
send_message_to_user("Saiu da chat", id);
}
printf("Ending Leaving from chat\n");
pthread_mutex_unlock(&mutex);
}
// ADICIONA USUARIO EM CHAT
void add_user_in_chat(char* name, int id){
pthread_mutex_lock(&mutex);
printf("Add User in Chat\n");
ROOM* aux = room;
ROOM* aux2 = room;
USER* user = lobby;
while(user != NULL){
if(user->id == id)
break;
user = user->prox;
}
if(user->inRoom == 0){
while(aux != NULL){
aux2 = aux;
if(! strcmp(aux->name, name)){
USER* temp = aux2->list;
while(temp->prox != NULL)
temp = temp->prox;
USER* u = (USER*) malloc( sizeof(USER) );
strcpy(u->name,name);
u->id = id;
u->prox = NULL;
u->inRoom = 1;
temp->prox = u;
send_message_to_user("Cadastrado no Chat", id);
user->inRoom = 1;
user->friends = aux->list;
break;
}
aux = aux->prox;
}
if(aux == NULL){
send_message_to_user("Acho eu não vi essa sala por aqui, Digite certo", id);
}
}else{
send_message_to_user("Saia de um Chat para entrar em outro", id);
}
printf("END ADD User in Chat\n");
pthread_mutex_unlock(&mutex);
}
// MANDA MENSAGENS PARA TODOS USUARIO DO CHAT
void send_message_to_friends(char* message, int id){
char messageToSend[MESSAGE_SIZE];
USER* user = lobby;
USER* userInChat;
while(user != NULL){
if(user->id == id)
break;
user = user->prox;
}
userInChat = user->friends;
sprintf(messageToSend, "%s: %s\n", user->name, message);
while(userInChat != NULL) {
if(userInChat->id != id)
write(userInChat->id, messageToSend, MESSAGE_SIZE);
userInChat = userInChat->prox;
}
}
// THREAD SERVIDOR - TODA LOGICA AQUI
void *serverWork(void * arg){
char buffer[MESSAGE_SIZE];
int n;
int newsockfd = *(int *) arg; // Pode ser id do usuario
while(1){
bzero(buffer, MESSAGE_SIZE);
/* read from the socket */
n = read(newsockfd, buffer, MESSAGE_SIZE);
if (n <= 0) {
close(n);
break;
}
printf("Receive Message: %s", buffer);
// LOGICA DO QUE O SERVIDOR DEVE FAZER
// IMPLEMENTAR METODOS
if(strstr(buffer, "--firstacess") != 0){
char name[MESSAGE_SIZE];
sscanf(buffer, "--firstacess %s", name);
add_user_to_lobby(name, newsockfd);
}else if(strstr(buffer, "--nickname") != 0){
char name[MESSAGE_SIZE];
sscanf(buffer, "--nickname %s", name);
change_name_user(name, newsockfd);
}else if(strstr(buffer, "--chat") != 0){
char name[MESSAGE_SIZE];
sscanf(buffer, "--chat %s", name);
create_room(name, newsockfd);
}else if(strstr(buffer, "--join") != 0){
char name[MESSAGE_SIZE];
sscanf(buffer, "--join %s", name);
add_user_in_chat(name, newsockfd);
}else if(strstr(buffer, "--leave") != 0){
char name[MESSAGE_SIZE];
sscanf(buffer, "--leave %s", name);
leave_from_chat(name, newsockfd);
}else if(strstr(buffer, "--close") != 0){
send_message_to_user("Get out", newsockfd);
remove_user(newsockfd);
close(newsockfd);
}else if(strstr(buffer, "--list") != 0) {
show_rooms(newsockfd);
}else{
send_message_to_friends(buffer,newsockfd);
}
}
return NULL;
}
int main(){
int sockfd, newsockfd;
socklen_t clilen;
//char buffer[MESSAGE_SIZE];
struct sockaddr_in serv_addr, cli_addr;
pthread_t thread;
pthread_mutex_init(&mutex, NULL);
lobby = (USER*) malloc( sizeof(USER) );
room = (ROOM*) malloc( sizeof(ROOM) );
lobby->prox = NULL;
room->prox = NULL;
//pthread_mutex_init(&m, NULL);
// CRIA SOCKET
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
printf("ERROR opening socket\n");
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
serv_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(serv_addr.sin_zero), 8);
// ASSOCIA ENDEREÇO/PORTA
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
printf("ERROR on binding port\n");
exit(1);
}
// DISPONIBILIZA SERVIDOR PARA ACEITAR CONEXÕES,
// DISPONIBILIZA MAXCONNECT CONEXÕES PENDENTES
listen(sockfd, MAXCONNECT);
clilen = sizeof(struct sockaddr_in);
// MANTEM SERVIDOR SEMPRE PRONTO PARA UMA CONEXÃO
while(1) {
printf("Waiting for connections...\n");
// FUNÇÃO ACCEPT SEGURA ATE QUE EXISTA UMA CONEXÃO, PRESSO DENTRO DO ACCEPT
if ((newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen)) == -1)
printf("ERROR on accept\n");
printf("Socket id => %d\n", newsockfd);
// CRIA UMA CONEXÃO PARA CADA SERVIDOR - SERVIDOR CONCORRENTE
pthread_create(&thread, NULL, serverWork, &newsockfd);
}
close(newsockfd);
close(sockfd);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void* __stack_chk_guard = NULL;
void setup_stack_chk()
{
uint32_t* p;
p = (uint32_t*) &__stack_chk_guard;
*p = 0x00000aff;
}
void __attribute__((noreturn)) __stack_chk_fail()
{
printf("Stack overflow/corruption detected!");
exit(-1);
}
|
C
|
#include "bbuff.h"
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <stdbool.h>
void* candyBuff[BUFFER_SIZE];
sem_t empty;
sem_t full;
sem_t mutex;
int index, tracker, outIndex = 0;
void bbuff_init(){
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
sem_init(&mutex, 0, 1);
}
void bbuff_blocking_insert(void* item){
sem_wait(&empty);
sem_wait(&mutex);
tracker++;
candyBuff[index] = item;
index = (index+1) % BUFFER_SIZE;
sem_post(&mutex);
sem_post(&full);
}
void* bbuff_blocking_extract(void){
void* candyPtr = NULL;
sem_wait(&full);
sem_wait(&mutex);
tracker--;
candyPtr = candyBuff[outIndex];
candyBuff[outIndex] = NULL;
outIndex = (outIndex+1)%BUFFER_SIZE;
sem_post(&mutex);
sem_post(&empty);
return candyPtr;
}
_Bool bbuff_is_empty(void){
_Bool flag = false;
sem_wait(&mutex);
sem_getvalue(&empty, &index );
if (index == BUFFER_SIZE) flag= true;
sem_post(&mutex);
return flag;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* list_to_tab.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: awali-al <awali-al@student.1337.ma> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/04 16:37:17 by afaraji #+# #+# */
/* Updated: 2020/12/10 18:51:59 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"
int list_count(t_l *list)
{
t_l *node;
int i;
node = list;
i = 0;
while (node)
{
i++;
node = node->next;
}
return (i + 1);
}
char **list_to_tab(t_l *list)
{
t_l *node;
int i;
char **args;
if (!list)
return (NULL);
if (!(args = (char **)malloc(sizeof(char *) * list_count(list))))
return (NULL);
node = list;
i = 0;
while (node)
{
args[i] = ft_strdup(node->data);
i++;
node = node->next;
}
args[i] = NULL;
free_l(list);
return (args);
}
int is_char_in_str(char c, char *s)
{
while (*s)
{
if (*s == c)
return (1);
s++;
}
return (0);
}
|
C
|
#pragma once
#include <SFML/Graphics.hpp>
#include "Box2D.h"
#include <random>
const sf::Vector2f SCREEN_SIZE{ 1920.0f, 1080.0f };
const sf::Vector2f SCREEN_CENTER{ SCREEN_SIZE / 2.0f };
const int PIXELS_TO_METERS{ 50 };
const float FRICTION{ 0.99f };
const sf::Vector2f GRAVITY{ 0.0f, 50.0f * PIXELS_TO_METERS };
const sf::Vector2f PLANE_SIZE{ SCREEN_SIZE.x, 80.0f };
const sf::Vector2f PLANE_POS{ SCREEN_CENTER.x, SCREEN_SIZE.y - (PLANE_SIZE.y / 2.0f) };
const float SCALE = 64;
/// <summary>
/// Entity IDs for user data
/// 0 = player
/// 1 = shielder
/// 2 = charger
/// 3 = bullet
/// 10 = world
/// 11 = orb
/// 12 = exit
/// </summary>
enum EnemyType
{
ShieldBoi = 1,
ChargerBoi = 2,
TurretBoi = 3
};
//Any state an enemy can be goes here
enum class EnemyState
{
Patrol,
Player_Spotted,
Idle,
Shield,
Charging,
Attack,
};
enum class EndState
{
WIN,
LOSE
};
struct UserData
{
int entity;
void* data;
};
enum _entityCategory {
PLAYER = 0x0001,
ORB = 0x0002,
ENEMY = 0x0004,
WORLD = 0x0008,
PHASE_WALL = 0x0010,
EXIT = 0x0020,
};
|
C
|
#include<stdlib.h>
#include<stdio.h>
struct point
{
int x;
int y;
};
struct rect
{
struct point pt1;
struct point pt2;
};
struct point makepoint(int x,int y)
{
struct point temp;
temp.x=x;
temp.y=y;
return temp;
};
int main()
{
struct rect screen;
screen.pt1=makepoint(30,40);
screen.pt2=makepoint(50,60);
struct point p1;
p1=makepoint(60,70);
printf("%d %d\n",p1.x,p1.y);
}
|
C
|
#include<stdio.h>
int swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
return 0;
}
int main()
{
int a,b;
printf("Enter two numbers= ");
scanf("%d%d",&a,&b);
printf("\nBefore swap= %d,%d",a,b);
swap(&a,&b);
printf("\nAfter swap= %d,%d",a,b);
return 0;
}
|
C
|
#include <stdio.h>
#include "SinglyLinkedList.h"
void printSinglyLinkedList(SinglyLinkedList *singlyLinkedList)
{
int length = singlyLinkedList->length;
printf("Length: %d\n", length);
if (length > 0)
{
printf("Head: %d\n", singlyLinkedList->head->value);
printf("Tail: %d\n", singlyLinkedList->tail->value);
}
int counter = 0;
SinglyLinkedListNode *node = singlyLinkedList->head;
while (counter < length)
{
printf("%d: %u\n", counter, node->value);
node = node->next;
counter++;
}
printf("\n");
}
int main(void)
{
printf("Creating new SinglyLinkedList\n");
SinglyLinkedList *singlyLinkedList = createSinglyLinkedList();
printSinglyLinkedList(singlyLinkedList);
printf("Pushing 10 integers to the SinglyLinkedList\n");
for (int counter = 0; counter < 10; counter++)
pushValueSinglyLinkedList(singlyLinkedList, counter);
printSinglyLinkedList(singlyLinkedList);
printf("Popping 5 integers from the SinglyLinkedList\n");
for (int counter = 0; counter < 5; counter++)
popValueSinglyLinkedList(singlyLinkedList);
printSinglyLinkedList(singlyLinkedList);
printf("Inserting the value 99 at index 2\n");
insertValueSinglyLinkedList(singlyLinkedList, 2, 99);
printSinglyLinkedList(singlyLinkedList);
printf("Removing the value at index 2\n");
removeValueSinglyLinkedList(singlyLinkedList, 2);
printSinglyLinkedList(singlyLinkedList);
printf("Inserting the value 99 at index 5\n");
insertValueSinglyLinkedList(singlyLinkedList, 5, 99);
printSinglyLinkedList(singlyLinkedList);
printf("Removing the value at index 5\n");
removeValueSinglyLinkedList(singlyLinkedList, 5);
printSinglyLinkedList(singlyLinkedList);
printf("Inserting the value at index 0\n");
insertValueSinglyLinkedList(singlyLinkedList, 0, 99);
printSinglyLinkedList(singlyLinkedList);
printf("Removing the value at index 0\n");
removeValueSinglyLinkedList(singlyLinkedList, 0);
printSinglyLinkedList(singlyLinkedList);
printf("Adding 99 after the last node\n");
SinglyLinkedListNode *node = getNodeSinglyLinkedList(singlyLinkedList, singlyLinkedList->length - 1);
addValueAfterNodeSinglyLinkedList(singlyLinkedList, node, 99);
printSinglyLinkedList(singlyLinkedList);
printf("Removing the value after second last node\n");
removeValueAfterNodeSinglyLinkedList(singlyLinkedList, node);
printSinglyLinkedList(singlyLinkedList);
printf("Destroying the SinglyLinkedList\n");
destroySinglyLinkedList(singlyLinkedList);
return 0;
}
|
C
|
//print the numbers which is divisible by 3 in between 1-50
#include<stdio.h>
int main()
{
int i=0;
while(i <= 50)
{
if(i%3 == 0)
{
printf("hence the numbers are divisible by 3 : %d\n",i);
}
i++;
}
return 0;
}
|
C
|
#ifndef LCDBUTTONS_H
#define LCDBUTTONS_H
#include "dtd.h"
// Low-level button press
int readLCDbuttons() { // button pressed? return its value
// following literal depends upon ADC clock divider.
int keyValue, counter=3000; // gives a rough "one thousand and one" delay...
uint8_t button = btnNONE;
// my buttons when read return these values: 0, 132, 306, 478, 720
// the arithmetic halfway points are: 66 219 392 599 750
keyValue = analogRead(btnADC); // read value from sensor
if (keyValue < 1000) {
if (keyValue < 65)button = btnRIGHT;
else if (keyValue < 220)button = btnUP;
else if (keyValue < 390)button = btnDOWN;
else if (keyValue < 600)button = btnLEFT;
else if (keyValue < 750)button = btnSELECT;
else return btnNONE;
while (analogRead(btnADC) < 1000) {
if(!--counter)
return button; // timed out, do buttonpress and return for more. (allows autorepeat)
} // wait here for release, unless we timeout
}
return button;
}
#endif
|
C
|
// $Id: hashset.c,v 1.7 2013-05-23 15:41:07-07 - - $
//andrew lien
//ahlien
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "debugf.h"
#include "hashset.h"
#include "strhash.h"
#define HASH_NEW_SIZE 15
typedef struct hashnode hashnode;
struct hashnode {
char *word;
hashnode *link;
};
struct hashset {
size_t size;
size_t load;
hashnode **chains;
};
//chains IS an array
/*
So like you have an array, pretty much, you can think of it
as an up and down array, and each element of that array
has a corresponding hash code value, and thats how it knows
which word goes with which position. There's a function he gives
us, it's caleld strhash.c, don't mess with it, but we just send
the word that we send in to the strhash.c and that gives you a
value. So then, that value is goign to act as your index point
It's in hash hashcode_t, that's your index now, and that's going
to basically find the point in the has you're going to start at
and then within that chain, there's a linked list,
*/
hashset *new_hashset (void) {
hashset *this = malloc (sizeof (struct hashset));
assert (this != NULL);
this->size = HASH_NEW_SIZE;
this->load = 0;
size_t sizeof_chains = this->size * sizeof (hashnode *);
this->chains = malloc (sizeof_chains);
assert (this->chains != NULL);
memset (this->chains, 0, sizeof_chains);
DEBUGF ('h', "%p -> struct hashset {size = %d, chains=%p}\n",
this, this->size, this->chains);
return this;
}
void free_hashset (hashset *this) {
DEBUGF ('h', "free (%p)\n", this);
for(int i = 0; i < (int)this->size; i++) free(this->chains[i]);
memset(this->chains,0,this->size*sizeof(char*));
free(this->chains);
memset(this,0,sizeof(this));
free(this);
}
void doubletheArray(hashset *this){
//printf("Here is where i am going to double the array\n");
int previousSize = this->size;
this->size = (previousSize * 2) + 1;
//allocate a new array & set its pointers to null
char **newhashnode = malloc (this->size * sizeof (char*));
for (int i = 0; i < (int)this-> size; i++) newhashnode[i] = NULL;
//for each entry in the OLD array
for (int i = 0; i < previousSize; i++) {
//used if statement instead of while loop, continue
if (this->chains[i] == NULL) continue;
//popped hash node from this->chains &
//recomputed the hash number & hash index for new array
int newIndex = strhash(this->chains[i]) % this->size;
//push the hash node onto the index of the new array
while (newhashnode[newIndex] != NULL) {
if (strcmp(newhashnode[newIndex], this->chains[i]) == 0) break;
//when newhash matches size of thischains, break;
//increment new index based on % this size
newIndex = (newIndex + 1) % this->size;
}
//give newhashnode properties of this->chains
newhashnode[newIndex] = this->chains[i];
//at this point newhasnode has properties of
//this->chains & has bigger array
}
char **tmp = this->chains;
this->chains = newhashnode;
free(tmp); //free old this->chains
}
//if word is put into hash, ignore it, append to end of linked list
//loading the dictionary
void put_hashset (hashset *this, char *item) {
// STUBPRINTF ("hashset=%p, item=%s\n", this, item);
//from implementation 5(e)
if((this->load*2) > this->size) doubletheArray(this);
hashcode_t ind = (strhash(item)%this->size);
while(this->chains[ind] != NULL){
ind = (ind + 1) % this->size;
}
this->chains[ind] = strdup(item);
this->load++;
}
//the spell checking portion, you're going to input
//another filname, and that file is goign to have word
// that is spelled correctly or incorectly, and you're
//going to output the word that's spelled correctly.
bool has_hashset (hashset *this, char *item) {
//STUBPRINTF ("hashset=%p, item=%s\n", this, item);
//In order to avoid negative numbers, use defined data type
//hashcode_t, defined to be an unsigned 32-bit integer.
hashcode_t ind = (strhash(item) % this->size);
while(this->chains[ind] != NULL){
if(strcmp(this->chains[ind],item) == 0) return true;
ind = (ind + 1) % this->size;//perform linear search down hash chain
}
//convert to lower case, implementation 6(ii);
int a = 0;
char *low = item;
while(item[a] != NULL){
low[a] = (tolower(item[a])); //tolower makes lowercases
a++;
}
ind = (strhash(low) % this->size);
while(this->chains[ind] != NULL) {
if(strcmp(this->chains[ind],low) == 0) return true;
ind = (ind + 1) % this->size;
}
return false;
}
//for implementation 5
void hash_check(hashset *this, int hashDump){
//printf("It's calling the hash check function\n");
int j = 0;
//need cluster array a quarter of main hash
int cluster[this->size/4]; //no need to malloc
//initialize this new array to null
for(size_t i = 0; i< (int)this->size/4; i++) cluster[i] = NULL;
int clusterCount = 0;
for (int i = 0; i < (int)this->size; i++){
if ((int)this->size == i-1){ //the last element of the array
if ((this->chains[i] =! NULL) && (this->chains[0] == NULL)) {
++cluster[clusterCount];
clusterCount = 0;
}
if ((this->chains[i] == NULL) && (this->chains[0] == NULL)) {
//merge two clusers
int firstclusterCount=0;
for (int k = 0; k < (int)this->size; k++){
//find size of first cluster
if (this->chains[k] != NULL) {
++firstclusterCount;
} else {
--cluster[firstclusterCount];
++cluster[firstclusterCount + clusterCount];
}
}
}
}else if (this->chains[i] != NULL) {
j++; //for counting number of words in hashset
++clusterCount;
} else {
++cluster[clusterCount];
clusterCount = 0;
}
}
printf ("%10d words in the hash set\n", j);
printf ("%10zu length of the hash array\n", this->size);
int sum = 0;
for (int i = 1; i < this->size/4; i++) {
if (cluster[i] != 0) {
printf("%10d clusters of size %i\n", cluster[i] , i);
sum+=(cluster[i]*i);
}
}
//printf("%10d Sum of clusters
//which should equal word count\n", sum);
if (hashDump > 1) {
for (int i = 0; i < this->size; i++){
if (this->chains[i] != NULL) {
char *word = this->chains[i];
hashcode_t hash = strhash(word);
printf("array[%10d] = %12u \"%s\"\n", i, hash, word);
}
}
}
}
|
C
|
/*
ULIMIT(cResource [, nNewValue]) -> nValue
cResource is a one of:
"CPU" CPU time in seconds
"FSIZE" Maximum filesize
"DATA" max data size
"STACK" max stack size
"CORE" max core file size
"RSS" max resident set size
"NPROC" max number of processes
"NOFILE" max number of open files
"MEMLOCK" max locked-in-memory address space
"AS" address space (virtual memory) limit
*/
int
clip_ULIMIT(ClipMachine * ClipMachineMemory)
{
#ifdef OS_MINGW
return EG_ARG;
#else
char *res = _clip_parc(ClipMachineMemory, 1);
long newval;
int resource;
int r;
struct rlimit rlimit;
if (!res)
return EG_ARG;
#ifdef RLIMIT_CPU
if (!strcasecmp(res, "CPU"))
resource = RLIMIT_CPU;
#else
if (0)
;
#endif
#ifdef RLIMIT_FSIZE
else if (!strcasecmp(res, "FSIZE"))
resource = RLIMIT_FSIZE;
#endif
#ifdef RLIMIT_DATA
else if (!strcasecmp(res, "DATA"))
resource = RLIMIT_DATA;
#endif
#ifdef RLIMIT_STACK
else if (!strcasecmp(res, "STACK"))
resource = RLIMIT_STACK;
#endif
#ifdef RLIMIT_CORE
else if (!strcasecmp(res, "CORE"))
resource = RLIMIT_CORE;
#endif
#ifdef RLIMIT_RSS
else if (!strcasecmp(res, "RSS"))
resource = RLIMIT_RSS;
#endif
#ifdef RLIMIT_NPROC
else if (!strcasecmp(res, "NPROC"))
resource = RLIMIT_NPROC;
#endif
#ifdef RLIMIT_NOFILE
else if (!strcasecmp(res, "NOFILE"))
resource = RLIMIT_NOFILE;
#endif
#ifdef RLIMIT_MEMLOCK
else if (!strcasecmp(res, "MEMLOCK"))
resource = RLIMIT_MEMLOCK;
#endif
#ifdef RLIMIT_AS
else if (!strcasecmp(res, "AS"))
resource = RLIMIT_AS;
#else
#ifdef RLIMIT_DATA
else if (!strcasecmp(res, "AS"))
resource = RLIMIT_DATA;
#endif
#endif
else
return EG_ARG;
if (ClipMachineMemory->argc > 1)
{
newval = _clip_parnl(ClipMachineMemory, 2);
getrlimit(resource, &rlimit);
if (newval < 0)
rlimit.rlim_cur = RLIM_INFINITY;
else if (rlimit.rlim_max != RLIM_INFINITY && newval > rlimit.rlim_max)
newval = rlimit.rlim_max;
rlimit.rlim_cur = newval;
setrlimit(resource, &rlimit);
}
r = getrlimit(resource, &rlimit);
if (r)
_clip_retnl(ClipMachineMemory, -1);
else
_clip_retnl(ClipMachineMemory, rlimit.rlim_cur);
return 0;
#endif
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
//Stack//
struct intStack{
int size;
int* data;
int cnt;
};
int initStack (struct intStack *st, int size){
st->data = (int*)malloc(size);
if(st->data == NULL)
return -1;
st->size = size;
st->cnt = 0;
return 0;
}
int push(struct intStack *st, int el){
if(st->cnt < st->size){
st->data[st->cnt] = el;
st->cnt ++;
}
else{
printf("Error, stack is full");
return 0;
}
return 0;
}
int pop(struct intStack *st){
int buf;
if(st->cnt > 0){
buf = st->data[st->cnt - 1];
st->cnt --;
}
return buf;
}
void test(){
struct intStack test;
initStack(&test,10);
printf("Input: 1, 2, 3, 4, 5\n");
push(&test,1);
push(&test,2);
push(&test,3);
push(&test,4);
push(&test,5);
printf("Output:\n");
printf("%d\n", pop(&test));
printf("%d\n", pop(&test));
printf("%d\n", pop(&test));
printf("%d\n", pop(&test));
printf("%d\n", pop(&test));
}
int main(){
test();
}
|
C
|
//strcatģʵ
//strcatҪǽַӣԴַӵĿַ֮ҪĿַĿռҪ㹻
//ҪĿַԪصַԴַԪصַ
//ӺĿַԪصַ
#include<stdio.h>
#include<assert.h>
char* my_strcat(char* arr1, const char* arr2)
{
assert(arr1);
assert(arr2);
char* ret = arr1;
//ѰĿַĵַ
while (*++arr1);
//arr2Ԫӵarr1
while (*arr1++ = *arr2++)
{
;
}
return ret;
}
int main()
{
char arr1[30] = "abcdef";
char arr2[] = "ghijk";
my_strcat(arr1, arr2);
printf("%s\n", arr1);
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void my_reverse(char* s)
{
char tmp;
for (int i = 0, j = strlen(s)-1; i < j; i++, j--) {
tmp = s[i];
s[i] = s[j];
s[j] = tmp;
}
}
int lengthOfLastWord(char* s)
{
int i, j;
my_reverse(s);
i = 0;
while (s[i] == ' ' && i < strlen(s)) {
i++;
}
j = i;
while (s[j] != ' ' && j < strlen(s)) {
j++;
}
return j - i;
}
int main(int argc, char *argv[])
{
if (argc != 2)
return 0;
printf("%d\n", lengthOfLastWord(argv[1]));
return 0;
}
|
C
|
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int ValidArgv(string command_text);
string Encryption(int key, string text);
int main(int argc, string argv[])
{
if (argc == 2)
{
int valid_key = ValidArgv(argv[1]);
if (valid_key == 0)
{
int key = atoi(argv[1]);
string plaintext = get_string("plaintext: ");
string encrypted = Encryption(key, plaintext);
printf("ciphertext: %s\n", encrypted);
}
else
{
printf("Usage: ./caesar key");
return 1;
}
}
else
{
printf("Usage: ./caesar key");
return 1;
}
}
int ValidArgv(string command_text)
{
int valid;
for (int i = 0; i < strlen(command_text); i++)
{
if (isdigit(command_text[i]))
{
valid = 0;
}
else
{
valid = 1;
}
}
return valid;
}
string Encryption(int key, string text)
{
for (int i = 0; i < strlen(text); i++)
{
if (isupper(text[i]))
{
text[i] = (text[i] + key - 65) % 26 + 65;
}
else if (islower(text[i]))
{
text[i] = (text[i] + key - 97) % 26 + 97;
}
}
return text;
}
|
C
|
#include <stdio.h>
/* Find the difference between the sum of the squares of the first
* one hundred natural numbers and the square of the sum. */
int main()
{
int i, sum_sqrs, sqr_sum;
sum_sqrs = sqr_sum = 0;
for (i = 1; i <= 100; i++)
{
printf("%d\n", i);
sum_sqrs = sum_sqrs + i*i;
sqr_sum = sqr_sum + i;
}
printf("Sum of squares = %d\n", sum_sqrs);
printf("Square of sum = %d\n", sqr_sum*sqr_sum);
printf("Difference = %d\n", sqr_sum*sqr_sum - sum_sqrs);
return 0;
}
|
C
|
int ft_atoi(char *str)
{
int i;
int res;
int s;
i = 0;
res = 0;
s = 1;
while (str[i] == 32 || (str[i] >= 9 && str[i] <= 13))
i++;
if (str[i] == '-' || str[i] == '+')
{
if (str[i] == '-')
s *= -1;
i++;
}
while (str[i])
{
if (!(str[i] >= '0' && str[i] <= '9'))
return (res * s);
res *= 10;
res += str[i] - '0';
i++;
}
return (res * s);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 100
#define MAX_LINE 15000
char** s_strcut(char *ori, char *cut, int *datalen); /* 文字列oriをcutに含まれる文字で切り分ける関数 datallenにdataの要素数を返す */
int s_strlen(char *);
void s_strcpy(char *, char *);
typedef struct person_s
{
char name[20];
int age;
double weight;
double height;
struct person_s *next;
} person;
person* construct_person(char name[20], int age, double weight, double height, person *previous)
{
person* ret = (person *)malloc(sizeof(person));
strcpy(ret->name, name);
ret->age = age;
ret->weight = weight;
ret->height = height;
ret->next = NULL;
return ret;
}
void print_person(person* p)
{
printf("name: %s\nage: %d\nweight: %lf\nheight: %lf\n", p->name, p->age, p->weight, p->height);
}
/* 最初のメンバ*p, 表示する人数n */
void print_many_person(person *p, int n)
{
int i;
person *print = p;
for (i = 0; i < n; i++) {
print_person(print);
print = print->next;
}
printf("\n");
}
int main(int argc, char *argv[])
{
int len = 0;
char cut[1] = {','};
char **buf;
char buffer[MAX_LEN];
FILE *fp;
person *current, *first;
int dlen; /* s_strlenの変数datelenを満たすだけの変数、意味はない */
if ((fp = fopen(argv[1], "r")) == NULL) {
fprintf(stderr, "Failed to open the file\n");
return 1;
}
len = 0;
while(fgets(buffer, MAX_LEN, fp) != NULL) {
buf = s_strcut(buffer, cut, &dlen);
if (len == 0) {
current = construct_person(buf[0], atoi(buf[1]), atof(buf[3]), atof(buf[2]), NULL);
first = current;
} else {
current->next = construct_person(buf[0], atoi(buf[1]), atof(buf[3]), atof(buf[2]), current);
current = current->next;
}
len++;
free(buf);
}
print_many_person(first, 5);
return 0;
}
int s_strlen(char *str)
{
int len = 0;
while(str[len] != '\0') {
len++;
}
return len;
}
void s_strcpy(char *str1, char *str2)
{
int len;
int i;
len = s_strlen(str2);
for (i = 0; i <= len; i++) {
str1[i] = str2[i];
}
return;
}
/* 文字列oriをcutに含まれる文字で切り分ける関数 datalenにdataの要素数を返す */
char** s_strcut(char *ori, char *cut, int *datalen) {
int i, j, k, n;
char **data;
int orilen = s_strlen(ori);
int cutn = s_strlen(cut);
char tmp[1000];
int state;
*datalen = 1; /* 何個に分割されるかを示す */
n = 0;
for(i = 0; i < orilen; i++) {
for (j = 0; j < cutn; j++) {
if (ori[i] == cut[j]) {
(*datalen)++;
}
}
}
data = (char **)malloc(sizeof(char*)*(*datalen));
k = 0;
for (i = 0; i <= orilen; i++) {
state = 0;
for (j = 0; j < cutn; j++) {
if (ori[i] == '\0') {
state = 1;
} else if (ori[i] == cut[j]) {
state = 1;
}
}
if (state == 1){
tmp[k] = '\0';
data[n] = (char*)malloc(sizeof(char) * (k+1));
s_strcpy(data[n], tmp);
k = 0;
n++;
} else {
tmp[k] = ori[i];
k++;
}
}
return data;
}
|
C
|
//
// numOf0.h
//
// Created by lg on 2020/6/2.
// Copyright © 2020 sculg. All rights reserved.
//
#ifndef numOf0_h
#define numOf0_h
//2、自然数中0的个数
int numOf0(int i) {
int count = 0;
if(i < 0) {
return -1;
}
while (i!=0) {
if ((i & 1) == 0) {
count ++;
}
i>>=1;
}
return count;
}
#endif /* numOf0_h */
|
C
|
#include "libgfx.h"
static int swap_vars(t_3d *p0, t_3d *p1)
{
float temp;
if (fabs(p1->x - p0->x) > fabs(p1->y - p0->y))
return (0);
temp = p0->y;
p0->y = p0->x;
p0->x = temp;
temp = p1->y;
p1->y = p1->x;
p1->x = temp;
return (1);
}
void init_color_table(t_data *d)
{
int i;
float r[3];
float g[3];
float b[3];
d->colors = (int *)malloc(sizeof(int) * 100);
r[0] = (float)(0x9E05FA >> 16 & 0xFF);
r[1] = (float)(0x9E05FA >> 16 & 0xFF);
g[1] = (float)(0xA10000 >> 8 & 0xFF);
b[0] = (float)(0x9E05FA & 0xFF);
b[1] = (float)(0xA10000 & 0xFF);
i = -1;
while (++i < 100)
{
r[2] = (float)(r[0] * i) / 100 + (float)(r[1] * (100 - i)) / 100;
g[2] = (float)(g[0] * i) / 100 + (float)(g[1] * (100 - i)) / 100;
b[2] = (float)(b[0] * i) / 100 + (float)(b[1] * (100 - i)) / 100;
d->colors[i] = (int)r[2] << 16 | (int)g[2] << 8 | (int)b[2];
}
}
static void find_deltas(float *delta, t_3d p0, t_3d p1)
{
delta[0] = p1.x - p0.x;
delta[1] = p1.y - p0.y;
delta[2] = p1.z - p0.z;
}
static void draw_point(t_data *d, int x, int y, float z)
{
int i;
unsigned int color;
float which;
if (x > 0 && y > 0 && x < WINDOW_SIZE_X && y < WINDOW_SIZE_Y)
{
which = ((z - d->plot->z_min)
/ (d->plot->z_max - d->plot->z_min)) * 100;
color = d->colors[abs((int)which - 1)];
i = (x * 4) + (y * d->s_line);
d->pixel_img[i] = color;
d->pixel_img[++i] = color >> 8;
d->pixel_img[++i] = color >> 16;
}
}
/*
** Bresenham's line algorithm
*/
void ft_3d_drawline(t_data *d, t_3d p0, t_3d p1)
{
float delta[3];
float error;
float deltaerr;
int dir;
dir = swap_vars(&p0, &p1);
find_deltas(delta, p0, p1);
deltaerr = fabs(delta[1] / delta[0]);
error = -1.0;
while ((int)p0.x != (int)p1.x)
{
draw_point(d, dir ? p0.y : p0.x, dir ? p0.x : p0.y, p0.z);
error += deltaerr;
if (error >= 0.0)
{
p0.y += (p0.y > p1.y) ? -1 : 1;
error -= 1.0;
}
p0.z += delta[2] / fabs(delta[0]);
p0.x += (p0.x > p1.x) ? -1 : 1;
}
}
|
C
|
#ifndef __PPHASH_H
#define __PPHASH_H
struct ht_kv_s {
char *key;
void *value;
struct ht_kv_s *next;
};
typedef struct ht_kv_s ht_kv_t;
struct hashtable_s {
int size;
int (*destroy_value)(void *);
int item_count;
struct ht_kv_s **table;
};
typedef struct hashtable_s hashtable_t;
hashtable_t *ht_create( int size, int (*free_value)(void *) );
void ht_destroy( hashtable_t *hashtable);
int ht_hash( hashtable_t *hashtable, char *key );
ht_kv_t *ht_pair( char *key, void *value );
void ht_set( hashtable_t *hashtable, char *key, void *value );
void *ht_get( hashtable_t *hashtable, char *key );
int ht_size(hashtable_t *hashtable);
#endif
|
C
|
#include<stdio.h>
#include<stdlib.h>
void addq(int* , int*, int* , int*);
void delq(int* ,int* ,int* , int *);
void display(int* , int* , int*);
int main()
{
int size=4;
int a[size];
int front = -1;
int rear = -1;
while(1)
{
printf("\n1.Enter new element");
printf("\n2.Delete Element");
printf("\n3.Display all Elements");
printf("\n4....EXIT.....\n");
int choice;
printf("\nEnter choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
addq(a , &front , &rear ,&size);
break;
case 2:
delq(&front, &rear, a, &size);
break;
case 3:
display(&front , &rear ,a);
break;
case 4:
exit(0);
break;
default:
printf("\nEntered invalid choice!");
}
}
}
void addq(int *a, int *front, int *rear , int *size)
{
int id;
*front = 0;
if(*rear==*size)
{
printf("\nQueue is full");
}
else{
(*rear)++;
printf("\nEnter ID = ");
scanf("%d",&id);
a[(*rear)] = id;
}
}
void delq(int *front, int *rear , int *a , int *size)
{
if((*front == -1 && *rear == -1) || (*front == *size && *rear == *size))
{
printf("\nlist is empty\n");
}
else{
printf("\npoped ID = %d\n",(a[*front]));
(*front)++;
}
}
void display(int *front, int *rear , int *a)
{
int temp=*front;
if(*front == -1)
printf("\nList is Empty");
else{
while(temp!=*rear)
{
printf("%d\n",(a[temp]));
temp++;
}
}
}
|
C
|
#include <ctype.h>
#include <string.h>
#include "parsing.h"
int match(char *s, char *pattern) {
regex_t reg;
regmatch_t matched;
bool res;
REG_COMPILE(reg, pattern, REG_EXTENDED);
res = regexec(®, s, 1, &matched, 0) != REG_NOMATCH;
regfree(®);
return (res);
}
int parse_selector_sequence(selector_sequence *seq, char **s) {
int wide_res, small_res;
while (**s == ' ') ++*s;
if (strstr(*s, "24/7 ") == *s) {
seq->anyway = true;
*s += sizeof("24/7");
return (SUCCESS);
}
wide_res = parse_wide_range_selector(&seq->wide_range, s);
if (wide_res == ERROR)
return (ERROR);
small_res = parse_small_range_selector(&seq->small_range, s);
if (small_res == ERROR)
return (ERROR);
if (wide_res == small_res && wide_res == EMPTY) {
seq->anyway = true;
return (EMPTY);
}
return (SUCCESS);
}
int parse_rule_modifier(rule_modifier *rule, char **s) {
regex_t reg_comment;
regmatch_t match_comment;
while (**s == ' ') ++*s;
REG_COMPILE(reg_comment, "^\"[^\"]*\"", REG_EXTENDED);
if (strstr(*s, "open") == *s) rule->type = RULE_OPEN, *s += sizeof("open") - 1;
else if (strstr(*s, "closed") == *s) rule->type = RULE_CLOSED, *s += sizeof("closed") - 1;
else if (strstr(*s, "off") == *s) rule->type = RULE_CLOSED, *s += sizeof("off") - 1;
else if (strstr(*s, "unknown") == *s) rule->type = RULE_UNKNOWN, *s += sizeof("unknown") - 1;
else if (regexec(®_comment, *s, 1, &match_comment, 0) != REG_NOMATCH) {
if ((*s)[1] == '"') {
++*s;
printf("Invalid syntax: empty comment.\n");
return (ERROR);
}
strncpy(rule->comment, *s + match_comment.rm_so + 1, match_comment.rm_eo - match_comment.rm_so - 2);
*s += match_comment.rm_so;
} else if (isalpha(**s)) {
printf("Invalid syntax: invalid rule modifier.\n");
return (ERROR);
}
regfree(®_comment);
while (**s == ' ') ++*s;
return (SUCCESS);
}
int parse_rule_sequence(rule_sequence *seq, char **s) {
while (**s == ' ') ++*s;
if (!seq->separator) {
if (strstr(*s, ",") == *s) seq->separator = SEP_COMA, ++*s;
if (strstr(*s, ";") == *s) seq->separator = SEP_SEMICOLON, ++*s;
if (strstr(*s, "||") == *s) seq->separator = SEP_FALLBACK, *s += 2;
}
if (parse_selector_sequence(&seq->selector, s) == ERROR)
return (ERROR);
if (parse_rule_modifier(&seq->state, s) == ERROR)
return (ERROR);
return (SUCCESS);
}
void free_oh(opening_hours oh) {
if (!oh)
return;
selector_sequence selector = oh->rule.selector;
if (selector.wide_range.years)
del_bitset(selector.wide_range.years);
if (selector.wide_range.weeks)
del_bitset(selector.wide_range.weeks);
if (selector.wide_range.monthdays.days)
del_bitset(selector.wide_range.monthdays.days);
if (selector.small_range.weekday.range)
del_bitset(selector.small_range.weekday.range);
if (selector.small_range.hours.time_range)
del_bitset(selector.small_range.hours.time_range);
if (selector.small_range.hours.extended_time_range)
del_bitset(selector.small_range.hours.extended_time_range);
if (oh->to_str)
free(oh->to_str);
free_oh(oh->next_item);
free(oh);
}
char *set_cursor(int pos, char *str) {
memset(str, ' ', pos);
str[pos] = '^';
str[pos + 1] = 0;
return (str);
}
opening_hours build_opening_hours(char *s) {
opening_hours oh = calloc(1, sizeof(*oh)),
cur = oh;
int it = 0;
char *entire_string = s,
cursor_str[strlen(s) * 2 + 1];
if (!oh) {
dprintf(2, "FATAL ERROR: Allocation failed for oh.\nMaybe RAM is full?\n");
exit(2);
}
oh->rule.separator = SEP_HEAD;
do {
if (it++) {
cur = (cur->next_item = calloc(1, sizeof(*oh)));
}
if (parse_rule_sequence(&cur->rule, &s) == ERROR) {
printf("\n%s\n%s\n", entire_string, set_cursor(s - entire_string, cursor_str));
free_oh(cur);
return (NULL);
}
} while (*s && *++s);
return (oh);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* rush00_main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sreijola <sreijola@student.hive.fi> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/07/28 13:14:34 by sreijola #+# #+# */
/* Updated: 2019/07/28 13:17:55 by sreijola ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_rush.h"
#include "ft_read.h"
void testprint(char *masterstr, int x)
{
int i;
i = 0;
ft_putchar('\n');
while (*(masterstr + i))
{
ft_putchar(*(masterstr + i));
++i;
if (i % x == 0)
ft_putchar('\n');
}
}
int main(int argc, char **argv)
{
int x = atoi(argv[1]);
int y = atoi(argv[2]);
int length = x;
char *first_line0;
/*t_rush_info *myinfo0;*/
t_rush_info *myinfo1;
/*t_rush_info *myinfo2;
t_rush_info *myinfo3;
t_rush_info *myinfo4;
/*myinfo0 = ft_rush_collector00(length, y);
printf("%s %s\n", myinfo0->name, myinfo0->print);
testprint(myinfo0->print, x);
free (myinfo0->print);
free (myinfo0);*/
myinfo1 = ft_rush_collect_test01(length, y);
printf("%s %s\n", myinfo1->name, myinfo1->print);
testprint(myinfo1->print, x);
free (myinfo1->print);
free (myinfo1);
/*myinfo2 = ft_rush_collector02(length, y);
printf("%s %s\n", myinfo2->name, myinfo2->print);
testprint(myinfo2->print, x);
free (myinfo2->print);
free (myinfo2);
myinfo3 = ft_rush_collector03(length, y);
printf("%s %s\n", myinfo3->name, myinfo3->print);
testprint(myinfo3->print, x);
free (myinfo3->print);
free (myinfo3);
myinfo4 = ft_rush_collector04(length, y);
printf("%s %s\n", myinfo4->name, myinfo4->print);
testprint(myinfo4->print, x);
free (myinfo4->print);
free (myinfo4);*/
ft_putchar('0' + ft_read());
return (0);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#define MAX 4
int queue[MAX];
int rear = -1, front = -1, size = 0;
void enqueue(int item);
int dequeue();
int display_front();
void display();
int isEmpty();
int main() {
int choice,item;
printf("******MENU******\n");
printf("1.Enqueue.\n");
printf("2.Dequeue.\n");
printf("3.Display Front.\n");
printf("4.Display Queue.\n");
printf("5.Quit.\n\n");
while(1) {
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1:
printf("Enter the element: ");
scanf("%d",&item);
enqueue(item);
printf("\n");
break;
case 2:
item=dequeue();
if(item!=-1)
printf("Deleted element is: %d\n\n",item);
break;
case 3:
item=display_front();
if(item!=-1)
printf("Element at the front is: " );
printf("%d\n\n",display_front());
break;
case 4:
display();
break;
case 5:
exit(1);
default:
printf("Wrong choice\n");
}
}
return 0;
}
void enqueue(int item) {
if (size == MAX) {
printf("Queue Overflow\n");
return;
}
if (front == -1)
front=0;
rear=(rear+1)%MAX;
queue[rear]=item;
size++;
return;
}
int dequeue() {
int item;
if (isEmpty()) {
printf("Queue Underflow\n\n");
return -1;
}
item=queue[front];
front=(front+1)%MAX;
size--;
return item;
}
int display_front() {
if (isEmpty()) {
printf("Queue Underflow\n\n");
return -1;
}
return queue[front];
}
int isEmpty() {
if (size==0)
return 1;
else
return 0;
}
void display() {
int i;
if (isEmpty()){
printf("Queue is empty\n\n");
return;
}
printf("Elements in Queue are: ");
if(front <= rear) {
for(i=front; i <= rear; ++i)
printf("%d ",queue[i]);
}
else {
for(i=front; i < MAX; ++i)
printf("%d ",queue[i]);
for(i=0; i<=rear; ++i)
printf("%d ",queue[i]);
}
printf("\n\n");
return;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
int main ( int argc, char **argv ) {
int i, size, nk;
double pki, dumb;
char *file, *file2, cmd[100];
FILE *pt, *fl;
file = argv[1];
file2 = argv[2];
/* Obtaining numer of lines of file 1,
* file to interpolate*/
sprintf( cmd," wc -l < ./%s", file );
FILE *f = popen( cmd,"r" );
char path[100];
while ( fgets(path, sizeof(path)-1, f ) != NULL) {
printf("\nLines in ascci input file: %s\n", path);
size = atoi(path);
}
pclose(f);
double k[size], pk[size];
/*Reading file to perform the interpolation*/
pt = fopen( file,"r" );
for (i=0; i<size;i++){
fscanf( pt, "%lf %lf", &k[i],&pk[i] );
}
pclose(pt);
/* Obtaining numer of lines of
* file containing k values*/
sprintf( cmd," wc -l < ./%s", file2 );
f = popen( cmd,"r" );
char path2[100];
while ( fgets(path2, sizeof(path2)-1, f) != NULL) {
printf("\nLines in k input file: %s\n", path2);
nk = atoi(path2);
}
pclose(f);
/*Reading file to obtain k values to perform interpolation*/
double ki[nk];
FILE *pt2 = fopen( file2,"r" );
for (i=0; i<nk;i++){
fscanf( pt2, "%lf %lf", &ki[i],&dumb );
}
pclose(pt2);
/* Performing interpolation*/
gsl_interp_accel *acc = gsl_interp_accel_alloc ();
gsl_spline *spline = gsl_spline_alloc ( gsl_interp_cspline, size );
gsl_spline_init ( spline, k, pk, size );
/* Writing interpolated values*/
fl = fopen( "pk_interp.dat","w" );
for ( i = 0; i < nk; i++ ){
pki = gsl_spline_eval ( spline, ki[i], acc );
fprintf ( fl,"%lf %lf\n", ki[i], pki );
}
printf("Interpolation performed\n\n");
// Realising memory
gsl_spline_free (spline);
gsl_interp_accel_free (acc);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DESC 0
#define ASC 1
#define WINDOW 2
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
void printArray(int *arr, size_t n)
{
int i;
for (i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
void swap(int *arr, int idx1, int idx2)
{
int tmp = arr[idx1];
arr[idx1] = arr[idx2];
arr[idx2] = tmp;
}
void insertionSort(int *arr, size_t n, int asc)
{
/*
n uzunlugunda bir dizgeyi alip Insertion Sort algoritmasi ile siralar
asc: ASC/DESC sekilde siralama icin.
*/
int i, j;
for (i = 0; i < n - 1; i++) // Butun elemanlar icin
{
for (j = i + 1; j < n; j++) // i. elemandan itibaren
{
if ((asc && arr[i] < arr[j]) || (!asc && arr[i] > arr[j]))
{
// ASC ise ilk sol eleman sag elemandan kucukse
// veya DESC ise ve sol eleman sag elemandan buykse
continue; // burasi sirali zaten gec
}
else
{
swap(arr, i, j); // degilse yerlerini degistir
}
}
}
}
void merge_sorted(int *arr1, size_t arr1_s, int *arr2, size_t arr2_s, int *target, int asc)
{
int i, i1, i2; // Genel sayac, ilk kismin sayaci, ikinci kismin sayaci
size_t lim = arr1_s + arr2_s; // sonucun toplam uzunlugu
i1 = 0;
i2 = 0;
for (i = 0; i < lim; i++)
{
if (i1 >= arr1_s || i2 >= arr2_s)
break; // sayaclar limitlerden buyuk olursa donguyu kes
if ((asc && (arr1[i1] < arr2[i2]) || !asc && ((arr1[i1] > arr2[i2])))) // ASC/DESC kontrolu
{
target[i] = arr1[i1]; // Sonuca ekle
i1++; // Sayaci arttir
}
else
{
target[i] = arr2[i2];
i2++;
}
}
// Eger ilk dizgedeki elemanlar tukendiyse kalani ikinci dizgeden doldur
if (i1 >= arr1_s)
{
for (; i2 < arr2_s; i2++)
{
target[i] = arr2[i2];
i++;
}
}
// Eger ikinci dizgedeki elemanlar tukendiyse kalani ilk dizgeden doldur
if (i2 >= arr2_s)
{
for (; i1 < arr1_s; i1++)
{
target[i] = arr1[i1];
i++;
}
}
}
void timsort(int *arr, int *target, int n, int asc)
{
/*
Kucuk alt-dizgeleri Insertion Sort ile sirala
*/
int i = 0;
for (; i < n; i += WINDOW)
{
insertionSort(&arr[i], MIN((n - i), WINDOW), asc);
}
/*
Pencere araligini surekli iki kat arttirarak sirayla Merge Array uygula
*/
int j;
for (i = WINDOW; i < n; i *= 2) // i pencere araligi
{
for (j = 0; j < n; j += 2 * i)
{
// arr[j] sol parcanin baslangic yeri // MIN(i, n-j) sol parcanin uzunlugu
// arr[i+j] sag parcanin baslangic yeri // MAX(0, MIN(i, n - j -i)) sag parcanin uzunlugu
merge_sorted(&arr[j], MIN(i, n - j), &arr[i + j], MAX(0, MIN(i, n - j -i)), &target[j], asc);
}
// Siralama gerceklestikten sonra arr degiskenin sirali hale getir
memcpy(arr, target, sizeof(int) * n);
}
}
int main(int argc, char **argv)
{
int arr[11] = {3, 15, 4, 1, -1, 5, 7, 12, 31, -4, -7};
int *target = malloc(sizeof(int) * 11);
timsort(arr, target, 11, ASC);
printArray(target, 11);
return 0;
}
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
char buf[1024];
int main(void)
{
int fd;
int ret;
char *ptr[3];
int i;
char command[128];
system("ps -eo vsz,rss,pid,comm | grep a.out");
system("cat /proc/meminfo | grep MemFree");
fd = open("/dev/my_mem0", O_RDWR | O_SYNC);
if (fd < 0) {
printf("fail to open my_mem0\n");
return 0;
}
ptr[0] = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
if (ptr == MAP_FAILED) {
perror("mmap failed");
}
printf("ptr-%p\n", ptr[0]);
for (i = 0; i < 10; i++) {
printf("%x ", ptr[0][i]);
}
printf("\n");
ptr[1] = mmap(NULL, 4096*2, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 4096*1);
if (ptr == MAP_FAILED) {
perror("mmap failed");
}
printf("ptr-%p\n", ptr[1]);
for (i = 0; i < 10; i++) {
printf("%x ", ptr[1][i]);
}
printf("\n");
ptr[2] = mmap(NULL, 4096*3, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 4096*3);
if (ptr == MAP_FAILED) {
perror("mmap failed");
}
printf("ptr-%p\n", ptr[2]);
for (i = 0; i < 10; i++) {
printf("%x ", ptr[2][i]);
}
printf("\n");
printf("ptr-%p\n", ptr[2] + 4096);
for (i = 4096; i < 4096 + 10; i++) {
printf("%x ", ptr[2][i]);
}
printf("\n");
system("ps -eo vsz,rss,pid,comm | grep a.out");
system("cat /proc/meminfo | grep MemFree");
sprintf(command, "cat /proc/%d/smaps", getpid());
system(command);
sleep(1);
munmap(ptr[0], 4096);
munmap(ptr[1], 4096*2);
munmap(ptr[2], 4096*3);
close(fd);
return 0;
}
|
C
|
#include "crypto.h"
int main()
{
//===========================================================================================
//Déclaration
//===========================================================================================
char* chaine=NULL;
int i=0;
float* freq=NULL;
int cle=0;
int choix=0;
do{ //Boucle pour recommencer le programme tant que l'utilisateur ne la pas décidé
print_Prog(); // Affichage styliser du pragramme
choix=menu(); // Choix du menu
switch (choix)
{
//===========================================================================================
//1er menu
//Chiffrement d'un msg d'après la méthode César en fonction d'une clé
//===========================================================================================
case 1:
chaine=saisieChaine(); // Saisie de la chaine
cle=saisieCle(); // Saisie de la clé
printf("\nLe message crypté est:\n");
for (i=0;i<strlen(chaine);i++) // boucle pour chiffrer un à un les caractère
//de la chaine
{
printf("%c",chiffrement(chaine[i],cle));
}
printf("\n\n");
break;
//===========================================================================================
//2ème menu
//Dechiffrement d'un msg d'après la méthode César en fonction d'une clé
//===========================================================================================
case 2:
chaine=saisieChaine(); // Saisie de la chaine
cle=saisieCle(); // Saisie de la clé
printf("\nLe message décrypté est:\n");
for (i=0;i<strlen(chaine);i++) // booucle pour déchiffrer un à un les
//caractère de la chaine
{
printf("%c",dechiffrement(chaine[i],cle));
}
printf("\n\n");
break;
//===========================================================================================
//3ème menu
//Analyse de la fréquence d'aparition des lettres du msg en %
//===========================================================================================
case 3:
chaine=saisieChaine(); // Saisie de la chaine
freq=analyseFreq(chaine, strlen(chaine));
//Calcule de la fréquence d'aparition des lettres dans la chaine
printf("La fréquence d'apparition des lettres sont:\n");
for(i=0;i<26;i++) // boucle pour afficher la fréquence de chaque lettre
{
printf("'%c': ",('A'+i));
printf("%f\n",freq[i]);
}
break;
//===========================================================================================
//4ème menu
//Récupération de la clé après Analyse de la fréquence d'apparition des lettres dans le msg
//===========================================================================================
case 4:
chaine=saisieChaine(); // Saisie de la chaine
freq=analyseFreq(chaine, strlen(chaine));
//Calcule de la fréquence d'aparition des lettres dans la chaine
printf("La clé du msg est: %d\n",calculCle(freq));
// Affichage de la clé de la chaine après analyse et calcule de la clé
printf("\n");
break;
//===========================================================================================
//5ème menu
//Déchiffrement automatique du message après récupération de la clé
//===========================================================================================
case 5:
chaine=saisieChaine();
freq=analyseFreq(chaine, strlen(chaine));
cle=calculCle(freq);
for (i=0;cle>26;i++)
{
cle=cle-26;
}
printf("\n\nLe message décrypté est:\n");
for (i=0;i<strlen(chaine);i++)
{
printf("%c",dechiffrement(chaine[i],cle));
}
printf("\n\n");
break;
//===========================================================================================
//6ème menu
//Sortie du programme
//===========================================================================================
case 6:
break;
//===========================================================================================
//Default
//Affichage par défault si la choix ne correspond à aucun menu
//===========================================================================================
default:
printf("Votre choix n'est pas valide.");
}
printf("Appuyer sur une touche pour continuer\n");
getchar();
} while (choix != 6);
system ("clear");
return 0;
}
|
C
|
//socket
//ȷscokaddr_inṹ
// ʮIPת
//ʹbind
//ʹlisten
//ʹaccept
// acceptµ
//ʹrecvմݣļ·
//ļҪļ
// Ӹַȡļ
//ʹrecvļ
// жrecvص״̬
//յݷ뻺
//дļ
//رļ
//رsocket
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <netinet/in.h>
#include <errno.h>
#include <memory.h>
#include <stdlib.h> //for malloc
#define MAXLINE 4096
#define BUFFER_SIZE 1024
int main()
{
int sockfd; //Socket
int temp,n;
struct sockaddr_in server,client; //ַṹͿͻ˵ַṹ
char filename[100]; //ļ
char filepath[100]; //ļ·
char *buffer;//file buffer ļ
int fileTrans;
buffer = (char *)malloc(sizeof(char)*BUFFER_SIZE);
bzero(buffer,BUFFER_SIZE);
//memset(buffer,0,sizeof(buffer));
int lenfilepath;
FILE *fp;
int writelength;
//һʽ TCP
if((sockfd = socket(AF_INET,SOCK_STREAM,0))<0)
{
printf("socket build error!\n");
}
else
{
printf("socket build success!\n");
}
//÷ַ
memset(&server,0,sizeof(server)); // bzero(&server,sizeof(server))
server.sin_family= AF_INET; //Э
server.sin_addr.s_addr = htonl(INADDR_ANY); //ַ
server.sin_port = htons(6666); //˿ں
//ַṹ
if((bind(sockfd,(struct sockaddr*)&server,sizeof(server)))==-1)
{
printf("bind error!\n");
}
else
{
printf("bind success!\n");
}
//ü
if(listen(sockfd,10)==-1)
{
printf("listen error!\n");
}
else
{
printf("listen success!\n");
}
printf("waiting..\n");
while(1)
{
if((temp = accept(sockfd,(struct sockaddr*)NULL,NULL))>0)
{
//printf("client IP: %d\n",ntohl(client.sin_addr.s_addr));
//printf("client PORT: %d\n",ntohs(client.sin_port));
memset(filename,'\0',sizeof(filename));
memset(filepath,'\0',sizeof(filepath));
lenfilepath = recv(temp,filepath,100,0);
printf("filepath :%s\n",filepath);
if(lenfilepath<0)
{
printf("recv error!\n");
}
else
{
int i=0,k=0;
for(i=strlen(filepath);i>=0;i--)
{
if(filepath[i]!='/')
{
k++;
}
else
break;
}
strcpy(filename,filepath+(strlen(filepath)-k)+1);
}
printf("filename :%s\n",filename);
fp = fopen(filename,"w");
if(fp!=NULL)
{
while(fileTrans =recv(temp,buffer,BUFFER_SIZE,0))
{
if(fileTrans<0)
{
printf("recv error!\n");
break;
}
writelength = fwrite(buffer,sizeof(char),fileTrans,fp);
if(writelength <fileTrans)
{
printf("write error!\n");
break;
}
bzero(buffer,BUFFER_SIZE);
//memset(buffer,0,sizeof(buffer));
}
printf("recv finished!\n");
fclose(fp);
}
else
{
printf("filename is null!\n");
}
close(temp);
}
else
{
printf("accept error!\n");
close(temp);
}
}
close(sockfd);
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<time.h>
#include<stdlib.h>
#define maxn 6666
int ar[maxn];
char save[maxn*6+8];
int cmp(int *a,int *b){return *a-*b;}
#define improve
#ifdef self_first
void merge_sort(int *s,int *e){
if(s+1>=e) return;
int *m=s+(e-s)/2;
merge_sort(s,m);
merge_sort(m,e);
int t[e-s];
for(int i=0,j=0,k=0;i+j<e-s;){
for(;s+i<m&&(cmp(&s[i],&m[j])>=0||m+j==e);i++)
t[k++]=s[i];
for(;m+j<e&&(cmp(&s[i],&m[j])<0||s+i==m);j++)
t[k++]=m[j];
}
memcpy(s,t,sizeof(t));
}
#endif
#ifdef improve
void merge_sort(int *s,int *e){
if(s+1>=e) return;
int *m=s+(e-s)/2;
merge_sort(s,m);
merge_sort(m,e);
int *i=s,*j=m,*t=(int*)malloc(4*(e-s)),*k=t;
while(i<m&&j<e){
if(cmp(i,j)>0) *k++=*i++;
else *k++=*j++;
}
while(i<m) *k++=*i++;
while(j<e) *k++=*j++;
memcpy(s,t,4*(e-s));
}
#endif
int main(){
srand(time(0));
for(int i=0;i<maxn;i++) ar[i]=rand();
double start=clock();
merge_sort(ar,ar+maxn);
printf("%lf\n",clock()-start);
for(int i=0;i<maxn;i++) sprintf(save+i*6,"%5d%c",ar[i],i%16==15?'\n':' ');
puts(save);
}
|
C
|
//This program plots a formula of survival probablity of mother charged pions for different distance between Neutrino target and 3D dipole.
float boostFactor(float x) //x is Neutrino Energy
{
return 0.018/(TMath::Sqrt(4*TMath::Sq(x)-TMath::Sq(0.14)));
}
void survivalprob()
{
TCanvas *c = new TCanvas();
c->SetTicks();
c->SetGrid();
//1D Function Class
TF1* f1 = new TF1("f1", "(TMath::Exp(-30*boostFactor(x)))", 0, 30); //For 30m distance
f1->SetLineColor(kRed);
f1->SetTitle("#pi^{#pm} Survival Probability (L=30m, 50m, 100m, 220m); E_{#nu} [Gev]; p(E_{#nu})");
f1->Draw();
TF1* f2 = new TF1("f2", "(TMath::Exp(-50*boostFactor(x)))", 0, 30); //For 50m distance
f2->SetLineColor(kBlue);
f2->Draw("SAME");
TF1* f3 = new TF1("f3", "(TMath::Exp(-100*boostFactor(x)))", 0, 30); //For 100m distance
f3->SetLineColor(kBlack);
f3->Draw("SAME");
TF1* f4 = new TF1("f4", "TMath::Exp(-220*boostFactor(x))", 0, 30); //For 220m distance
f4->SetLineColor(kGreen);
f4->Draw("SAME");
//Setting Legend
auto legend = new TLegend(0.8,0.5,0.6,0.7);
legend->SetHeader("#pi^{#pm} Survival Probability","C"); // option "C" for centering legend title
legend->AddEntry("f1","L=30m","l"); // l for line
legend->AddEntry("f2","L=50m","l");
legend->AddEntry("f3","L=100m","l");
legend->AddEntry("f4","L=220m","l");
legend->Draw();
}
|
C
|
#include<stdio.h>
long m(int n)
{
if(n<=0)
return 1;
return n * m(n-1);
}
int main()
{
printf("%ld",m(6));
}
|
C
|
__attribute__((always_inline)) unsigned char SIZE(unsigned char n)
{
return n & 0x7F;
}
__attribute__((always_inline)) unsigned char FREE(unsigned char n)
{
return n >> 7;
}
int main()
{
unsigned char tab[19*19] = {0};
int n;
int i;
int j;
int a;
int b;
for (n = 0; n < 1000000; n++)
for (i = 0; i < 19; i++)
for (j = 0; j < 19; j++)
{
a = SIZE(tab[i * j]);
b = FREE(tab[i * j]);
}
return 0;
}
|
C
|
#include <stdio.h>
int main(int argc, char **argv)
{
int i = 0;
while ( i++ < 3 ) {
printf("start of while\n");
if ( 1 ) {
printf("true\n");
continue;
} else {
printf("never\n");
}
if ( 1 ) printf("always\n");
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.