language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
int ifib(int);
int rfib(int);
// Main to call fib function and output iterative and recursive results
int main(int argc, char *args[]) {
int n = atoi(args[1]);
printf("Fibonacci = Iterative Algorithm\n");
printf("ifib(%d) = %d\n", n, ifib(n));
printf("Fibonacci = Recursive Algorithm\n");
printf("rfib(%d) = %d\n", n, rfib(n));
printf("Done\n");
return 0;
}
// The iterative algorithm
int ifib(int n) {
if (n <= 0) {
return 0;
} else if (n <= 2) {
return 1;
} else {
int a = 1; // first Fibonacci value
int b = 1; // second Fibonacci value
int index = 0; // index
for (index = 1; index < n / 2; index++) {
a += b;
b += a;
}
if (n % 2 == 0) {
// return Fibonacci value
return b;
} else {
// update and return second Fib value
return a + b;
}
}
}
//The recursive algorithm
int rfib(int n) {
// setting the base case
if (n <= 0) {
return 0;
} else if (n <= 2) {
return 1;
//Run general case where the current value is the sum of 2 previous values
} else {
return rfib(n - 1) + rfib(n - 2);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TITLE_LENGTH 40
struct film {
char title[TITLE_LENGTH];
int rate;
};
struct film_list {
struct film * movie;
struct film_list * next;
};
int getFilm(struct film *);
void printList(struct film_list *);
int main(void){
puts("This program record film in list");
struct film_list * current;
struct film_list head;
current = &head;
do {
struct film * movie = (struct film *)malloc(sizeof(struct film));
struct film_list * next= (struct film_list *)malloc(sizeof(struct film_list));
getFilm(movie);
current->movie = movie;
puts("Enter done to stop or any other key to continue");
char directive[5];
fgets(directive, 5, stdin);
if(strcmp(directive, "done") == 0){
current->next = NULL;
printList(&head);
break;
} else {
current->next = next;
current = next;
}
} while(1);
return 0;
}
int getFilm(struct film * movie){
puts("Please input film name:");
fgets(movie->title, TITLE_LENGTH, stdin);
puts("Please input rate of the film:");
scanf("%d", &movie->rate);
getchar();
return 1;
}
void printList(struct film_list * fl){
struct film_list * current = fl;
printf("tile \t rate\n");
while(current != NULL){
printf("%s \t %d\n", current->movie->title, current->movie->rate);
current = current->next;
}
printf("\n");
}
|
C
|
//
// Copyright (c) 2006-2009 Niels Heinen
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. The name of author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#include <util.h>
#include <sys/types.h>
#include <pwd.h>
// from main.c
extern int loop_control;
extern int loop_analyzer;
extern int loop_sniffer;
extern int loop_main;
extern pthread_t t_control;
extern pcap_t *handle;
//
// memcmp that allows case insensitive compares
//
int mymemcmp(const void *str1, const void *str2,int size,int nocase) {
const unsigned char *a = (const unsigned char*) str1;
const unsigned char *b = (const unsigned char*) str2;
if(nocase == -1) {
while(--size >= 0) {
if(*a++ != *b++)
return -1;
}
} else {
while(--size >= 0) {
if(tolower(*a++) != tolower(*b++))
return -1;
}
}
return 0;
}
// Drop privileges for security reasons..
int drop_privileges(char *user) {
struct passwd *pw = getpwnam(user);
if (pw == NULL) {
log_error("Cannot drop privileges to user %s", user);
return -1;
}
// Set group privileges
if (setegid(pw->pw_gid) == -1 || setgid(pw->pw_gid) == -1) {
log_error("Privilege dropping error: Unable to set GID to %d",pw->pw_gid);
return -1;
}
// Set user privileges
if(seteuid(pw->pw_uid) == -1 || setuid(pw->pw_uid)) {
log_error("Privilege dropping error: Unable to set UID to %d",pw->pw_uid);
return -1;
}
log_info("Dropped privileges to user \"%s\" (UID: %d)",user,getuid());
return 0;
}
void fork_to_background() {
int child;
if((child = fork()) == -1) {
log_error("Unable to fork process..\n");
exit(1);
}
if(child != 0) {
exit(0);
}
}
// convert a hex value to char
char hex2char (char *hex)
{
char mychar;
mychar = (hex[0] >= 'A' ? ((hex[0] & 0xdf) - 'A') + 10 : (hex[0] - '0'));
mychar *= 16;
mychar += (hex[1] >= 'A' ? ((hex[1] & 0xdf) - 'A') + 10 : (hex[1] - '0'));
return (mychar);
}
// Dump the buffer in hex value
void dumphex(void *data, int size) {
char *hex = (char *)data;
char asarray[20];
char hxarray[64];
int starta=0,starth=0;
int i=0;
memset(hxarray,0x20,sizeof(hxarray) -1);
memset(asarray,0x20,sizeof(asarray) -1);
printf("------------------------------------------------------------------------------------------------------\n");
for (i=0;i<size;i++) {
if(iswalpha((int)hex[i])) {
asarray[starta++] = ((unsigned char*)hex)[i];
} else {
asarray[starta++] = '.';
}
sprintf(hxarray + starth,"%02x ",((unsigned char *)hex)[i]);
if(starta == 19) {
asarray[starta] = '\0';
printf("%s | %s\n",hxarray,asarray);
memset(hxarray,0x20,sizeof(hxarray) -1);
memset(asarray,0x20,sizeof(asarray) -1);
starth=starta=0;
} else {
starth += 3;
}
}
asarray[starta] = '\0';
printf("%57s | %s\n",hxarray,asarray);
printf("------------------------------------------------------------------------------------------------------\n");
}
// TODO add dynamic payload signature matching (perhaps pcre?)
//
// Usage information
//
void usage() {
printf("\n\n");
printf("\n------------------------------------------------------\n");
printf(" %s (version: %s %s)\n",PROGNAME, VERSION);
printf("------------------------------------------------------\n");
printf("\n");
printf("Options:\n");
printf(" -c <conf file> # Configuration\n");
printf(" -i <device> # Read from device (online)\n");
printf(" -v # Verbosity\n");
printf(" \n");
printf(" -q # Quiet mode\n");
printf(" -d # Tcpdump mode\n");
printf(" -s # Syslog mode\n");
printf(" -f <filter> # Specify the pcap filter\n");
printf(" -r <pcap file> # Read from pcap file (offline)\n");
printf(" -P <divert port> # Divert socket\n");
printf(" -I # Inline mode\n");
printf(" -S <sig file> # File with signatures\n");
printf(" -l <dir> # Directory for packet dumps\n");
printf(" -u <user> # Run as user\n");
printf(" -D # Daemon mode\n");
printf(" -T # Disable strict TCP\n");
printf("\n\n");
}
//
// Cleanup characters
//
// Cleanup a string (remove spaces)Impact on memory?
char * cleanup_char(char *word) {
int i;
char *ptr = word;
for(i=0; i<strlen(word); i++) {
//printf("hex: %x\n",word[i]);
if(word[i] == HEX_VAL_SPACE) {
ptr = word + (i + 1);
continue;
}
if(word[i] == HEX_VAL_QUOTES) {
ptr = word + (i + 1);
}
break;
}
word = ptr;
//printf("Word: \"%s\"\n",word);
for(i=strlen(word) -1; i >= 0; i--) {
if(word[i] == HEX_VAL_SPACE) {
word[i] = '\0';
continue;
}
if(word[i] == HEX_VAL_QUOTES)
word[i] = '\0';
break;
}
return word;
}
int is_file(char *file) {
struct stat sbuf;
if (stat(file, &sbuf) != 0) {
return 0;
}
if (!S_ISREG(sbuf.st_mode)) {
return 0;
}
return 1;
}
int is_dir(char *file) {
struct stat sbuf;
if (stat(file, &sbuf) != 0) {
return 0;
}
if (!S_ISDIR(sbuf.st_mode)) {
return 0;
}
return 1;
}
// Signal handles
void sigquit_handler () {
printf("\n");
log_info("Received signal..");
loop_sniffer = 0;
loop_analyzer = 0;
loop_control = 0;
loop_main = 0;
// Get all messages
pop_all_messages();
if(handle != NULL)
pcap_breakloop(handle);
//close files
logoutputs_close();
}
// Signal handles
void sighup_handler () {
printf("\n");
log_info("Received HUP signal");
// log_info("Stopping control thread..");
// loop_control = 0;
// Wait for it to end
// pthread_join(t_control,NULL);
// Reload signatures
reloadSignatures();
// Start new control thread
// log_info("Starting new control thread..");
// loop_control = 1;
// pthread_create(&t_control,NULL,(void*)control_loop,NULL);
}
//
// String match routing, used by content
// only
//
// 0 --> no match possible (e.g. error)
// 1 --> match
// 2 --> no match
int content_payload_compare(struct signature *sig, struct traffic* traf, struct payload_opts *popts) {
int i,strfound = 0, breakbool = 0;
char *payload = (char *)traf->payload;
// Always assume we start from the first byte
int offset=0;
// If there is an offset defined in the signature then
// we apply it (offset is always relative from byte 0
if(popts->offset > 0) {
if(popts->offset >= traf->psize) {
DEBUG(stdout,"Offset exceeds data size");
return 0;
}
offset = popts->offset;
}
// Distance if an offset that is relative to the
// last match.. overwrites the above. which is pretty ugly
if(popts->distance != -1)
offset = traf->poffset + popts->distance;
if(popts->within != -1)
offset = traf->poffset;
DEBUGF("Going to inspect %d bytes\n",psize);
strfound = CONTENT_TEST_NOT_FOUND;
for (i=offset; i<(traf->psize - popts->matchstr_size) + 1 && breakbool == 0 ;i++) {
if(popts->distance != -1)
breakbool = 1;
// If depth was used then only look the amount of bytes
// as specified by it
if(popts->depth > 0 && popts->depth > i)
return 0;
// within check (todo: abuse depth?)
// If 'i' is larger then i + within then the
// next string is not within "within" bytes ;p
if(popts->within != -1 && i > (traf->poffset + popts->within)){
return 0;
}
// Not a possible start? -> revise
if(popts->nocase != 1 && payload[i] != ((char *)popts->matchstr)[0]) {
continue;
} else if(popts->nocase == 1 && tolower(payload[i]) != tolower(((char *)popts->matchstr)[0])) {
continue;
}
// Check if the is data at "isdataat", relatively to the point
// of the last match. isdataat without "relative" is not supported and
// can be replaced with dsize.
//printf("if(%d != -1 && %d < %d)\n",popts->isdataat,(traf->psize - (i + popts->matchstr_size)),popts->isdataat);
if(popts->isdataat != -1 && (traf->psize - (i + popts->matchstr_size)) < popts->isdataat) {
return 0;
}
// Match?
if(mymemcmp(payload + i,popts->matchstr,popts->matchstr_size,popts->nocase) == 0) {
// Continue searching ater match
i = (i + popts->matchstr_size);
// Last matchpointer
traf->poffset = i;
strfound = CONTENT_TEST_FOUND;
break;
}
}
if(popts->test == strfound)
return 1;
// No match
return 0;
}
//
// String match routing, used by uricontent and content
//
// 0 --> no match possible (e.g. error)
// 1 --> match
// 2 --> no match
int payload_compare(struct signature *sig, char *data, int psize,int ptype) {
int i,cindex,strfound = 0,matches=0, breakbool = 0;
int offset=0, lmatch=0;
struct payload_opts *popts = NULL;
for(cindex=0;cindex <SIG_MAX_CONTENT;cindex++) {
// Loop content or loop uricontent
if(ptype == TYPE_CONTENT) {
popts = (struct payload_opts*)sig->content[cindex];
} else {
popts = (struct payload_opts*)sig->uricontent[cindex];
}
// If below is true then we're done processing the content or
// uricontent payload options and can check if this signature
// was a match or not.
if(popts == NULL) {
//printf("matches: %d cindex: %d\n",matches,cindex);
if(cindex > 0 && matches == cindex) {
return 1;
}
return 0;
}
if(popts->offset > 0) {
if(popts->offset >= psize) {
DEBUG(stdout,"Offset exceeds data size");
return 0;
}
offset = popts->offset;
}
// Distance if an offset that is relative to the
// last match..
if(popts->distance != -1)
offset = lmatch + popts->distance;
if(popts->within != -1)
offset = lmatch;
DEBUGF("Going to inspect %d bytes\n",psize);
strfound = CONTENT_TEST_NOT_FOUND;
for (i=offset; i<(psize - popts->matchstr_size) + 1 && breakbool == 0 ;i++) {
if(popts->distance != -1)
breakbool = 1;
// If depth was used then only look the amount of bytes
// as specified by it
if(popts->depth > 0 && popts->depth > i)
return 0;
// within check
if(lmatch != 0) {
// If 'i' is larger then lmatch + within then the
// next string is not within "within" bytes ;p
if(popts->within != -1 && i > (lmatch + popts->within)){
break; // Test.. break instead of return
//return 0;
}
}
// Potential start
if(data[i] != ((char *)popts->matchstr)[0])
continue;
// Check if the is data at "isdataat", relatively to the point
// of the last match. isdataat without "relative" is not supported and
// can be replaced with dsize.
//printf("if(%d != -1 && %d < %d)\n",popts->isdataat,(psize - (i + popts->matchstr_size)),popts->isdataat);
if(popts->isdataat != -1 && (psize - (i + popts->matchstr_size)) < popts->isdataat) {
return 0;
}
// Match
if(mymemcmp(data + i,popts->matchstr,popts->matchstr_size,popts->nocase) == 0) {
// Continue searching ater match
i = (i + popts->matchstr_size);
// Last matchpointer
lmatch = i;
strfound = CONTENT_TEST_FOUND;
break;
}
}
if(popts->test == strfound)
matches++;
}
// No match
return 2;
}
int base64_encode(char *input,char *output) {
unsigned char alphabet[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int i,bits, char_count;
int a = 0;
char_count = 0;
bits = 0;
for (i=0;i<strlen(input) && input[i] != '\0'; i++) {
bits += input[i];
char_count++;
if (char_count == 3) {
output[a++] = alphabet[bits >> 18];
output[a++] = alphabet[(bits >> 12) & 0x3f];
output[a++] = alphabet[(bits >> 6) & 0x3f];
output[a++] = alphabet[bits & 0x3f];
bits = 0;
char_count = 0;
} else {
bits <<= 8;
}
}
if (char_count != 0) {
bits <<= 16 - (8 * char_count);
output[a++] = alphabet[bits >> 18];
output[a++] = alphabet[(bits >> 12) & 0x3f];
if (char_count == 1) {
output[a++] = '=';
output[a++] = '=';
} else {
output[a++] = alphabet[(bits >> 6) & 0x3f];
output[a++] = '=';
}
}
// Terminate
output[a] = '\0';
return 0;
}
|
C
|
#include <stdio.h>
#define MAX_LINE_LENGTH 20
void reverse(char str[]);
int getline_(char s[], int lim);
int main(void)
{
int len;
char line[MAX_LINE_LENGTH];
while ((len = getline_(line, MAX_LINE_LENGTH)) != 0)
{
reverse(line);
printf("%s\n", line);
}
}
void reverse(char str[])
{
int length = 0;
while (str[length] != '\0')
length++;
length++;
int i = 0;
char copy[length];
while ((copy[i] = str[i]) != '\0')
i++;
copy[i] = '\0';
for (i = 0; i < length - 1; i++)
{
str[length - i - 2] = copy[i];
}
}
int getline_(char s[], int lim)
{
int c, i;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if (c == '\n')
{
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "head.h"
int main(int argc, char *argv[])
{
int a = atoi(argv[1]);
int b = atoi(argv[2]);
int c = add(a,b);
printf("%d\n",argc );
printf("%s %s\n",argv[1],argv[2] );
printf("%d + %d = %d\n",a,b,c );
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(void)
{
unsigned int n;
int retorno;
char cadena_s1[] = "ab";
char cadena_s2[] = "abc";
n = 3;
retorno = strncmp (cadena_s1, cadena_s2, n);
printf("%i\n", retorno);
}
|
C
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.c
* Author: axel
*
* Created on 7 de junio de 2020, 13:22
*/
#include <stdio.h>
#include <stdlib.h>
#include "PortControl.h"
#include "const.h"
#include "hardware.h"
int input(void);
void printPort(char puerto);
void printInstructions(void);
/*
*
*/
int main(void)
{
char puerto = 'a'; //Inicializo en el puerto A
int mask = 0xFF; //Inicializo la mascara en 11111111b
int var = -3; //Inicializo la variable con un valor que no interfiera con las funciones
FILE* fptr;
RPI_export_pin();
RPI_set_direction();
maskOff(mask, puerto); //Apago todos los bit del puerto
printInstructions(); //Imprimo las instrucciones
printPort(puerto); //Imprimo el puerto
while (var != QUIT) //Mientras no se presiones q
{
var = input(); //Consigo el valor del input
switch (var)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
{
bitToggle(var, puerto); //Cambio el estado de un bit al contrario
};
break;
case 's':
case 'S':
{
maskOn(mask, puerto); // prendo todos los bits
};
break;
case 'c':
case 'C':
{
maskOff(mask, puerto); // apago todos los bit
};
break;
case 't':
case 'T':
{
maskToggle(mask, puerto); // prende los bits apagados y apaga los prendidos
};
break;
case 'i':
case 'I':
{
printInstructions(); // imprimo nuevamente las instrucciones
};
break;
}
printPort(puerto); //Imprimo el puerto
RPI_print_led();
}
RPI_unexport_pin();
printf ("Termino el programa\n"); //Se presiono q y termina el programa
return 0;
}
int input(void)
{
int c = 0;
int conta = 0;
int out = 0; //Flag para q
int res = 0; //Para devolver la respuesta
while ((c = getchar()) != '\n') {
if ((c >= '0') && (c <= '7')) //Si es uno de los numeros de los bites del puerto
{
res *= 10;
res = (c - '0'); // lo almaceno en res pasandolo a int y aumento el contador
conta++;
}//Si es una de las letras para los comandos
else if (c == 't' || c == 'T' || c == 'c' || c == 'C' || c == 's' || c == 'S' || c == 'i' || c == 'I') {
conta++; //Aumento el contador
res = c; //La almaceno en res
} else if ((c == 'Q') || (c == 'q')) //En el caso de ser el comando q
{
out = 1; //Enciendo el flag de q
conta++; //Aumento El contador
} else {
conta = -10; //Si no es ninguno de los casos anteriores el contador general en -10
}
}
if (conta <= 0 || conta > 1) //Si el contador es menor a 0 o mayor a 1
{
res = ERROR; //Devuelvo error
printf("Lo ingresado no es valido\n"); //y lo imprimo en pantalla
}
if (out == 1 && conta == 1) //Si se presiono q y el contador es 1
{
res = QUIT; //Devuelvo QUIT para salir del programa
}
return res;
}
void printPort(char puerto) {
int i = 0;
printf("|");
for (i = 0; i <= 7; i++) {
if (bitGet(i, puerto)) //Si bitGet devuelve 1, porque el bit esta prendido
{
printf("*"); // imprimo un *
} else //Caso contrario (si devuelve un 0)
{
printf(" "); // imprimo un espacio
}
printf("|");
}
printf("\n");
}
void printInstructions(void) //Imprime las instrucciones para utilizar el programa
{
printf("* * * * * * * * * *\n");
printf("Instrucciones:\n Ingresar: \t (mayusculas o minusculas)\n");
printf("-Numero entre el 0 y el 7: led que se quiera prender o apagar.\n");
printf("-S: encender todos los leds\n-C: apagar todos los leds.");
printf("T: apagar todos los leds encendidos y encender todos los leds apagados.\n");
printf("-I: volver a ver las instrucciones\n");
printf("-Q: terminar el programa.\n");
printf("* * * * * * * * * *\n\n\n");
}
|
C
|
#include "helpers.h"
#include <math.h>
// Convert image to grayscale
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
for(int i = 0; i < height; i++)
{
for(int j = 0; j < width; j++)
{
int rgbGrey = round((image[i][j].rgbtBlue + image[i][j].rgbtGreen + image[i][j].rgbtRed)/3.000);
image[i][j].rgbtBlue = rgbGrey;
image[i][j].rgbtGreen = rgbGrey;
image[i][j].rgbtRed = rgbGrey;
}
}
return;
}
int limit(int RGB)
{
if (RGB > 255)
{
RGB = 255;
}
return RGB;
}
// Convert image to sepia
void sepia(int height, int width, RGBTRIPLE image[height][width])
{
int sepiaBlue;
int sepiaGreen;
int sepiaRed;
for(int i = 0; i < height; i++)
{
for(int j = 0; j < width; j++)
{
sepiaRed = limit(round(image[i][j].rgbtRed * 0.393 + image[i][j].rgbtGreen * 0.769 + image[i][j].rgbtBlue * 0.189));
sepiaGreen = limit(round(image[i][j].rgbtRed * 0.349 + image[i][j].rgbtGreen * 0.686 + image[i][j].rgbtBlue * 0.168));
sepiaBlue = limit(round(image[i][j].rgbtRed * 0.272 + image[i][j].rgbtGreen * 0.534 + image[i][j].rgbtBlue * 0.131));
image[i][j].rgbtBlue = sepiaBlue;
image[i][j].rgbtGreen = sepiaGreen;
image[i][j].rgbtRed = sepiaRed;
}
}
return;
}
// Reflect image horizontally
void reflect(int height, int width, RGBTRIPLE image[height][width])
{
int tmp[3];
for(int i = 0; i < height; i++)
{
for(int j = 0; j < width / 2; j++)
{
tmp[0] = image[i][j].rgbtBlue;
tmp[1] = image[i][j].rgbtGreen;
tmp[2] = image[i][j].rgbtRed;
image[i][j].rgbtBlue = image[i][width - j - 1].rgbtBlue;
image[i][j].rgbtGreen = image[i][width - j - 1].rgbtGreen;
image[i][j].rgbtRed = image[i][width - j - 1].rgbtRed;
image[i][width - j - 1].rgbtBlue = tmp[0];
image[i][width - j - 1].rgbtGreen = tmp[1];
image[i][width - j - 1].rgbtRed = tmp[2];
}
}
return;
}
// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{
int sumBlue;
int sumGreen;
int sumRed;
float counter;
//create a temporary table of colors to not alter the calculations
RGBTRIPLE temp[height][width];
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
sumBlue = 0;
sumGreen = 0;
sumRed = 0;
counter = 0.00;
// sums values of the pixel and 8 neighboring ones, skips iteration if it goes outside the pic
for (int k = -1; k < 2; k++)
{
if (j + k < 0 || j + k > height - 1)
{
continue;
}
for (int h = -1; h < 2; h++)
{
if (i + h < 0 || i + h > width - 1)
{
continue;
}
sumBlue += image[j + k][i + h].rgbtBlue;
sumGreen += image[j + k][i + h].rgbtGreen;
sumRed += image[j + k][i + h].rgbtRed;
counter++;
}
}
// averages the sum to make picture look blurrier
temp[j][i].rgbtBlue = round(sumBlue / counter);
temp[j][i].rgbtGreen = round(sumGreen / counter);
temp[j][i].rgbtRed = round(sumRed / counter);
}
}
//copies values from temporary table
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
image[j][i].rgbtBlue = temp[j][i].rgbtBlue;
image[j][i].rgbtGreen = temp[j][i].rgbtGreen;
image[j][i].rgbtRed = temp[j][i].rgbtRed;
}
}
}
|
C
|
//program to check given strings are anagrams or not
#include <stdio.h>
#include <string.h>
int main(void)
{
char str1[100],str2[100];
printf("enter first string\n");
gets(str1);
printf("enter second string\n");
gets(str2);
char k; //k is temporary variable for swapping in sort fuction
int i, j;
int n1 = strlen(str1);
int n2 = strlen(str2);
//check the length of both strings is equal or not
//if length no equal then strings are not anagrams
if(n1!=n2)
{
printf("%s and %s are not anagrams\n",str1,str2);
return 0;
}
//sort the strings
for (i=0;i<n1-1;i++)
{
for (j=i+1;j<n1;j++)
{
if (str1[i]>str1[j])
{
k=str1[i];
str1[i]=str1[j];
str1[j]=k;
}
if (str2[i]>str2[j])
{
k=str2[i];
str2[i]=str2[j];
str2[j]=k;
}
}
}
//Compare both strings
for(i=0;i<n1;i++)
{
if(str1[i]!=str2[i])
{
printf("Strings are not anagrams \n",str1,str2);
return 0;
}
}
printf("Strings are anagrams\n");
return 0;
}
|
C
|
// Includes
#include <PA9.h> // Include for PA_Lib
// Function: main()
int main(int argc, char ** argv)
{
PA_Init(); // Initializes PA_Lib
PA_InitVBL(); // Initializes a standard VBL
PA_InitText(0,0);
PA_InitText(1,0);
PA_OutputText(0, 4, 1, "Text on the bottom screen!");
PA_OutputText(1, 5, 1, "Text on the top screen!");
// Infinite loop to keep the program running
while (1)
{
if (Pad.Newpress.A) PA_SetScreenLight(0, // screen
1); // Turn on bottom light
if (Pad.Newpress.B) PA_SetScreenLight(0, 0);
if (Pad.Newpress.X) PA_SetScreenLight(1, 1);// Turn on top light
if (Pad.Newpress.Y) PA_SetScreenLight(1, 0);
PA_WaitForVBL();
}
return 0;
} // End of main()
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
const int BUFFER_SIZE = 256;
int max(int a, int b)
{
if (a < b)
return b;
return a;
}
void* generate_random_stream(void* arg)
{
int current_size = 0;
char buffer[BUFFER_SIZE];
int bytes_read = 0;
printf("before loop in thread\n");
int i = 0;
while(i++ < 7)
{
while (current_size < BUFFER_SIZE*3/4)
{
bytes_read = snprintf(buffer+current_size, max(0, BUFFER_SIZE-current_size), "%d ", rand());
if (bytes_read == -1)
{
perror("snprintf");
break;
}
current_size += bytes_read;
}
printf("%s \n", buffer);
current_size = 0;
sleep(1);
}
pthread_detach(pthread_self());
printf("THREAD REACHED ITS END\n");
}
int main(int argc, char* argv[])
{
pthread_t t1;
pthread_create(&t1, NULL, &generate_random_stream, NULL);
int size_1 = __CHAR_BIT__*__CHAR_BIT__;
char str_1[size_1];
memset(&str_1, '-', size_1);
str_1[size_1] = '\0';
int i=0;
while(++i < 6)
{
sleep(1);
printf("MSG from main %d \n%s\n", i, str_1);
}
int result = 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "Tabla_hash.h"
/*Funcion Agregar_Definicion:
Se copian las cadenas de palabra y definicion
en una variable de tipo "elment" para insertarlas
después en la tabla hash dependiendo de
*/
void Agregar_Definicion(lista *colision, char *palabra, char *definicion)
{
element e;
int i=0;
while(palabra[i] != '\0'){
e.palabra[i] = palabra[i];
i++;
}
e.palabra[i] = '\0';
i=0;
while(definicion[i] != '\0'){
e.significado[i] = definicion[i];
i++;
}
e.significado[i] = '\0';
Insertar(colision,e);
}
/*
Menu de la practica 3
Con este menu se decide que
que operacion hacer con la tabla hash
*/
void menu()
{
printf("\n1.- Cargar un archivo de definiciones\n"
"2.- Agregar una palabra y su definici�n\n"
"3.- Buscar una palabra y ver su definici�n\n"
"4.- Modificar una definici�n\n"
"5.- Eliminar una palabra\n"
"6.- Mostrar Estadisticas\n"
"7.- Salir\n");
}
/*
Convierte la cadena leída del archivo a sus valores ASCII,
recibe la cadena y un arreglo de destino para estos valores.
*/
void Caracter_a_ASCII(char* cadena, int ascii[])
{
int i;
for(i=0; i<strlen(cadena); i++)
{
if(cadena[i]<0)
ascii[i]=(int)(MAX_VALOR_ASCII+cadena[i])+1; //Porque es un número negativo en cadena[]
else
ascii[i]= (int)cadena[i];
}
return;
}
/*
Convierte un numero decimal a binario,
recibe un entero, y devuelve un long con su equivalencia en base 2.
*/
long Dec_Bin(int numAscii)
{
long r_bin;
int i;
if(numAscii<2)
r_bin= numAscii;
else
r_bin= numAscii%2 + (10*Dec_Bin(numAscii/2));
return r_bin;
}
/*
Cuenta los digitos que contiene el número binario, es util para analizar
dicho numero y manipularlo,
recibe el binario en formato long, y devuelve un entero que representa
la cantidad de digitos (0 o 1) que lo componen.
*/
int CuentaDigitosDeBinario(long num)
{
int contador=1;
while(num/10>0)
{
num=num/10;
contador++;
}
return contador;
}
/*
Convierte un numero binario a decimal,
recibe un long, y devuelve un int con su equivalencia en base 10.
*/
int Bin_Dec(long numBin)
{
int r_dec=0, tam_bin, i;
int arrayNumBin[MAX_VALOR_ASCII];
//meter binario a la cadena de enteros para poder opoerarlo
tam_bin= CuentaDigitosDeBinario(numBin);
for(i=0; i<tam_bin; i++)
{
arrayNumBin[i]= numBin%10;
numBin= numBin/10;
}
//conversión a decimal
for(i=0; i<tam_bin; i++)
{
r_dec+= pow(2, i)*arrayNumBin[i];
}
return r_dec;
}
/*
Realiza la suma de los numero bianrios generados en las conversiones de
las funciones correcpondientes
*/
long Suma_Binaria(long numBin, long numInicial)
{
long suma;
int decNumBin, decNumInicial;
decNumBin= Bin_Dec(numBin);
decNumInicial= Bin_Dec(numInicial);
suma= Dec_Bin(decNumBin+decNumInicial);
//printf("suma: %d\n", suma);
return suma;
}
/*
Auxiliar para al comparacion de 0s y 1s, contiene la tabla de verdad de la compuerta XOR
*/
int Comparacion_XOR(int bitArraySuma, int bitAuxXOR)
{
int salidaXOR;
if(bitArraySuma==0 && bitAuxXOR==0)
salidaXOR=0;
if(bitArraySuma==0 && bitAuxXOR==1)
salidaXOR=1;
if(bitArraySuma==1 && bitAuxXOR==0)
salidaXOR=1;
if(bitArraySuma==1 && bitAuxXOR==1)
salidaXOR=0;
return salidaXOR;
}
/*
Realiza la comparacion de una seccion del arreglo inicial con un arreglo auxiliar,
de modo que surge una nueva expresion con una comparacion y/o.
*/
long Compuerta_XOR(long sumaBinaria)
{
long res_XOR;
int auxPreXOR[3], auxXOR[3];
int arraySumaBinaria[32]= {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
char charArraySumaBinaria[32];
int i, tam_bin;
//Meter binario a la cadena de enteros para poder operarlo
tam_bin= CuentaDigitosDeBinario(sumaBinaria);
//Insertar el numero binario en la ultima parte del arreglo
for(i=31; i>31-tam_bin; i--)
{
//printf("%d", i);
arraySumaBinaria[i]= sumaBinaria%10;
sumaBinaria= sumaBinaria/10;
}
printf("\n");
for(i=0; i<32; i++)
printf("%d", arraySumaBinaria[i]);
//Meter los primeros enteros de la cadena a un arreglo auxiliar previo a la comparacion XOR
for(i=0; i<3; i++)
auxPreXOR[i]=arraySumaBinaria[i];
/////////Realizacion de la operacion XOR
//Se compara una seccion de la cadena arraySumaBinaria con el previo del XOR
for(i=10; i<13; i++)
auxXOR[i-10]= Comparacion_XOR(arraySumaBinaria[i], auxPreXOR[i-10]);
//Se sustituye la seccion de la cadena original con la comparacion realizada
for(i=0; i<3; i++)
arraySumaBinaria[i+10]=auxXOR[i];
/////////
//Conversion auxiliar para transformar el arreglo de enteros a un solo entero
for(i=0; i<32; i++)
charArraySumaBinaria[i]= (char)(arraySumaBinaria[i]+48);
/*
for(i=0; i<32; i++)
printf("%d", charArraySumaBinaria[i]);
*/
res_XOR= atoi(charArraySumaBinaria);
return res_XOR;
}
/*
Realiza la acción de acomodar la palabra en la tabla hash
*/
int Operacion_Hash(long numBin, long* numInicial)
{
int ret, i, tam_bin;
int array0s[]= {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};//32 es el tamaño que naneja el simulador
long sumaBinaria;
sumaBinaria= Suma_Binaria(*numInicial, numBin);
printf("\nBinaria %ld", sumaBinaria);
*numInicial= Compuerta_XOR(sumaBinaria);
printf("\nNvo init %ld", (*numInicial));
ret= *numInicial%TAM_TABLA;
return ret;
}
|
C
|
/*
* $Id: commands.c 427 2009-08-13 17:48:06Z noah-w $
*
* This file contains a basic implementations of request
* you may send to Spotify's service.
*
*/
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "buf.h"
#include "channel.h"
#include "commands.h"
#include "packet.h"
#include "util.h"
/*
* Writes to /tmp
*
*/
static int dump_generic (CHANNEL * ch, unsigned char *buf, unsigned short len)
{
FILE *fd;
char filename[512];
if (len == 0)
return 0;
if (ch->state == CHANNEL_HEADER)
snprintf (filename, sizeof (filename),
"/tmp/channel-%d-%s.hdr-%d", ch->channel_id,
ch->name, ch->header_id);
else
snprintf (filename, sizeof (filename), "/tmp/channel-%d-%s",
ch->channel_id, ch->name);
if ((fd = fopen (filename, "ab")) != NULL) {
fwrite (buf, 1, len, fd);
fclose (fd);
return 0;
}
return -1;
}
int cmd_send_cache_hash (SESSION * session)
{
int ret;
struct buf* buf = buf_new();
buf_append_data(buf, session->cache_hash, sizeof (session->cache_hash));
ret = packet_write (session, 0x0f, buf->ptr, buf->len);
DSFYDEBUG ("packet_write() returned %d\n", ret);
buf_free(buf);
return ret;
}
/*
* Request ads
* The response is plain XML
*
*/
int cmd_requestad (SESSION * session, unsigned char ad_type)
{
CHANNEL *ch;
int ret;
char buf[100];
struct buf* b = buf_new();
snprintf (buf, sizeof (buf), "RequestAd-with-type-%d", ad_type);
ch = channel_register (buf, dump_generic, NULL);
DSFYDEBUG
("allocated channel %d, retrieving ads with type id %d\n",
ch->channel_id, ad_type);
buf_append_u16(b, ch->channel_id);
buf_append_u8(b, ad_type);
ret = packet_write (session, CMD_REQUESTAD, b->ptr, b->len);
DSFYDEBUG ("packet_write() returned %d\n", ret);
buf_free(b);
return ret;
}
/*
* Request image using a 20 byte hash
* The response is a JPG
*
*/
int cmd_request_image (SESSION * session, unsigned char *hash,
channel_callback callback, void *private)
{
CHANNEL *ch;
int ret;
char buf[100];
struct buf* b = buf_new();
strcpy (buf, "image-");
hex_bytes_to_ascii (hash, buf + 6, 20);
ch = channel_register (buf, callback, private);
DSFYDEBUG
("allocated channel %d, retrieving img with UUID %s\n",
ch->channel_id, buf + 6);
buf_append_u16(b, ch->channel_id);
buf_append_data(b, hash, 20);
ret = packet_write (session, CMD_IMAGE, b->ptr, b->len);
DSFYDEBUG ("packet_write() returned %d\n", ret);
buf_free(b);
return ret;
}
/*
* Search music
* The response comes as compressed XML
*
*/
int cmd_search (SESSION * session, char *searchtext, unsigned int offset,
unsigned int limit, channel_callback callback, void *private)
{
CHANNEL *ch;
int ret;
char buf[100];
unsigned char searchtext_length;
assert (limit);
struct buf* b = buf_new();
snprintf (buf, sizeof (buf), "Search-%s", searchtext);
ch = channel_register (buf, callback, private);
DSFYDEBUG ("allocated channel %d, searching for '%s'\n",
ch->channel_id, searchtext);
buf_append_u16(b, ch->channel_id);
buf_append_u32(b, offset);
buf_append_u32(b, limit);
buf_append_u16(b, 0);
searchtext_length = (unsigned char) strlen (searchtext);
buf_append_u8(b, searchtext_length);
buf_append_data(b, searchtext, searchtext_length);
ret = packet_write (session, CMD_SEARCH, b->ptr, b->len);
DSFYDEBUG ("packet_write() returned %d\n", ret)
buf_free(b);
return ret;
}
/*
* Notify server we're going to play
*
*/
int cmd_token_notify (SESSION * session)
{
int ret;
ret = packet_write (session, CMD_TOKENNOTIFY, NULL, 0);
if (ret != 0) {
DSFYDEBUG ("packet_write(cmd=0x4f) returned %d, aborting!\n",
ret)
}
return ret;
}
int cmd_aeskey (SESSION * session, unsigned char *file_id,
unsigned char *track_id, channel_callback callback,
void *private)
{
int ret;
CHANNEL *ch;
char buf[256];
/* Request the AES key for this file by sending the file ID and track ID */
struct buf* b = buf_new();
buf_append_data(b, file_id, 20);
buf_append_data(b, track_id, 16);
buf_append_u16(b, 0);
/* Allocate a channel and set its name to key-<file id> */
strcpy (buf, "key-");
hex_bytes_to_ascii (file_id, buf + 4, 20);
ch = channel_register (buf, callback, private);
DSFYDEBUG
("allocated channel %d, retrieving AES key for file '%.40s'\n",
ch->channel_id, buf);
/* Force DATA state to be able to handle these packets with the channel infrastructure */
ch->state = CHANNEL_DATA;
buf_append_u16(b, ch->channel_id);
ret = packet_write (session, CMD_REQKEY, b->ptr, b->len);
buf_free(b);
if (ret != 0) {
DSFYDEBUG ("packet_write(cmd=0x0c) returned %d, aborting!\n", ret)
}
return ret;
}
/*
* A demo wrapper for playing a track
*
*/
int cmd_action (SESSION * session, unsigned char *file_id,
unsigned char *track_id)
{
int ret;
/*
* Notify the server about our intention to play music, there by allowing
* it to request other players on the same account to pause.
*
* Yet another client side restriction to annoy those who share their
* Spotify account with not yet invited friends.
* And as a bonus it won't play commercials and waste bandwidth in vain.
*
*/
if ((ret =
packet_write (session, CMD_REQUESTPLAY, (unsigned char *) "",
0)) != 0) {
DSFYDEBUG ("packet_write(0x4f) returned %d, aborting!\n",
ret)
return ret;
}
#ifdef P2P
/* Request a 100 byte P2P initialization block */
struct buf* b = buffer_new();
buf_append_data(b, file_id, 20);
ret = packet_write (session, 0x20, b->ptr, b->len);
bufr_free(b);
if (ret != 0) {
DSFYDEBUG ("packet_write(cmd=0x20) returned %d, aborting!\n",
ret);
return ret;
}
#endif
/* Request the AES key for this file by sending the file ID and track ID */
return cmd_aeskey (session, file_id, track_id, dump_generic, NULL);
}
/*
* Request a part of the encrypted file from the server.
*
* The data should be decrypted using the AES in CTR mode
* with AES key provided and a static IV, incremeted for
* each 16 byte data processed.
*
*/
int cmd_getsubstreams (SESSION * session, unsigned char *file_id,
unsigned int offset, unsigned int length,
unsigned int unknown_200k, channel_callback callback,
void *private)
{
char buf[512];
CHANNEL *ch;
int ret;
hex_bytes_to_ascii (file_id, buf, 20);
ch = channel_register (buf, callback, private);
DSFYDEBUG
("cmd_getsubstreams: allocated channel %d, retrieving song '%s'\n",
ch->channel_id, ch->name);
struct buf* b = buf_new();
buf_append_u16(b, ch->channel_id);
/* I have no idea wtf these 10 bytes are for */
buf_append_u16(b, 0x0800);
buf_append_u16(b, 0x0000);
buf_append_u16(b, 0x0000);
buf_append_u16(b, 0x0000);
buf_append_u16(b, 0x4e20); /* drugs are bad for you, m'kay? */
buf_append_u32(b, unknown_200k);
buf_append_data(b, file_id, 20);
assert (offset % 4096 == 0);
assert (length % 4096 == 0);
offset >>= 2;
length >>= 2;
buf_append_u32(b, offset);
buf_append_u32(b, offset + length);
hex_bytes_to_ascii (file_id, buf, 20);
DSFYDEBUG
("Sending GetSubstreams(file_id=%s, offset=%u [%u bytes], length=%u [%u bytes])\n",
buf, offset, offset << 2, length, length << 2);
ret = packet_write (session, 0x08, b->ptr, b->len);
buf_free(b);
if (ret != 0) {
channel_unregister (ch);
DSFYDEBUG
("packet_write(cmd=0x08) returned %d, aborting!\n",
ret);
}
DSFYDEBUG("end\n");
return ret;
}
/*
* Get metadata for an artist (kind=1), an album (kind=2) or a list of tracks (kind=3)
* The response comes as compressed XML
*
*/
int cmd_browse (SESSION * session, unsigned char kind, unsigned char *idlist,
int num, channel_callback callback, void *private)
{
CHANNEL *ch;
char buf[256];
int i, ret;
assert (((kind == BROWSE_ARTIST || kind == BROWSE_ALBUM) && num == 1)
|| kind == BROWSE_TRACK);
strcpy (buf, "browse-");
hex_bytes_to_ascii(idlist, buf + 7, 16);
ch = channel_register (buf, callback, private);
struct buf* b = buf_new();
buf_append_u16(b, ch->channel_id);
buf_append_u8(b, kind);
for (i = 0; i < num; i++)
buf_append_data(b, idlist + i * 16, 16);
if (kind == BROWSE_ALBUM || kind == BROWSE_ARTIST) {
assert (num == 1);
buf_append_u32(b, 0);
}
if ((ret =
packet_write (session, CMD_BROWSE, b->ptr, b->len)) != 0) {
DSFYDEBUG
("packet_write(cmd=0x30) returned %d, aborting!\n",
ret)
}
buf_free(b);
return ret;
}
/*
* Request playlist details
* The response comes as plain XML
*
*/
int cmd_getplaylist (SESSION * session, unsigned char *playlist_id,
int revision, channel_callback callback, void *private)
{
CHANNEL *ch;
char buf[256];
int ret;
strcpy (buf, "playlist-");
hex_bytes_to_ascii (playlist_id, buf + 9, 17);
buf[9 + 2 * 17] = 0;
ch = channel_register (buf, callback, private);
struct buf* b = buf_new();
buf_append_u16(b, ch->channel_id);
buf_append_data(b, playlist_id, 17);
buf_append_u32(b, revision);
buf_append_u32(b, 0);
buf_append_u32(b, 0xffffffff);
buf_append_u8(b, 0x1);
if ((ret =
packet_write (session, CMD_GETPLAYLIST, b->ptr, b->len)) != 0) {
DSFYDEBUG
("packet_write(cmd=0x35) returned %d, aborting!\n",
ret);
}
buf_free(b);
return ret;
}
/*
* Modify playlist
* The response comes as plain XML
*/
int cmd_changeplaylist (SESSION * session, unsigned char *playlist_id,
char *xml, int revision, int num_tracks, int checksum,
int collaborative, channel_callback callback,
void *private)
{
CHANNEL *ch;
char buf[256];
int ret;
strcpy (buf, "chplaylist-");
hex_bytes_to_ascii (playlist_id, buf + 11, 17);
buf[11 + 2 * 17] = 0;
ch = channel_register (buf, callback, private);
struct buf* b = buf_new();
buf_append_u16(b, ch->channel_id);
buf_append_data(b, playlist_id, 17);
buf_append_u32(b, revision);
buf_append_u32(b, num_tracks);
buf_append_u32(b, checksum); /* -1=create playlist */
buf_append_u8(b, collaborative);
buf_append_u8(b, 3); /* Unknown */
buf_append_data(b, xml, strlen(xml));
if ((ret =
packet_write (session, CMD_CHANGEPLAYLIST, b->ptr, b->len)) != 0) {
DSFYDEBUG ("packet_write(cmd=0x36) "
"returned %d, aborting!\n", ret);
}
buf_free(b);
return ret;
}
int cmd_ping_reply (SESSION * session)
{
int ret;
unsigned long pong = 0;
if ((ret = packet_write (session, CMD_PONG, (void*)&pong, 4)) != 0) {
DSFYDEBUG
("packet_write(cmd=0x49) returned %d, aborting!\n",
ret);
}
return ret;
}
|
C
|
/**
* Stack data structure implementation and demonstration
*
* Author: Gediminas Rapolavicius <[email protected]>
* Website: http://github.com/GedRap
*/
#include "stack.h"
#include <stdio.h>
/**
* Demonstration of the stack implementation
*/
int main() {
Stack_Item *item1 = stack_item_create(1);
Stack_Item *item2 = stack_item_create(3);
printf("[DEBUG] Stack Item 2 at %p\n", item2);
Stack *stack = stack_create(5);
stack_dump(stack);
stack_push(stack, item1);
stack_push(stack, item2);
printf("Stack after pushing\n");
stack_dump(stack);
Stack_Item *popped = stack_pop(stack);
printf("[DEBUG] Popped item at %p (expected %p)\n", popped, item2);
int popped_value = stack_item_get_val(popped);
printf("[DEBUG] Expected to pop 3, popped %d\n", popped_value);
printf("[DEBUG] Stack after popping\n");
stack_dump(stack);
return 1;
}
|
C
|
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#ifdef S_BLKSIZE
#define BL_SIZE S_BLKSIZE
#else
#include <sys/param.h>
#define BL_SIZE DEV_BSIZE
#endif
int main(int argc, char *argv[])
{
if (argc != 2){
printf("Usage: %s some.file\n", argv[0]);
return 1;
}
struct stat stat_buf;
if (lstat(argv[1], &stat_buf) == -1){
perror("Failed to stat");
return 2;
}
printf("File: \"%s\"\n", argv[0]);
printf("Type: ");
switch (stat_buf.st_mode & S_IFMT) {
case S_IFBLK: printf("block device\n"); break;
case S_IFCHR: printf("character device\n"); break;
case S_IFDIR: printf("directory\n"); break;
case S_IFIFO: printf("FIFO/pipe\n"); break;
case S_IFLNK: printf("symlink\n"); break;
case S_IFREG: printf("regular file\n"); break;
case S_IFSOCK: printf("socket\n"); break;
default: printf("unknown?\n"); break;
}
printf("Size: %llu\n", (unsigned long long)stat_buf.st_size);
printf("Used space: %llu\n", (unsigned long long)stat_buf.st_blocks * BL_SIZE);
printf("UID: %d\n", stat_buf.st_uid);
printf("GID: %d\n", stat_buf.st_gid);
printf("atime: %ld sec %ld nanosec\n", stat_buf.st_atimespec.tv_sec, stat_buf.st_atimespec.tv_nsec);
printf("mtime: %ld sec %ld nanosec\n", stat_buf.st_mtimespec.tv_sec, stat_buf.st_mtimespec.tv_nsec);
printf("ctime: %ld sec %ld nanosec\n", stat_buf.st_ctimespec.tv_sec, stat_buf.st_ctimespec.tv_nsec);
return 0;
}
|
C
|
/* Disabling epilogues until we find a better way to deal with scans. */
/* { dg-additional-options "--param vect-epilogues-nomask=0" } */
/* { dg-require-effective-target vect_int } */
#include <stdarg.h>
#include "tree-vect.h"
#define N 128
int c[N];
/* Vectorization of reduction using loop-aware SLP. */
__attribute__ ((noinline))
int main1 (int n, int res0, int res1)
{
int i;
int max0 = -100, max1 = -313;
for (i = 0; i < n; i++) {
max1 = max1 < c[2*i+1] ? c[2*i+1] : max1;
max0 = max0 < c[2*i] ? c[2*i] : max0;
}
/* Check results: */
if (max0 != res0
|| max1 != res1)
abort ();
return 0;
}
int main (void)
{
int i;
check_vect ();
for (i = 0; i < N; i++)
c[i] = (i+3) * -1;
c[0] = c[1] = -100;
main1 (N/2, -5, -6);
return 0;
}
/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 2 "vect" { xfail vect_no_int_min_max } } } */
/* { dg-final { scan-tree-dump-times "vectorizing stmts using SLP" 1 "vect" { xfail vect_no_int_min_max } } } */
/* { dg-final { scan-tree-dump-times "VEC_PERM_EXPR" 0 "vect" } } */
|
C
|
/***************************************************************************
* Organisation : Kernel Masters, KPHB, Hyderabad, India. *
* facebook page : www.facebook.com/kernelmasters *
* *
* Conducting Workshops on - Embedded Linux & Device Drivers Training. *
* ------------------------------------------------------------------- *
* Tel : 91-9949062828, Email : [email protected] *
* *
***************************************************************************
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation. No warranty is attached; we cannot take *
* responsibility for errors or fitness for use. *
***************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
int main()
{
int fd, count;
char buff="12345";
fd = open("/dev/MyChar", O_RDWR);
printf("fd:%d\n", fd);
count = write(fd,buff,2);
printf("count:%d\n", count);
count = read(fd,buff,2);
printf("count:%d\n", count);
}
|
C
|
/// @file
/// Test QR Factorization
/// \test Test QR Factorization
#include <ceed.h>
int main(int argc, char **argv) {
Ceed ceed;
CeedScalar qr[12] = {1, -1, 4, 1, 4, -2, 1, 4, 2, 1, -1, 0};
CeedScalar tau[3];
CeedInit(argv[1], &ceed);
CeedQRFactorization(ceed, qr, tau, 4, 3);
for (int i=0; i<12; i++) {
if (qr[i] <= 1E-14 && qr[i] >= -1E-14) qr[i] = 0;
fprintf(stdout, "%12.8f\n", qr[i]);
}
for (int i=0; i<3; i++) {
if (tau[i] <= 1E-14 && tau[i] >= -1E-14) tau[i] = 0;
fprintf(stdout, "%12.8f\n", tau[i]);
}
CeedDestroy(&ceed);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#define N 100000
int main()
{
char s[90][90];
int i,j,t=0;
while(scanf("%s",&s[t])!=EOF)
{
t++;
if(getchar()=='\n')
break;
}
for(j=t-1;j>=0;j--)
{
printf("%s",s[j]);
if(j>0) printf(" ");
}
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef int /*<<< orphan*/ ulg ;
typedef char uch ;
typedef int /*<<< orphan*/ FILE ;
/* Variables and functions */
int bit_depth ;
int channels ;
int color_type ;
int /*<<< orphan*/ fgets (char*,int,int /*<<< orphan*/ *) ;
int /*<<< orphan*/ fprintf (int /*<<< orphan*/ ,char*,...) ;
int /*<<< orphan*/ height ;
int /*<<< orphan*/ * saved_infile ;
int /*<<< orphan*/ sscanf (char*,char*,int*,...) ;
int /*<<< orphan*/ stderr ;
int /*<<< orphan*/ width ;
int readpng_init(FILE *infile, ulg *pWidth, ulg *pHeight)
{
static uch ppmline[256];
int maxval;
saved_infile = infile;
fgets(ppmline, 256, infile);
if (ppmline[0] != 'P' || ppmline[1] != '6') {
fprintf(stderr, "ERROR: not a PPM file\n");
return 1;
}
/* possible color types: P5 = grayscale (0), P6 = RGB (2), P8 = RGBA (6) */
if (ppmline[1] == '6') {
color_type = 2;
channels = 3;
} else if (ppmline[1] == '8') {
color_type = 6;
channels = 4;
} else /* if (ppmline[1] == '5') */ {
color_type = 0;
channels = 1;
}
do {
fgets(ppmline, 256, infile);
} while (ppmline[0] == '#');
sscanf(ppmline, "%lu %lu", &width, &height);
do {
fgets(ppmline, 256, infile);
} while (ppmline[0] == '#');
sscanf(ppmline, "%d", &maxval);
if (maxval != 255) {
fprintf(stderr, "ERROR: maxval = %d\n", maxval);
return 2;
}
bit_depth = 8;
*pWidth = width;
*pHeight = height;
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main ()
{
char name[30];
float grade;
int sec;
printf("Enter your name\n");
scanf("%s",&name);
printf("Enter your section\n");
scanf("%d",&sec);
printf("Enter your GPA\n");
scanf("%f",&grade);
printf("Hello %s\n",name);
printf("Your section is %d and GPA is %.2f\n\n",sec,grade);
system("PAUSE");
return 0;
}
|
C
|
/*
Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1.
For example, with A = "abcd" and B = "cdabcdab".
Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; and B is not a substring of A repeated two times ("abcdabcd").
Note:
The length of A and B will be between 1 and 10000.
*/
class Solution {
public:
int repeatedStringMatch(string A, string B) {
string tmp= A;
for(int i =1; i<= B.size()/ A.size() +2; ++i){
if(tmp.find(B) != string::npos)
return i;
tmp+=A;
}
return -1;
}
};
|
C
|
/** retorna um caractere */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tokens.h"
#include "symbol_table.h"
symbol_t stable;
#include "comfet.c"
#include "stack.c"
int main(int argc, char* argv[]) {
int token;
//Não Terminais
int const E = 11;
int const X = 12;
//Terminais
int sADD = ADD;
int sSUB = SUB;
int sMULT = MULT;
int sDIV = DIV;
int sA_PAR = A_PAR;
int sF_PAR = F_PAR;
int sIDF = IDF;
int sINT_LIT = INT_LIT;
int sF_LIT = F_LIT;
int sVAZIO = VAZIO;
//Tabela de símbolo
init_table( &stable );
//Tabela Sintática M
//Ordem SIMBOLO '(' ')' '+' '-' '*' '/' F_LIT INT_LIT IDF $
//E
//X
int M[2][10] = {{1,0,0,0,0,0,4,3,2,0},{0,9,5,6,7,8,0,0,0,9}}; //Valores representam as regras da grámatica (Arquivo grámatica contém as regras)
int produzido; //Resultado da consulta da tabela M[x][a], onde x = Nao_Terminal / a = Terminal
//Declara e inicia PIlha com E (valor de start)
stack pilha;
push(&pilha,(void*) &E);
int* symbol_stack = NULL; //variável que recebe valor da pilha a partir do pop pop;
//BUffer (Carrega arquivo txt)
yyin = fopen("test.txt", "r"); //passar arquivo por cmd
if(!yyin) {
printf("Error: could not find file !\n");
exit(-1);
}
// Busca token para iniciar análise
token = yylex();
//Comeca Análise Sintática
/*Lembrar 3 Possibilidade
A = Valor do Buffer
X = Valor desempilhado
Sendo X Terminais:
1) X = A = $(vazio), FIM
2) X = A != $, remove X, avança a (chama yylex())
Sendo X Não-Terminais:
3) Consulta tabele M[X,A], subst. X pelo valor produzido.
*/
if(token > 0){ //se token == 0 significa o fim do fluxo de entrada ou não existe mais token para ser chamado.
while(empty(pilha) == 0){ //enquanto pilha nao estiver cheia, aqui busca-se zerar a pilha e o fluxo de entrada juntos.
symbol_stack = (int*) pop(&pilha);
printf("Valor desempilhado: %i.\n ", *symbol_stack);
printf("Valor BUffer: %i.\n ", token);
if(*symbol_stack == E || *symbol_stack == X){ //Verifica é Não_Terminal: Case 3.
produzido = M[(*symbol_stack)- 11][token - 1]; // -11 PORQUE os valores da matriz começa de 0 e as das variáveis terinais começa de 11. // -1 E PORQUE os valores da matriz começa de 0 e as das variáveis terinais começa de 1.
printf("M[%i][%i].\n ", (*symbol_stack)- 11, token - 1);
printf("Produzido: %i.\n ", produzido);
//verificar os casos que são as regras da gramática
if(produzido == 1){// 1) E -> '(' E ')' X
push(&pilha,(void*) &X);
push(&pilha,(void*) &sF_PAR);
push(&pilha,(void*) &E);
push(&pilha,(void*) &sA_PAR);
}
else if(produzido == 2){
// 2) E -> IDF X
push(&pilha,(void*) &X);
push(&pilha,(void*) &sIDF);
}
else if(produzido == 3){// 3) E -> INT_LIT X
push(&pilha,(void*) &X);
push(&pilha,(void*) &sINT_LIT);
}
else if(produzido == 4){// 4) E -> F_LIT X
push(&pilha,(void*) &X);
push(&pilha,(void*) &sF_LIT);
}
else if(produzido == 5){// 5) X -> '+' E
push(&pilha,(void*) &E);
push(&pilha,(void*) &sADD);
}
else if(produzido == 6){// 6) X -> '-' E
push(&pilha,(void*) &E);
push(&pilha,(void*) &sSUB);
}
else if(produzido == 7){// 7) X -> '*' E
push(&pilha,(void*) &E);
push(&pilha,(void*) &sMULT);
}
else if(produzido == 8){// 8) X -> '/' E
push(&pilha,(void*) &E);
push(&pilha,(void*) &sDIV);
}
else if(produzido == 9){// 9) X -> &
push(&pilha,(void*) &sVAZIO);
}
else {
printf("ERROR, PRUDUÇÃO ERRADA.\n");
exit(0);
}
}// Verificar é um Terminal: Caso 1 e 2;
else{
if(*symbol_stack == token ){ //CASO 1 e 2
printf("SAIU DO BUFFER %i e da Pilha %i.\n", token, *symbol_stack);
token = yylex();
if(token == 0){token = sVAZIO;
if(*symbol_stack==10){printf("Okay.\n");break;}
}
}
else if(*symbol_stack != token && *symbol_stack == sVAZIO){ //VAZIO
}
else{ // ERRO
printf("ERROR, VALOR NAO DEFINIDO");
exit(0);
}
}
}
}
fclose(yyin);
return(0);
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
// questo programma stampa :
// the quick brown fox jumped over the lazy dogs
// the quick brown fox jumped over the lazy dogs
// perché non è stato fatto il flush dello stdout
int main (void) {
printf("The quick brown fox jumped over ");
//fflush(stdout);
fork();
printf("the lazy dogs\n");
return 0;
}
|
C
|
#include "invArray.h"
struct invArray_s{
inv_t *vettInv;
int nInv,maxInv;
};
invArray_t invArray_init(){
invArray_t invArray = (invArray_t) malloc(sizeof (struct invArray_s));
invArray->nInv = 0;
invArray->vettInv = NULL;
return invArray;
}
void invArray_read(FILE *fp, invArray_t invArray){
assert(fp != NULL);
fscanf(fp,"%d",&invArray->nInv);
invArray->maxInv = invArray->nInv;
invArray->vettInv = (inv_t *) malloc(invArray->nInv * sizeof (inv_t));
invArray->nInv = 0;
while (invArray->nInv < invArray->maxInv &&
inv_read(fp,&invArray->vettInv[invArray->nInv++]));
}
void invArray_free(invArray_t invArray){
free(invArray->vettInv);
free(invArray);
}
void invArray_print(FILE *fp, invArray_t invArray){
int i;
for(i=0; i<invArray->nInv; i++) {
fprintf(fp,"%2d >",i);
inv_print(fp, invArray_getByIndex(invArray, i), mode_inv);
}
}
void invArray_printByIndex(FILE *fp, invArray_t invArray, int index){
if(index >= 0 && index< invArray->maxInv)
inv_print(fp,invArray_getByIndex(invArray,index),mode_inv);
else fprintf(fp,"INDICE %d non presente in struttura dati\n",index);
}
inv_t *invArray_getByIndex(invArray_t invArray, int index){
return &invArray->vettInv[index];
}
int invArray_searchByName(invArray_t invArray, INV_KEY name){
int i;
for(i=0; i<invArray->nInv; i++)
if(INV_KEY_eq(name,inv_getKey(invArray_getByIndex(invArray,i))))
return i;
return -1;
}
|
C
|
/*
MILESTONE 3
MAIN PROGRAM
Name of the group : PRASTAV
Members of the group : 19ucs160 Aashita Agrawal
19ucs162 Pranjal Gupta
19uec070 Vedang Trivedi
19uec168 Aakash Taneja
19uec121 Ritisha Garg
19ucc088 Sai Shruti
19ume012 Tanishka Garg
Date the file was submitted : 19.04.2020
The purpose of the game program is to form and declare the best word (word with maximum score) using a bag of letters given as input.
DETAILS : In this milestone(3) we are given a bag of letters and are required to find a word from dictionary with maximum possible score.
METHOD :
SWITCH CASE : The file with name i.txt contains all the words which have length>=2 and length<=i
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <time.h>
int from_bag(char letters[], char word_copy[]);
int cal_weight(char word_copy[]);
int cal_score(int weight, int letter_len, int word_len);
|
C
|
#include "stdio.h"
int main(void){
int i,j;
for (i = 5, j = i - 1; i > 0, j > 0; --i , j = i - 1)
printf("%d ", i);// 5 4 3 2
printf("\n");
}
|
C
|
#define MAX 100
#define TRUE 1
#define FALSE 0
/* By: Jeferson da Silva Juliani
* Universidade Federal of Ceará
*/
typedef struct list{
int item[MAX];
int p;
}List;
// This function creat a list of integer, and returns a pointer of List
List* creatList();
/* This function takes as parameter an List 'x' and returns 0 for error
* and 1 for correct. It's function is to check if the List is full.
*/
int fullist(List* x);
/* This function takes as parameter an integer 'y' and a type List,
* and returns 0 for error or 1 for correct. It's function is adds
* this 'y' at the start of the List.
*/
int addStart(List* x,int y);
/* This function takes as parameter an integer 'y' and a type List,
* and returns 0 for error or 1 for correct. It's function is adds
* this 'y' at the end of the List.
*/
int addEnd(List* x,int y);
/* This function takes as parameter an integer 'y' and a type List,
* and returns 0 for error or 1 for correct. It's function is adds
* this 'y' in the list of way ordered.
*/
int addSort(List* x,int y);
// This function takes as parameter an List 'x' and free this List.
void freelist(List* x);
// This function takes as parameter an List 'x' and print this List.
void printList(List* x);
/* This function takes as parameter an List 'x' and a integer 'pos'.
* It's function is to move the positions of the List for left.
*/
void move(List* x,int pos);
/* This function takes as parameter an List 'x' and a integer 'elem'.
* It's function is to remove the element of the List.
*/
int removeElem(List* x, int elem);
/* This function takes as parameter an List 'x' and a integer 'elem',
* and returns the position of 'elem' in the List or -1 for element no found.
*/
int position(List* x,int elem);
|
C
|
#include <stdio.h>
int main(void) {
int c;
printf("Enter a character:");
c=getchar();
printf("%c--->hex%x\n", c, c);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#include "graphics.h"
#include "paramater.h"
#include "gameWorldGenerate.h"
#include "aiStrategy.h"
extern GLubyte world[WORLDX][WORLDY][WORLDZ];
/* viewpoint control */
extern void getViewPosition(float *, float *, float *);
extern void getOldViewPosition(float *, float *, float *);
/* mob controls */
extern void createMob(int, float, float, float, float);
extern void setMobPosition(int, float, float, float, float);
extern void hideMob(int);
extern void showMob(int);
/* mesh creation, translatio, rotation functions */
extern void unsetMeshID(int);
extern void setTranslateMesh(int, float, float, float);
extern void setRotateMesh(int, float, float, float);
extern void setScaleMesh(int, float);
extern void drawMesh(int);
extern void hideMesh(int);
void aiStatus() {
for (int i = 0; i < 9; i++) {
if (currentMonsterObj[i].item == 3 || currentMonsterObj[i].item == 2 || currentMonsterObj[i].item == 1) {
cactusMove(i);
}
}
}
void cactusMove(int itemId) {
int upperXrange = currentMonsterObj[itemId].x + 1;
int lowerXrange = currentMonsterObj[itemId].x - 1;
int upperZrange = currentMonsterObj[itemId].z + 1;
int lowerZrange = currentMonsterObj[itemId].z - 1;
float x, y, z;
int x_int, y_int, z_int;
getOldViewPosition(&x, &y, &z);
x_int = (int)x * -1;
y_int = (int)y * -1;
z_int = (int)z * -1;
if ((lowerXrange <= x_int && x_int <= upperXrange) && (lowerZrange <= z_int && z_int <= upperZrange)) {
//printf("%d, %d, %d, %d, %d. %d", upperXrange, lowerXrange,upperZrange, lowerZrange, x_int, z_int);
srand(time(NULL));
int result = rand() % 2;
if (currentMonsterObj[itemId].isAlive == 1) {
if (result == 0) {
if (currentMonsterObj[itemId].item == 1) {
printf("fish(room %d) attack Status: Missed\n", itemId);
} else if (currentMonsterObj[itemId].item == 2) {
printf("bat(room %d) attack Status: Missed\n", itemId);
} else if (currentMonsterObj[itemId].item == 3) {
printf("cactus(room %d) attack Status: Missed\n", itemId);
}
} else if (result == 1) {
if (currentMonsterObj[itemId].item == 1) {
printf("fish(room %d) attack Status: hit\n", itemId);
} else if (currentMonsterObj[itemId].item == 2) {
printf("bat(room %d) attack Status: hit\n", itemId);
} else if (currentMonsterObj[itemId].item == 3) {
printf("cactus(room %d) attack Status: hit\n", itemId);
}
}
}
}
}
|
C
|
/* queue.c
Implementation of a FIFO queue abstract data type.
by: Steven Skiena
begun: March 27, 2002
*/
/*
Copyright 2003 by Steven S. Skiena; all rights reserved.
Permission is granted for use in non-commerical applications
provided this copyright notice remains intact and unchanged.
This program appears in my book:
"Programming Challenges: The Programming Contest Training Manual"
by Steven Skiena and Miguel Revilla, Springer-Verlag, New York 2003.
See our website www.programming-challenges.com for additional information.
This book can be ordered from Amazon.com at
http://www.amazon.com/exec/obidos/ASIN/0387001638/thealgorithmrepo/
*/
#include "queue.h"
void init_queue(queue *q)
{
q->first = 0;
q->last = QUEUESIZE-1;
q->count = 0;
}
void enqueue(queue *q, Bus_data x)
{
q->last = (q->last+1) % QUEUESIZE;
q->q[ q->last ] = x;
q->count = q->count + 1;
}
Bus_data dequeue(queue *q)
{
Bus_data x;
x = q->q[ q->first ];
q->first = (q->first+1) % QUEUESIZE;
q->count = q->count - 1;
return x;
}
bool empty(queue *q)
{
if (q->count <= 0) return true;
else return false;
}
|
C
|
include "holberton.h"
/**
* print_triangle - print a triangle
* @size: square dimensions
*
*/
void print_triangle(int size)
{
int a, b;
if (size <= 0)
{
_putchar('\n');
}
else
{
a = 0;
while (a < size)
{
b = 0;
while (b < size)
{
if (a < size - b - 1)
_putchar(32);
else
_putchar(35);
b++;
}
a++;
_putchar(10);
}
}
}
|
C
|
/*
** EPITECH PROJECT, 2019
** line
** File description:
** line
*/
#include "my.h"
int line_nbpipe(int line, char **tab)
{
int i = 0;
int out = 0;
while (tab[line][i] != '\0') {
if (tab[line][i] == '|')
out += 1;
i = i + 1;
}
return (out);
}
int check_empty(char *buff)
{
if (buff[0] == '\n')
return (1);
return (0);
}
int count_line_difflen(char **tab, int len)
{
int i = 0;
int a = 0;
while (tab[i] != NULL) {
if (line_nbpipe(i, tab) != len)
a = a + 1;
i = i + 1;
}
return (a);
}
int count_line_len(char **tab, int len)
{
int i = 0;
int a = 0;
while (tab[i] != NULL) {
if (line_nbpipe(i, tab) == len)
a = a + 1;
i = i + 1;
}
return (a);
}
int count_line_betlen(char **tab, int min, int max)
{
int i = 0;
int a = 0;
while (tab[i] != NULL) {
if (line_nbpipe(i, tab) > min && line_nbpipe(i, tab) <= max)
a = a + 1;
i = i + 1;
}
return (a);
}
|
C
|
//
// Complex.h
// Complex Numbers
//
// Created by Daniel Shterev on 19.02.20.
// Copyright © 2020 Daniel Shterev. All rights reserved.
//
#ifndef Complex_h
#define Complex_h
struct Complex
{
int real ;
int imaginary ;
} ;
Complex add(Complex a, Complex b) ;
Complex multiply (Complex a, Complex b) ;
#endif /* Complex_h */
|
C
|
#include "lists.h"
#include <stdio.h>
#include <string.h> /* use strlen & strdup*/
#include <stdlib.h> /* use NULL*/
/**
* add_node - adds a new node at the beginning
* @head: first node
* @str: string
* Return: & of the new node || NULL
*/
list_t *add_node(list_t **head, const char *str)
{
list_t *nw_node;
nw_node = malloc(sizeof(list_t)); /* Reserve memory*/
if (nw_node == NULL) /* In case of error = NULL*/
return (NULL);
nw_node->len = _strlen(str); /*->len stores the length of str*/
nw_node->str = strdup(str); /*->str stores a str duplicate*/
nw_node->next = *head; /*->next is the head, first node*/
*head = nw_node; /*we have to print head from the main.c*/
return (nw_node); /* Address of the new element*/
}
/**
* _strlen - function that returns the length of a string.
* @s : s is a character
* Return: value is i
*/
int _strlen(const char *s)
{
int i;
while (*(s + i))
{
i++;
}
return (i);
}
|
C
|
#include "libft.h"
void ft_bzero(void *b, size_t len)
{
size_t i;
unsigned char *tmp;
i = 0;
tmp = (unsigned char *)b;
while (i < len)
tmp[i++] = 0;
}
|
C
|
#include <stdio.h>
int main() {
int arr1[3][3] = {
{2, 3, 0},
{8, 9, 1},
{7, 0, 5}
};
int arr2[3][3] = {
{1, 0, 0},
{1, 0, 0},
{1, 0, 0}
};
int sum[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
sum[i][j] = arr1[i][j] + arr2[i][j];
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", sum[i][j]);
}
printf("\n");
}
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include"contact.h"
//ͨѶ¼
//ʼͨѶ¼
void menu()
{
printf("-----------------------------\n");
printf("------- 1.add 2.del ---\n");
printf("------- 3.search 4.change---\n");
printf("------- 5.sort 6.print ---\n");
printf("------- 0.exit ---\n");
printf("-----------------------------\n");
}
int main()
{
int input = 0;
Contact con;
InnitContact(&con);//ʼ
menu();
do
{
printf("ѡ");
scanf("%d", &input);
switch (input)
{
case 1:
Add(&con);
break;
case 2:
Del(&con);
break;
case 3:
Search(&con);
break;
case 4:
Change(&con);
break;
case 5:
Sort(&con);//- С ӴС
break;
case 6:
Print(&con);
break;
case 0:
exit(1);
break;
default:
printf("ѡѡ");
break;
}
} while (input);
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
char marks[3];
marks[0]=65;
marks[1]=75;
marks[2]=85;
printf("\n\nvalue of marks[0]=%d and address=%u",marks[0],&marks[0]);
printf("\n\nvalue of marks[1]=%d and address=%u",marks[1],&marks[1]);
printf("\n\nvalue of marks[2]=%d and address=%u",marks[2],&marks[2]);
getch();
}
|
C
|
#include <stdio.h>
int find_9(int num, int digit)
{
int count = 0;
do {
if (num % 10 == digit)
count++;
num = num / 10;
} while(num != 0);
return count;
}
int main(void)
{
int i = 0, sum = 0;
for(i = 1; i <= 1000; i++) {
sum += find_9(i, 9);
}
printf("1-100 zhong has %d ge 9 \n",sum);
return 0;
}
|
C
|
#include "config.h"
#include "global.h"
#include "stream.h"
int HuffDec(Bitstream *bitptr, const int *pCodeBook, int nNumCodes)
{
int n, k = 0;
int nShift, unBits = 0;
for(n = 0; n < nNumCodes; n++)
{
nShift = pCodeBook[k++];
if(nShift > 0)
{
unBits = unBits << nShift;
unBits |= GetBits(bitptr, nShift);
}
if(unBits == pCodeBook[k++])
{
return pCodeBook[k];
}
k++;
}
return 0;
}
int HuffDiff(Bitstream *bitptr, const int *pCodeBook, int nIndex, int nNumcodes)
{
int nDiff;
nDiff = HuffDec(bitptr, pCodeBook, nNumcodes);
nIndex = (nIndex + nDiff) % nNumcodes;
return nIndex;
}
int HuffDecRecurive(Bitstream *bitptr, const int *pCodeBook, int nNumCodes)
{
int nQIndex;
int k = -1;
do{
k++;
nQIndex = HuffDec(bitptr, pCodeBook, nNumCodes);
}while (nQIndex == nNumCodes - 1);
nQIndex = k*(nNumCodes - 1) + nQIndex;
return nQIndex;
}
int ResetHuffIndex()
{
return 0;
}
|
C
|
#include "gramtree.h"
#include "stdarg.h"
gramtree * Create_Node(int lineno, char *lex_name, int num, ...)
{
int i = 0;
va_list valist;
va_start(valist, num);
gramtree *lchild;
gramtree *new_node = (gramtree *)malloc(sizeof(gramtree));
new_node->unit_type = num;
new_node->line = lineno;
new_node->lex_unit_name = lex_name;
new_node->l_child = NULL;
new_node->r_child = NULL;
if (num > 0)
{
lchild = va_arg(valist, gramtree *);
new_node->l_child = lchild;
new_node->line = lchild->line;
if (num >= 2)
{
for (i = 0; i < num-1; i++)
{
lchild->r_child = va_arg(valist, gramtree *);
lchild = lchild->r_child;
}
}
}
return new_node;
}
void PreOrder_Traverse(struct gramtree* root, int level)
{
int i = 0;
if (root == NULL)
{
return;
}
if (root->unit_type >= 0) // 产生空的不显示
{
for ( ; i < level; i++)
{
printf(" "); // 缩进以显示父子关系
}
printf("%s", root->lex_unit_name);
// 若是终结符
if (!root->unit_type)
{
if (!strcmp(root->lex_unit_name, "ID") || !(strcmp(root->lex_unit_name, "TYPE")))
{
printf(": %s\n", root->id_type_name);
}
else if (!strcmp(root->lex_unit_name, "INT"))
{
printf(": %d\n", root->int_val);
}
else if (!strcmp(root->lex_unit_name, "FLOAT"))
{
printf(": %f\n", root->float_val);
}
else
{
printf("\n");
}
}
// 否则非终结符需打印行号
else
{
printf(" (%d) \n", root->line);
}
}
PreOrder_Traverse(root->l_child, level+1); // 先序遍历左孩子结点,层数+1
PreOrder_Traverse(root->r_child, level); // 先序遍历右孩子结点(即兄弟),层数不变
}
|
C
|
#include "include.h"
void write_database(dbh_t *header, ref_t *ref, char *filename)
{
FILE *file = fopen(filename, "wb");
if (file == NULL)
{
perror("Unable to write file");
return;
}
if ( fwrite(header, sizeof(dbh_t), 1, file) != 1 )
{
perror("Unable to write data to file");
return;
}
if ( fwrite(ref, sizeof(ref_t), header->num_refpoints, file) != header->num_refpoints )
{
perror("Unable to write data to file");
return;
}
fclose(file);
}
int main(int argc, char *argv[])
{
char *data = NULL;
char file[80] = "";
ref_t **ref;
int *x_coord;
int *y_coord;
int num_refpoints;
int num_scans;
int i, j;
dbh_t header;
int xmin = INT_MAX;
int xmax = INT_MIN;
int ymin = INT_MAX;
int ymax = INT_MIN;
if (argc != 3)
{
printf("Usage: create_database <num_refpoints> <num_scans>\n");
return 0;
}
num_refpoints = atoi(argv[1]);
num_scans = atoi(argv[2]);
x_coord = (int *)malloc(num_refpoints * sizeof(int));
if (x_coord == NULL)
{
perror("malloc failed");
return 0;
}
y_coord = (int *)malloc(num_refpoints * sizeof(int));
if (y_coord == NULL)
{
perror("malloc failed");
return 0;
}
// Allocate a pointer for each scan
ref = (ref_t **)malloc(num_scans * sizeof(ref_t *));
if (ref == NULL)
{
perror("malloc failed");
return 0;
}
if ( seq_parse(x_coord, y_coord, num_refpoints) != 0)
{
printf("seq_parse() failed\n");
return 1;
}
// Allocate memory for three data sets (one for each scan)
for(i = 0; i < num_scans; i++)
{
ref[i] = (ref_t *)calloc(num_refpoints, sizeof(ref_t));
if (ref[i] == NULL)
{
perror("calloc() failed");
return 1;
}
}
// Get the data
for(j = 0; j < num_refpoints; j++)
{
for(i = 0; i < num_scans; i++)
{
sprintf(file, "scan%d-%d", j+1, i+1);
data = (char *)get_file(file);
if (data == NULL)
{
printf("Failed to open %s\n", file);
return 2;
}
iwlist_parse(data, &ref[i][j]);
ref[i][j].x = x_coord[j];
ref[i][j].y = y_coord[j];
free((void *)data);
data = NULL;
}
}
// Now we want to combine the databases and average any matching access points
// we must also combine the lists as we may have new access points in a scan that werent in others.
for(i = 0; i < num_refpoints; i++)
{
for(j = 1; j < num_scans; j++)
{
combine_ref(&ref[0][i], &ref[j][i]);
}
divide_ref(&ref[0][i]);
}
for(i = 0; i < num_refpoints; i++)
{
xmin = MIN(xmin, ref[0][i].x);
xmax = MAX(xmax, ref[0][i].x);
ymin = MIN(ymin, ref[0][i].y);
ymax = MAX(ymax, ref[0][i].y);
}
header.num_refpoints = num_refpoints;
header.width = xmax - xmin + 1;
header.height = ymax - ymin + 1;
header.xoffset = -xmin;
header.yoffset = -ymin;
printf("Writing database\n");
write_database(&header, ref[0], "db.bin");
return 0;
}
|
C
|
// fight.c
#include <ansi.h>
inherit F_CLEAN_UP;
int main(object me, string arg)
{
object obj, old_target;
if( !wizardp(me) && environment(me)->query("no_fight") )
return notify_fail("這裏禁止戰鬥。\n");
if(!arg || !objectp(obj = present(arg, environment(me))))
return notify_fail("你想攻擊誰?\n");
if( !obj->is_character() )
return notify_fail("看清楚一點,那並不是生物。\n");
if( obj->is_fighting(me) )
return notify_fail("加油!加油!加油!\n");
if( !living(obj) )
return notify_fail(obj->name() + "已經無法戰鬥了。\n");
if(obj==me) return notify_fail("你不能攻擊自己。\n");
if( userp(obj) && (object)obj->query_temp("pending/fight")!=me ) {
message_vision("\n$N對著$n說道:"
+ RANK_D->query_self(me)
+ me->name() + ",領教"
+ RANK_D->query_respect(obj) + "的高招!\n\n", me, obj);
if( objectp(old_target = me->query_temp("pending/fight")) )
tell_object(old_target, YEL + me->name() + "取消了和你比試的念頭。\n" NOR);
me->set_temp("pending/fight", obj);
tell_object(obj, YEL "如果你願意和對方進行比試,請你也對" + me->name() + "("+(string)me->query("id")+")"+ "下一次 fight 指令。\n" NOR);
write(YEL "由於對方是由玩家控制的人物,你必須等對方同意才能進行比試。\n" NOR);
return 1;
}
if( obj->query("can_speak") ) {
message_vision("\n$N對著$n說道:"
+ RANK_D->query_self(me)
+ me->name() + ",領教"
+ RANK_D->query_respect(obj) + "的高招!\n\n", me, obj);
notify_fail("看起來" + obj->name() + "並不想跟你較量。\n");
if( !userp(obj) && !obj->accept_fight(me) ) return 0;
me->fight_ob(obj);
obj->fight_ob(me);
} else {
message_vision("\n$N大喝一聲,開始對$n發動攻擊!\n\n", me, obj);
me->fight_ob(obj);
obj->kill_ob(me);
}
return 1;
}
int help(object me)
{
write(@HELP
指令格式 : fight <人物>
這個指令讓你向一個人物「討教」或者是「切磋武藝」,這種形式的戰鬥純粹是
點到爲止,因此只會消耗體力,不會真的受傷,但是並不是所有的 NPC 都喜歡
打架,因此有需多狀況你的比武要求會被拒絕。
其他相關指令: kill
PS. 如果對方不願意接受你的挑戰,你仍然可以逕行用 kill 指令開始戰鬥,有
關 fight 跟 kill 的區分請看 'help combat'.
HELP
);
return 1;
}
|
C
|
#include <lib/trap.h>
#include <lib/x86.h>
#include "import.h"
unsigned int syscall_get_arg1(tf_t *tf)
{
return tf -> regs.eax;
}
unsigned int syscall_get_arg2(tf_t *tf)
{
return tf -> regs.ebx;
}
unsigned int syscall_get_arg3(tf_t *tf)
{
return tf -> regs.ecx;
}
unsigned int syscall_get_arg4(tf_t *tf)
{
unsigned int cur_pid;
unsigned int arg4;
cur_pid = get_curid();
arg4 = tf -> regs.edx;
return arg4;
}
unsigned int syscall_get_arg5(tf_t *tf)
{
unsigned int cur_pid;
unsigned int arg5;
cur_pid = get_curid();
arg5 = tf -> regs.esi;
return arg5;
}
unsigned int syscall_get_arg6(tf_t *tf)
{
unsigned int cur_pid;
unsigned int arg6;
cur_pid = get_curid();
arg6 = tf -> regs.edi;
return arg6;
}
void syscall_set_errno(tf_t *tf, unsigned int errno)
{
tf -> regs.eax = errno;
}
void syscall_set_retval1(tf_t *tf, unsigned int retval)
{
tf -> regs.ebx = retval;
}
void syscall_set_retval2(tf_t *tf, unsigned int retval)
{
tf -> regs.ecx = retval;
}
void syscall_set_retval3(tf_t *tf, unsigned int retval)
{
tf -> regs.edx = retval;
}
void syscall_set_retval4(tf_t *tf, unsigned int retval)
{
tf -> regs.esi = retval;
}
void syscall_set_retval5(tf_t *tf, unsigned int retval)
{
tf -> regs.edi = retval;
}
|
C
|
/*======================================================================
GRN gene regulation network
version 1.0
Implemented from the paper:
The evolution of phenotypic correlations and ‘developmental memory'
------------------------------------------------------------------------
Copyright (c) 2016 Anael Seghezzi
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would
be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not
be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
========================================================================*/
#include <stdio.h>
#include "../src/grn.c"
//#define REGL1 0.1 // L1 regularization
float exp2_fitness(int pattern, float phenotype[8])
{
float S1[8] = {1, 1, -1, -1, -1, 1, -1, 1};
float S2[8] = {1, -1, 1, -1, 1, -1, -1, -1};
float *S;
float dot = 0;
int i;
if (pattern == 0)
S = S1;
else
S = S2;
for (i = 0; i < 8; i++)
dot += phenotype[i] * S[i];
return 1 + dot;
}
int main(int argc, char **argv)
{
float phenotype[8];
struct grn_network net, netcpy;
int pattern = 0;
int i;
// create networks
grn_create(&net, 8);
grn_create(&netcpy, 8);
// run generations
for (i = 0; i < 800000; i++) {
float fitness, f1, f2;
if (i > 0 && (i % 2000) == 0) // alternate pattern
pattern = !pattern;
grn_copy(&netcpy, &net);
grn_mutate_single(&netcpy, 0.1, 0.0067);
grn_run(&net, phenotype, 10);
f1 = exp2_fitness(pattern, phenotype);
grn_run(&netcpy, phenotype, 10);
f2 = exp2_fitness(pattern, phenotype);
#ifdef REGL1
f1 += (1.0 - grn_matrix_l1(&net)) * REGL1;
f2 += (1.0 - grn_matrix_l1(&netcpy)) * REGL1;
#endif
if (f2 > f1) {
grn_copy(&net, &netcpy);
fitness = f2;
}
else {
fitness = f1;
}
printf("%.5d: fitness = %f\n", i, fitness);
}
grn_destroy(&net);
grn_destroy(&netcpy);
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
static void
print_var()
{
static unsigned long _id = 9;
printf("id: %lu\n", _id++);
}
int main(int argc, char **argv)
{
for (unsigned int idx = 0; idx < 100; idx++) {
print_var();
}
return 0;
}
|
C
|
#include<stdio.h>
void main()
{
char str[100];
printf("enter the string");
scanf("%[^'\n']s",str);
char ch,*p;
printf("enter the charcter");
scanf(" %c",&ch);
p=str;
int c=0,i=0;
while(*p!='\0')
{
if(*p==ch)
{
i=c;
break;
}
c++;
p++;
}
printf("\n%d",i);
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
void menu()
{
printf("**************************************\n");
printf("********* 1.play **********\n");
printf("********* 0.exit **********\n");
printf("**************************************\n");
}
void game()
{
printf("Ϸ");
}
int main()
{
int input = 0;
{
do
{
menu();//ӡ˵
printf("ѡ;>");
scanf("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
printf("˳Ϸ");
break;
default:
printf("");
}
printf("\n");
}
while (input);
}
system("pause");
return 0;
}
|
C
|
#include "includes.h"
int print_time(t_philsopher *p, char *s)
{
int res;
int time;
res = 0;
if ((res = sem_wait(p->write_lock)))
return (1);
if ((time = get_time(p->start_time)) == -1)
return (1);
if (print_event(p->num, time, s) == -1)
res |= 1;
res |= sem_post(p->write_lock);
return (res);
}
int print_event(int num, int time, char *s)
{
char buf[256];
char *tmp;
tmp = ft_itoa_buf(time, buf);
*tmp++ = '\t';
if (num > 0)
tmp = ft_itoa_buf(num, tmp);
ft_strlcpy(tmp, s, -1);
return (write(STDOUT_FILENO, buf, ft_strlen(buf)));
}
int clean_data(t_philos_list *phs)
{
clean_philosophers(phs->philosophers, phs->amount);
return (1);
}
int get_time(struct timeval *start_time)
{
struct timeval current_time;
if (gettimeofday(¤t_time, NULL))
return (-1);
return ((current_time.tv_sec - start_time->tv_sec) * 1000 +\
(current_time.tv_usec - start_time->tv_usec) / 1000);
}
|
C
|
#include "debug.h"
#include "uart.h"
#include "stdio.h"
#define PUTCHAR_PROTOTYPE int putchar(int c)
PUTCHAR_PROTOTYPE
{
UART_SendData(DBG_PORT,(u8*)&c,1);
return c;
}
void DBG_Init(void)
{
UART_Init(DBG_PORT,57600,UART_TX_ENABLE,UART_RX_DISABLE);
UART_Enable(DBG_PORT,ENABLE);
}
void DBG_PrintString(char* str)
{
printf("%s\n",str);
}
void DBG_PrintHex(u8 *source,u8 len)
{
for(int i=0;i<len;i++)
{
printf("%02x",source[i]);
printf(" ");
}
}
|
C
|
#include<stdio.h>
int main()
{
int hardness, ts, grade;
float carbon;
printf("Enter the values of hardness, tensile strength and carbon content in the steel:");
scanf("%d %d %f", &hardness, &ts, &carbon);
if ((hardness>50) && (carbon<0.7) && (ts>5600))
printf("Grade 10");
else if ((hardness>50) && (carbon<0.7))
printf("Grade 9");
else if ((carbon<0.7) && (ts>5600))
printf("Grade 8");
else if ((hardness>50) && (ts>5600))
printf("Grade 7");
else if ((hardness>50) || (carbon<0.7) || (ts>5600))
printf("Grade 6");
else
printf("Grade 5");
}
|
C
|
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <stdio.h>
int main()
{
if (fork() == 0)
{
printf("%d\n", getpid());
while (1)
{
}
}
int st;
wait(&st);
if (WIFSIGNALED(st))
printf("%s\n", strsignal(WTERMSIG(st)));
if (WIFEXITED(st))
printf("Return: %d\n", WEXITSTATUS(st));
return 0;
}
|
C
|
#include<stdio.h>
int main(void)
{
int i,term=1,sum=0;
for(i=1;i<=5;i++){
term=term*i;
sum=sum+term;
}
printf("sum=%d\n",sum);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUF_SIZE 100
int main()
{
FILE *fp = NULL;
FILE *fp2 = NULL;
int nbyte=0;
char buf[BUF_SIZE]={0, };
// file open
fp = fopen("./proto.c","rb");
if ( fp == NULL )
{
printf(" fopen() error \n");
exit(0);
}
fp2 = fopen("./p.txt","wb");
if ( fp2 == NULL )
{
printf(" fopen() error \n");
exit(0);
}
// Read data from proto.c : BUF_SIZE
while(1)
{
memset(&buf, 0, BUF_SIZE);
// file read
nbyte = fread(buf, 1, BUF_SIZE, fp);
if ( nbyte <= 0 ){
break;
}
// new file write
fwrite(buf, 1, nbyte, fp2);
}
fclose(fp);
fclose(fp2);
}
|
C
|
#pragma once
#include <math.h>
inline float Saturate(float v)
{
float result = min(max(v, 0), 1);;
return result;
}
inline V4 Saturate(V4 v)
{
V4 result = v;
result.x = min(max(result.x, 0), 1);
result.y = min(max(result.y, 0), 1);
result.z = min(max(result.z, 0), 1);
result.w = min(max(result.w, 0), 1);
return result;
}
//////////////////////////////////////////////////////////////////////////
// Intersections
struct Ray
{
V3 o;
V3 d;
};
struct Sphere
{
V3 o;
float r;
};
struct Plane
{
V3 p;
V3 n;
};
struct AABB
{
V3 min;
V3 max;
};
struct Vertex
{
V3 position;
V3 normal;
};
struct Mesh
{
int vertexCount;
Vertex * vertices;
Sphere bound;
AABB aabb;
};
enum GeoType
{
SPHERE,
PLANE,
MESH,
COUNT
};
struct Geometry
{
GeoType type;
union
{
Sphere sphere;
Plane plane;
Mesh mesh;
};
};
struct Intersection
{
V3 point;
V3 normal;
float t;
};
void ComputeMeshBound(Mesh * mesh)
{
V3 min = V3::FloatMax();
V3 max = V3::FloatMin();
for(int i = 0; i < mesh->vertexCount; ++i)
{
Vertex * v = &mesh->vertices[i];
if(min.x > v->position.x) min.x = v->position.x;
if(min.y > v->position.y) min.y = v->position.y;
if(min.z > v->position.z) min.z = v->position.z;
if(max.x < v->position.x) max.x = v->position.x;
if(max.y < v->position.y) max.y = v->position.y;
if(max.z < v->position.z) max.z = v->position.z;
}
mesh->aabb.min = min;
mesh->aabb.max = max;
mesh->bound = {};
mesh->bound.o = (min + max) / 2;
mesh->bound.r = Length((min - max) / 2);
}
bool IntersectRaySphere(Ray ray, Sphere sphere, Intersection * intersection)
{
// PROFILED_FUNCTION_FAST;
// See Real-Time Rendering 3rd ed., p. 741
V3 l = sphere.o - ray.o;
float s = Dot(l, ray.d);
float ll = Dot(l, l);
float rr = sphere.r*sphere.r;
if(s < 0 && ll > rr) return false;
float mm = ll - s*s;
if(mm > rr) return false;
float q = sqrt(rr - mm);
float t = 0;
if(ll > rr)
t = s - q;
else
t = s + q;
if(intersection)
{
(*intersection).t = t;
(*intersection).point = ray.o + ray.d*t;
(*intersection).normal = Normalize((*intersection).point - sphere.o);
}
return true;
}
bool TestRaySphere(Ray ray, Sphere sphere)
{
PROFILED_FUNCTION_FAST;
// See Real-Time Rendering 3rd ed., p. 741
V3 l = sphere.o - ray.o;
float s = Dot(l, ray.d);
float ll = Dot(l, l);
float rr = sphere.r*sphere.r;
if(s < 0 && ll > rr) return false;
float mm = ll - s*s;
if(mm > rr) return false;
return true;
}
bool TestRayAABB(Ray ray, AABB aabb)
{
PROFILED_FUNCTION_FAST;
// NOTE: cheating! Represent ray as a very long line segment
V3 offset = -(aabb.min + aabb.max) * 0.5f;
V3 start = ray.o + offset;
V3 end = start + ray.d*10000.0f;
V3 c = (start + end)*0.5f;
V3 w = (end - start)*0.5f;
V3 h = aabb.max + offset;
V3 v;
v.x = fabsf(w.x);
v.y = fabsf(w.y);
v.z = fabsf(w.z);
if(fabsf(c.x) > v.x + h.x) return false;
if(fabsf(c.y) > v.y + h.y) return false;
if(fabsf(c.z) > v.z + h.z) return false;
if(fabsf(c.y*w.z - c.z*w.y) > h.y*v.z + h.z*v.y) return false;
if(fabsf(c.x*w.z - c.z*w.x) > h.x*v.z + h.z*v.x) return false;
if(fabsf(c.x*w.y - c.y*w.x) > h.x*v.y + h.y*v.x) return false;
return true;
}
bool IntersectRayPlane(Ray ray, Plane plane, Intersection * intersection)
{
// PROFILED_FUNCTION_FAST;
bool result = false;
float denom = Dot(ray.d, -plane.n);
if(denom > EPSYLON)
{
float t = Dot(plane.p - ray.o, -plane.n) / denom;
if(t >= 0)
{
result = true;
if(intersection)
{
(*intersection).t = t;
(*intersection).point = ray.o + ray.d*t;
(*intersection).normal = plane.n;
}
}
}
return result;
}
bool IntersectRayMesh(Ray ray, Mesh mesh, Intersection * intersection)
{
PROFILED_FUNCTION_FAST;
bool result = false;
for(int i = 0; i < mesh.vertexCount; i += 3)
{
Vertex v0 = mesh.vertices[i + 0];
Vertex v1 = mesh.vertices[i + 1];
Vertex v2 = mesh.vertices[i + 2];
V3 edge1 = v1.position - v0.position;
V3 edge2 = v2.position - v0.position;
V3 h = Cross(ray.d, edge2);
float a = Dot(edge1, h);
if(fabs(a) > EPSYLON)
{
float f = 1.0f/a;
V3 s = ray.o - v0.position;
float u = f*Dot(s, h);
if(Saturate(u) == u)
{
V3 q = Cross(s, edge1);
float v = f*Dot(ray.d, q);
if(v >= 0.0f && u + v <= 1.0f)
{
float t = f*Dot(edge2, q);
// TODO: add this test to all intersections, remove ray origin shifting from main
if(t > EPSYLON)
{
result = true;
if(intersection)
{
(*intersection).t = t;
(*intersection).point = ray.o + ray.d*t;
(*intersection).normal = v0.normal;
}
}
}
}
}
}
return result;
}
bool TryIntersectRayMesh(Ray ray, Mesh mesh, Intersection * intersection)
{
bool result = false;
//return IntersectRaySphere(ray, mesh.bound, intersection);
//if(TestRaySphere(ray, mesh.bound))
{
if(TestRayAABB(ray, mesh.aabb))
{
result = IntersectRayMesh(ray, mesh, intersection);
}
}
return result;
}
bool Intersect(Ray ray, Geometry geo, Intersection * ix)
{
// PROFILED_FUNCTION_FAST;
bool result = false;
switch(geo.type)
{
case GeoType::SPHERE:
{
result = IntersectRaySphere(ray, geo.sphere, ix);
} break;
case GeoType::PLANE:
{
result = IntersectRayPlane(ray, geo.plane, ix);
} break;
case GeoType::MESH:
{
result = TryIntersectRayMesh(ray, geo.mesh, ix);
} break;
default:
{
} break;
}
return result;
}
|
C
|
/**
* This code is released under a BSD License.
*/
#include <stdio.h>
#include "simdcomp.h"
int main() {
int N = 5000 * SIMDBlockSize;
__m128i * buffer = malloc(SIMDBlockSize * sizeof(uint32_t));
uint32_t * datain = malloc(N * sizeof(uint32_t));
uint32_t * backbuffer = malloc(SIMDBlockSize * sizeof(uint32_t));
for (int gap = 1; gap <= 387420489; gap *= 3) {
printf(" gap = %u \n", gap);
for (int k = 0; k < N; ++k)
datain[k] = k * gap;
uint32_t offset = 0;
for (int k = 0; k * SIMDBlockSize < N; ++k) {
const uint32_t b = maxbits(datain + k * SIMDBlockSize);
simdpackwithoutmask(datain + k * SIMDBlockSize, buffer, b);//compressed
simdunpack(buffer, backbuffer, b);//uncompressed
for (int j = 0; j < SIMDBlockSize; ++j) {
if (backbuffer[j] != datain[k * SIMDBlockSize + j]) {
printf("bug in simdpack\n");
return -2;
}
}
const uint32_t b1 = simdmaxbitsd1(offset,
datain + k * SIMDBlockSize);
simdpackwithoutmaskd1(offset, datain + k * SIMDBlockSize, buffer,
b1);//compressed
simdunpackd1(offset, buffer, backbuffer, b1);//uncompressed
for (int j = 0; j < SIMDBlockSize; ++j) {
if (backbuffer[j] != datain[k * SIMDBlockSize + j]) {
printf("bug in simdpack d1\n");
return -3;
}
}
offset = datain[k * SIMDBlockSize + SIMDBlockSize - 1];
}
}
free(buffer);
free(datain);
free(backbuffer);
printf("Code looks good.\n");
return 0;
}
|
C
|
#include "raylib.h"
int main(void)
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - basic window");
int mframesCounter = 0;
int sframesCounter = 0;
int MframesCounter = 0;
int hframesCounter = 0;
int horas = 0;
int minutos = 0;
int segundos = 0;
int milisegundos = 0;
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Update
mframesCounter++;
sframesCounter ++;
milisegundos = mframesCounter;
if(milisegundos >= 60)
{
mframesCounter = 0;
segundos++;
}if(segundos >=60)
{
segundos= 0;
minutos ++;
}if(minutos >=60)
{
minutos = 0;
horas ++;
}if(horas >=24)
{
horas = 0;
}
//----------------------------------------------------------------------------------
// TODO: Update your variables here
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(RAYWHITE);
DrawText(TextFormat("TIME: %i", horas), 10, 10, 20, BLACK);
DrawText(TextFormat(":%i", minutos), 100, 10, 20, BLACK);
DrawText(TextFormat(":%i", segundos), 130, 10, 20, BLACK);
DrawText(TextFormat(":%i", milisegundos), 160, 10, 20, BLACK);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
|
C
|
// https://www.hackerrank.com/challenges/bitwise-operators-in-c/problem
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
//Complete the following function.
void calculate_the_maximum(int n, int k) {
//Write your code here.
int res_and=0, res_or=0, res_xor=0;
int max_and=0, max_or=0, max_xor=0;
for(int a=1; a<=n; a++){
for(int b=a+1; b<=n; b++){
res_and = a & b;
res_or = a | b;
res_xor = a ^ b;
if ((res_and > max_and) && (res_and <= k-1)){max_and = res_and;}
if ((res_or > max_or) && (res_or <= k-1)){max_or = res_or;}
if ((res_xor > max_xor) && (res_xor <= k-1)){max_xor = res_xor;}
}
}
printf("%d\n",max_and);
printf("%d\n",max_or);
printf("%d\n",max_xor);
}
int main() {
int n, k;
scanf("%d %d", &n, &k);
calculate_the_maximum(n, k);
return 0;
}
|
C
|
#include "prototypes.h"
void init(){
srand(time(NULL));
// initialize SDL video
if ( SDL_Init( SDL_INIT_VIDEO |SDL_INIT_AUDIO ) < 0 )
{
printf( "Unable to init SDL: %s\n", SDL_GetError() );
exit(EXIT_FAILURE); // On quitte le programme
}
if(TTF_Init() < 0)
{
printf(stderr, "Erreur d'initialisation de TTF_Init : %s\n", TTF_GetError());
exit(EXIT_FAILURE);
}
// make sure SDL cleans up before exit
atexit(SDL_Quit);
//set window icon
SDL_WM_SetIcon(SDL_LoadBMP("img/icon.bmp"), NULL);
//Set title and create color
SDL_WM_SetCaption("Coinche Vie", NULL);
}
void free_screen(SDL_Surface **cards){
// Libration des surfaces charges
for (int i = 0 ; i < DECK_SIZE + 2 ; i++)
SDL_FreeSurface(cards[i]);
}
void free_all(){
//TTF_CloseFont(police);
TTF_Quit();
IMG_Quit();
SDL_Quit();
}
|
C
|
/*
** manage_precision.c for manage_precision.c in /home/bequig_s//workspace/module-Unix/my_printf/my_prinf2
**
** Made by sebastien bequignon
** Login <[email protected]>
**
** Started on Sun Nov 18 19:14:07 2012 sebastien bequignon
** Last update Mon Nov 19 16:11:47 2012 sebastien bequignon
*/
#include <stdlib.h>
#include "my_printf.h"
#include "../my.h"
int set_precision(t_query *to_fill, char *format)
{
int i;
char *nb;
i = 0;
if (format[0] == '.')
{
while (format[i] >= '0' && format[i] <= '9')
i++;
if (i > 0)
{
nb = get_part_of_string(format, i);
to_fill->precision = my_getnbr(nb);
free(nb);
return (i);
}
return (-1);
}
return (i);
}
|
C
|
/*
* csvTool.c
*
* Created on: 13 May 2018
* Author: Ben Tomlin
* Student #: 834198
*/
#include <stdio.h>
#include "dataStructure.h"
#include <stdlib.h>
#include <string.h>
#define CSV_BUFFER_SIZE 1024
#define CSV_DEFAULT_FS ','
dsa_t* readRow(FILE* csv) {
/**
* Read a row of <csv> and return its cells as an array.
*
* A row is read in a buffered manner. Rows may be delimited with
* '\n' or an EOF. Cells are delimited with CSV_DEFUALT_FS or row
* delimiters.
*
* Empty rows are ignored, and the next row is read
*/
if (feof(csv)!=0) {return(NULL);}
char buffer[CSV_BUFFER_SIZE];
dsa_t* leftoverBuffer=create_dsa();
char* leftover;
char* leftoverScanner;
char* bufferScanner;
char* cellEnd;
char* cellStart=buffer;
char* cell;
dsa_t* rowData = create_dsa();
int cellLength;
int leftoverLength=0;
int lastCellLength=0;
int haveRow=0;
int eofReached;
/* Read in text of csv file */
do{
fgets(buffer, CSV_BUFFER_SIZE, csv);
/* Move to the next row if current row empty */
if(strlen(buffer)==0){return(readRow(csv));}
/* Test for remaining row data */
if ((buffer[strlen(buffer)-1]=='\n') || (feof(csv)!=0)){haveRow=1;}
bufferScanner=buffer;
/* Break text into cells and write to dsa */
while((cellEnd=strchr(bufferScanner, CSV_DEFAULT_FS))!=NULL){
cellLength=cellEnd-cellStart;
cell = malloc(sizeof(char)*(cellLength+1));
/* This cell contains the leftover from prior fgets reads that did not complete the line*/
if (leftoverBuffer->length>0) {
/* Find leftover length */
leftoverLength=0;
for(int lx=0;lx<leftoverBuffer->length-1;lx++){
leftoverLength+=strlen(getItem_dsa(leftoverBuffer,lx));
}
/* Reassemble leftover */
leftover=leftoverScanner=malloc(sizeof(char)*(leftoverLength+1));
for(int lx=(leftoverBuffer->length-1);lx>=0;lx--){
const char* leftoverFragment=getItem_dsa(leftoverBuffer, lx);
strcat(leftoverScanner, leftoverFragment);
leftoverScanner+=strlen(leftoverFragment);
}
/* Put leftover in cell, and clear leftover buffer */
cell = realloc(cell, sizeof(char)*(leftoverLength+cellLength+1));
memcpy(cell, leftoverScanner, leftoverLength);
cell+=leftoverLength;
delete_dsa(leftoverBuffer);
leftoverBuffer=create_dsa();
} // break up cells while
/* Extract cell from row */
memcpy(cell, bufferScanner, cellLength);
cell[cellLength]='\0';
/* Jump up to last FS match, and one beyond it */
bufferScanner+=cellLength+1;
appendto_dsa(rowData, cell);
}
/* Stash leftover if we dont have the whole cell */
if(!haveRow){
appendto_dsa(leftoverBuffer, cellEnd+1);
/* Extract final cell, which is delimited with \n or EOF */
} else {
/* This does not include the final new line if present */
eofReached = (feof(csv)!=0);
lastCellLength = (buffer+strlen(buffer))-bufferScanner-!eofReached;
cell = malloc(sizeof(char)*(lastCellLength+1));
memcpy(cell, bufferScanner, lastCellLength);
cell[lastCellLength]='\0';
appendto_dsa(rowData, cell);
}
} while(!haveRow);
delete_dsa(leftoverBuffer);
return(rowData);
}
void writeRow(FILE* csv, dsa_t* row) {
/**
* Write array content of <row> into <csv>
*/
for(int ix=0;ix<row->length;ix++){
const char* element = getItem_dsa(row, ix);
if(ix!=0){fputc(CSV_DEFAULT_FS, csv);}
fputs(element, csv);
}
fputc('\n', csv);
}
|
C
|
/*
** parfait.c for parfait.c in /home/thenascrazy/C_-_Prog_Elem/dante/generateur
**
** Made by Afou Nacerdine
** Login <[email protected]>
**
** Started on Sat May 21 10:15:17 2016 Afou Nacerdine
** Last update Sun May 22 12:47:38 2016 Afou Nacerdine
*/
#include "generate.h"
void disp_map(t_struct *mv)
{
int x;
int y;
y = 0;
while (mv->map[y] != NULL)
{
x = 0;
while (mv->map[y][x] != -1)
{
if (mv->map[y][x] != 0)
my_printf("*");
else
my_printf("X");
x = x + 1;
}
if (mv->map[y + 1] != NULL)
my_printf("\n");
y = y + 1;
}
}
int generate_start(t_struct *mv)
{
int y;
y = 0;
mv->cell = 1;
if (mv->hauteur < 1 || mv->largeur < 1)
{
my_printf("Error: x y\n");
return (-1);
}
if ((mv->map = malloc(sizeof(int *) * (mv->hauteur + 1))) == NULL)
return (-1);
while (y < mv->hauteur)
{
if (y % 2 == 0)
create_line(mv, y);
else
create_line_same(mv, y);
y = y + 1;
}
mv->map[y] = NULL;
return (0);
}
int parfait(t_struct *mv)
{
int save;
if (generate_start(mv) == -1)
return (-1);
if (mv->hauteur % 2 == 0)
{
save = mv->map[mv->hauteur - 2][mv->largeur - 2];
mv->map[mv->hauteur - 1][mv->largeur - 1] = save;
mv->map[mv->hauteur - 1][mv->largeur - 2] = save;
save = mv->map[mv->hauteur - 2][mv->largeur - 1];
if (mv->largeur % 2 != 0)
mv->map[mv->hauteur - 1][mv->largeur - 1] = save;
}
else
{
save = mv->map[mv->hauteur - 1][mv->largeur - 2];
if (mv->largeur % 2 == 0)
mv->map[mv->hauteur - 1][mv->largeur - 1] = save;
}
get_one_way(mv);
disp_map(mv);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* write.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abnaceur <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/08/15 11:10:24 by abnaceur #+# #+# */
/* Updated: 2017/08/21 22:17:34 by abnaceur ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include "asm.h"
static char *create_file(char *file, int *fd)
{
char *cor_file;
size_t len;
len = ft_strlen(file) + 2;
if (!(cor_file = ft_memalloc(len + 1)))
return ("Malloc error");
ft_strcpy(cor_file, file);
ft_strcpy(cor_file + len - 3, "cor");
if ((*fd = open(cor_file, O_WRONLY | O_EXCL | O_CREAT, 0644)) == -1)
{
perror(cor_file);
free(cor_file);
return ("write error");
}
ft_printf("%s => %s\n", file, cor_file);
free(cor_file);
return (NULL);
}
static void write_prog_name(int fd, t_header *header)
{
int i;
long n;
int count;
count = 0;
n = COREWAR_EXEC_MAGIC;
while (n != 0)
{
n /= 256;
++count;
}
while (4 - count)
{
ft_putchar_fd(0x0, fd);
++count;
}
puthex_fd(COREWAR_EXEC_MAGIC, fd);
i = 0;
while (header->prog_name[i])
ft_putchar_fd(header->prog_name[i++], fd);
while (i++ < PROG_NAME_LENGTH)
ft_putchar_fd(0x0, fd);
}
static void write_comment(int fd, t_header *header, int n_bytes)
{
int i;
int count;
long n;
n = n_bytes;
count = 0;
while (n != 0)
{
n /= 0x100;
++count;
}
while (8 - count)
{
ft_putchar_fd(0x0, fd);
++count;
}
puthex_fd(n_bytes, fd);
i = 0;
while (header->comment[i])
ft_putchar_fd(header->comment[i++], fd);
while (i++ < COMMENT_LENGTH + 4)
ft_putchar_fd(0x0, fd);
}
char *write_file(t_asm *a, int n_lines, t_header *header)
{
int fd;
int count;
char *err_msg;
(void)n_lines;
if ((err_msg = create_file(a->file, &fd)))
return (err_msg);
count = set_label(a);
ft_printf("Name: %s\nComment: %s\n", header->prog_name, header->comment);
write_prog_name(fd, header);
write_comment(fd, header, count);
write_instruction(a, fd, n_lines);
close(fd);
return (NULL);
}
void puthex_fd(long code, int fd)
{
if (code >= 0x100)
{
puthex_fd(code / 0x100, fd);
puthex_fd(code % 0x100, fd);
}
else
ft_putchar_fd(code, fd);
}
|
C
|
#include<stdio.h>
int insertarray(int *a, int size, int capacity, int index, int num);
void display(int *a, int size);
int main()
{
int a[20]={3,5,3,6,3,6,5,7};
int insnum;
int size=8;
int index=6;
printf("Enter the number you want to print in array:\n");
scanf("%d",&insnum);
insertarray(a,size,100,index,insnum);
size=size+1;
display(a,size);
}
int insertarray(int *a, int size, int capacity, int index, int num)
{
int i;
if(size>=capacity)
{
return -1;
}
for(i=size-1;i>=index;i--)
{
a[i+1]=a[i];
}
a[index]=num;
}
void display(int *a, int size)
{
int i;
for ( i=0;i<size;i++)
printf(" %d ",a[i] );
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int data;
struct Node* next;
}Node;
void push(Node* head, int data){
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->next = NULL;
new_node->data = data;
while(head->next != NULL){
head = head->next;
}
head->next = new_node;
}
void print_list(Node* head){
while(head != NULL){
printf("%d->", head->data);
head = head->next;
}
printf("\n");
}
void reverse_list(Node** head){
Node* prev = NULL;
Node* current = *head;
Node* next = NULL;
while(current != NULL){
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head = prev;
}
// O(4n) => O(n)
void add_to_number_from_list(Node* head){
int number_from_list = 0;
int number_for_list = 0;
int base_ten_counter = 1;
reverse_list(&head);
Node* tmp = head;
while(tmp != NULL){
number_from_list += tmp->data * base_ten_counter;
base_ten_counter *= 10;
tmp = tmp->next;
}
reverse_list(&head);
number_from_list++;
base_ten_counter /= 10;
while(head != NULL){
number_for_list = (number_from_list / base_ten_counter) % 10;
head->data = number_for_list;
base_ten_counter /= 10;
head = head->next;
}
}
int main(){
/*
If 1 is added to list, change all values such as a normal sum:
Ex: List: 1 -> 9 -> 9-> 9 -> NULL (+1) = 2 -> 0 -> 0 -> 0;
*/
Node* HEAD = (Node*)malloc(sizeof(Node));
HEAD->data = 1;
HEAD->next = NULL;
push(HEAD, 9);
push(HEAD, 9);
push(HEAD, 9);
print_list(HEAD);
add_to_number_from_list(HEAD);
print_list(HEAD);
return 0;
}
|
C
|
#include "grafo.c"
static char* get_line(char*);
static int read_numbers(char*, u32, u32*, u32*);
static void free_resources(Grafo, char*, map, u32*, u32*);
Grafo ConstruccionDelGrafo() {
// Allocs the memory of the graph
Grafo G = (Grafo)malloc(sizeof(struct GrafoSt));
G->n = G->m = G->x = G->d = 0;
G->dict = G->color = G->order = NULL;
G->g = NULL;
if(!G) {
printf("fallo al reservar memoria para la estructura GrafoSt\n");
return NULL;
}
char* line = NULL;
// ----------------- READ COMMENTS ----------------- //
do {
line = get_line(line);
if(!line) {
free_resources(G, line, NULL, NULL, NULL);
printf("fallo al leer\n");
return NULL;
}
} while(line[0] == 'c');
// ---------------- READ p edge n m ---------------- //
// Compare the first part
if(memcmp(line, "p edge ", 7)) {
free_resources(G, line, NULL, NULL, NULL);
printf("error en primera linea sin comentario\n");
return NULL;
}
// Read n, m
if(read_numbers(line, 7, &G->n, &G->m) < 0) {
free_resources(G, line, NULL, NULL, NULL);
printf("error en primera linea sin comentario\n");
return NULL;
}
// ---------------- ALLOC RESOURCES ---------------- //
// Alloc map and adjacency list
map m = map_create();
if(!m) {
free_resources(G, line, NULL, NULL, NULL);
printf("fallo al reservar memoria\n");
return NULL;
}
G->g = (vector*)malloc(G->n * sizeof(vector));
if(!G->g) {
free_resources(G, line, m, NULL, NULL);
printf("fallo al reservar memoria para la estructura GrafoSt\n");
return NULL;
}
// Alloc the vectors for the adj. list
fore(i, 0, G->n) {
G->g[i] = vector_create();
if(!G->g[i]) {
free_resources(G, line, m, NULL, NULL);
printf("fallo al reservar memoria para el vector %u\n", i);
return NULL;
}
}
// Alloc memory for edges
u32* u = (u32*)calloc(G->m, sizeof(u32));
u32* v = (u32*)calloc(G->m, sizeof(u32));
// Alloc memory por dictionary, array of colors and order
G->dict = (u32*)malloc(G->n * sizeof(u32));
G->color = (u32*)malloc(G->n * sizeof(u32));
G->order = (u32*)malloc(G->n * sizeof(u32));
// If there was an error on any of the allocs, free the memory
if(!m || !u || !v || !G->dict || !G->color || !G->order) {
free_resources(G, line, m, u, v);
printf("fallo al reservar memoria\n");
return NULL;
}
// ------------------ READ EDGES ------------------ //
fore(i, 0, G->m) {
line = get_line(line);
if(!line) {
free_resources(G, line, m, u, v);
printf("fallo al leer\n");
return NULL;
}
// Compare the first part
if(memcmp(line, "e ", 2)) {
free_resources(G, line, m, u, v);
printf("error de lectura en lado %u\n", i + 1);
return NULL;
}
// Read u and v
read_numbers(line, 2, &u[i], &v[i]);
// Add {u[i], 0} and {v[i], 0} to tree
if(map_add(m, u[i], 0) < 0 || map_add(m, v[i], 0) < 0) {
free_resources(G, line, m, u, v);
printf("fallo al agregar un nodo al mapa\n");
return NULL;
}
}
// Check G->n matches
if(map_size(m) != G->n) {
free_resources(G, line, m, u, v);
printf("cantidad de vértices leidos no es la declarada\n");
return NULL;
}
// Default order: Natural
OrdenNatural(G);
// Map the smallest vertex to 0, the second smallest to 1, ..., the greatest to n - 1
map_sort(m);
vector * g = G->g;
// Construct adjacency list
fore(i, 0, G->m) {
// Find the mapping of u and v
u32 real_u = *map_find(m, u[i]);
u32 real_v = *map_find(m, v[i]);
// Store their names into the dictionary
G->dict[real_u] = u[i];
G->dict[real_v] = v[i];
// Push edges real_u -> real_v and real_u <- real_v
if(vector_push_back(g[real_u], real_v) < 0 || vector_push_back(g[real_v], real_u) < 0) {
free_resources(G, line, m, u, v);
printf("Fallo al crear una arista\n");
return NULL;
}
}
fore(i, 0, G->n) G->d = max(G->d, vector_size(g[i]));
// Free resources
free_resources(NULL, line, m, u, v);
// Run Greedy
Greedy(G);
// Return graph
return G;
}
Grafo CopiarGrafo(Grafo G) {
// Creates the new graph
Grafo copy = (Grafo)malloc(sizeof(struct GrafoSt));
if(!copy) return NULL;
// Copy number of vertex, edges, number of colors, and delta
copy->n = G->n;
copy->m = G->m;
copy->x = G->x;
copy->d = G->d;
// Allocs the vectors and arrays for verteces and colors
copy->g = (vector*)malloc(copy->n * sizeof(vector));
copy->dict = (u32*)malloc(copy->n * sizeof(u32));
copy->color = (u32*)malloc(copy->n * sizeof(u32));
copy->order = (u32*)malloc(copy->n * sizeof(u32));
// If any of the previous allocs failed, destroy resources
if(!copy->g || !copy->dict || !copy->color || !copy->order) {
DestruccionDelGrafo(copy);
return NULL;
}
fore(i, 0, copy->n) {
// Copy coloring and order
copy->color[i] = G->color[i];
copy->order[i] = G->order[i];
copy->dict[i] = G->dict[i];
// Allocs the neighbours for every vertex
copy->g[i] = vector_create();
if(!copy->g[i]) {
DestruccionDelGrafo(copy);
return NULL;
}
vector * g = G->g;
vector * cg = copy->g;
// Copy the adjacency of every vertex
fore(j, 0, vector_size(g[i])) {
u32 v = vector_at(g[i], j);
if(vector_push_back(cg[i], v)) {
DestruccionDelGrafo(copy);
return NULL;
}
}
}
return copy;
}
void DestruccionDelGrafo(Grafo G) {
if(G->g){
fore(i, 0, G->n) if(G->g[i]) vector_destroy(G->g[i]);
free(G->g);
}
if(G->dict) free(G->dict);
if(G->color) free(G->color);
if(G->order) free(G->order);
free(G);
}
static char* get_line(char* line) {
// Wipe previous line
if(line) free(line);
// Alloc space for line
line = (char*)malloc(sizeof(char));
if(!line) return line;
size_t sz = 0, cap = 1;
char c;
while(EOF != (c = fgetc(stdin)) && c != '\n' && c != '\r' && c != '\0') {
line[sz++] = c;
if(sz == cap) {
line = realloc(line, sizeof(char) * (cap *= 2));
if(!line) return line;
}
}
// Add null character to line
line[sz++] = '\0';
// Give the line its real size
return realloc(line, sizeof(char) * sz);
}
static int read_numbers(char* line, u32 i, u32* u, u32* v) {
// Check the first number starts at i
if('0' > line[i] && line[i] > '9') return -1;
// Init both numbers
*u = *v = 0;
// Read first number
while('0' <= line[i] && line[i] <= '9') {
*u = *u * 10 + line[i++] - '0';
}
// Advance to second number
while('0' > line[i] || line[i] > '9') if(line[i++] != ' ') return -1;
// Read second number
while('0' <= line[i] && line[i] <= '9') {
*v = *v * 10 + line[i++] - '0';
}
// Check that the trailing part are space characters
while(('0' > line[i] || line[i] > '9') && line[i] != '\0') if(line[i++] != ' ') return -1;
return 0;
}
static void free_resources(Grafo g, char* line, map m, u32* u, u32* v) {
// Destroy graph
if(g) DestruccionDelGrafo(g);
// Destroy buffer-input
if(line) free(line);
// Destroy map
if(m) map_destroy(m);
// Destroy edges
if(u) free(u);
if(v) free(v);
}
|
C
|
/**
*
* @file ProgramOne.c
* @brief Generates a table of values in different bases, based off a given input values
*
* @author Kyle Bryan
* @date September 13 2019
* version 1.0
*
* The binary conversion algorithm in the toBinary function was leveraged from:
* https://www.geeksforgeeks.org/program-decimal-binary-conversion/
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "ProgramOne.h"
int main (void)
{
//inputted data per the project
int input[33] = {-6, 10, 4, -6, 9, 4, -6, 10, 5, -9, 10, 8, 237, 10, 8,
0354, 8, 8, 0xEB, 16, 8, -125, 10, 8, 65400, 01, 8, 65400,
10, 16, -32701, 10, 16};
_Bool positive = 0;
int radix = 0;
int value = 0;
int operandSize = 0;
int *pbinaryNum;
int absValue = 0;
int maxValue = 0;
_Bool signedOverflow = 0;
//cycle through all the input data
for(int k = 0; k<(sizeof(input)/sizeof(input[0])); k=k+3)
{
value = input[k];
radix = input[(k+1)];
operandSize = input[(k+2)];
positive = (value > 0) ? 1 : 0;
absValue = abs(value);
maxValue = pow(2, operandSize)-1;
//see if input value to too large to be represented with the given OperandSize
if(positive)
{
signedOverflow = (absValue > maxValue/2) ? 1: 0;
}
else
{
signedOverflow = (absValue > (maxValue/2+1)) ? 1: 0;
}
if(radix == 8)
{
printf("Input: Value %o Radix %d OperandSize %d\n", value, radix, operandSize);
}
else if (radix == 16)
{
printf("Input: Value %#X Radix %d OperandSize %d\n", value, radix, operandSize);/* code */
}
else
{
printf("Input: Value %d Radix %d OperandSize %d\n", value, radix, operandSize);
}
//see if a valid radix value is given
if(radix != 8 && radix !=10 && radix !=16)
{
printf("Invalid Radix Value");
printf("\n");
printf("\n");
continue;
}
//see if a valid operandSize is given
if(operandSize != 4 && operandSize !=8 && operandSize != 16)
{
printf("Invalid Operand Size Value");
printf("\n");
printf("\n");
continue;
}
printf("Output: Value Maximum Minimum\n");
printf("Binary (abs) 0b");
pbinaryNum = toBinary(absValue, operandSize);
if(pbinaryNum == NULL)
{
printf("Error: toBinary returned a NULL");
continue;
}
printf("\n");
printf("Octal (abs) %#o %#o 0", absValue, maxValue);
printf("\n");
printf("Decimal (abs) %d %d 0", absValue, maxValue);
printf("\n");
printf("Hexadecimal (abs) %#X %#X 0", absValue, maxValue);
printf("\n");
printf("Signed One's Complement 0b");
signedOnesComp(pbinaryNum, operandSize, positive, signedOverflow);
printf("\n");
printf("Signed Two's Complement 0b");
signedTwosComp(pbinaryNum, operandSize, positive, signedOverflow);
printf("\n");
printf("Signed Magnitude 0b");
signedMagnitude(pbinaryNum, operandSize, positive, signedOverflow);
printf("\n");
printf("\n");
}
}
//conversion to binary from https://www.geeksforgeeks.org/program-decimal-binary-conversion/
int * toBinary(int value, int operandSize)
{
static int binaryValue[16];
int temp =0;
for(int i = 0; i < 16; i++)
{
binaryValue[i] = temp;
}
int n =0;
//this while loop was taken from the "geeksforgeeks.org source"
while (value > 0)
{
// storing remainder in binary array
binaryValue[n] = value % 2;
value = value / 2;
n++;
}
for(int i = operandSize-1; i >= 0; i--)
{
printf("%d",binaryValue[i]);
}
//Prints maximum
printf(" 0b");
for(int i = 0; i <operandSize; i++)
{
printf("1");
}
//Prints minimum
printf(" 0b");
for(int i = 0; i <operandSize; i++)
{
printf("0");
}
return binaryValue;
}
void signedOnesComp(int *value, int operandSize, _Bool pos, _Bool signedOverflow)
{
if(signedOverflow)
{
printf("ERROR!!");
printf(" ");
}
else
{
//prints a positive or a negative ones complement bit string
if(pos)
{
for(int i = operandSize-1; i >= 0; i--)
{
printf("%d",(value[i]));
}
}
else
{
for(int i = operandSize-1; i >= 0; i--)
{
printf("%d",!(value[i]));
}
}
printf(" ");
}
// print maximum value
for(int i = operandSize-1; i >= 0; i--)
{
if(i==(operandSize-1))
{
printf("0b0");
}
else
{
printf("1");
}
}
printf(" ");
// print minimum value
for(int i = operandSize-1; i >= 0; i--)
{
if(i==(operandSize-1))
{
printf("0b1");
}
else
{
printf("0");
}
}
}
void signedTwosComp(int *value, int operandSize, _Bool pos, _Bool signedOverflow)
{
int temp;
int temp2;
int flag = 0;
int j = 0;
if(signedOverflow)
{
printf("ERROR!!");
printf(" ");
}
else
{
if(pos)
{
for(int i = operandSize-1; i >= 0; i--)
{
printf("%d",(value[i]));
}
}
else
{
//algorithm does the one complement first and then adds 1
//This loop does the ones complement
for(int i = 0; i<16; i++)
{
temp = value[i];
value[i] = !temp;
}
//this loop adds 1 to the ones complement
while(flag == 0)
{
temp2 = value[j];
value[j] = !temp2;
if(value[j] == 1)
{
flag = 1;
}
j++;
}
for(int i = operandSize-1; i >= 0; i--)
{
printf("%d",(value[i]));
}
}
printf(" ");
}
// print maximum value
for(int i = operandSize-1; i >= 0; i--)
{
if(i==(operandSize-1))
{
printf("0b0");
}
else
{
printf("1");
}
}
printf(" ");
// print minimum value
for(int i = operandSize-1; i >= 0; i--)
{
if(i==(operandSize-1))
{
printf("0b1");
}
else
{
printf("0");
}
}
}
void signedMagnitude(int *value, int operandSize, _Bool pos, _Bool signedOverflow)
{
if(signedOverflow)
{
printf("ERROR!!");
printf(" ");
}
else
{
if(pos)
{
for(int i = operandSize-1; i >= 0; i--)
{
printf("%d",(value[i]));
}
}
else
{
for(int i = operandSize-1; i >= 0; i--)
{
//adds the necessary sign bit in the MSB position
if(i == (operandSize-1))
{
printf("1");
}
else
{
printf("%d",(value[i]));
}
}
}
printf(" ");
}
// print maximum value
for(int i = operandSize-1; i >= 0; i--)
{
if(i==(operandSize-1))
{
printf("0b0");
}
else
{
printf("1");
}
}
printf(" 0b");
// print minimum value
for(int i = operandSize-1; i >= 0; i--)
{
printf("1");
}
}
|
C
|
#ifndef HASHMAP_H
#define HASHMAP_H
/**
* Opaque hashmap reference
*/
typedef struct hashmap hashmap;
typedef int(*hashmap_callback)(void *data, const char *key, void *value);
/**
* Creates a new hashmap and allocates space for it.
* @arg initial_size The minimim initial size. 0 for default (64).
* @arg map Output. Set to the address of the map
* @return 0 on success.
*/
int hashmap_init(int initial_size, hashmap **map);
/**
* Destroys a map and cleans up all associated memory
* @arg map The hashmap to destroy. Frees memory.
*/
int hashmap_destroy(hashmap *map);
/**
* Returns the size of the hashmap in items
*/
int hashmap_size(hashmap *map);
/**
* Gets a value.
* @arg key The key to look for. Must be null terminated.
* @arg value Output. Set to the value of th key.
* 0 on success. -1 if not found.
*/
int hashmap_get(hashmap *map, char *key, void **value);
/**
* Puts a key/value pair.
* @arg key The key to set. This is copied, and a seperate
* version is owned by the hashmap. The caller the key at will.
* @notes This method is not thread safe.
* @arg key_len The key length
* @arg value The value to set.
* 0 if updated, 1 if added.
*/
int hashmap_put(hashmap *map, char *key, void *value);
/**
* Deletes a key/value pair.
* @notes This method is not thread safe.
* @arg key The key to delete
* @arg key_len The key length
* 0 on success. -1 if not found.
*/
int hashmap_delete(hashmap *map, char *key);
/**
* Clears all the key/value pairs.
* @notes This method is not thread safe.
* 0 on success. -1 if not found.
*/
int hashmap_clear(hashmap *map);
/**
* Iterates through the key/value pairs in the map,
* invoking a callback for each. The call back gets a
* key, value for each and returns an integer stop value.
* If the callback returns 1, then the iteration stops.
* @arg map The hashmap to iterate over
* @arg cb The callback function to invoke
* @arg data Opaque handle passed to the callback
* @return 0 on success, or the return of the callback.
*/
int hashmap_iter(hashmap *map, hashmap_callback cb, void *data);
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* stack_utils2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tmerli <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/02/02 17:33:27 by tmerli #+# #+# */
/* Updated: 2018/02/15 05:07:03 by tmerli ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
int move_stack(char *move, t_stack **stacka, t_stack **stackb)
{
if (!ft_strcmp(move, "sa"))
swap(stacka);
else if (!ft_strcmp(move, "sb"))
swap(stackb);
else if (!ft_strcmp(move, "ss"))
s_swap(stacka, stackb);
else if (!ft_strcmp(move, "pa"))
push(stackb, stacka);
else if (!ft_strcmp(move, "pb"))
push(stacka, stackb);
else if (!ft_strcmp(move, "ra"))
rotate(stacka);
else if (!ft_strcmp(move, "rb"))
rotate(stackb);
else if (!ft_strcmp(move, "rr"))
r_rotate(stacka, stackb);
else if (!ft_strcmp(move, "rra"))
reverse_rotate(stacka);
else if (!ft_strcmp(move, "rrb"))
reverse_rotate(stackb);
else if (!ft_strcmp(move, "rrr"))
r_reverse_rotate(stacka, stackb);
else
return (0);
return (1);
}
int last(t_stack *a)
{
int last;
last = 0;
while (a)
{
last = a->nb;
a = a->next;
}
return (last);
}
t_stack *new_stack(int nb)
{
t_stack *stack;
if (!(stack = (t_stack*)malloc(sizeof(t_stack))))
return (NULL);
stack->nb = nb;
stack->pivot = 0;
stack->next = NULL;
return (stack);
}
void free_stack(t_stack *stack)
{
t_stack *tmp;
while (stack)
{
tmp = stack->next;
free(stack);
stack = tmp;
}
}
void print_stack(t_stack *stack)
{
ft_putendl("__");
while (stack)
{
ft_putnbr(stack->nb);
ft_putchar('\n');
stack = stack->next;
}
}
|
C
|
/* -*- mode: c; c-basic-offset: 4; -*- */
/*!
* \brief Operating system routines.
* \author Hershal Bhave
* \author Eric Crosson
* \version 0.1
* \date 2015
* \pre None
* \copyright GNU Public License.
* \addtogroup OS Operating system routines
*/
/*! \note There exists an array of threads in OS_THREADS, which we
* categorize into two double-linked-lists; one LL is used to to
* point to the circle of running threads, the other is used to point
* to the circle of dead threads. We do this so we can O(1) lookup
* for both the circle of dead and running threads. This makes it
* easy to walk through both circles and perform operations on them
* in reasonably quick time (i.e. faster than array looping).
*/
|
C
|
#include <stdio.h>
#include <pthread.h>
#include "utils.h"
#include "rdtsc.h"
void *func(void *threadid) {
pthread_exit(NULL);
}
int main(int argc, char* argv[]) {
int runs = get_runs(argc, argv);
unsigned long long clock_total = 0;
int j;
for (j = 0; j < runs; j++) {
unsigned long long start, end, diff;
long i;
pthread_t t;
start = rdtsc();
int rc = pthread_create(&t, NULL, func, (void *)i);
end = rdtsc();
diff = end - start;
clock_total = clock_total + diff;
//printf("%llu\n", diff);
}
printf("AVG: %lld\n", clock_total/runs);
pthread_exit(NULL);
}
|
C
|
#include <stdio.h>
int main(int argc, char *argv[])
{
int i=0;
// go through each string in argv
//why am i skipping argv[0]?
for (i=1; i < argc; i++) {
printf("arg %d: %s\n", i, argv[i]);
}
//let's make our own array of strings
char *states[] = {
"California", "Oregon",
"Washington", "Illinois"
};
int num_states = 4;
printf("mmmk states0 is: %s\n", states[0]);
printf("oook argv1 is: %s\n", argv[1]);
argv[1] = states[0];
printf("argv1 is now: %s\n", argv[1]);
printf("states0 is still: %s\n", states[0]);
for (i = 0; i < num_states; i++) {
printf("state %d: %s\n", i, states[i]);
}
return 0;
}
|
C
|
#include <stdio.h>
#define BUFSIZE 256
char buffer[BUFSIZE];
int buf_no = 0;
int front = 0;
int rear = 0;
// 1o
int getchr(void)
{
if(buf_no <= 0)
return getchar();
else {
int temp;
buf_no--;
temp = buffer[front++];
if(front == BUFSIZE)
front = 0;
return temp;
}
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int x = 3;
int fun(int a, int b)
{
if (a > b)
return (a + b);
else
return (a - b);
}
int f(int a)
{
int b = 0;
static int c = 3;
a = c++, b++;
return (a);
}
void inc()
{
static int x = 1;
x *= (x + 1);
printf("%d ", x);
return;
}
int main()
{
/*int x = 3, y = 8, z = 6, r;
r = fun(fun(x, y), 2 * z);
printf("%d\n", r);*/
//**********************************
/*int a = 2, i, k;
for (i = 0; i < 2; i++)
{
k = f(a++);
}
printf("%d\n", k);*/
//**********************************
int i;
for (i = 1; i < x; i++)
{
inc();
}
return 0;
}
|
C
|
/*********************************************************************
Blosc - Blocked Shuffling and Compression Library
Roundtrip tests for the NEON-accelerated shuffle/unshuffle.
Copyright (c) 2021 Lucian Marc <[email protected]>
https://blosc.org
License: BSD 3-Clause (see LICENSE.txt)
See LICENSE.txt for details about copyright and rights to use.
**********************************************************************/
#include "test_common.h"
#include "../blosc/shuffle.h"
#include "../blosc/shuffle-generic.h"
/* Include NEON-accelerated shuffle implementation if supported by this compiler.
TODO: Need to also do run-time CPU feature support here. */
#if defined(SHUFFLE_USE_NEON)
#include "../blosc/shuffle-neon.h"
#else
#if defined(_MSC_VER)
#pragma message("NEON shuffle tests not enabled.")
#else
#warning NEON shuffle tests not enabled.
#endif
#endif /* defined(SHUFFLE_USE_NEON) */
/** Roundtrip tests for the NEON-accelerated shuffle/unshuffle. */
static int test_shuffle_roundtrip_neon(size_t type_size, size_t num_elements,
size_t buffer_alignment, int test_type) {
#if defined(SHUFFLE_USE_NEON)
size_t buffer_size = type_size * num_elements;
/* Allocate memory for the test. */
void* original = blosc_test_malloc(buffer_alignment, buffer_size);
void* shuffled = blosc_test_malloc(buffer_alignment, buffer_size);
void* unshuffled = blosc_test_malloc(buffer_alignment, buffer_size);
/* Fill the input data buffer with random values. */
blosc_test_fill_random(original, buffer_size);
/* Shuffle/unshuffle, selecting the implementations based on the test type. */
switch (test_type) {
case 0:
/* neon/neon */
shuffle_neon(type_size, buffer_size, original, shuffled);
unshuffle_neon(type_size, buffer_size, shuffled, unshuffled);
break;
case 1:
/* generic/neon */
shuffle_generic(type_size, buffer_size, original, shuffled);
unshuffle_neon(type_size, buffer_size, shuffled, unshuffled);
break;
case 2:
/* neon/generic */
shuffle_neon(type_size, buffer_size, original, shuffled);
unshuffle_generic(type_size, buffer_size, shuffled, unshuffled);
break;
default:
fprintf(stderr, "Invalid test type specified (%d).", test_type);
return EXIT_FAILURE;
}
/* The round-tripped data matches the original data when the
result of memcmp is 0. */
int exit_code = memcmp(original, unshuffled, buffer_size) ?
EXIT_FAILURE : EXIT_SUCCESS;
/* Free allocated memory. */
blosc_test_free(original);
blosc_test_free(shuffled);
blosc_test_free(unshuffled);
return exit_code;
#else
return EXIT_SUCCESS;
#endif /* defined(SHUFFLE_USE_NEON) */
}
/** Required number of arguments to this test, including the executable name. */
#define TEST_ARG_COUNT 5
int main(int argc, char** argv) {
/* argv[1]: sizeof(element type)
argv[2]: number of elements
argv[3]: buffer alignment
argv[4]: test type
*/
/* Verify the correct number of command-line args have been specified. */
if (TEST_ARG_COUNT != argc) {
blosc_test_print_bad_argcount_msg(TEST_ARG_COUNT, argc);
return EXIT_FAILURE;
}
/* Parse arguments */
uint32_t type_size;
if (!blosc_test_parse_uint32_t(argv[1], &type_size) || (type_size < 1)) {
blosc_test_print_bad_arg_msg(1);
return EXIT_FAILURE;
}
uint32_t num_elements;
if (!blosc_test_parse_uint32_t(argv[2], &num_elements) || (num_elements < 1)) {
blosc_test_print_bad_arg_msg(2);
return EXIT_FAILURE;
}
uint32_t buffer_align_size;
if (!blosc_test_parse_uint32_t(argv[3], &buffer_align_size)
|| (buffer_align_size & (buffer_align_size - 1))
|| (buffer_align_size < sizeof(void*))) {
blosc_test_print_bad_arg_msg(3);
return EXIT_FAILURE;
}
uint32_t test_type;
if (!blosc_test_parse_uint32_t(argv[4], &test_type) || (test_type > 2)) {
blosc_test_print_bad_arg_msg(4);
return EXIT_FAILURE;
}
/* Run the test. */
return test_shuffle_roundtrip_neon(type_size, num_elements, buffer_align_size, test_type);
}
|
C
|
#include<stdio.h>
#include<stdbool.h>
char *itoa(int n)
{
int length=0;
bool negative = false;
char *ret = NULL;
if(n<0)
{
n = -n;
length++;
negative = true;
}
int temp = n;
while(temp)
{
temp/=10;
length++;
}
ret = malloc(sizeof(char)*(length+1));
ret[length]='\0';
if(negative)
ret[0]='-';
int i = length-1;
while(n)
{
ret[i--] = n%10+'0';
printf("ret[i]=%x\n",ret[i]);
n/=10;
}
return ret;
}
int atoi(char *str){
bool negative = false;
int value = 0;
if(str == NULL)
return value;
printf("*str++ = %c\n",*str);
if(*str == '-'){
negative = true;
str++;
}
printf("*str++ = %s\n",str);
while(*str != '\0'){
if(*str >= '0' && *str <= '9'){
value = value*10 + (int)*str - 48; // 48 = '0'
printf("value = %d\n",value);
}
str++;
}
if(negative)
value = -value;
return value;
}
int main(void)
{
char *string = itoa(14357);
printf("string is %s\n", string);
int num = atoi("123456789");
printf("test is %d\n", num);
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "thread_pool.h"
#define TASK_QUEUE_SIZE (100)
#define NSEC_PER_SEC 1000000000
#define QUEUE_IS_EMPTY(queue) (queue->head == queue->tail)
#define QUEUE_IS_FULL(queue) (queue->head == (queue->tail + 1) % TASK_QUEUE_SIZE)
#define QUEUE_ADD_POS(pos) ((pos) = ((pos) + 1) % TASK_QUEUE_SIZE)
static thread_pool_t *g_thread_pool;
static int g_terminate;
static void *worker_thread_func(void *arg)
{
thread_pool_t *pool = (thread_pool_t *)arg;
task_queue_t *queue = pool->queue;
worker_func_t func;
void *args;
int rv;
while (!g_terminate) {
rv = pthread_cond_timedwait(&pool->notify, &pool->lock, NSEC_PER_SEC/5);
if (rv != 0) {
pthread_mutex_unlock(&pool->lock);
if (rv != ETIMEDOUT) {
errno = rv;
fprintf(stderr, "E00034:\tpthread_cond_timedwait() error!!!!!\n");
return (void *)rv;
}
continue;
}
func = queue->tasks[queue->head].func;
args = queue->tasks[queue->head].arg;
queue->tasks[queue->head].func = NULL;
queue->tasks[queue->head].arg = NULL;
QUEUE_ADD_POS(queue->head);
pthread_mutex_unlock(&pool->lock);
//调用回调函数
(*func)(args);
}
}
/*
* 初始化线程池
* thread_num 为线程池的线程数量
*/
int init_thread_pool(int thread_num)
{
g_thread_pool = (thread_pool_t *)malloc(sizeof(thread_pool_t));
if (g_thread_pool == NULL) {
fprintf(stderr, "malloc thread_pool_t error!!!!\n");
return -1;
}
memset(g_thread_pool, 0, sizeof(thread_pool_t));
g_thread_pool->pids = (pthread_t *)malloc(sizeof(pthread_t) * thread_num);
if (g_thread_pool->pids == NULL) {
fprintf(stderr, "malloc thread ids error!!!!\n");
return -1;
}
g_thread_pool->queue = (task_queue_t *)malloc(sizeof(task_queue_t));
if (g_thread_pool->queue == NULL) {
fprintf(stderr, "malloc task queue error!!!!\n");
return -1;
}
g_thread_pool->queue->tasks = (thread_task_t *)malloc(sizeof(thread_task_t) * TASK_QUEUE_SIZE + 1);
if (g_thread_pool->queue->tasks == NULL) {
fprintf(stderr, "malloc task queue error!!!!\n");
return -1;
}
int i = 0, ret = 0;
for (; i < g_thread_pool->thread_num; ++i) {
ret = pthread_create(&g_thread_pool->pids[i], NULL,
worker_thread_func, g_thread_pool);
if (ret != 0) {
fprintf(stderr, "pthread_create error!!!!\n");
return -2;
}
g_thread_pool->thread_num++;
g_thread_pool->started++;
}
g_thread_pool->queue->head = 0;
g_thread_pool->queue->tail = 0;
return 0;
}
int thread_pool_add(thread_pool_t *thread_pool, worker_func_t func, void *arg)
{
task_queue_t *task_queue = thread_pool->queue;
pthread_mutex_lock(&thread_pool->lock);
if (QUEUE_IS_FULL(task_queue)) {
fprintf(stderr, "task queue is full error!!!!\n");
pthread_mutex_unlock(&thread_pool->lock);
return -1;
}
task_queue->tasks[task_queue->tail].func = func;
task_queue->tasks[task_queue->tail].arg = arg;
QUEUE_ADD_POS(task_queue->tail);
pthread_cond_signal(&thread_pool->notify);
pthread_mutex_unlock(&thread_pool->lock);
return 0;
}
//TODO:销毁线程池
//TODO:挂起线程池
int main()
{
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: wta <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/08/09 14:40:44 by wta #+# #+# */
/* Updated: 2019/01/12 01:21:58 by wta ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static void *del_tab(char **tab, int len)
{
int i;
if (tab)
{
i = -1;
while (++i < len)
ft_strdel(&tab[i]);
free(tab);
tab = NULL;
}
return (NULL);
}
static void splitbuf(char *str, char *tokens)
{
int i;
int j;
i = -1;
while (str[++i] != '\0')
{
j = -1;
while (tokens[++j] != '\0')
{
if (str[i] == tokens[j])
str[i] = '\0';
}
}
}
static int cnt_wd(char *str, int len)
{
int count;
int wd;
int i;
count = 0;
i = -1;
wd = 0;
while (++i < len)
{
if (wd == 0 && str[i] != '\0')
{
count++;
wd = 1;
}
else if (str[i] == '\0')
wd = 0;
}
return (count);
}
static char *dup_n_wd(char *buf, int len, int n)
{
int nwd;
int wd;
int i;
i = -1;
wd = 0;
nwd = 0;
while (++i < len)
{
if (wd == 0 && buf[i] != '\0')
{
if (nwd == n)
return (ft_strdup(&buf[i]));
nwd++;
wd = 1;
}
else if (buf[i] == '\0')
wd = 0;
}
return (NULL);
}
char **ft_strsplit(char const *s, char *tokens)
{
char **split;
char buf[4096];
int len;
int wdct;
int idx;
split = NULL;
if (s != NULL)
{
ft_bzero(buf, 4096);
ft_strcpy(buf, s);
splitbuf(buf, tokens);
len = ft_strlen(s);
wdct = cnt_wd(buf, len);
if ((split = (char**)ft_memalloc((sizeof(char*) * (wdct + 1)))) != NULL)
{
idx = -1;
while (++idx < wdct)
{
if ((split[idx] = dup_n_wd(buf, len, idx)) == NULL)
return (del_tab(split, len));
}
}
}
return (split);
}
|
C
|
#include <stdio.h>
void mystery(int n)
{
if (n < 1)
{
printf("Finished\n");
}
else
{
printf("%d\n", n);
mystery(n - 1);
printf("%d\n", n);
}
}
int main()
{
mystery(3);
return 0;
}
|
C
|
#include <stdio.h>
float fonksiyon(float x);
float integral(float a, float b);
int main(){
float a, b;
printf("sirasiyla a ve b degerlerini giriniz: ");
scanf("%f%f", &a, &b);
printf("------------------------\n");
printf("3x^2 + 5x fonksiyonunun %.2f sayisindan %.2f sayisina integrali %.2f\n", a, b, integral(a, b));
}
float fonksiyon(float x){
return 3 * x * x + 5 * x;
}
float integral(float a, float b){
float n, h, k, toplam;
n = 1000;
h = (b - a) / n;
toplam = 0;
for (k = 1; k < n; k++){
toplam = toplam + fonksiyon(a + k * h);
}
return h * (fonksiyon(a) / 2 + toplam + fonksiyon(b) / 2);
}
|
C
|
#include<stdio.h>
void fun(int a)
{
printf("%d\n",a);
}
int main()
{
void (*fun_ptr)(int)=&fun;
(*fun_ptr)(5);
void (*fun_ptr2)(int)=fun;
fun_ptr2(5);
return 0;
}
|
C
|
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include "header.h"
int main() {
printf("Processo P2 avviato\n");
struct msg_calc m_p2;
m_p2.processo = P2;
key_t queue = ftok(FTOK_PATH_Q, FTOK_CHAR_Q);
int id_queue = msgget(queue,IPC_CREAT|0644);
if(id_queue < 0) {
perror("Msgget fallita");
exit(1);
}
srand(time(NULL));
int i;
for(i=0;i<11;i++){
m_p2.numero=generafloat(2,20);
printf("invio messaggio: <%lu, %f>\n", m_p2.processo, m_p2.numero);
msgsnd(id_queue, &m_p2, sizeof(struct msg_calc)-sizeof(long),0);
sleep(2);
}
return 0;
}
|
C
|
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// ex 1
/*
int main(int argc, char *argv[]){
char input;
while(read(0,&input,1) > 0){
write(1,&input,1);
}
return 0;
}
*/
// ex 2
/*
int main(int argc, char *argv[]){
if(argc != 2){
printf("Numero de argumentos invalido.");
return 1;
}
char c = 'a';
int file, i;
file = open(argv[1],O_WRONLY|O_CREAT|O_TRUNC,0666);
if(file == -1){
printf("Erro a abrir/criar ficheiro");
return 1;
}
for(i = 0; i < 10*1024*1024; i++){
write(file,&c,1);
}
close(file);
return 0;
}
*/
// ex 3
/*
int main(int argc, char *argv[]){
if(argc != 2){
printf("Numero de argumentos invalido.\n");
return 1;
}
// long type is the backbone
long size = strtol(argv[1],0,10);
char input[size];
while(read(0,input,size) > 0){
write(1,input,size);
memset(input,0,size);
}
return 0;
}
*/
/*
// ex 4
time ./ficha1 1 < ex2.txt > lixo.txt
real 2m15.291s
user 0m0.936s
sys 2m14.340s
time ./ficha1 1024 < ex2.txt > lixo.txt
real 0m0.147s
user 0m0.004s
sys 0m0.140s
*/
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
int getNegativeCount(int *array, int n) {
int counter = 0;
for (int i = 0; i < n; ++i) {
if (array[i]<0){
counter++;
}
}
return counter;
}
int minimalAbsElement(int *array, int n){
int min = 100;
for (int i = 0; i < n; ++i) {
if (abs(min) > abs(array[i])){
min = array[i];
}
}
return min;
}
int sum(int * array, int n){
int sum = 0, min = minimalAbsElement(array, n);
for (int i = 0; i < n; ++i) {
if(array[i] == min){
for (int j = 0; j < n; ++j) {
sum += array[j];
}
return sum;
}
}
return sum;
}
int main() {
int n = 40;
int *array = (int *) calloc(n, sizeof(int));
srand(time(NULL));
for (int i = 0; i < n; ++i) {
array[i] = -100 + rand() % (100 + 100 + 1);
}
printf("\nThe sum of the elements of the array, located after the minimum modulo element. - %d", sum(array, n));
printf("\nThe number of negative elements of the array. - %d", getNegativeCount(array, n));
return 0;
}
|
C
|
#ifndef BSP_UART_H
#define BSP_UART_H
//*****************************************************************************
// File dependencies.
//*****************************************************************************
#include "stdint-gcc.h"
#include "semphr.h"
//*****************************************************************************
// Public / Internal definitions.
//*****************************************************************************
#define BSP_UART_0_TX_BUFFER_SIZE (8192)
#define BSP_UART_0_RX_BUFFER_SIZE (512)
#define BSP_UART_1_TX_BUFFER_SIZE (8192)
#define BSP_UART_1_RX_BUFFER_SIZE (512)
/*!
* \enum BSP_UART_ID_T
*/
typedef enum {
BSP_UART_ID_0, /*!< ID of 1st instance of UART */
BSP_UART_ID_1, /*!< ID of 2nd instance of UART */
N_BSP_UART /*!< Number of Uart supported */
} BSP_UART_ID_T;
/*!
* \enum BSP_UART_RETVAL_T
*/
typedef enum {
BSP_UART_NO_ERROR = 0, /*! No Error */
BSP_UART_ERROR, /*! Error in Task Creation */
BSP_UART_INVALID_ARG, /*! Invalid Argument */
BSP_UART_MUTEX_LOCK_FAILED, /*! Failed to Lock Mutex */
BSP_UART_INSUFFICIENT_BUFF, /*! Insufficient space in UART Transmit buffer */
N_BSP_UART_RETVAL
} BSP_UART_RETVAL_T;
//*****************************************************************************
// Public function prototypes.
//*****************************************************************************
#if defined(__cplusplus)
extern "C" {
#endif /* __cplusplus*/
//*****************************************************************************
//!
//! \brief This function initializes the underlying hardware.
//!
//! \param None
//!
//! \return Refer to BSP_UART_RETVAL_T
//!
//*****************************************************************************
extern BSP_UART_RETVAL_T BSP_UART_Init(void);
//*****************************************************************************
//!
//! \brief This function sets the BSP UART underlying hardware interrupt priority
//!
//! \param uartId Refer to ::BSP_UART_ID_T
//! \param prioNum Priority Value
//!
//! \return \c void
//!
//*****************************************************************************
extern void BSP_UART_SetIntPriority(BSP_UART_ID_T uartId, uint32_t prioNum);
//*****************************************************************************
//!
//! \brief This function registers a semaphore handle to signal that frame
//! is received.
//!
//! \param uartId Refer to ::BSP_UART_ID_T
//! \param semHdlr Semaphore Handle
//! \param delimiter Frame delimiter value
//!
//! \return Refer to ::BSP_UART_RETVAL_T
//!
//*****************************************************************************
extern BSP_UART_RETVAL_T BSP_UART_RegisterFrameReceiveSempahore(BSP_UART_ID_T uartId, SemaphoreHandle_t semHdlr, uint8_t delimiter);
//*****************************************************************************
//!
//! \brief This function is used to send data to underlying hardware.
//!
//! \param uartId Uart Instance ID (::BSP_UART_ID_T)
//! \param pData pointer to buffer that contains the data
//! \param size number of bytes to send
//!
//! \return Refer to ::BSP_UART_RETVAL_T
//!
//*****************************************************************************
extern BSP_UART_RETVAL_T BSP_UART_Send(BSP_UART_ID_T uartId,const uint8_t *pData, const uint32_t size);
//*****************************************************************************
//!
//! \brief This function is used to read bytes from underlying hardware.
//!
//! \param uartId Uart Instance ID (::BSP_UART_ID_T)
//! \param pData pointer to buffer that receives the data
//! \param pSize number of bytes to read. On function return, this indicates\n
//! the number of bytes read.
//!
//! \return Refer to ::BSP_UART_RETVAL_T
//!
//*****************************************************************************
extern BSP_UART_RETVAL_T BSP_UART_Receive(BSP_UART_ID_T uartId, uint8_t *pData, uint32_t *pSize);
//*****************************************************************************
//!
//! \brief This function returns the number of bytes in the receive buffer.
//!
//! \param uartId Uart Instance ID (::BSP_UART_ID_T)
//!
//! \return Number of bytes in the receive buffer
//!
//*****************************************************************************
extern uint32_t BSP_UART_GetRcvByteCount(BSP_UART_ID_T uartId);
#if defined(__cplusplus)
}
#endif /* __cplusplus*/
#endif // End BSP_UART_H
|
C
|
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
int x = 0;
int j = 1;
char* caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char* shor = "abcdefghijklmnopqrstuvwxyz";
//CHECKING INPUT FROM COMMAND LINE
if (argc != 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
// Checking for 26 letters
if (strlen(argv[1]) != 26)
{
printf("Key must contain 26 characters.\n");
return 1;
}
//Checking for weird stuff(input)
{
if (argc != 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
//checking for weird characters
else
{
for (j = 1; j < argc; j++)
{
for (int k = 0; k < strlen(argv[j]); k++)
if (((argv[j][k] >= 65) && (argv[j][k] <= 90)) || ((argv[j][k] >= 97) && (argv[j][k] <= 122)))
;
else
{
printf("Usage: ./substitution key\n");
return 1;
}
}
}
}
//Checking for Duplicates in Key
{
for (int v = 0; v < 26; v++)
for (int z = v + 1; z < 27; z++)
{
if (argv[1][v] == argv[1][z])
{
printf("Duplicates found in Key, exiting with code 1...\n");
return 1;
}
}
}
//end of check input function
printf("plaintext:");
char t[1000];
scanf("%[^\n]%*c", t);
//gets input
printf("ciphertext:");
//Run Main function
{
for (int u = 0; u < strlen(t); u++)
{
if ((t[u] >= 97) && (t[u] <= 122))
{
for (int g = 0; g < 26; g++)
{
if (t[u] == shor[g])
{
t[u] = argv[1][g];
if (t[u] <= 96)
{
printf("%c", t[u] + 32);
}
else
{
printf("%c", t[u]);
}
}
}
}
else if ((t[u] >= 65) && (t[u] <= 90))
{
for (int h = 0; h < 26; h++)
{
if (t[u] == caps[h])
{
t[u] = argv[1][h];
if (t[u] > 90)
{
printf("%c", t[u] - 32);
break;
}
else
{
printf("%c", t[u]);
break;
}
}
}
}
else
{
printf("%c", t[u]);
}
}
}
printf("\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
int main() {
struct winsize size;
if(isatty(STDOUT_FILENO) == 0)
return 0;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &size);
printf("%d rows, %d cols\n", size.ws_row, size.ws_col);
return 0;
}
|
C
|
#include <avr/io.h>
#include "adc_ATmega1284.h"
#include "joystick_IO.h"
//========================= Shared Variables =======================================
// ADC input of left joystick controlling DC motor
unsigned short FRJoystickInput = 0x00;
// FR joystick directions: 0 == forward, 1 == reverse
unsigned char FRDirection = 0x00;
// FR joystick speeds: 0, 1, 2, 3 (zero speed, low speed, medium speed, fast speed)
unsigned char FRSpeed = 0x00;
// LR joystick angles: 0, 1, 2, 3, 4, 5, 6, 7 ()
unsigned char LRAngles = 0x00;
//==================================================================================
void start_adc() {
ADC_init();
}
//================== Foward/Reverse Joystick State Machine =========================
enum FRJoystickDirection_states {FRJoystickDirectionIdle, FRJoystickDirectionForward, FRJoystickDirectionReverse};
int FRJoystickDirectionTick(int state) {
FRJoystickInput = ADC_read(1);
// State Transitions
switch(state) {
case FRJoystickDirectionIdle:
if(FRJoystickInput > 550) {
state = FRJoystickDirectionForward;
} else if(FRJoystickInput < 470) {
state = FRJoystickDirectionReverse;
}
else {
state = FRJoystickDirectionIdle;
}
break;
case FRJoystickDirectionForward:
state = FRJoystickDirectionIdle;
break;
case FRJoystickDirectionReverse:
state = FRJoystickDirectionIdle;
break;
default:
state = FRJoystickDirectionIdle;
break;
}
// State Actions
switch(state) {
case FRJoystickDirectionIdle:
FRDirection = 0;
break;
case FRJoystickDirectionForward:
FRDirection = 0;
break;
case FRJoystickDirectionReverse:
FRDirection = 1;
break;
}
return state;
}
//================= FR Joystick Motor Speed State Machine ================================
enum FRJoystickSpeed_states {FRJoystickSpeedIdle, FRJoystickSpeedGo};
int FRJoystickSpeedTick(int state) {
// State Transitions
switch(state) {
case FRJoystickSpeedIdle:
if(FRJoystickInput > 550 || FRJoystickInput < 470) {
state = FRJoystickSpeedGo;
}
else {
state = FRJoystickSpeedIdle;
}
break;
case FRJoystickSpeedGo:
if(FRJoystickInput > 550 || FRJoystickInput < 470) {
state = FRJoystickSpeedGo;
}
else {
state = FRJoystickSpeedIdle;
}
break;
default:
state = FRJoystickSpeedIdle;
break;
}
// State Actions
switch(state) {
case FRJoystickSpeedIdle:
FRSpeed = 0x00;
break;
case FRJoystickSpeedGo:
if((FRJoystickInput > 0 && FRJoystickInput <= 156) || (FRJoystickInput > 862)){
FRSpeed = 0x03;
}
else if((FRJoystickInput > 156 && FRJoystickInput <= 312) || (FRJoystickInput > 706 && FRJoystickInput <= 862)){
FRSpeed = 0x02;
}
else if((FRJoystickInput > 312 && FRJoystickInput <= 468) || (FRJoystickInput > 550 && FRJoystickInput <= 706)){
FRSpeed = 0x01;
}
break;
}
return state;
}
//=================== Servo Motor Angle State Machine =====================================
enum LRJoystick_states {LRJoystickIdle, LRJoystickTurnLeft, LRJoystickTurnRight};
int LRJoystickTick(int state) {
unsigned short LRJoystickInput = ADC_read(0);
// State Transitions
switch(state) {
case LRJoystickIdle:
if(LRJoystickInput > 550) {
state = LRJoystickTurnRight;
} else if(LRJoystickInput < 470) {
state = LRJoystickTurnLeft;
}
else {
state = LRJoystickIdle;
}
break;
case LRJoystickTurnLeft:
if(LRJoystickInput > 550) {
state = LRJoystickTurnRight;
} else if(LRJoystickInput < 470) {
state = LRJoystickTurnLeft;
}
else {
state = LRJoystickIdle;
}
break;
case LRJoystickTurnRight:
if(LRJoystickInput > 550) {
state = LRJoystickTurnRight;
} else if(LRJoystickInput < 470) {
state = LRJoystickTurnLeft;
}
else {
state = LRJoystickIdle;
}
break;
default:
state = LRJoystickIdle;
break;
}
// State Actions
switch(state) {
case LRJoystickIdle:
LRAngles = 0x03;
break;
case LRJoystickTurnLeft:
if(LRJoystickInput > 0 && LRJoystickInput <= 156){
LRAngles = 0x00;
} else if(LRJoystickInput > 156 && LRJoystickInput <= 312){
LRAngles = 0x01;
} else if(LRJoystickInput > 312 && LRJoystickInput <= 470){
LRAngles = 0x02;
}
break;
case LRJoystickTurnRight:
if(LRJoystickInput > 550 && LRJoystickInput <= 706){
LRAngles = 0x04;
} else if(LRJoystickInput > 706 && LRJoystickInput <= 862){
LRAngles = 0x05;
} else if(LRJoystickInput > 862){
LRAngles = 0x06;
}
break;
}
return state;
}
//===========================================================================================
|
C
|
#include<stdio.h>
void escreveCaracter(char a, int i) {
for (int j=0; j < i; j++) {
printf("%c", a);
}
}
int main()
{
int b, l, a;
char c;
do {
printf("B: Numero impar >= 3: ");
scanf("%d",&b);
} while (b % 2 == 0 || b < 3 || b <= 0);
do {
printf("L: Numero impar >= 1 e < (B/2): ");
scanf("%d",&l);
} while (l % 2 == 0 || l > (b/2) || l <= 0);
do {
printf("A: Numero > 1: ");
scanf("%d",&a);
} while (a <= 0);
printf("Character para desenho: ");
scanf(" %c",&c);
int spaces = b / 2;
int stars = 1;
do {
for (int i=0; i < spaces; i++) {
escreveCaracter(' ',1);
}
for (int j=0; j< stars; j++){
escreveCaracter(c,1);
}
printf("\n");
spaces = spaces -1;
stars = stars + 2;
} while (spaces >= 0);
int spaces2 = (b - l) / 2;
for (int m=0; m < a; m++) {
for (int n=0; n < spaces2; n++) {
escreveCaracter(' ',1);
}
for (int o=0; o < l; o++) {
escreveCaracter(c,1);
}
printf("\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/*
create a simple program which checks if the num is odd or even
*/
int main()
{
int num;
num = 32;
switch (num%2) {
case 1 : printf("The number is odd.");
break;
case 0 : printf("The number is even.");
break;
}
return 0;
}
|
C
|
/*This Program displays the greatest & smallest number of 3 entered numbers. */
# include <stdio.h>
# include <conio.h>
void main()
{ int x,y,z; x=y=z=0; clrscr();
printf("\nEnter Number #1 : \t"); scanf("%d",&x);
printf("\nEnter Number #2 : \t"); scanf("%d",&y);
printf("\nEnter Number #3 : \t"); scanf("%d",&z);
if (x>y)
{ if (x>z)
{ printf("\n\nGreatest Number : %d",x);
if (y>z) printf("\n\nSmallest Number : %d",z);
else printf("\n\nSmallest Number : %d",y);
}
else
{ printf("\n\nGreatest Number : %d",z);
printf("\n\nSmallest Number : %d",y);
}
}
else
{ if (y>z)
{ printf("\n\nGreatest Number : %d",y);
if (z>x) printf("\n\nSmallest Number : %d",x);
else printf("\n\nSmalleest Number : %d",z);
}
else
{ printf("\n\nGreatest Number : %d",z);
printf("\n\nSmallest Number : %d",x);
}
}
getch();
}
|
C
|
//
// main.c
// Array
//
// Created by Eun Jae Lee on 20/11/17.
// Copyright © 2017 Eun Jae Lee. All rights reserved.
//
// data type array_name[size];
// int a[10];
// char ch[30];
// One dimensional arrays
// 2 dimennsional arrays
// multi dimentional arrays
#include <stdio.h>
int main() {
int marks[5], total = 0, avg = 0, i;
printf("Enter your 5 subject marks \n");
for (i=0; i<5; i++) {
scanf("%d ",&marks[i]);
total = total + marks[i];
avg = total / 5;
}
printf("Total marks = %d \n",total);
printf("Your average = %d \n", avg);
getchar();
/*
int a[5] = {10,20,30,40,50};
printf("%d \n",a[3]);
=========================
int a[5];
a[0] = 10;
a[1] = 20;
a[2] = 30;
a[3] = 40;
a[4] = 50;
*/
// return 0;
}
|
C
|
//
// Created by svalov on 8/18/16.
//
#include <funcResults.h>
#include <hashTable.h>
#include <memory.h>
#include <stdio.h>
bool checkEquality(hashEntry_T *entry, hashVal_T hash, void *key, size_t size, equalFunc_T equal){
if(NULL == entry)
return false;
if(NULL == key)
return false;
if(0 == size)
return false;
hashVal_T value = entry->HashValue;
if(value == hash) {
// compare key
int compare;
compare = equal(entry->Key, key, size);
return (0 == compare);
}
return false;
}
hashEntry_T** searchEntry(hashTable_T* table, void* key, void* data){
if(NULL == table)
return NULL;
if(NULL == key)
return NULL;
hashVal_T hash = table->HashFunction(key, table->KeySize);
uint32_t bin = hash % table->StorageSize;
hashEntry_T** entry = table->Table+bin;
while(NULL != *entry){
hashEntry_T* cEntry = *entry;
if(checkEquality(cEntry, hash, key, table->KeySize, table->EqualFunction)){
if(NULL != data) {
int cmp = memcmp(cEntry->Data, data, table->DataSize);
if(0 == cmp)
return entry;
} else
return entry;
}
entry = &(cEntry->Next);
}
return NULL;
}
int hashInit(hashTable_T* table, hashFunc_T function, int storageSize, size_t keySize, size_t dataSize){
if(NULL == table)
return FUNC_RESULT_FAILED_ARGUMENT;
if(NULL == function)
return FUNC_RESULT_FAILED_ARGUMENT;
if(0 == storageSize)
return FUNC_RESULT_FAILED_ARGUMENT;
if(0 == keySize)
return FUNC_RESULT_FAILED_ARGUMENT;
if(0 == dataSize)
return FUNC_RESULT_FAILED_ARGUMENT;
table->DataSize = dataSize;
table->KeySize = keySize;
table->HashFunction = function;
table->StorageSize = storageSize;
table->Count = 0;
table->EqualFunction = memcmp;
table->DataFreeFunction = free;
table->KeyFreeFunction = free;
#ifdef HASH_ENABLE_ITERATOR
table->Last = NULL;
#endif
size_t totalStorageSize = sizeof(hashEntry_T*)*storageSize;
table->Table = malloc(totalStorageSize);
if(NULL == table->Table)
return FUNC_RESULT_FAILED_MEM_ALLOCATION;
memset(table->Table,0, totalStorageSize);
return FUNC_RESULT_SUCCESS;
}
int hashClear(hashTable_T* table){
if(NULL == table)
return FUNC_RESULT_FAILED_ARGUMENT;
for(int i=0; i<table->StorageSize;i++){
while(table->Table[i]!=NULL){
// remove from list
hashEntry_T* current = table->Table[i];
table->Table[i] = current->Next;
// free memory
table->KeyFreeFunction(current->Key);
table->DataFreeFunction(current->Data);
free(current);
}
}
table->Count = 0;
return FUNC_RESULT_SUCCESS;
}
int hashFree(hashTable_T* table){
if(NULL == table)
return FUNC_RESULT_FAILED_ARGUMENT;
if(0 != table->Count)
return FUNC_RESULT_FAILED_ARGUMENT;
free(table->Table);
table->Table = NULL;
return FUNC_RESULT_SUCCESS;
}
int hashAdd(hashTable_T* table, void* key, void* data){
if(NULL == table)
return FUNC_RESULT_FAILED_ARGUMENT;
if(NULL == key)
return FUNC_RESULT_FAILED_ARGUMENT;
if(NULL == data)
return FUNC_RESULT_FAILED_ARGUMENT;
hashVal_T hash = table->HashFunction(key, table->KeySize);
uint32_t bin = hash % table->StorageSize;
hashEntry_T* entry = malloc(sizeof(hashEntry_T));
if(NULL == entry)
return FUNC_RESULT_FAILED_MEM_ALLOCATION;
entry->HashValue = hash;
entry->Next = table->Table[bin];
//allocate
entry->Key = malloc(table->KeySize);
entry->Data = malloc(table->DataSize);
if(NULL == entry->Key || NULL == entry->Data){
free(entry->Key);
free(entry->Data);
free(entry);
return FUNC_RESULT_FAILED_MEM_ALLOCATION;
}
//copy
memcpy(entry->Key, key, table->KeySize);
memcpy(entry->Data, data, table->DataSize);
#ifdef HASH_ENABLE_ITERATOR
entry->ListPrev = table->Last;
if(NULL != table->Last)
table->Last->ListNext = entry;
entry->ListNext = NULL;
table->Last = entry;
#endif
table->Table[bin] = entry;
table->Count++;
return FUNC_RESULT_SUCCESS;
}
int hashRemove(hashTable_T* table, void* key){
return hashRemoveExact(table, key, NULL);
}
int hashRemoveExact(hashTable_T* table, void* key, void* value){
if(NULL == table)
return FUNC_RESULT_FAILED_ARGUMENT;
if(NULL == key)
return FUNC_RESULT_FAILED_ARGUMENT;
hashEntry_T** entry = searchEntry(table, key, value);
if(NULL != entry) {
hashEntry_T* cEntry = *entry;
#ifdef HASH_ENABLE_ITERATOR
//remove from list
if (NULL != cEntry->ListPrev)
cEntry->ListPrev->ListNext = cEntry->ListNext;
if (NULL != cEntry->ListNext)
cEntry->ListNext->ListPrev = cEntry->ListPrev;
if (table->Last == cEntry)
table->Last = cEntry->ListPrev;
#endif
//remove
table->KeyFreeFunction(cEntry->Key);
table->DataFreeFunction(cEntry->Data);
*entry = cEntry->Next;
free(cEntry);
table->Count--;
return FUNC_RESULT_SUCCESS;
}
return FUNC_RESULT_SUCCESS;
}
void* hashGetPtr(hashTable_T* table, void* key){
if(NULL == table)
return NULL;
if(NULL == key)
return NULL;
hashEntry_T** entry = searchEntry(table, key, NULL);
if(NULL != entry) {
hashEntry_T* cEntry = *entry;
return cEntry->Data;
}
return NULL;
}
int hashGet(hashTable_T* table, void* key, void* data){
if(NULL == table)
return FUNC_RESULT_FAILED_ARGUMENT;
if(NULL == key)
return FUNC_RESULT_FAILED_ARGUMENT;
if(NULL == data)
return FUNC_RESULT_FAILED_ARGUMENT;
hashEntry_T** entry = searchEntry(table, key, NULL);
if(NULL != entry) {
hashEntry_T* cEntry = *entry;
// copy
memcpy(data, cEntry->Data, table->DataSize);
return FUNC_RESULT_SUCCESS;
}
return FUNC_RESULT_FAILED;
}
bool hashContain(hashTable_T* table, void* key){
return hashContainExact(table, key ,NULL);
}
bool hashContainExact(hashTable_T* table, void* key, void* data){
if(NULL == table)
return false;
if(NULL == key)
return false;
hashEntry_T** entry = searchEntry(table, key, data);
if(NULL != entry)
return true;
return false;
}
#ifdef HASH_ENABLE_ITERATOR
int hashGetFirst(hashTable_T* table, void* key, hashIterator_T* iterator){
if(NULL == table)
return FUNC_RESULT_FAILED_ARGUMENT;
if(NULL == iterator)
return FUNC_RESULT_FAILED_ARGUMENT;
if(NULL == key)
return FUNC_RESULT_FAILED_ARGUMENT;
int hash = table->HashFunction(key, table->KeySize);
int bin = hash % table->StorageSize;
hashEntry_T** entry = searchEntry(table, key, NULL);
if(NULL != entry) {
hashEntry_T *cEntry = *entry;
// fill iterator
iterator->Item = cEntry;
iterator->Compare = true;
iterator->KeySize = table->KeySize;
iterator->Key = malloc(iterator->KeySize);
iterator->EqualFunction = table->EqualFunction;
if (NULL == iterator->Key)
return FUNC_RESULT_FAILED_MEM_ALLOCATION;
memcpy(iterator->Key, key, iterator->KeySize);
iterator->HashValue = hash;
//next fill
iterator->NextItem = iterator->Item!=NULL ? iterator->Item->Next : NULL;
// return sucess
return FUNC_RESULT_SUCCESS;
}
return FUNC_RESULT_FAILED;
}
int hashIterator(hashTable_T* table, hashIterator_T* iterator){
if(NULL == table)
return FUNC_RESULT_FAILED_ARGUMENT;
if(NULL == iterator)
return FUNC_RESULT_FAILED_ARGUMENT;
iterator->HashValue = 0;
iterator->Compare = false;
iterator->Key = NULL;
iterator->KeySize = 0;
iterator->Item = table->Last;
iterator->EqualFunction = table->EqualFunction;
iterator->NextItem = iterator->Item!=NULL ? iterator->Item->ListPrev : NULL;
return FUNC_RESULT_SUCCESS;
}
bool hashIteratorEnded( hashIterator_T * item ){
if(NULL == item)
return false;
return (NULL == item->Item);
}
int hashIteratorNext(hashIterator_T* item){
if(NULL == item)
return FUNC_RESULT_FAILED_ARGUMENT;
if(NULL == item->Item)
return FUNC_RESULT_FAILED_ARGUMENT;
if(item->Compare) {
do {
item->Item = item->NextItem;
item->NextItem = item->NextItem!=NULL ? item->NextItem->Next : NULL;
}while(!hashIteratorEnded( item ) &&
!checkEquality(item->Item, item->HashValue, item->Key, item->KeySize, item->EqualFunction));
return FUNC_RESULT_SUCCESS;
}
else{
item->Item = item->NextItem;
item->NextItem = item->NextItem!=NULL ? item->NextItem->ListPrev : NULL;
return FUNC_RESULT_SUCCESS;
}
}
void* hashIteratorData(hashIterator_T* item){
if(NULL == item)
return NULL;
if(NULL == item->Item)
return NULL;
return item->Item->Data;
}
void* hashIteratorKey(hashIterator_T* item){
if(NULL == item)
return NULL;
if(NULL == item->Item)
return NULL;
return item->Item->Key;
}
int hashIteratorFree(hashIterator_T* item){
if(NULL == item)
return FUNC_RESULT_FAILED_ARGUMENT;
item->Item = NULL;
free(item->Key);
item->Key = NULL;
item->KeySize = 0;
item->Compare = false;
return FUNC_RESULT_SUCCESS;
}
#endif
|
C
|
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
using namespace std;
int main()
{
int t;
scanf("%d", &t);
for (int cas = 1; cas <= t; ++cas)
{
int m, n;
scanf("%d%d", &m, &n);
float ans = m * n;
if (m % 2 && n % 2)
{
ans += 0.41;
}
printf("Scenario #%d:\n%.2f\n\n", cas, ans);
}
return 0;
}
|
C
|
#include "unistd.h"
#include "fcntl.h"
#include "stdio.h"
#include "stdlib.h"
int main()
{
int fd;
while(1)
{
fd = open("/dev/myuart",O_RDWR);
if(fd < 0)
{
printf("open /dev/myuart error\n");
exit(-1);
}
sleep(2);
close(fd);
sleep(2);
}
return 0;
}
|
C
|
//Q9.Write a C program that accepts an integer from keyboard and calculates
// the sum of digits of an integer
#include <stdio.h>
int main()
{
int i,i1,i2,sum=0;
printf("\n\n\t\tEnter the integer");
scanf("%d",&i);
i1=i;
while(i1!=0)
{
i2=i1%10;
sum=sum+i2;
i1=i1/10;
}
printf("\n\n\t\tthe sum of the digits is %d\n\n",sum);
return 0;
}
|
C
|
//5. xay dung cac ham;
// nhiap mang co 2 ptu
// in mang co n ptu
// tim gia tri ln va vi tri phan tu co gt lon nhat do trong mang
#include<stdio.h>
#include<math.h>
#define MAX_SIZE 100
void Nhapmang(int arr[], int n ){
for (int i=0; i<n ; i++)
{
printf("Phan tu arr[%d]: ",i);
scanf("%d", &arr[i]);
}
}
void Xuatmang(int arr[], int n) {
// printf("\n");
for (int i=0; i<n; i++)
{
printf("%d\t",arr[i]);
}
}
int GTLN(int a[],int n ){
int max=a[0];
for (int i=0; i<n;i++){
if (a[i]>max){
max=a[i];
printf("\nGTLN trong mang:%5d\n",max);
}
}
return max;
}
void vitriptucoGTLN (int a[], int n){
int vitrimax=GTLN(a,n);
printf("Vi tri cua phan tu co GTLN: ");
for (int i=0; i<n;i++){
if (a[i]==vitrimax){
printf("%5d",i+1);
}
}
}
int main(){
int arr[MAX_SIZE];
int n;
do{
printf("Nhap n = ");
scanf("%d", &n);
}while(n <= 0 || n > MAX_SIZE);
Nhapmang(arr, n);
Xuatmang(arr, n);
vitriptucoGTLN(arr,n);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "LinkedList.h"
#include "Parser.h"
#include "Venta.h"
int parser_Ventas(FILE* pFile , LinkedList* pList)
{
int ret=-1;
char auxBufferIdVenta[50];
int bufferIdVenta;
char auxBufferIdProd[50];
char bufferFecha[125];
char bufferCodProducto[50];
char auxBufferCantidad[50];
int bufferCantidad;
char auxBufferPrecioUnitario[50];
float bufferPrecioUnitario;
char bufferCUIT[50];
int flagFirstLine=0;
Venta* venta;
if(pFile != NULL)
{
do{
if(fscanf(pFile,"%[^,],%[^,],%[^,],%[^,],%[^,],%[^\n]\n",auxBufferIdVenta,bufferFecha,auxBufferIdProd,auxBufferCantidad,auxBufferPrecioUnitario,bufferCUIT)==6 && flagFirstLine!=0)
{
bufferIdVenta = atoi(auxBufferIdVenta);
bufferCantidad = atoi(auxBufferCantidad);
bufferPrecioUnitario=atof(auxBufferPrecioUnitario);
venta=Venta_newConParametros(bufferIdVenta,bufferFecha,auxBufferIdProd,bufferCantidad,bufferPrecioUnitario, bufferCUIT);
ll_add(pList,(Venta*)venta);
}
if(flagFirstLine==0){
flagFirstLine++;
ret=0;
}
} while(!feof(pFile));
}
return ret;
}
|
C
|
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "parser.h"
#define MIN(a, b) (a > b ? b : a)
#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
#define mix(a,b,c) \
{ \
a -= c; a ^= rot(c, 4); c += b; \
b -= a; b ^= rot(a, 6); a += c; \
c -= b; c ^= rot(b, 8); b += a; \
a -= c; a ^= rot(c,16); c += b; \
b -= a; b ^= rot(a,19); a += c; \
c -= b; c ^= rot(b, 4); b += a; \
}
#define final(a,b,c) \
{ \
c ^= b; c -= rot(b,14); \
a ^= c; a -= rot(c,11); \
b ^= a; b -= rot(a,25); \
c ^= b; c -= rot(b,16); \
a ^= c; a -= rot(c,4); \
b ^= a; b -= rot(a,14); \
c ^= b; c -= rot(b,24); \
}
static const uint16_t crc16tab[256]= {
0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,
0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,
0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,
0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,
0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,
0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d,
0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4,
0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,
0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,
0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b,
0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,
0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,
0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,
0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49,
0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,
0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,
0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f,
0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067,
0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,
0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,
0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d,
0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,
0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,
0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634,
0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab,
0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,
0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,
0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92,
0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9,
0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,
0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,
0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0
};
uint32_t lookup3_hash(const char *key)
{
uint32_t a,b,c;
uint32_t length = strlen(key);
/* Set up the internal state */
a = b = c = 0xdeadbeef + length;
const uint8_t *k = (const uint8_t *)key;
while (length > 12) {
a += k[0];
a += ((uint32_t)k[1])<<8;
a += ((uint32_t)k[2])<<16;
a += ((uint32_t)k[3])<<24;
b += k[4];
b += ((uint32_t)k[5])<<8;
b += ((uint32_t)k[6])<<16;
b += ((uint32_t)k[7])<<24;
c += k[8];
c += ((uint32_t)k[9])<<8;
c += ((uint32_t)k[10])<<16;
c += ((uint32_t)k[11])<<24;
mix(a,b,c);
length -= 12;
k += 12;
}
switch(length) {
case 12: c+=((uint32_t)k[11])<<24;
case 11: c+=((uint32_t)k[10])<<16;
case 10: c+=((uint32_t)k[9])<<8;
case 9 : c+=k[8];
case 8 : b+=((uint32_t)k[7])<<24;
case 7 : b+=((uint32_t)k[6])<<16;
case 6 : b+=((uint32_t)k[5])<<8;
case 5 : b+=k[4];
case 4 : a+=((uint32_t)k[3])<<24;
case 3 : a+=((uint32_t)k[2])<<16;
case 2 : a+=((uint32_t)k[1])<<8;
case 1 : a+=k[0]; break;
case 0 : return c;
}
final(a,b,c);
return c;
}
uint16_t crc16(struct pos_array *pos)
{
uint16_t crc = 0;
const struct pos *p;
uint8_t *s;
int h, c, len;
for (h = 0; h < pos->pos_len; h++) {
p = &pos->items[h];
len = p->len;
s = p->str;
for (c = 0; c < len; c++) {
crc = (crc << 8) ^ crc16tab[((crc >> 8) ^ *s++) & 0x00FF];
}
}
return crc;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.