language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
// The MIT License (MIT)
//
// Copyright (c) 2013 Alex Kozlov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "asplite/parser.h"
#include <assert.h>
#include <stdlib.h>
// Searches char c in range between |begin| and |end| exclusive.
// The function updates new_lines with number of new lines encountered.
// begin Points to the beginning of the range.
// end Point just past the last character in the range.
// c Character to search for.
// new_lines Number of encountered new lines will be added here if specified.
// Returns pointer pointing to teh found character, otherwise NULL.
static const char *SearchCharacter(const char *begin, const char *end, char c,
size_t *new_lines)
{
size_t newline_count = 0;
const char *p;
assert(begin != NULL);
assert(end != NULL);
assert(begin <= end);
for (p = begin; p < end; p++) {
if (*p == '\n')
newline_count++;
if (*p == c) {
if (new_lines != NULL)
*new_lines += newline_count;
return p;
}
}
return NULL;
}
static const char *TryParseChunk(const char *buffer, const char *current,
const char *end, ParserCallback callback, void *user_data,
size_t *lineno)
{
enum ChunkType type = InlineCodeRenderBlock;
size_t available = end - current;
size_t lines = 0;
const char *iter;
// There should be at least 4 characters that make
// an empty block <%%>.
// The longest prefix is <%--
if (available < 4)
return NULL;
assert(*current == '<');
if (*++current != '%')
return NULL;
switch(*++current) {
case '@':
type = DirectiveBlock;
current++;
break;
case '=':
type = InlineExpressionRenderBlock;
current++;
break;
case ':':
type = InlineExpressionRenderHtmlBlock;
current++;
break;
case '-':
if (*(current + 1) == '-') {
type = ServerSideComment;
current += 2;
}
break;
}
for (iter = current; iter < end; iter++) {
if (*iter == '\n')
lines++;
if (type == ServerSideComment) {
if (*iter == '-' && (iter + 3) < end &&
iter[1] == '-' && iter[2] == '%' && iter[3] == '>') {
callback(buffer, type, *lineno,
current - buffer, (iter - 1) - buffer, user_data);
*lineno += lines;
return iter + 4;
}
}
else if (*iter == '%') {
if ((iter + 1) < end && iter[1] == '>') {
callback(buffer, type, *lineno,
current - buffer, (iter - 1) - buffer, user_data);
*lineno += lines;
return iter + 2;
}
}
}
// TODO: If there is an unterminated server side block, raise an error.
return NULL;
}
int ParseBuffer(const char *buffer, size_t buffer_size,
ParserCallback callback, void *user_data)
{
const char *current = buffer;
const char *last = current;
const char *end = buffer + buffer_size;
const char *new_position;
size_t lineno = 1;
while (current < end) {
size_t lines = 0;
const char *at = SearchCharacter(current, end, '<', &lines);
if (at != NULL) {
callback(buffer, Content, lineno, last - buffer, at - buffer,
user_data);
lineno += lines;
current = at;
last = at;
new_position = TryParseChunk(buffer, current, end, callback,
user_data, &lineno);
if (new_position != NULL) {
// Point just past the directive
last = current = new_position;
}
else {
// Skip <. last is pointing to <
current += 1;
}
}
else {
callback(buffer, Content, lineno, last - buffer, end - buffer,
user_data);
break;
}
}
return 0;
}
|
C
|
//
// Created by Suraj M on 1/27/19.
//
#include "matrix.h"
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include <math.h>
int sign(int num){
if((num % 2 ) == 0){
return 1;
}
else{
return -1;
}
}
Matrix makeMatrix(int num_rows) {
Matrix matrix;
matrix.vals = malloc(num_rows * sizeof(double *));
for (int i = 0; i < num_rows; i++) {
matrix.vals[i] = malloc(num_rows * sizeof(double));
}
return matrix;
}
void readValues(FILE* f,int num_rows,Matrix* matrix){
//char buffer[256];
int i = 0, j = 0;
double val;
for (i = 0; i < num_rows; i++) {
for (j = 0; j < num_rows; j++) {
fscanf(f, "%lf", &val);
matrix -> vals[i][j] = val;
}
}
}
void createSubMatrix(Matrix* m, Matrix* orig_matrix,int num_rows,int col_offset){
int i, j = 0;
int offset = 0;
for ( j = 0; j < num_rows; j++){
if(j == col_offset){
j++;
offset=1;
}
for(i = 1; i < num_rows; i++){
if(j == col_offset){
j++;
offset=1;
}
if(offset==1){
m->vals[i-1][j-1] = orig_matrix->vals[i][j];
}
else{
m->vals[i-1][j] = orig_matrix->vals[i][j];
}
}
}
}
void freeMatrix(Matrix* matrix, int num_rows){
for(int i = 0 ; i < num_rows ; i++) {
free(matrix->vals[i]);
}
free(matrix->vals);
}
Matrix createMat(int num_rows){
int j = 0;
Matrix mat;
mat.vals = malloc(num_rows * sizeof( double *));
for (j = 0; j < num_rows; j++) {
mat.vals[j] = malloc(num_rows * sizeof( double));
}
return(mat);
}
double findDeterminant(Matrix* matrix, int num_rows, int offset) {
double determinant=0;
Matrix subMat;
if(num_rows==2){
determinant = ((matrix->vals[0][0] * matrix->vals[1][1]) -(matrix->vals[0][1] * matrix->vals[1][0]));
return determinant;
}
else if(num_rows==1){
determinant = matrix->vals[0][0];
return determinant;
}
else{
for(int i = 0; i<num_rows; i++){
subMat = createMat(num_rows-1);
createSubMatrix(&subMat,matrix, num_rows, i);
determinant = determinant+ (double) matrix->vals[0][i] * sign(i+0) * findDeterminant(&subMat,(num_rows-1),i);
freeMatrix(&subMat, num_rows-1);
}
return determinant;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Swap utility
void swap(long int* a, long int* b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
/*
void BubbleSort(long int arr[], long int n)
{
long int i, j;
for (i = 0; i < n - 1; i++)
{
for (j = 1; j < n-i-1; j++)
if (arr[j]< arr[i])
swap(&arr[i], &arr[j]);
}
}
*/
void InsertionSort(int arr[],int n){
for(int i=1;i<n;i++){
int key = arr[i];
int j=i-1;
while(j>=0 && arr[j]>key){
arr[j+1]=arr[j];
j--;
}
arr[j+1]=key;
}
}
int main()
{
long int n = 1000;
int it = 0;
double tim1[10];
printf("A_size\tInsertion sort\n");
while (it++ < 10)
{
long int a[n];
for (int i = 0; i < n; i++)
{
long int no = rand() % n + 1;
a[i] = no; }
clock_t start, end;
start = clock();
InsertionSort(a, n);
end = clock();
tim1[it] = ((double)(end - start));
// for plotting graph with integer values
printf("%li, %li\n",n,(long int)tim1[it]);
// increases the size of array by 10000
n += 1000;
}
return 0;
}
|
C
|
#include <stdio.h>
// ϱ
void main() {
float input[3];
for (int i=0; i < 3; i++) {
printf("%d ° :", i + 1);
scanf("%f", &input[i]);
}
printf(" : %.3f", (input[0] + input[1] + input[2]) / 3);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/input.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#define DEVS_FILE "/proc/bus/input/devices"
#define BUF_LEN 4096
#define DEV_ST_LINE 9
#define DEV_LINE_SIZE 512
char _dev_struct[DEV_ST_LINE][DEV_LINE_SIZE+1];
char _at_kbd_file[256];
char _usb_kbd_file[256];
int kfd[2] = {-1,-1};
void handle_sig(int sig) {
switch(sig) {
case SIGINT:
case SIGTERM:
for(int i=0; i<2; i++) {
if (kfd[i] > 0)
close(kfd[i]);
}
exit(0);
default:;
}
}
int init_dev_file() {
int errcode = 0;
FILE * f = fopen(DEVS_FILE, "r");
if (f == NULL){
perror("fopen");
return -1;
}
char *p = NULL;
int i=0;
int k = 0;
int len = 0;
char *kp = NULL;
char *ep;
while (1) {
p = fgets(_dev_struct[i], DEV_LINE_SIZE, f);
if (errno && p == NULL) {
errcode = -1;
goto end_dev;
}else if (p == NULL) {
break;
}
if (strcmp(p, "\n") == 0) {
i=0;
continue;
}
i++;
if (i < DEV_ST_LINE) {
continue;
} else {
i = 0;
}
if (strstr(_dev_struct[1], "keyboard") || strstr(_dev_struct[1], "Keyboard")) {
k = 0;
len = strlen(_dev_struct[1]);
while(k<len) {
if (_dev_struct[1][k++] == '"')
break;
}
if (strncmp(_dev_struct[1]+k, "USB", 3) == 0) {
kp = _usb_kbd_file;
} else if (strncmp(_dev_struct[1]+k, "AT" , 2) == 0){
kp = _at_kbd_file;
}
if (strstr(_dev_struct[2], "input0")) {
ep = strstr(_dev_struct[5], "event");
if (ep != NULL) {
for(int j=0;j<strlen(ep); j++) {
if (ep[j]==' ') {
ep[j] = '\0';
break;
}
}
strcpy(kp, "/dev/input/");
strcat(kp, ep);
}
}
}
}
end_dev:;
fclose(f);
return errcode;
}
int set_nonblocking(int fd) {
int old_opt = fcntl(fd, F_GETFL);
int new_opt = old_opt | O_NONBLOCK;
fcntl(fd, F_SETFL, new_opt);
return old_opt;
}
void handle_key_evt(int fd) {
struct input_event kt;
int count = 0;
count = read(fd, &kt, sizeof(kt));
if (count < 0 && errno == EAGAIN) {
return ;
} else if (count > 0) {
if (kt.type == EV_KEY) {
if (kt.value == 0 || kt.value == 1) {
printf("key %d %s\n", kt.code, kt.value?"pressed":"released");
if (kt.code == KEY_ESC)
kill(getpid(), SIGTERM);
}
}
} else {
perror("read");
}
}
int main(int argc, char *argv[]) {
signal(SIGINT, handle_sig);
signal(SIGTERM, handle_sig);
_at_kbd_file[0] = '\0';
_usb_kbd_file[0] = '\0';
if (init_dev_file() < 0) {
return -1;
}
printf("%s\n%s\n", _at_kbd_file, _usb_kbd_file);
int kfd_count = 0;
if (strlen(_at_kbd_file) > 0) {
kfd[0] = open(_at_kbd_file, O_RDONLY);
if (kfd[0] < 0) {
dprintf(2, "%s\n", _at_kbd_file);
} else {
kfd_count++;
}
}
if (strlen(_usb_kbd_file) > 0) {
kfd[1] = open(_usb_kbd_file, O_RDONLY);
if (kfd[1] < 0) {
dprintf(2, "%s\n", _usb_kbd_file);
perror("open");
}
else {
kfd_count++;
}
}
if (kfd_count <= 0) {
dprintf(2, "Error: failed to open input device file\n");
return -1;
}
for(int i=0;i<2;i++) {
if (kfd[i] > 0)
set_nonblocking(kfd[i]);
}
while (1) {
if (kfd[1] > 0) {
handle_key_evt(kfd[1]);
}
if (kfd[0] > 0) {
handle_key_evt(kfd[0]);
}
//usleep(500000);
}
return 0;
}
|
C
|
#include<stdio.h>
void combine (int *arr,int start,int *result,int index,int n,int arr_len)
{
for(int ct = start;ct < arr_len-index+1;ct++){
result[n-index] = ct;
if(index==1){
for(int j = 0;j<n;j++) {
printf("%d\t", arr[result[j]]);
}
printf("\n");
}
else{
combine(arr,ct+1,result,index-1,n,arr_len);
}
}
}
int main()
{
int Num = 6;
int arr[Num]={1,2,3,4,5,6};
int result[Num]={};
int arr_len = sizeof(arr)/sizeof(int);
for(int n = 1;n<=arr_len;n++){
int start = 0;
int index = n;
combine(arr,start,result,index,n,arr_len);
}
}
|
C
|
#include <stdio.h>
int main() {
double width, height, perimeter, area;
width = 10.0;
height = 32;
perimeter = (2*width) + (2*height);
area = width * height;
printf("Width: %.2f Height: %.2f \n", width, height);
printf("Area: %.2f, Perimeter: %.2f \n", area, perimeter);
}
|
C
|
/*
* Assignment 1: my_copy.c
* Implement a cp(copy) command with –p option.
*
* Pre-requisites:-
* Knowledge about system calls, How to read and understand ‘man pages’.
* Command line arguments, File operation system calls (open, read, write, close, fstat ..etc)
*
* Objective: -
* To understand and implement using basic system calls.
*
* Requirements: -
* 1. Copy source file to destination file which passed through cmd-line arguments.
* After copying both files must have equal size, even it’s a zero sized file.
* Eg: - ./my_copy source.txt dest.txt.
* 1. If arguments are missing show the usage (help) info to user.
* 2. Implement a my_copy() function where you have to pass two file descriptors.
* Int my_copy(int source_fd, int dest_fd);
* 3. If –p option passed copy permissions as well to destination (refer ‘fstat’ man page).
* Eg: - ./my_copy –p source.txt dest.txt.
* 4. If the destination file is not present then create a new one with given name.
* Incase if it is present show a confirmation from user to overwrite.
* Eg: - ./my_copy source.txt destination.txt
* File “destination.txt” is already exists.
* Do you want to overwrite (Y/n)
* 5. If user type ‘Y/n’ or enter key overwrite the destination with new file.
* In n/N don’t overwrite and exit from program.
* 6. Program should able handle all possible error conditions.
*
* Sample execution: -
* 1. When no arguments are passed
* ./my_copy
* Insufficient arguments
* Usage:- ./my_copy [option] <source file> <destination file>
*
* 2. When destination file is not exists
* ./my_copy source.txt dest.txt
* New dest.txt file is created and source.txt file will be copied to dest.txt file
*
* 3. When destination file exists
* ./my_copy source.txt dest.txt
* File “dest.txt” is already exists.
* Do you want to overwrite (Y/n)
*
* 4. When –p option passed
* ./my_copy –p source.txt dest.txt
* Permissions also copied from source file to destination file
*
* Also try:-
* 5. ./my_copy /etc/hosts /etc/services
* 6. ./my_copy /dev/zero /tmp/new
*
* Useful commands:-
* Man, cksum, ls –l
*/
#include "syscalls.h"
int main(int argc, char *argv[])
{
int fd, fd2, read_len;
char choice;
//for -p to copy the permission mode
struct stat sb;
/* Do arg count check */
if (argc < 3)
{
printf("Insufficient arguments\n");
printf("Usage:- ./my_copy [option] <source file> <destination file> \n");
return 1;
}
/* check for -p permissions */
if (strcmp(argv[1], "-p") == 0 )
{
printf("Permissions also copied from source file to destination file.\n");
/* To open source.txt to read */
if ( (fd = open(argv[2], O_RDONLY)) == -1 )
{
perror("open");
return -1;
}
//get the permission of this file
//stat(argv[2], &sb);
if (stat(argv[2], &sb) )
{
perror("stat");
return -1;
}
/* To create/ open dest.txt to copy the data */
if ( (fd2 = open(argv[3], O_WRONLY|O_CREAT|O_TRUNC, 0666)) == -1 )
{
printf("File %s is already exists.\n Do you want to overwrite (y/n): ", argv[2]);
scanf("\n%c", &choice);
if(choice == 'n' || choice == 'N')
{
return 0;
}
else if (choice == 'y' || choice == 'Y')
{
//for overwriting
if ( (fd2 = creat(argv[3], 0666)) == -1 )
{
perror("open");
return -1;
}
}
}
//change the permisions
if (chmod(argv[3], sb.st_mode & 07777))
{
perror("chmod");
return -1;
}
}
/* when no -p option is given */
else
{
/* To open source.txt to read */
if ( (fd = open(argv[1], O_RDONLY)) == -1 )
{
perror("open");
return -1;
}
/* To create/ open dest.txt to copy the data */
if ( (fd2 = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, 0666)) == -1 )
{
printf("File %s is already exists.\n Do you want to overwrite (y/n): ", argv[2]);
scanf("\n%c", &choice);
if(choice == 'n' || choice == 'N')
{
return 0;
}
else if (choice == 'y' || choice == 'Y')
{
//for overwriting
if ( (fd2 = creat(argv[2], 0666)) == -1 )
{
perror("open");
return -1;
}
}
}
}
//copy appropraitely
my_copy(fd, fd2);
close(fd);
close(fd2);
return 0;
}
int my_copy(int source_fd, int dest_fd)
{
int read_len = 0;
char buff[BUFF_SIZE];
//read the data from the source.txt till end and copy
while( ((read_len = read(source_fd, buff, BUFF_SIZE)) != -1 ) && (read_len != 0))
{
if( write(dest_fd, buff, read_len) == -1 )
{
perror("write");
close(source_fd);
close(dest_fd);
return -1;
}
}
return 0;
}
|
C
|
#include "Classification.h"
Classification_t *ClassificationConstruct(int classificationIndex, char *classificationName)
{
Classification_t *newClassification = (Classification_t *)malloc(sizeof(Classification_t));
if(newClassification == NULL)
{
printf("Not enough memory");
exit(0);
}
newClassification->classificationIndex = classificationIndex;
strcpy(newClassification->classificationName, classificationName);
newClassification->next = NULL;
return newClassification;
}
Classification_t *getClassification(Classification_t **startClassification, char *classificationName)
{
if(*startClassification == NULL)
{
*startClassification = ClassificationConstruct(0, classificationName);
return *startClassification;
}
Classification_t *currentClassification = *startClassification;
Classification_t *prevClassification = NULL;
while(currentClassification != NULL)
{
if(strcmp(currentClassification->classificationName, classificationName) == 0)
{
return currentClassification;
}
prevClassification = currentClassification;
currentClassification = currentClassification->next;
}
prevClassification->next = ClassificationConstruct(prevClassification->classificationIndex+1, classificationName);
return prevClassification->next;
}
void printClassification(Classification_t *startClassification)
{
printf("CLASSIFICATION\n\n");
Classification_t *currentClassification = startClassification;
while(currentClassification != NULL)
{
printf("%s ", currentClassification->classificationName);
currentClassification = currentClassification->next;
}
printf("\n\n");
}
|
C
|
#include "load_dump.h"
#define NUM_ARGS 1
#define DESCRIPTION "integer sum numbers in the first column and output a single value\n\n"
#define USAGE "... | bsum\n\n"
#define EXAMPLE ">> echo -e '1\n2\n3\n4.1\n' | bsv | bsum | csv\n10\n\n"
int main(int argc, const char **argv) {
HELP();
SIGPIPE_HANDLER();
LOAD_DUMP_INIT();
bsv_int_t val = 0;
while (1) {
LOAD(0);
if (load_stop)
break;
switch (load_types[0]) {
case BSV_INT:
val += BYTES_TO_INT(load_columns[0]);
break;
case BSV_FLOAT:
val += BYTES_TO_FLOAT(load_columns[0]);
break;
case BSV_CHAR: ASSERT(0, "fatal: you cannot sum chars\n"); break;
}
}
load_max = 0;
load_columns[0] = (char*)&val;
load_types[0] = BSV_INT;
load_sizes[0] = sizeof(bsv_int_t);
DUMP(0, load_max, load_columns, load_types, load_sizes);
DUMP_FLUSH(0);
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
printf("\n enter the character:");
scanf("%c",&ch);
if(ch>='a' && ch<='Z' || ch>='A' && ch<='A')
printf("\nthe character is an alphabet",ch);
else
printf("\nthe character is not an alphabet",ch);
getch();
}
|
C
|
/** Pallindrom Check */
#include <stdio.h>
#include <string.h>
int main(){
char str[100];
int len, mid, i, j, flag=0;
printf("Enter your input: ");
gets(str);
len=strlen(str);
mid=len/2;
for(i=0, --len;i<=mid;i++, len--){
if(str[i]!=str[len]){
flag=1;
}
}
if(flag==0){
printf("Palindrome!");
}else{
printf("Not Palindrome!");
}
return 0;
}
|
C
|
#include<stdio.h>
int main(){
int i;
while(1){
printf("Enter no?\n"); //step -1
if(scanf(" %d",&i)>0) //step-2
printf("Num=%d\n",i);
else
printf("Entered character.Pls enter int\n");
}
}
|
C
|
/************************************/
/* Owner: Vital@Nirvana */
/* Created: 12/18/00 */
/* Modified: 8/20/01 */
/* Realm: Acadie */
/************************************/
#include <ansi.h>
#include "/players/vital/closed/headers/vital.h" /*color header*/
#include "/players/vital/dest/include/dest.h"
inherit "room/room";
reset(arg) {
if(!arg) {
set_light(1);
short_desc = "Acadie Shop";
long_desc =
" An Acadie Shop\n\
The shop has a strange material for floors and shelves. The \n\
light is provided by small globes mounted along the ceiling. \n\
All of the merchandise is neatly arranged and everything is \n\
in its place. There is a large sign along the back wall.\n ";
items = ({
"shop",
"The shop has a strange material for floors and shelves. The \n\
light is provided by small globes mounted along the ceiling. \n\
All of the merchandise is neatly arranged and everything is \n\
in its place. There is a large sign along the back wall.\n ",
"material",
"The strange material is wood. It seems like a ludicrous waste \n\
of precious resources, if it were not for the fact that this \n\
planet has plentiful forested areas",
"floors",
"The dark, brown floorboards are sturdy beneath your feet",
"shelves",
"The shelves are organized and surprisingly full",
"light",
"The light is provided by the strange glowing globes on the ceiling",
"globes",
"They glow with a natural light, but it has a light blue tint to it",
"merchandise",
"The shelves are full of various things. The shopkeeper deals \n\
in many different things",
"everything",
"The shelves are full of various things. The shopkeeper deals \n\
in many different things",
"sign",
"Perhaps if you were to \'read\' the sign, you could learn more",
"wall",
"The wall is composed of stone that must come from a nearby quarry"
});
dest_dir = ({
ACADIE+"room/sidewalk3.c","out",
});
}
}
init() {
::init();
add_action("search_me","search");
add_action("sell","sell");
add_action("value","value");
add_action("buy","buy");
add_action("list","list");
add_action("read_me", "read");
}
read_me(str) {
if(!str || str != "sign") {
notify_fail("You have to \'read sign'\ to see what is on it.\n");
return 0;
}
else if(str == "sign"); {
write("\nYou can \'buy\', \'sell\', \'value\', or \'list\' things here in the shop.\n");
}
return 1;
}
search_me(str) {
if(!str) {
notify_fail("What are trying to search?\n");
return 0;
}
switch(str) {
case "floor":
write("The boards of the floor are solid and well fitted.\n");
break;
case "shelves":
write("The search the shelves looking for something you need.\n");
break;
case "walls":
write("The walls are sturdy and the seams are well fitted.\n");
break;
default: write("You furiously search the "+str+" but find nothing.\n");
}
}
sell(string item) {
object ob;
if (!item) {
notify_fail("What are you trying to sell?\n");
return 0;
}
if (item == "all") {
object next;
ob = first_inventory(this_player());
while(ob) {
next = next_inventory(ob);
if (!ob->drop() && ob->query_value()) {
write(ob->short() + ":\t");
do_sell(ob);
}
ob = next;
}
write("Ok All items have been sold.\n");
return 1;
}
ob = present(item, this_player());
if (!ob)
ob = present(item, this_object());
if (!ob) {
write("No such item ("); write(item); write(") here.\n");
return 1;
}
do_sell(ob);
return 1;
}
do_sell(ob) {
int value, do_destroy;
value = ob->query_value();
if (!value) {
write(ob->short() + " has no value.\n");
return 1;
}
if (environment(ob) == this_player()) {
int weight;
if (call_other(ob, "drop", 0)) {
write("I can't take it from you!\n");
return 1;
}
weight = call_other(ob, "query_weight", 0);
call_other(this_player(), "add_weight", - weight);
}
if (value > 6000)
do_destroy = 1;
if(ob->query_dest_flag()) do_destroy = 1;
if (value > 1000) {
write("The shop is low on money...\n");
value = 1000;
}
write("You get "); write(value); write(" gold coins.\n");
say(call_other(this_player(), "query_name", 0) + " sells " +
call_other(ob, "short", 0) + ".\n");
call_other(this_player(), "add_money", value);
add_worth(value, ob);
if (do_destroy) {
write("The valuable item is hidden away.\n");
destruct(ob);
return 1;
}
call_other("/players/vital/closed/std/store", "store", ob);
return 1;
}
value(string item) {
int value;
string name_of_item;
if (!item)
return 0;
name_of_item = present(item);
if (!name_of_item)
name_of_item = find_item_in_player(item);
if (!name_of_item) {
if (call_other("/players/vital/closed/std/store", "value", item))
return 1;
write("No such item ("); write(item); write(") here\n");
write("or in the store.\n");
return 1;
}
value = call_other(name_of_item, "query_value", 0);
if (!value) {
write(item); write(" has no value.\n");
return 1;
}
write("You would get "); write(value); write(" gold coins.\n");
return 1;
}
buy(item) {
if (!item)
return 0;
call_other("/players/vital/closed/std/store", "buy", item);
return 1;
}
list(obj) {
call_other("/players/vital/closed/std/store", "inventory", obj);
return 1;
}
find_item_in_player(i)
{
object ob;
ob = first_inventory(this_player());
while(ob) {
if (call_other(ob, "id", i))
return ob;
ob = next_inventory(ob);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int front=-1,rear=-1;
int a[20];
void insertfrombeginning(int n){
int data;
scanf("%d",&data);
if(rear==-1){
front=0;
rear=0;
}
else if(rear==n&&front==0 || front==rear+1){
printf("\n overflow");
return;
}
else if(front==n-1){
front=0;
}
else{
front=front+1;
}
a[front]=data;
}
void insertfromend(int n){
int data;
scanf("%d",&data);
if(rear==-1){
rear=0;
front=0;
}
else if(front ==0 && rear==n-1 || front==rear+1){
printf("\n overflow, cannot insert");
}
else if(rear==n-1){
rear=0;
}
else{
rear=rear+1;
}
a[rear]=data;
}
void deletefrombeginning(int n){
if(front==-1){
printf("\n underflow, nothing to delete");
return;
}
else if(front==rear){
front=-1;
rear=-1;
}
else if(front==n-1){
front=0;
}
else
front+=1;
}
void deletefromend(int n){
if(rear==-1){
printf("\n underflow, nothing to delete");
return;
}
else if(rear==0){
rear=n-1;
}
else if(rear==front){
rear=-1;
front=-1;
}
else{
rear=rear-1;
}
}
void printx(int n){
int i;
if(front == -1){
printf("\n nothing to print");
}
else if(front<rear){
for(i=front;i<=rear;i++){
printf(" %d ",a[i]);
}
printf("\n");
}
else{
for(i=front;i<n;i++){
printf(" %d ",a[i]);
}
for(i=0;i<=rear;i++){
printf(" %d ",a[i]);
}
printf("\n");
}
}
void main(){
int n;
scanf("%d",&n);int opt2,opt3;
int opt;
printf("\n enter your choice");
do{
printf("\n 1.Input Restricted \n 2.Output Restricted");
scanf("%d",&opt);
switch(opt){
case 1:
do{
printf("\n 1.insert \n 2.Delete from END \n 3.Delete from FRONT \n 4.Exit");
scanf("%d",&opt2);
switch(opt2){
case 1: insertfromend(n);
printx(n);
break;
case 2: deletefromend(n);
printx(n);
break;
case 3: deletefrombeginning(n);
printx(n);
break;
case 4: printf("\n exiting");
break;
}
}while(opt2!=4);
break;
case 2:
do{
printf("\n 1.Insert from Beginning \n 2.Insert from END \n 3.Delete \n 4.Exit");
scanf("%d",&opt3);
switch(opt3){
case 1: insertfrombeginning(n);
printx(n);
break;
case 2: insertfromend(n);
printx(n);
break;
case 3: deletefrombeginning(n);
printx(n);
break;
case 4: printf("\n Exiting ");
printx(n);
break;
}
}while(opt3!=4);
break;
}
}while(opt!=4);
printx(n);
}
|
C
|
/*
* CTYPE.H Character classification and conversion
*/
#ifndef CTYPE_H
#define CTYPE_H
extern unsigned char _ctype[];
#define _CTc 0x01 /* control character */
#define _CTd 0x02 /* numeric digit */
#define _CTu 0x04 /* upper case */
#define _CTl 0x08 /* lower case */
#define _CTs 0x10 /* whitespace */
#define _CTp 0x20 /* punctuation */
#define _CTx 0x40 /* hexadecimal */
#define isalnum(c) (_ctype[c]&(_CTu|_CTl|_CTd))
#define isalpha(c) (_ctype[c]&(_CTu|_CTl))
#define isascii(c) !((c)&~0x7F)
#define iscntrl(c) (_ctype[c]&_CTc)
#define isdigit(c) (_ctype[c]&_CTd)
#define isgraph(c) !(_ctype[c]&(_CTc|_CTs))
#define islower(c) (_ctype[c]&_CTl)
#define isprint(c) !(_ctype[c]&_CTc)
#define ispunct(c) (_ctype[c]&_CTp)
#define isspace(c) (_ctype[c]&_CTs)
#define isupper(c) (_ctype[c]&_CTu)
#define isxdigit(c) (_ctype[c]&_CTx)
#define toupper(c) (islower(c) ? (c)^0x20 : (c))
#define tolower(c) (isupper(c) ? (c)^0x20 : (c))
#define _toupper(c) ((c)^0x20)
#define _tolower(c) ((c)^0x20)
#define toascii(c) ((c)&0x7F)
#endif CTYPE_H
|
C
|
/***
*strdate.c - contains the function "_strdate()"
*
* Copyright (c) 1989-2001, Microsoft Corporation. All rights reserved.
*
*Purpose:
* contains the function _strdate()
*
*Revision History:
* 06-07-89 PHG Module created, base on asm version
* 03-20-90 GJF Made calling type _CALLTYPE1, added #include
* <cruntime.h> and fixed the copyright. Also, cleaned
* up the formatting a bit.
* 07-25-90 SBM Removed '32' from API names
* 10-04-90 GJF New-style function declarator.
* 12-04-90 SRW Changed to include <oscalls.h> instead of <doscalls.h>
* 12-06-90 SRW Added _CRUISER_ and _WIN32 conditionals.
* 05-19-92 DJM ifndef for POSIX build.
* 04-06-93 SKS Replace _CRTAPI* with __cdecl
* 11-01-93 CFW Enable Unicode variant, rip out Cruiser.
* 02-10-95 GJF Merged in Mac version.
* 05-17-99 PML Remove all Macintosh support.
*
*******************************************************************************/
#ifndef _POSIX_
#include <cruntime.h>
#include <tchar.h>
#include <time.h>
#include <oscalls.h>
/***
*_TSCHAR *_strdate(buffer) - return date in string form
*
*Purpose:
* _strdate() returns a string containing the date in "MM/DD/YY" form
*
*Entry:
* _TSCHAR *buffer = the address of a 9-byte user buffer
*
*Exit:
* returns buffer, which contains the date in "MM/DD/YY" form
*
*Exceptions:
*
*******************************************************************************/
_TSCHAR * __cdecl _tstrdate (
_TSCHAR *buffer
)
{
int month, day, year;
SYSTEMTIME dt; /* Win32 time structure */
GetLocalTime(&dt);
month = dt.wMonth;
day = dt.wDay;
year = dt.wYear % 100; /* change year into 0-99 value */
/* store the components of the date into the string */
/* store seperators */
buffer[2] = buffer[5] = _T('/');
/* store end of string */
buffer[8] = _T('\0');
/* store tens of month */
buffer[0] = (_TSCHAR) (month / 10 + _T('0'));
/* store units of month */
buffer[1] = (_TSCHAR) (month % 10 + _T('0'));
/* store tens of day */
buffer[3] = (_TSCHAR) (day / 10 + _T('0'));
/* store units of day */
buffer[4] = (_TSCHAR) (day % 10 + _T('0'));
/* store tens of year */
buffer[6] = (_TSCHAR) (year / 10 + _T('0'));
/* store units of year */
buffer[7] = (_TSCHAR) (year % 10 + _T('0'));
return buffer;
}
#endif /* _POSIX_ */
|
C
|
#ifndef SHORTEST_PATH_H
#define SHORTEST_PATH_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <assert.h>
#define INF INT_MAX
typedef struct adj_list_node{
unsigned int vertex;
unsigned int weights;
struct adj_list_node * next_vertex;
}LIST_NODE;
typedef struct adj_list_vnode{
unsigned int vertex;
LIST_NODE * connections;
struct adj_list_vnode * next_vertex;
}NODE;
typedef struct graph{
NODE * graph;
int number_of_vertices;
}GRAPH;
typedef struct heap_node{
unsigned int vertex;
unsigned int d;
unsigned int p;
}HEAP_NODE;
typedef struct heap{
HEAP_NODE ** Array;
int number_of_elements;
int size;
}HEAP;
#ifdef __cplusplus
extern "C"{
#endif
GRAPH * create_graph();
GRAPH * read(GRAPH * G,char * filename);
NODE * create_node(int vertex);
LIST_NODE * create_connection(int vertex, int weight);
GRAPH * add_connection(GRAPH * G,int vertex,int * connection);
GRAPH * add_vertex(GRAPH * G,int vertex);
HEAP * create_heap();
HEAP_NODE * create_heap_node(int vertex,int distance,int predecessor);
HEAP * heap_insert(GRAPH * G,int source_vertex);
HEAP_NODE * heap_delete(HEAP * heap);
void heapify(HEAP * heap, int idx);
void swap_nodes(HEAP_NODE ** A, HEAP_NODE ** B);
int isEmpty(HEAP * heap);
int getHeapIdx(HEAP * heap, int vertex);
HEAP_NODE * extract_min(HEAP * heap);
HEAP * decrease_key(HEAP * heap,int pre_vertex, int vertex,int distance);
HEAP * relax(HEAP * heap, HEAP_NODE * extracted_vertex, LIST_NODE * next_vertex, int dist);
void dijkstra(GRAPH * G, int destination_vertex);
void printGraph(GRAPH * G);
void printHeap(HEAP * heap);
void print_shortest_path(HEAP_NODE ** stack,int index);
void destroy_graph(GRAPH * G);
void destroy_heap(HEAP * heap);
#ifdef __cplusplus
}
#endif
#endif //SHORTEST_PATH_H
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* do.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mvillaes <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/29 21:56:38 by mvillaes #+# #+# */
/* Updated: 2021/06/15 21:08:54 by mvillaes ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
void do_a(int **stack, t_data *data)
{
int i;
i = 1;
while (i < data->total_elements)
{
find_small(stack, data);
hold_first(stack, data);
choose_hold(stack, data);
pb(stack, data);
i++;
}
}
void do_b(int **stack, t_data *data)
{
int i;
i = 1;
while (i < data->total_elements)
{
move_2_top_b(stack, data);
find_small_b(stack, data);
i++;
}
}
void ft_3(int **stack, t_data *data)
{
if (data->elements_a > 2)
{
if (stack[2][1] > stack[3][1])
{
rra(stack, data);
sa(stack, data);
}
if (stack[1][1] > stack[3][1])
ra(stack, data);
}
if (stack[1][1] > stack[2][1])
sa(stack, data);
}
void ft_5(int **stack, t_data *data)
{
find_small(stack, data);
move_top_a(stack, data);
pb(stack, data);
find_small(stack, data);
move_top_a(stack, data);
pb(stack, data);
ft_3(stack, data);
pa(stack, data);
ra(stack, data);
pa(stack, data);
ra(stack, data);
}
|
C
|
/* Terminierung eines Pthreads durch pthread_cancel().*/
#include <pthread.h>
#include <stdio.h>
/* Funktion, die der Thread ausführen soll */
void *endlosschleife() {
while (1) printf("Hier ist ein Thread\n");
}
/* Hauptprogramm */
int main(int argc, char *argv[]) {
pthread_t th;
/* Erzeugung eines Threads */
pthread_create(&th, NULL, endlosschleife, NULL);
/* Beenden des Threads nach einer Sekunde */
sleep(1);
pthread_cancel(th);
printf("Thread ist beendet\n");
}
|
C
|
/*
* @file process.h
* Assignment 3: PCB's and Process Scheduling Simulation
* PCB ADT
*/
#ifndef _PROCESS_H_
#define _PROCESS_H_
#include "list.h"
// Maximum length of the message between sender and receiver,
// according to the instructions, 40 char max
#define MESSAGE_MAX_LENGTH 42
#define CMD_MAX_LENGTH 10
// Three states of the process, running, ready or blocked
enum ProcessState {
RUNNING,
READY,
BLOCKED
};
// PCB data structure
typedef struct PCB_s PCB;
struct PCB_s {
int pid;
int priority;
enum ProcessState state;
char proc_message[MESSAGE_MAX_LENGTH];
};
// Semaphore data structure
typedef struct Semaphore_s Semaphore;
struct Semaphore_s {
int val; // the value of the semaphore
List* blocked_process; // a list of processes waiting on the semaphore
};
// Queues
List* high_priority_queue; // ready queue with priority 0
List* mid_priority_queue; // ready queue with priority 1
List* low_priority_queue; // ready queue with priority 2
List* send_blocked_queue; // a queue of processes waiting on a send operation
List* receive_blocked_queue; // a queue of processes waiting on a receive operation
Semaphore* semaphores[5]; // an array of 5 semaphore pointers
PCB* init_process; // the init process, we assume the init process always has PID=0
PCB* running_process; // the currently running process
int pid; // global pid counter, assigned to newly created processes
// Functions related to process scheduling simulation
// Initialize global queues
void init();
// Function to find the next process in the ready queue to execute, and return a pointer to its PCB.
// If none is found, return the pointer to init process.
PCB* reSchedule();
// Function to create a process and put it on the appropriate ready queue,
// identified by the priority argument. Return the pid of the created process
// on success or -1 for failure.
int procCreate(int priority);
// Function to copy the currently running process and put it on the ready queue,
// the newly created process has the same priority as the original one. Attemping
// to copy the init process will result in failure. Return the pid of the resulting
// process or -1 for failure.
int procFork();
// Function to kill the named process and remove it from the system, identified by
// the parameter pid. Allowing to kill a process in any state.
// Return the pid of the killed process on success or -1 for failure.
int procKill(int pid);
// Function to kill the currently running process. Rescheduling required.
// Return the pid of the currently running process on success or -1 for failure.
int procExit();
// Function to signal that the time quantum for the currently running process
// has expired. Using round robin scheduling.
// Return the pid of the next scheduled process. We assume that using this function
// to signal the init process will do nothing.
int procQuantum();
// Function to send a message from the currently running process to another process
// the sender is blocked on a blocked queue until being replied.
// Return pid of the recipient on success (the recipient can be found) or -1 if the
// recipient doesn't exist.
int procSend(int pid, char* message);
// Function to receive a message. It checks if there is a message waiting for the
// currently executing process, it there is it receives it, otherwise it gets blocked
// on the receive blocked queue. (can be unblocked by the procSend routine and be ready)
// Return the next executing process's PID on success or -1 on failure.
int procReceive();
// Function to delivers reply to sender (blocked in the send blocked queue) and unblock
// the sender. Return the pid of the sender being replied.
int procReply(int pid, char* message);
// Function to initialize the named semaphore with the value given. ID's can take a value
// from 0 to 4. Initilization for each can only be done once. The initial value must be 0 or higher.
// Return the semaphore ID on success or -1 on failure.
int newSemaphore(int semID, int val);
// Function to execute the semaphore P operation on behalf of the runing process.
// Return 0 for success or -1 for failure. Decrement.
int semaphoreP(int semID);
// Function to execute the semaphore V operation on behalf of the running process.
// Return 0 for success or -1 for failure. Increment.
int semaphoreV(int semID);
// Function to dump complete state information of the process identified by the
// pid. Return its pid if found, else return -1.
int procInfo(int pid);
// Display all process queues and their contents.
void totalInfo();
// Function to free all allocated memory, invoked when the simulation terminates.
void freeAll();
#endif
|
C
|
#include <wiringPi.h>
int main(void){
if (wiringPiSetup()== -1)
return 1;
int i=0;
int pins[] = {0,1,4,5,6,7,8,9,12,13};
int num = 10;
for (i=0; i < num; i++) {
digitalWrite(pins[i], LOW);
}
return 0;
}
|
C
|
#include <stdio.h>
struct test { int a; int b; struct test *ptr; };
static void f1(const struct test *const ptr)
{
}
static struct test f2(void)
{
return (struct test) { 1, 2, NULL };
}
int main(int argc, char *argv[])
{
f1(&((struct test) { 1, 2, NULL }));
f1(&(struct test)f2());
f1(&f2());
return 0;
}
|
C
|
/**
* @file matrice.h
* @brief En-ttes de la librairie matrice
*/
#ifndef MATRICE_H_
#define MATRICE_H_
typedef struct Matrice* Matrice;
/**
* Alloue une matrice.
*
* @param nLignes Nombre de lignes de la matrice.
* @param nColonnes Nombre de colonnes de la matrice.
* @param caractereParDefaut Caractre avec lequel remplir toute la matrice.
* @return Matrice alloue. NULL si la matrice n'a pas pu tre alloue.
*/
Matrice Matrice_creer(int nLignes, int nColonnes, char caractereParDefaut);
/**
* Copie une matrice.
*
* @param matrice Matrice copier.
* @return Matrice copie.
*/
Matrice Matrice_copier(Matrice matrice);
/**
* Dtruit une matrice.
*
* @param matrice Matrice dtruire.
*/
void Matrice_detruire(Matrice matrice);
/**
* Affiche une matrice.
*
* @param matrice Matrice afficher.
*/
void Matrice_afficher(Matrice matrice);
/**
* Rcupre la taille d'une matrice.
* Si un des pointeurs rcuprant la taille est NULL,
* celui-ci n'est pas trait.
*
* @param matrice Matrice dont il faut rcuprer la taille.
* @param nLignes Nombre de lignes.
* @param nColonnes Nombre de colonnes.
*/
void Matrice_getTaille(Matrice matrice, int* nLignes, int* nColonnes);
/**
* Rcupre la valeur d'un coefficient de la matrice.
*
* @param matrice Matrice traiter.
* @param i Ligne du coefficient.
* @param j Colonne du coefficient.
* @return Le coefficient.
*/
char Matrice_get(Matrice matrice, int i, int j);
/**
* Assigne une valeur un coefficient de la matrice.
*
* @param matrice Matrice traiter.
* @param i Ligne du coefficient.
* @param j Colonne du coefficient.
* @param valeur Valeur assigner.
*/
void Matrice_set(Matrice matrice, int i, int j, char valeur);
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* draw.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yalona <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/01/17 12:01:47 by yalona #+# #+# */
/* Updated: 2020/03/10 15:10:26 by yalona ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/fdf.h"
t_point pr_point(t_point p, t_fdf *fdf)
{
rotate_x(&p.y, &p.z, fdf->camera->x_angle, fdf);
rotate_y(&p.x, &p.z, fdf->camera->y_angle, fdf);
rotate_z(&p.x, &p.y, fdf->camera->z_angle);
p = iso(p, fdf, fdf->projection);
return (p);
}
void ft_draw_canvas(t_fdf *fdf)
{
int k;
int *temp;
fdf->canvas_ptr = mlx_new_image(fdf->ptr, 0.75 * (fdf->pix_x), fdf->pix_y);
fdf->addr_canvas = mlx_get_data_addr(fdf->canvas_ptr, &fdf->bits_can,
&fdf->line_size_can, &fdf->endian_can);
k = 0;
temp = (int *)(fdf->addr_canvas);
while (k < 0.75 * (fdf->pix_x) * fdf->pix_y)
{
temp[k] = ft_rgb(0x00, 0x00, 0x00);
k++;
}
}
void put_pixel(t_fdf *fdf, int x, int y, int color)
{
int i;
if (x >= 0 && x < (fdf->pix_x * 0.75) && y >= 0 && y < fdf->pix_y)
{
i = (x * fdf->bits_can / 8) + (y * fdf->line_size_can);
fdf->addr_canvas[i] = color;
fdf->addr_canvas[++i] = color >> 8;
fdf->addr_canvas[++i] = color >> 16;
}
}
void ft_draw_map_arr_2(t_fdf *fdf, int i, t_point a)
{
int j;
j = 0;
while (j < fdf->x - 1)
{
draw_line_n(pr_point(a, fdf),
pr_point(fdf->arr_point[i * fdf->x + j + 1], fdf), fdf);
a = fdf->arr_point[i * fdf->x + j + 1];
j++;
}
mlx_put_image_to_window(fdf->ptr, fdf->window, fdf->canvas_ptr, 0, 0);
ft_draw_menu(fdf);
}
void ft_draw_map_arr(t_fdf *fdf)
{
int i;
int j;
t_point a;
a = fdf->arr_point[0];
i = -1;
mlx_clear_window(fdf->ptr, fdf->window);
ft_draw_canvas(fdf);
while (++i < fdf->y - 1)
{
j = 0;
while (j < fdf->x - 1)
{
draw_line_n(pr_point(a, fdf),
pr_point(fdf->arr_point[i * fdf->x + j + 1], fdf), fdf);
draw_line_n(pr_point(a, fdf),
pr_point(fdf->arr_point[(i + 1) * fdf->x + j], fdf), fdf);
a = fdf->arr_point[i * fdf->x + j + 1];
j++;
}
draw_line_n(pr_point(a, fdf),
pr_point(fdf->arr_point[(i + 1) * fdf->x + j], fdf), fdf);
a = fdf->arr_point[(i + 1) * fdf->x];
}
ft_draw_map_arr_2(fdf, i, a);
}
|
C
|
#include <stdio.h>
#include "../ex07/ft_find_next_prime.c"
int ft_find_next_prime(int nb);
int main()
{
printf("The next prime greater or equal to 5 is: %d\n", ft_find_next_prime(5));
printf("The next prime greater or equal to 10 is: %d\n", ft_find_next_prime(10));
printf("The next prime greater or equal to 100 is: %d\n", ft_find_next_prime(100));
printf("The next prime greater or equal to 1000 is: %d\n", ft_find_next_prime(1000));
printf("The next prime greater or equal to 50000 is: %d\n", ft_find_next_prime(50000));
printf("The next prime greater or equal to 2147483647 is: %d\n", ft_find_next_prime(2147483647));
}
|
C
|
#include<stdio.h>
void main()
{
char a[30],b;
int i,j;
printf("ENTER STRING : ");
gets(a);
// printf("ENTER CHAR YOU WANNA DELETE : ");
// scanf("%c",&b);
for(i=0;a[i]!=NULL;i++)
{
// if(a[i]==b)
if(a[i]==' ')
{
for(j=i;a[j]!=NULL;j++)
{
a[j]=a[j+1];
}
i--;
}
}
printf("\n\n %s",a);
}
|
C
|
// sudoku_check.c
// Created by Lauren Kira Murray on 17/02/2014.
#include <stdio.h>
#include "sudoku_header.h"
/* method which takes in an array and returns its state (invalid, incomplete or complete) */
enum tag check_array(int array[]) {
//flag to keep track of incomplete arrays
int flag = 0;
for (int i = 0; i < 9; i++) {
for (int j = i + 1; j < 9; j++) {
if(array[j] == '.' || array[i] == '.'){
flag = 1;
}else if (array[i] == array[j]) {
return INVALID;
}
}
}
if (flag == 1){
return INCOMPLETE;
}
else{
return COMPLETE;
}
}
/* method which checks if a sudoku is invalid, incomplete or complete by calling the check_array method on different rows, columns and boxes */
enum tag check_sudoku(struct sudoku* sudoku_struct) {
// 0 = complete, 1 = incomplete
int check = 0;
//check row
for(int i = 0; i < 9; i++){
enum tag result = check_array(sudoku_struct->row_struct_array[i].items);
if (result == INVALID){
return result;
}
else if (result == INCOMPLETE){
check = 1;
}
}
//check columns
//9 times (for each column)
for(int i = 0; i < 9; i++){
int array[9];
//9 times (for each row)
for(int j = 0; j < 9; j++){
array[j] = sudoku_struct->row_struct_array[j].items[i];
}
enum tag result = check_array(array);
if (result == INVALID){
return result;
}
else if (result == INCOMPLETE){
check = 1;
}
}
//check boxes
//9 times (for each box)
for(int i = 0; i < 9; i++){
int array[9];
int outer_row = (i/3)*3;
int outer_col = (i%3)*3;
//9 times (for each cell in the box)
for(int j = 0; j < 9; j++){
int inner_row = j/3;
int inner_col = j%3;
int row = outer_row + inner_row;
int col = outer_col + inner_col;
array[j] = sudoku_struct->row_struct_array[row].items[col];
}
enum tag result = check_array(array);
if (result == INVALID){
return result;
}
else if (result == INCOMPLETE){
check = 1;
}
}
if(check == 0){
return COMPLETE;
}
else{
return INCOMPLETE;
}
}
|
C
|
#define _BSD_SOURCE 1
#define _SVID_SOURCE 1
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <linux/limits.h>
#include <dirent.h>
#include <stdlib.h>
#include <sys/wait.h>
#include "commands.h"
#include "utils.h"
int do_launch(int argc, char** argv){
int pid;
int status;
char* PATH[5]; //EnvPATH
struct dirent **dirs;
struct stat fstat;
int dirnum;
for(int i=0; i<5;i++){
PATH[i] = malloc(256);
}
if(strncmp(argv[0], "/", 1))
{
strcpy(PATH[0], "/usr/local/bin/");
strcpy(PATH[1], "/usr/bin/");
strcpy(PATH[2], "/bin/");
strcpy(PATH[3], "/usr/sbin/");
strcpy(PATH[4], "/sbin/");
for(int j=0; j<5; j++){
dirnum = scandir(PATH[j], &dirs, NULL, alphasort);
for(int i=0; i<dirnum;i++){
lstat(dirs[i]->d_name, &fstat);
if(!strcmp(dirs[i]->d_name, argv[0]) && (fstat.st_mode & S_IXUSR) == S_IXUSR){
strcat(PATH[j], argv[0]);
strcpy(argv[0], PATH[j]);
pid = fork();
if(pid == 0){
execv(argv[0], argv);
perror("Process failure");
exit(EXIT_FAILURE);
}
pid = wait(&status);
free(PATH[j]);
return pid;
}
}
}
}else{
pid = fork();
if(pid == 0){
execv(argv[0], argv);
exit(EXIT_FAILURE);
}
pid = wait(&status);
for(int i = 0; i<5; i++)
free(PATH[i]);
return pid;
}
for(int i = 0; i<5; i++)
free(PATH[i]);
return -1;
}
int do_ls(int argc, char** argv) {
if (!validate_ls_argv(argc, argv))
return -1;
struct dirent **dirs;
int dirnum = scandir(".", &dirs, NULL, alphasort);
if (dirnum == 0) {
printf("Empty directory.\n");
return -1;
}
for(int i = 0; i<dirnum; i++)
{
if (!strcmp(dirs[i]->d_name, ".") ||
!strcmp(dirs[i]->d_name, "..") ||
!strcmp(dirs[i]->d_name, ".git") ||
!strcmp(dirs[i]->d_name, ".gitignore"))
continue;
struct stat fstat;
lstat(dirs[i]->d_name, &fstat);
if((fstat.st_mode & S_IFDIR) == S_IFDIR)
printf("\033[1;94m%s \033[0m", dirs[i]->d_name);
else if((fstat.st_mode & S_IXUSR) == S_IXUSR)
printf("\033[1;92m%s \033[0m", dirs[i]->d_name);
else printf("\033[0;97m%s \033[0m", dirs[i]->d_name);
}
printf("\n");
return 0;
}
int do_cd(int argc, char** argv) {
if (validate_cd_argv(argc, argv) == 0)
return -1;
if (validate_cd_argv(argc, argv) == 2)
return 0;
if (chdir(argv[1]) == -1)
return -1;
return 0;
}
int do_pwd(int argc, char** argv) {
if (!validate_pwd_argv(argc, argv))
return -1;
char curdir[PATH_MAX];
if (getcwd(curdir, PATH_MAX) == NULL)
return -1;
printf("%s\n", curdir);
return 0;
}
int validate_cd_argv(int argc, char** argv) {
if (strcmp(argv[0], "cd") != 0) return 0;
struct stat buf;
stat(argv[1], &buf);
if (!S_ISDIR(buf.st_mode)) return 0;
return 1;
}
int validate_pwd_argv(int argc, char** argv) {
if (argc != 1) return 0;
if (strcmp(argv[0], "pwd") != 0) return 0;
return 1;
}
int validate_ls_argv(int argc, char** argv) {
if (strcmp(argv[0], "ls2") != 0) return 0;
return 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N (40 * 1024 * 1024)
int main()
{
srand(time(NULL));
int n, *data = malloc(N);
scanf("%d", &n);
for (int i = 0; i < N / 4; i++)
data[i] = rand();
int idx = rand() % N;
printf("data[%d] = %d\n", idx, data[idx]);
scanf("%d", &n);
free(data);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(){
char cadeia[50]; // Variavel para armazenar a cadeia de caracteres
int qtd = 0, // Variavel para armazenar a quantidade de caracteres
i, pv = 0; // Contador
// Recebimento da cadeia
printf("Digite uma cadeia de caracteres: ");
gets(cadeia);
// Identificar a quantidade de caracteres
for(i = 0; cadeia[i] != '\0'; i++){
qtd++;
}
// Imprime a nova cadeia
printf("\nNova cadeia: ");
i = 0;
while(i <= qtd){
printf("%c", cadeia[i]);
if((cadeia[i] == ' ') || (cadeia[i] == '\0')){
pv++;
i++;
while(cadeia[i] == ' '){
i++;
}
}else{
i++;
}
}
printf("\nQtd palavras: %d", pv);
}
|
C
|
#ifndef AST_H
#define AST_H
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
int yylex();
void yyrestart(FILE*);
int yyparse();
int yyerror(char*);
typedef struct AST_Node
{
int term_type; /* 0 -> token; 1 -> non-terminated */
int token_type; /* type of tokens (enum) */
int int_type; /* 0 -> Dec; 1 -> Oct; 2 -> Hex */
char *name;
char *value;
int row_index;
struct AST_Node *parent;
struct AST_Node *first_child;
struct AST_Node *sibling;
} AST_Node;
int str_to_int(char *str, int type);
AST_Node *create_node(char *name, char *value, int token_type, int lineno);
void add_child_sibling(AST_Node *parent, const int count, ...);
void print_AST(AST_Node *node, int indent);
#endif
|
C
|
/**
4.2 write a program to read values of x,y and print as
x+y/x-y x+y/2 (x+y)(x-y)
*/
///program begin
#include<stdio.h>
#include<conio.h>
//main() function begin
int main()
{
float x,y,a,b,c;
printf("Enter x\n");
scanf("%f",&a);
printf("Enter y\n");
scanf("%f",&y);
a=((x+y)/(x-y));
b=(x+y)/2;
c=(x+y)*(x-y);
printf("%.2f %.2f %.2f",a,b,c);
getch();
return 0;
}
///main() end
///program end
/**
output
Enter x
45
Enter y
54
-1.00 27.00 -2916.00
*/
|
C
|
#ifndef _random_h_
#define _random_h_
#include "Vec.h"
#include <cstdlib>
#include <cmath>
inline void random_seed (const unsigned int& s) throw () {
srand(s); }
/** gleichverteilte Zufallszahl in [0,1] */
inline double urandom () throw () {
return static_cast<double>( rand())/RAND_MAX; }
/** gleichverteilte Zufallszahl in [f,t] */
inline double urandom (const double& f, const double& t) throw () {
return (t-f)*urandom ()+f; }
/** Bernoulli-Experiment mit Erfolgswahrscheinlichkeit p */
inline bool brandom (const double& p) throw () {
return (urandom()<p); }
/** Standard-normalverteilte Zufallszahl */
inline double nrandom () throw () {
double u1 = urandom();
double u2 = urandom();
return ( sqrt(-2.0* log(u1))*cos(6.2831853071*u2));
}
/** Normalverteilte Zufallszahl N(mu,sigma^2) */
inline double nrandom (const double& mu, const double& sigma) throw () {
return nrandom()*sigma+mu; }
/** Standard-Normalverteilter Zufallszahlvektor */
inline Vec n2random () throw () {
double u1 = urandom();
double u2 = urandom();
double s = sqrt(-2.0* log(u1));
return Vec (s*cos(6.2831853071*u2), s*sin(6.2831853071*u2));
}
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
int N;
int lsearch (int v, int arr[], int size){
for (int i = 0; i < N; i++) {
if(v == arr[i]) {printf("True\n"); return 1; }
}
printf("False\n");
return 0;
}
int main(int argc, char *argv[]){
int a[] = {34,12,56,3,18,10,2,3,1};
int n = atoi(argv[1]);
N = sizeof(a)/sizeof(int);
lsearch(n, a, N);
return 0;
}
|
C
|
#pragma once
#include <ntstatus.h>
#define WIN32_NO_STATUS
#include <windows.h>
#undef WIN32_NO_STATUS
#include "..\LinkedList\LinkedList.h"
typedef struct Node {
LONG Data;
struct Node* Right;
struct Node* Left;
union {
struct Node* Parent;
PLNode LNode;
};
} Node, *PNode;
typedef struct Tree {
PNode Root;
ULONG Count;
} Tree, *PTree;
NTSTATUS
TreeAdd(PTree Tree, LONG Data);
VOID
TreePrintPreOrder(PNode Node);
VOID
TreePrintPostOrder(PNode Node);
VOID
TreePrintInOrder(PNode Node);
ULONG
TreeGetHeight(PNode Node);
BOOLEAN
TreeCheckNodeExists(PTree Tree, PNode Node);
BOOLEAN
TreeCheckIfStrictlyBinaryTree(PNode Node);
VOID
TreePrintLeafNodes(PNode Node);
VOID
TreeSwap(PNode Node);
ULONG
TreeCheckIfCompleteBinaryTree(PNode Node);
VOID
TreePreOrderNonRecurssive(PNode Node);
BOOLEAN
TreeCheckIfBalanced(PNode Node);
NTSTATUS
TreemakeMinHeightTreeFromSortedArray(PTree *Tree, PULONG Array, ULONG Length);
BOOLEAN
TreeCheckIfBST(PTree Tree);
VOID
TreeLinkAtLevels(PTree Tree, PLNode* Heads, PULONG Count);
PNode
TreeFindCommonAncestor(PNode Root, PNode p, PNode q);
PNode
TreeFindNode(PTree Tree, LONG Data);
BOOLEAN
TreeCheckIfSubtree(PTree t1, PTree t2);
VOID
TreePrintPathWhichAddToSum(PTree Tree, LONG Sum);
VOID
TreeMorrisTraversal(PTree Tree);
BOOLEAN
TreeCheckIfSymmetric(PTree Tree);
VOID
TreePrintInorderWithParentPointer(PTree Tree);
VOID
TreePrintExterior(PTree Tree);
VOID
TreeConstructFromPreAndInorder(PULONG Inorder, ULONG InorderSize,
PULONG Preorder, ULONG PreorderSize,
PTree* Tree);
|
C
|
/************************************************************************
* 8080 Emulator Storage Peripheral v0.0.0 *
* Pramuka Perera *
* June 23, 2017 *
* Non-volatile data storage *
************************************************************************/
#ifndef INCLUDE
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "common.h"
#define INCLUDE
#endif
#include <limits.h>
#define STORAGE_ACCESS_RATE 40 //Hz (25 ms)
#define STORAGE_ACCESS_PERIOD (CLOCK_RATE / STORAGE_ACCESS_RATE) //Clock Cycles
FILE *storage = NULL;
void LoadNonVolatileMemory(uint8_t *hard_disk)
{
int i;
storage = fopen("storage", "r");
for(i = 0; i < HARD_DISK_SIZE; i++)
{
hard_disk[i] = fgetc(storage);
}
fclose(storage);
storage = NULL;
}
void StoreNonVolatileMemory(uint8_t *hard_disk)
{
int i;
storage = fopen("storage", "w");
for(i = 0; i < HARD_DISK_SIZE; i++)
{
fputc(hard_disk[i], storage);
}
fclose(storage);
storage = NULL;
}
/*
* Memory-mapped Nonvolatile Memory Registers
* 0x3ffc - Storage Control Register
* BITS: 4 3 2 1 0
* VALUE: Interrupt-Handled Flag Write-Request Flag Read-Request Flag Ready Flag Interrupt-Enable
* 0x3ffd - Data Register
* 0x3ffe/f - Address Registers
*/
void NonVolatileMemoryOperation()
{
static int storage_op_completion_time = INT_MAX;
static io_state storage_state = READY;
uint16_t address;
switch(storage_state)
{
case READY:
if(memory[NV_MEM_CTRL_REG] & READ_REQUEST)
{
//state output
storage_op_completion_time = time + STORAGE_ACCESS_PERIOD;
memory[NV_MEM_CTRL_REG] &= ~RDY;
//next state
storage_state = READING;
}
else if(memory[NV_MEM_CTRL_REG] & WRITE_REQUEST)
{
//state output
storage_op_completion_time = time + STORAGE_ACCESS_PERIOD;
memory[NV_MEM_CTRL_REG] &= ~RDY;
//next state
storage_state = WRITING;
}
//otherwise state = READY
break;
case READING:
if(time >= storage_op_completion_time)
{
//state output
address = (memory[NV_MEM_ADDR_HIGH] << 8) + memory[NV_MEM_ADDR_LOW];
memory[address] = memory[NV_MEM_DATA_REG];
storage_op_completion_time = INT_MAX;
memory[NV_MEM_CTRL_REG] |= DONE;
//next state
storage_state = OP_COMPLETE;
if(memory[NV_MEM_CTRL_REG] & INTERRUPT_ENABLE)
{
interrupt_request = 1;
interrupt_vector = STORAGE_READ;
storage_state = INTERRUPT;
}
}
break;
case WRITING:
if(time >= storage_op_completion_time)
{
//state output
address = (memory[NV_MEM_ADDR_HIGH] << 8) + memory[NV_MEM_ADDR_LOW];
hard_disk[address] = memory[NV_MEM_DATA_REG];
memory[NV_MEM_CTRL_REG] |= DONE;
storage_op_completion_time = INT_MAX;
//next state
storage_state = OP_COMPLETE;
if(memory[NV_MEM_CTRL_REG] & INTERRUPT_ENABLE)
{
interrupt_request = 1;
interrupt_vector = STORAGE_WRITE;
storage_state = INTERRUPT;
}
}
break;
case INTERRUPT:
if(memory[NV_MEM_CTRL_REG] & DONE)
{
//state output
interrupt_request = 1;
interrupt_vector = (memory[NV_MEM_CTRL_REG] & READ_REQUEST) ? STORAGE_READ : STORAGE_WRITE;
//state = INTERRUPT
}
else
{
//state output
memory[NV_MEM_CTRL_REG] |= RDY;
memory[NV_MEM_CTRL_REG] &= ~(WRITE_REQUEST | READ_REQUEST);
//next state
storage_state = READY;
}
break;
case OP_COMPLETE:
if((memory[NV_MEM_CTRL_REG] & DONE) == 0)
{
//state output
memory[NV_MEM_CTRL_REG] |= RDY;
memory[NV_MEM_CTRL_REG] &= ~(WRITE_REQUEST | READ_REQUEST);
//next state
storage_state = READY;
}
break;
default:
break;
};
}
/*
void NonVolatileMemoryOperation()
{
static int storage_op_completion_time = INT_MAX;
uint16_t address;
//if ready, start timer to emulate access-operation, and clear READY to indicate operation is ongoing
if(memory[NV_MEM_CTRL_REG] & READY)
{
if(memory[NV_MEM_CTRL_REG] & WRITE_REQUEST || memory[NV_MEM_CTRL_REG] & READ_REQUEST)
{
storage_op_completion_time = time + STORAGE_ACCESS_PERIOD; //current time + time needed for access operation
memory[NV_MEM_CTRL_REG] &= ~(READY | INTERRUPT_HANDLED);
}
}
//if emulated time of operation has passed, do the requested operation
else if((memory[NV_MEM_CTRL_REG] & READY) == 0 && time >= storage_op_completion_time)
{
//send an interrupt signal if interrupts are enabled
if(memory[NV_MEM_CTRL_REG] & ~INTERRUPT_ENABLE)
{
interrupt_request = 1;
}
//indicate operation is complete and device can carry out another operation
memory[NV_MEM_CTRL_REG] |= READY;
//actual read operation
if(memory[NV_MEM_CTRL_REG] & READ_REQUEST)
{
address = (memory[NV_MEM_ADDR_HIGH] << 8) + memory[NV_MEM_ADDR_LOW];
memory[address] = memory[NV_MEM_DATA_REG];
memory[NV_MEM_CTRL_REG] &= ~READ_REQUEST;
storage_op_completion_time = INT_MAX;
return;
}
//actual write operation
if(memory[NV_MEM_CTRL_REG] & WRITE_REQUEST)
{
address = (memory[NV_MEM_ADDR_HIGH] << 8) + memory[NV_MEM_ADDR_LOW];
hard_disk[address] = memory[NV_MEM_DATA_REG];
memory[NV_MEM_CTRL_REG] &= ~WRITE_REQUEST;
storage_op_completion_time = INT_MAX;
return;
}
}
}
*/
|
C
|
// 300号题目最长上升子序列的扩展版本
// 首先按照envelopes的长度从短到长排序
// dp[i]表示以envelopes[i]作为最外层的套娃最大深度
// 算法复杂度O(n^2)
class Solution {
public:
int maxEnvelopes(vector<vector<int>>& envelopes) {
int n = envelopes.size();
if (n < 1) return 0;
int max_ret = 1;
vector<int> dp(n, 1);
sort(envelopes.begin(), envelopes.end(), cmp);
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (envelopes[i][0] > envelopes[j][0] &&
envelopes[i][1] > envelopes[j][1]) {
dp[i] = max(dp[i], dp[j] + 1);
}
}
max_ret = max(max_ret, dp[i]);
}
return max_ret;
}
static int cmp(vector<int>& e1, vector<int>& e2) {
return e1[0] < e2[0];
}
};
|
C
|
#include <stdio.h>
#include <string.h>
int i, pilih, pmbyr, kmbl, jmlh, no, tmbh, akhir, kmbl1;
int total[30];
int ttlhrg=0, ukuran=0;
int hrg[4]={12000,10000,6000,9000};
char p[5];
int main ()
{
awal: //label awal
printf("====================================\n");
printf("| |\n");
printf("| Selamat Datang di Kafe 86 ! |\n");
printf("| |\n");
printf("====================================\n\n");
printf("1. Menu Kafe\n");
printf("2. Pesan Menu\n");
printf("3. Keluar dari Kafe\n");
printf("\nMasukkan Pilihan Anda: ");
scanf("%i", &pilih);
//output untuk tiap pilihan user
switch(pilih)
{
//pilihan 1. Menu Kafe
case 1:
printf("========================================\n");
printf("| |\n");
printf("| Menu Kafe 86 |\n");
printf("| |\n");
printf("========================================\n");
printf("|Menu : Harga: |\n");
printf("|1. Espresso 12K |\n");
printf("|2. Coklat Hangat 10K |\n");
printf("|3. Kentang Goreng 6K |\n");
printf("|4. Pancake 9k |\n");
printf("========================================\n");
printf("\n");
goto awal;
//pilihan 2. Pesan Menu
case 2:
menu: //label menu
printf("\nMasukkan nomor menu: ");
scanf("%i", &no);
//mencetak perintah sesuai input nomor menu
if(no<1||no>4){
printf("Harap Masukkan Nomor Menu yang Sesuai!\n");
goto menu;
}
else{
printf("Masukkan Jumlah Menu: ");
scanf("%i", &jmlh);
total[i]=hrg[no-1]*jmlh;
i++;
ukuran=ukuran+1;
goto lain;
}
bayar: //label bayar
for(i=0;i<ukuran;i++){
ttlhrg=ttlhrg+total[i];
}
printf("\nTotal Harga:Rp. %i", ttlhrg);
printf("\nMasukkan Jumlah Uang Anda:Rp. ");
scanf("%i", &pmbyr);
//menghitung uang kembali
kmbl=pmbyr-ttlhrg;
if(kmbl>=0){
printf("\nKembalian Anda:Rp. %i\n", kmbl);
printf("Terima Kasih Telah Membeli!");
break;
}
else{
kmbl1=kmbl*-1;
printf("\nUang Anda Kurang:Rp. %i", kmbl1);
goto tambah;
}
tambah: //label tambah
//untuk menambah uang pembayaran yang kurang
printf("\nMasukkan Uang Tambahan:Rp. ");
scanf("%i", &tmbh);
akhir=tmbh-kmbl1;
if(akhir>=0){
printf("Kembalian Anda:Rp. %i\n", akhir);
printf("Terima Kasih Telah Membeli!");
break;
}
else{
printf("Uang Tambahan Tidak Mencukupi!\n");
goto tambah;
}
lain: //label lain (Jika user ingin memesan menu lain)
printf("\nApakah Anda Ingin Memesan Menu Lain? (y/t): ");
scanf("%s", p);
if(strcmp(p,"y")==0||strcmp(p,"Y")==0){
goto menu;
}
else if(strcmp(p,"t")==0||strcmp(p,"T")==0){
goto bayar;
}
else{
printf("Masukkan pilihan yang benar...\n");
goto lain;
}
//pilihan 3. Keluar
case 3:
printf("Terima Kasih Telah Membeli!");
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "trie.h"
static ASCIITrie *ASCIITrie_Buscar_Recursiva(ASCIITrie *T, unsigned char *chave, int tam, int p){
if(T == NULL) return NULL;
if(p == tam) return T;
return ASCIITrie_Buscar_Recursiva(T->filhos[chave[p]-97], chave, tam, p+1);
}
static void AT_Inserir_Recursivo(ASCIITrie **T, unsigned char *chave, int valor, int tam, int p){
if((*T) == NULL) *T = AT_Criar();
if(p == tam){
(*T)->valor = valor;
(*T)->estado = TRIE_OCUPADO;
return;
}
AT_Inserir_Recursivo(&(*T)->filhos[chave[p]-97], chave, valor, tam, p+1);
}
static void AT_Remover_Recursivo(ASCIITrie **T, unsigned char *chave, int tam, int p){
if(*T == NULL) return;
if(p == tam)
(*T)->estado = TRIE_LIVRE;
else
AT_Remover_Recursivo(&(*T)->filhos[chave[p]-97], chave, tam, p+1);
if((*T)->estado == TRIE_LIVRE){
for(int i = 0; i < 26; i++)
if((*T)->filhos[i] != NULL) return;
free(*T);
*T = NULL;
}
}
static void AT_Destruir_R(ASCIITrie *T){
if(T == NULL) return;
for(int i = 0; i < 26; i++){
if(T->filhos[i] != NULL){
AT_Destruir_R(T->filhos[i]);
T->filhos[i] = NULL;
}
}
free(T);
}
ASCIITrie *AT_Buscar(ASCIITrie *T, unsigned char *chave){
return ASCIITrie_Buscar_Recursiva(T, chave, strlen(chave), 0);
}
ASCIITrie *AT_Criar(){
ASCIITrie *no = malloc(sizeof(ASCIITrie));
no->valor = 0;
no->estado = TRIE_LIVRE;
no->tamanho = 0;
for(int i = 0; i < 26; i++) no->filhos[i] = NULL;
return no;
}
void AT_Inserir(ASCIITrie **T, unsigned char *chave, int valor){
AT_Inserir_Recursivo(T, chave, valor, strlen(chave), 0);
(*T)->tamanho += 1;
}
void AT_Remover(ASCIITrie **T, unsigned char *chave){
AT_Remover_Recursivo(T, chave, strlen(chave), 0);
}
void AT_Destruir(ASCIITrie *T){
AT_Destruir_R(T);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
void error(char *msg);
int main() {
char buf[40];
int inlet[2], outlet[2];
pipe(inlet);
pipe(outlet);
pid_t pid = fork();
if(pid == -1) {
error("cannot create child process");
}
if(pid == 0) {
dup2(inlet[0], 0);
close(inlet[1]);
close(inlet[0]);
dup2(outlet[1], 1);
close(outlet[0]);
close(outlet[1]);
if(execl("/usr/games/nethack", "/usr/games/nethack", NULL)) {
error("cannot open file on child process");
}
}
close(outlet[1]);
close(inlet[0]);
while(1) {
fgets(buf, sizeof(buf), stdin);
write(inlet[1], buf, strlen(buf));
while(read(outlet[0], buf, sizeof(buf)) != 0) {
fprintf(stdout, "%s", buf);
}
}
}
void error(char *msg) {
fprintf(stderr, "%s: %s", msg, strerror(errno));
}
|
C
|
#include "int_to_bstr.h"
#include <stdio.h>
char *int_to_bstr(int number, char *b_str, int size)
{
int mask = 1;
b_str[size] = '\0';
for(size--; size >= 0; size--, number >>= 1)
b_str[size] = (mask & number) + '0';
return b_str;
}
|
C
|
/*C progam to check eligibility of candidates to marry
Author: abhijeet
Created on 10 Sept, 2019, 06:06 AM
*/
#include <stdio.h>
int main()
{
int age;
char stat,sex;
printf("Enter marital status, Gender and Age in (M,F,18) format :");
scanf("%c,%c,%d",&stat,&sex,&age);
if(stat=='m')
{
printf("You Cannot Marry");
}
else if(stat=='u')
{
if(sex=='m')
{
if(age>=21)
{
printf("You can Marry");
}
else
{
printf("You Cannot Marry");
}
}
else if(sex=='f')
{
if(age>=18)
{
printf("You can Marry");
}
else
{
printf("You Cannot Marry");
}
}
else
printf("Invalid Gender");
}
else
{
printf("Invalid Marital status");
}
return 0;
}
|
C
|
#include<stdio.h>
int main(){
char nome[];
scanf("%s", nome);
printf ("\n%s\n", nome);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_cd.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jrosemar <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/13 14:18:09 by jrosemar #+# #+# */
/* Updated: 2021/01/27 17:45:18 by jrosemar ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
char *cut_pwd(char *line)
{
char *str;
int i;
int count;
i = 0;
count = ft_strlen(line);
while (line[count] != '/')
count--;
if (count == 0)
{
str = (char *)malloc(sizeof(char) * 2);
str = ft_strdup("/\0");
}
else
{
str = (char *)malloc(sizeof(char) * (count + 1));
while (i < count)
{
str[i] = line[i];
i++;
}
str[i] = '\0';
}
free(line);
return (str);
}
char *add_str(char **env, char *s1, char *s2)
{
char *temp;
char *str;
int len;
int i;
i = 0;
temp = change_pwd(env, s1, ft_strlen(s1));
len = ft_strlen(temp) + ft_strlen(s2) + 1;
str = (char *)malloc(sizeof(char) * len + 1);
len = ft_strlen(temp);
ft_memcpy(str, temp, len);
str[len] = '/';
len++;
while (s2[i] != '\0')
{
str[len + i] = s2[i];
i++;
}
str[len + i] = '\0';
free(temp);
return (str);
}
char *check_cd(char **arr, t_ptr *ptr)
{
char *str;
if (arr[1][0] == '/')
str = ft_strdup(arr[1]);
else
str = add_str(ptr->env, "PWD=", arr[1]);
if ((chdir(str)) == -1)
ft_putstr("No such file or directory\n");
return (str);
}
char *changes_env(t_ptr *ptr)
{
char *str;
str = change_pwd(ptr->env, "PWD=", 4);
str = cut_pwd(str);
chdir(str);
return (str);
}
void ft_cd(char **arr, t_ptr *ptr)
{
char *str;
char *present;
t_var var;
var = init_variable();
var.i = find_size_arr(arr);
present = NULL;
if (var.i > 2)
{
ft_putstr("Too many arguments\n");
return ;
}
if (arr[1] == NULL)
str = home_var(ptr, &var);
else if (ft_memcmp(arr[1], "-\0", 2) == 0)
str = oldpwd_var(ptr, &var);
else if (ft_strcmp(arr[1], "..") == 0)
str = changes_env(ptr);
else
str = check_cd(arr, ptr);
if (var.flag == 0)
ft_cd1(present, ptr, str);
}
|
C
|
#include <stdio.h>
#include "node.h"
int main()
{
char data[] = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7 };
int i;
fprintf(stdout, "Array: ");
for(i = 0; i < 14; i++)
fprintf(stdout, "%hhd ", *(data+i));
fprintf(stdout, "\n");
// Create a linked list of nodes, using the node library
// functions where applicable (mknode() specifically), and
// have each node contain one of the above array elements,
// to have a linked list equivalent of the array.
// Display the list from beginning to end- the above order
// of values should be seen.
Node *first = NULL;
Node *tmp = NULL;
first = mknode(data[0]);
tmp = first;
// create nodes 1-13
for (i = 1; i < 14; i++)
{
tmp -> right = mknode(data[i]);
tmp = tmp -> right;
}
// print nodes.info for nodes 0-13
fprintf(stdout, "List: ");
tmp = first;
for (i = 0; i < 14; i++)
{
fprintf(stdout, "%hhd ", tmp -> info);
tmp = tmp -> right;
}
fprintf(stdout, "\n");
return(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void foo(int x) {
int a[10];
unsigned int z = (unsigned int)x;
sparrow_print(z);
if (z > 0) {
a[z] = 1; /* x is too big by the C casting rule */
/* A helpful footprint should be included in z's abstract value,
hopefully, here! */
}
}
void call_foo() {
foo(-1);
}
int main()
{
call_foo();
return 0;
}
void goo() {
int x;
int* a = (int*)malloc(x); /* x is too small by integer overflow */
}
|
C
|
#include<stdio.h>
#include<sys/time.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/stat.h>
#include<fcntl.h>
int main()
{
fd_set read_fileset,testfd;
int fd2,fd3, retfd;
int buf;
int val,ret;
char buff[4099];
fd2=open("/dev/input/event1",O_RDONLY);
if(fd2<0)
printf("error while open the file event1\n");
fd3=open("/dev/input/event2",O_RDONLY);
if(fd3<0)
printf("error while open the file event2\n");
//while(1) {
/* initially makes as zero files */
FD_ZERO(&read_fileset);
/* add our file discriptors */
FD_SET(fd2,&read_fileset);
FD_SET(fd3,&read_fileset);
while(1){
testfd=read_fileset;
retfd=select(FD_SETSIZE,&testfd,NULL,NULL,0);
printf ("retfd:%d\n",retfd);
if(retfd<0){
printf("select is failed\n");
return -1;
}
/* Touch screen data event0 */
if(FD_ISSET(fd2,&testfd))
{
printf("data is available on power0 button event1\n");
ret = read(fd2,&buff,4010);
printf ("ret:%d\n",ret);
}
if(FD_ISSET(fd3,&testfd))
{
printf("data is available on keypad event2\n");
ret = read(fd3,&buff,4096);
printf ("ret:%d\n",ret);
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <assert.h>
#include "../src/threadpool.h"
// ThreadPool_work function prototypes
ThreadPool_work_t *ThreadPool_work_create(thread_func_t func, void *arg);
void ThreadPool_work_destroy(ThreadPool_work_t *work);
// ThreadPool_work_queue function prototypes
ThreadPool_work_queue_t *ThreadPool_work_queue_create();
void ThreadPool_work_queue_destroy(ThreadPool_work_queue_t *work_queue);
void ThreadPool_work_queue_push(ThreadPool_work_queue_t *work_queue, ThreadPool_work_t *work);
ThreadPool_work_t *ThreadPool_work_queue_pop(ThreadPool_work_queue_t *work_queue);
bool ThreadPool_work_queue_empty(ThreadPool_work_queue_t *work_queue);
// testing data
const char *message[5] = {
"ThreadPool_work 1",
"ThreadPool_work 2",
"ThreadPool_work 3",
"ThreadPool_work 4",
"ThreadPool_work 5",
};
void test_normal_use() {
ThreadPool_work_queue_t *work_queue = ThreadPool_work_queue_create();
assert(ThreadPool_work_queue_empty(work_queue) == 1);
for (int i = 0; i < 5; i++) {
ThreadPool_work_t *work = ThreadPool_work_create(NULL, (void *) message[i]);
ThreadPool_work_queue_push(work_queue, work);
}
// assert queue not empty
assert(ThreadPool_work_queue_empty(work_queue) == 0);
for (int i = 0; i < 5; i++) {
ThreadPool_work_t *work = ThreadPool_work_queue_pop(work_queue);
// assert first-in first-out
assert(work->arg == message[i]);
ThreadPool_work_destroy(work);
}
// assert empty
assert(ThreadPool_work_queue_empty(work_queue) == 1);
ThreadPool_work_queue_destroy(work_queue);
}
void test_delete_full() {
ThreadPool_work_queue_t *work_queue = ThreadPool_work_queue_create();
for (int i = 0; i < 5; i++) {
ThreadPool_work_t *work = ThreadPool_work_create(NULL, (void *) message[i]);
ThreadPool_work_queue_push(work_queue, work);
}
// assert queue not empty
assert(ThreadPool_work_queue_empty(work_queue) == 0);
ThreadPool_work_queue_destroy(work_queue);
}
int main(int argc, char *argv[]) {
fputs("Testing ThreadPool_work_queue: ", stdout);
test_normal_use();
test_delete_full();
fputs("Passed \n", stdout);
return 0;
}
|
C
|
/*
树的广度优先遍历,将每一层的节点保存在vector中
*/
//寻找下一层节点
vector<TreeNode*> FindCnode(vector<TreeNode*> childnode)
{
vector<TreeNode*> result;
for (int i = 0; i < childnode.size(); i++)
{
if (childnode[i]->left != NULL)
{
result.push_back(childnode[i]->left);
}
if (childnode[i]->right != NULL)
{
result.push_back(childnode[i]->right);
}
}
return result;
}
//返回左下角值
int findBottomLeftValue(TreeNode* root) {
vector<TreeNode*> childnode;
childnode.push_back(root);
int result = 0;
while (childnode.size()!=0)
{
result = childnode[0]->val;
childnode = FindCnode(childnode);
}
return result;
}
void CreatTree(TreeNode* root, int depth)
{
if (depth == 0)
{
return;
}
else
{
root->left = new TreeNode(root->val * 2);
root->right = new TreeNode(root->val * 2 + 1);
CreatTree(root->left, depth - 1);
CreatTree(root->right, depth - 1);
}
}
|
C
|
#include <stdlib.h>
#include <stdint.h>
#include <harfbuzz-external.h>
#include "tables/category-properties.h"
#include "tables/combining-properties.h"
HB_LineBreakClass
HB_GetLineBreakClass(HB_UChar32 ch) {
abort();
return 0;
}
static int
combining_property_cmp(const void *vkey, const void *vcandidate) {
const uint32_t key = (uint32_t) (intptr_t) vkey;
const struct combining_property *candidate = vcandidate;
if (key < candidate->range_start) {
return -1;
} else if (key > candidate->range_end) {
return 1;
} else {
return 0;
}
}
static int
code_point_to_combining_class(HB_UChar32 cp) {
const void *vprop = bsearch((void *) (intptr_t) cp, combining_properties,
combining_properties_count,
sizeof(struct combining_property),
combining_property_cmp);
if (!vprop)
return 0;
return ((const struct combining_property *) vprop)->klass;
}
int
HB_GetUnicodeCharCombiningClass(HB_UChar32 ch) {
return code_point_to_combining_class(ch);
return 0;
}
static int
category_property_cmp(const void *vkey, const void *vcandidate) {
const uint32_t key = (uint32_t) (intptr_t) vkey;
const struct category_property *candidate = vcandidate;
if (key < candidate->range_start) {
return -1;
} else if (key > candidate->range_end) {
return 1;
} else {
return 0;
}
}
static HB_CharCategory
code_point_to_category(HB_UChar32 cp) {
const void *vprop = bsearch((void *) (intptr_t) cp, category_properties,
category_properties_count,
sizeof(struct category_property),
category_property_cmp);
if (!vprop)
return HB_NoCategory;
return ((const struct category_property *) vprop)->category;
}
void
HB_GetUnicodeCharProperties(HB_UChar32 ch,
HB_CharCategory *category,
int *combiningClass) {
*category = code_point_to_category(ch);
*combiningClass = code_point_to_combining_class(ch);
}
HB_CharCategory
HB_GetUnicodeCharCategory(HB_UChar32 ch) {
return code_point_to_category(ch);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct node
{
int st;
struct node *link;
};
struct node1
{
int nst[20];
};
static int set[20],nostate,noalpha,s,notransition,nofinal,start,finalstate[20],c,r,buffer[20];
int complete=-1;
char alphabet[20];
static int eclosure[20][20]={0};
struct node1 hash[20];
struct node * transition[20][20]={NULL};
int compare(struct node1 a,struct node1 b)
{
int i;
for (i = 1; i <= nostate; i++)
{
if (a.nst[i]!=b.nst[i])
{
return 0;
}
}
return 1;
}
int insertdfastate(struct node1 newstate)
{
int i;
for (i = 0; i <= complete; i++)
{
if (compare(hash[i],newstate))
{
return 0;
}
}
complete++;
hash[complete]=newstate;
return 1;
}
int findalpha(char c)
{
int i;
for (i = 0; i < noalpha; i++)
{
if (alphabet[i]==c)
{
return i;
}
}
return(-1);
}
void insert(int r,char c,int s)
{
int j;
struct node *temp;
j=findalpha(c);
if (j==-1)
{
printf("\nError!!");
exit(0);
}
temp=(struct node *)malloc(sizeof(struct node));
temp->st=s;
temp->link=transition[r][j];
transition[r][j]=temp;
}
void printnewstate(struct node1 state)
{
int j;
printf("{");
for (j = 1; j <= nostate; j++)
{
if (state.nst[j]!=0)
{
printf("q%d,",state.nst[j]);
}
}
printf("}\t");
}
void findfinalstate()
{
int i,j,k,t;
for (i = 0; i <= complete; i++)
{
for (j = 1; j <= nostate; j++)
{
for (k = 0; k < nofinal; k++)
{
if (hash[i].nst[j]==finalstate[k])
{
printnewstate(hash[i]);
printf("\t");
j=nostate;
break;
}
}
}
}
}
void main()
{
int i,j,k,m,t,n,l;
struct node *temp;
struct node1 newstate={0},tmpstate={0};
printf("Enter the Number of Alphabets:");
scanf("%d",&noalpha);
getchar();
printf("\nEnter the Alphabets:\n");
for (i = 0; i < noalpha; i++)
{
alphabet[i]=getchar();
getchar();
}
printf("\nEnter the Number of States:");
scanf("%d",&nostate);
printf("\nEnter the Initial State:");
scanf("%d",&start);
printf("\nEnter the Number of Final State(s):");
scanf("%d",&nofinal);
printf("\nEnter the Final State(s):");
for (i = 0; i < nofinal; i++)
{
scanf("%d",&finalstate[i]);
}
printf("\nEnter the Number of Transitions:");
scanf("%d",¬ransition);
printf("\nNOTE:-Input Transitions in the form:State Alphabet State");
printf("\nNOTE:-State numbers must be greater than Zero");
printf("\nEnter the Transitions:\n");
for (i = 0; i < notransition; i++)
{
scanf("%d %c %d",&r,&c,&s);
insert(r,c,s);
}
for (i = 0; i < 20; i++)
{
for (j = 0; j < 20; j++)
{
hash[i].nst[j]=0;
}
}
complete=-1;
i=-1;
printf("\nEquivalent DFA:");
printf("\n**************");
printf("\nTransitions of DFA:\n");
newstate.nst[start]=start;
insertdfastate(newstate);
while (i!=complete)
{
i++;
newstate=hash[i];
for (k = 0; k < noalpha; k++)
{
c=0;
for (j = 1; j <= nostate; j++)
{
l=newstate.nst[j];
if (l!=0)
{
temp=transition[l][k];
while (temp!=NULL)
{
if (set[temp->st]==0)
{
c++;
set[temp->st]=temp->st;
}
temp=temp->link;
}
}
}
printf("\n");
if (c!=0)
{
for (m = 1; m <= nostate; m++)
{
tmpstate.nst[m]=set[m];
}
insertdfastate(tmpstate);
printnewstate(newstate);
printf("%c\t",alphabet[k]);
printnewstate(tmpstate);
printf("\n");
}
else
{
printnewstate(newstate);
printf("%c\t",alphabet[k]);
printf("NULL\n");
}
}
}
printf("\nStates of DFA:");
printf("\n*************\n");
for (i = 0; i <= complete; i++)
{
printnewstate(hash[i]);
}
printf("\nAlphabets:\n");
for (i = 0; i < noalpha; i++)
{
printf("%c\t",alphabet[i]);
}
printf("\nStart State:q%d",start);
printf("\nFinal States:\n");
findfinalstate();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "funciones.h"
#define S 20
typedef struct
{
char nombre[20];
int edad;
int dni;
int estado;
char alta;
} eDatosPersonales;
void mostrarPersona(eDatosPersonales personas[], int cant);
int main()
{
char seguir='s';
int opcion=0;
eDatosPersonales personas[S];
int i, j, u, k;
char respuesta;
int contador=0;
int auxDniBusqueda;
char flagBusqueda='n';
for(i=0;i<S;i++)
{
personas[i].estado=-1;
personas[i].alta='n';
}
while(seguir=='s')
{
printf("1- Agregar persona\n"); //OK
printf("2- Borrar persona\n");
printf("3- Imprimir lista ordenada por nombre\n");//OK
printf("4- Imprimir grafico de edades\n\n");
printf("5- Salir\n");
scanf("%d",&opcion);
switch(opcion)
{
case 1:
while(contador<20)
{
respuesta='s';
while(respuesta=='s')
{
if(personas[contador].estado!=-1)
{
printf("NO HAY LUGAR");
break;
}
else
{
personas[contador].estado=0;
personas[contador].alta='s';
for(j=contador;j<S;j++)
{
printf("Ingrese dni: \n\n");
fflush(stdin);
scanf("%d", &personas[j].dni);
if(personas[contador].dni!=personas[j].dni)
{
printf("Ingrese el nombre: \n\n");
fflush(stdin);
gets(personas[j].nombre);
personas[j].nombre[0]= toupper(personas[j].nombre[0]);//Pone la primera letra en mayusculas
printf("Ingrese la edad: \n\n");
fflush(stdin);
scanf("%d", &personas[j].edad);
break;
}
else if(personas[contador].dni==personas[j].dni)
{
printf("EL DNI YA FUE INGRESADO");
break;
}
}
}
printf("Quiere seguir ingresando? s o n: ");
fflush(stdin);
scanf("%c", &respuesta);
if(respuesta=='s')
{
contador++;
}
}
contador++;
break;
}
break;
case 2:
printf("Ingrese el numero de DNI a borrar: ");
fflush(stdin);
scanf("%d", &auxDniBusqueda);
for(k=0;k<contador;k++)
{
if(personas[k].dni==auxDniBusqueda)
{
personas[k].alta='n';
flagBusqueda='s';
printf("Se borro a:%s ", personas[k].nombre);
break;
}
else if(flagBusqueda=='n')
{
printf("No se encontro el DNI");
break;
}
}
break;
case 3:
mostrarPersona(personas, contador);
break;
case 4:
break;
case 5:
seguir = 'n';
break;
}
}
return 0;
}
void mostrarPersona(eDatosPersonales personas[], int cant)
{
int j;
for(j=0;j<=cant;j++)
{
printf("\n---------------");
printf("\n\nNOMBRE:\n\n%s ", personas[j].nombre);
printf("\n\nEDAD:\n\n%d ", personas[j].edad);
printf("\n\nDNI:\n\n%d ", personas[j].dni);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
char url[] = "1_teste.bin";
FILE * file = fopen(url, "rb");
int a[10];
if (file != NULL)
{
fread(a, sizeof(int), 10, file);
printf("Eu lí! :)\n\n");
int i;
for (i = 0; i < 10; i++)
{
printf("%d\n", a[i]);
}
fread(a, sizeof(int), 10, file);
for (i = 0; i < 10; i++)
{
printf("%d\n", a[i]);
}
}
else printf("erro!\n");
fclose(file);
return 0;
}
|
C
|
static inline int mandel(float c_re, float c_im, int count) {
float z_re = c_re, z_im = c_im;
int i;
for (i = 0; i < count; ++i) {
if (z_re * z_re + z_im * z_im > 4.)
break;
float new_re = z_re*z_re - z_im*z_im;
float new_im = 2.f * z_re * z_im;
z_re = c_re + new_re;
z_im = c_im + new_im;
}
return i;
}
export void test(uniform float x0, uniform float y0,
uniform float x1, uniform float y1,
uniform int width, uniform int height,
uniform int maxIterations,
uniform int output[]) {
float dx = (x1 - x0) / width;
float dy = (y1 - y0) / height;
for (uniform int j = 0; j < height; j++) {
foreach (i = 0 ... width) {
float x = x0 + i * dx;
float y = y0 + j * dy;
int index = j * width + i;
output[index] = mandel(x, y, maxIterations);
}
}
}
int main() {
unsigned int width = 768, height = 512;
float x0 = -2., x1 = 1.;
float y0 = -1., y1 = 1.;
int maxIterations = 256;
int *buf = new int[width*height];
test(x0, y0, x1, y1, width, height, maxIterations, buf);
}
|
C
|
/*************************************************************************
# FileName : server.c
# Author : fengjunhui
# Email : [email protected]
# Created : 2018年12月29日 星期六 13时44分59秒
************************************************************************/
#include<stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include "common.h"
/************************************************
*函数名:do_login
*参 数:套接字、消息结构体
*返回值:是否登陆成功
*功 能:登陆
*************************************************/
int do_login(int sockfd)
{
int n;
MSG msg;
while(1){
printf("*************************************************************\n");
printf("******** 1:管理员模式 2:普通用户模式 3:退出********\n");
printf("*************************************************************\n");
printf("请输入您的选择(数字)>>");
scanf("%d",&n);
getchar();
switch(n)
{
case 1:
msg.msgtype = ADMIN_LOGIN;
msg.usertype = ADMIN;
break;
case 2:
msg.msgtype = USER_LOGIN;
msg.usertype = USER;
break;
case 3:
msg.msgtype = QUIT;
if(send(sockfd, &msg, sizeof(MSG), 0)<0)
{
perror("do_login send");
return -1;
}
recv(sockfd,&msg,sizeof(MSG),0);
printf("%s\n",msg.recvmsg);
close(sockfd);
exit(0);
default:
printf("您的输入有误,请重新输入\n");
}
admin_or_user_login(sockfd,&msg);
}
}
/**************************************
*函数名:do_query
*参 数:消息结构体
*功 能:登陆
****************************************/
void do_admin_query(int sockfd,MSG *msg)
{
printf("------------%s-----------%d.\n",__func__,__LINE__);
char sql[1000] = {0};
msg->msgtype = ADMIN_QUERY;
memset(sql,0,sizeof(sql));
send(sockfd, msg, sizeof(MSG), 0);
while(1){
recv(sockfd,sql,sizeof(sql),0);
if(strcmp(sql,"123")==0)
{
break;
}else{
printf("%-7s\n",sql);
}
memset(sql,0,sizeof(sql));
}
}
/**************************************
*函数名:admin_modification
*参 数:消息结构体
*功 能:管理员修改
****************************************/
void do_admin_modification(int sockfd,MSG *msg)//管理员修改
{
printf("------------%s-----------%d.\n",__func__,__LINE__);
char sql[1000] = {0};
int i;
msg->msgtype = ADMIN_MODIFY;
printf("要修改的员工的编号\n");
scanf("%d",&msg->info.no);
/*send(sockfd,msg,sizeof(MSG),0);
while(1){
memset(sql,0,sizeof(sql));
recv(sockfd,sql,sizeof(sql),0);
if(strcmp(sql,"123")==0)
{
break;
}else{
printf("%-7s\n",sql);
}
}*/
printf("请输入要修改的内容\n");
//msg->recvmsg =
printf("员工编号");
scanf("%d",&msg->info.no);
printf("员工姓名");
scanf("%s",msg->info.name);
printf("员工密码");
scanf("%s",msg->info.passwd);
printf("员工年龄");
scanf("%d",&msg->info.age);
printf("员工电话");
scanf("%s",msg->info.phone);
printf("员工地址");
scanf("%s",msg->info.addr);
printf("员工职位");
scanf("%s",msg->info.work);
printf("员工工作年限");
scanf("%d",&msg->info.level);
printf("员工工资");
scanf("%lf",&msg->info.salary);
printf("员工入职年月");
scanf("%s",msg->info.date);
send(sockfd,msg,sizeof(MSG),0);
}
/**************************************
*函数名:admin_adduser
*参 数:消息结构体
*功 能:管理员创建用户
****************************************/
void do_admin_adduser(int sockfd,MSG *msg)//管理员添加用户
{
printf("------------%s-----------%d.\n",__func__,__LINE__);
msg->msgtype = ADMIN_ADDUSER;
printf("请输入权限\n");
scanf("%d",&msg->info.usertype);
printf("%d",msg->info.usertype);
printf("请输入员工信息\n");
printf("员工编号");
scanf("%d",&msg->info.no);
printf("员工姓名");
scanf("%s",msg->info.name);
printf("员工密码");
scanf("%s",msg->info.passwd);
printf("员工年龄");
scanf("%d",&msg->info.age);
printf("员工电话");
scanf("%s",msg->info.phone);
printf("员工地址");
scanf("%s",msg->info.addr);
printf("员工职位");
scanf("%s",msg->info.work);
printf("员工工作年限");
scanf("%d",&msg->info.level);
printf("员工工资");
scanf("%lf",&msg->info.salary);
printf("员工入职年月");
scanf("%s",msg->info.date);
send(sockfd, msg, sizeof(MSG), 0);
}
/**************************************
*函数名:admin_deluser
*参 数:消息结构体
*功 能:管理员删除用户
****************************************/
void do_admin_deluser(int sockfd,MSG *msg)//管理员删除用户
{
printf("------------%s-----------%d.\n",__func__,__LINE__);
int a;
msg->msgtype = ADMIN_DELUSER;
printf("请输入员工编号删除\n");
scanf("%d",&msg->info.no);
send(sockfd,msg,sizeof(MSG),0);
}
/**************************************
*函数名:do_history
*参 数:消息结构体
*功 能:查看历史记录
****************************************/
void do_admin_history (int sockfd,MSG *msg)
{
printf("------------%s-----------%d.\n",__func__,__LINE__);
msg->msgtype = ADMIN_HISTORY;
char sql[1000] = {0};
//msg->msgtype = ADMIN_QUERY;
memset(sql,0,sizeof(sql));
send(sockfd, msg, sizeof(MSG), 0);
while(1){
recv(sockfd,sql,sizeof(sql),0);
if(strcmp(sql,"123")==0)
{
break;
}else{
printf("%-7s\n",sql);
send(sockfd,msg,sizeof(MSG),0);
}
memset(sql,0,sizeof(sql));
}
}
/**************************************
*函数名:admin_menu
*参 数:套接字、消息结构体
*功 能:管理员菜单
****************************************/
void admin_menu(int sockfd,MSG *msg)
{
int n;
while(1)
{
printf("*************************************************************\n");
printf("* 1:查询 2:修改 3:添加用户 4:删除用户 5:查询历史记录*\n");
printf("* 6:退出 *\n");
printf("*************************************************************\n");
printf("请输入您的选择(数字)>>");
scanf("%d",&n);
getchar();
switch(n)
{
case 1:
do_admin_query(sockfd,msg);
break;
case 2:
do_admin_modification(sockfd,msg);
break;
case 3:
do_admin_adduser(sockfd,msg);
break;
case 4:
do_admin_deluser(sockfd,msg);
break;
case 5:
do_admin_history(sockfd,msg);
break;
case 6:
msg->msgtype = QUIT;
send(sockfd, msg, sizeof(MSG), 0);
recv(sockfd,msg,sizeof(MSG),0);
printf("%s\n",msg->recvmsg);
close(sockfd);
exit(0);
default:
printf("您输入有误,请重新输入!\n");
}
}
}
/**************************************
*函数名:do_query
*参 数:消息结构体
*功 能:登陆
****************************************/
void do_user_query(int sockfd,MSG *msg)
{
printf("------------%s-----------%d.\n",__func__,__LINE__);
char sql[1000] = {0};
int i;
msg->msgtype = USER_QUERY;
strcpy(msg->recvmsg,"123");
send(sockfd,msg,sizeof(MSG),0);
for(i=0;i<2;i++)
{
recv(sockfd,sql,sizeof(sql),0);
send(sockfd,msg,sizeof(MSG),0);
printf("%s\n",sql);
memset(sql,0,sizeof(sql));
}
}
/**************************************
*函数名:do_modification
*参 数:消息结构体
*功 能:修改
****************************************/
void do_user_modification(int sockfd,MSG *msg)
{
int n;
printf("------------%s-----------%d.\n",__func__,__LINE__);
msg->msgtype = USER_MODIFY;
while(1){
printf("**********修改内容*****************\n");
printf("**1.密码***2.电话***3.地址***4.退出*\n");
printf("***********************************\n");
printf("请输入选项");
scanf("%d",&n);
switch (n)
{ case 1:
printf("请输入新密码\n");
scanf("%s",msg->info.passwd);
strcpy(msg->recvmsg,msg->info.passwd);
strcpy(msg->amend,"passwd");
send(sockfd,msg,sizeof(MSG),0);
continue;
case 2:
printf("请输入新电话\n");
scanf("%s",msg->info.phone);
strcpy(msg->recvmsg,msg->info.phone);
strcpy(msg->amend,"phone");
send(sockfd,msg,sizeof(MSG),0);
continue;
case 3:
printf("请输入新地址\n");
scanf("%s",msg->info.addr);
strcpy(msg->recvmsg,msg->info.addr);
strcpy(msg->amend,"addr");
send(sockfd,msg,sizeof(MSG),0);
continue;
case 4:
//user_menu(sockfd,msg);
return ;
default:
printf("您输入有误,请输入数字\n");
break;
}
}
}
/**************************************
*函数名:user_menu
*参 数:消息结构体
*功 能:管理员菜单
****************************************/
void user_menu(int sockfd,MSG *msg)
{
printf("------------%s-----------%d.\n",__func__,__LINE__);
int n;
while(1)
{
printf("*************************************************************\n");
printf("************* 1:查询 2:修改 3:退出 *************\n");
printf("*************************************************************\n");
printf("请输入您的选择(数字)>>");
scanf("%d",&n);
getchar();
switch(n)
{
case 1:
do_user_query(sockfd,msg);
break;
case 2:
do_user_modification(sockfd,msg);
break;
case 3:
msg->msgtype = QUIT;
send(sockfd, msg, sizeof(MSG), 0);
close(sockfd);
exit(0);
default:
printf("您输入有误,请输入数字\n");
break;
}
}
}
int admin_or_user_login(int sockfd,MSG *msg)
{
printf("------------%s-----------%d.\n",__func__,__LINE__);
//输入用户名和密码
memset(msg->username, 0, NAMELEN);
printf("请输入用户名:");
scanf("%s",msg->username);
getchar();
memset(msg->passwd, 0, DATALEN);
printf("请输入密码(6位)");
scanf("%s",msg->passwd);
getchar();
//发送登陆请求
send(sockfd, msg, sizeof(MSG), 0);
//接受服务器响应
recv(sockfd, msg, sizeof(MSG), 0);
printf("msg->recvmsg :%s\n",msg->recvmsg);
//判断是否登陆成功
if(strncmp(msg->recvmsg, "OK", 2) == 0)
{
if(msg->usertype == ADMIN)
{
printf("亲爱的管理员,欢迎您登陆员工管理系统!\n");
strcpy(msg->cunchu,msg->username);
admin_menu(sockfd,msg);
}
else if(msg->usertype == USER)
{
printf("亲爱的用户,欢迎您登陆员工管理系统!\n");
strcpy(msg->cunchu,msg->username);
user_menu(sockfd,msg);
}
}
else
{
printf("登陆失败!%s\n", msg->recvmsg);
return -1;
}
return 0;
}
int main(int argc, const char *argv[])
{
//socket->填充->绑定->监听->等待连接->数据交互->关闭
int sockfd;
int acceptfd;
ssize_t recvbytes,sendbytes;
struct sockaddr_in serveraddr;
struct sockaddr_in clientaddr;
socklen_t addrlen = sizeof(serveraddr);
socklen_t cli_len = sizeof(clientaddr);
//创建网络通信的套接字
sockfd = socket(AF_INET,SOCK_STREAM, 0);
if(sockfd == -1){
perror("socket failed.\n");
exit(-1);
}
printf("sockfd :%d.\n",sockfd);
//填充网络结构体
memset(&serveraddr,0,sizeof(serveraddr));
memset(&clientaddr,0,sizeof(clientaddr));
serveraddr.sin_family = AF_INET;
// serveraddr.sin_port = htons(atoi(argv[2]));
// serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
serveraddr.sin_port = htons(5001);
serveraddr.sin_addr.s_addr = inet_addr("192.168.1.161");
if(connect(sockfd,(const struct sockaddr *)&serveraddr,addrlen) == -1){
perror("connect failed.\n");
exit(-1);
}
do_login(sockfd);
close(sockfd);
return 0;
}
|
C
|
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#define PING_MODE 1
#define PONG_MODE 2
#define DEBUG 1
#define MSG_SIZE 1
// configurable_values
#define STARTING_HOST 0
#define PING_DELAY 50000
#define PONG_DELAY 1000000
// Debug mode default disabled
int debug = 0;
// Initial ping, pong and m values
int ping = 1;
int pong = -1;
int m = 0;
// Host variables
int my_id = 1;
int nproc;
int nextHost;
int critical_section = 0;
pthread_mutex_t main_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t wait_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t wait_conditional = PTHREAD_COND_INITIALIZER;
// void regenerate(int val) {
// ping = abs(val);
// pong = -ping;
// }
void incarnate(int val) {
// ping = (abs(val) + 1)%(nproc+1);
ping = abs(val)+1;
pong = -ping;
}
void sendToken(int val, int type){
m = val;
if(type == PING_MODE){
if(debug){
printf("[Thread %d] Sending PING: %d\n",my_id, val);
}
usleep(PING_DELAY);
MPI_Send(&val, MSG_SIZE, MPI_INT, nextHost, PING_MODE, MPI_COMM_WORLD);
}
else if(type == PONG_MODE){
if(debug){
printf("[Thread %d] Sending PONG: %d\n",my_id, val);
}
usleep(PONG_DELAY);
MPI_Send(&val, MSG_SIZE, MPI_INT, nextHost, PONG_MODE, MPI_COMM_WORLD);
}
}
void *receive_thread()
{
// printf("%d: Zaczynam wątek odbierający\n", my_id);
while (1)
{
int msg;
MPI_Status status;
int size;
MPI_Recv(&msg, MSG_SIZE, MPI_INT,MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD,&status);
MPI_Get_count( &status, MPI_INT, &size);
if(status.MPI_TAG == PING_MODE){
if(!(abs(msg) < abs(m))){
if(debug){
printf("[Thread %d] PING received: %d\n",my_id,msg);
}
pthread_mutex_lock(&main_mutex);
if(m == msg){
// instead of regenerate and than increment do incarnate (to simplyfy code)
incarnate(msg);
if(debug){
printf("[Thread %d] PONG REGENERATE\n[Thread %d] New PONG value %d\n",my_id,my_id,pong);
}
sendToken(pong,PONG_MODE);
}
else {
ping = msg;
if(debug){
printf("[Thread %d] Received token for Critical section %d\n",my_id,ping);
}
}
critical_section = 1;
pthread_mutex_unlock(&main_mutex);
pthread_cond_signal(&wait_conditional);
}
else {
if(debug){
printf("[Thread %d] Old PING %d\n",my_id,msg);
}
}
}
else if(status.MPI_TAG == PONG_MODE){
if(!(abs(msg) < abs(m))){
if(debug){
printf("[Thread %d] PONG received: %d\n",my_id,msg);
}
pthread_mutex_lock(&main_mutex);
// PING and PONG meets
if(critical_section){
incarnate(msg);
if(debug){
printf("[Thread %d] Incarnation: %d\n",my_id,ping);
}
sendToken(pong,PONG_MODE);
pthread_mutex_unlock(&main_mutex);
}
else if(m == msg){
// instead of regenerate and than increment do incarnate (to simplyfy code)
incarnate(msg);
if(debug){
printf("[Thread %d] PING REGENERATE\n[Thread %d] New PING value %d\n",my_id,my_id,ping);
}
critical_section = 1;
sendToken(pong,PONG_MODE);
pthread_mutex_unlock(&main_mutex);
pthread_cond_signal(&wait_conditional);
}
else{
pong = msg;
sendToken(pong,PONG_MODE);
pthread_mutex_unlock(&main_mutex);
}
}
else {
if(debug){
printf("[Thread %d] Old PONG %d\n",my_id,msg);
}
}
}
pthread_cond_signal(&wait_conditional);
}
return 0;
}
int main(int argc, char** argv) {
int run_mode =0;
int opt;
while ((opt = getopt(argc, argv, "dt:")) != -1) {
switch (opt) {
case 'd':
debug = DEBUG;
break;
case 't':
if(strncmp(optarg,"ping",4)==0){
run_mode = PING_MODE;
}
else if(strncmp(optarg,"pong",4)==0){
run_mode = PONG_MODE;
}
else{
fprintf(stderr,"Wrong parameters \n");
exit(EXIT_FAILURE);
}
break;
default: /* '?' */
fprintf(stderr, "Usage: %s [-t mode] -d \n",
argv[0]);
exit(EXIT_FAILURE);
}
}
int temp;
MPI_Init_thread(&argc, &argv, 3, &temp);
MPI_Comm_size(MPI_COMM_WORLD, &nproc );
MPI_Comm_rank(MPI_COMM_WORLD, &my_id );
MPI_Barrier(MPI_COMM_WORLD);
nextHost = (my_id+1)%nproc;
pthread_t thread;
int rc = pthread_create(&thread, NULL, receive_thread, NULL);
if(rc){
fprintf(stderr,"Receiving thread failed to start...\nExiting...\n");
MPI_Finalize();
}
printf("Sync level: %d\n", temp);
MPI_Barrier(MPI_COMM_WORLD);
sleep(1);
if(debug){
printf("Starting thread : %d\n",my_id);
};
if(my_id == STARTING_HOST){
// Sending PING
if(!(run_mode == 1)){
sendToken(ping,PING_MODE);
}
if(!(run_mode == 2)){
// Sending PONG
sendToken(pong,PONG_MODE);
}
}
while(1){
pthread_mutex_lock(&wait_mutex);
while(!critical_section){
pthread_cond_wait(&wait_conditional,&wait_mutex);
}
if(debug){
printf("Thread %d entered critical section\n",my_id);
}
sleep(2);
if(debug){
printf("Thread %d left critical section\n",my_id);
}
pthread_mutex_lock(&main_mutex);
critical_section = 0;
sendToken(ping,PING_MODE);
pthread_mutex_unlock(&main_mutex);
pthread_mutex_unlock(&wait_mutex);
}
pthread_join(thread, NULL);
MPI_Finalize();
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int a=9, b,c;
b = (a==9) ? (a=5;c=1) :10 ;//
printf("%d",b);
return 0;
}
|
C
|
#include "bubble.h"
int num_comp = 0;
int num_swap = 0;
void get_results(int *comp_count, int *swap_count)
{
*comp_count = num_comp;
*swap_count = num_swap;
num_comp = 0;
num_swap = 0;
}
void swap(int *array, int index1, int index2)
{
num_swap++;
array[index1] = array[index1] ^ array[index2];
array[index2] = array[index1] ^ array[index2];
array[index1] = array[index1] ^ array[index2];
}
void bubble_sort(int *array, int arrayLength)
{
for(int i = 0; i < arrayLength - 1; i++){
for(int j = i + 1; j < arrayLength; j++){
num_comp++;
if(array[i] > array[j])
swap(array, i, j);
}
}
}
|
C
|
#include <stdio.h>
int main(int argc, char *argv[])
{
int n, k, kn, s, i, t = 0;
scanf("%d %d\n", &n, &k);
for (i = 1; i <= n; ++i) {
scanf("%d", &s);
if (i <= k && s > 0) {
++t;
if (i == k)
kn = s;
} else if (kn == s && s > 0) {
++t;
}
}
printf("%d", t);
return 0;
}
|
C
|
/*
* libc.c SYSTEM CALL WRAPPERS
*/
#include <libc.h>
#include <types.h>
#include <errno.h>
int errno;
void itoa(int a, char *b)
{
int i, i1;
char c;
if (a==0) { b[0]='0'; b[1]=0; return ;}
i=0;
while (a>0)
{
b[i]=(a%10)+'0';
a=a/10;
i++;
}
for (i1=0; i1<i/2; i1++)
{
c=b[i1];
b[i1]=b[i-i1-1];
b[i-i1-1]=c;
}
b[i]=0;
}
int strlen(char *a)
{
int i;
i=0;
while (a[i]!=0) i++;
return i;
}
void perror()
{
switch(errno) {
case 9:
write (1, "Bad file number\n", 16);
break;
case 13:
write (1, "Permission denied\n", 18);
break;
case 14:
write (1, "Bad address\n", 12);
break;
case 22:
write (1, "Invalid argument\n", 17);
break;
case 38:
write (1, "Function not implemented\n",25);
break;
default:
write (1, "Error not defined\n",18);
break;
}
}
|
C
|
#include "holberton.h"
/**
* _strncpy - cpoies a string of n char
* @dest: the final string
* @src: the string to copy from
* @n: the number of char to copy
* Return: the final output
*/
char *_strncpy(char *dest, char *src, int n)
{
int count;
for (count = 0; count < n && src[count] != '\0'; count++)
dest[count] = src[count];
while (count < n)
{
dest[count] = '\0';
count++;
}
return (dest);
}
|
C
|
#include <stdio.h>
void arrayShiftRight(int array[], int size) {
int last = size - 1;
int tmp = array[last];
for ( int i = 0; i < last; last-- ) {
array[last] = array[last-1];
}
array[0] = tmp;
}
int main() {
int size = 5;
int array[] = { 1, 9, 3, 8, 5 };
arrayShiftRight(array, size);
for ( int i = 0; i < size; i++ ) {
printf("%d\n", array[i]);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Dog
{
int age;
char *breed;
};
int main()
{
/** Create a program that does the following while using the pre-made struct above:
** Create and allocate a dynamic struct array that can hold the information of 5 dogs.
** Ask the user for input for each of the five dogs one at a time, making sure to allocate any memory necessary for the breed.
** Print the information of all 5 dogs at the end, making sure to keep it in order, so "Dog 1 name is x, etc"
** Free all of the memory allocated and use Valgrind to help find leaks
**/
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void display_tab(int *od, int *doo)
{
for(; od<doo; ++od)
printf("%d\n", *od);
}
int counting_lines(char const *name)
{
FILE *file = fopen(name, "r");
if(file==NULL)
{
printf("Nie udalo sie otworzyc pliku");
getchar();
exit(1);
}
char line[255];
int number_of_lines = 0;
while(fgets(line, 250, file)!=NULL)
++number_of_lines;
fclose(file);
return number_of_lines;
}
void sort(int tab[], int num)
{
int cubby, k;
for(int i=1; i<num; i++)
{
cubby = tab[i];
for(k=i-1; k>=0; k--)
{
if(cubby < tab[k])
{
tab[k+1] = tab[k];
}
else
break;
}
tab[k+1] = cubby;
}
}
int main(int argc, char *argv[])
{
if(argc < 2)
{
printf("Nie podano nazwy pliku do otwarcia!\n");
exit(1);
}
char const *name1 = argv[1];
int number_of_lines = counting_lines(name1);
int tab[number_of_lines];
FILE *file = fopen(name1, "r");
char line[255];
for(int i=0; i<number_of_lines; i++)
{
fgets(line, 250, file);
tab[i] = (int)strtol(line, NULL, 10);
}
fclose(file);
sort(tab, number_of_lines);
if(argc == 2)
display_tab(tab, tab+number_of_lines);
else{
char const *name2 = argv[2];
file = fopen(name2, "w");
fprintf(file, "%d", tab[0]);
fclose(file);
file = fopen(name2, "a");
for(int i=1; i<number_of_lines; i++)
{
fprintf(file, "\n");
fprintf(file, "%d", tab[i]);
}
fclose(file);
}
}
|
C
|
#include "blather.h"
client_t client_actual = {}; //client as global variable
client_t *client = &client_actual; //pointer to client
simpio_t simpio_actual; //simpio as global variable
simpio_t *simpio = &simpio_actual; //pointer to simpio
pthread_t user_thread; //user interaction thread(user input)
pthread_t server_thread; //server interaction thread(reading mesg from server)
int join_fd; //fd for join fifo to server
void *user_worker(void *arg){ //function passed into user thread
while(!simpio->end_of_input){ // repeat until End of Input
simpio_reset(simpio); //reset simpio every time getting new input
iprintf(simpio, "");
while(!simpio->line_ready && !simpio->end_of_input){ //get input by one char
simpio_get_char(simpio);
}
if(simpio->line_ready){ //if input is complete
mesg_t mesg_actual = {}; //mesg
mesg_t *mesg = &mesg_actual; //pointer to mesg
mesg->kind = BL_MESG; //set kind as BL_MESG
strncpy(mesg->name, client->name, MAXPATH); //copy name to mesg
strncpy(mesg->body, simpio->buf, MAXPATH); //copy body(text) to mesg
// iprintf(simpio, "kind, name and body: %d %s %s ", mesg->kind, mesg->name, mesg->body);
int res = write(client->to_server_fd, mesg, sizeof(mesg_t)); //send data to server
check_fail(res==-1,1,"Sending msg to server Fail!\n");
}
}
mesg_t mesg_actual = {}; //mesg
mesg_t *mesg = &mesg_actual; //pointer to mesg
//if client entered End of Input (means client departed)
mesg->kind = BL_DEPARTED;
snprintf(mesg->name, MAXNAME, "%s", client->name);
write(client->to_server_fd, mesg, sizeof(mesg_t)); //send departure message to server
pthread_cancel(server_thread); //cancel server thread since user departed chat
return NULL;
}
void *server_worker(void *arg){
mesg_t mesg_actual; //mesg
mesg_t *mesg = &mesg_actual; //pointer to mesg
mesg->kind = BL_MESG; // initialize kind to default
// int res = read(client->to_client_fd, mesg, sizeof(mesg_t)); //get message first
// printf("read: %d\n", res);
while(mesg->kind != BL_SHUTDOWN){ //repeat till getting shutdown mesg from server
int res = read(client->to_client_fd, mesg, sizeof(mesg_t)); //get message first
check_fail(res==-1,1,"Read from server Fail!\n"); // error check
switch(mesg->kind){ // do jobs based on mesg kind
case BL_MESG :
iprintf(simpio, "[%s] : %s\n", mesg->name, mesg->body);
break;
case BL_JOINED :
iprintf(simpio, "-- %s JOINED --\n", mesg->name);
break;
case BL_DEPARTED :
if(!strcmp(mesg->name,client->name)){
break; //the iprintf should not show up to the client who is actually departing..
}
iprintf(simpio, "-- %s DEPARTED --\n", mesg->name);
break;
default :
break;
}
}
iprintf(simpio, "!!! server is shutting down !!!\n"); // let know that server is shutting down
pthread_cancel(user_thread); //cancel user thread for server is shutting down
return NULL;
}
int main(int argc, char *argv[]){
if(argc < 3){ //if user did not put command args properly
printf("usage: %s <server name> <client name>\n", argv[0]);
exit(1);
}
char server_name[MAXPATH]; //server name
char join_fifo[MAXPATH]; //join fifo name
snprintf(server_name, MAXPATH, "%s", argv[1]);
snprintf(join_fifo, MAXPATH, "%s.fifo", argv[1]);
snprintf(client->name, MAXPATH, "%s", argv[2]); //client name
snprintf(client->to_client_fname, MAXPATH, "%d.tc.fifo", getpid()); //to-client fifo name
snprintf(client->to_server_fname, MAXPATH, "%d.ts.fifo", getpid()); //to-server fifo name
client->data_ready = 0; //data is not ready so 0
join_t join_req = {}; //join request to server
snprintf(join_req.name, MAXPATH, "%s", client->name); //copy name to request
// printf("name is %s\n", join_req.name);
snprintf(join_req.to_client_fname, MAXPATH, "%s", client->to_client_fname); //copy fifo name to request
snprintf(join_req.to_server_fname, MAXPATH, "%s", client->to_server_fname); //copy fifo name to request
remove(client->to_client_fname); //remove previously existing fifo
remove(client->to_server_fname); //remove previously existing fifo
mkfifo(client->to_client_fname, DEFAULT_PERMS); //make fifo
mkfifo(client->to_server_fname, DEFAULT_PERMS); //make fifo
client->to_client_fd = open(client->to_client_fname, O_RDWR); //open to-client fd
client->to_server_fd = open(client->to_server_fname, O_RDWR); //open to-server fd
join_fd = open(join_fifo, O_RDWR); //open fd for join fifo
//now server knows the client and they can interact!
write(join_fd, &join_req, sizeof(join_t));
char prompt[MAXNAME]; // prompt buffer
snprintf(prompt, MAXNAME, "%s>> ", client->name); // create a prompt string
simpio_set_prompt(simpio, prompt); // set the prompt
simpio_reset(simpio); // initialize simpio
simpio_noncanonical_terminal_mode(); // set the terminal into a compatible mode
pthread_create(&user_thread, NULL, user_worker, NULL); // start user thread to read input
pthread_create(&server_thread, NULL, server_worker, NULL); // start server thread to read message from server
pthread_join(user_thread, NULL); // wait for user thread to return
pthread_join(server_thread, NULL); //wait for server thread to return
simpio_reset_terminal_mode(); // reset terminal at end of run
printf("\n");
return 0;
}
|
C
|
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
// "只有字母和数字[0-9a-zA-Z]、一些特殊符号"$-_.+!*'(),"[不包括双引号]、以及某些保留字,才可以不经过编码直接用于URL。"
static int
isURIChar(const char ch) {
if (isalnum(ch))
return 1;
if (ch == ' ')
return 0;
switch (ch) {
case '$':
case '-':
case '_':
case '.':
case '+':
case '!':
case '*':
case '\'':
case '(':
case ')':
return 1;
default:
return 0;
}
}
char *
URIEncode(const char *uri, const char *type) {
int n = strlen(uri);
char *cp = (char *)malloc(n * 6);
memset(cp, 0, n * 6);
int pn = 0;
// scan uri
if (strcmp("uri", type) == 0) {
for (int i = 0; i < n; i ++ ) {
if (isURIChar(uri[i])) {
cp[pn++] = uri[i];
continue;
}
// UTF8
char it[4] = { 0 };
if ((unsigned char)uri[i] < 0x10)
sprintf(it, "%%0%X", (unsigned char)uri[i]);
else
sprintf(it, "%%%X", (unsigned char)uri[i]);
strcat(cp, it);
pn += 3;
}
} else if (strcmp("c", type) == 0) {
for (int i = 0; i < n; i ++ ) {
char it[5] = { 0 };
if ((unsigned char)uri[i] < 0x10)
sprintf(it, "\\x0%X", (unsigned char)uri[i]);
else
sprintf(it, "\\x%X", (unsigned char)uri[i]);
strcat(cp, it);
pn += 4;
}
} else if (strcmp("java", type) == 0 || strcmp("unicode", type) || strcmp("js", type) || strcmp("utf", type)) {
for (int i = 0; i < n; i ++ ) {
if (uri[i] < 0) {
cp[pn++] = uri[i];
continue;
}
//continue;
char it[7] = { 0 };
if ((unsigned char)uri[i] < 0x10)
sprintf(it, "\\u000%X", (unsigned char)uri[i]);
else
sprintf(it, "\\u00%X", (unsigned char)uri[i]);
strcat(cp, it);
pn += 6;
}
}
return cp;
}
int
main(int argc, char *argv[]) {
#define BUFLE 1024L
long long cur = 0;
long long length = BUFLE * 2;
char *buf = (void *)malloc(length);
while (1) {
long long le = read(0, &buf[cur], length - cur - 1);
cur += le;
if (le < 1) {
break;
}
if (length - cur < BUFLE) {
length *= 2;
buf = realloc(buf, length);
}
}
buf[cur] = '\0';
if (argc == 2)
printf("%s\n", URIEncode(buf, argv[1]));
else
printf("%s\n", URIEncode(buf, "uri"));
return 0;
}
|
C
|
/* K&R exercise 1.17
* Prints lines which are longer than 80 characters
*/
#include <stdio.h>
/* Maximum allowed length of line */
#define MAXLEN 1000
int getline (char [], int);
main()
{
char line[MAXLINE];
int len;
while ((len = getline(line, MAXLEN)) > 0)
if (len > 80)
printf("%s",line);
return 0;
}
/* Reads a line of input */
int getline(char s[], int lim)
{
int c,i;
i = 0;
while(--lim > 0 && (c = getchar()) != EOF && c != '\n')
s[i++] = c;
if (c == '\n')
{
s[i] = c;
i++;
}
s[i] = '\0';
return i;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_op_run_dq.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tayamamo <[email protected].> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/15 19:06:05 by tayamamo #+# #+# */
/* Updated: 2021/04/23 03:33:20 by tayamamo ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
static void _run_rrr(t_dq *dq, int op)
{
int tmp;
if ((op == RRA || op == RRR) && !ft_deque_is_empty(dq->a))
{
tmp = ft_deque_get_back(dq->a);
ft_deque_pop_back(dq->a);
ft_deque_push_front(dq->a, tmp);
}
if ((op == RRB || op == RRR) && !ft_deque_is_empty(dq->b))
{
tmp = ft_deque_get_back(dq->b);
ft_deque_pop_back(dq->b);
ft_deque_push_front(dq->b, tmp);
}
}
static void _run_rr(t_dq *dq, int op)
{
int tmp;
if ((op == RA || op == RR) && !ft_deque_is_empty(dq->a))
{
tmp = ft_deque_get_front(dq->a);
ft_deque_pop_front(dq->a);
ft_deque_push_back(dq->a, tmp);
}
if ((op == RB || op == RR) && !ft_deque_is_empty(dq->b))
{
tmp = ft_deque_get_front(dq->b);
ft_deque_pop_front(dq->b);
ft_deque_push_back(dq->b, tmp);
}
}
void ft_op_run_dq(t_dq *dq, int op)
{
int tmp;
if (op == SA || op == SS)
ft_deque_swap_front(dq->a);
if (op == SB || op == SS)
ft_deque_swap_front(dq->b);
if ((op == PA) && !ft_deque_is_empty(dq->b))
{
tmp = ft_deque_get_front(dq->b);
ft_deque_pop_front(dq->b);
ft_deque_push_front(dq->a, tmp);
}
if ((op == PB) && !ft_deque_is_empty(dq->a))
{
tmp = ft_deque_get_front(dq->a);
ft_deque_pop_front(dq->a);
ft_deque_push_front(dq->b, tmp);
}
_run_rr(dq, op);
_run_rrr(dq, op);
}
|
C
|
#include <stdio.h>
struct money_box // ü
{
int w500; // 500
int w100; // 100
int w50; // 50
int w10; // 10
};
typedef struct money_box MoneyBox; // MoneyBox
void init(MoneyBox *s); // MoneyBox ʱȭ
void save(MoneyBox *s, int unit, int cnt); // MoneyBox
int total(MoneyBox *s);
int main(void)
{
MoneyBox yuni;
int unit, cnt, tot;
init(&yuni);
while (1)
{
printf(" ݾװ : ");
scanf("%d", &unit);
if (unit <= 0) break;
scanf("%d", &cnt);
save(&yuni, unit, cnt);
}
tot = total(&yuni);
printf(" ݾ : %d\n", tot);
return 0;
}
void init(MoneyBox *s)
{
s->w500 = s->w100 = s->w50 = s->w10 = 0;
}
void save(MoneyBox *s, int unit, int cnt)
{
if (unit == 500) s->w500 += cnt;
else if (unit == 100) s->w100 += cnt;
else if (unit == 50) s->w50 += cnt;
else if (unit == 10) s->w10 += cnt;
}
int total(MoneyBox *s)
{
int sum = 0;
sum += s->w500 * 500;
sum += s->w100 * 100;
sum += s->w50 * 50;
sum += s->w10 * 10;
return sum;
}
|
C
|
#include <stdio.h>
#include <icmpv6.h>
#include <common.h>
void print_icmp6_header(const struct icmp6hdr *icmp, int size) {
printf("\n\t|-Type: ");
switch ((icmp -> type)) {
case ICMP6_ECHOREQUEST:
printf("Echo Request");
break;
case ICMP6_ECHOREPLY:
printf("Echo Reply");
break;
default:
printf("%d", (icmp -> type));
}
printf("\n\t|-Code: ");
printf("%u", icmp -> code);
printf("\n\t|-Checksum: ");
printf("%.4x", ntohs(icmp -> cksum));
printf("\n\t|-Header data: ");
printf("%.8x\n", ntohl(icmp -> dataun.un_data32[0]));
}
void print_icmp6_echo(const struct icmp6hdr *icmp, int size) {
printf("\n\t|-Identifier: ");
printf("%.1x", ntohs(icmp->dataun.un_data16[0]));
printf("\n\t|-Sequence Number: ");
printf("%.1x", ntohs(icmp->dataun.un_data16[1]));
printf("\n\t|-Data: ");
}
|
C
|
#include<stdio.h>
int main()
{
float x,y,r,x1,y1,a,b,c;
scanf("%f%f%f%f%f",&x,&y,&r,&x1,&y1);
a=(((x1-x)*(x1-x))+((y1-y)*(y1-y)));
b=r*r;
c=a-b;
if (c<=0){
if (c==0){
printf("Point is on the circle.");
}
else {
printf("Point is inside the circle.");
}
}
else {
printf("Point is outside the circle.");
}
return 0;
}
|
C
|
/* scanner.c
*
* Token scanner (in literature also called symbol scanner)
*
* A program consist of a sequence of tokens. A token is a group of one or
* more characters which have a special meaning in the programming language.
* The scanner reads a program character by character (by using the 'reader'
* object) and converts these into tokens.
*
* Object 'scanner' is the API to the token scanner. Only one scanner object
* exists. For its definition see scanner.h.
*
* The next token is read by calling 'scanner.next'. On return variable
* 'scanner.token' contains the token and 'scanner.string' - if applicable - the
* identifier, the number, the character or the string. In all other cases it
* contains an empty string ("").
*
* 1994 K.W.E. de Lange
*/
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include "identifier.h"
#include "scanner.h"
#include "reader.h"
#include "error.h"
/* Table containing all language keywords and their corresponding tokens.
*/
static struct {
char *keyword;
token_t token;
} keywordTable[] = { /* Note: keyword strings must be sorted alphabetically */
{ "and", AND },
{ "break", BREAK },
{ "char", DEFCHAR },
{ "continue", CONTINUE },
{ "def", DEFFUNC },
{ "do", DO },
{ "else", ELSE },
{ "float", DEFFLOAT },
{ "for", FOR },
{ "if", IF },
{ "import", IMPORT },
{ "in", IN },
{ "input", INPUT },
{ "int", DEFINT },
{ "list", DEFLIST},
{ "or", OR },
{ "pass", PASS },
{ "print", PRINT },
{ "return", RETURN },
{ "str", DEFSTR },
{ "while", WHILE }
};
/* Forward declarations.
*/
static token_t read_next_token(char *buffer);
static token_t read_identifier(char *buffer);
static token_t read_character(char *buffer);
static token_t read_string(char *buffer);
static token_t read_number(char *buffer);
/* API: Initialize scanner object 'sc'.
*/
static void scanner_init(struct scanner *sc)
{
assert(sc != NULL);
/* load the function addresses from the global scanner */
*sc = scanner;
/* reset all object variables to their initial states */
sc->token = UNKNOWN;
sc->peeked = 0;
sc->at_bol = true;
sc->string[0] = 0;
}
/* API: Save the global scanner state in sc.
*/
static void scanner_save(struct scanner *sc)
{
assert(sc != NULL);
*sc = scanner;
}
/* API: Load the global scanner state from sc.
*/
static void scanner_jump(struct scanner *sc)
{
assert(sc != NULL);
scanner = *sc;
}
/* API: Read the next token.
*
* return token read
*
* If previously a peek was executed then return the peeked token.
*/
static token_t next_token(void)
{
if (scanner.peeked == 0)
scanner.token = read_next_token(scanner.string);
else {
scanner.token = scanner.peeked;
scanner.peeked = 0;
}
debug_printf(DEBUGTOKEN, "\ntoken : %s %s", \
tokenName(scanner.token), scanner.string);
return scanner.token;
}
/* API: Look at the next token, without actually considering it read.
*
* return peeked token
*
* Only a single peek is possible, you cannot look more then 1 token ahead.
*/
static token_t peek_token(void)
{
if (scanner.peeked == 0)
scanner.peeked = read_next_token(scanner.string);
return scanner.peeked;
}
/* Read the next token.
*
* buffer pointer to buffer containing the token which was read
* return obecttype which was read
*
* After reading 'buffer' contains:
* the identifier if token == IDENTIFIER
* the number if token == INTEGER or FLOAT
* the string if token == STRING
* the character if token == CHAR
* and an empty string ("") for all other tokens
*/
static token_t read_next_token(char *buffer)
{
char ch;
assert(buffer != NULL);
buffer[0] = 0;
/* Determine the level of indentation. If it has increased compared to the
* previous line then token is INDENT. Has it decreased then check if it
* was equal to the previous (smaller) indentation. If so then the token
* is DEDENT, else there is an indentation error.
* If the indentation has not changed then continue reading the next token.
*/
while (scanner.at_bol == true) {
int col = 0;
scanner.at_bol = false;
/* determine the indentation */
while (1) {
ch = reader.nextch();
if (ch == ' ')
col++;
else if (ch == '\t')
col = (col / config.tabsize + 1) * config.tabsize;
else
break;
} /* col = column-nr of first character which is not tab or space */
/* ignore empty lines or comment only lines */
if (ch == '#')
while (ch != '\n' && ch != EOF)
ch = reader.nextch();
if (ch == '\n') {
scanner.at_bol = true;
continue;
} else if (ch == EOF) {
col = 0; /* do we need more DEDENTs? */
if (col == local->indentation[local->indentlevel])
return ENDMARKER;
} else
reader.pushch(ch);
if (col == local->indentation[local->indentlevel])
break; /* indentation has not changed */
else if (col > local->indentation[local->indentlevel]) {
if (local->indentlevel == MAXINDENT)
error(SyntaxError, "max indentation level reached");
local->indentation[++local->indentlevel] = col;
return INDENT;
} else { /* col < local->indentation[local->level] */
if (--local->indentlevel < 0)
error(SyntaxError, "inconsistent use of TAB and space in identation");
if (col != local->indentation[local->indentlevel]) {
scanner.at_bol = true; /* not yet at old indentation level */
reader.to_bol();
}
return DEDENT;
}
}
/* skip spaces */
do {
ch = reader.nextch();
} while (ch == ' ' || ch == '\t');
/* skip comments */
if (ch == '#')
while (ch != '\n' && ch != EOF)
ch = reader.nextch();
/* check for end of line or end of file */
if (ch == '\n') {
scanner.at_bol = true;
return NEWLINE;
} else if (ch == EOF)
return ENDMARKER;
if (isdigit(ch)) {
reader.pushch(ch);
return read_number(buffer);
} else if (isalpha(ch)) {
reader.pushch(ch);
return read_identifier(buffer);
} else {
switch (ch) {
case '\'': return read_character(buffer);
case '\"': return read_string(buffer);
case EOF : return ENDMARKER;
case '(' : return LPAR;
case ')' : return RPAR;
case '[' : return LSQB;
case ']' : return RSQB;
case ',' : return COMMA;
case '.' : return DOT;
case ':' : return COLON;
case '*' : if (reader.peekch() == '=') {
reader.nextch();
return STAREQUAL;
} else
return STAR;
case '%' : if (reader.peekch() == '=') {
reader.nextch();
return PERCENTEQUAL;
} else
return PERCENT;
case '+' : if (reader.peekch() == '=') {
reader.nextch();
return PLUSEQUAL;
} else
return PLUS;
case '-' : if (reader.peekch() == '=') {
reader.nextch();
return MINUSEQUAL;
} else
return MINUS;
case '/' : if (reader.peekch() == '=') {
reader.nextch();
return SLASHEQUAL;
} else
return SLASH;
case '!' : if (reader.peekch() == '=') {
reader.nextch();
return NOTEQUAL;
} else
return NOT;
case '=' : if (reader.peekch() == '=') {
reader.nextch();
return EQEQUAL;
} else
return EQUAL;
case '<' : if (reader.peekch() == '=') {
reader.nextch();
return LESSEQUAL;
} else if (reader.peekch() == '>') {
reader.nextch();
return NOTEQUAL;
} else
return LESS;
case '>' : if (reader.peekch() == '=') {
reader.nextch();
return GREATEREQUAL;
} else
return GREATER;
default : return UNKNOWN;
}
}
}
/* Read a string.
*
* string pointer to a buffer where the string will be stored
* return objecttype which was read (by definition STR_T)
*
* Strings are surrounded by double quotes. Escape sequences are recognized.
* Examples: "abc" "xyz\n" ""
*/
static token_t read_string(char *string)
{
char ch;
int count = 0;
while (1) {
ch = reader.nextch();
if (ch != EOF && ch != '\"') {
if (ch == '\\')
switch (reader.peekch()) {
case '0' : reader.nextch(); ch = '\0'; break;
case 'a' : reader.nextch(); ch = '\a'; break;
case 'b' : reader.nextch(); ch = '\b'; break;
case 'f' : reader.nextch(); ch = '\f'; break;
case 'n' : reader.nextch(); ch = '\n'; break;
case 'r' : reader.nextch(); ch = '\r'; break;
case 't' : reader.nextch(); ch = '\t'; break;
case 'v' : reader.nextch(); ch = '\v'; break;
case '\\': reader.nextch(); ch = '\\'; break;
case '\'': reader.nextch(); ch = '\''; break;
case '\"': reader.nextch(); ch = '\"'; break;
}
if (count < BUFSIZE)
string[count++]= ch;
} else {
string[count] = 0;
break;
}
}
return STR_T;
}
/* Read an integer or a floating point number.
*
* number pointer to buffer with string representation of the number read
* return objecttype which was read (INT_T or FLOAT_T)
*
* Scientific notation (e, E) is recognized.
* Examples: 2 2. 0.2 2.0 1E+2 1E2 1E-2 0.1e+2
*/
static token_t read_number(char *number)
{
char ch;
int dot = 0;
int exp = 0;
int count = 0;
while (1) {
ch = reader.nextch();
if (ch != EOF && (isdigit(ch) || ch == '.')) {
if (ch == '.') {
if (++dot > 1)
error(ValueError, "multiple decimal points");
}
if (count < BUFSIZE)
number[count++] = ch;
} else { /* check for scientific notation */
if (ch == 'e' || ch == 'E') {
exp = 1;
if (count < BUFSIZE)
number[count++] = ch;
ch = reader.nextch();
if (ch == '-' || ch == '+') {
if (count < BUFSIZE)
number[count++] = ch;
ch = reader.nextch();
}
if (!isdigit(ch))
error(ValueError, "missing exponent");
while (ch != EOF && isdigit(ch)) {
if (count < BUFSIZE)
number[count++] = ch;
ch = reader.nextch();
}
}
number[count] = 0;
reader.pushch(ch);
break;
}
}
if (dot == 1 || exp == 1)
return FLOAT_T;
return INT_T;
}
/* Read a name and check whether it is a keyword or an identifier.
*
* name pointer to buffer with keyword or identifier
* return keyword token (or IDENTIFIER in case of an identifier)
*
* A name consist of digits, letters and underscores, and must start with
* a letter.
*/
static token_t read_identifier(char *name)
{
char ch;
int count = 0, l, h, m, d;
while (1) {
ch = reader.nextch();
if (ch != EOF && (isalnum(ch) || ch == '_')) {
if (count < BUFSIZE)
name[count++] = ch;
} else {
name[count] = 0;
reader.pushch(ch);
break;
}
}
l = 0, h = (int)(sizeof keywordTable / sizeof keywordTable[0]) - 1;
while (l <= h) {
m = (l + h) / 2;
d = strcmp(&name[0], keywordTable[m].keyword);
if (d < 0)
h = m - 1;
if (d > 0)
l = m + 1;
if (d == 0)
break;
};
if (d == 0) {
name[0] = 0;
return keywordTable[m].token;
} else
return IDENTIFIER;
}
/* Read a character constant. This can be a single letter or an escape sequence.
*
* c pointer to buffer with the character read
* return objecttype which was read (by definition CHAR_T)
*
* A character constant is surrounded by single quotes.
* Examples: 'a' '\n'
*/
static token_t read_character(char *c)
{
char ch;
ch = reader.nextch();
if (ch == '\\') { /* is an escape sequence */
ch = reader.nextch();
switch (ch) {
case '0' : c[0] = '\0'; break;
case 'a' : c[0] = '\a'; break;
case 'b' : c[0] = '\b'; break;
case 'f' : c[0] = '\f'; break;
case 'n' : c[0] = '\n'; break;
case 'r' : c[0] = '\r'; break;
case 't' : c[0] = '\t'; break;
case 'v' : c[0] = '\v'; break;
case '\\': c[0] = '\\'; break;
case '\'': c[0] = '\''; break;
case '\"': c[0] = '\"'; break;
default : error(SyntaxError, "unknown escape sequence: %c", ch);
}
} else { /* not an escape sequence */
if (ch == '\'' || ch == EOF)
error(SyntaxError, "empty character constant");
else
c[0] = ch;
}
ch = reader.nextch();
if (ch != '\'')
error(SyntaxError, "to many characters in character constant");
c[1] = 0;
return CHAR_T;
}
/* Token scanner API and data, including the initial settings.
*/
Scanner scanner = {
.token = UNKNOWN,
.peeked = 0,
.at_bol = true,
.string[0] = 0,
.next = next_token,
.peek = peek_token,
.init = scanner_init,
.save = scanner_save,
.jump = scanner_jump
};
|
C
|
//Program to perform selection sort
#include<stdio.h>
#include<stdlib.h>
int size=10;
void insert(int *A);
void display(int *A);
void sort(int *A);
main()
{
int A[size];
insert(A);
printf("\n Your array is \n");
display(A);
sort(A);
printf("\n Your sorted array is \n");
display(A);
}
void insert(int *A)
{
int i;
printf("\n Enter %d elements to the array \n",size);
for(i=0;i<size;i++)
{
scanf("%d",&(*(A+i)));
}
}
void display(int *A)
{
int i;
for(i=0;i<size;i++)
{
printf("%d \n",*(A+i));
}
}
void sort(int *A)
{
int i,j,min,pos;
for(i=0;i<size;i++)
{
min=*(A+i);
pos=i;
for(j=i;j<size;j++)
{
if(*(A+j)<min)
{
min=*(A+j);
pos=j;
}
}
if(pos!=i)
{
*(A+pos)=*(A+i);
*(A+i)=min;
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
void tri_croissant_pouls(Ligne *tab, int const n){
/* Booléen marquant l'arrêt du tri si le tableau est ordonné */
int en_desordre = TRUE;
/* Boucle de répétition du tri et le test qui
arrête le tri dès que le tableau est ordonné(en_desordre=FALSE) */
while (en_desordre)
{
/* Supposons le tableau ordonné */
en_desordre = FALSE;
/* Vérification des éléments des places j et j+1 */
for (int j = 0; j < n-1; j++)
{
/* Si les 2 éléments sont mal triés */
if(tab[j].poul > tab[j+1].poul)
{
/* Inversion des 2 éléments */
int tmp = tab[j+1].poul;
tab[j+1].poul = tab[j].poul;
tab[j].poul = tmp;
/* Le tableau n'est toujours pas trié */
en_desordre = TRUE;
}
}
}
}
void tri_decroissant_pouls(Ligne *tab, int const n){
/* Booléen marquant l'arrêt du tri si le tableau est ordonné */
int en_desordre = TRUE;
/* Boucle de répétition du tri et le test qui
arrête le tri dès que le tableau est ordonné(en_desordre=FALSE) */
while (en_desordre)
{
/* Supposons le tableau ordonné */
en_desordre = FALSE;
/* Vérification des éléments des places j et j+1 */
for (int j = 0; j < n-1; j++)
{
/* Si les 2 éléments sont mal triés */
if(tab[j].poul < tab[j+1].poul)
{
/* Inversion des 2 éléments */
int tmp = tab[j+1].poul;
tab[j+1].poul = tab[j].poul;
tab[j].poul = tmp;
/* Le tableau n'est toujours pas trié */
en_desordre = TRUE;
}
}
}
}
void tri_croissant_temps(Ligne *tab, int const n){
/* Booléen marquant l'arrêt du tri si le tableau est ordonné */
int en_desordre = TRUE;
/* Boucle de répétition du tri et le test qui
arrête le tri dès que le tableau est ordonné(en_desordre=FALSE) */
while (en_desordre)
{
/* Supposons le tableau ordonné */
en_desordre = FALSE;
/* Vérification des éléments des places j et j+1 */
for (int j = 0; j < n-1; j++)
{
/* Si les 2 éléments sont mal triés */
if(tab[j].temp > tab[j+1].temp)
{
/* Inversion des 2 éléments */
int tmp = tab[j+1].temp;
tab[j+1].temp = tab[j].temp;
tab[j].temp = tmp;
/* Le tableau n'est toujours pas trié */
en_desordre = TRUE;
}
}
}
}
void tri_decroissant_temps(Ligne *tab, int const n){
/* Booléen marquant l'arrêt du tri si le tableau est ordonné */
int en_desordre = TRUE;
/* Boucle de répétition du tri et le test qui
arrête le tri dès que le tableau est ordonné(en_desordre=FALSE) */
while (en_desordre)
{
/* Supposons le tableau ordonné */
en_desordre = FALSE;
/* Vérification des éléments des places j et j+1 */
for (int j = 0; j < n-1; j++)
{
/* Si les 2 éléments sont mal triés */
if(tab[j].temp < tab[j+1].temp)
{
/* Inversion des 2 éléments */
int tmp = tab[j+1].temp;
tab[j+1].temp = tab[j].temp;
tab[j].temp = tmp;
/* Le tableau n'est toujours pas trié */
en_desordre = TRUE;
}
}
}
}
int searchmilis(Ligne *tab,int n,int milis,int *tabrep,int nrep) { //Fonction pour recherche miliseconde sequenciel, tab=tableau de structure de donnes, n= taille du tableau, milis=temp a chercher, tabrep=liste vide ou serons ajouter les valeurs ou la recherche a trouver milis, nrep=taille tableau de reponce. renvoie le nombre de resultat trouver
int x=0;
for (int i=0;i<=n;i++) {
if (tab[i].temp==milis) {
if (x>nrep) {
tabrep[x]=i;
x++;
} else {
return -1;
}
}
}
return x-1;
}
int searchpoul(Ligne *tab,int n,int poul,int *tabrep,int nrep) { //Fonction pour recherche poul sequenciel, tab=tableau de structure de donnes, n= taille du tableau, poul=nombre a chercher, tabrep=liste vide ou serons ajouter les valeurs ou la recherche a trouver milis, nrep=taille tableau de reponce. renvoie le nombre de resultat trouver
int x=0;
for (int i=0;i<=n;i++) {
if (tab[i].poul==poul) {
if (x>nrep) {
tabrep[x]=i;
x++;
} else {
return -1;
}
}
}
return x-1;
}
float moyenne(Ligne *tab,int n, int borninf, int bornsup) {//Renvoie la moyenne des éléments du tableau entre la borne infèrieur et supèrieur
if (borninf>=0 && bornsup<=n && borninf<bornsup) {
int somme=0,diviseur=0;
for (int i=0;i<n;i++) {
if (tab[i].temp>=borninf && tab[i].temp<=bornsup) {
somme+=tab[i].poul;
diviseur++;
}
}
if (diviseur>0) {
return somme/diviseur;
} else {
return -1;
}
} else {
return -1;
}
}
void min_max(Ligne *tab, int n, int *min, int *max) {// change la valeur de min et max pour y affecter le minimum et maximum du poul de tableau donnée en entrer
for (int i=0;i<n;i++) {
if (tab[i].poul>*max) {
*max=tab[i].poul;
} else if (tab[i].poul<*min) {
*min=tab[i].poul;
}
}
}
void print_tab(Ligne *tab, int n){//affiche je tableau donnée en entrer
for (size_t i = 0; i < n; i++) {
printf("%d - %d; %d\n",i,tab[i].temp, tab[i].poul );
}
}
|
C
|
/******************************************************************************
*
* Модуль управління кроковими двигунами
*
*****************************************************************************/
#include "stepper.h"
#include <project.h>
#include <math.h>
/******* ВИЗНАЧЕННЯ ГЛОБАЛЬНИХ ЗМІННИХ****************************************/
// залишок кроків котрі потрібно зробити по обох осях
volatile uint32_t xStepsRemaining;
volatile uint16_t xStepsExecuted16;
// виконано кроків по обох осях
volatile uint32_t xStepsExecuted;
volatile uint32_t xStepsExecutedSpiral;
// поточний стан моторів
volatile X_MOTOR_STATE_ENUM Stepper_xMotorState;
/******* ЛОКАЛЬНІ ЗМІННІ *****************************************************/
// масив періодів таймера для плавного розгону крокового двигуна
static uint32_t acceleration[ACCEL_ARRAY_SIZE];
//останній діючий індекс масиву розгону, відповідає максимальній швидкості
static uint32_t accelMaxIndex = 0;
static uint32_t accelHalfSpeedIndex = 0;
static uint32_t spiralRotations;
static uint32_t slopeBeginTarget;
static uint32_t slopeEndTarget;
// змінні для пошуку центра датчика 0-азимуту
static volatile uint32_t attempToFindZero = 0;
static volatile uint32 stepsAfterZero = 0;
static uint32_t accelLimit;
/******* ОБРОБНИКИ ПЕРЕРИВАНЬ ************************************************/
// обробник для руху по осі Х
CY_ISR(isr_1)
{
//Pin_STEP_Write(~Pin_STEP_Read());
Step_Counter_ClearInterrupt(Step_Counter_INTR_MASK_TC);
}
CY_ISR(X_MoveISR)
{
xStepsRemaining--;
if ((xStepsRemaining) == 0)
{
Step_Counter_Stop();
CyDelayUs(5);
Step_Counter_Init();
Stepper_xMotorState = X_MOTOR_READY;
}
// очистити апаратне переривання - розблокувати на наступний раз
// X_Counter_ReadStatusRegister();
if (xStepsRemaining <= accelLimit) // тормозимося
{
Step_Counter_WritePeriod(acceleration[xStepsRemaining-1]);
}
else if (xStepsExecuted <= accelMaxIndex) // розганяємося
{
Step_Counter_WritePeriod(acceleration[xStepsExecuted]);
}
else // повна швидкість
{
Step_Counter_WritePeriod(FULL_SPEED_PERIOD);
}
xStepsExecuted++;
Step_Counter_ClearInterrupt(Step_Counter_INTR_MASK_TC);
}
/******* ІМПЛЕМЕНТАЦІЯ ГЛОБАЛЬНИХ ФУНКЦІЙ ***************************************/
static bool FillAccelerationArray()
{
float T0 = 1.0/LOW_SPEED; // початковий період, сек
float t = 0.0; // біжучий час
float t_imp; // поточний імпульс
accelHalfSpeedIndex = 0;
for (uint32_t i = 0; i < ACCEL_ARRAY_SIZE; i++)
{
t_imp = T0 / (1.0 + T0 * t * ACCELERATION);
t += t_imp;
t_imp *= TIMER_FREQUENCY;
acceleration[i] = t_imp;
accelMaxIndex = i;
// вийти з циклу якщо вже досягнуто ліміту прискорення
if (t > ACCELERATION_TIME) break;
}
return (t > ACCELERATION_TIME); // повертаємо істину якщо масив розгону влізся в память
}
bool Stepper_Init(void)
{
Step_Counter_Init();
X_Interrupt_StartEx(X_MoveISR);
return FillAccelerationArray();
}
void Stepper_MoveX(bool nonBlocking, MOTOR_ENUM motor ,X_DIRECTION_ENUM direction, uint32_t steps)
{
xStepsExecuted = 0;
xStepsRemaining = steps;
Stepper_xMotorState = X_MOTOR_MOVE;
accelLimit = steps/2;
Step_Counter_Enable();
Motor_Control_Reg_Write(motor);
if (accelLimit > accelMaxIndex)
{
accelLimit = accelMaxIndex;
}
Step_Counter_WritePeriod(LOW_SPEED_PERIOD);
Pin_DIR_X_Write(direction);
Pin_DIR_Y_Write(direction);
Step_Counter_Start();
//якщо функція блокуюча - чекаємо поки двигун виконає всі кроки
if (!nonBlocking)
{
while (Stepper_xMotorState < X_MOTOR_READY);
}
}
void Stepper_StopX(void)
{
Step_Counter_Stop();
Stepper_xMotorState = X_MOTOR_READY;
}
|
C
|
#include "message.h"
#include <stdio.h>
void printMessage (Message * message) {
printf ("Message producer id = %i \n", message->producerId);
printf ("Message key = %i \n", message->key);
printf ("Message stop = %i \n", message->stop);
struct tm tm = *localtime(&message->createdAt);
printf("Message created at: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
}
|
C
|
#include "binary_trees.h"
/**
* binary_tree_rotate_right - performs a right-rotation on a binary tree
* @tree: pointer to the root node of the tree to rotate
* Return: A pointer to the new root of the binary tree
*/
binary_tree_t *binary_tree_rotate_right(binary_tree_t *tree)
{
binary_tree_t *root = NULL, *child = NULL, *parent = NULL;
if (!tree || !tree->left)
return (NULL);
root = tree->left;
child = root->right;
parent = tree->parent;
root->right = tree;
tree->left = child;
if (child)
child->parent = tree;
tree->parent = root;
root->parent = parent;
if (parent)
{
if (parent->left != tree)
parent->right = root;
else
parent->left = root;
}
return (root);
}
|
C
|
#include <stdio.h>
int main () {
float valor1, valor2, operacao, resultado;
printf("Digite dois valores: ");
scanf("%f %f", &valor1, &valor2);
printf("Escolha a operao [1. Adio 2. Subtrao 3. Diviso 4. Multiplicao]: ");
scanf("%f", &operacao);
if (operacao==1) {
resultado = valor1 + valor2;
} else if (operacao==2) {
resultado = valor1 - valor2;
} else if (operacao==3) {
resultado = valor1 / valor2;
} else if (operacao==4) {
resultado = valor1 * valor2;
}
printf("O resultado da operao escolhida eh: %f", resultado);
return 0;
}
|
C
|
/*
* Copyright (c) 2017 Paul Mattes.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the names of Paul Mattes nor the names of his contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY PAUL MATTES "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 PAUL MATTES 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.
*/
/*
* Construct a manifest file from a template.
* Roughly Equivalent to the mkmanifest.sh used on Unix.
*
* mkmanifest
* -a 32|64
* -d description
* -e app-name
* -m manifest-template
* -v version-file
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "wincmn.h"
typedef char bool;
#define true 1
#define false 0
/* Keyword substitutions. */
#define SUBST(s) { s, "%" #s "%" }
enum subst {
NAME,
VERSION,
ARCHITECTURE,
DESCRIPTION,
NUM_SUBST
};
static struct {
enum subst subst;
const char *keyword;
char *value;
} substs[] = {
SUBST(NAME),
SUBST(VERSION),
SUBST(ARCHITECTURE),
SUBST(DESCRIPTION)
};
/* Allocate memory. */
void *
Malloc(size_t len)
{
void *r;
r = malloc(len);
if (r == NULL) {
fprintf(stderr, "out of memory\n");
exit(1);
}
return r;
}
/* Free memory. */
void
Free(void *s)
{
free(s);
}
/* Allocate a string. */
static char *
NewString(char *s)
{
return strcpy(Malloc(strlen(s) + 1), s);
}
/* Display usage and exit. */
void
Usage(void)
{
fprintf(stderr, "Usage: mkmanifest -a 32|64 -d description -e app-name -m manifest-template -v version-file\n");
exit(1);
}
/* Parse the version string (3.2ga7) into Windows format (3.2.7.0). */
char *
parse_version(const char *version_string)
{
enum fsm {
BASE,
DIG_A,
DIG_A_DOT,
DIG_B,
KW,
DIG_C
} state = BASE;
unsigned char c;
char out[256];
char *outp = out;
# define STORE(c) { \
if (outp - out >= sizeof(out)) { \
return NULL; \
} \
*outp++ = c; \
}
while ((c = *version_string++)) {
switch (state) {
case BASE:
if (isdigit(c)) {
STORE(c);
state = DIG_A;
} else {
return NULL;
}
break;
case DIG_A:
if (isdigit(c)) {
STORE(c);
} else if (c == '.') {
STORE(c);
state = DIG_A_DOT;
} else {
return NULL;
}
break;
case DIG_A_DOT:
if (isdigit(c)) {
STORE(c);
state = DIG_B;
} else {
return NULL;
}
break;
case DIG_B:
if (isdigit(c)) {
STORE(c);
} else {
state = KW;
}
break;
case KW:
if (isdigit(c)) {
STORE('.');
STORE(c);
state = DIG_C;
}
break;
case DIG_C:
if (isdigit(c)) {
STORE(c);
} else {
return NULL;
}
break;
}
}
if (state != DIG_C) {
return NULL;
}
STORE('.');
STORE('0');
STORE('\0');
return NewString(out);
}
int
main(int argc, char *argv[])
{
bool ia64 = false;
FILE *f;
char buf[1024];
char *version = NULL;
char *manifest = NULL;
char *arch = NULL;
char *version_string = NULL;
char *manifest_version = NULL;
char *appname = NULL;
char *description = NULL;
int i, j, k;
/* Check the command line. */
for (i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-e")) {
if (i + 1 >= argc) {
Usage();
}
appname = argv[++i];
} else if (!strcmp(argv[i], "-v")) {
if (i + 1 >= argc) {
Usage();
}
version = argv[++i];
} else if (!strcmp(argv[i], "-d")) {
if (i + 1 >= argc) {
Usage();
}
description = argv[++i];
} else if (!strcmp(argv[i], "-a")) {
if (i + 1 >= argc) {
Usage();
}
arch = argv[++i];
if (!strcmp(arch, "32") || !strcmp(arch, "Win32")) {
ia64 = false;
} else if (!strcmp(arch, "64") || !strcmp(arch, "x64")) {
ia64 = true;
} else {
Usage();
}
} else if (!strcmp(argv[i], "-m")) {
if (i + 1 >= argc) {
Usage();
}
manifest = argv[++i];
} else {
Usage();
}
}
if (appname == NULL || description == NULL || manifest == NULL
|| arch == NULL || version == NULL) {
Usage();
}
/* Read up version.txt. */
f = fopen(version, "r");
if (f == NULL) {
perror(version);
return 1;
}
while (fgets(buf, sizeof(buf), f) != NULL) {
if (!strncmp(buf, "version=\"", 9)) {
char *q;
version_string = NewString(buf + 9);
q = strchr(version_string, '"');
if (q == NULL) {
fprintf(stderr, "syntax error in %s\n", version);
return 1;
}
*q = '\0';
}
}
fclose(f);
if (version_string == NULL) {
fprintf(stderr, "missing version= in %s\n", version);
return 1;
}
/* Translate the version. */
manifest_version = parse_version(version_string);
if (manifest_version == NULL) {
fprintf(stderr, "Syntax error in version '%s'\n", version_string);
return 1;
}
/* Populate the subsitutions. */
substs[NAME].value = appname;
substs[VERSION].value = manifest_version;
substs[ARCHITECTURE].value = ia64? "ia64": "x86";
substs[DESCRIPTION].value = description;
/* Check the substitutions. */
for (j = 0; j < NUM_SUBST; j++) {
for (k = 0; k < NUM_SUBST; k++) {
if (strstr(substs[k].value, substs[j].keyword) != NULL) {
fprintf(stderr, "Substitution '%s' contains keyword '%s'\n",
substs[k].value, substs[j].keyword);
return 1;
}
}
}
/* Parse and substitute. */
f = fopen(manifest, "r");
if (f == NULL) {
perror(manifest);
return 1;
}
while (fgets(buf, sizeof(buf), f) != NULL) {
int i;
char *xbuf = NewString(buf);
for (i = 0; i < NUM_SUBST; i++) {
char *s;
while ((s = strstr(xbuf, substs[i].keyword)) != NULL) {
size_t left_len = s - xbuf;
char *middle_string = substs[i].value;
size_t middle_len = strlen(middle_string);
char *right_string = s + strlen(substs[i].keyword);
size_t right_len = strlen(right_string);
size_t bufsize = left_len + middle_len + right_len + 1;
char *ybuf = Malloc(bufsize);
sprintf(ybuf, "%.*s%s%s",
(int)left_len, xbuf,
middle_string,
right_string);
Free(xbuf);
xbuf = ybuf;
}
}
write(1, xbuf, (int)strlen(xbuf));
Free(xbuf);
}
fclose(f);
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
struct employee
{
int id;
char name[20];
}e1;
int main()
{
e1.id=123;
strcpy(e1.name,"rahul");
printf("%d\n%s",e1.id,e1.name);
return 0;
}
|
C
|
// Author: i0gan
// Github: https://github.com/i0gan/pwn_waf
// Pwn Waf for AWD CTF
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main(void) {
setbuf(stdin, NULL);
setbuf(stdout, NULL);
char buf[128];
puts("Test puts:");
#define show_str "Test write\x00\x01\x02\x03\xff\n"
write(1, show_str, sizeof(show_str) - 1);
puts("Test read:");
read(0, buf, 128);
puts("Test gets:\n");
gets(buf);
puts("Test get shell:\n");
//system("/bin/sh");
execve("/bin/sh", NULL, NULL);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char str[101];
scanf("%s",&str);
int hashtable[200]={0};
for(int i=0, n=strlen(str);i<n;i++)
{
hashtable[str[i]]++;
}
int res=0;
for(int i=0;i<200;i++)
{
if(hashtable[i]!=0) res++;
}
if(res%2==0) printf("CHAT WITH HER!");
else printf("IGNORE HIM!");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <lib.h>
char getgroup(int pid)
{
message m;
m.m1_i1 = pid;
return _syscall(MM, GETSCHEDGROUP, &m);
}
void setgroup(int pid, char group)
{
message m;
m.m1_i1 = pid;
m.m1_i2 = group;
_syscall(MM, SETSCHEDGROUP, &m);
}
int main(int argc, char* argv[])
{
pid_t pid = getpid();
char group;
if (argc != 2)
{
printf("Usage: %s <sched group:A/B/C\n", argv[0]);
return 0;
}
group = getgroup(pid);
printf("> Process pid=%d (this) is of group '%c'\n", pid, group);
group = argv[1];
if (group <'A' || group > 'C')
{
printf("Usage: %s <sched group:A/B/C\n");
return 0;
}
setgroup(pid, group);
group = getgroup(pid);
printf("> Process pid=%d (this) is now of group '%c'\n", pid, group);
while (1){};
return 0;
}
|
C
|
#include <builtins.h>
#include <string.h>
void builtin_exit(t_env *env)
{
int ret;
if (env->argc <= 1)
ret = 0;
else
ret = atoi(env->argv[1]);
free(env);
exit(ret);
}
|
C
|
typedef unsigned long u32;
typedef signed long s32;
typedef unsigned short u16;
typedef signed short s16;
typedef unsigned char u8;
typedef signed char s8;
#define GPM4CON (*(volatile u32*)0x110002e0)
#define GPM4DAT (*(volatile u8*)0x110002e4)
#define GPX3CON (*(volatile u32*)0x11000c60)
#define GPX3DAT (*(volatile u8*)0x11000c64)
static inline void led_init(void);
static inline void key_init(void);
static inline void led_on(u8 led_stat);
static inline u8 key_stat(void);
void _start(void)
{
led_init();
key_init();
while (1) {
led_on(~key_stat());
}
}
static inline void led_init(void)
{
//将GPM4_0-3这4个管脚设为output
GPM4CON = (GPM4CON & ~0xffff) | 0x1111;
}
static inline void key_init(void)
{
//将GPX3_2-5设为输入
GPX3CON &= ~(0xffff << 8);
}
//4个led灯的状态,0亮灯,1灭灯
static inline void led_on(u8 led_stat)
{
//GPM4_0-3
GPM4DAT = (GPM4DAT & ~0xf) | (led_stat & 0xf);
}
//4个按键的状态,0按下,1抬起
static inline u8 key_stat(void)
{
//GPX3_2-5
return (GPX3DAT >> 2) & 0xf;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#define NUM_THREADS 10
int cntA;
int cntB;
int cntC;
pthread_mutex_t mutaA;
pthread_mutex_t mutaB;
pthread_mutex_t mutaC;
pthread_t threads[NUM_THREADS];
int array[100*NUM_THREADS];
void *init(void *arg) {
int idx = (*(int *) arg);
int offset = idx * 100;
int i;
for (i = 0; i < 100; i++) {
array[i+offset] = rand() % 3;
}
pthread_exit(NULL);
}
void *func(void *arg) {
int idx = (*(int *) arg);
int i;
int offset = idx * 100;
for (i = 0; i < 100; i++) {
if (array[i+offset] == 0) {
pthread_mutex_lock(&mutaA);
cntA++;
pthread_mutex_unlock(&mutaA);
} else if (array[i+offset] == 1) {
pthread_mutex_lock(&mutaB);
cntB++;
pthread_mutex_unlock(&mutaB);
} else {
pthread_mutex_lock(&mutaC);
cntC++;
pthread_mutex_unlock(&mutaC);
}
}
pthread_exit(NULL);
}
int main() {
// initialize the random array.
srand(time(NULL));
int i;
int rc = 0;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_mutex_init(&mutaA, NULL);
pthread_mutex_init(&mutaB, NULL);
pthread_mutex_init(&mutaC, NULL);
cntA = 0;
cntB = 0;
cntC = 0;
for (i = 0; i < NUM_THREADS; i++) {
rc = pthread_create(&threads[i], &attr, init, &i);
if (rc) {
printf("pthread_create failes, error code %d\n", rc);
exit(0);
}
}
for (i = 0; i < NUM_THREADS; i++) {
rc = pthread_join(threads[i], NULL);
if (rc) {
printf("pthread_join fails, error code %d\n", rc);
exit(0);
}
}
for (i = 0; i < NUM_THREADS; i++) {
rc = pthread_create(&threads[i], &attr, func, &i);
if (rc) {
printf("pthread_create fails, error code %d\n", rc);
exit(0);
}
}
for (i = 0; i < NUM_THREADS; i++) {
rc = pthread_join(threads[i], NULL);
if (rc) {
printf("pthread_join fails, error code %d\n", rc);
exit(0);
}
}
printf("cntA = %d, cntB = %d, cntC = %d, total = %d\n", cntA, cntB, cntC, cntA + cntB + cntC);
return 0;
}
|
C
|
#ifdef SEM_IMPEMENTATION
#include "sem_implementation/message_queue.h"
#else
#include "cond_implementation/message_queue.h"
#endif
#include "console_app_tools.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define PRODUCERS_COUNT 5
#define CONSUMERS_COUNT 4
#define PRODUCER_PUT_DELAY_SEC 2
#define CONSUMER_GET_DELAY_SEC 4
#define QUEUE_DROP_TIMING_SEC 20
#define MESSAGES_LIMIT 10
pthread_t threads[PRODUCERS_COUNT + CONSUMERS_COUNT];
Message_Queue queue;
int get_thread_id()
{
pthread_t self = pthread_self();
for (int i = 0; i < PRODUCERS_COUNT + CONSUMERS_COUNT; i++)
if (pthread_equal(self, threads[i]))
return i < PRODUCERS_COUNT ? i : i - PRODUCERS_COUNT;
return -1;
}
void *producer_run()
{
int id = get_thread_id();
char message_text[STRING_LEN_LIMIT + 1];
int message_number = 1;
while (1)
{
sprintf(message_text, "Hello from PRODUCER#%d [%d]", id, message_number++);
sleep(PRODUCER_PUT_DELAY_SEC);
if (!message_queue_put(&queue, message_text))
pthread_exit(NULL);
printf("%s[PRODUCER#%d] Put: %s\n", YELLOW_COLOR, id, message_text);
}
}
void *consumer_run()
{
int id = get_thread_id();
char message_text_buf[STRING_LEN_LIMIT + 1];
while (1)
{
sleep(CONSUMER_GET_DELAY_SEC);
if (!message_queue_get(&queue, message_text_buf, STRING_LEN_LIMIT + 1))
pthread_exit(NULL);
else
printf("%s[CONSUMER#%d] Get: %s\n", MAGENTA_COLOR, id, message_text_buf);
}
}
int main()
{
message_queue_init(&queue, MESSAGES_LIMIT);
printf("%s[PARENT] Init\n", PARENT_COLOR);
for (int i = 0; i < PRODUCERS_COUNT; i++)
if (pthread_create(&threads[i], NULL, producer_run, NULL))
throw_and_exit("pthread_create");
for (int i = PRODUCERS_COUNT; i < PRODUCERS_COUNT + CONSUMERS_COUNT; i++)
if (pthread_create(&threads[i], NULL, consumer_run, NULL))
throw_and_exit("pthread_create");
sleep(QUEUE_DROP_TIMING_SEC);
message_queue_drop(&queue);
printf("%s[PARENT] Drop\n", PARENT_COLOR);
for (int i = 0; i < PRODUCERS_COUNT + CONSUMERS_COUNT; i++)
if (pthread_join(threads[i], NULL))
throw_and_exit("pthread_join");
message_queue_destroy(&queue);
printf("%s[PARENT] Destroy\n", PARENT_COLOR);
exit(EXIT_SUCCESS);
}
|
C
|
int main()
{
for (char c[101]; cin.getline(c, 101);)
{
char a[101] = { ' ' };
int len = strlen(c), cnt = 0, left[101] = { 0 };
for (int i = 0; i < len; i++)
{
if (c[i] != '(' && c[i] != ')')
a[i] = ' ';
else
{
if (c[i] == '(')
{
a[i] = '$';
cnt += 1;
left[cnt] = i + 1;
}
else
{
if (cnt<=0)
a[i] = '?';
else
{
a[i] = ' ';
a[left[cnt]-1] = ' ';
left[cnt] = 0;
cnt -= 1;
}
}
}
}
cout << c << endl;
cout << a << endl;
}
return 0;
}
|
C
|
/*!---------------------------------------------------------------------------+
* File : cbpm_rf_bucket.c |
* |
* Description : Returns the CESR RF bucket number for the timing setup and |
* bunch index provided. |
* |
* bunch index argument starts at 1 |
* RF buckets are indexed here starting from 1 |
* If bunch index is out of range for the timing setup found, return -1. |
*-----------------------------------------------------------------------------+*/
#include "cbpm_includes.h"
int cbpm_rf_bucket( int tsetup, int bunch ) {
int retval;
if (bunch < 1) {
retval = -1;
}
// timing setup is 4ns
if (tsetup == s4ns_P_FIX_G ||
tsetup == s4ns_E_FIX_G ||
tsetup == s4ns_P_VAR_G ||
tsetup == s4ns_E_VAR_G ) {
if (bunch > 640) {
retval = -1;
}
retval = bunch * 2;
}
// timing setup is 14ns
if (tsetup == s14ns_VAR_G ||
tsetup == s14ns_FIX_G ) {
if (bunch > 183) {
retval = -1;
}
retval = (((bunch-1)*14) / 2) + 1;
}
return retval;
}
|
C
|
//
// Created by tobiah on 17/10/17.
//
#include <dirent.h>
#include <memory.h>
#include "test_algorithms.h"
#include "../../src/huffman_algorithms/standard_huffman.h"
#include "../../src/huffman_algorithms/adaptive_huffman.h"
#include "../../src/huffman_algorithms/adaptive_sliding_huffman.h"
#include "../../src/huffman_algorithms/two-pass_adaptive_huffman.h"
#include "../../src/huffman_algorithms/blockwise_adaptive_huffman.h"
#define TEMP_FILE_1 "_tmp.out" //could have used tmp file function
#define TEMP_FILE_2 "_tmp2.out"
const static char* TEST_DIR = "../tests/test_files/";
char* test_all_huffman_algorithms() {
//encoder decoder
test(test_standard_huffman);
test(test_adaptive_huffman);
test(test_sliding_window_adaptive_huffman);
test(test_two_pass_huffman);
test(test_blockwise_adaptive_huffman);
//decoder robustness
test(test_decode_robustness_standaard_huffman);
test(test_decode_robustness_adaptive_huffman);
test(test_decode_robustness_sliding_window_huffman);
test(test_decode_robustness_two_pass_huffman);
test(test_decode_robustness_blockwise_huffman);
return NULL;
}
char* test_huffman_algorithm(huffman_function encoder, huffman_function decoder) {
char string_buf[200];
DIR* map = opendir(TEST_DIR);
struct dirent* dp;
while ((dp = readdir(map)) != NULL) {
if (dp->d_type == DT_REG) {
memset(string_buf, 0, 200);
strcat(string_buf, TEST_DIR);
strcat(string_buf, dp->d_name);
FILE* input_stream = fopen(string_buf, "r+");
FILE* output_stream1 = fopen(TEMP_FILE_1, "w+");
FILE* output_stream2 = fopen(TEMP_FILE_2, "w+");
huffman_stream in;
huffman_stream out1;
huffman_stream out2;
huffman_stream_init(input_stream, &in);
huffman_stream_init(output_stream1, &out1);
huffman_stream_init(output_stream2, &out2);
encoder(&in, &out1);
huffman_stream_flush(&out1);
huffman_stream_rewind(&out1);
decoder(&out1, &out2);
huffman_stream_flush(&out2);
huffman_stream_rewind(&out2);
huffman_stream_rewind(&in);
int cmp = cmp_file(input_stream, output_stream2);
assert_true(cmp);
huffman_stream_close(&in);
huffman_stream_close(&out1);
huffman_stream_close(&out2);
fclose(input_stream);
fclose(output_stream1);
fclose(output_stream2);
remove(TEMP_FILE_1);
remove(TEMP_FILE_2);
}
}
closedir(map);
return NULL;
}
char* test_standard_huffman() {
return test_huffman_algorithm(encode_standard_huffman, decode_standard_huffman);
}
char* test_adaptive_huffman() {
return test_huffman_algorithm(encode_adaptive_huffman, decode_adaptive_huffman);
}
char* test_sliding_window_adaptive_huffman() {
return test_huffman_algorithm(encode_adaptive_sliding_huffman, decode_adaptive_sliding_huffman);
}
char* test_two_pass_huffman() {
return test_huffman_algorithm(encode_two_pass_adaptive_huffman, decode_two_pass_adaptive_huffman);
}
char* test_blockwise_adaptive_huffman() {
return test_huffman_algorithm(encode_blockwise_adaptive_huffman, decode_blockwise_adaptive_huffman);
}
char* test_decode_robustness_algorithm(huffman_function decode) {
NULL_CHECK(decode);
char string_buf[200];
DIR* map = opendir(TEST_DIR);
struct dirent* dp;
while ((dp = readdir(map)) != NULL) {
if (dp->d_type == DT_REG) {
memset(string_buf, 0, 200);
strcat(string_buf, TEST_DIR);
strcat(string_buf, dp->d_name);
FILE* input = fopen(string_buf, "r+");
FILE* output = fopen("/dev/null", "w");
huffman_stream in;
huffman_stream out;
huffman_stream_init(input, &in);
huffman_stream_init(output, &out);
//check for errors
if (!setjmp(buf)){
decode(&in, &out);
}else{
//error codes are okay here.
success();
}
//only close the output file (it only flushes the stream)
huffman_stream_close(&out);
fclose(input);
fclose(output);
}
}
closedir(map);
return NULL;
}
char* test_decode_robustness_standaard_huffman() {
return test_decode_robustness_algorithm(decode_standard_huffman);
}
char* test_decode_robustness_adaptive_huffman() {
return test_decode_robustness_algorithm(decode_adaptive_huffman);
}
char* test_decode_robustness_sliding_window_huffman() {
return test_decode_robustness_algorithm(decode_adaptive_sliding_huffman);
}
char* test_decode_robustness_two_pass_huffman() {
return test_decode_robustness_algorithm(decode_two_pass_adaptive_huffman);
}
char* test_decode_robustness_blockwise_huffman() {
return test_decode_robustness_algorithm(decode_blockwise_adaptive_huffman);
}
|
C
|
/**
* ╔═════════════════════════╗
* ║ PARSING LAMBDA CALCULUS ║
* ╚═════════════════════════╝
*
* \author [email protected]
*
* \notes A small library to parse lambda calculus, both into a more
* canonical abstract syntax tree presentation and into the de
* Bruijn-coded abstract syntax trees, reading lambda "source
* code" from a filepointer. Source syntax is as follows:
*
* Variables: Strings of < 16 chars. Legit chars are either
* alpha-numeric or '_'.
* Lambdas: "\x.term" where "x" is a variable and "term"
* is another lambda-expression.
* Applications: "(fun arg)" where "fun" and "arg" are terms.
* The parentheses are mandatory.
*
* Additionally, we extend the lambda-calculus with a define
* macro, with syntax
*
* Define: "@ name = term".
*
* Here `name` is a variable (as above) and `term` is a closed
* term. All top-level declarations should be of this form. The
* string `name` may be used as an alias for `term` in any sub-
* sequent declaration.
*
* The library also includes functions to translate between the
* two abstract syntax tree-encodings, for pretty-printing and
* etc; essentially everything needed for an interpreter or REPL
* except an evaluation/normalization algorithm. The functions
* are written focusing on efficiency but include a modicum of
* error-handling and are memory-safe under most (all?) usage.
*/
/* ***** ***** */
#ifndef LAMBDA_PARSER_H
#define LAMBDA_PARSER_H
/* ***** ***** */
/**********************************************************************/
/* CANONICAL AST TYPE */
/**********************************************************************/
/**
* \brief The obvious encoding of lambda calculus: terms are either
* variables (symbols), lambdas (abstractions) `\variable.term`
* or applications `(term term)`.
*/
struct terms1;
/**
* \brief Frees all nodes (and all heap data at them) of the AST.
*/
void decref_terms1(struct terms1 *t0);
void incref_terms1(struct terms1 *t0);
/**
* \brief Pretty-prints the AST, returning it to lambda source code.
*/
void fprintf_terms1(FILE *out, struct terms1 *t0);
/*********************************************************************/
/* DE BRUIJN AST TYPE */
/*********************************************************************/
/**
* \brief Variables are only natural numbers, lambdas (abstractions)
* are just `\term` and applications are `(term term)`.
*/
struct terms2;
/**
* \brief Frees all nodes (and all heap data at them) of the AST.
*/
void decref_terms2(struct terms2 *t0);
void inccref_terms2(struct terms2 *t0);
/**
* \brief Pretty-prints the AST (in textual de Bruijn form).
*/
void fprintf_terms2(FILE *out, struct terms2 *t0);
/*********************************************************************/
/* NAMES */
/*********************************************************************/
/**
* \brief Stacks backed by dynamical arrays of char-pointers. Used to
* store lambda-bindings of variable names.
*/
struct names;
/**
* \brief Allocates a `names` array that can store `cap` variables
* without having to resize.
*/
struct names *alloc_names(size_t cap);
/**
* \brief Frees `xs` and all variables stored in it.
*/
void free_names(struct names *xs);
/**
* \brief Gets the de Bruijn index of the variable `x` with respect
* to the context `xs`: this is just the depth of `x` in the
* stack `xs` -- if `x` is unbound we return `-1`.
*/
int get_dbidx(char *x, struct names *xs);
/**********************************************************************/
/* TRANSLATING TO/FROM DE BRUIJN ENCODING */
/**********************************************************************/
/**
* \brief Typically called with an empty stack `xs` of names, in case
* it stores all the lambda-bound variables of the term in `xs`
* after it returns. Frees neither argument.
*/
struct terms2 *lam2db(struct terms1 *t, struct names *xs);
/**
* \brief Convenience wrapper of `lam2db`, allocating an empty stack
* of bound variable names which it frees before returning.
*/
struct terms2 *lam2db_nonames(struct terms1 *t);
/**
* \brief Replaces de Bruijn indexes by named variables, using the
* given stack of names as a dictionary, and translates all
* lambdas and applications accordingly. Note that it reverses
* the stack of names.
*/
struct terms1 *db2lam(struct terms2 *t, struct names *xs);
/*********************************************************************/
/* PARSING LAMBDA-TERMS */
/*********************************************************************/
/**
* \brief Parses a closed term from input. Returns `NULL` in case of
* failure.
*/
struct terms1 *parse_terms1(FILE *inp);
/**
* \brief Like `parse_terms1` but de Bruijn-encodes the term while it
* is parsing. More efficient than first using `parse_terms1`
* and then `lam2db`.
*/
struct terms2 *parse_terms2(FILE *inp, struct names *xs);
/**
* \brief Convenience wrapper. Note that in order to, e.g., pretty
* print results we need to keep the `names` around (in order
* to be able to translate back from the de Bruijn encoding)
* which this function doesn't.
*/
struct terms2 *parse_terms2_nonames(FILE *inp);
/*********************************************************************/
/* PARSING DECLARATIVE LAMBDA-TERMS */
/*********************************************************************/
/**
* \brief Struct for storing bindings between variable names and
* canonically encoded lambda-terms.
*/
struct contexts1;
struct contexts1 *alloc_contexts1(size_t cap);
void free_contexts1(struct contexts1 *ctx);
struct contexts2;
struct contexts2 *alloc_contexts2(size_t cap);
void free_contexts2(struct contexts2 *ctx);
/**
* \brief Parses one declared closed term from input. Returns `NULL`
* in case of failure.
*/
struct terms1 *parse_declterms1(FILE *inp, struct contexts1 *ctx);
struct terms2 *parse_declterms2(FILE *inp, struct names *xs
, struct contexts2 *ctx);
/* ***** ***** */
#endif // LAMBDA_PARSER_H
|
C
|
#pragma once
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "common.h"
typedef struct list ioopm_list_t; /// Meta: struct definition goes in C file
typedef struct list_node ioopm_list_node_t;
typedef bool (*ioopm_list_predicate)(cmp_func_t cmp_func, elem_t value, void *extra);
typedef void (*action_func_t)(elem_t element, void *data);
/// @brief Creates a new empty list
/// @param cmp_func function to compare values. Can not be NULL
/// @return an empty linked list
ioopm_list_t *ioopm_linked_list_create(cmp_func_t cmp_func);
/// @brief Tear down the linked list and return all its memory (but not the memory of the elements)
/// @param list the list to be destroyed
void ioopm_linked_list_destroy(ioopm_list_t *list);
/// @brief Insert at the end of a linked list in O(1) time
/// @param list the linked list that will be appended
/// @param value the value to be appended
void ioopm_linked_list_append(ioopm_list_t *list, elem_t value);
/// @brief Insert at the front of a linked list in O(1) time
/// @param list the linked list that will be prepended to
/// @param value the value to be prepended
void ioopm_linked_list_prepend(ioopm_list_t *list, elem_t value);
/// @brief Insert an element into a linked list in O(n) time.
/// The valid values of index are [0,n] for a list of n elements,
/// where 0 means before the first element and n means after
/// the last element.
/// @param list the linked list that will be extended
/// @param index the position in the list
/// @param value the value to be inserted
void ioopm_linked_list_insert(ioopm_list_t *list, int index, elem_t value);
/// @brief Remove an element from a linked list in O(n) time.
/// The valid values of index are [0,n-1] for a list of n elements,
/// where 0 means the first element and n-1 means the last element.
/// @param list the linked list
/// @param index the position in the list
/// @return the value removed
elem_t ioopm_linked_list_remove(ioopm_list_t *list, int index);
/// @brief Retrieve an element from a linked list in O(n) time.
/// The valid values of index are [0,n-1] for a list of n elements,
/// where 0 means the first element and n-1 means the last element.
/// @param list the linked list that will be extended
/// @param index the position in the list
/// @return the value at the given position
elem_t ioopm_linked_list_get(ioopm_list_t *list, int index);
/// @brief Test if an element is in the list
/// @param list the linked list
/// @param element the element sought
/// @return true if the element is in the list, else false
bool ioopm_linked_list_contains(ioopm_list_t *list, elem_t element);
/// @brief Lookup the number of elements in the linked list in O(1) time
/// @param list the linked list
/// @return the number of elements in the list
size_t ioopm_linked_list_size(ioopm_list_t *list);
/// @brief Test whether a list is empty or not
/// @param list the linked list
/// @return true if the number of elements int the list is 0, else false
bool ioopm_linked_list_is_empty(ioopm_list_t *list);
/// @brief Remove all elements from a linked list
/// @param list the linked list
void ioopm_linked_list_clear(ioopm_list_t *list);
/// @brief Test if a supplied property holds for all elements in a list.
/// The function returns as soon as the return value can be determined.
/// @param list the linked list
/// @param prop the property to be tested (function pointer)
/// @param extra an additional argument (may be NULL) that will be passed to all internal calls of prop
/// @return true if prop holds for all elements in the list, else false
bool ioopm_linked_list_all(ioopm_list_t *list, ioopm_list_predicate pred, void *extra);
/// @brief Test if a supplied property holds for any element in a list.
/// The function returns as soon as the return value can be determined.
/// @param list the linked list
/// @param prop the property to be tested
/// @param extra an additional argument (may be NULL) that will be passed to all internal calls of prop
/// @return true if prop holds for any elements in the list, else false
bool ioopm_linked_list_any(ioopm_list_t *list, ioopm_list_predicate pred, void *extra);
/// @brief Apply a supplied function to all elements in a list.
/// @param list the linked list
/// @param fun the function to be applied
/// @param extra an additional argument (may be NULL) that will be passed to all internal calls of func
void ioopm_linked_list_apply_to_all(ioopm_list_t *list, action_func_t fun, void *extra);
|
C
|
#include "Data.h"
#include "Main_First.h"
#include "Data_Base.h"
#include "Data_Expand.h"
NODE *FindMidNode(const LINKLIST *pL)
{
/*法一
**首先遍历一遍单链表以确定单链表的长度L.
**然后再次从头结点出发循环L/2次找到单链
**表的中间结点.
**算法复杂度为:O(L+L/2) = O(3L/2).
NODE *p = pL->pNext;
size_t i = 1;
size_t length = ListLength(pL);
while (p && i<(leng+1)/2)
{
p = p->pNext;
++i;
}
return p;
*/
/*法二(推荐)
**利用快慢指针
*/
NODE *mid = (NODE *)pL;/*必须转换, const类型不能赋值给非const类型, 反之却可以.*/
NODE *p = (NODE *)pL;
while(p && p->pNext) /*p和p->pNext的顺序绝对不能调换!!!*/
{
mid = mid->pNext;
p = p->pNext->pNext;
}
if (p == pL)
{
return NULL;
}
return mid;
}
|
C
|
/*
MIT License
Copyright (c) 2017 Tim Slator
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*---------------------------------------------------------------------------------------------------
* Description
*
* Provides a wrapper for the Cypress USB serial component.
*
*-------------------------------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------------------------------
* Includes
*-------------------------------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdarg.h>
#include "serial.h"
#include "utils.h"
#include "usbif.h"
/*---------------------------------------------------------------------------------------------------
* Constants
*-------------------------------------------------------------------------------------------------*/
static CHAR line_data[MAX_LINE_LENGTH];
static UINT8 char_offset = 0;
/*---------------------------------------------------------------------------------------------------
* Functions
*-------------------------------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------------------------------
* Name: CopyAndTerminateLine
* Description: Copies the accumulated line data into the output variable, captures the line length
* from the character offset, clears the line data, and returns the length.
* Parameters: line - output line data
* Return: line length
*
*-------------------------------------------------------------------------------------------------*/
static UINT8 CopyAndTerminateLine(CHAR* const line)
{
UINT8 length;
length = char_offset;
if (length > 0)
{
memcpy(line, line_data, length);
line[length] = '\0';
}
memset(line_data, 0, MAX_LINE_LENGTH);
char_offset = 0;
return length;
}
/*---------------------------------------------------------------------------------------------------
* Name: SetCharData
* Description: Updates the character data in the line, adjusts the character offset, and echos the
* character is echo is TRUE.
* Parameters: line - output line data
* echo - indicates whether the character should be echoed
* Return: line length
*
*-------------------------------------------------------------------------------------------------*/
static void SetCharData(CHAR ch, BOOL echo)
{
line_data[char_offset] = ch;
char_offset++;
if (echo)
{
Ser_WriteByte(ch);
}
}
/*---------------------------------------------------------------------------------------------------
* Name: Ser_Init
* Description: Initializes the serial module
* Parameters: None
* Return: None
*
*-------------------------------------------------------------------------------------------------*/
void Ser_Init()
{
memset(line_data, 0, MAX_LINE_LENGTH);
char_offset = 0;
}
/*---------------------------------------------------------------------------------------------------
* Name: Ser_Start
* Description: Starts the serial module
* Parameters: None
* Return: None
*
*-------------------------------------------------------------------------------------------------*/
void Ser_Start()
{
USBIF_Start();
}
/*---------------------------------------------------------------------------------------------------
* Name: Ser_PutString
* Description: Sends a string to the serial port
* Parameters: str - the string to be output
* Return: None
*
*-------------------------------------------------------------------------------------------------*/
void Ser_PutString(CHAR const * const str)
{
USBIF_PutString(str);
}
/*---------------------------------------------------------------------------------------------------
* Name: Ser_PutStringFormat
* Description: Sends a string containing format specifiers to the serial port
* Parameters: fmt - the string to be output
* ... - variable argument list
* Return: None
*
*-------------------------------------------------------------------------------------------------*/
void Ser_PutStringFormat(CHAR const * const fmt, ...)
{
CHAR str[MAX_STRING_LENGTH];
va_list ap;
va_start(ap, fmt);
vsnprintf(str, MAX_STRING_LENGTH, fmt, ap);
va_end(ap);
Ser_PutString(str);
}
/*---------------------------------------------------------------------------------------------------
* Name: Ser_ReadData
* Description: Reads one or more bytes (max 64) of data from the USB serial port.
* Parameters: date read from the serial port
* Return: Number of bytes read.
*
*-------------------------------------------------------------------------------------------------*/
UINT8 Ser_ReadData(CHAR* const data)
{
return USBIF_GetAll(data);
}
/*---------------------------------------------------------------------------------------------------
* Name: Ser_ReadByte
* Description: Returns a byte from the serial port.
* Parameters: None
* Return: None
*
*-------------------------------------------------------------------------------------------------*/
UINT8 Ser_ReadByte()
{
return USBIF_GetChar();
}
/*---------------------------------------------------------------------------------------------------
* Name: Ser_ReadLine
* Description: Non-blocking reads all serial data until a newline is received.
* Note: Putty apparently does not send \n so \r is being used.
* Parameters: line - pointer to charater buffer
* echo - echos characters to serial port if TRUE.
* max_length - the maximum length of the line (maximum is 64).
* Return: 0 for newline or carriage return
* -1 for no input
* > 0 for all other
*
*-------------------------------------------------------------------------------------------------*/
INT8 Ser_ReadLine(CHAR* const line, BOOL echo, UINT8 max_length)
{
UINT8 length;
UINT8 line_length;
CHAR ch;
BOOL max_chars_read = FALSE;
length = 0;
line_length = max_length == 0 ? MAX_LINE_LENGTH : min(max_length, MAX_LINE_LENGTH);
line_length--;
max_chars_read = char_offset == line_length;
ch = Ser_ReadByte();
if (ch == 0x00)
{
/* This means there was no input and since this is a polled routine we return -1 length
to indicate that nothing happened.
*/
length = -1;
}
else if (ch == '\n' || ch == '\r' || max_chars_read)
{
length = CopyAndTerminateLine(line);
/* max_chars_read is True if we have read max_length characters.
we will have actually read the next character when this condition
occurs, so we store it before returning so that we don't drop
data.
*/
if (max_chars_read)
{
SetCharData(ch, echo);
}
return length;
}
else
{
SetCharData(ch, echo);
}
return -1;
}
/*---------------------------------------------------------------------------------------------------
* Name: Ser_WriteByte
* Description: Writes a byte to the serial port.
* Parameters: None
* Return: None
*
*-------------------------------------------------------------------------------------------------*/
void Ser_WriteByte(UINT8 value)
{
USBIF_PutChar(value);
}
void Ser_WriteLine(CHAR* const line, BOOL newline)
{
Ser_PutStringFormat("%s%s", line, newline == TRUE? "\r\n" : "");
}
/* [] END OF FILE */
|
C
|
#ifndef _OFFICES_H_
#define _OFFICES_H_
#define ADDRESS_LENGTH 64
#define CITY_LENGTH 32
#define COUNTRY_LENGTH 32
#define POSTAL_CODE_LENGTH 16
typedef enum
{
OFFICE_NOERR,
OFFICE_INVALIDADDRESS,
OFFICE_INVALIDCITY,
OFFICE_INVALIDCOUNTRY,
OFFICE_INVALIDPOSTALCODE
} officeError;
typedef struct sOffice
{
char address[ADDRESS_LENGTH];
char city[CITY_LENGTH];
char country[COUNTRY_LENGTH];
char postalCode[POSTAL_CODE_LENGTH];
struct sOffice * nextOffice;
} tOffice;
tOffice * offices_firstOffice;
// Initializes contents of an office struct
void offices_initStruct(tOffice * office);
// Gets the latest stored office.
tOffice * offices_getLastOffice();
// Register a new office
officeError offices_registerNewOffice();
// Display the list of offices
void offices_listOffices();
// Transforms the error value enumerate into a string
char * offices_errMsg(officeError err);
// Verifies the introduced information is valid
officeError offices_checkOffice(tOffice * office);
#endif
|
C
|
#include "shell.h"
/**
* _strcpy - copy an array.
* @dest: destiny
* @src: source
* Return: void.
*/
char *_strcpy(char *dest, char *src)
{
int i, n;
n = 0;
while (src[n] != '\0')
{
n++;
}
for (i = 0; src[i] != '\0'; i++)
dest[i] = src[i];
dest[i++] = '\0';
return (dest);
}
/**
* _strlen - len of char *
* @s: String to know the length
* Return: return 1 more to count the null byte.
*/
int _strlen(char *s)
{
int i;
for (i = 0; s[i] != '\0'; i++)
;
return (i + 1);
}
/**
* str_replace - replace a str with a second content
* @dest: Destination str
* @src: Source str
* Return: void
*/
void str_replace(char *dest, char *src)
{
int i;
for (i = 0; src[i] != '\0'; i++)
dest[i] = src[i];
dest[i] = '\0';
}
/**
* _strcmp - Compare strings
* Description: This function compare two strings
* @string1: First string to compare
* @string2: Second string to compare
* Return: @n bytes of @src
*/
int _strcmp(char *string1, char *string2)
{
char *s1 = string1;
char *s2 = string2;
while (*s1 != '\0' && *s2 != '\0')
{
if (*s1 > *s2)
return (*s1 - *s2);
else if (*s2 > *s1)
return ((*s2 - *s1) * -1);
s1++;
s2++;
}
return (0);
}
|
C
|
#include "dma.h"
#include "csr_control.h"
#include "sig_utils.h"
#define DMA_NOW (0xffffffff)
void dma_in_set(int start_address, int dma_len) {
// set up input buffer to receive INPUT_BUF_START size
CSR_WRITE(DMA_0_START_ADDR, start_address);
CSR_WRITE(DMA_0_LENGTH, dma_len);
CSR_WRITE(DMA_0_TIMER_VAL, DMA_NOW); // start right away
CSR_WRITE_ZERO(DMA_0_PUSH_SCHEDULE);
}
void dma_out_set(int start_address, int dma_len) {
// set up input buffer to receive INPUT_BUF_START size
CSR_WRITE(DMA_1_START_ADDR, start_address);
CSR_WRITE(DMA_1_LENGTH, dma_len);
CSR_WRITE(DMA_1_TIMER_VAL, DMA_NOW); // start right away
CSR_WRITE_ZERO(SLICER);
CSR_WRITE_ZERO(DMA_1_PUSH_SCHEDULE);
}
int dma_in_check(int timeout){
int helper;
if (timeout == 0){
while(1){
CSR_READ(mip, helper);
// clear because we are reading occupancy now
if(helper & DMA_0_ENABLE_BIT) {
CSR_WRITE_ZERO(DMA_0_INTERRUPT_CLEAR);
return TRUE;
}
}
} else {
for(int i = 1; i <= timeout; i++) {
CSR_READ(mip, helper);
// clear because we are reading occupancy now
if(helper & DMA_0_ENABLE_BIT) {
CSR_WRITE_ZERO(DMA_0_INTERRUPT_CLEAR);
return i;
}
}
return FALSE;
}
}
int dma_out_check(int timeout){
int helper;
if (timeout == 0){ //block forever
while(1) {
CSR_READ(mip, helper);
// clear because we are reading occupancy now
if(helper & DMA_1_ENABLE_BIT) {
CSR_WRITE_ZERO(DMA_1_INTERRUPT_CLEAR);
return TRUE;
}
}
} else {
for(int i = 1; i <= timeout; i++) {
CSR_READ(mip, helper);
// clear because we are reading occupancy now
if(helper & DMA_1_ENABLE_BIT) {
CSR_WRITE_ZERO(DMA_1_INTERRUPT_CLEAR);
return i;
}
}
return FALSE;
}
}
// output dma, same as out,set but will wait first
void dma_block_send(unsigned int dma_ptr, unsigned int word_count) {
unsigned int occupancy;
while(1) {
CSR_READ(DMA_1_SCHEDULE_OCCUPANCY, occupancy);
if( occupancy < DMA_1_SCHEDULE_DEPTH) {
break;
}
}
CSR_WRITE(DMA_1_START_ADDR, dma_ptr);
CSR_WRITE(DMA_1_LENGTH, word_count);
CSR_WRITE(DMA_1_TIMER_VAL, 0xffffffff); // start right away
CSR_WRITE_ZERO(SLICER);
CSR_WRITE_ZERO(DMA_1_PUSH_SCHEDULE);
}
// do not pass limit more than 16
void dma_block_send_limit(const unsigned dma_ptr, const unsigned word_count, const unsigned limit) {
unsigned int occupancy;
while(1) {
CSR_READ(DMA_1_SCHEDULE_OCCUPANCY, occupancy);
if( occupancy < limit) {
break;
}
}
CSR_WRITE(DMA_1_START_ADDR, dma_ptr);
CSR_WRITE(DMA_1_LENGTH, word_count);
CSR_WRITE(DMA_1_TIMER_VAL, 0xffffffff); // start right away
CSR_WRITE_ZERO(SLICER);
CSR_WRITE_ZERO(DMA_1_PUSH_SCHEDULE);
}
// output dma, same as out,set but will wait first
void dma_block_send_finalized(unsigned int dma_ptr, unsigned int word_count, unsigned finalized) {
unsigned int occupancy;
while(1) {
CSR_READ(DMA_1_SCHEDULE_OCCUPANCY, occupancy);
if( occupancy < DMA_1_SCHEDULE_DEPTH) {
break;
}
}
CSR_WRITE(DMA_1_START_ADDR, dma_ptr);
CSR_WRITE(DMA_1_LENGTH, word_count);
CSR_WRITE(DMA_1_TIMER_VAL, 0xffffffff); // start right away
CSR_WRITE_ZERO(SLICER);
if(finalized) {
CSR_WRITE(DMA_1_LAST_RTL, 1);
}
CSR_WRITE_ZERO(DMA_1_PUSH_SCHEDULE);
}
void dma_send_finalized(unsigned int dma_ptr, unsigned int word_count, unsigned finalized) {
CSR_WRITE(DMA_1_START_ADDR, dma_ptr);
CSR_WRITE(DMA_1_LENGTH, word_count);
CSR_WRITE(DMA_1_TIMER_VAL, 0xffffffff); // start right away
CSR_WRITE_ZERO(SLICER);
if(finalized) {
CSR_WRITE(DMA_1_LAST_RTL, 1);
}
CSR_WRITE_ZERO(DMA_1_PUSH_SCHEDULE);
}
void dma_block_send_reverse(unsigned int dma_ptr, unsigned int word_count) {
unsigned int occupancy;
while(1) {
CSR_READ(DMA_1_SCHEDULE_OCCUPANCY, occupancy);
if( occupancy < DMA_1_SCHEDULE_DEPTH) {
break;
}
}
CSR_WRITE(DMA_1_START_ADDR, dma_ptr);
CSR_WRITE(DMA_1_LENGTH, word_count);
CSR_WRITE(DMA_1_TIMER_VAL, 0xffffffff); // start right away
CSR_WRITE_ZERO(SLICER);
CSR_WRITE(DMA_1_REVERSE, 1);
CSR_WRITE_ZERO(DMA_1_PUSH_SCHEDULE);
CSR_WRITE(DMA_1_REVERSE, 0);
}
void dma_block_send_timer(unsigned int dma_ptr, unsigned int word_count, unsigned timer_val) {
unsigned int occupancy;
while(1) {
CSR_READ(DMA_1_SCHEDULE_OCCUPANCY, occupancy);
if( occupancy < DMA_1_SCHEDULE_DEPTH) {
break;
}
}
CSR_WRITE(DMA_1_START_ADDR, dma_ptr);
CSR_WRITE(DMA_1_LENGTH, word_count);
CSR_WRITE(DMA_1_TIMER_VAL, timer_val);
CSR_WRITE_ZERO(SLICER);
CSR_WRITE_ZERO(DMA_1_PUSH_SCHEDULE);
}
// input dma
void dma_block_get(unsigned int dma_ptr, unsigned int word_count) {
unsigned int occupancy;
while(1) {
CSR_READ(DMA_0_SCHEDULE_OCCUPANCY, occupancy);
if( occupancy < DMA_0_SCHEDULE_DEPTH) {
break;
}
}
CSR_WRITE(DMA_0_START_ADDR, dma_ptr);
CSR_WRITE(DMA_0_LENGTH, word_count);
CSR_WRITE(DMA_0_TIMER_VAL, 0xffffffff); // start right away
CSR_WRITE_ZERO(DMA_0_PUSH_SCHEDULE);
}
void dma_run_till_last(void) {
unsigned int occupancy;
while(1) {
CSR_READ(DMA_0_SCHEDULE_OCCUPANCY, occupancy);
if( occupancy < DMA_0_SCHEDULE_DEPTH) {
break;
}
}
CSR_WRITE(DMA_0_LAST_RTL, 0x1);
CSR_WRITE_ZERO(DMA_0_PUSH_SCHEDULE);
}
// WARNING this will reset any in-progress input DMA's you have
// this is best run at the beginning of a FPGA's life
// this fn schedules as many input dma's as possible, over and over
// on the junk memory
// it will always run until the run_time (measured in TIMER_VALUE)
// even if no input dma's come, or they are STILL coming
void flush_input_dma(unsigned int dma_junk, unsigned int junk_len, unsigned int run_time)
{
CSR_WRITE_ZERO(DMA_0_FLUSH_SCHEDULE);
unsigned int then;
unsigned int now;
unsigned int occupancy;
CSR_READ(TIMER_VALUE, then);
do {
CSR_READ(TIMER_VALUE, now);
CSR_READ(DMA_0_SCHEDULE_OCCUPANCY, occupancy);
if( occupancy < DMA_0_SCHEDULE_DEPTH) {
dma_in_set(dma_junk, junk_len);
}
} while(now-then < (run_time) );
CSR_WRITE_ZERO(DMA_0_FLUSH_SCHEDULE);
}
|
C
|
/**
* @brief
* Wrappers for exist functions: deal with erro return ...
*
* @author jervis
* @time 09/06/10 11:11:06
* @version 0.1
*
* Copyright (C) jervis <[email protected]>
*
*/
#include "jlib.h"
/********************************
* Wrappers for Unix I/O routines
********************************/
int Open(const char *pathname, int flags, mode_t mode)
{
int rc;
if ((rc = open(pathname, flags, mode)) < 0)
more_error("Open error");
return rc;
}
ssize_t Read(int fd, void *buf, size_t count)
{
ssize_t rc;
if ((rc = read(fd, buf, count)) < 0)
more_error("Read error");
return rc;
}
ssize_t Write(int fd, const void *buf, size_t count)
{
ssize_t rc;
if ((rc = write(fd, buf, count)) < 0)
more_error("Write error");
return rc;
}
off_t Lseek(int fildes, off_t offset, int whence)
{
off_t rc;
if ((rc = lseek(fildes, offset, whence)) < 0)
more_error("Lseek error");
return rc;
}
void Close(int fd)
{
int rc;
if ((rc = close(fd)) < 0)
more_error("Close error");
}
int Select(int n, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout)
{
int rc;
if ((rc = select(n, readfds, writefds, exceptfds, timeout)) < 0)
more_error("Select error");
return rc;
}
int Dup2(int fd1, int fd2)
{
int rc;
if ((rc = dup2(fd1, fd2)) < 0)
more_error("Dup2 error");
return rc;
}
void Stat(const char *filename, struct stat *buf)
{
if (stat(filename, buf) < 0)
more_error("Stat error");
}
void Fstat(int fd, struct stat *buf)
{
if (fstat(fd, buf) < 0)
more_error("Fstat error");
}
/*********************************************
* Wrappers for Unix process control functions
********************************************/
/* $begin forkwrapper */
pid_t Fork(void)
{
pid_t pid;
if ((pid = fork()) < 0)
more_error("Fork error");
return pid;
}
/* $end forkwrapper */
void Execve(const char *filename, char *const argv[], char *const envp[])
{
if (execve(filename, argv, envp) < 0)
more_error("Execve error");
}
/* $begin wait */
pid_t Wait(int *status)
{
pid_t pid;
if ((pid = wait(status)) < 0)
more_error("Wait error");
return pid;
}
/* $end wait */
pid_t Waitpid(pid_t pid, int *iptr, int options)
{
pid_t retpid;
if ((retpid = waitpid(pid, iptr, options)) < 0)
more_error("Waitpid error");
return(retpid);
}
/* $begin kill */
void Kill(pid_t pid, int signum)
{
int rc;
if ((rc = kill(pid, signum)) < 0)
more_error("Kill error");
}
/* $end kill */
void Pause(void)
{
(void)pause();
return;
}
unsigned int Sleep(unsigned int secs)
{
unsigned int rc;
if ((rc = sleep(secs)) < 0)
more_error("Sleep error");
return rc;
}
unsigned int Alarm(unsigned int seconds) {
return alarm(seconds);
}
void Setpgid(pid_t pid, pid_t pgid) {
int rc;
if ((rc = setpgid(pid, pgid)) < 0)
more_error("Setpgid error");
return;
}
pid_t Getpgrp(void) {
return getpgrp();
}
/************************************
* Wrappers for Unix signal functions
***********************************/
handler_t *Signal(int signum, handler_t *handler)
{
struct sigaction action, old_action;
action.sa_handler = handler;
sigemptyset(&action.sa_mask); /* block sigs of type being handled */
action.sa_flags = 0;
if (signum == SIGALRM) {
#ifdef SA_INTERRUPT
action.sa_flags |= SA_INTERRUPT;
#endif
} else {
#ifdef SA_RESTART
action.sa_flags |= SA_RESTART;
#endif
}
if (sigaction(signum, &action, &old_action) < 0)
more_error("Signal error");
return (old_action.sa_handler);
}
void Sigprocmask(int how, const sigset_t *set, sigset_t *oldset)
{
if (sigprocmask(how, set, oldset) < 0)
more_error("Sigprocmask error");
return;
}
void Sigemptyset(sigset_t *set)
{
if (sigemptyset(set) < 0)
more_error("Sigemptyset error");
return;
}
void Sigfillset(sigset_t *set)
{
if (sigfillset(set) < 0)
more_error("Sigfillset error");
return;
}
void Sigaddset(sigset_t *set, int signum)
{
if (sigaddset(set, signum) < 0)
more_error("Sigaddset error");
return;
}
void Sigdelset(sigset_t *set, int signum)
{
if (sigdelset(set, signum) < 0)
more_error("Sigdelset error");
return;
}
int Sigismember(const sigset_t *set, int signum)
{
int rc;
if ((rc = sigismember(set, signum)) < 0)
more_error("Sigismember error");
return rc;
}
/*******************************
* Wrappers for Posix semaphores
*******************************/
void Sem_init(sem_t *sem, int pshared, unsigned int value)
{
if (sem_init(sem, pshared, value) < 0)
more_error("Sem_init error");
}
void P(sem_t *sem)
{
if (sem_wait(sem) < 0)
more_error("P error");
}
void V(sem_t *sem)
{
if (sem_post(sem) < 0)
more_error("V error");
}
/***************************************
* Wrappers for memory mapping functions
***************************************/
void *Mmap(void *addr, size_t len, int prot, int flags, int fd, off_t offset)
{
void *ptr;
if ((ptr = mmap(addr, len, prot, flags, fd, offset)) == ((void *) -1))
more_error("mmap error");
return(ptr);
}
void Munmap(void *start, size_t length)
{
if (munmap(start, length) < 0)
more_error("munmap error");
}
/****************************
* Sockets interface wrappers
****************************/
int Socket(int domain, int type, int protocol)
{
int rc;
if ((rc = socket(domain, type, protocol)) < 0)
more_error("Socket error");
return rc;
}
void Setsockopt(int s, int level, int optname, const void *optval, int optlen)
{
int rc;
if ((rc = setsockopt(s, level, optname, optval, optlen)) < 0)
more_error("Setsockopt error");
}
void Bind(int sockfd, struct sockaddr *my_addr, int addrlen)
{
int rc;
if ((rc = bind(sockfd, my_addr, addrlen)) < 0)
more_error("Bind error");
}
void Listen(int s, int backlog)
{
int rc;
if ((rc = listen(s, backlog)) < 0)
more_error("Listen error");
}
int Accept(int s, struct sockaddr *addr, socklen_t *addrlen)
{
int rc;
if ((rc = accept(s, addr, addrlen)) < 0)
more_error("Accept error");
return rc;
}
void Connect(int sockfd, struct sockaddr *serv_addr, int addrlen)
{
int rc;
if ((rc = connect(sockfd, serv_addr, addrlen)) < 0)
more_error("Connect error");
}
/************************
* DNS interface wrappers
***********************/
/* $begin gethostbyname */
struct hostent *Gethostbyname(const char *name)
{
struct hostent *p;
if ((p = gethostbyname(name)) == NULL)
more_error("Gethostbyname error");
return p;
}
/* $end gethostbyname */
struct hostent *Gethostbyaddr(const char *addr, int len, int type)
{
struct hostent *p;
if ((p = gethostbyaddr(addr, len, type)) == NULL)
more_error("Gethostbyaddr error");
return p;
}
/***************************************************
a Wrappers for dynamic storage allocation functions
***************************************************/
void *Malloc(size_t size)
{
void *p;
if ((p = malloc(size)) == NULL)
more_error("Malloc error");
return p;
}
void *Realloc(void *ptr, size_t size)
{
void *p;
if ((p = realloc(ptr, size)) == NULL)
more_error("Realloc error");
return p;
}
void *Calloc(size_t nmemb, size_t size)
{
void *p;
if ((p = calloc(nmemb, size)) == NULL)
more_error("Calloc error");
return p;
}
void Free(void *ptr)
{
free(ptr);
}
/******************************************
* Wrappers for the Standard I/O functions.
******************************************/
void Fclose(FILE *fp)
{
if (fclose(fp) != 0)
more_error("Fclose error");
}
FILE *Fdopen(int fd, const char *type)
{
FILE *fp;
if ((fp = fdopen(fd, type)) == NULL)
more_error("Fdopen error");
return fp;
}
char *Fgets(char *ptr, int n, FILE *stream)
{
char *rptr;
if (((rptr = fgets(ptr, n, stream)) == NULL) && ferror(stream))
more_error("Fgets error");
return rptr;
}
FILE *Fopen(const char *filename, const char *mode)
{
FILE *fp;
if ((fp = fopen(filename, mode)) == NULL)
more_error("Fopen error");
return fp;
}
void Fputs(const char *ptr, FILE *stream)
{
if (fputs(ptr, stream) == EOF)
more_error("Fputs error");
}
size_t Fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
size_t n;
if (((n = fread(ptr, size, nmemb, stream)) < nmemb) && ferror(stream))
more_error("Fread error");
return n;
}
void Fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
{
if (fwrite(ptr, size, nmemb, stream) < nmemb)
more_error("Fwrite error");
}
/************************************************
* Wrappers for Pthreads thread control functions
************************************************/
void Pthread_rwlock_destroy(pthread_rwlock_t *rwlock)
{
int rc;
if ((rc = pthread_rwlock_destroy(rwlock)) != 0)
err_exit(rc, "Pthread_rwlock_destroy error");
}
void Pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,
const pthread_rwlockattr_t *restrict attr)
{
int rc;
if ((rc = pthread_rwlock_init(rwlock, attr)) != 0)
err_exit(rc, "Pthread_rwlock_init error");
}
void Pthread_rwlock_rdlock(pthread_rwlock_t *rwlock)
{
int rc;
if ((rc = pthread_rwlock_rdlock(rwlock)) != 0)
err_exit(rc, "Pthread_rwlock_rdlock error");
}
void Pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock)
{
int rc;
if ((rc = pthread_rwlock_tryrdlock(rwlock)) != 0)
err_exit(rc, "Pthread_rwlock_tryrdlock error");
}
void Pthread_rwlock_wrlock(pthread_rwlock_t *rwlock)
{
int rc;
if ((rc = pthread_rwlock_wrlock(rwlock)) != 0)
err_exit(rc, "Pthread_rwlock_rwlock error");
}
void Pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock)
{
int rc;
if ((rc = pthread_rwlock_trywrlock(rwlock)) != 0)
err_exit(rc, "Pthread_rwlock_tryrwlock error");
}
void Pthread_rwlock_unlock(pthread_rwlock_t *rwlock)
{
int rc;
if ((rc = pthread_rwlock_unlock(rwlock)) != 0)
err_exit(rc, "Pthread_rwlock_unlock error");
}
void Pthread_mutex_destroy(pthread_mutex_t *mutex)
{
int rc;
if ((rc = pthread_mutex_destroy(mutex)) != 0)
err_exit(rc, "Pthread_mutex_destroy error");
}
void Pthread_mutex_init(pthread_mutex_t *restrict mutex,
const pthread_mutexattr_t *restrict attr)
{
int rc;
if ((rc = pthread_mutex_init(mutex, attr)) != 0)
err_exit(rc, "Pthread_mutex_init error");
}
void Pthread_mutex_lock(pthread_mutex_t *mutex)
{
int rc;
if ((rc = pthread_mutex_lock(mutex)) != 0)
err_exit(rc, "Pthread_mutex_lock error");
}
void Pthread_mutex_trylock(pthread_mutex_t *mutex)
{
int rc;
if ((rc = pthread_mutex_trylock(mutex)) != 0)
err_exit(rc, "Pthread_mutex_trylock error");
}
void Pthread_mutex_unlock(pthread_mutex_t *mutex)
{
int rc;
if ((rc = pthread_mutex_unlock(mutex)) != 0)
err_exit(rc, "Pthread_mutex_unlock error");
}
void Pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate)
{
int rc;
if ((rc = pthread_attr_setdetachstate(attr, detachstate)) != 0)
err_exit(rc, "Pthread_attr_etdetachstate error");
}
void Pthread_attr_destroy(pthread_attr_t *attr)
{
int rc;
if ((rc = pthread_attr_destroy(attr)) != 0)
err_exit(rc, "Pthread_attr_destory error");
}
void Pthread_attr_init(pthread_attr_t *attr)
{
int rc;
if ((rc = pthread_attr_init(attr)) != 0)
err_exit(rc, "Pthread_attr_init error");
}
void Pthread_create(pthread_t *tidp, pthread_attr_t *attrp,
void * (*routine)(void *), void *argp)
{
int rc;
if ((rc = pthread_create(tidp, attrp, routine, argp)) != 0)
err_exit(rc, "Pthread_create error");
}
void Pthread_cancel(pthread_t tid) {
int rc;
if ((rc = pthread_cancel(tid)) != 0)
err_exit(rc, "Pthread_cancel error");
}
void Pthread_join(pthread_t tid, void **thread_return) {
int rc;
if ((rc = pthread_join(tid, thread_return)) != 0)
err_exit(rc, "Pthread_join error");
}
/* $begin detach */
void Pthread_detach(pthread_t tid) {
int rc;
if ((rc = pthread_detach(tid)) != 0)
err_exit(rc, "Pthread_detach error");
}
/* $end detach */
void Pthread_exit(void *retval) {
pthread_exit(retval);
}
pthread_t Pthread_self(void) {
return pthread_self();
}
void Pthread_once(pthread_once_t *once_control, void (*init_function)()) {
pthread_once(once_control, init_function);
}
/**********************************
* Wrappers for robust I/O routines
**********************************/
ssize_t Rio_readn(int fd, void *ptr, size_t nbytes)
{
ssize_t n;
if ((n = rio_readn(fd, ptr, nbytes)) < 0)
more_error("Rio_readn error");
return n;
}
void Rio_writen(int fd, void *usrbuf, size_t n)
{
if (rio_writen(fd, usrbuf, n) != n)
more_error("Rio_writen error");
}
void Rio_readinitb(rio_t *rp, int fd)
{
rio_readinitb(rp, fd);
}
ssize_t Rio_readnb(rio_t *rp, void *usrbuf, size_t n)
{
ssize_t rc;
if ((rc = rio_readnb(rp, usrbuf, n)) < 0)
more_error("Rio_readnb error");
return rc;
}
ssize_t Rio_readlineb(rio_t *rp, void *usrbuf, size_t maxlen)
{
ssize_t rc;
if ((rc = rio_readlineb(rp, usrbuf, maxlen)) < 0)
more_error("Rio_readlineb error");
return rc;
}
/******************************************
* Wrappers for the client/server helper routines
******************************************/
int Open_clientfd(char *hostname, int port)
{
int rc;
if ((rc = open_clientfd(hostname, port)) < 0) {
if (rc == -1)
more_error("Open_clientfd Unix error");
else
more_error("Open_clientfd DNS error");
}
return rc;
}
int Open_listenfd(int port)
{
int rc;
if ((rc = open_listenfd(port)) < 0)
more_error("Open_listenfd error");
return rc;
}
|
C
|
#include "initialisation.h"
//------------------------------||:FONCTION:||---------------------------------||
void initialisation(Bonhomme **soignant, Bonhomme **lambda, Coordonnees **virus,
int * cpt_lambda, int * cpt_virus, int * cpt_soignant, int nrow, int ncol, Case
emplacement[nrow][ncol], int vie_virus[])
{
//ok donc maintenant que les structures et les listes sont mises en place, y'a plus qu'à.
//1. on initialise une première grille de N par M cases. Il faut faire le tour de chaque case et faire poper les soigneurs, les virus et les civils.
//2. à chaque fois qu'un soigneur ou un civil apparait, il faut l'introduire dans Bonhomme/soigneur ou civil pour l'ajouter aux listes.
//Ne pas oublier d'initialiser chaque bonhomme.
Bonhomme * tempS; //tableaux temporaires pour les realloc
Bonhomme * tempL; //tableau temporaire pour les realloc
Coordonnees * tempV;
//Allocation dynamique pour les tableaux soignants et lambda
*soignant = (Bonhomme*) malloc (*cpt_soignant * sizeof(Bonhomme));
if( *soignant == NULL )
{
fprintf(stderr,"Allocation impossible");
free(*soignant);
exit(EXIT_FAILURE);
}
*lambda = (Bonhomme*) malloc (*cpt_lambda * sizeof(Bonhomme));
if( *lambda == NULL )
{
fprintf(stderr,"Allocation impossible");
free(*lambda);
exit(EXIT_FAILURE);
}
*virus = (Coordonnees*) malloc (*cpt_virus * sizeof(Coordonnees));
if (*virus == NULL)
{
fprintf(stderr,"Allocation impossible");
free(*virus);
exit(EXIT_FAILURE);
}
// INITIALISATION
int i, j;
int nbrAlea;
srand(time(NULL));
for (i = 0; i < N; i++)
{
for (j = 0; j < M; j++)
{
int resultat = probabilite(PROB_V, PROB_L, PROB_S); //si resultat == 4, alors la case reste vide.
if (resultat == 1)
{
//alors présence d'un virus
emplacement[i][j].PV_virus = vie_virus[4];//initialisation du compteur de vie du virus pour cette case
(*virus)[*cpt_virus].y = i;
(*virus)[*cpt_virus].x = j;
*cpt_virus += 1;
//realloc puisqu'on ajoute un élément au tableau virus
tempV = realloc (*virus, (*cpt_virus+1) * sizeof(Coordonnees));
if (tempV == NULL)
{
fprintf(stderr,"Reallocation impossible");
free(*virus);
*virus = NULL;
exit(EXIT_FAILURE);
}
else
{
*virus = tempV;
}
}
else if (resultat == 2)
{
//alors presence d'un lambda
emplacement[i][j].occupee = 1;
emplacement[i][j].lambda_present = (*lambda)[*cpt_lambda];
emplacement[i][j].soignant_present = NULL;
(*lambda)[*cpt_lambda].localisation.y = i;
(*lambda)[*cpt_lambda].localisation.x = j;
attribution_direction(*lambda, *cpt_lambda);
*cpt_lambda += 1;
//realloc puisqu'on ajoute un élément au tableau lambda
tempL = realloc (*lambda, (*cpt_lambda+1) * sizeof(Bonhomme));
if (tempL == NULL)
{
fprintf(stderr,"Reallocation impossible");
free(*lambda);
*lambda = NULL;
exit(EXIT_FAILURE);
}
else
{
*lambda = tempL;
}
}
else if (resultat == 3)
{ //presence d'un soignant
emplacement[i][j].occupee = 1;
emplacement[i][j].soignant_present = (*soignant)[*cpt_soignant];
emplacement[i][j].lambda_present = NULL;
(*soignant)[*cpt_soignant].localisation.y = i;
(*soignant)[*cpt_soignant].localisation.x = j;
(*soignant)[*cpt_soignant].vocation = 1;
attribution_direction(*soignant, *cpt_soignant);
*cpt_soignant += 1;
//realloc puisqu'on ajoute un élément au tableau soignant
tempS = realloc (*soignant, (*cpt_soignant+1) * sizeof(Bonhomme));
if ( tempS == NULL )
{
fprintf(stderr,"Reallocation impossible");
free(*soignant);
*soignant = NULL;
exit(EXIT_FAILURE);
}
else
{
*soignant = tempS;
}
}
//printf("virus : %d, lambda : %d, soignant : %d\n", *cpt_virus, *cpt_lambda, *cpt_soignant);
}
}
printf("1/soigneur x:%d y:%d\n", (*soignant)[0].localisation.x, (*soignant)[0].localisation.y);
printf("2/soigneur x:%d y:%d\n", (*soignant)[1].localisation.x, (*soignant)[1].localisation.y);
printf("3/soigneur x:%d y:%d\n", (*soignant)[2].localisation.x, (*soignant)[2].localisation.y);
printf("2/soigneur x:%d y:%d\n", (*soignant)[10].localisation.x, (*soignant)[10].localisation.y);
printf("1/lambda x:%d y:%d\n", (*lambda)[0].localisation.x, (*lambda)[0].localisation.y);
printf("2/lambda x:%d y:%d\n", (*lambda)[1].localisation.x, (*lambda)[1].localisation.y);
printf("3/lambda x:%d y:%d\n", (*lambda)[2].localisation.x, (*lambda)[2].localisation.y);
printf("2/lambda x:%d y:%d\n", (*lambda)[10].localisation.x, (*lambda)[10].localisation.y);
}
//-------------------------------||:IMPLEMENTATION DES FONCTIONS:||----------------------------------||
void attribution_direction(Bonhomme *entite, int indice) //attribue une direction parmi les 8 possibles
{
int a;
a = pioche(1,8);
entite[indice].direction = a;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.