language
string | src_encoding
string | length_bytes
int64 | score
float64 | int_score
int64 | detected_licenses
sequence | license_type
string | text
string |
---|---|---|---|---|---|---|---|
C | UTF-8 | 7,106 | 3.4375 | 3 | [] | no_license | #include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <sys/time.h>
#include "sorting.h"
#define true 1
#define false 0
#define SOGLIA_QSORT 69
#define SOGLIA_MSORT 64
int * vcopy(int v[], int n){
int i = 0;
int * vett = malloc(sizeof(int) * n);
for(i = 0; i < n; i ++){
vett[i] = v[i];
}
return vett;
}
/** SELECTION SORT */
void ssort(int a[], int n) {
int i = 0, j, min;
while (i < n) {
min = i;
for(j = 0; j < n - i; j ++){
if(a[min] > a[j+i])
min = j+i;
}
scambia(a, i, min);
i++;
}
}
void ssortMax(int a[], int n) {
int i = n, j, max;
while (i > 0){
max = i;
for (j = i - 1; j >= 0; j--) {
if(a[max] < a[j])
max = j;
}
scambia(a, i, max);
i--;
}
//for(i = 0; i < n; i ++)
//printf("\n%d", a[i]);
}
/** INSERTION SORT */
/** METODO AUSILIARIO INSERISCI
preso come parametro un array v di interi ORDINATO
fino all'elemento di indice i-1,
inserisce l'intero a[i] al posto giusto in v[0..i]
*/
void inserisci(int v[], int i) {
int temp = v[i], j = i;
while(j > 0 && v[j - 1] > temp){
v[j] = v[j-1];
j--;
}
v[j] = temp;
}
void isort(int a[], int n) {
//printf("isort");
int i;
for(i = 0; i < n; i++)
inserisci(a, i);
}
void inserisci2(int v[], int i, int min) {
int temp = v[i], j = i;
while(j > min && v[j - 1] > temp){
v[j] = v[j-1];
j--;
}
v[j] = temp;
}
void isort2(int a[], int inf, int sup){
int i;
for (i = inf; i <= sup; i++)
inserisci2(a, i, inf);
}
void isort3(int a[], int fst, int lst) {
int i;
for (i = fst + 1; i <= lst; i++) {
int x = a[i];
int j = i;
while (j > fst && x < a[j-1]) {
a[j] = a[j-1];
j--;
}
a[j] = x;
}
}
/** MERGESORT */
void merge(int a[], int first, int middle, int last, int aux[]){
int i = first, j = middle+1, k = first;
while(i <= middle && j <= last) {
if(a[i] <= a[j])
aux[k++] = a[i++];
else
aux[k++] = a[j++];
}
int h, l, r;
for(h = middle, l = last; h >= i;)//Ricopio la parte ordinata del primo segmento in a
a[l--] = a[h--];
for(r = first; r < k; r++)//Ricopio la parte ordinata del secondo segmento in a
a[r] = aux[r];
}
void mergesortASDric(int a[], int first, int last, int aux[]){
if(first < last) {
int m = (first+last)/2;
mergesortASDric(a, first, m, aux);
mergesortASDric(a, m+1, last, aux);
merge(a, first, m, last, aux);
}
}
void mergesortASD(int a[], int n) {
int * aux = malloc(sizeof(int) * n);
mergesortASDric(a, 0, n-1, aux);
}
void scambia(int * arr, int i1, int i2){
int temp = arr[i1];
arr[i1] = arr[i2];
arr[i2] = temp;
}
/////////////////////////
/** INIZIO COMPITO 05 **/
/////////////////////////
//TODO: mergesort - versione-base, con insertion-sort su porzioni sotto una soglia;
//TODO: mergesort - versione senza chiamate inutili del merge (ed eventualmente con merge ottimizzato);
//TODO: mergesort - versione "a passo alternato".
/** QUICKSORT **/
//TODO: quicksort - versione del libro di testo;
//TODO: quicksort - una delle versioni alla Hoare;
//TODO: (facoltativo) quicksort - un'altra versione a scelta;
//TODO: quicksort - la versione alla Hoare scelta sopra, ottimizzata con insertion sort sotto un'opportuna soglia, da determinarsi per mezzo di prove;
/////////////
//Compito05//
//Mergesort//
/////////////
void msortB(int a[], int first, int last, int aux[], int soglia){
if(last - first < soglia){
isort2(a, first, last);
return;
}
if(first < last) {
int m = (first+last)/2;
msortB(a, first, m, aux, soglia);
msortB(a, m+1, last, aux, soglia);
merge(a, first, m, last, aux);
}
}
void mergesortB(int a[], int l){
int * aux = malloc(sizeof(int) * l);
msortB(a, 0, l-1, aux, SOGLIA_MSORT);
}
void mergesortBTestSoglia(int a[], int l, int soglia){
int * aux = malloc(sizeof(int) * l);
msortB(a, 0, l-1, aux, soglia);
}
//Mergesort senza chiamate inutili del merge
void msortO(int a[], int first, int last, int aux[]){
if(first < last) {
int m = (first+last)/2;
msortO(a, first, m, aux);
msortO(a, m+1, last, aux);
if(a[m] > a[m+1])
merge(a, first, m, last, aux);
}
}
void mergesortO(int a[], int n) {
int * aux = malloc(sizeof(int) * n);
msortO(a, 0, n-1, aux);
}
//Mergesort passo alternato
void mergePA(int a[], int fst, int mid, int lst, int c[]) {
int i = fst, j = mid+1, k = fst;
while(i <= mid && j <= lst) {
if(a[i]<= a[j])
c[k++] = a[i++];
else
c[k++] = a[j++];
}
while(i <= mid) c[k++] = a[i++];
while(j <= lst) c[k++] = a[j++];
}
void msortPA(int a[], int inf, int sup, int b[]){
if(inf < sup) {
int m = (inf + sup)/2;
msortPA(b, inf, m, a);
msortPA(b, m+1, sup, a);
mergePA(b, inf, m, sup, a);
}
}
void mergesortPA(int * a, int l) {
int * aux = malloc(sizeof(int) * l);
aux = vcopy(a, l);
msortPA(a, 0, l-1, aux);
}
/////////////
//Quicksort//
/////////////
void qsortASD(int * a, int inf, int sup){
if(inf < sup){
srand((int) time(NULL));
int iPivot = inf + rand() % (sup - inf);
scambia(a, sup, iPivot);
int x = a[sup];
int i = inf;
int j = sup-1;
while(i <= j) {
while(i <= j && a[i] <= x) i++;
while(i <= j && a[j] >= x) j--;
if(i < j) scambia(a, i, j);
}
scambia(a,i,sup);
qsortASD(a, inf, i-1);
qsortASD(a, i+1, sup);
}
}
void quicksort(int * arr, int l){
qsortASD(arr, 0, l);
}
//Da provare
void qsortHoare(int a[], int inf, int sup) {
if(inf < sup) {
srand((int) time(NULL));
int iPivot = inf + rand() % (sup - inf);
int x = a[iPivot];
int i = inf;
int j = sup;
do{
while(a[i] < x) i++;
while(a[j] > x) j--;
if(i <= j){
scambia(a,i,j);
i++; j--;
}
}while (i <= j);
qsortHoare(a, inf, j);
qsortHoare(a, i, sup);
}
}
void quicksortHoare(int v[], int l){
qsortHoare(v, 0, l);
}
void qsortOttimizzato(int a[], int inf, int sup, int soglia){
if((sup - inf) <= soglia){
isort2(a, inf, sup);
return;
}
if(inf < sup) {
srand((int) time(NULL));
int iPivot = inf + rand() % (sup - inf);
int x = a[iPivot];
int i = inf;
int j = sup;
do{
while(a[i] < x) i++;
while(a[j] > x) j--;
if(i <= j){
scambia(a,i,j);
i++; j--;
}
}while (i <= j);
qsortOttimizzato(a, inf, j, soglia);
qsortOttimizzato(a, i, sup, soglia);
}
}
void quicksortOttimizzato(int a[], int l){
qsortOttimizzato(a, 0, l, SOGLIA_QSORT);
}
void quicksortOttimizzatoTestSoglia(int a[], int l, int soglia){
qsortOttimizzato(a, 0, l, soglia);
}
|
C | UTF-8 | 696 | 2.65625 | 3 | [
"MIT"
] | permissive | #ifndef __KERNELS_H__
#define __KERNELS_H__
enum
{
KERNEL_MEAN = 0,
KERNEL_WMEAN,
KERNEL_GAUSS,
KERNEL_SOBEL_X,
KERNEL_SOBEL_Y,
KERNEL_SOBEL_B,
KERNEL_LAPLACIAN,
NUM_KERNEL_TYPE // Make sure this stays at the end!
};
double Gauss2d(int x, int y);
void createGaussKernel( int m_conv_x, int m_conv_y, double &m_div, double* buffer);
void createMeanKernel( int m_conv_x, int m_conv_y, double &m_div, double* buffer);
void createSobXKernel( int m_conv_x, int m_conv_y, double &m_div, double* buffer);
void createSobYKernel( int m_conv_x, int m_conv_y, double &m_div, double* buffer);
void createLaplacianKernel( int m_conv_x, int m_conv_y, double &m_div, double* buffer);
#endif
|
C | UTF-8 | 4,707 | 2.71875 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* color.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ebatchas <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/03/17 22:09:32 by ebatchas #+# #+# */
/* Updated: 2019/03/17 22:09:44 by ebatchas ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_print_foreground2(char *str)
{
if (!ft_strcmp(str, "F_LIGHT_RED"))
return (ft_tally_print(F_LIGHT_RED, DEFAULT_LEN1));
else if (!ft_strcmp(str, "F_LIGHT_GREEN"))
return (ft_tally_print(F_LIGHT_GREEN, DEFAULT_LEN1));
else if (!ft_strcmp(str, "F_LIGHT_YELLOW"))
return (ft_tally_print(F_LIGHT_YELLOW, DEFAULT_LEN1));
else if (!ft_strcmp(str, "F_LIGHT_BLUE"))
return (ft_tally_print(F_LIGHT_BLUE, DEFAULT_LEN1));
else if (!ft_strcmp(str, "F_LIGHT_MAGENTA"))
return (ft_tally_print(F_LIGHT_MAGENTA, DEFAULT_LEN1));
else if (!ft_strcmp(str, "F_LIGHT_CYAN"))
return (ft_tally_print(F_LIGHT_CYAN, DEFAULT_LEN1));
else if (!ft_strcmp(str, "F_WHITE"))
return (ft_tally_print(F_WHITE, DEFAULT_LEN1));
else
return (-1);
}
static int ft_print_foreground(char *str)
{
if (!ft_strcmp(str, "F_DEFAULT"))
return (ft_tally_print(F_DEFAULT, DEFAULT_LEN1));
else if (!ft_strcmp(str, "F_EOC"))
return (ft_tally_print(F_EOC, DEFAULT_LEN2));
else if (!ft_strcmp(str, "F_BLACK"))
return (ft_tally_print(F_BLACK, DEFAULT_LEN1));
else if (!ft_strcmp(str, "F_RED"))
return (ft_tally_print(F_RED, DEFAULT_LEN1));
else if (!ft_strcmp(str, "F_GREEN"))
return (ft_tally_print(F_GREEN, DEFAULT_LEN1));
else if (!ft_strcmp(str, "F_YELLOW"))
return (ft_tally_print(F_YELLOW, DEFAULT_LEN1));
else if (!ft_strcmp(str, "F_BLUE"))
return (ft_tally_print(F_BLUE, DEFAULT_LEN1));
else if (!ft_strcmp(str, "F_MAGENTA"))
return (ft_tally_print(F_MAGENTA, DEFAULT_LEN1));
else if (!ft_strcmp(str, "F_CYAN"))
return (ft_tally_print(F_CYAN, DEFAULT_LEN1));
else if (!ft_strcmp(str, "F_LIGHT_GRAY"))
return (ft_tally_print(F_LIGHT_GRAY, DEFAULT_LEN1));
else if (!ft_strcmp(str, "F_DARK_GRAY"))
return (ft_tally_print(F_DARK_GRAY, DEFAULT_LEN1));
else
return (ft_print_foreground2(str));
}
static int ft_print_background2(char *str)
{
if (!ft_strcmp(str, "B_LIGHT_RED"))
return (ft_tally_print(B_LIGHT_RED, DEFAULT_LEN1));
else if (!ft_strcmp(str, "B_LIGHT_GREEN"))
return (ft_tally_print(B_LIGHT_GREEN, DEFAULT_LEN1));
else if (!ft_strcmp(str, "B_LIGHT_YELLOW"))
return (ft_tally_print(B_LIGHT_YELLOW, DEFAULT_LEN1));
else if (!ft_strcmp(str, "B_LIGHT_BLUE"))
return (ft_tally_print(B_LIGHT_BLUE, DEFAULT_LEN1));
else if (!ft_strcmp(str, "B_LIGHT_MAGENTA"))
return (ft_tally_print(B_LIGHT_MAGENTA, DEFAULT_LEN1));
else if (!ft_strcmp(str, "B_LIGHT_CYAN"))
return (ft_tally_print(B_LIGHT_CYAN, DEFAULT_LEN1));
else if (!ft_strcmp(str, "B_WHITE"))
return (ft_tally_print(B_WHITE, DEFAULT_LEN1));
else
return (-1);
}
static int ft_print_background(char *str)
{
if (!ft_strcmp(str, "B_DEFAULT"))
return (ft_tally_print(B_DEFAULT, DEFAULT_LEN1));
else if (!ft_strcmp(str, "B_EOC"))
return (ft_tally_print(B_EOC, DEFAULT_LEN2));
else if (!ft_strcmp(str, "B_BLACK"))
return (ft_tally_print(B_BLACK, DEFAULT_LEN1));
else if (!ft_strcmp(str, "B_RED"))
return (ft_tally_print(B_RED, DEFAULT_LEN1));
else if (!ft_strcmp(str, "B_GREEN"))
return (ft_tally_print(B_GREEN, DEFAULT_LEN1));
else if (!ft_strcmp(str, "B_YELLOW"))
return (ft_tally_print(B_YELLOW, DEFAULT_LEN1));
else if (!ft_strcmp(str, "B_BLUE"))
return (ft_tally_print(B_BLUE, DEFAULT_LEN1));
else if (!ft_strcmp(str, "B_MAGENTA"))
return (ft_tally_print(B_MAGENTA, DEFAULT_LEN1));
else if (!ft_strcmp(str, "B_CYAN"))
return (ft_tally_print(B_CYAN, DEFAULT_LEN1));
else if (!ft_strcmp(str, "B_LIGHT_GRAY"))
return (ft_tally_print(B_LIGHT_GRAY, DEFAULT_LEN1));
else if (!ft_strcmp(str, "B_DARK_GRAY"))
return (ft_tally_print(B_DARK_GRAY, DEFAULT_LEN1));
else
return (ft_print_background2(str));
}
int ft_print_color(char *str)
{
int ret;
ret = ft_print_foreground(str);
if (ret < 0)
ret = ft_print_background(str);
return (ret < 0 ? 0 : 1);
}
|
C | UTF-8 | 1,606 | 2.609375 | 3 | [] | no_license | /*
===============================================================================
Name : Lab_5.c
Author : $(author)
Version :
Copyright : $(copyright)
Description : main definition
===============================================================================
*/
#ifdef __USE_CMSIS
#include "LPC17xx.h"
#endif
#include <cr_section_macros.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "spi.h"
#include "mfrc522.h"
#include "mfrc.h"
#include "lcd.h"
#include "wait.h"
#include "flash.h"
#define INPUT_MASK 1<<26
#define SECTOR_29_ADDRESS 0x00078000
#define UID_SIZE 4
//assume que uid não é maior que 4
unsigned int getUidUint(Uid* uidPtr){
unsigned int val = 0;
if (uidPtr->size > 4){
printf("Não é garantido o funcionamento correto para cartões com uid maior que 4.");
}
for (int i=0; i<UID_SIZE; ++i){
val |= (uidPtr->uidByte[i] << 8*i);
}
return val;
}
void saveInFlash(Uid* uidPtr){
unsigned int val = getUidUint(uidPtr);
FLASH_EraseSectors(29, 29);
FLASH_WriteData((unsigned int *)SECTOR_29_ADDRESS, &val, 4);
}
int main(void) {
LCDText_Init();
MFRC522_Init();
WAIT_Init();
Uid uid;
unsigned int *addr = (unsigned int *)SECTOR_29_ADDRESS;
while(1){
LCDText_Locate(0, 0);
LCDText_Printf("Memory:%u", *addr);
while(!PICC_IsNewCardPresent()){
printf("try\n");
}
printf("card present\n");
int result = PICC_ReadCardSerial(&uid);
if(result){
printf("card read\n");
LCDText_Locate(1, 0);
LCDText_Printf("UID:%u", getUidUint(&uid));
saveInFlash(&uid);
WAIT_Ms(1000);
}
}
return 0 ;
}
|
C | UTF-8 | 393 | 2.828125 | 3 | [] | no_license | #include <stdio.h>
#include <gsl_rng.h>
#include <gsl_randist.h>
int main (int argc, char *argv[])
{
/* set up GSL RNG */
gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937);
/* end of GSL setup */
int i,n;
double gauss,gamma;
n=atoi(argv[1]);
for (i=0;i<n;i++) {
gauss=gsl_ran_gaussian(r,2.0);
gamma=gsl_ran_gamma(r,2.0,3.0);
printf("%2.4f %2.4f\n", gauss,gamma);
}
return(0);
}
|
C | UTF-8 | 140 | 2.84375 | 3 | [] | no_license | #include <stdio.h>
int main(){
int i, x;
scanf("%d", &x);
for (i = 1; i <= x; i++){
printf("Bem - Vindos!\n");
}
} |
C | UTF-8 | 1,959 | 2.859375 | 3 | [] | no_license | #include <windows.h>
#include <stdio.h>
#include <string.h>
HANDLE port, hPort;
HANDLE OpenPort()
{
DCB dcb;
hPort = CreateFile("COM4", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if(hPort == INVALID_HANDLE_VALUE)
printf("CHYBA: nie je mozne otvorit port");
else
printf("Pristup na port v poriadku\n\n");
memset(&dcb, 0x0, sizeof(DCB)); // nastavy vsetky prvky struktory na 0
dcb.DCBlength = sizeof(DCB);
dcb.BaudRate = 9600;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
SetCommState(hPort, &dcb);
if(!SetCommState(hPort, &dcb))
{
printf("CHYBA: neda sa nakonfigurovat port");
CloseHandle(hPort);
hPort = INVALID_HANDLE_VALUE;
}
return hPort;
}
int main(void)
{
DWORD dwRead, dwWritten;
int PocetZnakovPrijem, PocetZnakovVysielanie,
pocitadlo = 0;
unsigned char PrijatyZnak[] = "-",
NoveData[6],
adresa = 0x81;
DWORD dwCommModemStatus;
NoveData[0] = 1;
NoveData[1] = 2;
NoveData[2] = 1;
NoveData[3] = 2;
NoveData[4] = 1;
NoveData[5] = 2;
printf("Ovladac 1.2 DME\n");
port = OpenPort();
if(hPort == INVALID_HANDLE_VALUE)
{
printf("CHYBA: otvorenie portu zlyhalo");
getch();
return 0x01;
}
SetCommMask (port, EV_RXCHAR); // nastavuje na aku udalost (event) sa bude reagovat
PocetZnakovPrijem = strlen(PrijatyZnak);
PocetZnakovVysielanie = strlen(NoveData);
while (!kbhit())
{
printf("pocitadlo = %d %c\r", pocitadlo, PrijatyZnak);
// WriteFile(port, &adresa, 1, &dwWritten, NULL);
// WriteFile(port, NoveData, PocetZnakovVysielanie, &dwWritten, NULL);
WaitCommEvent (port, &dwCommModemStatus, 0); // caka kym nepride po seriaku dajaky znak
ReadFile(port, &PrijatyZnak, 1, &dwRead, NULL); // precita znak zo seriaku
pocitadlo++;
Sleep(1);
}
CloseHandle(hPort);
return 0x00;
}
|
C | UTF-8 | 3,574 | 3.109375 | 3 | [] | no_license | #include <mpi.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
////////////////////////////////////////////////////////////////////////////////
// Program main
////////////////////////////////////////////////////////////////////////////////
char *textData;
int textLength;
char *patternData;
int patternLength;
clock_t c0, c1;
time_t t0, t1;
void outOfMemory()
{
fprintf (stderr, "Out of memory\n");
exit (0);
}
void readFromFile (FILE *f, char **data, int *length)
{
int ch;
int allocatedLength;
char *result;
int resultLength = 0;
allocatedLength = 0;
result = NULL;
ch = fgetc (f);
while (ch >= 0)
{
resultLength++;
if (resultLength > allocatedLength)
{
allocatedLength += 10000;
result = (char *) realloc (result, sizeof(char)*allocatedLength);
if (result == NULL)
outOfMemory();
}
result[resultLength-1] = ch;
ch = fgetc(f);
}
*data = result;
*length = resultLength;
}
int readText ()
{
FILE *f;
char fileName[1000];
#ifdef DOS
sprintf (fileName, "inputs\\text.txt");
#else
sprintf (fileName, "inputs/text.txt");
#endif
f = fopen (fileName, "r");
if (f == NULL)
return 0;
readFromFile (f, &textData, &textLength);
fclose (f);
return 1;
}
int readPattern(int testNumber)
{
FILE *f;
char fileName[1000];
#ifdef DOS
sprintf (fileName, "inputs\\pattern%d.txt", testNumber);
#else
sprintf (fileName, "inputs/pattern%d.txt", testNumber);
#endif
f = fopen (fileName, "r");
if (f == NULL)
return 0;
readFromFile (f, &patternData, &patternLength);
fclose (f);
return 1;
}
int hostMatch(long *comparisons)
{
int i,j,k, lastI;
i=0;
j=0;
k=0;
lastI = textLength-patternLength;
*comparisons=0;
while (i<=lastI && j<patternLength)
{
(*comparisons)++;
if (textData[k] == patternData[j])
{
k++;
j++;
}
else
{
i++;
k=i;
j=0;
}
}
if (j == patternLength)
return i;
else
return -1;
}
void processData()
{
unsigned int result;
long comparisons;
result = hostMatch(&comparisons);
if (result == -1)
printf ("Pattern not found\n");
else
printf ("Pattern found at position %d\n", result);
printf ("# comparisons = %ld\n", comparisons);
}
int main(int argc, char **argv)
{
int testNumber;
if (!readText())
{
printf("Unable to open text file");
return 0;
}
//Initialise MPI environment
MPI_Init(NULL, NULL);
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
//If there are fewer than 2 processes, kill the execution.
if (world_size < 2)
{
fprintf(stderr, "World size must be greater than 1 for %s\n", argv[0]);
MPI_Abort(MPI_COMM_WORLD, 1);
}
//Process 0 prints the number of patterns, so that it is not printed multiple times.
if(world_rank == 0)
{
printf("Pattern search using %d processes\n", world_size);
}
//Set the testNumber so that each rank processes different pattern files.
testNumber = world_rank+1;
//While there is still another pattern to process, search the text.
while (readPattern(testNumber))
{
c0 = clock(); t0 = time(NULL);
processData();
c1 = clock(); t1 = time(NULL);
printf("Test %d run by process %d\n", testNumber, world_rank);
printf("Test %d elapsed wall clock time = %ld\n", testNumber, (long) (t1 - t0));
printf("Test %d elapsed CPU time = %f\n\n", testNumber, (float) (c1 - c0)/CLOCKS_PER_SEC);
testNumber+=world_size;
}
//End of MPI section
MPI_Finalize();
}
|
C | UTF-8 | 5,918 | 2.828125 | 3 | [] | no_license | #include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
//#include "wshell.h"
int Mysh_cd(char **args,char **hist, int current);
int Mysh_help(char **args,char **hist, int current);
int Mysh_exit(char **args,char **hist, int current);
int Mysh_history(char **args,char **hist, int current);
int clear_history(char **args,char **hist, int current);
int lastcommand(char **args,char **hist, int current);
/*
List of builtin commands, followed by their corresponding functions.
*/
char *builtin_str[] = {
"cd",
"help",
"exit",
"history",
"hc",
"!!"
};
int (*builtin_func[]) (char **,char **, int) = {
&Mysh_cd,
&Mysh_help,
&Mysh_exit,
&Mysh_history,
&clear_history,
&lastcommand
};
int Mysh_num_builtins() {
return sizeof(builtin_str) / sizeof(char *);
}
int Mysh_cd(char **args,char *hist[], int current)
{
if (args[1] == NULL)
{
fprintf(stderr, "Mysh: expected argument to \"cd\"\n");
}
else
{
if (chdir(args[1]) != 0)
//chdir() changes the current working directory to that specified in path
perror("Mysh");}
return 1;
}
int Mysh_help(char **args,char *hist[], int current)
{
int i;
printf("YangMing's SHELL\n");
printf("The following are built in:\n");
for (i = 0; i < Mysh_num_builtins(); i++) {
printf(" %s\n", builtin_str[i]);
}
return 1;
}
int Mysh_exit(char **args,char *hist[], int current)
{
return 0;
}
#define HISTORY_COUNT 20
int Mysh_history(char **args,char *hist[], int current)
{
int i = current;
int hist_num = 1;
do {
if (hist[i]) {
printf("%4d %s\n", hist_num, hist[i]);
hist_num++;
}
i = (i + 1) % HISTORY_COUNT;
} while (i != current);
return 1;
}
int clear_history(char **args,char *hist[], int current)
{
int i;
for (i = 0; i < HISTORY_COUNT; i++) {
free(hist[i]);
hist[i] = NULL;
}
return 1;
}
int Mysh_execute(char **args,char *hist[], int current);
char **Mysh_split_line(char *line);
int lastcommand(char **args,char *hist[], int current)
{
free(hist[current-1]);
hist[current-1] = NULL;
char *newline;
newline=strdup(hist[current-2]);
// printf("newline:%s\n", newline);
args = Mysh_split_line(newline);
return Mysh_execute(args,hist,current);
}
char *Mysh_read_line(void)
{
char *line = NULL;
ssize_t bufsize = 0; // have getline allocate a buffer for us
getline(&line, &bufsize, stdin);
//if (line[strlen(line) - 1] == '\n')
//line[strlen(line)]-1 = '\0';
return line;
}
#define Mysh_TOK_BUFSIZE 64
#define Mysh_TOK_DELIM " \t\r\n\a"
char **Mysh_split_line(char *line)
{
int bufsize = Mysh_TOK_BUFSIZE, position = 0;
char **tokens = malloc(bufsize * sizeof(char*));
char *token, **tokens_backup;
if (!tokens) {
fprintf(stderr, "Mysh: allocation error\n");
exit(EXIT_FAILURE);
}
token = strtok(line, Mysh_TOK_DELIM);
//breaks string str into a series of tokens using the delimiter delim
while (token != NULL) {
tokens[position] = token;
position++;
if (position >= bufsize) {
bufsize += Mysh_TOK_BUFSIZE;
tokens_backup = tokens;
tokens = realloc(tokens, bufsize * sizeof(char*));
if (!tokens) {
free(tokens_backup);
fprintf(stderr, "Mysh: allocation error\n");
exit(EXIT_FAILURE);
}
}
token = strtok(NULL, Mysh_TOK_DELIM);
}
tokens[position] = NULL;
return tokens;
}
int Mysh_launch(char **args)
{
pid_t pid;
int status;
pid = fork();
//fork() creates a child process that differs from the parent process only in its PID and PPID
if (pid == 0) {// Child process
if (execvp(args[0], args) == -1)
//execvp: executes the program pointed to by filename
{
perror("Mysh");
//prints a descriptive error message to stderr.
// First the string str is printed, followed by a colon then a space.
}
exit(EXIT_FAILURE);
}
else if (pid < 0) {
// Error forking
perror("Mysh");
} else {
// Parent process
do {
waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
// WIFEXITED:Process Completion Status
}
return 1;
}
int Mysh_execute(char **args, char **hist, int current)
{
int i;
if (args[0] == NULL) {
// An empty command was entered.
return 1;
}
for (i = 0; i < Mysh_num_builtins(); i++) {
if (strcmp(args[0], builtin_str[i]) == 0)
//strcmp:compare str1 with str2,这里str2等于str1,才是0.即Match到了
{
return (*builtin_func[i])(args,hist,current);
}
}
char *str;
str=args[0];
char *p;
int n;
p = strtok(str, "!");
n = atoi(p);
if ( n > 0 && n < 20) {
free(hist[current-1]);
hist[current-1] = NULL;
char *newline2;
newline2=strdup(hist[n-1]);
printf("command:%s\n",newline2);
args = Mysh_split_line(newline2);
return Mysh_execute(args,hist,current);
}
return Mysh_launch(args);
}
void Mysh_loop(void)
{
char *line;
char **args;
int status;
//char prompt[MAX_PROMPT];
char *hist[HISTORY_COUNT];
int i, current = 0;
for ( i = 0; i < HISTORY_COUNT; i++) {
hist[i]= NULL;
}
char buff[PATH_MAX + 1];
do {
printf("[YangMing]>%s $ ",getcwd (buff,PATH_MAX + 1 ));
//type_prompt(prompt);
line = Mysh_read_line();
free(hist[current]);
hist[current]=strdup(line);
current = (current + 1) % HISTORY_COUNT;
args = Mysh_split_line(line);
status = Mysh_execute(args, hist, current);
free(line);
free(args);
} while (status);
}
int main(int argc, char **argv)
{
// Load config files, if any.
// Run command loop.
Mysh_loop();
// Perform any shutdown/cleanup.
return EXIT_SUCCESS;
}
|
C | UTF-8 | 519 | 3.09375 | 3 | [] | no_license | #include <iostream>
void marple_new_flow(int &new1, int &count) {
if (count == 0) {
count = 1;
new1 = 1;
}
}
int main(int argc, char **argv) {
int new1, count;
std::cout << "input the initial value of p.new: " << std::endl;
std::cin >> new1;
std::cout << "input the initial value of count: " << std::endl;
std::cin >> count;
// Run domino func
marple_new_flow(new1, count);
std::cout << "The updated values of p.new and count are " << new1 << ", " << count << std::endl;
return 0;
}
|
C | UTF-8 | 5,745 | 2.84375 | 3 | [] | no_license | #include <stdio_ext.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "utn.h"
#include "contrataciones.h"
static int con_buscarIndiceVacio(Contratacion* pBuffer,int limite,int*indice);
int con_inicializarArray(Contratacion* pBuffer,int limite){
int i;
for(i=0;i<limite;i++){
pBuffer[i].isEmpty=1;
}
return 0;
}
int con_borrarPorID(Contratacion* pBuffer,int limite,int id){
int i;
int retorno=-1;
for(i=0;i<limite;i++){
if(pBuffer[i].isEmpty==0&& pBuffer[i].ID==id){
pBuffer[i].isEmpty=1;
retorno=0;
}
}
return retorno;
}
int con_contratarPublicidad(Contratacion* pBuffer,int id,int limite){
int indice;
if(con_buscarIndiceVacio(pBuffer,limite,&indice)==0){
pBuffer[indice].ID=con_obtenerID();
pBuffer[indice].isEmpty=0;
pBuffer[indice].idPantalla=id;
utn_getLetrasYNumeros(pBuffer[indice].video,15,"\nIngrese el nombre del video: ");
utn_getLetrasYNumeros(pBuffer[indice].cuit,10,"\nIngrese el CUIT: ");
utn_getEntero(&pBuffer[indice].dias,3,"\nIngrese la cantidad de dias: ","\nError Ingrese una cantidad de dias validos",1,200);
}
return 0;
}
int con_obtenerID(){
static int ID=0;
return ID++;
}
static int con_buscarIndiceVacio(Contratacion* pBuffer,int limite,int*indice){
int i;
int retorno=-1;
for(i=0;i<limite;i++){
if(pBuffer[i].isEmpty==1){
*indice=i;
retorno=0;
break;
}
}
return retorno;
}
int con_imprimirPorCuit(Contratacion* pBuffer,int limite,char* cuit){
int i;
int retorno=-1;
if(pBuffer!=NULL&&limite>0&&cuit!=NULL){
for(i=0;i<limite;i++){
if(pBuffer[i].isEmpty==0&&strcmp(pBuffer[i].cuit,cuit)==0){
retorno=0;
printf("\nID: %d",pBuffer[i].ID);
printf("\tID Pantalla: %d",pBuffer[i].idPantalla);
printf("\tDias: %d",pBuffer[i].dias);
printf("\tVideo: %s",pBuffer[i].video);
}
}
}
return retorno;
}
int con_modificarPorIdPantalla(Contratacion* pBuffer,int limite,int idPantalla){
int i;
int retorno=-1;
if(pBuffer!=NULL&&limite>0){
for (i=0;i<limite;i++){
if(pBuffer[i].idPantalla==idPantalla&& pBuffer[i].isEmpty==0){
retorno=0;
utn_getEntero(&pBuffer[i].dias,3,"\nIngrese la cantidad de dias: ","\nError Ingrese una cantidad de dias validos",1,200);
}
}
}
return retorno;
}
int con_cancelarById(Contratacion* pBuffer,int limite,int idPantalla){
int i;
int retorno=-1;
if(pBuffer!=NULL&&limite>0){
for(i=0;i<limite;i++){
if(pBuffer[i].idPantalla==idPantalla&& pBuffer[i].isEmpty==0){
retorno=0;
pBuffer[i].isEmpty=1;
}
}
}
return retorno;
}
int con_listarImportePorContratacion(Contratacion* pBufferCon,Pantalla* pBufferPan,int limiteCon,char* cuit,int limitePan){
int retorno=-1;
return retorno;
}
int con_imprimirContrataciones(Contratacion* array,int len)
{
int retorno = -1;
int i;
if(array != NULL && len > 0)
{
for(i=0;i<len;i++)
{
if(!array[i].isEmpty)
{
printf("\nID: %d\nvideo: %s\ncuit: %s\ndias: %d\n\n",
array[i].ID, array[i].video, array[i].cuit, array[i].dias);
}
}
retorno = 0;
}
return retorno;
}
int con_ordenarByCuit(Contratacion* pArray,int limite,int orden)
{
int retorno=-1;
int i;
int j;
Contratacion auxiliar;
if(pArray != NULL && limite > 0 && (orden == 0 || orden == 1))
{
for(i=1;i < limite; i++)
{
if(pArray[i].isEmpty == 0)
{
auxiliar = pArray[i];
j = i - 1;
if(orden == 0)
{
while ((j >= 0) && pArray[j].isEmpty == 0 && (strcmp(auxiliar.cuit, pArray[j].cuit) < 0))
{
pArray[j + 1] = pArray[j];
j--;
}
pArray[j + 1] = auxiliar;
}
else if(orden == 1)
{
while ((j >= 0) && pArray[j].isEmpty == 0 && (strcmp(auxiliar.cuit, pArray[j].cuit) < 0))
{
pArray[j + 1] = pArray[j];
j--;
}
pArray[j + 1] = auxiliar;
}
}
}
retorno = 0;
}
return retorno;
}
int con_intercambiarPocionEstructura(Contratacion* pBuffer,int indiceDestino,int indiceOrigen){
return 0;
}
int con_list(Contratacion* pArray, int limite)
{
int retorno = -1;
Contratacion auxiliar;
int flagDistinto;
if(pArray != NULL && limite > 0)
{
con_ordenarByCuit(pArray, limite, 0);
do
{
flagDistinto = 0;
}while(flagDistinto == 1);
}
return retorno;
}
int con_agruparPosiciones(Contratacion* pBuffer,int limite){
return 1;
}
int con_ingresoForzado(Contratacion* pBuffer,int limite,char* video,char* cuit,int dias,int idPantalla){
int aux;
con_buscarIndiceVacio(pBuffer,limite,&aux);
strcpy(pBuffer[aux].video,video);
strcpy(pBuffer[aux].cuit,cuit);
pBuffer[aux].dias=dias;
pBuffer[aux].idPantalla=idPantalla;
pBuffer[aux].isEmpty=0;
pBuffer[aux].ID=con_obtenerID();
return 0;
}
int con_listarClientesEImportes(Contratacion * pBufferCon,Pantalla* pbufferPan,int limiteCon,int limitePan){
return 1;
}
|
C | GB18030 | 1,452 | 2.8125 | 3 | [] | no_license | int Add(stud *p)//Ӻ
{
if(p==NULL || p->next==NULL)
{
printf("\t\t\tѧϢ\n");
system("pause");
return 4;
}
stud *q=p,*a=p,*head[100];
int i=-1,b,n=0;
char m='y';
while(q->next)
{
n++;
q=q->next;
}
while(m=='y')
{
system("cls");
q=a;
printf("\t\t\tѧϢ...:\n");
if((head[++i]=(stud *)malloc(sizeof(stud)))==NULL)
{
printf("\t\t\tռ䲻㽨ʧ\n");
exit(0);
}
printf("\t\t\tҪ뵽b֮(0<=b<=%d):",n);
scanf("%d",&b);
printf("\t\t\t %c %c %c %c %c %c %c %c %c %c %c %c %c %c %c %c %c\n",4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4);
if(b<0 || b>n)
{
printf("\n\t\t\n");
system("pause");
break;
}
//뵽b֮
for(n=1;n<=b;n++)
q=q->next;
head[i]->next=NULL;
printf("\t\tѧ:");
scanf("%s",head[i]->num);
printf("\t\t:");
scanf("%s",head[i]->name);
printf("\t\tijɼ:");
scanf("%d",&head[i]->chinese);
printf("\t\tѧɼ:");
scanf("%d",&head[i]->math);
printf("\t\tӢɼ:");
scanf("%d",&head[i]->English);
head[i]->sum=head[i]->chinese+head[i]->English+head[i]->math;
head[i]->next=q->next;
q->next=head[i];
printf("\t\t\tɹ\n");
printf("\t\t\tǷ(y or n):");
scanf(" %c",&m);
}
return 1;
} |
C | UTF-8 | 233 | 2.5625 | 3 | [] | no_license | //sigdemo1.c
//Coded by Lixin on 2020/01/06
#include<stdio.h>
#include<signal.h>
main(){
void f(int);
int i;
signal(SIGINT,f);
for(i=0;i<5;i++){
printf("hallo!\n");
sleep(1);
}
}
void f(int signum){
printf("OUCH!\n");
}
|
C | GB18030 | 1,127 | 3.90625 | 4 | [] | no_license | //һ
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
void swap(int* x, int* y)
{
int tmp = *x;
*x = *y;
*y = tmp;
}
int main()
{
int a[] = { 1, 2, 3, 4, 5 };
int b[] = { 6, 7, 8, 9, 10 };
int sz = sizeof(a) / sizeof(a[0]);
for (int i = 0; i < sz; i++)
{
swap(&a[i], &b[i]);
}
printf("aֵ");
for (int i = 0; i < 5; i++)
{
printf("%d", a[i]);
}
printf("\n");
printf("bֵ");
for (int i = 0; i < 5; i++)
{
printf("%d", b[i]);
}
system("pause");
return 0;
}
//ڶ
#include<stdio.h>
#include<stdlib.h>
int main()
{
int sign = 1;
double a = 2.0, sum = 1.0, term;
while (a <= 100)
{
sign = -sign;
term = sign / a;
sum = sum + term;
a = a + 1;
}
printf("%f\n", sum);
printf("pause");
return 0;
}
//
#include<stdio.h>
#include<stdlib.h>
int main()
{
int number = 0, count = 0;
for (int i = 1; i <= 100; i++)
{
number = i;
while (number > 0)
{
int d = number % 10;
if (d == 9)
{
count++;
}
number /= 10;
}
}
printf("9ĸΪ%\n", count);
system("pause");
return 0;
} |
C | UTF-8 | 17,471 | 3.046875 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include <string.h>
#include<netinet/in.h>
#include<time.h>
#define UDP_PORT 9999
int cal_string_size(char* st){
int i = 0;
while(st[i] != NULL)
i+=1;
return i;
}
char** str_split(char* a_str, const char a_delim)
{
char** result = 0;
size_t count = 0;
char* tmp = a_str;
char* last_comma = 0;
char delim[2];
delim[0] = a_delim;
delim[1] = 0;
/* Count how many elements will be extracted. */
while (*tmp)
{
if (a_delim == *tmp)
{
count++;
last_comma = tmp;
}
tmp++;
}
/* Add space for trailing token. */
count += last_comma < (a_str + strlen(a_str) - 1);
/* Add space for terminating null string so caller
knows where the list of returned strings ends. */
count++;
result = malloc(sizeof(char*) * count);
if (result)
{
size_t idx = 0;
char* token = strtok(a_str, delim);
while (token)
{
*(result + idx++) = strdup(token);
token = strtok(0, delim);
}
*(result + idx) = 0;
}
return result;
}
int is_same(char* first,char* second,int first_size,int second_size){
// printf("first : %d_____second : %d",first_size,second_size);
for(int i = 0; i < second_size; i++){
if (first[i] != second[i]){
return 0;
}
}
return 1;
}
void parser(char* str,char* deli, char** words)
{
char* token;
token = strtok(str, deli);
//printf("%s\n",words[0]);
/* walk through other tokens */
int i = 0;
while( token != NULL ) {
// printf("%d %s",i,token);
words[i]= token;
token = strtok(NULL, deli);
i++;
}
}
int sendall(int s, char *buf, int *len)
{
int total = 0; // how many bytes we've sent
int bytesleft = *len; // how many we have left to send
int n;
while(total < *len) {
n = write(s, buf+total, bytesleft);
if (n == -1) { break; }
total += n;
bytesleft -= n;
}
*len = total; // return number actually sent here
return n==-1?-1:0; // return -1 on failure, 0 on success
}
struct User
{
char* id ;
char* password;
char code[10];
int gem;
int online_or_not;
int current_socket;
char* port;
};
struct Question
{
char* question_text;
char answer[3][20];
int right_answer;
};
char* concat(const char* s1, const char* s2)
{
char* result = (char*)malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, s1);
strcat(result, s2);
return result;
}
int is_duplicate_id(struct User users[],char* id,int number_of_users){
for(int i = 0; i < number_of_users; i++){
if (is_same((users[i].id),id,sizeof (users[i].id),sizeof( id))){
write(1,users[i].id,sizeof users[i].id);
return 0;
}
}
return 1;
}
int is_socket_using(struct User users[],int this_socket,int *number_of_users){
// printf("\nslaam jendegan\n");
for(int i = 0; i < *number_of_users; i++){
if (users[i].current_socket == this_socket ){
return 0;
}
}
return 1;
}
int sign_up(int user_socket,char* id,char* password, struct User users[],int *number_of_users){
if (!is_duplicate_id(users,concat(id,""),*number_of_users)){
write(user_socket,"your id is used\ntry agian\n",sizeof "your id is used\ntry agian\n");
return 0;
}
users[*number_of_users].id = concat(id,"");
users[*number_of_users].password = concat(password,"");
users[*number_of_users].online_or_not = 0;
//
printf("\n size not seted for id in signup : %d",strlen(id));
printf("\n size seted for id in signup : %d",strlen (users[*number_of_users].id));
*(number_of_users)+=1;
return 1;
// write(1,number_of_users,sizeof *number_of_users);
}
void who_am_i(struct User users[],int this,int* number_of_users){
int flag = 0;
for(int i = 0; i < *number_of_users; i++){
if (users[i].current_socket == this) {
write(this,'\n',sizeof '\n');
write(this,users[i].current_socket,sizeof users[i].current_socket);
write(this,users[i].id,sizeof users[i].id);
write(this, " : is your id\n",sizeof " : is your id\n");
return;
}
}
if (flag == 0) {
write(this,'\n',sizeof '\n');
write(this,"You are not login\n",sizeof "You are not login\n");
return;
}
}
int log_in(int user_want_logged_socket,struct User users[],char* id,char*password,char* port,int *number_of_users){
int logged = -1;
printf("\n%d\n",strlen( id));
for(int i = 0; i < *number_of_users; i++){
printf("\nresult : %d\n",strcmp(id,"mahdi"));
if (!strcmp(users[i].id,id) && !strcmp(users[i].password,password)) {
if ( users[i].online_or_not ){
printf("\nsiiikiii678");
write(user_want_logged_socket,"\nThis user is online\n",sizeof"\nThis user is online\n" );
return 0;
}
write(1,"\nfinded\n","\nfinded\n");
logged = i;
printf("\ngigi:%d\n",logged);
break;
}
}
if (logged == -1) {
//user doesn't exist
write(user_want_logged_socket,"\nThis user doesn't exist\n",sizeof"\nThis user doesn't exist\n" );
return 0;
}
printf("\nport is : %s\n",port);
users[logged].online_or_not = 1;
users[logged].current_socket = user_want_logged_socket;
users[logged].port = port;
printf("\nclient port is :%s\n",users[logged].port);
return 1;
}
void log_out(struct User users[],int want_log_out,int *number_of_users){
for(int i = 0; i < *number_of_users; i++){
if (users[i].current_socket == want_log_out ) {
write(users[i].current_socket,"\nYou loged Out\n",sizeof "\nYou loged Out\n");
users[i].online_or_not = 0;
users[i].current_socket = 0;
return;
}
}
write(want_log_out,"\nYou are not logged in\n",sizeof "\nYou are not logged in\n");
return 0;
}
void find_port_for_chat(struct User users[],int want_chat,char* id,int *number_of_users,int is_compettion_start){
if (!is_compettion_start) {
for(int i = 0; i < *number_of_users; i++){
printf("\nin need this pepole : %s :online :%d size: %d",users[i].id,users[i].online_or_not,strlen(users[i].id));
printf(" compare : %d\n",strcmp(users[i].id, id));
printf("chat want id: %s :size :%d\n",id,strlen(id));
if (is_same(users[i].id,id,cal_string_size(users[i].id),cal_string_size(id)) == 1) {
if(users[i].online_or_not){
write(want_chat,concat("@1@",users[i].port),sizeof concat("@1@",users[i].port));
write(users[i].current_socket,concat("@2@",users[i].port),sizeof concat("@2@",users[i].port));
return ;
}
else
{
write(want_chat,"\nYour friend is not online\n",sizeof "\nYour friend is not online\n");
return ;
}
}
}
write(want_chat,"\nYour friend id is wrong\n",sizeof "\nYour friend id is wrong\n");
return ;
}
else{
write(want_chat,"\nCan't chat now\n",sizeof "\nCan't chat now\n");
}
}
void Handle_command(int user_socket,char** words, struct User users[], int *number_of_users,int is_competition_start){
if (is_same(words[0],"whoami",cal_string_size(words[0]),cal_string_size("whoami"))) {
who_am_i(users,user_socket,number_of_users);
}
else if (is_same(words[0],"signup",cal_string_size(words[0]),cal_string_size("signup"))){
printf("\nbefore call signup : %d\n",strlen(words[1]));
if (is_competition_start == 0) {
if(is_socket_using(users,user_socket,number_of_users)) {
if(sign_up(user_socket,words[1],words[2],users,number_of_users)){
write(user_socket,"\nYou signedup successfully\n",sizeof "\nYou signedup successfully\n");
}
}
else
{
write(user_socket,"\nYour socket is using\n",sizeof "\nYour cocket is using\n");
}
}
else
{
write(user_socket,"\nYou can't signup now\n",sizeof "\nYou can't signup now\n");
}
}
else if (is_same(words[0],"login",cal_string_size(words[0]),cal_string_size("login"))){
if (is_competition_start == 0) {
printf("\nbefore call login : %d\n",strlen(words[1]));
if (is_socket_using(users,user_socket,number_of_users)) {
if(log_in(user_socket,users,words[1],words[2],words[3],number_of_users)){
write(user_socket,"\nYou loggedin successfully\n",sizeof "\nYou loggedin successfully\n");
}
}
else
{
write(user_socket,"\nYour socket is using\n",sizeof "\nYour cocket is using\n");
}
}
else
{
write(user_socket,"\nYou can't login now\n",sizeof "\nYou can't login now\n");
}
}
else if (is_same(words[0],"logout",cal_string_size(words[0]),cal_string_size("logout"))) {
log_out(users,user_socket,number_of_users);
}
else if (is_same(words[0],"chat",cal_string_size(words[0]),cal_string_size("chat"))) {
find_port_for_chat(users,user_socket,words[1],number_of_users,is_competition_start);
}
memset(&words,0,sizeof words);
}
int cal_time(clock_t start,int endtime){
// printf("\nwhy\n");
if((clock() - start)/CLOCKS_PER_SEC >= endtime){
return 1 ;
}
return 0;
}
int main(int argc, char const *argv[])
{
char server_message[256] = "You have reached the server\n";
int server_socket;
server_socket = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(atoi(argv[1]));
server_address.sin_addr.s_addr = INADDR_ANY;
// struct sockaddr_in clientAddress;
// clientAddress.sin_family = AF_INET;
// clientAddress.sin_addr.s_addr = inet_addr("255.255.255.255");
// clientAddress.sin_port = htons(PORT);
bind(server_socket,(struct sockaddr*) &server_address, sizeof(server_address));
if (listen(server_socket, 5) < 0) {
perror("listenr failed");
exit(3);
}
//broadcast start
int udp_socket;
struct sockaddr_in message_address;
int udpFlag = 1;
if((udp_socket = socket(AF_INET,SOCK_DGRAM,0)) < 0){
write(1,"Could not open a socket for broadcast\n",strlen("Could not open a socket for broadcast\n"));
exit(0);
}
setsockopt(udp_socket,SOL_SOCKET,SO_BROADCAST,&udpFlag,sizeof(udpFlag));
message_address.sin_family = AF_INET;
message_address.sin_addr.s_addr = INADDR_BROADCAST;
message_address.sin_port = htons(UDP_PORT);
//broadcast end
fd_set master; // master file descriptor list
fd_set read_fds; // temp file descriptor list for select()
int fdmax; // maximum file descriptor number
int newfd; // newly accept()ed socket descriptor
struct sockaddr_storage remoteaddr; // client address
socklen_t addrlen;
char buf[256]; // buffer for client data
int nbytes;
char remoteIP[INET6_ADDRSTRLEN];
int yes=1; // for setsockopt() SO_REUSEADDR, below
int i, j, rv;
int broadcast =1;
FD_ZERO(&master); // clear the master and temp sets
FD_ZERO(&read_fds);
FD_SET(server_socket,&master);
FD_SET(STDIN_FILENO, &master);
fdmax = server_socket;
int count =0;
char* token;
char** words;
struct User users[100];
int *number_of_users = 0;
int is_competition_started =0;
clock_t comp_start_time = clock();
struct timeval timeout;
int flag = 0;
int counted = 0;
timeout.tv_usec = timeout.tv_sec = 0;
int exit_flag = 0;
int broad_cast_Question = 0;
for(;;) {
if(cal_time(comp_start_time , 100) == 1){
is_competition_started = 1;
if(counted == 0) {
flag = 1;
}
}
if (flag == 1) {
write(1,"\nCompetition is started\n",sizeof "\nCompetition is started\n");
sendto(udp_socket,"\nCompetition is started\n",strlen("\nCompetition is started\n"),
0,(struct sockaddr*)&message_address,sizeof(message_address));
flag = 0;
counted++;
}
memset(&token,0,sizeof(token));
read_fds = master; // copy it
if (select(fdmax+1, &read_fds, NULL, NULL, &timeout) == -1) {
perror("select");
exit(4);
}
// run through the existing connections looking for data to read
for(i = 0; i <= fdmax; i++) {
if (FD_ISSET(i, &read_fds)) { // we got one!!
if (i == server_socket) {
// handle new connections
addrlen = sizeof remoteaddr;
newfd = accept(server_socket,(struct sockaddr *)&remoteaddr,&addrlen);
count =1;
if (newfd == -1) {
perror("accept");
} else {
FD_SET(newfd, &master); // add to master set
if (newfd > fdmax) { // keep track of the max
fdmax = newfd;
}
printf("selectserver: new connection from NAGHI on socket %d\n",newfd);
char welcome_message[256] = "welcome to server\n";
int lenn = cal_string_size(welcome_message);
// printf("\n%d\n",lenn);
sendall(newfd,welcome_message,&lenn);
}
}
else if(i == STDIN_FILENO){
if ((nbytes = read(i, buf, sizeof buf))){
if (is_same(buf,"exit",strlen(buf),strlen("exit")) == 1) {
exit_flag = 1;
write(1,"\nBye Bye\n",sizeof "\nBye Bye\n");
}
sendto(udp_socket,buf,strlen(buf),0,(struct sockaddr*)&message_address,sizeof(message_address));
memset(&buf,0,sizeof buf);
// write(1,"I send folan\n",strlen("I send folan\n"));
}
} else {
// handle data from a client
memset(&buf,0,sizeof buf);
if ((nbytes = read(i, buf, sizeof buf)) <= 0) {
// got error or connection closed by client
if (nbytes == 0) {
// connection closed
printf("selectserver: socket %d hung up\n", i);
} else {
perror("recv");
}
memset(&token,0,sizeof(token));
close(i); // bye!
FD_CLR(i, &master); // remove from master set
}
// strcat(buf," :client sent__\n");
// write(0,buf,nbytes);
if (nbytes != 0) {
printf("\n1:%s\n",buf);
buf[strlen(buf)] = '\0';
printf("\n2:%s\n",buf);
// parser(buf,"@",words);
words = str_split(buf,'@');
// printf("clieeent:%s\n",buf);
// free(words);
printf("parsed:%s\n",words[0]);
printf("parsed2:%s\n",words[1]);
// printf("lili:%ld",strlen(words[1]));
printf("(parsed3:%s)\n",words[2]);
printf("(parsed4:%s)\n",words[3]);
Handle_command(i,words, users,&number_of_users,is_competition_started);
// words[0] = "";
memset(&words,0,sizeof words);
// printf("cleand:%s\n",words[0]);
memset(&buf,0,sizeof buf);
}
// memset(&token,0,sizeof(token));
} // END handle data from client
} // END got new incoming connection
} // END looping through file descriptors
if (exit_flag == 1) {
break;
}
} // END for(;;)--and you thought it would never end!
close(server_socket);
return 0;
}
|
C | UTF-8 | 1,084 | 3.078125 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#include <math.h>
#include "sorts.c"
#include "utils.c"
int main()
{
int option, i;
printf("\nDo you want to view the input and output values ?\n[ 1 ] - YES\n[ 0 ] - NO\n\nYour choice: ");
scanf("%d", &option);
system("cls || clear");
for (i = 1; i <= 6; i++)
{
float j = pow(10, i);
int size = (int) j;
int *vetor;
clock_t Ticks[2];
vetor = (int *)malloc(size * sizeof(int));
createRandomVetor(vetor, size);
printf("\nData ordering tests for vectors with %i values:\n\n", size);
printf("\tSort type\t==\tRuntime (seconds)\n");
teste(vetor, size, bubbleSort, "BubbleSort", option);
teste(vetor, size, selectionSort, "SelectionSort", option);
teste(vetor, size, insertionSort, "InsertionSort", option);
teste(vetor, size, quickSort, "QuickSort", option);
teste(vetor, size, mergeSort, "MergeSort", option);
}
return 0;
}
|
C | UTF-8 | 1,611 | 3.09375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <libkallsyms/kallsyms_in_memory.h>
static size_t
get_file_length(const char *file_name)
{
struct stat st;
if (stat(file_name, &st) < 0) {
return 0;
}
return st.st_size;
}
static bool
do_get_kallsyms(const char *file_name, size_t len)
{
int fd;
unsigned long* mem;
kallsyms *info;
fd = open(file_name, O_RDONLY);
if (fd < 0) {
fprintf(stderr, "file open failed \"%s\"(%d)\n", strerror(errno), errno);
return false;
}
mem = (unsigned long*)mmap(NULL, len, PROT_READ, MAP_SHARED, fd, 0);
if(mem == MAP_FAILED)
{
fprintf(stderr, "mmap error \"%s\"(%d)\n", strerror(errno), errno);
close(fd);
return false;
}
info = kallsyms_in_memory_init(mem, len);
if (info) {
kallsyms_in_memory_print_all(info);
}
if (munmap(mem, len)) {
fprintf(stderr, "munmap error \"%s\"(%d)\n", strerror(errno), errno);
}
if (close(fd)) {
fprintf(stderr, "close error \"%s\"(%d)\n", strerror(errno), errno);
}
return info != NULL;
}
int main(int argc, char** argv)
{
char *file_name;
size_t len;
kallsyms_in_memory_set_verbose(true);
if (argc !=2 ) {
fprintf(stderr, "Usage: %s FILENAME\n", argv[0]);
return 2;
}
file_name = argv[1];
len = get_file_length(file_name);
if (len == 0) {
fprintf(stderr, "Can't get file size\n");
}
if (!do_get_kallsyms(file_name, len)) {
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
/*
vi:ts=2:nowrap:ai:expandtab:sw=2
*/
|
C | UTF-8 | 571 | 3.53125 | 4 | [] | no_license | #include "holberton.h"
/**
* _strpbrk - searches a string for any of a set of bytes
*@s: pointer
*@accept: pointer
* Return: s + era or '\0'
*/
char *_strpbrk(char *s, char *accept)
{
int era; /*recorre s*/
int ase; /* recorre accept*/
int les;
for (era = 0; s[era] != '\0'; era++)
{/**Recorre a s*/
les = 0;
for (ase = 0; accept[ase] != '\0'; ase++)
{/**Recorre a accept*/
if (s[era] == accept[ase])
{
les = 1;
}
}
if (les == 1)
{/**Si hay algun byte return*/
return (s + era);
}
}
/**si no return null*/
return ('\0');
}
|
C | UTF-8 | 826 | 2.78125 | 3 | [] | no_license | #include <stddef.h>
typedef struct ArrayList ArrayList;
ArrayList *arraylist_new();
void arraylist_add(ArrayList *list, void *elem);
void arraylist_add_all(ArrayList *list, ArrayList *addable);
void arraylist_insert(ArrayList *list, size_t i, void *elem);
void *arraylist_get(ArrayList *list, size_t i);
void *arraylist_get_last(ArrayList *list);
void *arraylist_remove(ArrayList *list, size_t i);
void *arraylist_remove_last(ArrayList *list);
ArrayList *arraylist_reverse(ArrayList *list);
void *arraylist_it_next(ArrayList *list);
void *arraylist_it_first(ArrayList *list);
size_t arraylist_size(ArrayList *list);
void arraylist_foreach(ArrayList *list, void (*callback)(void*));
void arraylist_print(ArrayList *list, void (*printfn)(void*));
void arraylist_free(ArrayList *list);
void arraylist_free_all(ArrayList *list);
|
C | UTF-8 | 361 | 3 | 3 | [] | no_license | #include <stdio.h>
#include <math.h>
#include <unistd.h>
int main()
{
short int buffer[64];
for(int i = 0; i < 44100 * 5 / 64; ++i)
{
for(int j = 0; j < 64; ++j)
{
buffer[j] = 20000 * (sin((i * 64 + j) * 220 * 2 * 3.14159265 / 44100.0));
}
write(1, buffer, 64 * sizeof(short int));
}
return 0;
}
|
C | UTF-8 | 1,039 | 4 | 4 | [] | no_license | /******************************************* OBJETIVO ******************************************************
* Faça um programa para receber uma matriz 3×3 (solicitar ao usuário) e apresentar a soma dos elementos da
* diagonal principal e a matriz na forma como deve ser vista: com linhas e colunas
*
* AUTHOR: GuhPires
* VISIT: https://github.com/GuhPires/fei-c
**********************************************************************************************************/
#include <stdio.h>
int main(void) {
int m[3][3], main_diagonal = 0;
printf("Popule a matriz...\n");
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
printf("Valor: ");
scanf("%d", &m[i][j]);
}
}
printf("A matriz digitada: \n");
for(int i = 0; i < 3; i++) {
printf(" |");
for(int j = 0; j < 3; j++) {
printf("\t%d", m[i][j]);
if(i == j) {
main_diagonal += m[i][j];
}
}
printf("\t|\n");
}
printf("A soma da Diagonal Principal é: %d\n", main_diagonal);
return 0;
} |
C | UTF-8 | 1,429 | 3.53125 | 4 | [] | no_license | #include<stdio.h>
int size(int *p) {
int i=0, len=0;
while(p[i] != '\0') {
if(p[i] != -233)
len++;
i++;
}
return len;
}
int push(int *p, int X) {
int last;
last = size(p);
p[last++] = X;
}
int isEmpty(int *p) {
if(size(p) == 0)
return 0;
else
return 1;
}
int pop(int *p) {
int re;
int i=0;
while(p[i] != '\0') {
if(p[i] != -233)
break;
i++;
}
re = p[i];
p[i] = -233;
return(re);
}
int main(void)
{
int A[1000];
int B[1000];
int N;
int temp;
int i=0;
scanf("%d", &N);
while(i<N)
{
scanf("%d", &temp);
if (temp % 2 == 0)
push(B, temp);
else
push(A, temp);
i++;
}
i=1;
while(size(A)!=0 && size(B)!=0) {
if(i == N-2)
printf("%d", pop(A));
else
printf("%d ", pop(A));
if(i % 2 == 0)
if(i == N-2)
printf("%d", pop(B));
else
printf("%d ", pop(B));
i++;
}
while(size(A)!=0) {
if(i == N-2)
printf("%d", pop(A));
else
printf("%d ", pop(A));
i++;
}
while(size(B)!=0) {
if(i == N-2)
printf("%d", pop(B));
else
printf("%d ", pop(B));
i++;
}
return 0;
}
|
C | UTF-8 | 8,734 | 2.53125 | 3 | [] | no_license | #include <netinet/in.h>
#include <stdio.h>
#include <strings.h>
#include <string.h>
#include <sys/ioctl.h>
#include "multicast.h"
#include "address.h"
#include "log.h"
// modified from source code of net-tools_1.60, ipmaddr.c
// NOTE: ONLY support IPv4
#define PATH_PROCNET_IGMP "/proc/net/igmp" /* net/core/igmp.c */
#define PATH_PROCNET_DEV_MCAST "/proc/net/dev_mcast" /* net/core/dev_addr_lists.c */
// parse hex number in string format form @str and store in @addr.
// @return: the number of byte stored in @addr.
// e.g. "c0a80001" -> addr[4] = {1, 0, 168, 192}
static int parse_hex(char *str, unsigned char *addr)
{
int len = 0;
while (*str) {
int tmp;
if (str[1] == '\0')
return -1;
if (sscanf(str, "%02x", &tmp) != 1)
return -1;
addr[len] = tmp;
len++;
str += 2;
}
return len;
}
/*
* for AF_PACKET, i.e. ether hwaddr
* seq format: "index, name, refcount, global_use, address"
*/
static int read_dev_mcast(struct mcast_info *array, int num)
{
int i = 0;
char buf[256];
struct mcast_info *m = NULL;
char hexa[32];
FILE *fp = fopen(PATH_PROCNET_DEV_MCAST, "r");
if (!fp) {
err("fopen %s failed: %m\n", PATH_PROCNET_DEV_MCAST);
return -1;
}
i = 0;
bzero(array, sizeof(struct mcast_info) * num);
while (fgets(buf, sizeof(buf), fp)) {
m = array + i;
int len;
sscanf(buf, "%d%s%d%d%s", &m->index, m->name, &m->users, &m->st, hexa);
len = parse_hex(hexa, (unsigned char*)m->addr);
if (len < 0) {
err("parse hex failed\n");
return -1;
}
m->family = AF_PACKET;
i++;
if (i >= num) {
err("over num %d\n", num);
fclose(fp);
return -1;
}
}
fclose(fp);
return i;
}
/*
* for AF_INET
* idx, name, count, querier, \n\t, multiaddr, users, Timer(runing:clock), reporter
* just read idx, name, multiaddr, users
*/
static int read_igmp(struct mcast_info *array, int num)
{
struct mcast_info *m;
struct mcast_info *head = NULL;
char buf[256];
int i = 0;
FILE *fp = fopen(PATH_PROCNET_IGMP, "r");
if (!fp) {
err("fopen %s failed: %m\n", PATH_PROCNET_IGMP);
return -1;
}
if (fgets(buf, sizeof(buf), fp) == NULL) // eat first line
err("fgets failed\n");
i = 0;
bzero(array, sizeof(struct mcast_info) * num);
while (fgets(buf, sizeof(buf), fp)) {
m = array + i;
m->family = AF_INET;
if (buf[0] != '\t') {
sscanf(buf, "%d%s", &m->index, m->name);
head = m;
continue;
}
if (head != m) {
m->index = head->index;
strncpy(m->name, head->name, IFNAMSIZ);
}
sscanf(buf, "%08x%d", (unsigned int*)m->addr, &m->users);
i++;
if (i >= num) {
err("over num %d\n", num);
fclose(fp);
return -1;
}
}
fclose(fp);
return i;
}
// normal group, non-source group
static int mcast_join_leave_inet(int skfd, char *ifname, struct sockaddr *grp, int join)
{
if (grp->sa_family != AF_INET) {
err("Not support non-AF_INET mcast ops\n");
return -1;
}
int ret = 0;
struct ip_mreq mreq;
int cmd = (join ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP);
memcpy(&mreq.imr_multiaddr, &((struct sockaddr_in *)grp)->sin_addr,
sizeof(struct in_addr));
struct ifreq ifreq;
strncpy(ifreq.ifr_name, ifname, IFNAMSIZ);
if (ioctl(skfd, SIOCGIFADDR, &ifreq) < 0) {
err("get ifaddr failed: %m");
return -1;
}
memcpy(&mreq.imr_interface, &((struct sockaddr_in *)&ifreq.ifr_addr)->sin_addr,
sizeof(struct in_addr));
ret = setsockopt(skfd, IPPROTO_IP, cmd, &mreq, sizeof(mreq));
if (ret < 0) {
err("%s multicast ioctl failed: %m", join ? "join": "leave");
return -1;
}
return 0;
}
static int mcast_set_ttl_inet(int skfd, int val)
{
unsigned char ttl = val;
int ret = setsockopt(skfd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));
if (ret < 0) {
err("set multicast TTL failed: %m");
return -1;
}
return 0;
}
static int mcast_get_ttl_inet(int skfd)
{
unsigned char ttl;
socklen_t len;
len = sizeof(ttl);
if (getsockopt(skfd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, &len) < 0) {
err("get multicast TTL failed: %m\n");
return -1;
}
return ttl;
}
static int mcast_set_iface_inet(int skfd, char *ifname)
{
struct in_addr inaddr;
struct ifreq ifreq;
strncpy(ifreq.ifr_name, ifname, IFNAMSIZ);
if (ioctl(skfd, SIOCGIFADDR, &ifreq) < 0) {
err("get iface addr ioctl failed: %m\n");
return -1;
}
memcpy(&inaddr, &((struct sockaddr_in *)&ifreq.ifr_addr)->sin_addr,
sizeof(struct in_addr));
int ret = setsockopt(skfd, IPPROTO_IP, IP_MULTICAST_IF,
&inaddr, sizeof(struct in_addr));
if (ret < 0) {
err("set multicast iface failed: %m\n");
return -1;
}
return 0;
}
static int mcast_get_iface_inet(int skfd, uint32_t *ip)
{
struct in_addr inaddr;
socklen_t len;
int ret = getsockopt(skfd, IPPROTO_IP, IP_MULTICAST_IF,
&inaddr, &len);
if (ret < 0) {
*ip = 0;
err("set multicast iface failed: %m\n");
return -1;
}
info("ip = %08x\n", inaddr.s_addr);
*ip = ntohl(inaddr.s_addr);
return 0;
}
////////////////////////////////////////////////////////////////////////////////
int mcast_get_list(struct mcast_info *array, int size, int family)
{
int n = 0;
int ret;
if (family == AF_PACKET || family == AF_UNSPEC) {
ret = read_dev_mcast(array, size);
if (ret < 0) {
err("read_dev_mcast failed\n");
return -1;
}
n += ret;
}
if (family == AF_INET || family == AF_UNSPEC) {
ret = read_igmp(array + n, size - n);
if (ret < 0) {
err("read_igmp failed\n");
return -2;
}
n += ret;
}
return n;
}
void mcast_print(struct mcast_info *m, FILE *fp)
{
if (m == NULL || fp == NULL) {
err("Invliad parameters\n");
return;
}
char str[32] = {0};
const char *type = NULL;
if (m->family == AF_INET) {
snprintf(str, sizeof(str), "%d.%d.%d.%d", m->addr[0], m->addr[1], m->addr[2], m->addr[3]);
} else {
snprintf(str, sizeof(str), "%02x:%02x:%02x:%02x:%02x:%02x",
m->addr[0], m->addr[1], m->addr[2], m->addr[3],
m->addr[4], m->addr[5]);
}
if (m->family == AF_INET)
type = "inet";
else if (m->family == AF_PACKET)
type = "link";
else
type = "?";
fprintf(fp, "%3d %-6s: %4s %-18s [%d]\n", m->index, m->name, type, str, m->users);
}
int mcast_join(int skfd, char *ifname, uint32_t ip)
{
if (skfd <= 0 || ifname == NULL || ip == 0) {
err("invalid parameters\n");
return -1;
}
struct sockaddr grp;
sa_set_addr(&grp, ip);
sa_set_family(&grp, AF_INET);
return mcast_join_leave_inet(skfd, ifname, &grp, true);
}
int mcast_leave(int skfd, char *ifname, uint32_t ip)
{
if (skfd <= 0 || ifname == NULL || ip == 0) {
err("invalid parameters\n");
return -1;
}
struct sockaddr grp;
sa_set_addr(&grp, ip);
sa_set_family(&grp, AF_INET);
return mcast_join_leave_inet(skfd, ifname, &grp, false);
}
/*
* actually, in IPv4, @ttl's type is u_char
*/
int mcast_set_ttl(int skfd, int ttl)
{
if (skfd <= 0 || ttl < 0) {
err("invalid parameters\n");
return -1;
}
return mcast_set_ttl_inet(skfd, ttl);
}
int mcast_get_ttl(int skfd)
{
if (skfd <= 0) {
err("invalid parameters\n");
return -1;
}
return mcast_get_ttl_inet(skfd);
}
int mcast_set_iface(int skfd, char *ifname)
{
if (skfd <= 0 || ifname == NULL) {
err("invalid parameters\n");
return -1;
}
return mcast_set_iface_inet(skfd, ifname);
}
int mcast_get_iface(int skfd, uint32_t *ip)
{
if (skfd <= 0 || ip == NULL) {
err("invalid parameters\n");
return -1;
}
return mcast_get_iface_inet(skfd, ip);
}
/*
* modify ether link layer multicast address
*/
int mcast_modify_ether(char *ifname, int is_add, char *hwaddr, int len)
{
struct ifreq ifr;
int fd;
int cmd = 0;
memset(&ifr, 0, sizeof(ifr));
cmd = is_add ? SIOCADDMULTI : SIOCDELMULTI;
strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
memcpy(ifr.ifr_hwaddr.sa_data, hwaddr, len);
fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) {
perror("Cannot create socket");
return -1;
}
if (ioctl(fd, cmd, (char*)&ifr) != 0) {
perror("modify lla mcast failed");
close(fd);
return -1;
}
close(fd);
return 0;
}
|
C | GB18030 | 2,291 | 3.828125 | 4 | [] | no_license | //ջӦ
#include "stack.h"
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//ƥ䷵1
int match_brackets(const char * string)
{
if (NULL == string) {
return 1;
}
Stack s;
init(&s);
//Ŷ࣬Ŷ࣬˳ͬ
while (*string) {
if (*string == '(' || *string == '[' || *string == '{') {
pushBack(&s, *string);
string++;
continue;
}
else if (*string == ')' || *string == '}' || *string == ']') {
char tmp = top(&s);
pop(&s);
if ((*string == ')'&& tmp == '(') ||
(*string == '}'&& tmp == '{') ||
(*string == ']'&& tmp == '[') ) {
string++;
continue;
}
else {
//˳ƥ
return 0;
}
}
else {
string++;
}
}
//ֻеַɨˣջŶƥˣȷƥ
if (isEmpty(&s)) {
return 1;
}
return 0;
}
//-1,رʽֵ
int exp(const char* str)
{
if(NULL == str){
return 0;
}
char *low = str;
char *fast = str;
Stack s;
init(&s);
//ųǰո
while (*low && *low == ' ') {
low++;
}
fast = low;
//ʼ
while (*fast) {
if (isdigit(*low)) {
//ȡһ
int sum = 0;
while (*fast && isdigit(*fast)) {
sum = sum * 10 + (*fast - '0');
fast++;
}
pushBack(&s, sum);
}
else if(*low=='+' || *low == '-' || *low == '*' || *low == '/'){
//Dz
int tmp = 0;
switch (*low) {
case '+':
tmp = top(&s); pop(&s);
tmp += top(&s); pop(&s);
pushBack(&s, tmp);
break;
case '-':
tmp = top(&s); pop(&s);
tmp = top(&s) - tmp; pop(&s);
pushBack(&s, tmp);
break;
case '*':
tmp = top(&s); pop(&s);
tmp *= top(&s); pop(&s);
pushBack(&s, tmp);
break;
case '/':
tmp = top(&s); pop(&s);
tmp = top(&s) / tmp; pop(&s);
pushBack(&s, tmp);
break;
default:break;
}
fast++;
}
else {
return -1;
}
//lowfastָһַͷ
while (*fast && *fast == ' ') {
fast++;
}
low = fast;
}
return top(&s);
}
void testApp()
{
//const char *string = "(()()abc{[]})";
//int ret = match_brackets(string);
const char *str = " 12 3 4 + * 6 - 8 2 / +";
int ans = exp(str);
system("pause");
}
|
C | UTF-8 | 3,192 | 3.46875 | 3 | [] | no_license | #include <stdlib.h>
#include <stdio.h>
#include <limits.h>
//#define MIN 32
//#define MAX 127
#define MIN 96
#define MAX 123
// fn prototypes
void write(FILE *fp);
void compare(FILE *shit, FILE *eng, int *end);
unsigned int rand_interval(unsigned int min, unsigned int max);
/*
le main function.
ideally we get it to write then read and sort
*/
int main ()
{
// the evidence
FILE *fp;
int end;
// prompt
printf("Enter how many chars u want bby: ");
scanf("%d", &end);
// call write.
write(fp, end);
}
void compare (FILE *shit, FILE *eng, int *end){
//where we store the string from
char *lineShit = NULL, *lineEng = NULL;
size_t lenShit = 0, lenEng = 0;
ssize_t readShit, readEng;
if((shit=fopen("text", "rb")==NULL)||(eng=fopen("english", "rb"))){
perror("Invalid file path");
}
while ((readShit = getline(&lineShit, &lenShit, shit)) != -1 &&
(readEng = getline(&lineEng, &lenEng, eng)) != -1){
if ()
}
}
/*
write some chars
takes in a file struct
*/
void write(FILE *fp, int *end){
// this is what we actually write.
unsigned int write;
int wLimit = rand_interval(3,27), count = 0, wcCount = 0, end;
while (count<end)
{
// call random function
write = rand_interval(MIN, MAX);
// for null byte.
if (write == 10){
if ((fp = fopen("text", "ab+"))==NULL){
// whoopsies! no path found!
perror("Invalid file path!");
} else{
// no error, write to file!
fputc(write, fp);
fclose (fp);
// we back out of if to while. hopefully rand_interval runs?
// pardon muh'logic
wcCount = 0;
wLimit = rand_interval(3,27);
write = rand_interval(MIN, MAX);
count += 1;
//break;
}
}
// just for lowercase letters.
if ((write>96)&&(write<123)){
//printf("wCCount: %i", wcCount);
//printf("wLimit: %i", wLimit);
if ((fp = fopen("text", "ab+"))==NULL){
// whoopsies! no path found!
perror("Invalid file path!");
}
else{
// largest shakespeare word is 27 letters: long 'nough for me.
if (wcCount < wLimit){
// now we continue, write character.
fputc(write, fp);
// we back out of if to while. hopefully rand_interval runs?
// pardon muh'logic
wcCount += 1;
count += 1;
}
else {
// write new line, reset counter, limit.
fputc(10, fp);
wLimit = rand_interval(3,27);
wcCount = 0;
}
}
}
else{
// nice try no cigar
write = rand_interval(MIN, MAX);
}
fclose (fp);
}
}
/*
a researched solution to c's bounded random generator. cannot just use %
since makes assumption about c's rand generator.
*/
unsigned int rand_interval(unsigned int min, unsigned int max)
{
int r;
const unsigned int range = 1 + max - min;
const unsigned int buckets = RAND_MAX / range;
const unsigned int limit = buckets * range;
/* Create buckets, fire randomly at buckets till you land.
* If you don't land, try again.
*/
do
{
r = rand();
} while(r >= limit);
return min + (r/buckets);
}
|
C | UTF-8 | 1,699 | 2.75 | 3 | [] | no_license | #include "test_sockutils.h"
#include "testmacros.h"
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "errors.h"
#include "sockutils.h"
/* BEGIN TESTS */
int t_Server_close_communication__close_noconnected_socket() {
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
int res = server_close_communication(sock);
if(res != OK)
mu_sysfail("close failed");
mu_end;
}
int t_Server_close_communication__close_connected_socket() {
int sock[2];
int res;
if (socketpair(PF_LOCAL, SOCK_STREAM, 0, sock) == -1)
mu_sysfail("socketpair");
res = server_close_communication(sock[0]);
if(res != OK)
mu_sysfail("close s1 failed");
res = server_close_communication(sock[1]);
if(res != OK)
mu_sysfail("close s2 failed");
mu_end;
}
int t_server_open_socket__opensocket() {
int handler = server_open_socket(DEFAULT_PORT, DEFAULT_MAX_QUEUE);
mu_assert("Server won't open", handler !=ERR_SOCK);
close(handler);
mu_end;
}
/* END TESTS */
int test_sockutils_suite(int* errors, int* success) {
int tests_run = 0;
int tests_passed = 0;
printf("Begin test_sockutils suite.\n");
/* BEGIN TEST EXEC */
mu_run_test(t_Server_close_communication__close_noconnected_socket);
mu_run_test(t_Server_close_communication__close_connected_socket);
mu_run_test(t_server_open_socket__opensocket);
/* END TEST EXEC */
if(tests_passed == tests_run)
printf("End test_sockutils suite. " TGREEN "%d/%d\n\n" TRESET, tests_passed, tests_run);
else
printf("End test_sockutils suite. " TRED "%d/%d\n\n" TRESET, tests_passed, tests_run);
*errors += (tests_run - tests_passed);
*success += tests_passed;
return tests_run;
}
|
C | UTF-8 | 4,678 | 3.265625 | 3 | [] | no_license | #define _POSIX_C_SOURCE 1
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
//------------------------------------------------------------------------------
// DEFINITIONS
//------------------------------------------------------------------------------
#define ERROR -1
#define SUCCESS 0
#define VERSION "0.1"
const char help_str[] = "Usage:\n"
" tp1 -h\n"
" tp1 -V\n"
" tp1 [options]\n"
"Options:\n"
" -V, --version\tPrint version and quit.\n"
" -h, --help\tPrint this information.\n"
" -i, --input\tLocation of the input file.\n"
" -o, --output\tLocation of the output file.\n"
" -I, --ibuf-bytes\tbyte-count of the input buffer\n"
" -O, --obuf-bytes\tbyte-count of the output buffer\n"
"Examples:\n"
" tp1 -i ~/input -o ~/output\n";
//------------------------------------------------------------------------------
// EXTERNAL FUNCTIONS
//------------------------------------------------------------------------------
extern int palindrome(int ifd, size_t ibytes, int ofd, size_t obytes);
//------------------------------------------------------------------------------
// EQUAL
//------------------------------------------------------------------------------
bool equal(const char* str1, const char* str2) {
return strcmp(str1, str2) == 0;
}
//------------------------------------------------------------------------------
// ARG PARSE
//------------------------------------------------------------------------------
int argParse(int argc, char** argv, FILE** descriptors, size_t** ref) {
int arg = 1;
const int size = 12;
const char* flags[] = {"-i", "-o", "-V", "-h", "--version", "--help",
"--input", "--output", "-I", "-O", "--ibuf-bytes",
"--obuf-bytes"};
bool std;
char* flag = "";
bool isFlagNull;
while (arg < argc) {
isFlagNull = true;
if (argv[arg][0] == '-') {
for (int i = 0; i < size; i++) {
if (strcmp(argv[arg], flags[i]) == 0) {
flag = argv[arg];
isFlagNull = false;
break;
}
}
if (equal(flag, "-h") || equal(flag, "--help")) {
printf("%s\n", help_str);
*ref[2] = 1;
return SUCCESS;
}
if (equal(flag, "-V") || equal(flag, "--version")) {
printf("tp1: version %s\n", VERSION);
*ref[2] = 1;
return SUCCESS;
}
if (isFlagNull) {
printf("Invalid argument: %s\n", argv[arg]);
descriptors[0] = NULL;
return ERROR;
}
} else {
std = equal(argv[arg], "-");
if ((equal(flag, "-i") || equal(flag, "--input")) && !std) {
descriptors[0] = fopen(argv[arg], "r");
if (descriptors[0] == NULL) return ERROR;
} else if ((equal(flag, "-o") || equal(flag, "--output")) && !std) {
descriptors[1] = fopen(argv[arg], "w");
if (descriptors[1] == NULL) return ERROR;
}
if ((equal(flag, "-I") || equal(flag, "--ibuf-bytes")) && !std) {
*ref[0] = (size_t)atoi(argv[arg]);
}
if ((equal(flag, "-O") || equal(flag, "--obuf-bytes")) && !std) {
*ref[1] = (size_t)atoi(argv[arg]);
}
flag = "nullStr";
}
arg++;
}
return SUCCESS;
}
//------------------------------------------------------------------------------
// MAIN
//------------------------------------------------------------------------------
int main(int argc, char** argv) {
FILE* fdescriptors[2] = {stdin, stdout};
size_t ibytes = 1, obytes = 1;
size_t clean_exit = 0;
size_t* ref[3] = {&ibytes, &obytes, &clean_exit};
int s = argParse(argc, argv, fdescriptors, ref);
if (s == ERROR) return 1;
if (clean_exit) return 0; // finalizacion limpia, cuando se usa -h o -V
FILE* archIn = fdescriptors[0];
FILE* archOut = fdescriptors[1];
int fdIn = fileno(archIn);
int fdOut = fileno(archOut);
if (fdIn == -1 || fdOut == -1) return 1;
if (palindrome(fdIn, ibytes, fdOut, obytes) == -1) {
printf("palindrome returned -1\n");
return 1;
}
if (archIn != stdin && fclose(archOut) == EOF) return 1;
if (archOut != stdout && fclose(archOut) == EOF) return 1;
return 0;
}
//------------------------------------------------------------------------------
|
C | UTF-8 | 1,203 | 2.796875 | 3 | [] | no_license | // *** I am client ***
#include<stdio.h>
#include<stdlib.h>
#include<netdb.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<netinet/in.h>
int main(){
int sock, len = 0;
struct sockaddr_in my, ser;
// struct hostent *h;
char *host, buff[50], s[] = "172.20.22.121";
// h = gethostbyname(host);
/* if(h){
perror("host error:");
exit(1);
}*/
bzero(buff, sizeof(buff));
bzero(&my, sizeof(my));
bzero(&ser, sizeof(ser));
my.sin_port = htons(5502);
my.sin_family = AF_INET;
my.sin_addr.s_addr = INADDR_ANY;
ser.sin_family = AF_INET;
ser.sin_port = htons(5500);
inet_pton(AF_INET, "172.20.22.121", &ser.sin_addr);
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0){
perror("socket:");
exit(1);
}
bind(sock, (struct sockaddr *)&my, sizeof(my));
if(connect(sock, (struct sockaddr *)&my, sizeof(my)) < 0){
perror("connect:");
close(sock);
exit(1);
}
while(1){
printf("type the message\n");
scanf("%s", buff);
if(send(sock, (void*) buff, sizeof(buff), 0) < 0){
perror("sen:");
}
if(strcmp(buff,"bye") == 0){
break;
}
bzero(buff, sizeof(buff));
}
close(sock);
return 0;
}
|
C | UTF-8 | 1,363 | 2.90625 | 3 | [] | no_license | #ifndef HEAP_H
#define HEAP_H
struct aux_struct;
#include "auxqueue.h"
struct HeapNode
{
struct HeapNode* parent;
struct HeapNode* right;
struct HeapNode* left;
char* caller;
float bill;
};
struct Heap
{
struct HeapNode* root;
struct HeapNode* last;
int counter;
float revenue;
};
/*Creates Heap*/
void heap_create(struct Heap**);
/*Destroys the Heap*/
void heap_destroy(struct Heap*);
/*Destroys recursively each node*/
void heap_destroy_rec(struct HeapNode*);
/*Inserts a new element into the heap*/
void heap_insert(struct Heap*,char*,float);
/*Deletes an element from the heap*/
void heap_delete(struct Heap*,char*,float);
/*Adds a new node */
void heap_add_node(struct Heap*,struct HeapNode** ,struct HeapNode*,char,char*,float );
/*Extracts Root's value*/
int extract_root(struct Heap* heap,struct aux_struct*);
/*Shifts up element until the heap property is satisfied*/
void shift_up(struct Heap*,struct HeapNode*);
/*Shifts down element until the heap property is satisfied*/
void shift_down(struct Heap* heap,struct HeapNode* node);
/*Prints Heap nodes using BFS*/
void heap_print(struct Heap*);
/*Prints top subscribers that make top k % of revenue*/
void heap_top(struct Heap*,float);
/*Swaps two nodes*/
/*Just their stored data [caller and bill] not the whole nodes*/
void swap(struct HeapNode*,struct HeapNode*);
#endif
|
C | UTF-8 | 1,718 | 4.53125 | 5 | [] | no_license | /*
* Exercise 9.3 Kochan - Programming in C
*
* Write a function 'elapsed_time' that takes as its arguments two 'time'
* structures and returns a 'time' structure that represents the elapsed time
* (in hours, minutes and seconds) between the two times. So the call
*
* elapsed_time (time1, time2)
*
* where 'time1' represents 3:45:15 and 'time2' represents 9:44:03, should
* return a 'time' structure that represents 5 hours, 58 minutes and 48
* seconds. Be careful with times that cross midnight.
*/
#include <stdio.h>
// declaring struct time globally
struct time
{
int hour;
int minutes;
int seconds;
};
// prototypes
struct time elapsed_time (struct time time1, struct time time2);
// main function
int main (void)
{
struct time time1, time2, time3; // time3 will be time2-time1 struct
printf ("Enter the first time (hh:mm:ss): ");
scanf ("%i:%i:%i", &time1.hour, &time1.minutes, &time1.seconds);
printf ("Now, enter the second time (hh:mm:ss): ");
scanf ("%i:%i:%i", &time2.hour, &time2.minutes, &time2.seconds);
time3 = elapsed_time (time1, time2);
printf ("The elapsed time is %.2i:%.2i:%.2i\n", time3.hour, time3.minutes,
time3.seconds);
return 0;
}
// elapsed_time function
struct time elapsed_time (struct time time1, struct time time2)
{
int secondsCalc = (time2.hour * 3600 + time2.minutes * 60 + time2.seconds) -
(time1.hour * 3600 + time1.minutes * 60 + time1.seconds);
if (secondsCalc < 0)
secondsCalc += 24 * 3600;
struct time calc;
calc.hour = (secondsCalc / 3600);
calc.minutes = (secondsCalc % 3600) / 60;
calc.seconds = (secondsCalc % 3600) % 60;
return calc;
}
|
C | UTF-8 | 2,336 | 3.5625 | 4 | [] | no_license | /*
Project Euler
Problem 11 - find largest product 4 nums in a line
Jacob Mintz
*/
#include <stdio.h>
int getGrid(void);
int main(void)
{
int NROWS = 20;
int NCOLS = 20;
int LINE = 4;
int largeProd = 1;
int prod;
//int *nums = getGrid();
int a[2][4];
int i, f, g;
int nums[20][20];
FILE *fptr; //pointer to file
fptr = fopen("Jacob_Project_Euler\\P11Grid.txt","r");
if(fptr == NULL){
printf("Error!");
exit(1);
}
for(int i=0; i<20; i++){
for(int f=0; f<20; f++){
fscanf(fptr,"%d", &nums[i][f]);
printf("%4d",nums[i][f]);
}
printf("\n");
}
fclose(fptr);
//Verts
for(i=0; i<NROWS; i++){
for(f=0; f<(NCOLS - LINE); f++){
for(g=0, prod=1; g<4;g++)
prod *= nums[i][f+g];
if(prod>largeProd){
largeProd = prod;
for(int assi=0; assi<4; assi++){
a[0][assi] = i;
a[1][assi] = f+assi;
}
}
}
}
//Horz
for(i=0; i<(NROWS-LINE); i++){
for(f=0; f<NCOLS; f++){
for(g=0,prod=1; g<4;g++)
prod *= nums[i+g][f];
if(prod>largeProd){
largeProd = prod;
for(int assi = 0; assi<4; assi++){
a[0][assi] = i+assi;
a[1][assi] = f;
}
}
}
}
//Angle Down/Right
for(i=0; i<(NROWS-LINE); i++){
for(f=0; f<(NCOLS-LINE); f++){
for(g=0, prod=1; g<4;g++)
prod *= nums[i+g][f+g];
if(prod>largeProd){
largeProd = prod;
for(int assi = 0; assi<4; assi++){
a[0][assi] = i+assi;
a[1][assi] = f+assi;
}
}
}
}
//Angle Down/Left
for(i=1; i<(NROWS-LINE); i++){
for(f=LINE-1; f<NCOLS; f++){
for(g=0, prod=1; g<4;g++)
prod *= nums[i+g][f-g];
if(prod>largeProd){
largeProd = prod;
for(int assi = 0; assi<4; assi++){
a[0][assi] = i+assi;
a[1][assi] = f-assi;
}
}
}
}
printf("At %d, %d the largest product is: %d\n\n",a[0][0]+1,a[1][0]+1,largeProd);
for(i=0; i<4;i++){
int b1 = a[0][i]+1;
int b2 = a[1][i]+1;
int b3 = nums[b1-1][b2-1];
printf("(%d, %d) %d",b1,b2,b3);
printf("\n");
}
return 0;
}
/*
int getGrid(void){
int nums[20][20];
FILE *fptr; //pointer to file
fptr = fopen("Jacob_Project_Euler\\P11Grid.txt","r");
if(fptr == NULL){
printf("Error!");
exit(1);
}
for(int i=0; i<20; i++){
for(int f=0; f<20; f++){
fscanf(fptr,"%d", &nums[i][f]);
printf("%4d",nums[i][f]);
}
printf("\n");
}
fclose(fptr);
return *nums;
}
*/
|
C | UTF-8 | 538 | 2.921875 | 3 | [] | no_license | #define _GNU_SOURCE
#include <stdio.h>
#include <dlfcn.h>
int main(int argc, char** argv) {
if(argc < 3){
fprintf(stderr, "Too few arguments");
return 1;
}
char* filename = argv[1];
char* symname = argv[2];
double (*function)(double);
void* lib = dlopen(filename, 0);
function = dlsym(lib, symname);
if(!function){
perror("dlsym");
return 1;
}
double value;
while(scanf("%lf", &value) > 0){
printf("%.3f\n", function(value));
}
return 0;
}
|
C | UTF-8 | 1,354 | 4.21875 | 4 | [] | no_license | #include <stdio.h>
// Calculate the Greatest Common Denominator/Divisor (GCD) of two
// positive integers extA and extB.
// NOTE: LIKELY TO TERMINATE IF EITHER VALUE IS 0
unsigned int
extOut (unsigned int extA, unsigned int extB)
{
unsigned int A = extA;
unsigned int B = extB;
unsigned int C;
unsigned int OUT;
unsigned int swap;
// Find the minimum of A and B and set A to the larger of the two,
// and B to the smaller of the two.
if (A < B) {
swap = A;
A = B;
B = swap;
}
// Set C to the remainder of A divided by B. If C is zero, stop.
// The GCD is B. Otherwise, copy B to A and C to B, then start
// over.
for (C = A % B; 0 != C; C = A % B) {
A = B;
B = C;
}
// The GCD is B. Return it.
OUT = B;
return OUT;
}
// Allow the user to specify two numbers. Calculate the GCD of those
// two numbers and print it.
int
main (int argc, const char* const argv[])
{
unsigned int one;
unsigned int two;
char trash[2];
if (3 > argc || 1 != sscanf (argv[1], "%u%1s", &one, trash) ||
1 != sscanf (argv[2], "%u%1s", &two, trash) ||
0 == one || 0 == two) {
fprintf (stderr, "syntax: %s <n1> <n2>\n (both >0)\n", argv[0]);
return 2;
}
printf ("GCD(%u,%u) is %u.\n", one, two, extOut (one, two));
return 0;
}
|
C | UTF-8 | 199 | 2.9375 | 3 | [] | no_license | #include<stdio.h>
int main(){
char x[100];
char* p;
int result=0;
scanf("%s",x);
for(p=x;*p!='\0';++p){
if(*p=='X')++result;
}
printf("Result = %d\n",result);
return 0;
}
|
C | UTF-8 | 1,109 | 4.78125 | 5 | [] | no_license | /*
Within this program, we will pass an array with 6 integers to a function, have the function swap the first and last integer, the second and the second to last integer, the third and the third to last integer.
The function is called reverseArray and doesn't return anything (void). It should take one parameter, representing the array of integers.
The main function first reads 6 integers from the input, and assigns them to the array. The main function then calls reverseArray, passing the array as an argument.
The main function then prints the reversed array.
Examples
Input:
1 2 3 4 5 6
Output:
6 5 4 3 2 1
*/
#include <stdio.h>
void reverseArray(int []);
int main(void)
{
int array[6];
int i = 0;
for(i = 0; i < 6; i++)
{
scanf("%d", &array[i]);
}
printf("\n");
reverseArray(array);
for(i = 0; i < 6; i++)
{
printf("%d ", array[i]);
}
return 0;
}
void reverseArray(int arr[])
{
int j = 0, temp = 0;
for(j = 0; j < 3; j++)
{
temp = arr[j];
arr[j] = arr[5 - j];
arr[5 - j] = temp;
}
}
|
C | GB18030 | 2,059 | 2.5625 | 3 | [] | no_license | #include <reg52.h>
#include "port.h"
#include "Timer.h"
#include "Led7Seg.h"
uint8 g_u8LedDisplayBuffer[8] ={0};//ʾ
//-----------------------------------------------------------------------
// ܵĶ
//-----------------------------------------------------------------------
code uint8 g_u8LedDisplayCode[] =
{
0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,
0x80,0x90,0x88,0x83,0xC6,0xA1,0x86,0x8E,
0xbf//'-'Ŵ
};
#define LED_PORT P0
//-----------------------------------------------------------------------
// ܶ뺯
//-----------------------------------------------------------------------
static void SendLedSegData(uint8 dat)
{
LED_PORT = dat;
io_led_seg_cs = 1; //,Ͷ
io_led_seg_cs = 0;
}
//-----------------------------------------------------------------------
// λѡͨ
//-----------------------------------------------------------------------
static void SendLedBitData(uint8 dat)
{
uint8 temp;
temp = (0x01 << dat); //Ҫѡͨλλ
LED_PORT = temp;
io_led_bit_cs = 1; //λ,λ
io_led_bit_cs = 0;
}
//-----------------------------------------------------------------------
// Ķ̬ɨ躯
//-----------------------------------------------------------------------
void LedDisplay(uint8 *pBuffer)
{
static uint8 s_LedDisPos = 0;
if(g_bSystemTime2Ms)
{
g_bSystemTime2Ms = 0;
SendLedBitData(8); // ֻҪλѡΪ0~7 Ͷ֮ǰصλѡ
if(pBuffer[s_LedDisPos] == '-') //ʾ'-'
{
SendLedSegData(g_u8LedDisplayCode[16]);
}
else
{
SendLedSegData(g_u8LedDisplayCode[pBuffer[s_LedDisPos]]);
}
SendLedBitData(s_LedDisPos);
if(++s_LedDisPos > 7)
{
s_LedDisPos = 0; //ʾɨܵλ
}
}
}
|
C | UTF-8 | 671 | 3.40625 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
void findPalind(char *arr)
{
int flag = 0;
int i = 0;
while (arr[i] != '\0')
{
flag = flag ^ arr [i];
i++;
}
printf ("\nflag = %d", flag);
if (((flag < 'z') && (flag > 'a')) || ((flag < 'Z') && (flag > 'A')))
flag = 0;
// Find the required answer here. Print Yes or No at the end of this function depending on your inspection of the string
if (flag==0)
printf("YES\n");
else
printf("NO\n");
return;
}
int main() {
char arr[100001];
scanf("%s",arr);
findPalind(arr);
return 0;
}
|
C | UTF-8 | 568 | 2.90625 | 3 | [] | no_license | #ifndef __HEAD_H__
#define __HEAD_H__
#include <stdio.h>
struct shape {
const char* name;
struct shape_operations* sops;
};
struct shape_operations {
void (*draw)(const struct shape*);
};
struct triangle {
int a, b, c;
struct shape base;
};
struct circle {
int r;
struct shape base;
};
struct square {
int e;
struct shape base;
};
#define offset_of(type, member) \
((unsigned long)(&(((type*)0)->member)))
#define container_of(ptr, type, member) \
((type*)((unsigned long)(ptr) - offset_of(type, member)))
#endif
|
C | UTF-8 | 4,464 | 3.4375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
void error(char *msg) {
fprintf(stderr, "%s: %s\n", msg, strerror(errno));
exit(1);
}
void redirect_file_descriptor(int file_descriptor_from, int file_descriptor_to) {
if(dup2(file_descriptor_to, file_descriptor_from) == -1)
error("Can't redirect output");
}
int get_file_descriptor(FILE *f) {
return fileno(f);
}
int test_simple() {
printf("Process start\n");
pid_t p = getpid();
printf("Process Id: %i\n", p);
printf("About to fork...");
pid_t pid = fork();
if(pid == -1) {
fprintf(stderr, "Fork failed: %s\n", strerror(errno));
return 1;
}
if(pid == 0) {
printf("In simple child process\n");
return 0; // Return 0 to indicate successful finish of child task
} else {
printf("In main process\n");
}
printf("This should only print in the parent process\n");
int status;
waitpid(pid, &status, 0);
printf("Simple child finished\n");
return status;
}
int test_exec() {
pid_t pid = fork();
if(pid == (pid_t) -1) {
fprintf(stderr, "Fork 2 failed: %s\n", strerror(errno));
return 1;
}
if(pid == (pid_t) 0) {
printf("About to launch exec command\n");
/* call out to the shell to run one of the other programs from this one on the child process */
if(execl("./formatting", "./formatting", NULL) == -1) {
fprintf(stderr, "Cannot run program: %s\n", strerror(errno));
}
printf("This should not be printed because exec will not return...");
return 0;
} else {
printf("In main process, again\n");
}
printf("This also should only print in the parent process, wait for children\n");
int status;
waitpid(pid, &status, 0);
return status;
}
int test_redirect_of_stdout_to_file() {
FILE *f = fopen("process-output.txt", "w");
// Create a child process
pid_t pid = fork();
if (pid == (pid_t) -1) {
error("Can't fork process");
}
if (pid == (pid_t) 0) {
printf("Changing child to write to process-output.txt\n");
redirect_file_descriptor(get_file_descriptor(stdout), get_file_descriptor(f));
printf("This should show up in the file, not on stdout\n");
redirect_file_descriptor(get_file_descriptor(f), 1);
if (fclose(f) == -1) {
error("Unable to close process-output.txt");
};
return 0;
}
printf("The main process should get here, not the child\n");
int status;
waitpid(pid, &status, 0);
return status;
}
int test_write_from_child_to_parent() {
int fd[2]; // fd[0] is the read end of the pipe, fd[1] is the write end of the pipe
if (pipe(fd) == -1) {
error("Can't create pipe\n");
}
int read_fd = fd[0];
int write_fd = fd[1];
pid_t pid = fork();
if (pid == (pid_t) -1) {
error("Can't fork process");
}
if (pid == (pid_t) 0) {
printf("Child changed stdout to write to pipe\n");
redirect_file_descriptor(get_file_descriptor(stdout), write_fd);
close(read_fd); // Child will not use the read end of the pipe
printf("This should show up in the main thread\n");
printf("This should also show up in the main thrread\n");
return 0;
}
printf("Parent changed stdin to read from pipe\n");
redirect_file_descriptor(get_file_descriptor(stdin), read_fd);
close(write_fd); // Parent will not use the write end of the pipe
int status;
waitpid(pid, &status, 0);
char line[255];
while (fgets(line, 255, stdin)) {
printf("line detected from child: %s", line);
}
return status;
}
int main(int argc, char *argv[]) {
if (argc == 1) {
test_write_from_child_to_parent();
} else {
int to_run = atoi(argv[1]);
switch (to_run) {
case 0:
test_simple();
break;
case 1:
test_exec();
break;
case 2:
test_redirect_of_stdout_to_file();
break;
case 3:
test_write_from_child_to_parent();
break;
default:
test_write_from_child_to_parent();
}
}
return 0;
}
/* ANALYSIS:
One of the fun things to note is that '<', '>', '2>', and '|' from the command line corresponde to C functionality
* '<' is a redirect of stdin
* '>' is a redirect of stdout
* '2>' is a redirect of stderr
* '|' is a simple way to link one programs stdin to anothers stdout
The file descriptor table is where these redirections are carried out.
|stream | file descriptor|
|---|---|
| stdin | 0 |
| stdout | 1 |
| stderr | 2 |
*/
|
C | UTF-8 | 827 | 2.578125 | 3 | [] | no_license | #include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <unistd.h>
#include "rscommon/commonbase.h"
#include "rscommon/msq.h"
void usage(void);
int getSize(int qkey);
void usage() {
printf("Get message numbers in a given queue\n"
" Usage: qnum QUEUE_KEY\n");
}
int getSize(int qkey) {
int qid;
struct msqid_ds qds;
memset(&qds, 0, sizeof(struct msqid_ds));
qid = MsqGet(qkey, C_MsqR);
if (qid < 0) {
return -1;
}
if (MsqInfo(qid, &qds) != 0) {
return -2;
}
return (int)qds.msg_qnum;
}
int main(int args, char **argv) {
int nRetCode = -1;
if (args != 2) {
usage();
exit(-1);
}
if ((nRetCode = getSize(atoi(argv[1]))) < 0) {
exit(-2);
}
printf("%d\n", nRetCode);
return (0);
}
|
C | UTF-8 | 1,179 | 2.84375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include "effects.h"
#include "lpd8806.h"
#include "colors.h"
int bargraph_manual(int spi_fd, char *color1, char *color2) {
int i;
unsigned char data[128];
int bar=0;
unsigned char ch;
int lr,lg,lb,rr,rg,rb;
/* color left */
if (color1) {
get_color(color1,&lr,&lg,&lb);
}
else {
lr=63;
lg=0;
lb=0;
}
/* color right */
if (color2) {
get_color(color2,&rr,&rg,&rb);
}
else {
rr=0;
rg=0;
rb=0;
}
/* Clear to black */
for(i=0;i<128;i++) data[i]=128;
while(1) {
scanf("%c",&ch);
printf("Pressed %d\n",ch);
if (ch=='i') {
bar++;
if (bar>32) bar=32;
}
if (ch=='m') {
bar--;
if (bar<0) bar=0;
}
for(i=0;i<32;i++) {
if (i<bar) {
data[(i*3)+0]=128+lg;
data[(i*3)+1]=128+lr;
data[(i*3)+2]=128+lb;
} else {
data[(i*3)+0]=128+rg;
data[(i*3)+1]=128+rr;
data[(i*3)+2]=128+rb;
}
}
lpd8806_write(spi_fd,data);
}
lpd8806_close(spi_fd);
return 0;
}
|
C | UTF-8 | 277 | 3.359375 | 3 | [] | no_license | #include<stdio.h>
//给出三个整数,分别表示等差数列的第一项、最后一项和公差,求该数列的和。
int main(){
int a,b,c;
int sum=0;
scanf("%d%d%d",&a,&b,&c);
sum = sum + a;
while (a!=b)
{
a = a + c;
sum=sum+a;
}
printf("%d",sum);
return 0;
} |
C | UTF-8 | 1,900 | 3.703125 | 4 | [
"MIT"
] | permissive | /**************************************************************
* Copyright (c) Wuzhiyi
* Introduction to Algorithms
*
* 题目: Problem 6-2
* 名称: D-ARY-HEAP
* 作者: skanev
* 语言: c
* 内容摘要: 对d叉堆的分析
*
* 修改记录:
* 修改日期 版本号 修改人 修改内容
* ------------------------------------------------------------
* 20150708 V1.0 wuzhiyi 创建
**************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define PARENT(i,d) ((i-1)/d)
#define CHILD(i,c,d) (3*i+c+1)
typedef struct {
int *elements;
int d;
int heap_size;
int length;
} heap_t;
void max_heapify(heap_t *heap, int i)
{
int largest=i;
for (int k=0; k<heap->d; k++) {
int child=CHILD(i,k,heap->d);
if (child<heap->heap_size && heap->elements[child]>heap->elements[largest])
largest=child;
}
if (largest!=i)
{
int tmp=heap->elements[i];
heap->elements[i]=heap->elements[largest];
heap->elements[largest]=tmp;
max_heapify(heap,largest);
}
}
int extract_max(heap_t *heap)
{
int max=heap->elements[0];
heap->elements[0]=heap->elements[heap->heap_size-1];
heap->heap_size--;
max_heapify(heap,0);
return max;
};
void increase_key(heap_t *heap, int i, int key)
{
if (key<heap->elements[i]) {
fprintf(stderr,"new key is smaller than current key\n");
exit(0);
}
while (i>0 && heap->elements[PARENT(i,heap->d)]<key) {
heap->elements[i]=heap->elements[PARENT(i,heap->d)];
i=PARENT(i,heap->d);
}
heap->elements[i]=key;
}
void insert(heap_t *heap, int key)
{
heap->heap_size++;
heap->elements[heap->heap_size-1]=INT_MIN;
increase_key(heap,heap->heap_size-1,key);
}
|
C | UTF-8 | 8,273 | 3.03125 | 3 | [] | no_license | /*
============================================================================
Name : shell.c
Author : André Schaiter Florian Gwechenberger
Version :
Copyright : made by André Schaiter Florian Gwechenberger
Description : FHS Lite Shell in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <dirent.h>
#define ERROR_ALLOKATING (-1);
#define ERROR_CHANGING_DIRECTORY (-2);
struct tm *tmnow;
char dir_file[15] = {"tmp_dir.txt"};
char tasks[5][8] ={"fhsdate","fhstime","echo","help","exit"};
char helps[5][100]={{"Befehl [fhsdate] gibt das Datum von heute aus"},
{"Befehl [fhstime] gibt die jetztige Uhrzeit aus"},
{"Befehl [echo] gibt die nachstehenden Zeichen nochmal aus"},
{"Befehl [help] gibt alle Befehle aus"},
{"Befehl [exit] schließt das Programm"}};
int main(void) {
DIR * dir;
FILE * history_file;
FILE * dir_stream;
int counter = 0;
history_file = fopen("history.txt","r+");
//Fehlerkontrolle für fopen missing
char * charpwd = malloc(sizeof(char)* 1024);
if(charpwd == NULL){
return ERROR_ALLOKATING;
}
strcpy(charpwd,"/home/flo/"); //copy of starting directory
int exit = 0; //0= false; 1=true for action "exit"
//loop until user writes "exit"
if ((dir = opendir (charpwd)) != NULL) {
// printf ("%s\n", currentdir->d_name);
}
else{
printf("Failed to open dir");
}
do{
//echo; fhsdate; fhstime; exit; help;
int i;
int inputlength;
char arguments[100];
int attachment = 0;
char * input = malloc(sizeof(char)*1000);
//tries to open dir
printf("%s> ",charpwd);
pid_t pid;
int parent;
void * status;
//File * stream;
fgets(input,1000, stdin);
parent = fork();
if(parent == 0){
if(input[0]!='\n'){
char input_history [strlen(input)];
fseek(history_file,0,SEEK_SET);
fscanf(history_file, "%i", &counter);
counter++;
char tmpzahl[10];
sprintf(tmpzahl, "%i\n", counter);
fseek(history_file,0,SEEK_SET);
fprintf(history_file,tmpzahl);
fseek(history_file,0,SEEK_END);
strcpy(input_history,input);
fprintf(history_file,input_history);
inputlength= strlen(input);
realloc(input,strlen(input));
int pos;
pos = strcspn(input," ");
//"Switch"
if(pos<strlen(input)){
attachment = 1;
strcpy(arguments,input+pos+1);
realloc(input,pos);
input[pos]='\0';
arguments[inputlength-pos-2]='\0';
}
else{
input[inputlength-1]='\0';
}
//action echo
if(strcmp(input,"echo")==0){
printf("%s\n",arguments);
}
//action cd - change directory
else if(strcmp(input,"cd")==0){
if(change_dir(strlen(charpwd),charpwd,strlen(arguments),arguments) == 0){
printf("Path %s not existing!\n", arguments);
}else{
dir_stream = fopen(dir_file,"w");
if(dir_stream>0){
fprintf(dir_stream,"%s",charpwd);
fclose(dir_stream);
return 2;
}
}
}
else if(strcmp(input,"ls")==0){
if(show_dir(strlen(charpwd),charpwd) < 0){
return -4;
}
}
//action help
else if(strcmp(input,"help")==0){
int i;
if(attachment==1){
for(i=0; i<(sizeof(tasks)/8);i++){
if(strcmp(arguments,tasks[i])==0){
printf("%s",helps[i]);
break;
}
}
}
else{
for(i=0; i<(sizeof(tasks)/8);i++){
printf("-%s\n",tasks[i]);
}
}
}
else if(strcmp(input,"pushd")==0){
FILE * pushing;
pushing = fopen("path.txt","w");
fprintf(pushing,charpwd);
fclose(pushing);
}
else if(strcmp(input,"popd")==0){
FILE * pushing;
char * tmpstring = malloc(sizeof(char) * 1024);
pushing = fopen("path.txt","r");
fgets(tmpstring,1024,pushing);
if(change_dir(strlen(charpwd),charpwd,strlen(tmpstring),tmpstring) == 0){
printf("Path %s not existing!\n", arguments);
}else{
dir_stream = fopen(dir_file,"w");
if(dir_stream>0){
fprintf(dir_stream,"%s",charpwd);
fclose(dir_stream);
return 2;
}
}
}
else if(strcmp(input,"history")==0){
char * tmpstring = malloc(sizeof(char) * 1024);
fseek(history_file,0,SEEK_SET);
fgets(tmpstring,1024,history_file);
// fscanf(config_file, "%*[^\n]\n", NULL);
int i;
for(i=0;i<counter;i++){
fgets(tmpstring,1024,history_file);
printf("%i\t%s",i+1,tmpstring);
}
return 2;
}
//action fhsdate
else if(strcmp(input,"fhsdate")==0){
getdate();
}
//action fhstime
else if(strcmp(input,"fhstime")==0){
getTime();
}
else if(strcmp(input,"pwd")==0){
printf("%s\n",charpwd);
}
//action exit
else if(strcmp(input,"exit")==0){
return 1;
}
else if(strncmp(input,"./",2)==0){
pid_t pid;
int p_type, status; //p_type = process type for example child {0} or parent {1<=}
p_type = fork();
if(p_type == 0){ // child
//deklaring path including path of action
char tmp_path[strlen(charpwd)+strlen(input)];
strcpy(tmp_path,charpwd); strcat(tmp_path,input+2);
//executing and checking result of action [-1->error, 0< ok, etc.]
return execlp(tmp_path, input+2, arguments, NULL);
}
else{ // parent
pid = wait(&status);
if(status < 0 || status >= 65280){
printf("ERROR accrued during executing of required file: \n\t*Filename: %s\n\t*Filepath %s\n",input+2,charpwd);
if(strcmp(arguments,"")!=0){
printf("\t*Arguments: %s\n",arguments);
}
}else{
}
}
}else{
printf("Unknown input: %s.\n", input);
}
return 0;
}
return 0;
}else{
pid = wait(&status);
if(status < 0){
printf("ERROR input\n");
}else if(status == 256){
exit = 1;
}else if(status == 0){
}else if(status == (2*(256))){
dir_stream=fopen(dir_file,"r");
if(dir_stream > 0){
fgets(charpwd,"%s",dir_stream);
fclose(dir_stream);
}
}
else{
}
}
}while(exit != 1);
fclose(history_file);
return 0;
}
void getdate(){
time_t tnow;
time(&tnow);
tmnow = localtime(&tnow);
printf("Heute ist der ");
printf("%d.%d.%d\n",
tmnow->tm_mday, tmnow->tm_mon + 1, tmnow->tm_year + 1900);
}
void getTime() {
struct tm *zeit;
time_t sekunde;
char string[80];
time(&sekunde);
zeit = localtime(&sekunde);
strftime(string, 80,"Es ist %H Uhr und %M Minuten",zeit);
printf("%s\n",string);
}
int change_dir(int dir_size, char charpwd[dir_size], int arg_size, char arguments[arg_size]){
DIR * dir;
char * tmpstring = malloc(sizeof(char)*1024);
if(tmpstring==0){
return ERROR_ALLOKATING;
}
strcpy(tmpstring,charpwd);
//check which direction
//checko on cd .. - return to one dir back
if(strcmp(arguments,"..")==0){
int tmppos = 0;
//check every single position if there a the last valid position
int i;
for(i=0;i<strlen(tmpstring)-1;i++){
if(tmpstring[i] == '/'){
tmppos = i;
}
}
tmpstring[tmppos+1]='\0';
}
//check if requested whole path
else if(arguments[0]=='/'){
strcpy(tmpstring,arguments);
}
//add folder to path
else{
strcat(tmpstring,arguments);
}
//check if last char == /, if not add /
if(tmpstring[strlen(tmpstring)-1]!='/'){
strcat(tmpstring,"/");
}
//check if path is reachable
if ((dir = opendir (tmpstring)) != NULL) {
strcpy(charpwd,tmpstring);
free(tmpstring);
return 1;
}
else{
free(tmpstring);
return 0;
}
}
int show_dir(int size, char path_dir[size]){
if(path_dir <= 0){
return -4;
}
DIR * current_dir;
if((current_dir = opendir(path_dir)) == NULL){
return -2;
}
struct dirent * dir_element;
while(dir_element = readdir (current_dir)){
printf("%s\t",dir_element->d_name);
}
printf("\n");
}
void getecho(int size, char arguments[size]){
printf("%s",arguments);
}
void getexit(){
exit;
}
void gethelp(int size, char argument[size]){
}
|
C | UTF-8 | 2,310 | 2.640625 | 3 | [] | no_license | /*
* Copyright (c) 2013 Yannik Li(Yanqing Li)
*
* 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.
*/
#include <string.h>
#include <kernel/types.h>
#include <kernel/printk.h>
#include <kernel/debug.h>
void _assert(
const char* assertion,
const char* file,
unsigned int line,
const char* function)
{
printk("YakOS failed assertion '%s' at %s:%u in function %s\n",
assertion,
file,
line,
function
);
halt();
}
void hexdump(const void *ptr, size_t len)
{
addr_t address = (addr_t)ptr;
size_t count;
int i;
for (count = 0 ; count < len; count += 16) {
printk("0x%08lx: ", address);
printk("%08x %08x %08x %08x |", *(const uint32_t *)address, *(const uint32_t *)(address + 4), *(const uint32_t *)(address + 8), *(const uint32_t *)(address + 12));
for (i=0; i < 16; i++) {
char c = *(const char *)(address + i);
if (isalpha(c)) {
printk("%c", c);
} else {
printk(".");
}
}
printk("|\n");
address += 16;
}
}
void hexdump8(const void *ptr, size_t len)
{
addr_t address = (addr_t)ptr;
size_t count;
int i;
for (count = 0 ; count < len; count += 16) {
printk("0x%08lx: ", address);
for (i=0; i < 16; i++) {
printk("0x%02hhx ", *(const uint8_t *)(address + i));
}
printk("\n");
address += 16;
}
}
|
C | GB18030 | 284 | 3.34375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *a[3];
int i;
for(i=0;i<3;i++)
{
a[i]=(char *)malloc(sizeof(char)*30); //Ϊÿַ30ֽڵĿռ
scanf("%s",a[i]);
}
for(i=0;i<3;i++)
{
printf("%s\n",a[i]);
free(a[i]);
}
return 0;
}
|
C | UTF-8 | 2,250 | 3.859375 | 4 | [] | no_license | While we're on the subject of structures, we might as well look at bitfields. They can only be declared inside a
structure or a union, and allow you to specify some very small objects of a given number of bits in length. Their
usefulness is limited and they aren't seen in many programs, but we'll deal with them anyway. This example should
help to make things clear:
struct {
/* field 4 bits wide */
unsigned field1 :4;
/*
* unnamed 3 bit field
* unnamed fields allow for padding
*/
unsigned :3;
/*
* one-bit field
* can only be 0 or -1 in two's complement!
*/
signed field2 :1;
/* align next field on a storage unit */
unsigned :0;
unsigned field3 :6;
}full_of_fields;
Each field is accessed and manipulated as if it were an ordinary member of a structure. The keywords signed and
unsigned mean what you would expect, except that it is interesting to note that a 1-bit signed field on a two's
complement machine can only take the values 0 or -1. The declarations are permitted to include the const and
volatile qualifiers.
The main use of bitfields is either to allow tight packing of data or to be able to specify the fields within some
externally produced data files. C gives no guarantee of the ordering of fields within machine words, so if you do
use them for the latter reason, you program will not only be non-portable, it will be compiler-dependent too. The
Standard says that fields are packed into ‘storage units’, which are typically machine words. The packing order, and
whether or not a bitfield may cross a storage unit boundary, are implementation defined. To force alignment to a
storage unit boundary, a zero width field is used before the one that you want to have aligned.
Be careful using them. It can require a surprising amount of run-time code to manipulate these things and you can
end up using more space than they save.
Bit fields do not have addresses—you can't have pointers to them or arrays of them.
union
{
struct
{
char a:1;
char b:2;
char c:3;
}d;
char e;
} f;
f.e = 1;
printf("%d/n",f.d.a);
return 0;
|
C | UTF-8 | 6,314 | 2.546875 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* libft.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kmurray <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/28 12:26:25 by kmurray #+# #+# */
/* Updated: 2017/07/26 23:05:52 by kmurray ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef LIBFT_H
# define LIBFT_H
# include <stdlib.h>
# include <unistd.h>
# include <stdio.h>
# include <string.h>
# include <errno.h>
# include <sys/stat.h>
# include <sys/types.h>
# include <sys/wait.h>
# include <sys/ioctl.h>
# include <signal.h>
# include <fcntl.h>
# include "get_next_line.h"
# include "printf.h"
# define BLACK "\x1b[30m"
# define RED "\x1b[31m"
# define GREEN "\x1b[32m"
# define YELLOW "\x1b[33m"
# define BLUE "\x1b[34m"
# define MAGENTA "\x1b[35m"
# define CYAN "\x1b[36m"
# define WHITE "\x1b[37m"
# define BBLACK "\x1b[40m"
# define BRED "\x1b[41m"
# define BGREEN "\x1b[42m"
# define BYELLOW "\x1b[43m"
# define BBLUE "\x1b[44m"
# define BMAGENTA "\x1b[45m"
# define BCYAN "\x1b[46m"
# define BWHITE "\x1b[47m"
# define RESET "\x1b[0m"
# define CLEAR "\033c"
# define BOLD "\033[1m"
typedef char t_bool;
typedef struct s_list
{
void *content;
size_t content_size;
struct s_list *next;
} t_list;
void *ft_memset(void *dest, int c, size_t count);
void ft_bzero(void *s, size_t n);
void ft_freezero(void *mem, size_t size);
void *ft_memcpy(void *dest, void const *src, size_t count);
void *ft_memccpy(void *dest, void const *src,
int c, size_t count);
void *ft_memmove(void *dest, void const *src, size_t count);
void *ft_memchr(void const *s, int c, size_t n);
int ft_memcmp(void const *s1, void const *s2, size_t n);
void *ft_memalloc(size_t size);
void ft_memdel(void **ap);
void *ft_memdup(void const *str);
size_t ft_strlen(char const *str);
size_t ft_endspaces(char *str);
size_t ft_wordlen(char *str, char c);
size_t ft_count_words(char *str, char c);
size_t ft_strlchr(char *str, char c);
char *ft_strdup(char const *str);
char *ft_strndup(char const *str, size_t size);
char *ft_strmove(char *dest, char **src);
char *ft_strcpy(char *dest, char const *src);
char *ft_strncpy(char *dest, char const *src, size_t n);
char *ft_strcat(char *s1, char const *s2);
char *ft_strncat(char *s1, char const *s2, size_t n);
size_t ft_strlcat(char *s1, char const *s2, size_t size);
char *ft_strchr(char const *str, int c);
char *ft_strrchr(char const *str, int c);
char *ft_strstr(char const *big, char const *little);
char *ft_strnstr(char const *big, char const
*little, size_t len);
int ft_strlstr(char *big, char *little);
int ft_strlnstr(char *big, char *little);
char *ft_strsubstr(char *big, char *little, char *sub);
int ft_strcmp(char const *s1, char const *s2);
int ft_strncmp(char const *s1, char const *s2, size_t n);
char *ft_strnew(size_t size);
void ft_strdel(char **as);
void ft_strclr(char *s);
void ft_striter(char *str, void (*f)(char *));
void ft_striteri(char *str, void (*f)(unsigned int, char *));
char *ft_strmap(char const *str, char (*f)(char));
char *ft_strmapi(char const *str, char (*f)(unsigned int, char));
int ft_strequ(char const *s1, char const *s2);
int ft_strnequ(char const *s1, char const *s2, size_t n);
char *ft_strsub(char const *str, unsigned int start,
size_t size);
char *ft_strjoin(char const *s1, char const *s2);
char *ft_strtrim(char const *str);
char **ft_strsplit(char const *str, char c);
char **ft_dup_r(char **arr);
char **ft_dupn_r(char **arr, int size);
char **ft_pop_r(char **arr, int n);
int ft_size_r(char **arr);
void ft_print_r(char **arr);
void ft_del_r(char **arr);
int ft_atoi(char const *str);
char *ft_itoa(int n);
char *ft_lltoa_base(long long n, int base);
char *ft_maxtoa_base(intmax_t n, int base);
char *ft_umaxtoa_base(uintmax_t n, int base);
int ft_count_base(intmax_t n, int base);
int ft_countu_base(uintmax_t n, int base);
char ft_base_char(int n);
int ft_isprime(int n);
int ft_power_of(int base, int power);
int ft_max(int num1, int num2);
int ft_min(int num1, int num2);
int ft_abs(int x);
void ft_tboolswitch(t_bool *x);
int ft_isalpha(int c);
int ft_isdigit(int c);
int ft_isalnum(int c);
int ft_isascii(int c);
int ft_isprint(int c);
int ft_toupper(int c);
char *ft_toupperstr(char *str);
char *ft_tolowerstr(char *str);
char *ft_capitalize_each(char *str);
int ft_tolower(int c);
int ft_iswhitespace(char c);
void ft_putchar(char c);
void ft_putstr(char const *str);
int ft_putlchar(char c);
int ft_putlstr(char const *str);
void ft_putendl(char const *str);
void ft_putnbr(int n);
int ft_putlnbr(int n);
void ft_putchar_fd(char c, int fd);
void ft_putstr_fd(char const *str, int fd);
void ft_putendl_fd(char const *str, int fd);
void ft_putnbr_fd(int n, int fd);
int ft_putlnbr_fd(int n, int fd, int i);
void ft_printfile(char *path);
void ft_exit_malloc_error(char *str, size_t size);
void ft_exit_read_error(char *str, char **line, int fd);
t_list *ft_lstnew(void const *content, size_t content_size);
void ft_lstcat(t_list **alst, t_list *new);
void ft_lstdelone(void *content, size_t size);
void ft_lstdel(t_list **alst, void (*del)(void *, size_t));
void ft_lstadd(t_list **alst, t_list *new);
void ft_lstiter(t_list *lst, void (*f)(t_list *elem));
void ft_lstsort(t_list **lst, int (*cmp)(void *, void *));
t_list *ft_lstmap(t_list *lst, t_list *(*f)(t_list *elem));
t_list **ft_lstpop(t_list **alst, t_list **begin_list);
#endif
|
C | UTF-8 | 3,176 | 3.78125 | 4 | [] | no_license | // В одномерном массиве, состоящем из п вещественных элементов, вычислить:
// 1) максимальный по модулю элемент массива;
// 2) сумму элементов массива, расположенных между первым и вторым положительными элементами.
//Преобразовать массив таким образом, чтобы элементы, равные нулю, располага¬лись после всех остальных.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <stdbool.h>
#define n 5
void swap(int* a, int* b) { // меняет местами элементы
int tmp = *a;
*a = *b;
*b = tmp;
}
void print(int* box, int size) { //вывод массива
int i;
for (i = 0; i < size; ++i) printf("%i ", box[i]);
puts("");
}
void shift(int* beg, int* end) {
while (beg + 1 != end) {
swap(beg, beg + 1);
++beg;
}
}
void stable_partition(int* box, int size) {
int i;
int* end = box + size;
int* last = end - 1;
int stop = size;
for (i = 0; i < stop; ++i) {
while (0 == box[i]) {
shift(&box[i], end);
last = 0;
if (!--stop) break;
}
}
}
int main()
{
int i,j, b;
int iMax=0, iMin=0;
int numMaxFirst, count=0, summ=0;
int arr[n];
for(i = 0; i < n; i++)
{ // вводим элементы с клавиатуры
printf("input element %d: ", i + 1); scanf("%d", &arr[i]);
if(arr[i]>0)
{ // если элемент больше положительный запоминаем его для сравнения
numMaxFirst=i;// и запоминаем его позицию
}
}
for (i = 0; i < n; i++)
{
if (abs(arr[i]) > abs(arr[iMax])) {iMax = i; }
}
printf("\nMax element == %d\n", arr[iMax]); //вывод в терминал самого большого по модулю элемента
// ищем первый положительный
for(i = 0; i < n; i++)
{
if(arr[i]>0)
{ // если элемент больше положительный запоминаем его для сравнения
numMaxFirst=i;// и запоминаем его позицию
break;
}
}
// ищем второй положительный элемент
for(i = 0; i<n; ++i)
{
if(arr[i]>0 && i!=numMaxFirst) // нашли положительный элемент
{
for(j = numMaxFirst+1; j < i; j++) { //складываем все элементы, которые находятся между 1 и вторым положительным элементом.
summ+=arr[j];
}
printf("\nsumm between positive element: %d \n", summ);
break;
}
}
int size = sizeof(arr) / sizeof(arr[0]);
print(arr, size);
stable_partition(arr, size);
print(arr, size);
system("pause > nul");
return 0;
} |
C | UTF-8 | 16,265 | 2.640625 | 3 | [] | no_license | /*
* proxy.c
*
* Made: July 31, 2015 by jkasbeer
* Version: Part 3
* Known bugs: (1) Aborts in Mozilla Firefox @ www.cmu.edu with an error in
* Getaddrinfo. Stems from call to Open_clientfd & fails
* while executing freeaddrinfo (run-time error).
*
* Proxy Lab
*
* This is a concurrent web proxy with a 1 MiB web object cache.
* The cache can handle objects up to 10 KiB in size, and is implemented
* with a LRU eviction policy. It runs concurrently by creating a new thread
* for each new client that makes a request to a server, and features
* read-write locks for concurrent cache reading & writing, favoring writers.
* This was my favorite lab and I'm beyond proud of what I've written.
*/
#include <stdio.h>
#include "csapp.h"
#include "pcache.h"
/* String constant macros */
#define MAXPORT 8 // max port length (no larger than 6 digits)
#define BIGBUF 16384 // max buf length (16 Kb)
/* Global var's */
static const char *user_agent_hdr =
"User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:10.0.3) Gecko/20120305 Firefox/10.0.3\r\n";
static const char *accept_hdr =
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n";
static const char *accept_encoding_hdr = "Accept-Encoding: gzip, deflate\r\n";
static const char *conn_hdr = "Connection: close\r\n";
static const char *pconn_hdr = "Proxy-Connection: close\r\n";
static const char *end_hdr = "\r\n";
static const char *web_port = "80";
/* Request handling functions */
void *thread(void *fd);
void connect_req(int connected_fd);
int parse_req(int connection, rio_t *rio,
char *host, char *port, char *path);
int is_dir(char *path);
int not_error(char *obj);
void forward_req(int server, int client, rio_t *requio,
char *host, char *path);
int ignore_hdr(char *hdr);
/* Error handling functions */
void check_argc(int argc, int check, char **argv);
void bad_request(int fd, char *cause);
void flush_str(char *str);
void flush_strs(char *str1, char *str2, char *str3);
/* Function prototypes for wrapper functions */
int Pthread_rwlock_init(pthread_rwlock_t *rwlock,
const pthread_rwlockattr_t *attr);
int Pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
int Pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
int Pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
int Pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
/* Global web cache */
cache *C;
pthread_rwlock_t lock;
/*
* main - main proxy routine: listens for client requests
* and creates a new thread to process and forward
* each one as they come.
*/
int main(int argc, char **argv)
{
/* Main routine variables */
int plisten, *connection; // File descriptors
struct sockaddr_storage caddr; // Client info
socklen_t clen;
pthread_t tid; // Thread
/* Some setup.. */
check_argc(argc, 2, argv);
C = Malloc(sizeof(struct web_cache));
cache_init(C, &lock);
Signal(SIGPIPE, SIG_IGN);
/* Listen on port specified by user */
plisten = Open_listenfd(argv[1]);
clen = sizeof(caddr);
/* Infinite proxy loop */
while (1) {
/* Wait for client to send request */
connection = Malloc(sizeof(int));
*connection = Accept(plisten, (SA *)&caddr, &clen);
/* Create new thread to process the request */
Pthread_create(&tid, NULL, thread, connection);
}
}
/*
* thread - connect to the client on [fd] & forward request
*/
void *thread(void *fd)
{
/* Dereference fd then free it */
int connection = *((int *) fd);
Free(fd);
/* Detach thread to avoid memory leaks */
Pthread_detach(pthread_self());
/* Attempt to connect to server */
connect_req(connection);
/* Close thread's connection to client */
Close(connection);
}
/********************
* MY HELPER ROUTINES
********************/
/*
* sconnect - check for errors in the client request, parse the request,
* open a connection with the server, and finally forward
* the request to the server.
*/
void connect_req(int connection)
{
/* Core var's of connect_req */
int middleman; // File descriptor
char host[MAXLINE] = {0}, // Server info
port[MAXPORT] = {0},
path[MAXLINE] = {0};
/* Rio to parse client request */
rio_t rio;
/* Parse client request into host, port, and path */
if (parse_req(connection, &rio, host, port, path) < 0) {
fprintf(stderr, "Cannot read this request path..\n");
flush_strs(host, port, path);
}
/* Parsing succeeded.. continue */
else {
/* READING */
Pthread_rwlock_rdlock(&lock);
line *lion = in_cache(C, host, path);
Pthread_rwlock_unlock(&lock);
/* If in cache, don't connect to server */
if (lion != NULL) {
if (rio_writen(connection, lion->obj, lion->size) < 0)
fprintf(stderr, "rio_writen error: bad connection");
flush_strs(host, port, path);
}
/* Otherwise, connect to server & forward request */
else {
if ((middleman = Open_clientfd(host, port)) < 0) {
bad_request(middleman, host);
flush_strs(host, port, path);
}
else {
forward_req(middleman, connection, &rio, host, path);
/* Clean up & close connection to server */
flush_strs(host, port, path);
Close(middleman);
}
}
}
}
/*
* parse_req - parse client request into method, uri, and version,
* then parse the uri into host, port (if specified), and path;
* returns -1 on error, 0 otherwise.
*/
int parse_req(int connection, rio_t *rio,
char *host, char *port, char *path)
{
/* Parse request into method, uri, and version */
char meth[MAXLINE] = {0},
uri[MAXLINE] = {0},
vers[MAXLINE] = {0};
char rbuf[MAXLINE] = {0};
/* Strings to keep track of uri parsing */
char *spec, *check; // port specified ?
char *buf, *p, *save; // used for explicit uri parse
/* Constants necessary for string lib functions */
const char colon[2] = ":";
const char bslash[2] = "/";
/* SETUP FOR PARSING -- */
/* Initialize rio */
Rio_readinitb(rio, connection);
if (Rio_readlineb(rio, rbuf, MAXLINE) <= 0) {
bad_request(connection, rbuf);
flush_str(rbuf);
return -1;
}
/* Splice the request */
sscanf(rbuf, "%s %s %s", meth, uri, vers);
flush_str(rbuf);
/* Error: HTTP request that isn't GET or 'http://' not found */
if (strcmp(meth, "GET") || !(strstr(uri, "http://"))) {
bad_request(connection, uri);
flush_strs(meth, uri, vers);
return -1;
}
/* PARSE URI */
else {
buf = uri + 7; // ignore 'http://'
spec = index(buf, ':');
check = rindex(buf, ':');
if (spec != check) return -1; // cannot handle ':' after port
/* Port is specified.. */
if (spec) {
// Get host name
p = strtok_r(buf, colon, &save);
// Copy if successful
strcpy(host, p);
// Get port from buf
buf = strtok_r(NULL, colon, &save);
p = strtok_r(buf, bslash, &save);
// Copy if successful
strcpy(port, p);
// Get path (rest of buf)
while ((p = strtok_r(NULL, bslash, &save)) != NULL)
{ strcat(path, bslash); strcat(path, p); }
if (is_dir(path))
strcat(path, bslash);
}
/* Port not specified.. */
else {
// Get host name
p = strtok_r(buf, bslash, &save);
strcpy(host, p);
// Get path
while ((p = strtok_r(NULL, bslash, &save)) != NULL)
{ strcat(path, bslash); strcat(path, p); }
if (is_dir(path)) // append '/' if path is a directory
strcat(path, bslash);
// Set port as unspecified
strcpy(port, web_port);
}
/* Clean-up */
flush_strs(meth, uri, vers);
flush_strs(spec, buf, p);
flush_str(save);
return 0;
}
}
/*
* is_dir - determine if path is a directory or contains a file name;
* returns 1 if directory, 0 if not
*/
int is_dir(char *path)
{
/* If path is a file we support, return 0 */
if (strstr(path,".html") || strstr(path,".css") || strstr(path,".xml"))
return 0;
else if (strstr(path,".gif") || strstr(path,".png") || strstr(path,".jpg"))
return 0;
else if (strstr(path,".c") || strstr(path,".js") || strstr(path,".json"))
return 0;
else if (strstr(path,".ini") || strstr(path,".csv") || strstr(path,".tsv"))
return 0;
else if (strstr(path,".bak") || strstr(path,".bk") || strstr(path,".bin"))
return 0;
else if (strstr(path,".dat") || strstr(path,".dsk") || strstr(path,".raw"))
return 0;
else if (strstr(path,".asc") || strstr(path,".txt") || strstr(path,"tiny"))
return 0;
else if (strstr(path,".ttf") || strstr(path,".woff"))
return 0;
/* Otherwise, path is a directory */
else
return 1;
}
/*
* forward_request - Forward the client's request to the server;
* use file descriptor server & read client headers
* from &requio
*/
void forward_req(int server, int client, rio_t *requio,
char *host, char *path)
{
/* Client-side reading */
char buf[BIGBUF] = {0};
char cbuf[MAXLINE] = {0};
ssize_t n = 0;
/* Server-side reading */
char svbuf[MAXLINE] = {0};
rio_t respio;
ssize_t m = 0;
/* Implementing web object cache */
char object[MAX_OBJECT_SIZE] = {0};
size_t obj_size = 0;
/* BUILD & FORWARD REQUEST TO SERVER -- */
sprintf(buf, "GET %s HTTP/1.0\r\n", path);
/* Build client headers */
while((n = rio_readlineb(requio, cbuf, MAXLINE)) != 0)
{
if (n < 0) {
flush_str(cbuf); return;
}
if (!strcmp(cbuf, "\r\n"))
break; // empty line found => end of headers
if (!ignore_hdr(cbuf))
sprintf(buf, "%s%s\r\n", buf, cbuf);
flush_str(cbuf); // flush line after copied
}
/* Build proxy headers */
sprintf(buf, "%sHost: %s\r\n", buf, host);
sprintf(buf, "%s%s", buf, user_agent_hdr);
sprintf(buf, "%s%s", buf, accept_hdr);
sprintf(buf, "%s%s", buf, accept_encoding_hdr);
sprintf(buf, "%s%s", buf, conn_hdr);
sprintf(buf, "%s%s", buf, pconn_hdr);
sprintf(buf, "%s%s", buf, end_hdr);
/* Forward request to server */
if (rio_writen(server, buf, strlen(buf)) < 0) {
flush_str(buf); return;
}
/* BUILD & FORWARD SERVER RESPONSE TO CLIENT -- */
/* Initialize rio to read server's response */
Rio_readinitb(&respio, server);
/* Read from fd [server] & write to fd [client] */
while ((m = Rio_readlineb(&respio, svbuf, MAXLINE)) != 0)
{
// Rio error check
if (m < 0) {
flush_str(svbuf); return;
}
// For cache
obj_size += m;
sprintf(object, "%s%s", object, svbuf);
// Write to client
if (rio_writen(client, svbuf, m) < 0) {
flush_str(svbuf); return;
}
flush_str(svbuf);
}
/* Object is not cached.
If it's small enough & not a sever error, cache it */
if (obj_size <= MAX_OBJECT_SIZE && not_error(object)) {
/* WRITING */
Pthread_rwlock_wrlock(&lock);
add_line(C, make_line(host, path, object, obj_size));
Pthread_rwlock_unlock(&lock);
}
/* Clean-up */
flush_strs(buf, cbuf, svbuf);
flush_strs(host, path, object);
}
/*
* ignore_hdr - if this header is one of the mandatory proxy headers,
* ignore it (return 1); if it isn't, don't ignore (return 0)
*/
int ignore_hdr(char *hdr)
{
// Ignore header for Proxy-Connection
if (strstr(hdr, "Proxy-Connection"))
return 1; // ignore
// Ignore header for Connection
else if (strstr(hdr, "Connection"))
return 1; // ignore
// Ignore empty line for client headers
else if (strcmp(hdr, "\r\n"))
return 1; // ignore
// Everything else is acceptable
else
return 0; // don't ignore
}
/*
* not_error - determines if obj is a server error or not;
* return 1 if it isn't, 0 if it is
*/
int not_error(char *obj)
{
size_t objsize = strlen(obj) + 1;
char object[objsize];
memset(object, 0, sizeof(object));
memcpy(object, obj, objsize);
return strstr(object, "200") != NULL ? 1 : 0;
}
/********************
* CLEAN-UP FUNCTIONS
********************/
/*
* flush_str - wipe memory of a single string
*/
void flush_str(char *str)
{ if (str) memset(str, 0, sizeof(str)); }
/*
* flush_strs - wipe memory of up to 3 strings
*/
void flush_strs(char *str1, char *str2, char *str3)
{
if (str1) memset(str1, 0, sizeof(str1));
if (str2) memset(str2, 0, sizeof(str2));
if (str3) memset(str3, 0, sizeof(str3));
}
/****************
* ERROR HANDLERS
****************/
/* Error: 400
* bad_request - client error: invalid format in request
*/
void bad_request(int fd, char *cause)
{
char buf[MAXLINE];
sprintf(buf, "<html><title>Error 400: bad request</title>\r\n");
sprintf(buf, "%s<body><h1>Error 400: bad request</h1>\r\n", buf);
sprintf(buf, "%s<h3>Caused by <em>%s</em></h3></body></html>\r\n", buf, cause);
flush_str(buf);
}
/*
* check_argc - checks for incorrect argument count to command prompt;
* eliminates clutter in main function
*/
void check_argc(int argc, int check, char **argv)
{
if (argc != check) {
fprintf(stderr, "usage: %s <port>\n", argv[0]);
exit(1);
}
}
/**********************************
* Wrappers for robust I/O routines
**********************************/
ssize_t Rio_readn(int fd, void *ptr, size_t nbytes)
{
ssize_t n;
if ((n = rio_readn(fd, ptr, nbytes)) != 0) {
if (errno == ECONNRESET)
fprintf(stderr, "ECONNRESET muffled by proxy\n");
else if (n < 0)
fprintf(stderr, "Rio_readn error\n");
else
fprintf(stderr, "Rio_readn returned unknown error\n");
}
return n;
}
void Rio_writen(int fd, void *usrbuf, size_t n)
{
ssize_t rc;
if ((rc = rio_writen(fd, usrbuf, n)) != 0) {
if (errno == EPIPE)
fprintf(stderr, "EPIPE muffled by proxy\n");
if (n < 0)
fprintf(stderr, "Rio_writen error\n");
flush_str(usrbuf);
}
}
void Rio_readinitb(rio_t *rp, int fd)
{
rio_readinitb(rp, fd);
}
ssize_t Rio_readnb(rio_t *rp, void *usrbuf, size_t n)
{
ssize_t rc;
if ((rc = rio_readnb(rp, usrbuf, n)) < 0)
fprintf(stderr, "Rio_readnb error\n");
return rc;
}
ssize_t Rio_readlineb(rio_t *rp, void *usrbuf, size_t maxlen)
{
ssize_t rc;
if ((rc = rio_readlineb(rp, usrbuf, maxlen)) < 0)
fprintf(stderr, "Rio_readlineb error\n");
return rc;
}
/**************************
* READ-WRITE LOCK WRAPPERS
**************************/
/*
* Pthread_rwlock_init - wrapper function for pthread_rwlock_init;
* initializes rwlock
*/
int Pthread_rwlock_init(pthread_rwlock_t *rwlock,
const pthread_rwlockattr_t *attr)
{
int r;
if ((r = pthread_rwlock_init(rwlock, attr)) != 0)
cache_error("pthread_rwlock_init failed");
return r;
}
/*
* Pthread_rwlock_wrlock - wrapper function for pthread_rwlock_wrlock;
* applies a write-lock to *rwlock
*/
int Pthread_rwlock_wrlock(pthread_rwlock_t *rwlock)
{
int r;
if ((r = pthread_rwlock_wrlock(rwlock)) != 0)
cache_error("pthread_rwlock_wrlock failed");
return r;
}
/*
* Pthread_rwlock_rdlock - wrapper function for pthread_rwlock_rdlock;
* applies a read-lock to *rwlock
*/
int Pthread_rwlock_rdlock(pthread_rwlock_t *rwlock)
{
int r;
if ((r = pthread_rwlock_rdlock(rwlock)) != 0)
cache_error("pthread_rwlock_rdlock failed");
return r;
}
/*
* Pthread_rwlock_unlock - wrapper function for pthread_rwlock_unlock;
* unlocks rwlock
*/
int Pthread_rwlock_unlock(pthread_rwlock_t *rwlock)
{
int r;
if ((r = pthread_rwlock_unlock(rwlock)) != 0)
cache_error("pthread_rwlock_unlock failed");
return r;
}
/*
* Pthread_rwlock_destroy - wrapper function for pthread_rwlock_destroy;
* destroys read-write lock rwlock
*/
int Pthread_rwlock_destroy(pthread_rwlock_t *rwlock)
{
int r;
if ((r = pthread_rwlock_destroy(rwlock)) != 0)
cache_error("pthread_rwlock_destroy failed");
return r;
}
|
C | UTF-8 | 3,879 | 3.71875 | 4 | [] | no_license | /****************************************
** 319-1A
** Tom Beadman
** 20 Feb 2012
**
** Statistical Moments:
** This program calculates the statistical moments from a 100 element
** distribution contained in blank.txt.
**
** Currently the program is producing nonsense results half of the time and
** correct results the other half, this needs to be fixed.
****************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void moment(float data[], int n, float *ave, float *adev, float *sdev, float *var, float *skew, float *curt);
void sort(unsigned long n, float arr[]);
int main()
{
unsigned int i = 0;
unsigned int j = 0;
FILE *input;
const char inp_fn[] = "src/319/blank.txt";
float* ave = malloc(sizeof (float));
float* adev = malloc(sizeof (float));
float* sdev = malloc(sizeof (float));
float* var = malloc(sizeof (float));
float* skew = malloc(sizeof (float));
float* curt = malloc(sizeof (float));
float data[100];
printf("\n\n**************************************\n");
printf("Program to determine statistical moments for a given dataset\n");
printf("**************************************\n\n");
input = fopen(inp_fn, "r");
if ((input != (FILE*) NULL)) {
while (!feof(input)) {
fscanf(input, "%f \n", &data[i]);
i++;
}
printf("\nTransferred:\n");
for (j = 0; j < i; j++) {
printf("%f\n", data[j]);
}
moment(data, j, ave, adev, sdev, var, skew, curt);
printf("\nMoment Statistics\n");
printf("********************************\n");
printf("Number of points: %u\n", j);
printf("Mean value: %f\n", *ave);
printf("Average Deviation: %f\n", *adev);
printf("Standard Deviation: %f\n", *sdev);
printf("Variance: %f\n", *var);
printf("Skewness: %f\n", *skew);
printf("Kurtosis: %f\n", *curt);
printf("********************************\n");
//sort(j, data);
printf("\nSorted:\n");
for (j = 0; j < i; j++) {
printf("%f\n", data[j]);
}
printf("\nMoment Statistics\n");
printf("********************************\n");
printf("Number of points: %u\n", j);
printf("Mean value: %f\n", *ave);
printf("Average Deviation: %f\n", *adev);
printf("Standard Deviation: %f\n", *sdev);
printf("Variance: %f\n", *var);
printf("Skewness: %f\n", *skew);
printf("Kurtosis: %f\n", *curt);
printf("********************************\n");
return (EXIT_SUCCESS);
}
return (EXIT_FAILURE);
}
void moment(float data[], int n, float *ave, float *adev, float *sdev, float *var, float *skew, float *curt)
{
int j;
float ep = 0.0, s, p;
if (n <= 1) {
printf("n must be at least 2 in moment");
exit(EXIT_FAILURE);
}
s = 0.0;
for (j = 1; j <= n; j++) s += data[j];
*ave = s / n;
*adev = (*var) = (*skew) = (*curt) = 0.0;
for (j = 1; j <= n; j++) {
*adev += fabs(s = data[j]-(*ave));
ep += s;
*var += (p = s * s);
*skew += (p *= s);
*curt += (p *= s);
}
*adev /= n;
*var = (*var - ep * ep / n) / (n - 1);
*sdev = sqrt(*var);
if (*var) {
*skew /= (n * (*var)*(*sdev));
*curt = (*curt) / (n * (*var)*(*var)) - 3.0;
}
else {
printf("No skew/kurtosis when variance = 0 (in moment)");
exit(EXIT_FAILURE);
}
}
/*Sorts a specified array into increasing order*/
void sort(unsigned long n, float arr[])
{
int i, j;
float a;
for (j = 1; j < n; j++) {
a = arr[j];
i = j;
while ((i > 0) && (arr[i - 1] > a)) {
arr[i] = arr[i - 1];
i--;
}
arr[i] = a;
}
} |
C | UTF-8 | 1,331 | 4.09375 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
struct QNode {
int value;
struct QNode* next;
};
typedef struct QNode* PtrToQNode;
struct QueueStr {
PtrToQNode Front;
PtrToQNode Rear;
};
typedef struct QueueStr* Queue;
//函数:创建一个队列
Queue CreatQueue() {
Queue Q = (Queue)malloc(sizeof(struct QueueStr));
Q->Front = NULL;
Q->Rear = NULL;
return Q;
}
//函数:判断一个队列是否为空
bool isEmpty(Queue Q) {
return (Q->Front == NULL);
}
//函数:往队列中加一个元素
void AddQ(Queue Q, int E) {
PtrToQNode temp = (PtrToQNode)malloc(sizeof(struct QNode));
temp->value = E;
temp->next = NULL;
if ( isEmpty(Q) ) {
Q->Front = temp;
Q->Rear = temp;
}
else {
Q->Rear->next = temp;
Q->Rear = temp;
}
}
//函数:从队列中删除一个元素
int DeleteQ(Queue Q) {
if ( isEmpty(Q) ) {
printf("The Queue is empty so cannot delete\n");
return -404;
}
else {
PtrToQNode TopCell = Q->Front;
Q->Front = TopCell->next;
if (Q->Front == NULL) //如果队列中只有一个结点,被删后Front变为了NULL,Rear也要置为NULL
Q->Rear = NULL;
int E = TopCell->value;
free(TopCell);
return E;
}
}
// 主函数
int main() {
Queue Q1 = CreatQueue();
for (int i=11; i<=15; i++)
AddQ(Q1, i);
for (int j=11; j<=15; j++)
printf("%d ", DeleteQ(Q1));
return 0;
} |
C | GB18030 | 3,165 | 3.296875 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS 1
#include "Heap.h"
#define ARRSIZE(a) (sizeof(a)/sizeof(a[0]))
#include "Heap.h"
#include <string.h>
#include <stdio.h>
#if 1
void swap(HPDataType *a, HPDataType *b) //һԼԼԼԼͬʱԼĶӦַĿռ䣬ֵ*aͬʱְ*bĵˣԽsortΪһֻʣһڵʱ
{
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
#else
void swap(HPDataType *a, HPDataType *b)
{
HPDataType tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
#endif
void DownAdjust(Heap *hp, int n) //n Ҫе±
{
int cur = n;
while (cur*2+1<hp->size) //һûڵ㣬һҶӣֱ
{
if (hp->data[cur] < hp->data[cur * 2 + 1]) //Уcurڵ㻹Сִн
{
if (cur * 2 + 2>=hp->size || hp->data[2 * cur + 2] <= hp->data[cur * 2 + 1]) //ҺӲڻӴҺ
{
swap(&hp->data[cur], &hp->data[cur * 2 + 1]); //ӻ
cur = cur * 2 + 1; //λ
}
else{ //ҺӴӣҺӽ
swap(&hp->data[cur], &hp->data[cur * 2 + 2]);
cur = cur * 2 + 2;
}
}
else if (cur*2+2<hp->size && hp->data[cur] < hp->data[cur * 2 + 2]){ //curСҺҴҺ Һӻ
swap(&hp->data[cur], &hp->data[cur * 2 + 2]);
cur = cur * 2 + 2;
}
else {
break; //涼ѭ
}
}
}
void HeapInit(Heap *hp, HPDataType *data, int n)
{
int i;
hp->capacity = MAXSIZE>n?MAXSIZE:n;
hp->size = n;
hp->data = (HPDataType *)malloc(sizeof(HPDataType)*hp->capacity); //mallocпգҲҪп
memcpy(hp->data, data, sizeof(HPDataType)*n);
for (i = n/2-1; i >= 0; i--)
{
DownAdjust(hp, i);
}
}
void HeapDestory(Heap *hp)
{
if (hp->data)
{
free(hp->data);
hp->data = NULL;
hp->size = hp->capacity = 0;
}
}
void HeapPush(Heap *hp, HPDataType x)
{
int cur = hp->size;
if (hp->size == hp->capacity){
hp->capacity *= 2;
hp->data = (HPDataType *)realloc(hp->data, hp->capacity*sizeof(HPDataType));
}
hp->data[hp->size] = x;
hp->size++;
while (cur){
if (hp->data[cur] > hp->data[(cur - 1) / 2])
{
swap(&hp->data[cur], &hp->data[(cur - 1) / 2]);
cur = (cur - 1) / 2;
}
else{
break;
}
}
}
void HeapPop(Heap *hp)
{
swap(hp->data, hp->data + hp->size - 1);
hp->size--;
DownAdjust(hp, 0);
}
HPDataType HeapTop(Heap *hp)
{
if (hp->size == 0)
{
return (HPDataType)0;
}
return hp->data[0];
}
int HeapSize(Heap *hp)
{
return hp->size;
}
int HeapEmpty(Heap *hp)
{
return hp->size == 0;
}
void HeapPrint(Heap *hp)
{
int i;
int tag=0;
int tmp = 1;
for (i = 0; i < hp->size; i++)
{
printf("%d ", hp->data[i]);
if (i == tag)
{
printf("\n");
tmp *= 2;
tag += tmp;
}
}
}
void HeapSort(Heap *hp)
{
int tmp = hp->size;
while (hp->size >1)
{
HeapPop(hp);
}
hp->size = tmp;
} |
C | UTF-8 | 582 | 3.140625 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include <float.h>
int main(void)
{
double d_third = 1.0/3.0;
float f_third = 1.0/3.0;
printf("float of one third(6) = %.6f\n", f_third);
printf("float of one third(12) = %.12f\n", f_third);
printf("float of one third(16) = %.16f\n", f_third);
printf("double of one third(6) = %.6f\n", d_third);
printf("double of one third(12) = %.12f\n", d_third);
printf("double of one third(16) = %.16f\n", d_third);
printf("FLT_DIG in float.h is %d\n", FLT_DIG);
printf("DBL_DIG in float.h is %d\n", DBL_DIG);
return 0;
} |
C | UTF-8 | 869 | 3.5625 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define N 1000
void swap(double* a, double* b){
double c = *a;
*a = *b;
*b = c;
}
bool next_perm(int n, double* A){
int i = n-1;
for(; i > 0; i--){
if(A[i-1] < A[i]) break;
else if(i - 1 == 0) return false;
}
int m = i-1;
for(int j = i; j < n; j++){
if(A[j] > A[m]){
m = j;
}
}
swap(&A[i-1], &A[m]);
for(int j = i; j < i + (n - i) / 2; j++){
swap(&A[j], &A[n - j + i - 1]);
}
return true;
}
int main(){
int n;
scanf("%d", &n);
double* arr = calloc(n, sizeof(double));
for(int i = 0; i < n; i++){
scanf("%lf", &arr[i]);
}
printf("%d\n", next_perm(n, arr));
for(int i = 0; i < n; i++){
printf("%lf ", arr[i]);
}
return 0;
}
//1 2 5 6 4 3
//1 2 6 3 4 5 |
C | UTF-8 | 2,083 | 2.703125 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* manage_list.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ccoupez <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/23 11:00:48 by ccoupez #+# #+# */
/* Updated: 2018/04/23 15:17:26 by ccoupez ### ########.fr */
/* */
/* ************************************************************************** */
#include "../include/push_swap.h"
t_lstint *ft_lstint_new(int content)
{
t_lstint *list;
if (!(list = (t_lstint *)malloc(sizeof(t_lstint))))
return (NULL);
if (content)
list->data = content;
else
list->data = 0;
list->next = NULL;
list->prev = NULL;
list->type_tab = 'a';
return (list);
}
void ft_lstint_pback(t_info *dlist, t_lstint *new)
{
if (dlist->begin == NULL)
{
dlist->begin = new;
dlist->end = new;
new->prev = NULL;
}
else
{
dlist->end->next = new;
new->prev = dlist->end;
dlist->end = new;
}
new->next = NULL;
}
void ft_lstint_pfirst(t_info *dlist, t_lstint *new)
{
if (dlist->begin == NULL)
{
dlist->begin = new;
dlist->end = new;
new->next = NULL;
}
else
{
dlist->begin->prev = new;
new->next = dlist->begin;
dlist->begin = new;
}
}
void free_maillon(t_lstint **list)
{
t_lstint *tmp;
tmp = (*list)->next;
free(*list);
*list = tmp;
}
void free_lstint(t_info *lsta, t_info *lstb)
{
t_lstint *a;
t_lstint *b;
a = NULL;
b = NULL;
if (lsta)
a = lsta->begin;
if (lstb)
b = lstb->begin;
while (a || b)
{
if (a)
free_maillon(&a);
if (b)
free_maillon(&b);
}
if (lsta)
free(lsta);
if (lstb)
free(lstb);
}
|
C | UTF-8 | 942 | 2.515625 | 3 | [] | no_license | /* posix */
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
/* bsd extensions */
#include <sys/uio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define CLASS(x) (x[0]>>6)
int
inet_aton(char *from, struct in_addr *in)
{
unsigned char *to;
unsigned long x;
char *p;
int i;
in->s_addr = 0;
to = (unsigned char*)&in->s_addr;
if(*from == 0)
return 0;
for(i = 0; i < 4 && *from; i++, from = p){
x = strtoul(from, &p, 0);
if(x != (unsigned char)x || p == from)
return 0; /* parse error */
to[i] = x;
if(*p == '.')
p++;
else if(*p != 0)
return 0; /* parse error */
}
switch(CLASS(to)){
case 0: /* class A - 1 byte net */
case 1:
if(i == 3){
to[3] = to[2];
to[2] = to[1];
to[1] = 0;
} else if (i == 2){
to[3] = to[1];
to[1] = 0;
}
break;
case 2: /* class B - 2 byte net */
if(i == 3){
to[3] = to[2];
to[2] = 0;
}
break;
}
return 1;
}
|
C | UTF-8 | 2,082 | 2.84375 | 3 | [
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"CC0-1.0"
] | permissive | #ifndef AN_ALLOCATOR_H
#define AN_ALLOCATOR_H
#include "an_cc.h"
AN_EXTERN_C_BEGIN
#include "acf_export.h"
#include <stddef.h>
#include <string.h>
struct an_allocator {
void *(*malloc)(const void *ctx, size_t size, void *return_addr);
void *(*calloc)(const void *ctx, size_t nmemb, size_t size, void *return_addr);
void *(*realloc)(const void *ctx, void *address, size_t size_from, size_t size_to, void *return_addr);
void (*free)(const void *ctx, void *ptr, void *return_addr);
};
static inline void *
an_allocator_malloc(const struct an_allocator *a, size_t size, void *return_addr)
{
return a->malloc(a, size, return_addr);
}
static inline void *
an_allocator_calloc(const struct an_allocator *a, size_t nmemb, size_t size, void *return_addr)
{
return a->calloc(a, nmemb, size, return_addr);
}
static inline void *
an_allocator_realloc(const struct an_allocator *a, void *address, size_t size_from, size_t size_to, void *return_addr)
{
return a->realloc(a, address, size_from, size_to, return_addr);
}
static inline void
an_allocator_free(const struct an_allocator *a, void *ptr, void *return_addr)
{
a->free(a, ptr, return_addr);
}
char *an_allocator_strdup(const struct an_allocator *a, const char *s);
char *an_allocator_strndup(const struct an_allocator *a, const char *s, size_t n);
#define AN_MALLOC(IF, N) \
an_allocator_malloc((IF), (N), __builtin_return_address(0))
#define AN_CALLOC(IF, N, SIZE) \
an_allocator_calloc((IF), (N), (SIZE), __builtin_return_address(0))
#define AN_REALLOC(IF, ADDR, SIZE_FROM, SIZE_TO) \
an_allocator_realloc((IF), (ADDR), (SIZE_FROM), (SIZE_TO), __builtin_return_address(0))
#define AN_FREE(IF, ADDR) \
an_allocator_free((IF), (ADDR), __builtin_return_address(0))
#define AN_STRDUP(IF, S) \
an_allocator_strdup((IF), (S))
#define AN_STRNDUP(IF, S, N) \
an_allocator_strndup((IF), (S), (N))
/*
* Default allocator uses plain malloc, calloc, realloc, and free
*/
ACF_EXPORT const struct an_allocator *an_default_allocator(void);
extern const struct an_allocator default_allocator;
AN_EXTERN_C_END
#endif
|
C | UTF-8 | 1,898 | 2.515625 | 3 | [] | no_license | #ifndef UTILIDADES_GENERAL_H_
#define UTILIDADES_GENERAL_H_
#include <commons/config.h>
#include <stdint.h>
#include <errno.h> // Incluye perror
#include "sockets.h"
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <commons/log.h>
#include "tiposDeDatos.h"
#define ERROR -1
#define INT (sizeof(int))
#define CHAR (sizeof(char))
#define DIRECCION (sizeof(direccion))
#define VARIABLE (sizeof(variable))
#define HANDSHAKE_SIZE CHAR*2 // Tamaño de consola\0
#define NELEMS(x) (sizeof(x) / sizeof((x)[0]))
void* reservarMemoria(int size); // Hace lo mismo que el malloc pero se fija si hay error. Necesita casteo como malloc
void leerArchivoDeConfiguracion(char * ruta);
int comprobarQueExistaArchivo(char * ruta);
void setearValores_config(t_config * archivoConfig); // Hay que redefinirlo en cada proceso
int handshake_servidor(int sockCliente, char *mensaje); // Envía mensaje handshake al socketCliente y luego se queda esperando mensaje de confirmación
void handshake_cliente(int sockClienteDe, char *mensaje); // Se queda en espera de mensaje de servidor y luego envía un mensaje
int validar_cliente(char *id); // Valida que la conexión del cliente sea correcta
int validar_servidor(char *id); // Valida que la conexión al servidor sea correcta
int validar_conexion(int socket, int modo); // Decide si termina o no el programa ante un error, según el modo. Modo 1 es terminante. Con modo no terminante retorna: 0 en ERROR. 1 en éxito
int validar_recive(int bytes, int modo); // Decide si ante una desconexión o error en mensaje termina el programa o sigue, según el modo. Modo 1 es terminante. Retorno: 0 en desconexión o error. 1 en éxito
void dormir(float miliseconds); // Duerme el hilo del que se está ejecutando milisegundos (más preciso y consistente que sleep y usleep)
void liberarRegistroStack(registroStack* reg);
#endif
|
C | UTF-8 | 1,944 | 3.375 | 3 | [] | no_license | #include "inc.h"
//Position boids on the field based on what is passed in via file (regular text file)
//First line should be maximum sizes (width height)
/*
file encoding: 0 - barrier/unusable spot
1 - free spot open on the board
2 - boid in location
3 - exit location
*/
void setupSimulation(char * fileName, boidContainer * boids, goalContainer * goals, short *** board, short *** blank, unsigned int * width, unsigned int * height){
FILE * fd = fopen(fileName, "r");
unsigned int i, j;
boid * newBoid = NULL;
fscanf(fd, "%u %u", width, height);
(*board) = (short **) calloc(*width, sizeof(short *));
(*blank) = (short **) calloc(*width, sizeof(short *));
for(i = 0; i < *width; i++){
(*board)[i] = (short *) calloc(*height, sizeof(short));
(*blank)[i] = (short *) calloc(*height, sizeof(short));
}
//Go through parsing the file
for(j = 0; j < *height; j++){
for(i = 0; i < *width; i++){
fscanf(fd, "%1hd", &((*board)[i][j]));
(*blank)[i][j] = (*board)[i][j];
if((*board)[i][j] == 2){
(*blank)[i][j] = 1;
newBoid = (boid *) calloc(1, sizeof(boid));
newBoid->xpos = i;
newBoid->ypos = j;
newBoid->active = 1;
newBoid->velocity.x = 0;
newBoid->velocity.y = 0;
boidInsert(boids, newBoid);
newBoid = NULL;
}else if((*board)[i][j] == 3){
//Should add to a list of exits so that its easy to figure out closest exit don't need to go through entire map
addGoal(goals, i, j);
}
}
}
}
void addGoal(goalContainer * goals, int x, int y){
//Check for need to extend container
if(goals->size == goals->alloc){
goals->alloc += CONTAINEREXTEND;
if((goals->pos = (int **) realloc(goals->pos, goals->alloc * sizeof(int *))) == NULL){
fprintf(stderr, "Error extending goal conatiner, quitting...\n");
exit(1);
}
}
goals->pos[goals->size] = (int *) calloc(2, sizeof(int));
goals->pos[goals->size][0] = x;
goals->pos[goals->size][1] = y;
++goals->size;
}
|
C | UTF-8 | 3,044 | 2.984375 | 3 | [] | no_license | /**
* hash.c
* @file hash.h
* obj
* @date July 12, 2012
* @author Brandon Surmanski
*/
#include "hash.h"
#define MASK8 0xff
#define MASK16 0xffff
#define MASK24 0xffffff
#define MASK32 0xffffffff
#define MASK64 0xffffffffffffffff
#define FNV32_PRIME 16777619u
#define FNV64_PRIME 1099511628211ull
#define FNV32_OFFSET 2166136261u
#define FNV64_OFFSET 14695981039346656037ull
// Hash algorithm defaults to FNV
uint16_t (*hash16_text)(const const char *a, size_t max) = hash_fnv16_text;
uint16_t (*hash16_data)(const uint8_t *a, size_t sz) = hash_fnv16_data;
uint32_t (*hash32_text)(const const char *a, size_t max) = hash_fnv32_text;
uint32_t (*hash32_data)(const uint8_t *a, size_t sz) = hash_fnv32_data;
uint64_t (*hash64_text)(const char *a, size_t max) = hash_fnv64_text;
uint64_t (*hash64_data)(const uint8_t *a, size_t sz) = hash_fnv64_data;
/**
* FNV-1a hashing algorithm for 16-bits. For calculations of 16 bits,
* A 32 bit hash is folded to get a 16 bit value.
*/
uint16_t hash_fnv16_text(const char *a, size_t max)
{
uint32_t hash = hash_fnv32_text(a, max);
return (uint16_t) ((hash >> 16) ^ (hash & MASK16));
}
/**
* FNV-1a hashing algorithm for 16-bits. Unlike the text hashing, this
* will ignore the significance of null bytes
*/
uint16_t hash_fnv16_data(const uint8_t *a, size_t sz)
{
uint32_t hash = hash_fnv32_data(a, sz);
return (uint16_t) ((hash >> 16) ^ (hash & MASK16));
}
/**
* FNV-1a hashing algorithm for 32-bits.
*/
uint32_t hash_fnv32_text(const char *a, size_t max)
{
uint32_t hash = FNV32_OFFSET;
uint32_t next;
while ((next = (uint32_t) *a++) && max--)
{
hash = hash ^ next;
hash = hash * FNV32_PRIME;
}
return hash;
}
/**
* FNV-1a hashing algorithm for 32-bits. Unlike the text hashing,
* this method will ignore any significance of null bytes
*/
uint32_t hash_fnv32_data(const uint8_t *a, size_t sz)
{
uint32_t hash = FNV32_OFFSET;
uint32_t next;
while (sz--)
{
next = (uint8_t) *a++;
hash = hash ^ next;
hash = hash * FNV32_PRIME;
}
return hash;
}
uint32_t hash_fnv32_file(const char *filenm)
{
uint32_t hash = 0;
uint8_t buf[1024];
FILE *f = fopen(filenm, "rb");
while(fread(buf, 1, 1024, f))
{
uint32_t next = hash_fnv32_data(buf, 1024);
hash = hash ^ next;
hash = hash * FNV32_PRIME;
}
fclose(f);
return hash;
}
/**
* FNV-1a hashing algorithm for 64-bits.
*/
uint64_t hash_fnv64_text(const char *a, size_t max)
{
uint64_t hash = FNV64_OFFSET;
uint64_t next;
while ((next = (uint64_t) *a++) && max--)
{
hash = hash ^ next;
hash = hash * FNV64_PRIME;
}
return hash;
}
/**
* FNV-1a hashing algorithm for 64-bits.
*/
uint64_t hash_fnv64_data(const uint8_t *a, size_t sz)
{
uint64_t hash = FNV64_OFFSET;
uint64_t next;
while (sz--)
{
next = (uint8_t) *a++;
hash = hash ^ next;
hash = hash * FNV64_PRIME;
}
return hash;
}
|
C | UTF-8 | 898 | 3.59375 | 4 | [] | no_license | POINTERS TO FUNCTIONS
int x;
int *y;
x = 42;
y = &x;
*y = 0; // so now x = 0; keep this shit in MIND
----------
void f(char c); // function returns nothing, it takes a character, c, as a parameters
void (*funptr)(char); // we don't need to specify a name for the function's parameter
// ***** MORE COMPLETE EXAMPLE ******
#include <unistd.h> // for write
void ft_putchar(char c)
{
write(1, &c, 1)
return;
}
int main()
{
void (*f)(char);
f = &ft_putchar; // now we can just call ft_putchar with f('character') !!!
f('z');
return (0);
}
// ***** TYPEDEF EXAMPLE *****
#include <unistd.h>
typedef void (*funptr)(char);
void ft_putchar(char c)
{
write(1, &c, 1)
return;
}
int main()
{
funptr f; // creates a typedef (shortcut) that will create a pointer to a function
f = &ft_putchar;
f('z');
return (0);
}
// ***** MORE IN DEPTH EXAMPLE ***** (PSEUDO CODE)
|
C | UTF-8 | 2,921 | 2.578125 | 3 | [] | no_license | /*
* rs485Eltako.c
*
* Created: 10.11.2012 17:04:51
* Author: thomas
*/
#include <avr/io.h>
#include "uart2.h"
#include "rs485eltako.h"
rs485eltako_t msgrx;
typedef void (*voidFuncPtru08)(const rs485eltako_t *msg);
volatile static voidFuncPtru08 appRxFuncHandler;
#define MODE_WAITING_FOR_PREAMBLE 0
#define MODE_RECEIVED_SYNC_BYTE1 1
#define MODE_IN_FRAME 2
uint8_t mode;
uint8_t byteIdx;
uint8_t frameLen;
uint8_t checksum;
void rs485eltako_init(void) {
uart1Init();
uartSetBaudRate(1,RS485ELTAKO_BAUDRATE);
mode = MODE_WAITING_FOR_PREAMBLE;
}
uint8_t rs485eltako_transmitMessage(const rs485eltako_t *msg) {
uint8_t i;
uint8_t checksum;
char *msgbuf;
if (uartTransmitPending(1)) return 0;
uartAddToTxBuffer(1,RS485ELTAKO_SYNCBYTE1);
uartAddToTxBuffer(1,RS485ELTAKO_SYNCBYTE2);
checksum = 0;
uartAddToTxBuffer(1,RS485ELTAKO_LENGTH);
checksum+=RS485ELTAKO_LENGTH;
uartAddToTxBuffer(1,msg->org);
uartAddToTxBuffer(1,msg->databuf[3]);
uartAddToTxBuffer(1,msg->databuf[2]);
uartAddToTxBuffer(1,msg->databuf[1]);
uartAddToTxBuffer(1,msg->databuf[0]);
uartAddToTxBuffer(1,msg->idbuf[3]);
uartAddToTxBuffer(1,msg->idbuf[2]);
uartAddToTxBuffer(1,msg->idbuf[1]);
uartAddToTxBuffer(1,msg->idbuf[0]);
msgbuf =(char*)msg;
for (i=0;i<sizeof(rs485eltako_t);i++) {
checksum+=msgbuf[i];
}
uartAddToTxBuffer(1,RS485ELTAKO_STATUS);
checksum+=RS485ELTAKO_STATUS;
uartAddToTxBuffer(1,checksum);
uartSendTxBuffer(1);
return 1;
}
void rs485eltako_setRxHandler(void (*rx_func)(const rs485eltako_t *msg)) {
appRxFuncHandler = rx_func;
}
void rs485eltakoReceiveTask(void) {
uint8_t data;
//Check if new data available and get it
if (uartReceiveByte(1,&data)) {
switch (mode) {
case MODE_WAITING_FOR_PREAMBLE:
if (data==RS485ELTAKO_SYNCBYTE1) {
mode = MODE_RECEIVED_SYNC_BYTE1;
}
break;
case MODE_RECEIVED_SYNC_BYTE1:
if (data==RS485ELTAKO_SYNCBYTE2) {
mode = MODE_IN_FRAME;
byteIdx = 0;
} else {
//preamble wrong change back to searching for full preamble
mode = MODE_WAITING_FOR_PREAMBLE;
}
break;
case MODE_IN_FRAME:
if (byteIdx==0) {
frameLen = data&0x1F; //mask out H_SEQ, just keep LENGTH
checksum = data;
} else {
if (byteIdx==1) msgrx.org = data;
if (byteIdx>=2 && byteIdx<=5) msgrx.databuf[5-byteIdx] = data;
if (byteIdx>=6 && byteIdx<=9) msgrx.idbuf[9-byteIdx] = data;
//calculate checksum
if (byteIdx<frameLen) {
checksum+=data;
} else {
mode = MODE_WAITING_FOR_PREAMBLE;
if (checksum==data) appRxFuncHandler(&msgrx);
}
}
byteIdx++;
break;
}
}
}
uint32_t rs485eltako_createDimmerValue(uint8_t value) {
uint8_t val = ((uint16_t)value)*100/255;
if (val==0) return RS485ELTAKO_DIMMER_OFF;
return ((uint32_t) RS485ELTAKO_DIMMER_0 | ((uint32_t)val)<<16);
}
|
C | UTF-8 | 371 | 3 | 3 | [] | no_license |
/*Program name: ex06.c
student: 59160668 Nitichai Sawangsai
section:04
*/
#include<stdio.h>
int main (void)
{
int a,b;
printf("Please enter two integers:");
scanf("%d%d",&a,&b);
if (a <= b )
printf("%d < %d\n",a,b);
else
printf("%d > %d\n",a,b);
return 0;
} // aomza
|
C | UTF-8 | 3,925 | 2.8125 | 3 | [] | no_license | #include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <wait.h>
#include <stdio.h>
#include <glob.h>
#include <dirent.h>
#include <string.h>
int animalCount = 0, nameCount = 0, ageCount = 0;
char animals[55][20];
char names[55][20];
char ages[55][3];
int handleAnimal(char filename[], int j){
int charCount=0;
for(; j<strlen(filename)-4; j++){
if(filename[j] == ';'){
break;
}
animals[animalCount][charCount] = filename[j];
charCount++;
}
animalCount++;
return j;
}
int handleName(char filename[], int j){
int charCount=0;
for(j=j+1; j<strlen(filename)-4; j++){
if(filename[j] == ';'){
break;
}
names[nameCount][charCount] = filename[j];
charCount++;
}
nameCount++;
return j;
}
int handleAge(char filename[], int j){
int charCount=0;
for(j=j+1; j<strlen(filename)-4; j++){
if(filename[j] == '_'){
j++;
break;
}
ages[ageCount][charCount] = filename[j];
charCount++;
}
ageCount++;
return j;
}
int handleElse(char filename[], int j){
j = handleAnimal(filename, j);
j = handleName(filename, j);
j = handleAge(filename, j);
pid_t cid[10];
int stat[10];
char loc[100] = "modul2/petshop/";
char curloc[100] = "modul2/petshop/";
char animalName[50], animalName2[50], animalName3[50];
strcpy(animalName, animals[animalCount-1]);
strcpy(animalName2, animals[animalCount-1]);
strcpy(animalName3, animals[animalCount-1]);
strcat(loc, animalName);
strcat(curloc, filename);
cid[0] = fork();
if (cid[0] == 0) {
char *argv[4] = {"mkdir", "-p", loc, NULL};
execv("/bin/mkdir", argv);
}
while ((wait(&stat[0])) > 0);
char log[30]="";
FILE *fp;
strcat(log, "/home/solxius/modul2/petshop/");
strcat(log, animalName2);
strcat(log, "/keterangan.txt");
fp = fopen (log, "a");
fprintf(fp, "nama : %s\numur : %s\n\n", names[nameCount-1], ages[ageCount-1]);
fclose(fp);
char loca[100] = "modul2/petshop/";
strcat(loca, animalName3);
strcat(loca, "/");
strcat(loca, names[nameCount-1]);
strcat(loca, ".jpg");
if(j<strlen(filename)-4){
cid[1] = fork();
if (cid[1] == 0) {
char *argv[4] = {"cp", curloc, loca, NULL};
execv("/bin/cp", argv);
}
while ((wait(&stat[1])) > 0);
handleElse(filename, j);
}
else{
cid[1] = fork();
if (cid[1] == 0) {
char *argv[4] = {"mv", curloc, loca, NULL};
execv("/bin/mv", argv);
}
while ((wait(&stat[1])) > 0);
return j;
}
}
int main() {
pid_t child_id[10];
int status[10];
child_id[0] = fork();
if (child_id[0] == 0) {
char *argv[] = {"mkdir", "-p", "modul2/petshop", NULL};
execv("/bin/mkdir", argv);
}
while ((wait(&status[0])) > 0);
child_id[1] = fork();
if (child_id[1] == 0) {
char *argv[] = {"unzip", "/home/solxius/Downloads/pets.zip", "-d", "/home/solxius/modul2/petshop/", NULL};
execv("/bin/unzip", argv);
}
while ((wait(&status[1])) > 0);
child_id[2] = fork();
if (child_id[2] == 0) {
glob_t globbuf;
int err = glob("/home/solxius/modul2/petshop/*/", 0, NULL, &globbuf);
int numberofmatch = 3+(int) globbuf.gl_pathc;
char *argv[100] = {"rm", "-r"};
int count = 2;
for (int i = 0; globbuf.gl_pathv[i]; i++) {
argv[count] = globbuf.gl_pathv[i];
count++;
}
argv[count+1] = NULL;
execv("/bin/rm", argv);
}
while ((wait(&status[2])) > 0);
printf("parent\n");
struct dirent **namelist;
int n = scandir("/home/solxius/modul2/petshop/", &namelist, NULL, alphasort);
if (n == -1) {
perror("scandir");
exit(EXIT_FAILURE);
}
char filename[n][50];
for(int i=0; i<n; i++) {
strcpy(filename[i], namelist[i]->d_name);
free(namelist[i]);
}
free(namelist);
for(int i=2; i<n; i++){
int test = handleElse(filename[i], 0);
}
return 0;
}
|
C | UTF-8 | 2,245 | 2.65625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <setjmp.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include <math.h>
#include <semaphore.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/sendfile.h>
#include <dirent.h>
#include <time.h>
#define LISTENQ 1024 /* second argument to listen() */
typedef struct sockaddr SA;
typedef unsigned long long ull;
/* $end open_client_read_fd */
/*
* open_listenfd - open and return a listening socket on port
* Returns -1 and sets errno on Unix error.
*/
/* $begin open_listenfd */
int open_listenfd(int port){
int listenfd, optval = 1;
struct sockaddr_in serveraddr;
/* Create a socket descriptor */
if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
return -1;
/* Eliminates "Address already in use" error from bind. */
if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR,
(const void *)&optval , sizeof(int)) < 0)
return -1;
/* Listenfd will be an endpoint for all requests to port
on any IP address for this host */
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons((unsigned short)port);
if (bind(listenfd, (SA *)&serveraddr, sizeof(serveraddr)) < 0)
return -1;
/* Make it a listening socket ready to accept connection requests */
if (listen(listenfd, LISTENQ) < 0)
return -1;
return listenfd;
}
/* $end open_listenfd */
void unix_error(char *msg){/* unix-style error */
fprintf(stderr, "%s: %s\n", msg, strerror(errno));
exit(0);
}
int Select(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout){
int rc;
if ((rc = select(n, readfds, writefds, exceptfds, timeout)) < 0)
unix_error("Select error");
return rc;
}
int Accept(int s, struct sockaddr *addr, socklen_t *addrlen){
int rc;
if ((rc = accept(s, addr, addrlen)) < 0)
unix_error("Accept error");
return rc;
} |
C | UTF-8 | 2,014 | 2.984375 | 3 | [] | no_license | /*
* =====================================================================================
*
* Filename: synchronasition.c
*
* Description: fork fibonnacci
*
* Version: 1.0
* Created: 2011年09月12日 11时59分59秒
* Revision: none
* Compiler: gcc
*
* Author: XaoQin (), [email protected]
* Company: ZJU
*
* =====================================================================================
*/
#include<stdio.h>
#include<sys/shm.h>
#include<sys/stat.h>
#include<string.h>
#include<stdlib.h>
#define MAX_SEQUENCE 10
typedef struct{
long fib_sequence[MAX_SEQUENCE]; //max sequence
int sequcen_size;//length of fib
}shared_data;
//calc the 'a'th fib number
int fib(int a)
{
if ( a<0 ) {
printf( "error\n" );
return(0);
}
else if(a==0)
{
return(0);
}
else if (a>0&&a<=2 ) {
return 1;
}
else{
return(fib(a-1)+fib(a-2));
}
}
int
main( int argc, char **argv )
{
if(*argv[1]-'0'>=MAX_SEQUENCE) //test if the number is greater than 10
{
printf( "argv %d\n", *argv[1]-'0' );
printf( "in put a number less than 10\n" );
}
else
{
int segment_id;//the id for the shared memory segment
shared_data* shared_para=NULL;//a pointer to the shared memory segment
segment_id=shmget(IPC_PRIVATE, sizeof(shared_data), S_IRUSR|S_IWUSR);//allocate memory
shared_para=(shared_data*)shmat(segment_id, NULL, 0);//attach memory;
shared_para->sequcen_size=*argv[1]-'0';//the length of the fib
pid_t pid;
pid=fork();//fork a number
if(pid==0)
{//child
//fibonnacci(shared_para->sequcen_size);
int j;
for ( j = 0; j < shared_para->sequcen_size; j++ ) {
shared_para->fib_sequence[j]=fib(j);
}//calc the fib and write it to the shared memory
}
else if(pid>0)
{//father
wait(NULL);
int i;
for(i=0;i<shared_para->sequcen_size;i++)
{
printf( "%ld \n", shared_para->fib_sequence[i] );
}//write the fib to screen
shmdt(shared_para);//detach the shared memory segment
shmctl(segment_id, IPC_RMID, NULL); //remove the shared momory segment
}
}
return 0;
}
|
C | UTF-8 | 1,172 | 3.5 | 4 | [] | no_license | #include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Hello!\n");
// parse comand line arguments
printf("There are %d command line arguments.\n", argc);
printf("They are:\n");
int i;
for(i = 0; i < argc; i++) {
printf(" %d: %s\n", i, argv[i]);
}
float f = 0;
printf("f = %f\n", f);
f = 42.0;
printf("f = %f\n", f);
f = f /3.;
printf("f = %.10f\n", f);
double g;
g = 41.0 / 3.;
int A[10];
//fill A and print
for(i = 0; i < 10; i++) {
A[i] = i;
printf("A[%d] = %d\n", i, A[i]);
}
// variable-length array
int B[argc];
// fill B and print
for(i = 0; i < argc; i++) {
B[i] = i;
printf("B[%d) = %d\n", i, B[i]);
}
// dynamically allocated array
int *C; // telling c (language) that C (variable) is beg of seq ints
if(argc >1) {
int clen = atoi(argv[1]);
// allocate Cs memory
C = malloc(clen * sizeof(int));
// fill C and print
for(i = 0; i < clen; i++) {
C[i] = i;
printf("C[%d] = %d\n", i, C[i]);
}
free(C);
}
//read files
float a = 0.;
float b = 0.;
float c = 0.;
read("input", &a, &b, &c);
return EXIT_SUCCESS;
}
|
C | UTF-8 | 2,052 | 3.1875 | 3 | [] | no_license | /* See LICENSE file for copyright and license details. */
/* Global libraries */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
/* Local libraries */
#include "config.h"
#include "blocks.h"
/* Functions */
void signalhandler(int signum);
void pretty_print();
/* Basic signal handling */
void signalhandler(int signum)
{
/* Log signals to stderr */
fprintf(stderr, "Signal received: %d\n", signum);
/* playerctl needs a small delay to get current track */
if (signum == SIGUSR2)
usleep(100000);
}
/* Print in i3bar JSON format */
void pretty_print()
{
int i;
int n_arguments;
char *temperature = NULL;
char *battery = NULL;
char *volume = NULL;
char *music = NULL;
char *datetime = NULL;
char **arguments[] = { ARGUMENTS };
n_arguments = sizeof(arguments) / sizeof(arguments[1]);
/* First line needs to be empty */
printf("{\"version\":1}\n[[]\n");
/* Main loop */
while(1) {
/* Get new data */
temperature = get_temperature();
battery = get_battery();
volume = get_volume();
music = get_music();
datetime = get_datetime();
/* Print information */
printf(",[");
for (i = 0; i < n_arguments; ++i) {
printf("{\"full_text\": \" %s \",\"separator_block_width\":15}", *arguments[i]);
if (i < n_arguments-1)
printf(",");
}
printf("]\n");
fflush(stdout);
/* Free unneeded pointers */
free(temperature);
free(battery);
free(volume);
free(music);
free(datetime);
/* Wait for a specified duration unless a signal is received */
sleep(sleepduration);
}
}
/* Main funtion */
int main() {
/* Locale for date and time */
setlocale(LC_ALL, "");
/* Signal handlers for hotkeys */
signal(SIGUSR1, signalhandler);
signal(SIGUSR2, signalhandler);
pretty_print();
/* Exit successfully */
return EXIT_SUCCESS;
}
|
C | UTF-8 | 191 | 3.234375 | 3 | [] | no_license | #include <stdio.h>
int main()
{
int i = 520;
printf("before loop, i = %d\n", i );
for(int i = 0; i < 3; i++)
printf("i = %d\n", i);
printf("after loop, i = %d\n", i );
return 0;
}
|
C | UTF-8 | 556 | 3.03125 | 3 | [] | no_license | #include <cs50.h>
#include <stdio.h>
int main(void)
{
int height = 0;
do
{
height = get_int("Height:\n");
}
while (height < 1 || height > 8);
for (int row = 1; row <= height; row++)
{
for (int fs = 0; fs < height - row; fs++)
{
printf(" ");
}
for (int fh = 0; fh < row; fh++)
{
printf("#");
}
printf(" ");
for (int sh = 0; sh < row; sh++)
{
printf("#");
}
printf("\n");
}
}
|
C | UTF-8 | 277 | 2.8125 | 3 | [] | no_license | static int hashfs_unlink(const char *path)
{
char realpath[ PATH_MAX ];
int ret;
debug(1, "calling unlink %s", path);
if (mtor(path, realpath, sizeof(realpath)) < 0) {
ret = ENOMEM;
} else if ((ret = unlink(realpath)) < 0) {
ret = -errno;
}
return ret;
}
|
C | UTF-8 | 413 | 3.78125 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int *create_array(int n, int initial_value)
{
int *a;
a = malloc(n * sizeof(int));
if (!a)
return NULL;
for (int i = 0; i < n; i++)
a[i] = initial_value;
return a;
}
#define SIZE 923
int main(void)
{
int *A = create_array(SIZE, INT_MAX);
for (int i = 0; i < SIZE; i++)
printf("%d:%d\n", i, A[i]);
puts("");
return 0;
}
|
C | UTF-8 | 1,004 | 2.875 | 3 | [
"BSD-2-Clause-Views"
] | permissive | // 5 kyu
// Write your own printf #2
#include <stdarg.h>
#include <stdlib.h>
char *
mr_asprintf(const char *format, ...)
{
size_t size = 0x400;
char *str = malloc(size), nbuf[16], *nbufp;
size_t i = 0;
char *s;
int n;
va_list ap;
va_start(ap, format);
for (; *format != '\0'; format++) {
if (*format == '{') {
format++;
if (*format == '{') {
str[i] = *format;
i++;
} else if (*format == 's') {
s = va_arg(ap, char *);
for (; *s != '\0'; s++, i++)
str[i] = *s;
format++;
continue;
} else if (*format == 'i') {
nbufp = nbuf;
n = va_arg(ap, int);
if (n < 0) {
str[i] = '-';
i++;
n = abs(n);
} else if (n == 0) {
*nbufp = '0';
nbufp++;
};
for (; n != 0; n /= 10, nbufp++)
*nbufp = '0' + (n % 10);
for (nbufp--; nbufp >= nbuf; nbufp--, i++)
str[i] = *nbufp;
format++;
continue;
};
} else {
str[i] = *format;
};
i++;
};
va_end(ap);
str[i] = '\0';
return (&(str[0]));
}
|
C | GB18030 | 575 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <math.h>
#include <stdlib.h>
using namespace std;
int main()
{
cout << "-------֪ߣ-------" << endl;
int a, b, c;
double p, s;
cout <<"ֱε" << endl;
cin >> a >> b >> c;
if (a + b > c&&a - b < c)
{
p = (a + b + c) / 2;
s = sqrt(p*(p - a)*(p - b)*(p - c));
cout << "εs=" << s << endl;
}
else
cout << "βڣ" << endl;
getcgar();
getchar();
return 0;
system("pause");
} |
C | UTF-8 | 14,524 | 2.671875 | 3 | [] | no_license | #include "common.h"
#include "network.h"
#include "read_config.h"
#include "constants.h"
#include "thread_queue.h"
#include "cmd_queue.h"
// MACROS ------------------------------------------------------------------ //
#define USAGE "usage: ./peer_node <config_file> <server_ip> <server_port>"
#define CONFIG_FILE "peernode.cfg"
#define MAX_CLIENTS 10
// GLOBAL VARIABLES AND STRUCTS -------------------------------------------- //
pthread_t thread_pool[MAX_CLIENTS];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cv = PTHREAD_COND_INITIALIZER;
char logfile[MAX_WD_LEN];
char wd[MAX_WD_LEN];
// FUNCTION PROTOTYPES ----------------------------------------------------- //
void register_with_index(int, char *);
void client_to_uid(char *, int, char *);
void * thread_function(void *);
void * handle_connection(void *);
void write_to_log(char *);
void recv_list_files(int);
// ------------------------------------------------------------------------- //
// main() function
//
int main(int argc, char **argv) {
// Get parameters from config file.
char port_str[MAX_PORT_LEN];
pid_t pid;
if (argc != 4) {
printf("%s\n", USAGE);
exit(1);
}
read_config(argv[1], NULL, port_str, wd, logfile);
//printf("log file: %s\n", logfile);
// Clear out the log file.
FILE *lp;
if ((lp = fopen(logfile, "w")) == NULL) {
perror("fopen");
}
fclose(lp);
// Change the directory.
chdir(wd);
// Initialize the node as a client of the indexing server.
int index_socket;
if ((index_socket = init_client(argv[2], argv[3])) == -1) {
exit(1);
}
printf("client: connected to %d\n", index_socket);
// SERVER SECTION ------------------------------------------------------ //
if ((pid = fork()) == 0) {
int listener_socket, client_socket;
printf(" Initializing server. Listening on port %s\n", port_str);
listener_socket = init_server(port_str);
for (int i = 0; i < MAX_CLIENTS; i++) {
pthread_create(&thread_pool[i], NULL, thread_function, NULL);
}
while (1) {
//printf("Server: waiting for connection...\n");
client_socket = accept(listener_socket, NULL, NULL);
// Get the client's info.
struct sockaddr_in addr;
socklen_t addr_len = sizeof addr;
getpeername(client_socket, (struct sockaddr *)&addr, &addr_len);
char *client_ip = inet_ntoa(addr.sin_addr);
int client_port = ntohs(addr.sin_port);
printf(" Received connection from %s:%d\n", client_ip, client_port);
int *pclient = malloc(sizeof (int));
*pclient = client_socket;
pthread_mutex_lock(&mutex);
thread_enqueue(pclient);
pthread_cond_signal(&cv);
pthread_mutex_unlock(&mutex);
}
return 0;
}
register_with_index(index_socket, port_str);
// CLIENT SECTION ------------------------------------------------------ //
struct timeval start, end;
double exec_time;
int stat, len;
char full_cmd[MAX_CMD_LEN];
while (1) {
// Get user input.
printf("> ");
fgets(full_cmd, MAX_CMD_LEN, stdin);
if (full_cmd[0] == '\0') return 1;
if (full_cmd[0] == '\n') continue;
trimnl(full_cmd);
flush_cmd_queue();
cmd_queue_from_string(full_cmd);
// Get the command part of the command
char cmd_1[MAX_CMD_LEN];
cmd_dequeue(cmd_1);
if (strncmp(cmd_1, "list", MAX_CMD_LEN) != 0 &&
strncmp(cmd_1, "download", MAX_CMD_LEN) != 0 &&
strncmp(cmd_1, "quit", MAX_CMD_LEN) != 0) {
continue;
}
// handle list command --------------------------------------------- //
if (strncmp(cmd_1, "list", MAX_CMD_LEN) == 0) {
// Start the timer.
exec_time = 0;
gettimeofday(&start, NULL);
// Send the command.
send_stat(index_socket, OK);
send_len(index_socket, MAX_CMD_LEN);
send_msg(index_socket, cmd_1, MAX_CMD_LEN);
// Receive the number of files.
recv_stat(index_socket, &stat);
recv_len(index_socket, &len);
char *num_files_str = malloc(len);
recv_msg(index_socket, num_files_str, len);
int num_files = atoi(num_files_str);
free(num_files_str);
// Then receive each filename.
printf("FILE LIST\n============\n");
for (int i = 0; i < num_files; i++) {
recv_stat(index_socket, &stat);
recv_len(index_socket, &len);
char *filename = malloc(len);
recv_msg(index_socket, filename, len);
printf("%s\n", filename);
free(filename);
}
printf("============\n");
// Stop the timer an calculate the request time.
gettimeofday(&end, NULL);
exec_time = (double) (end.tv_sec - start.tv_sec)
+ (double) (end.tv_usec - start.tv_usec) / 1000000;
// Log the time.
chdir("../../");
FILE *fp;
if ((fp = fopen(logfile, "a")) == NULL) {
perror("fopen");
} else {
fprintf(fp, "Client: received file list - %lf ms\n", exec_time);
fclose(fp);
}
printf(" Client: received file list - %lf ms\n", exec_time);
chdir(wd);
}
// handle download command ----------------------------------------- //
if (strncmp(cmd_1, "download", MAX_CMD_LEN) == 0) {
// Start the timer.
exec_time = 0;
gettimeofday(&start, NULL);
// Send the command.
send_stat(index_socket, OK);
send_len(index_socket, MAX_CMD_LEN);
send_msg(index_socket, cmd_1, MAX_CMD_LEN);
// Dequeue the filename.
char filename[MAX_FN_LEN];
cmd_dequeue(filename);
// Send the filename to the indexing server.
send_stat(index_socket, OK);
send_stat(index_socket, MAX_FN_LEN);
send_msg(index_socket, filename, MAX_FN_LEN);
printf(" Client: sent filename\n");
// Receive the IP address and port of the the host server.
recv_stat(index_socket, &stat);
recv_len(index_socket, &len);
char *host_ip = malloc(len);
recv_msg(index_socket, host_ip, len);
recv_stat(index_socket, &stat);
recv_len(index_socket, &len);
char *host_port = malloc(len);
recv_msg(index_socket, host_port, len);
printf(" Client: received host ip %s and port %s\n", host_ip, host_port);
// Then connect to that host.
printf(" Client: connecting to %s:%s\n", host_ip, host_port);
int host_socket;
if ((host_socket = init_client(host_ip, host_port)) == -1) {
//kill(pid, SIGKILL);
exit(1);
}
// Send the filename.
send_stat(host_socket, OK);
send_len(host_socket, MAX_FN_LEN);
send_msg(host_socket, filename, MAX_FN_LEN);
// Then receive the file into a buffer.
recv_stat(host_socket, &stat);
recv_len(host_socket, &len);
char *f_buf = malloc(len);
recv_msg(host_socket, f_buf, len);
// And write it into a file.
FILE *fp = fopen(filename, "w");
fwrite(f_buf, len, 1, fp);
fclose(fp);
// Let the indexing server know that the file was received.
send_stat(index_socket, OK);
// Stop the timer an calculate the request time.
gettimeofday(&end, NULL);
exec_time = (double) (end.tv_sec - start.tv_sec)
+ (double) (end.tv_usec - start.tv_usec) / 1000000;
printf("Client: Sucessfully downloaded %s\n", filename);
// Log the time.
chdir("../../");
FILE *lp;
if ((lp = fopen(logfile, "a")) == NULL) {
perror("fopen");
} else {
fprintf(lp, "Client: received file %s - %lf ms\n", filename, exec_time);
fclose(lp);
}
chdir(wd);
free(f_buf);
free(host_ip);
free(host_port);
}
// Handle quit command --------------------------------------------- //
if (strncmp(cmd_1, "quit", MAX_CMD_LEN) == 0) {
// Let the indexing server know we are quiting, then kill the
// the server process of this program.
send_stat(index_socket, OK);
send_len(index_socket, MAX_CMD_LEN);
send_msg(index_socket, cmd_1, MAX_CMD_LEN);
close(index_socket);
//kill(pid, SIGKILL);
return 0;
}
}
close(index_socket);
return 0;
}
// ------------------------------------------------------------------------- //
void register_with_index(int index_socket, char *port) {
// First, send the port the client will be listening on as a server.
send_stat(index_socket, OK); //
send_len(index_socket, MAX_PORT_LEN); //
send_msg(index_socket, port, MAX_PORT_LEN); // ------------------- SEND A
// Then call `ls' and read the results into a buffer.
FILE *ls = popen("ls", "r");
char buf[4096];
memset(buf, 0, 4096);
fread(buf, 4096, 1, ls);
// Determine the number of files.
int l = strnlen(buf, 4096);
int num_files = 0;
for (int i = 0; i < l; i++) {
if (buf[i] == '\n') {
num_files++;
}
}
// Then we send the number of files to the server.
char num_files_str[12];
sprintf(num_files_str, "%d", num_files);
send_stat(index_socket, OK); //
send_len(index_socket, 12); //
send_msg(index_socket, num_files_str, 12); // -------------------- SEND B
// Now that the server knows how many `packets' to expect, we send the
// filenames one at a time.
char *token;
token = strtok(buf, "\n");
while (token != NULL) {
send_stat(index_socket, OK); //
send_len(index_socket, MAX_FN_LEN); //
send_msg(index_socket, token, MAX_FN_LEN); // ---------------- SEND C
token = strtok(NULL, "\n");
}
}
// ------------------------------------------------------------------------- //
void * thread_function(void *arg) {
while (1) {
int *pclient;
pthread_mutex_lock(&mutex);
if ((pclient = thread_dequeue()) == NULL) {
pthread_cond_wait(&cv, &mutex);
pclient = thread_dequeue();
}
pthread_mutex_unlock(&mutex);
if (pclient != NULL) {
handle_connection(pclient);
}
}
return NULL;
}
// ------------------------------------------------------------------------- //
void * handle_connection(void *pclient) {
int client_socket = *(int *)pclient;
int stat, len;
free(pclient);
// Receive the filename to be sent to the client.
recv_stat(client_socket, &stat);
recv_len(client_socket, &len);
char *filename = malloc(len);
recv_msg(client_socket, filename, len);
// Open the requested file and find the file size.
FILE *fp = fopen(filename, "r");
fseek(fp, 0L, SEEK_END);
int f_size = ftell(fp);
rewind(fp);
// Read the file into a buffer.
char *f_buf = malloc(f_size);
fread(f_buf, f_size, 1, fp);
fclose(fp);
// Then send the buffer to the client.
send_stat(client_socket, OK);
send_len(client_socket, f_size);
send_msg(client_socket, f_buf, f_size);
free(f_buf);
// Get the client's info.
//struct sockaddr_in addr;
//socklen_t addr_len = sizeof addr;
//getpeername(client_socket, (struct sockaddr *)&addr, &addr_len);
//char *client_ip = inet_ntoa(addr.sin_addr);
//int client_port = ntohs(addr.sin_port);
//char *logmsg = NULL;
//sprintf(logmsg, "Server: Received download request for %s from %s:%d",
// filename, client_ip, client_port);
//write_to_log(logmsg);
return NULL;
}
// ------------------------------------------------------------------------- //
void write_to_log(char *str) {
pthread_mutex_lock(&mutex);
FILE *fp = fopen(logfile, "a");
fprintf(stdout, "%s\n", str);
fclose(fp);
pthread_mutex_unlock(&mutex);
}
void recv_list_files(int index_socket) {
}
/*
// ------------------------------------------------------------------------- //
// register_with_index() function
//
void register_with_index(int index_socket, char *port_str) {
// The first thing we need to after connecting to the indexing server is
// to send it the list of files in the watched directory.
//char port_str[MAX_PORT_LEN];
//sprintf(port_str, "%d", port);
send_packet(index_socket, OK, 12, port_str);
// We start by calling `ls' and reading the results into a buffer.
FILE *ls = popen("ls", "r");
char buf[4096];
memset(buf, 0, 4096);
fread(buf, 4096, 1, ls);
// Then we determine the number of files.
int l = strnlen(buf, 4096);
int n = 0;
for (int i = 0; i < l; i++) {
if (buf[i] == '\n') {
n++;
}
}
// Then we send the number of files to the server.
char num_files[12];
sprintf(num_files, "%d", n);
send_packet(index_socket, OK, 12, num_files);
// Now that the server knows how many `packets' to expect, we send the
// filenames one at a time.
char *token;
token = strtok(buf, "\n");
while (token != NULL) {
printf("Sending %s\n", token);
send_packet(index_socket, OK, MAX_FN_LEN, token);
token = strtok(NULL, "\n");
}
}
// ------------------------------------------------------------------------- //
// client_to_uid() function
//
void client_to_uid(char *ip, int port, char *uid) {
char port_str[12];
char *delim = ":";
sprintf(port_str, "%d", port);
strncpy(uid, ip, MAX_IP_LEN);
strncat(uid, delim, 1);
strncat(uid, port_str, 12);
}
*/
|
C | UTF-8 | 2,042 | 3.859375 | 4 | [] | no_license | #include <stdio.h>
#include <malloc.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <time.h>
typedef int buffer_item;
#define PROD_SLEEP 1
#define CONS_SLEEP 1
#define BUFFER_SIZE 5
#define MAX_PROD 20
#define MAX_CONS 20
buffer_item buffer[BUFFER_SIZE];
unsigned int buff_idx;
int insert_item(buffer_item item) {
if (buff_idx == BUFFER_SIZE) {
/* what happens if space is not available? */
return -1;
}
/* insert an item into buffer */
buffer[buff_idx] = item;
buff_idx++;
return 0;
}
int remove_item(buffer_item *item) {
if (buff_idx == 0) {
/* what happens if the buffer is empty */
return -1;
}
/* remove an item from the buffer */
*item = buffer[buff_idx - 1];
buff_idx--;
return 0;
}
void * producer(void * param) {
buffer_item item;
while (1) {
/* sleep a random time period */
//sleep(PROD_SLEEP);
/* generate a random item */
item = rand();
if (insert_item(item) == -1) {
fprintf(stderr,"buffer is full, cannot write\n");
} else {
printf("Producer produced %d\n",item);
}
}
}
void * consumer(void * param) {
buffer_item item;
while (1) {
/* sleep a random time period */
//sleep(CONS_SLEEP);
/* generate a random item */
if (remove_item(&item) == -1) {
fprintf(stderr,"buffer is empty, cannot read\n");
} else {
printf("Consumer consumed %d\n",item);
}
}
}
int main(int argc, char * argv[]) {
int i;
pthread_t prod_tid[MAX_PROD];
pthread_t cons_tid[MAX_CONS];
/* 1. get cmd line arguments */
long int num_sec = atoi(argv[1]);
long int num_prod = atoi(argv[2]);
long int num_cons = atoi(argv[3]);
buff_idx = 0;
/* 2. Initialize buffer */
memset((void*)buffer, 0, BUFFER_SIZE*sizeof(buffer_item));
/* 3. Create producer threads */
for (i = 0; i < num_prod; i++) {
pthread_create(&prod_tid[i], NULL, producer, NULL);
}
/* 4. Create consumer threads */
for (i = 0; i < num_cons; i++) {
pthread_create(&cons_tid[i], NULL, consumer, NULL);
}
/* 5. Sleep */
sleep(num_sec);
/* 6. Exit */
return 0;
} |
C | UTF-8 | 2,554 | 2.875 | 3 | [] | no_license | //
// utils.c
// server
//
// Created by anton on 03.10.2018.
// Copyright © 2018 anton. All rights reserved.
//
#include "utils.h"
#include <stdio.h>
char* getParamTwoString(char* message, int all)
{
int index1 = 0;
int index2 = 0;
for (int i=0; i < strlen(message); i++)
{
if(all==0)
{
if(index1==0&&message[i]==' ')
{
index1 = i+1;
continue;
}
if((index1!=0&&message[i]==' ')||i==strlen(message)-1)
{
index2 = i;
break;
}
}
else
{
if(message[i]==' ')
{
index1 = i+1;
index2 = strlen(message)-1;
break;
}
}
}
if(index1!=0&&index2!=0)
{
char* str = malloc(sizeof(char)*(index2-index1+1));
for (int k = index1; k<index2;k++)
{
str[k-index1] = message[k];
}
str[index2-index1] = 0;
return str;
}
return NULL;
}
char* getParamThreeString(char* message)
{
int index1 = 0;
int index2 = 0;
int qnt=0;
for (int i=0; i<strlen(message); i++)
{
if(message[i]==' ')
{
qnt++;
}
if(message[i]==' '&& qnt>1)
{
index1 = i+1;
index2 = strlen(message)-1;
break;
}
}
if(index1!=0&&index2!=0)
{
char* str = malloc(sizeof(char)*(index2-index1+1));
for (int k = index1; k < index2; k++)
{
str[k-index1] = message[k];
}
str[index2-index1]=0;
return str;
}
return NULL;
}
char* createString(int length)
{
char* result = malloc(sizeof(typeof (char))*length);
memset(result, 0, sizeof(typeof (char))*length);
return result;
}
char* createStringCopy(char* src)
{
char* result = malloc(sizeof(typeof (char))*strlen(src));
strcpy(result, src);
return result;
}
enum CommandType getCommandType(char* Message)
{
if(strncmp(Message, "who",3)==0){
return WHO;
}
else if(strncmp(Message, "wall", 4)==0){
return WALL;
}
else if(strncmp(Message, "say", 3)==0){
return SAY;
}
else if(strncmp(Message, "kill", 4)==0){
return KILL;
}
else if(strncmp(Message, "heal", 4)==0){
return HEAL;
}
else{
return UNKNOWN;
}
}
|
C | UTF-8 | 194 | 3.234375 | 3 | [] | no_license | #include <stdio.h>
int main() {
int tabela[] = {1, 2, 4, 6, 12};
int n = sizeof(tabela) / sizeof(int);
for (int i = n-1; i >= 1; i--) {
printf("%d ",tabela[i]);
return 0;
}
}
|
C | UTF-8 | 1,365 | 3.515625 | 4 | [] | no_license | #include "variadic_functions.h"
#include <stdio.h>
#include <stdarg.h>
/**
* print_all - function that prints anything.
* @format: list of arguments.
* Return: Always 0.
*/
void print_all(const char * const format, ...)
{
check array[] = {
{"c", c_char},
{"i", c_int},
{"f", c_float},
{"s", c_string},
{NULL, NULL},
};
int i1, i;
char *coma = "";
va_list list;
va_start(list, format);
i = 0;
while (format && format[i])
{
i1 = 0;
while (array[i1].check != NULL)
{
if (format[i] == *array[i1].check)
{
printf("%s", coma);
array[i1].f(list);
coma = ", ";
break;
}
i1++;
}
i++;
}
printf("\n");
va_end(list);
}
/**
* c_char - list of strings.
* @list: list of arguments.
* Return: Always 0.
*/
void c_char(va_list list)
{
printf("%c", va_arg(list, int));
}
/**
* c_int - list of strings.
* @list: list of arguments.
* Return: Always 0.
*/
void c_int(va_list list)
{
printf("%i", va_arg(list, int));
}
/**
* c_float - list of strings.
* @list: list of arguments.
* Return: Always 0.
*/
void c_float(va_list list)
{
printf("%f", va_arg(list, double));
}
/**
* c_string - list of strings.
* @list: list of arguments.
* Return: Always 0.
*/
void c_string(va_list list)
{
char *k;
k = va_arg(list, char *);
if (k == NULL)
{
printf("(nil)");
}
else
{
printf("%s", k);
}
}
|
C | UTF-8 | 4,663 | 2.625 | 3 | [] | no_license | #include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
//#define PORT 3006
//#define BACKALOG 2
void serverArchivos(int id){
char buffer[100];
DIR *folder;
struct dirent *archivo;
folder=opendir("Server");
if (folder == NULL) printf("No puedo abrir el directorio");
else{
while ((archivo = readdir(folder))){
if ((strcmp(archivo->d_name,".")!=0)&&(strcmp(archivo->d_name,"..")!=0)){
bzero(buffer,100);
strcpy(buffer,archivo->d_name);
send(id,buffer,100,0);
}
}
bzero(buffer,100);
strcpy(buffer,"0");
send(id,buffer,100,0);
}
}
void chatRoom(int new_id, int new_id2){
char buffer1 [100];
char buffer2 [100];
send (new_id, "Ingrese su nombre: ",100,0);
send (new_id2, "Ingrese su nombre: ",100,0);
//LEE NOMBRES
recv (new_id, buffer1, 100, 0);
recv (new_id2, buffer2, 100, 0);
//ENVIA NOMBRES
send (new_id, buffer2,100,0);
send (new_id2, buffer1,100,0);
//EMPIEZA EL CHAT
do{
bzero(buffer1,100);
bzero(buffer2,100);
recv (new_id, buffer1, 100,0);
send (new_id2, buffer1, 100,0);
recv (new_id2, buffer2, 100, 0);
send (new_id, buffer2,100,0);
}while((strcmp(buffer1,"EXIT\n")!=0)||(strcmp(buffer2,"EXIT\n")!=0));
}
void subirArchivo(int id){
char archivo[100];
char buffer[100];
char buffer2[100];
bzero(buffer,100);
bzero(buffer2,100);
bzero(archivo,100);
int recibido=1;
FILE *f1;
recv(id, buffer, 100, 0);
strcat(archivo,"Server/");
strcat(archivo,buffer);
bzero(buffer,100);
f1 = fopen (archivo, "wb");
recv(id, buffer2, 1, 0);
while(strcmp(buffer2,"0")!=0){
recv(id, buffer, 1, 0);
fwrite(buffer,sizeof(char),1,f1);
recv(id, buffer2, 1, 0);
}
fclose(f1);
}
void descargarArchivo(int id){
char archivo[100];
char buffer[100];
char buffer2[100];
bzero(buffer,100);
bzero(buffer2,100);
bzero(archivo,100);
int recibido=1;
FILE *f1;
serverArchivos(id);
recv(id, buffer, 100, 0);
strcat(archivo,"Server/");
strcat(archivo,buffer);
printf("%s\n",archivo);
sleep(1);
f1 = fopen (archivo, "rb");
while(!feof(f1)){
send(id,"1",1,0);
bzero(buffer,100);
fread(buffer,sizeof(char),1,f1);
send(id,buffer,1,0);
}
send(id,"0",1,0);
fclose(f1);
}
int main (int argc, char *argv[]){
int id, opt, opt2, new_id, new_id2; //descriptores servidor, cliente
int tam1,tam2,PORT;
char buffer1 [100];
char buffer2 [100];
char opcion [10], opcion2 [10];
if(argc != 2){
printf("cantidad de parametros invalido \n");
return 1;
}
PORT=atoi(argv[1]);
struct sockaddr_in server; //inf servidor
struct sockaddr_in cliente1; //inf cliente1
struct sockaddr_in cliente2; //inf cliente2
//estructura server del SERVIDOR
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(PORT); //el puerto que usare
bzero(&(server.sin_zero),8);
//socket del servidor
if((id=socket(AF_INET , SOCK_STREAM, 0))<0){
printf("\nError no se pudo crear el socket \n");
return 1;
}
if(bind (id, (void *) &server, sizeof (server))<0){ //aqui esta la estructura para decir donde voy a funcionar
printf("Error al asociar el puerto a la conexion\n");
close(id);
return 1;
}listen (id, 2);//comienzo a escuchar
while(1){
//ACEPTA PRIMER CLIENTE
tam1=sizeof(struct sockaddr_in);
new_id = accept(id,(void *) &cliente1, &tam1); //si llega algo lo acepto
if(new_id<0){
printf("Error al aceptar trafico\n");
close(new_id);
return 1;
}
printf("Se obtuvo conexion desde %s\n",inet_ntoa (cliente1.sin_addr));
//ACEPTA SEGUNDO CLIENTE
tam2=sizeof(struct sockaddr_in);
new_id2 = accept(id,(void *) &cliente2, &tam2); //si llega algo lo acepto
if(new_id2<0){
printf("Error al aceptar trafico\n");
close(new_id2);
return 1;
}
printf("Se obtuvo conexion desde %s\n",inet_ntoa (cliente2.sin_addr));
recv(new_id, opcion,1,0);
opt=atoi(opcion);
printf("%i\n",opt);
switch(opt){
case 1: chatRoom(new_id, new_id2);
break;
case 2: subirArchivo(new_id);
break;
case 3: descargarArchivo(new_id);
break;
case 5: serverArchivos(new_id);
break;
default: printf("opt invalido\n");
}
recv(new_id2, opcion2,1,0);
opt2=atoi(opcion2);
printf("%i\n",opt2);
switch(opt2){
case 1:
break;
case 2: subirArchivo(new_id2);
break;
case 3: descargarArchivo(new_id2);
break;
case 5: serverArchivos(new_id2);
break;
default: printf("opt invalido\n");
}
close(new_id);
close(new_id2);
}
close(id);
return 0;
} |
C | UTF-8 | 2,843 | 2.625 | 3 | [] | no_license | #include <stdio.h>
#include <math.h>
#include <gsl/gsl_vector.h>
#include <assert.h>
#include <stdlib.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_interp.h>
int binsearch(gsl_vector* x, double z){
/* locates the interval for z by bisection */
int n = (*x).size;
assert(gsl_vector_get(x,0)<=z && z<=gsl_vector_get(x,n-2));
int i=0, j=n-1;
while(j-i>1){
int mid=(i+j)/2;
if(z>gsl_vector_get(x,mid)) i=mid; else j=mid;
}
return i;
}
//Linear spline functions (interpolation, integration=
double linterp(gsl_vector* x, gsl_vector* y, double z){
int i = binsearch(x, z);
double a = (gsl_vector_get(y,i+1)-gsl_vector_get(y,i))/
(gsl_vector_get(x,i+1)-gsl_vector_get(x,i));
double fz = a*(z-gsl_vector_get(x,i))+gsl_vector_get(y,i);
return fz;
}
double linterp_integ(gsl_vector* x, gsl_vector* y, double z){
int i = binsearch(x, z);
double intfz = 0.;
for(int j=0; j<i; j++){
double xj = gsl_vector_get(x,j), xjj = gsl_vector_get(x,j+1);
double yj = gsl_vector_get(y,j), yjj = gsl_vector_get(y,j+1);
double a = (yjj-yj)/(xjj-xj);
intfz += 0.5*a*(xjj*xjj-xj*xj)+(yj-a*xj)*(xjj-xj);
}
double xi = gsl_vector_get(x,i), xii = gsl_vector_get(x,i+1);
double yi = gsl_vector_get(y,i), yii = gsl_vector_get(y,i+1);
double a = (yii-yi)/(xii-xi);
intfz += 0.5*a*(z*z-xi*xi)-a*xi*(z-xi)+yi*(z-xi);
return intfz;
}
int main(){
FILE* xandy = fopen("out.xy.txt","w");
FILE* out10 = fopen("out.10.txt","w");
FILE* out100 = fopen("out.100.txt","w");
FILE* out500 = fopen("out.500.txt","w");
double xmax = 5;
FILE* files[]={out10, out100, out500};
double Ns[]={10, 100, 500};
for(int n = 0; n<3; n++){
double stepsize = xmax/(double)Ns[n];
gsl_vector* x = gsl_vector_alloc(Ns[n]);
gsl_vector* y = gsl_vector_alloc(Ns[n]);
double xa[(int)Ns[n]];
double ya[(int)Ns[n]];
for(int i=0; i<Ns[n]; i++){
gsl_vector_set(x,i,stepsize*i);
gsl_vector_set(y,i,(sin(stepsize*i)));
xa[i] = stepsize*i;
ya[i] = sin(stepsize*i);
}
gsl_interp *intel = gsl_interp_alloc(gsl_interp_linear,(int)Ns[n]);
gsl_interp_init(intel, xa, ya, (int) Ns[n]);
gsl_interp_accel *accel = gsl_interp_accel_alloc();
int count=0;
while(count<100){
count+=1;
double z = (double)rand()/(double) RAND_MAX*
gsl_vector_get(x,Ns[n]-2);
double interz = linterp(x,y,z);
double integralz = linterp_integ(x, y, z);
double gsl_interz = gsl_interp_eval(intel,xa,ya,z,accel);
double gsl_ing = gsl_interp_eval_integ(intel,xa,ya,xa[0]
,z,accel);
fprintf(files[n],"%g %g %g %g %g\n", z,
interz, -integralz+1, gsl_interz, -gsl_ing+1);
}
gsl_interp_free(intel);
gsl_vector_free(x);
gsl_vector_free(y);
}
for(int i=0; i<=200;i++){
fprintf(xandy, "%g %g %g\n",(double)i*xmax/200.,
sin((double)i*xmax/200.),cos((double) i*xmax/200.));
}
return 0;
}
|
C | UTF-8 | 1,307 | 3.578125 | 4 | [] | no_license | #include <stdio.h>
int ascii_to_text(int argc, char **argv);
int generate_keys (int argc, char **argv);
int text_to_ascii(int argc, char **argv);
int encrypt(int argc, char **argv);
int decrypt(int argc, char **argv);
int modular_exponentiation(char a[], char b[], char m[], char r[]);
int main (int argc, char **argv)
{
int mode=-1;
while(mode!=0)
{
printf("\n********************\n");
printf("\ntext_ascii\n");
printf("\nSelect mode:\n");
printf("1: Convert text to ascii\n");
printf("2: Convert ascii to text\n");
printf("3: Generate keys\n");
printf("4: Encrypt message\n");
printf("5: Decrypt message\n");
printf("0: Exit\n");
scanf("%d", &mode);
switch (mode)
{
case 1:
printf("\nConvert text to ascii\n");
text_to_ascii(argc, argv);
break;
case 2:
printf("\nConvert ascii to text\n");
ascii_to_text(argc, argv);
break;
case 3:
printf("\nGenerate keys\n");
generate_keys(argc, argv);
break;
case 4:
printf("\nEncrypt message\n");
encrypt(argc, argv);
break;
case 5:
printf("\nDecrypt message\n");
decrypt(argc, argv);
break;
case 0:
return 0;
break;
default:
printf("\nInvalid input. Try again\n");
return 1;
}
}
return 0;
}
|
C | UTF-8 | 459 | 2.9375 | 3 | [] | no_license | #include "../mem.h"
#include <stdlib.h>
#define MEM_SIZE 4096
/*
This tests whether worst fit is actually used, but this just has a hole somewhere (a pointer that doesn't get freed)
*/
int main(){
Mem_Init(MEM_SIZE);
void * ptr1 = Mem_Alloc(3000);
void * ptr2 = Mem_Alloc(50);
Mem_Free(ptr1, 0);
void * ptr3 = Mem_Alloc(2000);
Mem_Free(ptr3,0);
Mem_Dump();
void * ptr4 = Mem_Alloc(1000);
Mem_Dump();
exit(EXIT_SUCCESS);
}
|
C | UTF-8 | 2,106 | 3.171875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
typedef struct {
int inicio, fim, tamanho;
int itens[10000];
}Fila;
void criaFila( Fila *f){
f->inicio = 0;
f->fim = 0;
f->tamanho = 0;
int i;
for(i = 0 ; i < 5001 ; i++) f->itens[i] = 0;
}
int vazia(Fila *f){
return (f->tamanho == 0)? 1:0;
}
int cheia(Fila *f){
if (f->tamanho == 5000) return 1;
return 0;
}
int tamanho(Fila *f){
return f->tamanho;
}
int coloca(Fila *f, int elem){
if( cheia(f) == 0 ){
f->itens[f->fim] = elem;
f->fim++;
f->tamanho++;
return 1;
}
return -1;
}
int retira(Fila *f){
if( vazia(f) == 0 ){
int r;
f->tamanho--;
r = f->itens[f->inicio];
f->inicio++;
return r;
}
return -1;
}
void bfs(int grafo[][50], int numVertices, int raiz, int *cidAlcancadas, int maxPedagio){
int visitados[50] = {0};
int aux, i, j=0, auxMP;
Fila fila;
criaFila(&fila);
visitados[raiz] = 1;
coloca(&fila, raiz);
while( maxPedagio >= 0 ){
aux = retira(&fila);
for(i = 0; i < numVertices; i++){
if(grafo[aux][i] ==1 && !visitados[i]){
visitados[i] = 1;
coloca(&fila, i);
cidAlcancadas[j] = i+1;
j++;
}
}
maxPedagio--; //"numero de pulos"
}
}
int cmpfunc (const void * a, const void * b){
return ( *(int*)a - *(int*)b );
}
int main(void){
int cidades, estradas, cidAtual, maxPedagios;
int i, j, k, n = 1;
int x, y;
while( scanf("%d %d %d %d", &cidades, &estradas, &cidAtual, &maxPedagios) && cidades && estradas && cidAtual && maxPedagios ){
int grafo[50][50] = {0};
int cidAlcancadas[50] = {0};
int numCidadesAlcandas = 0;
for( i = 0 ; i < estradas; i++){
scanf("%d %d", &j, &k);
grafo[j-1][k-1] = 1;
grafo[k-1][j-1] = 1;
}
bfs(grafo,cidades,cidAtual-1, cidAlcancadas, maxPedagios);
for( numCidadesAlcandas = 0; cidAlcancadas[i] != 0; numCidadesAlcandas++); //contar qts cidades alcancadas tem
printf("Teste %d\n",n );
qsort(cidAlcancadas, numCidadesAlcandas, sizeof(int), cmpfunc);
for( j = 0; j < numCidadesAlcandas ; j++){
printf("%d", cidAlcancadas[j]);
(j+1 == i)? printf("\n\n"): printf(" ");
}
n++;
}
return 0;
} |
C | GB18030 | 273 | 2.765625 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<time.h>
main()
{
int i;
printf("%d ",randnum(1,10));
printf("%d ",randnum(1,10));
}
int randnum(int h,int t)//h~t֮
{
int n;
srand((unsigned)time(NULL));
n=rand()%26;
printf("%d",n);
return n;
}
|
C | GB18030 | 1,198 | 3.078125 | 3 | [] | no_license | #include "delay.h"
/*
*
ע⣺мIJu32 iܳ1800붨ʱһӣͨforѭdelay_ms100060Σʹdelay_ms60000Ȼͳˡ
*/
void delay_us(u32 i)
{
u32 temp;
SysTick->LOAD=9*i; //װֵ, 72MHZʱ
SysTick->CTRL=0X01; //ʹܣⲿʱԴ
SysTick->VAL=0; //
do
{
temp=SysTick->CTRL; //ȡǰֵ
}
while((temp&0x01)&&(!(temp&(1<<16)))); //ȴʱ䵽
SysTick->CTRL=0; //رռ
SysTick->VAL=0; //ռ
}
void delay_ms(u32 i)
{
u32 temp;
SysTick->LOAD=9000*i; //װֵ, 72MHZʱ
SysTick->CTRL=0X01; //ʹܣⲿʱԴ
SysTick->VAL=0; //
do
{
temp=SysTick->CTRL; //ȡǰֵ
}
while((temp&0x01)&&(!(temp&(1<<16)))); //ȴʱ䵽
SysTick->CTRL=0; //رռ
SysTick->VAL=0; //ռ
}
|
C | UTF-8 | 1,437 | 2.96875 | 3 | [] | no_license | #pragma once
#include "glm.h"
struct Camera {
glm::mat4 perspectiveMatrix;
glm::mat4 lookAtMatrix;
glm::mat4 viewMatrix;
glm::mat4 normalMatrix;
glm::vec3 position;
glm::vec3 direction;
glm::vec3 upVector;
glm::vec3 lookAtVector;
glm::vec3 rightVector;
float cameraAngle; //< Horizontal field of view angle in degrees
float nearPlane; //< near clipping plane distance
float farPlane; //< far clipping plane distance
float planeDistance; //<Distance of projection plane from camera position
float aspectRatio; //< Width to height ratio
inline void calculatePlaneDistance() {
planeDistance = 1.0f/tanf(glm::radians(cameraAngle) / 2.0f);
}
inline void calculateDirection() {
direction = glm::normalize(lookAtVector - position);
}
inline void calculateLookAtVector() {
lookAtVector = position + lookAtVector;
}
inline void calculateRightVector() {
rightVector = glm::normalize(glm::cross(direction, upVector));
}
inline void calculateUpVector() {
upVector = glm::normalize(glm::cross(rightVector, direction));
}
inline void calculatePerspectiveMatrix() {
perspectiveMatrix = glm::perspective(cameraAngle, aspectRatio, nearPlane, farPlane);
}
inline void calculateViewMatrices() {
lookAtMatrix = glm::lookAt(glm::vec3(0,0,0), direction, upVector);
viewMatrix = glm::translate(lookAtMatrix, -position);
normalMatrix = glm::transpose(glm::inverse(viewMatrix));
}
}; |
C | UTF-8 | 306 | 2.984375 | 3 | [] | no_license | #include <string.h>
extern char **environ;
char *getenv (const char *name)
{
char **p, *q;
int i;
i = strlen(name);
p = environ;
while (*p) {
q = strchr(*p, '=');
if (!q) /* Is it possible? */
continue;
if ((q - *p == i) && !memcmp(*p, name, i))
return q + 1;
++p;
}
return *p;
}
|
C | UTF-8 | 352 | 4.21875 | 4 | [] | no_license | #include <stdio.h>
void swap(int *x, int *y);
int main(){
int x, y;
printf("Enter the Value of X: ");
scanf("%d", &x);
printf("Enter the Value of Y: ");
scanf("%d", &y);
swap(&x, &y);
printf("The Swapped values are X is %d and Y is %d", x,y);
return 0;
}
void swap(int *x, int*y){
int z=*x;
*x=*y;
*y=z;
} |
C | UTF-8 | 4,276 | 4.34375 | 4 | [] | no_license | #include "linkedList.h"
/*
This function creates the list using a dummy head. It can be used by calling it and equaling it to the list you made.
*/
listNode * createList()
{
listNode * dummyNode = malloc(sizeof(listNode)*1);
dummyNode->x = 0;
dummyNode->y = 0;
dummyNode->nodeInfo = 0;
dummyNode->next = NULL;
return(dummyNode);
}
/*
This function destroys the list. It can be used by calling it and giving it a pointer to the list.
*/
void destroyList (listNode * theList)
{
if (theList == NULL)
{
printf("Error. NULL List. Returning.\n");
return;
}
while (theList->next != NULL)
{
removeFromFront(theList);
}
free(theList);
return;
}
/*
This function is used to add to the front of the list. The user gives it the list and the number they would like to put in the front.
*/
listNode * addToFront(listNode * theList, int x, int y, int nodeInfo)
{
listNode * newNode = initNode(x,y,nodeInfo);
if (theList == NULL)
{
printf("Error. Null List. Returning Null.\n");
return(NULL);
}
newNode->next = theList->next;
theList->next = newNode;
theList->nodeInfo ++;
return(theList);
}
/*
This function is used to get the value of the front of the list.
*/
int * getFrontValue(listNode * theList)
{
int * frontValue = malloc(sizeof(int)*3);
if (theList == NULL)
{
printf("Error. NULL List. Returning 0.\n");
return(0);
}
else if (theList->next == NULL)
{
printf("Error. Retuning 0. No Front Node Found in List.\n");
return(0);
}
else
{
frontValue[0] = (theList->next)->x;
frontValue[1] = (theList->next)->y;
frontValue[2] = (theList->next)->nodeInfo;
}
return(frontValue);
}
/*
This function is used to get the length of the list.
*/
int listLength(listNode * theList)
{
if (theList == NULL)
{
printf("Error. NULL List. Returning 0.\n");
return(0);
}
return(theList->nodeInfo);
}
/*
This function is used to add to the back of the list. The user gives it the list and the number they would like to put in the back.
*/
listNode * addToList(listNode * theList, int x, int y, int nodeInfo)
{
listNode * tailNode = malloc(sizeof(listNode)*1);
listNode * newNode = initNode(x,y,nodeInfo);
if (theList == NULL)
{
printf("Error. NULL list. Returning NULL.\n");
return(NULL);
}
tailNode = theList;
while (tailNode->next != NULL)
{
tailNode = tailNode->next;
}
tailNode->next = newNode;
theList->nodeInfo ++;
return(theList);
}
/*
This function is used to create a new node for the list.
*/
listNode * initNode(int x, int y, int nodeInfo)
{
listNode * newNode;
newNode = malloc(sizeof(listNode)*1);
newNode->x = x;
newNode->y = y;
newNode->nodeInfo = nodeInfo;
newNode->next = NULL;
return(newNode);
}
/*
This function is used to remove the first node from the list.
*/
listNode * removeFromFront (listNode * theList)
{
listNode * toBeRemoved;
if (theList == NULL)
{
printf("Error. The list is NULL.\n");
return(NULL);
}
else if (theList->next == NULL)
{
printf("Error. Retuning list. List is empty.\n");
return(theList);
}
else
{
toBeRemoved = theList->next;
theList->next = (theList->next)->next;
free(toBeRemoved);
theList->nodeInfo --;
}
return(theList);
}
/*
This function is used to create a new node for the list.
*/
void printList (listNode * theList)
{
listNode * currListPos;
if (theList == NULL)
{
printf("Error. NULL list. Returning.\n");
return;
}
else if (theList->next == NULL)
{
printf("The List is empty. Returning.\n");
return;
}
else
{
currListPos = theList->next;
while (currListPos->next != NULL)
{
printf("(%d,%d) NodeInfo:%d\n",currListPos->x,currListPos->y,currListPos->nodeInfo);
currListPos = currListPos->next;
}
printf("(%d,%d) NodeInfo:%d\n",currListPos->x,currListPos->y,currListPos->nodeInfo);
}
return;
}
|
C | UTF-8 | 1,061 | 3.046875 | 3 | [] | no_license | /*************************************************************************
> File Name: fork_waitpid_while.c
> Author:
> Mail:
> Created Time: 2020年03月29日 星期日 10时35分17秒
************************************************************************/
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(int argc,char* argv[])
{
int i;
pid_t pid,wpid;
for(i=0;i<5;i++)
{
pid=fork();
if(fork()==0)
break;
}
if(i==5)
{
/*while((wpid=waitpid(-1,NULL,0)))
{
printf("wat child %d\n",wpid);
}*/
while((wpid=waitpid(-1,NULL,WNOHANG))!=-1)
{
if(wpid>0)
{
printf("wait child %d\n",wpid);
}
else if(wpid==0)
{
sleep(1);
continue;
}
}
}
else
{
sleep(i);
printf("I'm %dth child,pid=%d\n",i+1,getpid());
}
}
|
C | UTF-8 | 2,616 | 3.015625 | 3 | [] | no_license | /*
* timer.c
* This C-file helps to either measure time between start and stop or sets a flag after a predetermined timer cycle count.
* Created: 01/04/17 15:46:48
* Author: Sondre
*/
#include "timer.h"
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdint.h>
#include <stdbool.h>
#define F_CPU 8000000UL
//Choose prescaler between 1,8,64,256,1024
#define TIMER_PRESCALER 64
#define NUMBER_OF_TIMERS 8
static bool timer_enabled[NUMBER_OF_TIMERS];
static int32_t elapsed_microseconds[NUMBER_OF_TIMERS];
#define NUMBER_OF_TASKS 8
static bool task_enabled[NUMBER_OF_TASKS];
static bool task_flag[NUMBER_OF_TASKS]; //is set to 1 after cycle_count has reached task_interval
static uint16_t cycle_count[NUMBER_OF_TASKS]; //current number of interrupt cycles
static uint16_t task_interval[NUMBER_OF_TASKS]; //number of interrupt cycles after which the task-flag is set
void timer_init() {
// Configure timer with normal mode
TCCR0A = 0;
// Enable overflow interrupt
TIMSK0 = (1 << TOIE0);
// set prescaler
switch(TIMER_PRESCALER){
case 1: TCCR0A |= 0b001; break;
case 8: TCCR0A |= 0b010; break;
case 64: TCCR0A |= 0b011; break;
case 256: TCCR0A |= 0b100; break;
case 1024: TCCR0A |= 0b101; break;
}
}
void timer_start(timer_t timer) {
elapsed_microseconds[timer] = -(1000000LL * TIMER_PRESCALER * TCNT0) / F_CPU ;
//elapsed_microseconds[timer] = 0;
timer_enabled[timer] = true;
}
void timer_stop(timer_t timer) {
timer_enabled[timer] = false;
}
uint16_t timer_elapsed_ms(timer_t timer) {
return (elapsed_microseconds[timer] + (1000000LL * TIMER_PRESCALER * TCNT0) / F_CPU)/ 1000;
//return elapsed_microseconds[timer]/1000;
}
uint32_t timer_elapsed_us(timer_t timer) {
return (elapsed_microseconds[timer] + (1000000LL * TIMER_PRESCALER * TCNT0) / F_CPU);
//return elapsed_microseconds[timer];
}
//Start a task with the designator task and a task interval of ti
void task_start(uint8_t task, uint16_t ti){
task_interval[task] = ti;
task_enabled[task] = true;
cycle_count[task] = 0;
}
void task_stop(uint8_t task){
task_enabled[task] = false;
cycle_count[task] = 0;
}
bool task_is_due(uint8_t task){
return task_flag[task];
}
void task_is_done(uint8_t task){
task_flag[task] = 0;
}
ISR(TIMER0_OVF_vect) {
for (int t = 0; t < NUMBER_OF_TASKS; t++) {
if (task_enabled[t]){
cycle_count[t]++;
if(cycle_count[t] == task_interval[t]) {
cycle_count[t] = 0;
task_flag[t] = true;
}
}
}
for (int t = 0; t < NUMBER_OF_TIMERS; t++) {
if (timer_enabled[t]){
elapsed_microseconds[t] += (1000000ULL * TIMER_PRESCALER * 256) / F_CPU;
}
}
}
|
C | UTF-8 | 5,103 | 2.84375 | 3 | [] | no_license | #include "display_handle.h"
//*********************************************//
// //
// Define the functions used for display //
// pictures, shapes and words //
// //
//*********************************************//
/***********************************
* Draw one snake in welcome window
***********************************/
void drawSnakeLogo(void) {
system("CLS");
color(YELLOW);
gotoxy(35, 1);
printf("/^\\/^\\");
gotoxy(34, 2);
printf("|__| 0|");
color(GREEN_DEEP);
gotoxy(33, 2);
printf("_");
color(RED);
gotoxy(25, 3);
printf("\\/");
color(GREEN_DEEP);
gotoxy(31, 3);
printf("/");
color(YELLOW_DARK);
gotoxy(37, 3);
printf("\\_/");
color(GREEN_LIGTH);
gotoxy(41, 3);
printf(" \\");
color(RED);
gotoxy(26, 4);
printf("\\____");
color(RED);
gotoxy(32, 4);
printf("__________/");
color(GREEN_DEEP);
gotoxy(31, 4);
printf("|");
color(GREEN_LIGTH);
gotoxy(43, 4);
printf("\\");
color(GREEN_DEEP);
gotoxy(32, 5);
printf("\\______");
color(GREEN_LIGTH);
gotoxy(44, 5);
printf("\\");
gotoxy(39, 6);
printf("| | \\");
gotoxy(38, 7);
printf("/ / \\");
gotoxy(37, 8);
printf("/ / \\ \\");
gotoxy(35, 9);
printf("/ / \\ \\");
gotoxy(34, 10);
printf("/ / \\ \\");
gotoxy(33, 11);
printf("/ / _----_ \\ \\");
gotoxy(32, 12);
printf("/ / _-~ ~-_ | |");
gotoxy(31, 13);
printf("( ( _-~ _--_ ~-_ _/ |");
gotoxy(32, 14);
printf("\\ ~-_____-~ _-~ ~-_ ~-_-~ /");
gotoxy(33, 15);
printf("~-_ _-~ ~-_ _-~");
gotoxy(35, 16);
printf("~--______-~ ~-___-~");
}
/***********************************
* Draw the menu
***********************************/
void drawMenu(void) {
int i, j;
color(BL_GR_LIGHT);
gotoxy(43, 18);
printf("Snake Likes Eating");
// draw the top and bottom frame
color(YELLOW);
for (i = 20; i <= 26; i+=6) {
for (j = 27; j <= 74; j++) {
gotoxy(j, i);
if (i == 20 || i == 26) {
printf("=");
}
}
}
color(WHITE);
gotoxy(35, 23);
printf("1. Start Game");
gotoxy(55, 23);
printf("2. Quit");
color(PINK);
gotoxy(29, 27);
printf("Please select [1/2] : [ ]\b\b");
}
/*******************************
* Draw the game map
*******************************/
void drawMap(void) {
int i;
// draw the top and bottom walls
color(PURPLE);
for (i = 0; i < 58; i += 2) {
gotoxy(i, 0);
printf("■");
gotoxy(i, 26);
printf("■");
}
// draw the left and right walls
for (i = 0; i < 26; i++) {
gotoxy(0, i);
printf("■");
gotoxy(56, i);
printf("■");
}
// draw the grid
/*
for (i = 2; i < 56; i += 2) {
for (j = 1; j < 26; j++) {
gotoxy(i, j);
color(3);
printf("□");
}
}
*/
}
/*******************************
* Show the real-time game info
*******************************/
void showGameInfo(void) {
color(BL_GR_LIGHT);
gotoxy(64, 4);
printf("# High Score # : %d", highScore);
color(YELLOW);
gotoxy(64, 8);
printf("Current score: %d", score);
color(PINK);
gotoxy(60, 12);
printf("*------------------------------*");
gotoxy(64, 14);
printf("Hints: ");
gotoxy(64, 15);
printf("1. Don't crash to the wall");
gotoxy(64, 16);
printf("2. Press NUM 1 to speed up");
gotoxy(64, 17);
printf("3. Press NUM 2 to speed down");
gotoxy(60, 19);
printf("*------------------------------*");
}
/*******************************
* Show the game end window
*******************************/
void showGameEndWindow(void) {
int ch = 0;
system("CLS");
gotoxy(39, 7);
// show the text according to game result
switch (gameResult)
{
case G_FAIL:
color(GRAY);
printf("Game Over!");
break;
case G_QUIT:
color(RED);
printf("Please be more patient...");
break;
case G_WIN:
color(YELLOW);
printf("Congratulations! You are the winner!");
break;
default:
break;
}
gotoxy(35, 12);
color(BL_GR_LIGHT);
printf("Your final score is %d", score);
// print highscore
if (score > highScore) {
gotoxy(33, 17);
color(PINK);
printf("New Highscore! Great Job!");
File_In();
}
else {
gotoxy(25, 17);
color(GREEN_LIGTH);
printf("Keep playing, you need %d to update highscore", highScore - score);
}
gotoxy(2, 22);
color(GRAY);
printf("press A to continue...");
while ((ch != 'A')&& (ch != 'a')) {
ch = _getch();
}
}
/***********************************
* Show further selection after end
***********************************/
int selectionAfterEnd(void) {
int select;
gotoxy(25, 23);
printf("Play again[1]");
gotoxy(52, 23);
printf("Quit[2]");
gotoxy(46, 25);
color(BLUE_LIGHT);
printf("You choose...");
do
{
scanf_s("%d", &select);
switch (select)
{
case 1:
return G_RESUME;
case 2:
return G_QUIT;
default:
color(GRAY);
gotoxy(46, 27);
printf("Please choose valid number[1/2] ... ");
break;
}
} while (TRUE);
} |
C | UTF-8 | 557 | 2.765625 | 3 | [] | no_license | #include <stdio.h>
#include<string.h>
int main()
{
FILE *fsource,*ftarget;
char data[10]="rajrpatel";
int length=strlen(data);
int i;
char ch;
fsource=fopen("Diary.txt","r");//
ftarget=fopen("raj.txt","a"); //I opened in append mode so ftarget pointer will be point after the last character of the file
/*for(i=0;i<length;i++)
fputc(data[i],fptr);
fptr=fopen("raj.txt","r");
*/
while( (ch=fgetc(fsource)) != EOF)
{
fputc(ch,ftarget);
}
fclose(fsource);
fclose(ftarget);
return 0;
}
|
C | UTF-8 | 712 | 3.296875 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
int main() {
int n, op, cont, i, total = 0;
char num[100];
scanf("%d", &op);
for(cont = 0; cont < op; cont++) {
scanf("%s", num);
for(i = 0; i <= strlen(num); i++) {
switch(num[i]) {
case '0': { total += 6; break; }
case '1': { total += 2; break; }
case '2': { total += 5; break; }
case '3': { total += 5; break; }
case '4': { total += 4; break; }
case '5': { total += 5; break; }
case '6': { total += 6; break; }
case '7': { total += 3; break; }
case '8': { total += 7; break; }
case '9': { total += 6; break; }
default: { total += 0; break; }
}
}
printf("%d leds\n", total);
total = 0;
}
return 0;
} |
C | UTF-8 | 790 | 3.390625 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2018
** philo
** File description:
** parsing arguments
*/
#include "philosopher.h"
bool is_number(char *str)
{
int i = 0;
while (str[i]) {
if (!isdigit(str[i]))
return (false);
i += 1;
}
return (true);
}
int check_args(char **argv)
{
bool p = (!strcmp(argv[1], "-p") || !strcmp(argv[3], "-p"));
bool e = (!strcmp(argv[1], "-e") || !strcmp(argv[3], "-e"));
if (!is_number(argv[2]) || !is_number(argv[4]) || !e || !p)
return (84);
return (0);
}
int get_philos(char **argv)
{
int i = 0;
if (!strcmp(argv[1], "-p"))
i = 2;
else if (!strcmp(argv[3], "-p"))
i = 4;
return (atoi(argv[i]));
}
int get_eat(char **argv)
{
int i = 0;
if (!strcmp(argv[1], "-e"))
i = 2;
else if (!strcmp(argv[3], "-e"))
i = 4;
return (atoi(argv[i]));
}
|
C | WINDOWS-1252 | 370 | 3.140625 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
//ݹ
void print(int n)
{
if (n > 9)
{
print(n / 10);
}
printf("%d ", n % 10);
}
int main()
{
//printf("hehe\n");
//main();
//ջ
unsigned int num = 0;
scanf("%d", &num);//1234
//ݹ
print(num);
//print(1234);
//print(123) 4
//print(12) 3 4
//print(1) 2 3 4
//
return 0;
}
|
C | UTF-8 | 516 | 3.734375 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int imprime_recursivo_inverso(char * string, int longitud){
if (longitud == 0){
printf("%c\n", string[longitud]);
return 0;
}
else {
printf("%c", string[longitud]);
imprime_recursivo_inverso(string, (--longitud));
return 0;
}
}
int main(){
char *str= malloc(10);
printf("Ingrese una palabra:" );
scanf("%s", str );
printf("Longitud del caracter %d\n",strlen(str));
imprime_recursivo_inverso(str, strlen(str));
return 0;
}
|
C | UTF-8 | 7,080 | 2.796875 | 3 | [] | no_license | /*************************************************************
* lcd.c - Demonstrate interface to a parallel LCD display
*
* This program will print a message on an LCD display
* using the 4-bit wide interface method
*
* PORTB, bit 4 (0x10) - output to RS (Register Select) input of display
* bit 3 (0x08) - output to R/W (Read/Write) input of display
* bit 2 (0x04) - output to E (Enable) input of display
* PORTB, bits 0-1, PORTD, bits 2-7 - Outputs to DB0-DB7 inputs of display.
*
* The second line of the display starts at address 0x40.
*
* Revision History
* Date Author Description
* 11/17/05 A. Weber First Release for 8-bit interface
* 01/13/06 A. Weber Modified for CodeWarrior 5.0
* 08/25/06 A. Weber Modified for JL16 processor
* 05/08/07 A. Weber Some editing changes for clarification
* 06/25/07 A. Weber Updated name of direct page segment
* 08/17/07 A. Weber Incorporated changes to demo board
* 01/15/08 A. Weber More changes to the demo board
* 02/12/08 A. Weber Changed 2nd LCD line address
* 04/22/08 A. Weber Added "one" variable to make warning go away
* 04/15/11 A. Weber Adapted for ATmega168
* 01/30/12 A. Weber Moved the LCD strings into ROM
* 02/27/12 A. Weber Corrected port bit assignments above
* 11/18/13 A. Weber Renamed for ATmega328P
* 04/10/15 A. Weber Extended "E" pulse, renamed strout to strout_P
* 05/06/17 A. Weber Change to use new LCD routines
*************************************************************/
#include "lcd.h"
//int main(void) {
//
// lcd_init(); // Initialize the LCD display
// lcd_moveto(0, 0);
// lcd_stringout_P((char *)str1); // Print string on line 1
//
// lcd_moveto(1, 0);
// lcd_stringout_P((char *)str2); // Print string on line 2
//
// lcd_clear();
//
//
// char displayChar;
// while (1) { // Loop forever
//
// displayChar = Keypad();
//
// if(displayChar > 34 && displayChar < 58)
// {
// lcd_moveto(0,0);
// lcd_writedata(displayChar);
// }
// }
//
// return 0; /* never reached */
//}
/*
lcd_stringout_P - Print the contents of the character string "s" starting at LCD
RAM location "x" where the string is stored in ROM. The string must be
terminated by a zero byte.
*/
void lcd_stringout_P(char *s)
{
unsigned char ch;
/* Use the "pgm_read_byte()" routine to read the date from ROM */
while ((ch = pgm_read_byte(s++)) != '\0') {
lcd_writedata(ch); // Output the next character
}
}
/*
lcd_init - Do various things to force a initialization of the LCD
display by instructions, and then set up the display parameters and
turn the display on.
*/
void lcd_init(void)
{
#ifdef NIBBLE_HIGH
DDRD |= LCD_Data_D; // Set PORTD bits 4-7 for output
#else
DDRB |= LCD_Data_B; // Set PORTB bits 0-1 for output
DDRD |= LCD_Data_D; // Set PORTD bits 2-3 for output
#endif
DDRB |= LCD_Bits; // Set PORTB bits 2, 3 and 4 for output
PORTB &= ~LCD_RS; // Clear RS for command write
_delay_ms(15); // Delay at least 15ms
lcd_writenibble(0x30); // Send 00110000, set for 8-bit interface
_delay_ms(5); // Delay at least 4msec
lcd_writenibble(0x30); // Send 00110000, set for 8-bit interface
_delay_us(120); // Delay at least 100usec
lcd_writenibble(0x30); // Send 00110000, set for 8-bit interface
_delay_ms(2);
lcd_writenibble(0x20); // Send 00100000, set for 4-bit interface
_delay_ms(2);
lcd_writecommand(0x28); // Function Set: 4-bit interface, 2 lines
lcd_writecommand(0x0f); // Display and cursor on
}
/*
lcd_moveto - Move the cursor to the row and column given by the arguments.
Row is 0 or 1, column is 0 - 15.
*/
void lcd_moveto(unsigned char row, unsigned char col)
{
unsigned char pos;
pos = row * 0x40 + col;
if(row == 2)
{
pos = 0x14 + col;
}
else if(row == 3)
{
pos = 0x54 + col;
}
lcd_writecommand(0x80 | pos);
if(row == 2){
pos = 0x14 + col;
}
else if(row == 3){
pos = 0x54 + col;
}
lcd_writecommand(0x80 | pos);
}
/*
lcd_stringout - Print the contents of the character string "str"
at the current cursor position.
*/
void lcd_stringout(char *str)
{
char ch;
while ((ch = *str++) != '\0')
lcd_writedata(ch);
}
/*
lcd_writecommand - Output a byte to the LCD command register.
*/
void lcd_writecommand(unsigned char x)
{
PORTB &= ~LCD_RS; // Clear RS for command write
lcd_writebyte(x);
lcd_wait();
}
/*
lcd_writedata - Output a byte to the LCD data register
*/
void lcd_writedata(unsigned char x)
{
PORTB |= LCD_RS; // Set RS for data write
lcd_writebyte(x);
lcd_wait();
}
/*
lcd_writebyte - Output a byte to the LCD
*/
void lcd_writebyte(unsigned char x)
{
lcd_writenibble(x);
lcd_writenibble(x << 4);
}
/*
lcd_writenibble - Output a 4-bit nibble to the LCD
*/
void lcd_writenibble(unsigned char x)
{
#ifdef NIBBLE_HIGH
PORTD &= ~LCD_Data_D;
PORTD |= (x & LCD_Data_D); // Put high 4 bits of data in PORTD
#else
PORTB &= ~LCD_Data_B;
PORTB |= (x & LCD_Data_B); // Put low 2 bits of data in PORTB
PORTD &= ~LCD_Data_D;
PORTD |= (x & LCD_Data_D); // Put high 2 bits of data in PORTD
#endif
PORTB &= ~(LCD_RW|LCD_E); // Set R/W=0, E=0
PORTB |= LCD_E; // Set E to 1
PORTB |= LCD_E; // Extend E pulse > 230ns
PORTB &= ~LCD_E; // Set E to 0
}
/*
lcd_wait - Wait for the BUSY flag to reset
*/
void lcd_wait()
{
#ifdef USE_BUSY_FLAG
unsigned char bf;
#ifdef NIBBLE_HIGH
PORTD &= ~LCD_Data_D; // Set for no pull ups
DDRD &= ~LCD_Data_D; // Set for input
#else
PORTB &= ~LCD_Data_B; // Set for no pull ups
PORTD &= ~LCD_Data_D;
DDRB &= ~LCD_Data_B; // Set for input
DDRD &= ~LCD_Data_D;
#endif
PORTB &= ~(LCD_E|LCD_RS); // Set E=0, R/W=1, RS=0
PORTB |= LCD_RW;
do {
PORTB |= LCD_E; // Set E=1
_delay_us(1); // Wait for signal to appear
bf = PIND & LCD_Status; // Read status register high bits
PORTB &= ~LCD_E; // Set E=0
PORTB |= LCD_E; // Need to clock E a second time to fake
PORTB &= ~LCD_E; // getting the status register low bits
} while (bf != 0); // If Busy (PORTD, bit 7 = 1), loop
#ifdef NIBBLE_HIGH
DDRD |= LCD_Data_D; // Set PORTD bits for output
#else
DDRB |= LCD_Data_B; // Set PORTB, PORTD bits for output
DDRD |= LCD_Data_D;
#endif
#else
_delay_ms(2); // Delay for 2ms
#endif
}
/*
lcd_clear clears entire screen
*/
void lcd_clear()
{
lcd_moveto(0,0);
lcd_writecommand(0x01);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.