language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[]) {
char* line1 = NULL;
char* line2 = NULL;
char tok[1024];
char* t;
char* lr1 = NULL;
char* lr2 = NULL;
char* c1 = NULL;
char* c2 = NULL;
FILE* in = fopen(argv[1], "r");
FILE* out = fopen(argv[2], "a");
if (fgets(tok, 1024, in) != NULL) {
line1 = malloc(strlen(tok) + 1);
strncpy(line1, tok, strlen(tok) + 1);
t = strtok(tok, "\t");
lr1 = malloc(strlen(t) + 1);
strncpy(lr1, t, strlen(t) + 1);
t = strtok(NULL, "\t");
c1 = malloc(strlen(t) + 1);
strncpy(c1, t, strlen(t) + 1);
}
while (line1 != NULL) {
free(line2);
line2 = NULL;
if (fgets(tok, 1024, in) != NULL) {
line2 = malloc(strlen(tok) + 1);
strncpy(line2, tok, strlen(tok) + 1);
t = strtok(tok, "\t");
free(lr2);
lr2 = malloc(strlen(t) + 1);
strncpy(lr2, t, strlen(t) + 1);
t = strtok(NULL, "\t");
free(c2);
c2 = malloc(strlen(t) + 1);
strncpy(c2, t, strlen(t) + 1);
//~ if (strcmp(lr1, lr2) == 0 && strcmp(c1, c2) != 0) {
if (strcmp(lr1, lr2) == 0) {
fprintf(out, "%s", line1);
}
}
while (line2 != NULL && strcmp(lr1, lr2) == 0) {
//~ if (strcmp(c1, c2) != 0) {
fprintf(out, "%s", line2);
//~ }
//~ printf("LALA : %s ; %s\n", lr1, lr2);
free(line2);
line2 = NULL;
if (fgets(tok, 1024, in) != NULL) {
line2 = malloc(strlen(tok) + 1);
strncpy(line2, tok, strlen(tok) + 1);
t = strtok(tok, "\t");
free(lr2);
lr2 = malloc(strlen(t) + 1);
strncpy(lr2, t, strlen(t) + 1);
free(c1);
c1 = malloc(strlen(c2) + 1);
strncpy(c1, c2, strlen(c2) + 1);
free(c2);
t = strtok(NULL, "\t");
c2 = malloc(strlen(t) + 1);
strncpy(c2, t, strlen(t) + 1);
}
}
free(line1);
line1 = NULL;
if (line2 != NULL) {
line1 = malloc(strlen(line2) + 1);
strncpy(line1, line2, strlen(line2) + 1);
}
free(lr1);
lr1 = malloc(strlen(lr2) + 1);
strncpy(lr1, lr2, strlen(lr2) + 1);
free(c1);
c1 = malloc(strlen(c2) + 1);
strncpy(c1, c2, strlen(c2) + 1);
}
free(line1);
free(line2);
free(lr1);
free(lr2);
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void insertsort(int &array, int elemente) {
int i,j,k,t;
for(i=2;i<=elemente;i++) {
j=i;
t=array[i];
k=t;
|
C
|
#include <stdio.h>
#include <string.h>
int mystrcmp(char *str1, char *str2);
int main() {
int i = 0;
int y, x = 0;
/*
* i is evaluated then incremented
* ex: when i = 9, it will get evaluated and then incremented to 10
* Below prints from 1 to 10
* */
while (i++ < 10) {
printf("\n[Debug] i++ %i", i);
}
i = 0;
/*
* i is incremented then is evaluated!!
* ex: when i = 9, it will incremented to 10 and then evaluated
* Below prints from 1 to 9
* */
while (++i < 10) {
printf("\n[Debug] ++i %i", i);
}
while (x < 10){
printf("\n[Debug] x++ %i", x);
/*
* x is incremented
* x++ or ++x makes no difference
* it only gets incremented and evaluated in the while loop
* */
x++;
}
/*
* Does not matter whether is y++ or ++y it only gets incremented
* Note: y++ < 10 will get evaluated then incremented
* and ++y < 10 will get incremented and then evaluated
* */
for (y = 0; y < 10; y++) {
printf("\n[Debug] y++ %i", y);
}
// comparing strings
char a_str_1[6] = "Hello";
char a_str_2[6] = "Hello";
char *a_str_p1 = &a_str_1[0];
int cmp_result = strcmp(a_str_p1, a_str_2);
printf("\nstr1: {%s}, str2: {%s}, cmp_result: {%i}",a_str_p1, a_str_2, cmp_result);
}
int mystrcmp(char *str1, char *str2) {
if (strlen(str1) != strlen(str2)) {
return 0;
}
while (*str1 == *str2) {
str1++;
str2++;
if (*str1 == '\0') {
break;
}
}
return *str1 == '\0' ? 1 : 0;
}
|
C
|
/*****************************************************
* Copyright 2016 Bumjin Im, Patrick Granahan *
* *
* COMP 421/521 Lab 3 (Yalnix yfs) test code *
* create_close.c *
* *
* Author *
* Bumjin Im ([email protected]) *
* Patrick ([email protected]) *
* *
* Created Apr. 16. 2016. *
*****************************************************/
#include <comp421/iolib.h>
#include <comp421/yalnix.h>
#include <stdio.h>
#define assert(message, test) do { if (!(test)) { Shutdown(); printf(message); return 1; } } while (0)
int main()
{
int fd;
// Simple create
fprintf(stderr, "Simple create\n");
fd = Create("a");
assert("Failed simple create\n", fd == 0);
// Tests all close cases
fprintf(stderr, "Simple open FD close\n");
assert("Expected close on open FD to succeed\n", Close(fd) == 0);
fprintf(stderr, "Simple closed FD close\n");
assert("Expected close on closed FD to fail\n", Close(fd) == ERROR);
// More simple create cases
fprintf(stderr, "Simple create\n");
fd = Create("a");
assert("Failed simple create a\n", fd == 0);
fprintf(stderr, "Simple open FD close\n");
assert("Expected close on open FD to succeed\n", Close(fd) == 0);
fprintf(stderr, "Simple create\n");
fd = Create("b");
assert("Failed simple create b\n", fd == 0);
fprintf(stderr, "Simple open FD close\n");
assert("Expected close on open FD to succeed\n", Close(fd) == 0);
fprintf(stderr, "Simple create\n");
fd = Create("01234567890123456789");
assert("Failed simple create 01234567890123456789\n", fd == 0);
fprintf(stderr, "Simple open FD close\n");
assert("Expected close on open FD to succeed\n", Close(fd) == 0);
fprintf(stderr, "Simple create, but pathname too long\n");
fd = Create("0123456789012345678901234567890");
assert("Failed simple create 0123456789012345678901234567890\n", fd == ERROR);
// Creates on tricky pathnames
fprintf(stderr, "Tricky pathname create\n");
fd = Create("");
assert("Failed tricky pathname create \"\"\n", fd == ERROR);
fprintf(stderr, "Tricky pathname create\n");
fd = Create("/");
assert("Failed tricky pathname create /\n", fd == ERROR);
fprintf(stderr, "Tricky pathname create\n");
fd = Create(".");
assert("Failed tricky pathname create .\n", fd == ERROR);
fprintf(stderr, "Tricky pathname create\n");
fd = Create("..");
assert("Failed tricky pathname create ..\n", fd == ERROR);
fprintf(stderr, "Tricky pathname create\n");
fd = Create(NULL);
assert("Failed tricky pathname create NULL\n", fd == ERROR);
// Test Create in conjunction with MkDir
Unlink("/a");
MkDir("/a");
MkDir("/a/b");
fprintf(stderr, "Create in conjunction with directories\n");
fd = Create("/a/b/c");
assert("Create in conjunction with directories\n", fd == 0);
fprintf(stderr, "Simple open FD close\n");
assert("Expected close on open FD to succeed\n", Close(fd) == 0);
fprintf(stderr, "Create in conjunction with directories\n");
fd = Create("/a/b/c/d");
assert("Treated a created file as a directory\n", fd == ERROR);
printf("All tests passed\n");
return Shutdown();
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<json-c/json.h>
#include "json_parser.h"
#include "json_msg.h"
#include "daemonLog.h"
//this function create json_object when you need json_object
struct json_object* json_createObject(void)
{
struct json_object *ret;
ret = json_object_new_object();
if(ret==NULL)
{
//Log record code
//exit
}
return ret;
}
const char* json_object_to_fileInfo(filetype type, char *path,
char *name, int offset, int size)
{
json_object *header, *body;
header = json_object_new_object();
body = json_object_new_object();
json_addObject(body, "filetype", INTEGER, (void*)type);
json_addObject(body, "path", STRING, (void*)path);
json_addObject(body, "name", STRING, (void*)name);
json_addObject(body, "offset", INTEGER, (void*) offset);
json_addObject(body, "size", INTEGER, (void*) size);
json_addObject(header, "header", OBJECT, body);
json_object_serialize(header);
return json_object_to_json_string(header);
}
void json_addObject(struct json_object* obj, const char *key,
jsonType type, void* data)
{
switch(type){
case BOOLEAN:
json_object_object_add(obj, key,
json_object_new_boolean((int)data));
break;
case INTEGER:
json_object_object_add(obj, key,
json_object_new_int((int)data));
break;
case STRING:
json_object_object_add(obj, key,
json_object_new_string((const char *) data));
break;
case OBJECT:
json_object_object_add(obj, key,(struct json_object*)data);
break;
default:
break;
}
}
const char* json_object_toString(struct json_object* obj)
{
return (const char*)json_object_to_json_string(obj);
}
int json_getObjectLength(struct json_object* obj)
{
return json_object_object_length(obj);
}
void json_useObject(struct json_object *obj)
{
json_object_get(obj);
}
void json_unuseObject(struct json_object *obj)
{
json_object_put(obj);
}
void json_object_serialize(struct json_object* obj)
{
json_object_set_serializer(obj, NULL, NULL, NULL);
}
json_bool json_getObject(struct json_object* obj, const char *key,
struct json_object** value)
{
return json_object_object_get_ex(obj, key, value);
}
filecmd* parse_fileCmd(json_object* obj)
{
filecmd *cmd = NULL;
json_object *body, *ret;
cmd = (filecmd*)malloc(sizeof(filecmd));
if(cmd == NULL)
return NULL;
//get filetype
json_object_object_get_ex(obj, "header", &body);
json_object_object_get_ex(body, "filetype", &ret);
cmd->type = (cmd_type)json_object_get_int(ret);
//get filepath
json_object_object_get_ex(body, "path", &ret);
strcpy(cmd->path, json_object_get_string(ret));
json_object_object_get_ex(body, "name", &ret);
strcpy(cmd->name, json_object_get_string(ret));
json_object_object_get_ex(body, "newpath", &ret);
strcpy(cmd->newpath, json_object_get_string(ret));
return cmd;
}
fileinfo* parse_fileTransmit(json_object* obj)
{
fileinfo *info = NULL;
json_object *body, *ret;
info = (fileinfo*)malloc(sizeof(fileinfo));
if(info == NULL)
return NULL;
json_object_object_get_ex(obj, "header", &body);
json_object_object_get_ex(body, "type", &ret);
info->type= (filetype)json_object_get_int(ret);
json_object_object_get_ex(body, "path", &ret);
strcpy(info->path, json_object_get_string(ret));
json_object_object_get_ex(body, "name", &ret);
strcpy(info->name, json_object_get_string(ret));
json_object_object_get_ex(body, "offset", &ret);
info->offset = json_object_get_int(ret);
json_object_object_get_ex(body, "size", &ret);
info->size = json_object_get_int(ret);
return info;
}
|
C
|
//General Library
#include "unity.h"
#include <malloc.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
//STM32F1XX standard Library
#include "stm32f10x_rcc.h"
#include "stm32f10x_spi.h"
#include "stm32f10x_tim.h"
#include "stm32f10x_gpio.h"
//Own Library
#include "Host.h"
#include "Linklist.h"
#include "Registers.h"
#include "peripherals.h"
#include "Timer_setting.h"
#include "projectStruct.h"
#include "CustomAssertion.h"
#include "RelativeTimeLinkList.h"
void setUp(void)
{
HostTim2= malloc((sizeof(TIM_TypeDef)));
}
void tearDown(void)
{
free(HostTim2);
HostTim2 = NULL;
}
/*
Condition: Rate > Intervel2
BaseTime currentTime currentActTime
|| || || Interval1 = CurrentTime - BaseTime;
V V V Interval2 = (currentActTime + actTime1) - Interval1;
|-------------|-------------| NewActTime = Rate - Intervel2;
<--Intervel1-> |-------------|
<--actTime1-->
|---------------------------|<-NewActTime->
<-------Intervel2----------->
|-----------------------------------------|
<------------------rate------------------->
*/
/*
Head-->NULL Head-->10-->NULL
*/
void test_timerListAdd_a_time_element_is_added_into_link_list(void){
printf("No.01 - timerListAdd\n");
Linkedlist *ptr = createLinkedList();
uint16_t arr[] = {10};
setBaseTime(ptr,10);
setCurrentTime(ptr,20);
timerListAdd(ptr,10);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,ptr);
}
/*
rate = 10
|------------|
0 10 0 10 15
|----------| |----------|-------|
<---10----> => <---10----><---5--->
Head-->10-->NULL Head-->10-->5-->NULL
*/
void test_timerListAdd_two_time_element_is_added_into_link_list(void){
printf("No.02 - timerListAdd\n");
Linkedlist *ptr = createLinkedList();
uint16_t arr[] = {10,5};
setBaseTime(ptr,10);
setCurrentTime(ptr,20);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,105);
timerListAdd(ptr,10);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,ptr);
}
/*
rate = 12
|------------------|
0 10 15 0 10 15 20
|----------|-------| |----------|-------|-------|
<---5---> => <---5--><---5--->
Head-->10-->5-->NULL Head-->10-->5-->5->NULL
*/
void test_timerListAdd_three_time_element_is_added_into_link_list(void){
printf("No.03 - timerListAdd\n");
Linkedlist *ptr = createLinkedList();
uint16_t arr[] = {10,5,5};
setBaseTime(ptr,10);
setCurrentTime(ptr,20);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,105);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,108);
timerListAdd(ptr,12);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,ptr);
}
/*
rate = 13
|--------------------|
0 10 15 20 0 10 15 20 22
|----------|-------|-------| |----------|-------|-------|---|
<---5---><---5--> => <---5---><--5--><-2->
Head-->10-->5-->5-->NULL Head-->10-->5-->5-->2->NULL
*/
void test_timerListAdd_four_time_element_is_added_into_link_list(void){
printf("No.04 - timerListAdd\n");
Linkedlist *ptr = createLinkedList();
uint16_t arr[] = {10,5,5,2};
setBaseTime(ptr,10);
setCurrentTime(ptr,20);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,105);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,108);
timerListAdd(ptr,12);
setBaseTime(ptr,100);
setCurrentTime(ptr,109);
timerListAdd(ptr,13);
}
/*
rate = 25
|------------------------|
0 10 15 20 22 0 10 15 20 22 25
|----------|-------|-------|---| |----------|-------|-------|---|-----|
<---5---><--5--><-2-> => <---5---><--5--><-2-><-3-->
Head-->10-->5-->5-->NULL Head-->10-->5-->5-->2->NULL
*/
void test_timerListAdd_five_time_element_is_added_into_link_list(void){
printf("No.05 - timerListAdd\n");
// Linkedlist *ptr = createLinkedList();
// int arr[] = {10,5,5,2,3};
// updateBaseTime(ptr,10);
// setCurrentTime(ptr,20);
// timerListAdd(ptr,10);
// updateBaseTime(ptr,100);
// setCurrentTime(ptr,105);
// timerListAdd(ptr,10);
// updateBaseTime(ptr,100);
// setCurrentTime(ptr,108);
// timerListAdd(ptr,12);
// updateBaseTime(ptr,100);
// setCurrentTime(ptr,109);
// timerListAdd(ptr,13);
// updateBaseTime(ptr,100);
// setCurrentTime(ptr,109);
// timerListAdd(ptr,13);
// updateBaseTime(ptr,100);
// setCurrentTime(ptr,110);
// timerListAdd(ptr,25);
// TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,ptr);
}
/*
Condition: Rate < Intervel2
BaseTime currentTime currentActTime
|| || || Interval1 = CurrentTime - BaseTime;
V V V Interval2 = (currentActTime + actTime1) - Intervel1;
|-------------|-------------|
<--Intervel1-> |-------------|
<--actTime1-->
|---------------------------|
<-------Intervel2----------->
|-------------|
<----rate---->
*/
/*
rate = 10
||
V
|------|<--5-->
0 20 0 20
|----------------| |--------------------|
<-------20------> => <--5--><--10--><--5-->
Head-->20-->NULL Head-->15-->5-->NULL
*/
void test_relative_Time_Link_list_added_a_time_Element_that_rate_smaller_than_Intervel2(void){
printf("No.06 - timerListAdd\n");
Linkedlist *ptr = createLinkedList();
uint16_t arr[] = {15,5};
setBaseTime(ptr,10);
setCurrentTime(ptr,20);
timerListAdd(ptr,20);
setBaseTime(ptr,100);
setCurrentTime(ptr,105);
timerListAdd(ptr,10);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,ptr);
}
/*
rate = 4
|------|
0 10 15 0 10 15
|----------|-------| |----------|-------|
<---5---> => <---8--><--4--><-3->
Head-->10-->5-->NULL Head-->10-->2-->3->NULL
*/
void test_relative_Time_Link_list_added_two_time_Element_and_added_a_timeElement_that_rate_smaller_than_Intervel2(void){
printf("No.07 - timerListAdd\n");
Linkedlist *ptr = createLinkedList();
uint16_t arr[] = {10,2,3};
setBaseTime(ptr,10);
setCurrentTime(ptr,20);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,105);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,108);
timerListAdd(ptr,4);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,ptr);
}
/*
rate = 13
|----------------|
0 10 15 22 0 10 15 18 22
|----------|-------|------| |-----------|-------|---|-------|
=> <--5-->
Head-->10-->5-->7-->NULL Head-->10-->5-->3-->4-->NULL
*/
void test_relative_Time_Link_list_three_time_Element_and_added_a_timeElement_that_rate_smaller_than_Intervel2(void){
printf("No.08 - timerListAdd\n");
Linkedlist *ptr = createLinkedList();
uint16_t arr[] = {10,5,3,4};
setBaseTime(ptr,10);
setCurrentTime(ptr,20);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,105);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,108);
timerListAdd(ptr,14);
setBaseTime(ptr,100);
setCurrentTime(ptr,105);
timerListAdd(ptr,13);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,ptr);
}
/*
rate = 7
|---------|
0 10 15 22 0 10 12 15 22
|----------|-------|------| |-----------|--|-----|-----------|
<---5---> => <--5-->
Head-->10-->5-->7-->NULL Head-->10-->2-->3-->7-->NULL
*/
void test_relative_Time_Link_list_four_time_Element_and_added_a_timeElement_that_rate_smaller_than_Intervel2(void){
printf("No.09 - timerListAdd\n");
Linkedlist *ptr = createLinkedList();
uint16_t arr[] = {10,2,3,7};
setBaseTime(ptr,10);
setCurrentTime(ptr,20);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,105);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,108);
timerListAdd(ptr,14);
setBaseTime(ptr,100);
setCurrentTime(ptr,105);
timerListAdd(ptr,7);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,ptr);
}
/*
Condition: Rate == Intervel2
BaseTime currentTime currentActTime
|| || || Intervel1 = CurrentTime - BaseTime;
V V V Intervel2 = (currentActTime + actTime1) - Intervel1;
|-------------|-------------|
<--Intervel1-> |-------------|
<--actTime1-->
|---------------------------|
<-------Intervel2----------->
|---------------------------|
<-----------rate------------>
*/
/*
rate = 10
|-----------|
0 10 0 10
|----------| |-----------|
=> <----5--->
Head-->10-->NULL Head-->10-->0-->NULL
*/
void test_relative_Time_Link_list_one_time_Element_and_added_a_timeElement_that_period_equal_timeInterval(void){
printf("No.10 - timerListAdd\n");
Linkedlist *ptr = createLinkedList();
uint16_t arr[] = {10,0};
setBaseTime(ptr,10);
setCurrentTime(ptr,20);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,105);
timerListAdd(ptr,5);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,ptr);
}
/*
rate = 7
|----------|
0 10 15 0 10 15
|----------|-------| |-----------|--------|
<---5---> => <----5--->
Head-->10-->5-->NULL Head-->10-->5-->0-->NULL
*/
void test_relative_Time_Link_list_two_time_Element_and_added_a_timeElement_that_period_equal_timeInterval(void){
printf("No.11 - timerListAdd\n");
Linkedlist *ptr = createLinkedList();
uint16_t arr[] = {10,5,0};
setBaseTime(ptr,10);
setCurrentTime(ptr,20);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,105);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,108);
timerListAdd(ptr,7);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,ptr);
}
/*
rate = 14
|-------------------|
0 10 15 22 0 10 15 22
|----------|-------|-------| |-----------|--------|---------|
<---5---> => <----5--->
Head-->10-->5-->8-->NULL Head-->10-->5-->8-->0-->NULL
*/
void test_relative_Time_Link_list_three_time_Element_and_added_a_timeElement_that_period_equal_timeInterval(void){
printf("No.12 - timerListAdd\n");
Linkedlist *ptr = createLinkedList();
uint16_t arr[] = {10,5,7,0};
setBaseTime(ptr,10);
setCurrentTime(ptr,20);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,105);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,108);
timerListAdd(ptr,14);
setBaseTime(ptr,100);
setCurrentTime(ptr,109);
timerListAdd(ptr,13);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,ptr);
}
/*
rate = 6
|------------|
0 10 15 22 0 10 15 22
|----------|-------|-------| |-----------|--------|---------|
<---5---> => <----5--->
Head-->10-->5-->8-->NULL Head-->10-->5-->0-->8-->NULL
*/
void test_relative_Time_Link_list_three_time_Element_and_added_a_timeElement_that_period_equal_timeInterval_within_15(void){
printf("No.13 - timerListAdd\n");
Linkedlist *ptr = createLinkedList();
uint16_t arr[] = {10,5,0,7};
setBaseTime(ptr,10);
setCurrentTime(ptr,20);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,105);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,108);
timerListAdd(ptr,14);
setBaseTime(ptr,100);
setCurrentTime(ptr,109);
timerListAdd(ptr,6);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,ptr);
}
/*
rate = 6
|------------|
0 10 15 22 0 10 15 22
|----------|-------|-------| |------------|--------|---------|
<---5---> => <---5--->
Head-->10-->5-->0-->8-->NULL Head-->10-->5-->0-->0-->8-->NULL
*/
void test_relative_Time_Link_list_the_link_list_contain_two_0_that_period_equal_timeInterval_within_15(void){
printf("No.14 - timerListAdd\n");
Linkedlist *ptr = createLinkedList();
uint16_t arr[] = {10,5,0,0,7};
setBaseTime(ptr,10);
setCurrentTime(ptr,20);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,105);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,108);
timerListAdd(ptr,14);
setBaseTime(ptr,100);
setCurrentTime(ptr,109);
timerListAdd(ptr,6);
setBaseTime(ptr,100);
setCurrentTime(ptr,109);
timerListAdd(ptr,6);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,ptr);
}
/*
rate = 6
|------------|
0 10 15 22 0 10 15 22
|----------|-------|-------| |------------|--------|---------|
<---5---> => <---5--->
Head-->10-->5-->0-->0-->8-->NULL Head-->10-->5-->0-->0-->0-->8-->NULL
*/
void test_relative_Time_Link_list_the_link_list_contain_three_0_that_period_equal_timeInterval_within_15(void){
printf("No.15 - timerListAdd\n");
Linkedlist *ptr = createLinkedList();
uint16_t arr[] = {10,5,0,0,0,7};
setBaseTime(ptr,10);
setCurrentTime(ptr,20);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,105);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,108);
timerListAdd(ptr,14);
setBaseTime(ptr,100);
setCurrentTime(ptr,109);
timerListAdd(ptr,6);
setBaseTime(ptr,100);
setCurrentTime(ptr,109);
timerListAdd(ptr,6);
setBaseTime(ptr,100);
setCurrentTime(ptr,109);
timerListAdd(ptr,6);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,ptr);
}
/*
rate = 6
|------------|
0 10 15 22 0 10 15 22
|----------|-------|-------| |------------|--------|---------|
<---5---> => <---5--->
Head-->10-->5-->0-->0-->0-->7-->NULL Head-->10-->5-->0-->0-->0-->0-->7-->NULL
*/
void test_relative_Time_Link_list_the_link_list_contain_four_0_that_period_equal_timeInterval_within_15(void){
printf("No.16 - timerListAdd\n");
Linkedlist *ptr = createLinkedList();
ListElement* store1;
ListElement* store2;
uint16_t arr[] = {10,5,0,0,0,0,7};
setBaseTime(ptr,10);
setCurrentTime(ptr,20);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,105);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,108);
timerListAdd(ptr,14);
setBaseTime(ptr,100);
setCurrentTime(ptr,109);
timerListAdd(ptr,6);
store1 = ptr->head->next->next;
setBaseTime(ptr,100);
setCurrentTime(ptr,109);
timerListAdd(ptr,6);
store2 = ptr->head->next->next;
TEST_ASSERT_EQUAL_PTR(store1,store2);
store1 = ptr->head->next->next->next;
setBaseTime(ptr,100);
setCurrentTime(ptr,109);
timerListAdd(ptr,6);
store2 = ptr->head->next->next->next;
TEST_ASSERT_EQUAL_PTR(store1,store2);
store1 = ptr->head->next->next->next->next;
setBaseTime(ptr,100);
setCurrentTime(ptr,109);
timerListAdd(ptr,6);
store2 = ptr->head->next->next->next->next;
TEST_ASSERT_EQUAL_PTR(store1,store2);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,ptr);
}
/*
rate = 14
|-----------------------|
0 10 15 22 0 10 15 22
|----------|-------|-------| |------------|--------|---------|
<---5---> => <---5--->
Head-->10-->5-->7-->0-->NULL Head-->10-->5-->7-->0-->0-->NULL
*/
void test_relative_Time_Link_list_the_link_list_contain_two_0_at_end_that_period_equal_timeInterval_within_15(void){
printf("No.17 - timerListAdd\n");
Linkedlist *ptr = createLinkedList();
uint16_t arr[] = {10,5,7,0,0};
setBaseTime(ptr,10);
setCurrentTime(ptr,20);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,105);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,108);
timerListAdd(ptr,14);
setBaseTime(ptr,100);
setCurrentTime(ptr,108);
timerListAdd(ptr,14);
ListElement* store1 = ptr->head->next->next->next;
setBaseTime(ptr,100);
setCurrentTime(ptr,108);
timerListAdd(ptr,14);
ListElement* store2 = ptr->head->next->next->next;
TEST_ASSERT_EQUAL_PTR(store1,store2);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,ptr);
}
/*
rate = 13
|----------------|
0 10 15 22 0 10 15 22
|----------|-------|-------| |------------|--------|---------|
<---5---> => <---5--->
Head-->10-->5-->0-->8-->NULL Head-->10-->5-->0-->3-->4-->NULL
*/
void test_relative_Time_Link_list_contain_a_0_and_added_a_timeElement_that_rate_smaller_than_Intervel2(void){
printf("No.18 - timerListAdd\n");
Linkedlist *ptr = createLinkedList();
uint16_t arr[] = {10,5,0,3,4,9};
setBaseTime(ptr,10);
setCurrentTime(ptr,20);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,105);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,105);
timerListAdd(ptr,10);
setBaseTime(ptr,100);
setCurrentTime(ptr,108);
timerListAdd(ptr,14);
setBaseTime(ptr,100);
setCurrentTime(ptr,105);
timerListAdd(ptr,13);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,ptr);
}
/*
0 0 10
| |-----------|
=>
Head-->0-->NULL Head-->0-->10-->NULL
*/
void test_relative_Time_Link_list_initial_the_first_Node_contain_0_and_add_a_new_node(void){
printf("No.19 - timerListAdd\n");
Linkedlist *ptr = createLinkedList();
uint16_t arr[] = {0,10};
// setBaseTime(ptr,10);
// setCurrentTime(ptr,20);
// timerListAdd(ptr,0);
// setBaseTime(ptr,100);
// setCurrentTime(ptr,108);
// timerListAdd(ptr,10);
// TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,ptr);
}
void test_new_timerListAdd_(void){
printf("No.21 - initialization root\n");
root = createLinkedList();
TEST_ASSERT_NULL(root->head);
TEST_ASSERT_EQUAL(0,root->curTime);
TEST_ASSERT_EQUAL(0,root->baseTime);
}
void test_updateActionTime_initialy_the_actionTime_of_motor_is_0_that_change_to_9_and_20(void){
printf("No.22 - updateActionTime\n");
ListElement *motor1 = createLinkedElement(0);
updateActionTime(motor1,9);
TEST_ASSERT_EQUAL(9,motor1->actionTime);
updateActionTime(motor1,20);
TEST_ASSERT_EQUAL(20,motor1->actionTime);
}
//*******************timerQueue*************************
// Condition: (period > timeInterval)
/*
rate = 14
|------------------------|
0 10 15 0 10 15 22
|----------|-------| |---------------|--------|--------|
<---5---> => <----5--->
Head-->10-->5-->NULL Head-->10-->5-->7-->NULL
*/
void test_timerQueue_create_three_TimerElement_that_added_to_relative_time_link_list_10_5_7(void){
printf("No.23 - timerQueue\n");
root = createLinkedList();
ListElement *motor1 = createLinkedElement(0);
ListElement *motor2 = createLinkedElement(0);
ListElement *motor3 = createLinkedElement(0);
uint16_t arr[] = {10,5,7};
setBaseTime(root,10);
setCurrentTime(root,20);
timerQueue(motor1,10);
TEST_ASSERT_EQUAL_PTR(root->head,motor1);
TEST_ASSERT_EQUAL_PTR(10,motor1->actionTime);
setBaseTime(root,100);
setCurrentTime(root,105);
timerQueue(motor2,10);
TEST_ASSERT_EQUAL_PTR(root->head->next,motor2);
TEST_ASSERT_EQUAL_PTR(5,motor2->actionTime);
setBaseTime(root,100);
setCurrentTime(root,108);
timerQueue(motor3,14);
TEST_ASSERT_EQUAL_PTR(root->head,motor1);
TEST_ASSERT_EQUAL_PTR(root->head->next,motor2);
TEST_ASSERT_EQUAL_PTR(root->head->next->next,motor3);
TEST_ASSERT_EQUAL(10,motor1->actionTime);
TEST_ASSERT_EQUAL(5,motor2->actionTime);
TEST_ASSERT_EQUAL(7,motor3->actionTime);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,root);
}
/* Condition: (period < timeInterval)
rate = 8
|----------|
0 10 15 0 10 15
|----------|-------| |---------------|--------|
<---5---> => <----5--->
Head-->10-->5-->NULL Head-->10-->3-->2-->NULL
*/
void test_timerQueue_create_three_TimerElement_that_to_relative_time_link_list_10_3_2(void){
printf("No.24 - timerQueue\n");
root = createLinkedList();
ListElement *motor1 = createLinkedElement(0);
ListElement *motor2 = createLinkedElement(0);
ListElement *motor3 = createLinkedElement(0);
uint16_t arr[] = {10,3,2};
setBaseTime(root,10);
setCurrentTime(root,20);
timerQueue(motor1,10);
TEST_ASSERT_EQUAL_PTR(root->head,motor1);
TEST_ASSERT_EQUAL(10,motor1->actionTime);
setBaseTime(root,100);
setCurrentTime(root,105);
timerQueue(motor2,10);
TEST_ASSERT_EQUAL_PTR(root->head,motor1);
TEST_ASSERT_EQUAL_PTR(root->head->next,motor2);
TEST_ASSERT_EQUAL(5,motor2->actionTime);
setBaseTime(root,100);
setCurrentTime(root,105);
timerQueue(motor3,8);
TEST_ASSERT_EQUAL_PTR(root->head,motor1);
TEST_ASSERT_EQUAL_PTR(root->head->next->next,motor2);
TEST_ASSERT_EQUAL_PTR(root->head->next,motor3);
TEST_ASSERT_EQUAL(10,motor1->actionTime);
TEST_ASSERT_EQUAL(3,motor3->actionTime);
TEST_ASSERT_EQUAL(2,motor2->actionTime);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,root);
}
/* Condition: (period < timeInterval)
rate = 3
|---|
0 10 15 0 10 15
|----------|-------| |---------------|--------|
<---5---> => <----5--->
Head-->10-->5-->NULL Head-->8-->2-->5-->NULL
*/
void test_timerQueue_create_three_TimerElement_that_to_relative_time_link_list_8_2_5(void){
printf("No.25 - timerQueue\n");
root = createLinkedList();
ListElement *motor1 = createLinkedElement(0);
ListElement *motor2 = createLinkedElement(0);
ListElement *motor3 = createLinkedElement(0);
uint16_t arr[] = {8,2,5};
setBaseTime(root,10);
setCurrentTime(root,20);
timerQueue(motor1,10);
TEST_ASSERT_EQUAL_PTR(root->head,motor1);
setBaseTime(root,100);
setCurrentTime(root,105);
timerQueue(motor2,10);
TEST_ASSERT_EQUAL_PTR(root->head->next,motor2);
setBaseTime(root,100);
setCurrentTime(root,105);
timerQueue(motor3,3);
TEST_ASSERT_EQUAL(8,motor3->actionTime);
TEST_ASSERT_EQUAL(2,motor1->actionTime);
TEST_ASSERT_EQUAL(5,motor2->actionTime);
TEST_ASSERT_EQUAL_PTR(root->head,motor3);
TEST_ASSERT_EQUAL_PTR(root->head->next,motor1);
TEST_ASSERT_EQUAL_PTR(root->head->next->next,motor2);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,root);
}
/* Condition: (period < timeInterval)
0 10 0 10
|----------| |---------|
Head-->10-->0-->NULL Head-->1-->9-->0-->NULL
*/
void test_timerQueue_create_three_TimerElement_that_to_relative_time_link_list_1_9_0(void){
printf("No.25.1 - timerQueue\n");
root = createLinkedList();
ListElement *motor1 = createLinkedElement(0);
ListElement *motor2 = createLinkedElement(0);
ListElement *motor3 = createLinkedElement(0);
uint16_t arr[] = {1,9,0};
setBaseTime(root,10);
setCurrentTime(root,20);
timerQueue(motor1,10);
TEST_ASSERT_EQUAL_PTR(root->head,motor1);
setBaseTime(root,100);
setCurrentTime(root,105);
timerQueue(motor2,5);
TEST_ASSERT_EQUAL_PTR(root->head->next,motor2);
setBaseTime(root,100);
setCurrentTime(root,100);
timerQueue(motor3,1);
TEST_ASSERT_EQUAL(1,motor3->actionTime);
TEST_ASSERT_EQUAL(9,motor1->actionTime);
TEST_ASSERT_EQUAL(0,motor2->actionTime);
TEST_ASSERT_EQUAL_PTR(root->head,motor3);
TEST_ASSERT_EQUAL_PTR(root->head->next,motor1);
TEST_ASSERT_EQUAL_PTR(root->head->next->next,motor2);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,root);
}
/* Condition: (period == timeInterval)
rate = 5
|------|
0 10 0 10
|---------------| |---------------|
=> <---5--->
Head-->10 Head-->10-->0-->NULL
*/
void test_timerQueue_create_three_TimerElement_that_to_relative_time_link_list_10_0(void){
printf("No.26 - timerQueue\n");
root = createLinkedList();
ListElement *motor1 = createLinkedElement(0);
ListElement *motor2 = createLinkedElement(0);
ListElement *motor3 = createLinkedElement(0);
uint16_t arr[] = {10,0,5};
setBaseTime(root,10);
setCurrentTime(root,20);
timerQueue(motor1,10);
TEST_ASSERT_EQUAL_PTR(root->head,motor1);
setBaseTime(root,100);
setCurrentTime(root,105);
timerQueue(motor2,5);
TEST_ASSERT_EQUAL(10,motor1->actionTime);
TEST_ASSERT_EQUAL(0,motor2->actionTime);
TEST_ASSERT_EQUAL_PTR(root->head,motor1);
TEST_ASSERT_EQUAL_PTR(root->head->next,motor2);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,root);
}
/* Condition: (period == timeInterval)
rate = 5
|------|
0 10 0 10
|---------------| |---------------|
=> <---5--->
Head-->10->0 Head-->10-->0-->0
*/
void test_timerQueue_create_three_TimerElement_that_to_relative_time_link_list_10_0_0(void){
printf("No.26.0.1 - timerQueue\n");
root = createLinkedList();
ListElement *motor1 = createLinkedElement(0);
ListElement *motor2 = createLinkedElement(0);
ListElement *motor3 = createLinkedElement(0);
uint16_t arr[] = {10,0,0};
setBaseTime(root,10);
setCurrentTime(root,20);
timerQueue(motor1,10);
TEST_ASSERT_EQUAL_PTR(root->head,motor1);
setBaseTime(root,100);
setCurrentTime(root,105);
timerQueue(motor2,5);
setBaseTime(root,100);
setCurrentTime(root,105);
timerQueue(motor3,5);
TEST_ASSERT_EQUAL(10,motor1->actionTime);
TEST_ASSERT_EQUAL(0,motor2->actionTime);
TEST_ASSERT_EQUAL(0,motor3->actionTime);
TEST_ASSERT_EQUAL_PTR(root->head,motor1);
TEST_ASSERT_EQUAL_PTR(root->head->next,motor2);
TEST_ASSERT_EQUAL_PTR(root->head->next->next,motor3);
TEST_ASSERT_EQUAL_PTR(root->head->next->next->next,motor1);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,root);
}
/* Condition: (period > timeInterval)
rate = 10
|---------------|
0 10 15 0 10 15
|----------|-------| |---------------|--------|
<---5---> => <----5--->
Head-->10-->0-->NULL Head-->10-->0-->5-->NULL
*/
void test_timerQueue_create_three_TimerElement_that_to_relative_time_link_list_10_0_5(void){
printf("No.26.1 - timerQueue\n");
root = createLinkedList();
ListElement *motor1 = createLinkedElement(0);
ListElement *motor2 = createLinkedElement(0);
ListElement *motor3 = createLinkedElement(0);
uint16_t arr[] = {10,0,5};
setBaseTime(root,10);
setCurrentTime(root,20);
timerQueue(motor1,10);
TEST_ASSERT_EQUAL_PTR(root->head,motor1);
setBaseTime(root,100);
setCurrentTime(root,105);
timerQueue(motor2,5);
TEST_ASSERT_EQUAL_PTR(root->head->next,motor2);
setBaseTime(root,100);
setCurrentTime(root,105);
timerQueue(motor3,10);
TEST_ASSERT_EQUAL_PTR(root->head,motor1);
TEST_ASSERT_EQUAL_PTR(root->head->next,motor2);
TEST_ASSERT_EQUAL_PTR(root->head->next->next,motor3);
TEST_ASSERT_EQUAL(10,motor1->actionTime);
TEST_ASSERT_EQUAL(0,motor2->actionTime);
TEST_ASSERT_EQUAL(5,motor3->actionTime);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,root);
}
/* Condition: (period == timeInterval)
rate = 7
|----------|
0 10 15 0 10 15
|----------|-------| |-----------|--------|
<---5---> => <----5--->
Head-->10-->5-->NULL Head-->10-->5-->0-->NULL
*/
void test_timerQueue_create_three_TimerElement_that_to_relative_time_link_list_10_5_0(void){
printf("No.27 - timerQueue\n");
root = createLinkedList();
ListElement *motor1 = createLinkedElement(0);
ListElement *motor2 = createLinkedElement(0);
ListElement *motor3 = createLinkedElement(0);
uint16_t arr[] = {10,5,0};
setBaseTime(root,10);
setCurrentTime(root,20);
timerQueue(motor1,10);
TEST_ASSERT_EQUAL_PTR(root->head,motor1);
setBaseTime(root,100);
setCurrentTime(root,105);
timerQueue(motor2,10);
TEST_ASSERT_EQUAL_PTR(root->head->next,motor2);
setBaseTime(root,100);
setCurrentTime(root,106);
timerQueue(motor3,9);
TEST_ASSERT_EQUAL_PTR(root->head,motor1);
TEST_ASSERT_EQUAL_PTR(root->head->next,motor2);
TEST_ASSERT_EQUAL_PTR(root->head->next->next,motor3);
TEST_ASSERT_EQUAL(10,motor1->actionTime);
TEST_ASSERT_EQUAL(5,motor2->actionTime);
TEST_ASSERT_EQUAL(0,motor3->actionTime);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,root);
}
/* Condition: (period < timeInterval)
rate = 5
|-----|
0 10 15 0 10 15
|----------|-------| |-----------|--------|
<---5---> => <--5-->
Head-->10-->5-->NULL Head-->10-->0-->5-->NULL
*/
void test_timerQueue_create_three_TimerElement_that_to_relative_time_link_list_10_0_5_(void){
printf("No.28 - timerQueue\n");
root = createLinkedList();
ListElement *motor1 = createLinkedElement(0);
ListElement *motor2 = createLinkedElement(0);
ListElement *motor3 = createLinkedElement(0);
uint16_t arr[] = {10,0,5};
setBaseTime(root,10);
setCurrentTime(root,20);
timerQueue(motor1,10);
TEST_ASSERT_EQUAL_PTR(root->head,motor1);
setBaseTime(root,100);
setCurrentTime(root,105);
timerQueue(motor2,10);
TEST_ASSERT_EQUAL_PTR(root->head->next,motor2);
setBaseTime(root,100);
setCurrentTime(root,105);
timerQueue(motor3,5);
TEST_ASSERT_EQUAL_PTR(root->head,motor1);
TEST_ASSERT_EQUAL_PTR(root->head->next,motor3);
TEST_ASSERT_EQUAL_PTR(root->head->next->next,motor2);
TEST_ASSERT_EQUAL(0,motor3->actionTime);
TEST_ASSERT_EQUAL(10,motor1->actionTime);
TEST_ASSERT_EQUAL(5,motor2->actionTime);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,root);
}
/* Condition: (period < timeInterval)
rate = 5
|----|
0 10 15 0 10 15
|----------|-------| |-----------|--------|
<---5---> => <--5-->
Head-->10-->0-->5-->NULL Head-->10-->0-->0-->5-->NULL
*/
void test_timerQueue_create_three_TimerElement_that_to_relative_time_link_list_10_0_0_5_(void){
printf("No.29 - timerQueue\n");
root = createLinkedList();
ListElement *motor1 = createLinkedElement(0);
ListElement *motor2 = createLinkedElement(0);
ListElement *motor3 = createLinkedElement(0);
ListElement *motor4 = createLinkedElement(0);
uint16_t arr[] = {10,0,0,5};
setBaseTime(root,10);
setCurrentTime(root,20);
timerQueue(motor1,10);
setBaseTime(root,100);
setCurrentTime(root,105);
timerQueue(motor2,10);
setBaseTime(root,100);
setCurrentTime(root,105);
timerQueue(motor3,5);
setBaseTime(root,100);
setCurrentTime(root,105);
timerQueue(motor4,5);
TEST_ASSERT_EQUAL(10,motor1->actionTime);
TEST_ASSERT_EQUAL(0,motor3->actionTime);
TEST_ASSERT_EQUAL(0,motor4->actionTime);
TEST_ASSERT_EQUAL(5,motor2->actionTime);
TEST_ASSERT_EQUAL_PTR(root->head,motor1);
TEST_ASSERT_EQUAL_PTR(root->head->next,motor3);
TEST_ASSERT_EQUAL_PTR(root->head->next->next,motor4);
TEST_ASSERT_EQUAL_PTR(root->head->next->next->next,motor2);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,root);
}
/* Condition: (period > timeInterval)
|----------|
0 7000 0 5010 1990
|-----------------| |-----------|--------|
=>
Head-->7000 Head-->5010->1990
*/
void test_timerQueue_create_three_TimerElement_that_to_relative_time_link_list_5000_1990(void){
printf("No.29.1 - timerQueue\n");
root = createLinkedList();
ListElement *motor1 = createLinkedElement(0);
ListElement *motor2 = createLinkedElement(0);
uint16_t arr[] = {5010,1990};
setBaseTime(root,0);
setCurrentTime(root,1);
timerQueue(motor1,7000);
setBaseTime(root,100);
setCurrentTime(root,110);
timerQueue(motor2,5000);
TEST_ASSERT_EQUAL_PTR(root->head->next,motor1);
TEST_ASSERT_EQUAL_PTR(root->head,motor2);
TEST_ASSERT_CYCLE_LINK_LIST_WITH_ARR(arr,root);
}
//***************dequeue****************
/*
head head
|| ||
V V
10 => dequeue() => NULL
*/
void test_dequeue_timer_list_link_contain_one_timerElement_using_dequeue_to_remove_first_timerElement(void){
printf("No.30 - dequeue\n");
root = createLinkedList();
ListElement *elem1 = createLinkedElement(0);
ListElement *elem2 = createLinkedElement(0);
ListElement *temp;
setBaseTime(root,10);
setCurrentTime(root,20);
timerQueue(elem1,10);
temp = dequeue(root);
TEST_ASSERT_NULL(root->head);
TEST_ASSERT_EQUAL_PTR(elem1,temp);
}
/*
head head
|| ||
V V
10-->5 => dequeue() => 5
*/
void test_dequeue_timer_list_link_contain_two_timerElement_using_dequeue_to_remove_first_timerElement(void){
printf("No.31 - dequeue\n");
root = createLinkedList();
ListElement *elem1 = createLinkedElement(0);
ListElement *elem2 = createLinkedElement(0);
ListElement *temp;
setBaseTime(root,10);
setCurrentTime(root,20);
timerQueue(elem1,10);
setBaseTime(root,100);
setCurrentTime(root,105);
timerQueue(elem2,5);
temp = dequeue(root);
TEST_ASSERT_EQUAL_PTR(elem2,root->head);
TEST_ASSERT_EQUAL_PTR(elem1,temp);
}
/*
head head
|| ||
V V
10-->5-->7 =>dequeue() => 5-->7
*/
void test_dequeue_timer_list_link_contain_three_timerElement_using_dequeue_to_remove_first_timerElement(void){
printf("No.32 - dequeue\n");
root = createLinkedList();
ListElement *elem1 = createLinkedElement(0);
ListElement *elem2 = createLinkedElement(0);
ListElement *elem3 = createLinkedElement(0);
ListElement *temp;
setBaseTime(root,10);
setCurrentTime(root,20);
timerQueue(elem1,10);
setBaseTime(root,100);
setCurrentTime(root,105);
timerQueue(elem2,5);
setBaseTime(root,100);
setCurrentTime(root,108);
timerQueue(elem3,14);
temp = dequeue(root);
TEST_ASSERT_EQUAL_PTR(elem2,root->head);
TEST_ASSERT_EQUAL_PTR(elem1,temp);
}
//************updateHead****************
void test_updateHead_the_link_list_contain_one_timerElement_the_head_of_root_will_point_to_null(void){
printf("No.33 - updateHead\n");
root = createLinkedList();
ListElement *elem1 = createLinkedElement(0);
setBaseTime(root,10);
setCurrentTime(root,20);
timerQueue(elem1,10);
updateHead(root);
TEST_ASSERT_NULL(root->head);
}
void test_updateHead_the_link_list_contain_twon_timerElement_the_head_of_root_will_point_to_next_element(void){
printf("No.34 - updateHead\n");
root = createLinkedList();
ListElement *elem1 = createLinkedElement(0);
ListElement *elem2 = createLinkedElement(0);
setBaseTime(root,10);
setCurrentTime(root,20);
timerQueue(elem1,10);
setBaseTime(root,100);
setCurrentTime(root,105);
timerQueue(elem2,5);
updateHead(root);
TEST_ASSERT_EQUAL_PTR(elem2,root->head);
}
//************insertTimeElementIntoBack******************
void test_insertTimeElementIntoBack_(void){
root = createLinkedList();
ListElement *elem1 = createLinkedElement(0);
ListElement *elem2 = createLinkedElement(0);
ListElement *elem3 = createLinkedElement(0);
addList(root,elem1);
addList(root,elem2);
insertTimeElementIntoBack(elem2,elem3);
TEST_ASSERT_EQUAL_PTR(root->head,elem1);
TEST_ASSERT_EQUAL_PTR(root->head->next,elem3);
TEST_ASSERT_EQUAL_PTR(root->head->next->next,elem2);
}
//************insertTimeElementIntoFront******************
void test_insertTimeElementIntoFront_(void){
root = createLinkedList();
ListElement *elem1 = createLinkedElement(0);
ListElement *elem2 = createLinkedElement(0);
ListElement *elem3 = createLinkedElement(0);
addList(root,elem1);
addList(root,elem2);
insertTimeElementIntoFront(elem2,elem3);
TEST_ASSERT_EQUAL_PTR(root->head,elem1);
TEST_ASSERT_EQUAL_PTR(root->head->next,elem2);
TEST_ASSERT_EQUAL_PTR(root->head->next->next,elem3);
}
|
C
|
#include <stdio.h>
int linearSearch(int a[],int size,int element)
{
for(int i=0;i<size;i++)
{
if(a[i]==element)
{
return i;
}
}
return -1;
}
int main()
{
int a[6]={1,2,3,4,5,6};
int search;
printf("enter the element to search\t");
scanf("%d",&search);
int size=sizeof(a)/sizeof(int);
int f=linearSearch(a,size,search);
if(f==-1)
{
printf("elemet not found\n");
}
else
{
printf("element is found at index %d",f);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main(){
int *ptr;
ptr=(int*)malloc(10*sizeof(int));
printf("\n7 Table till 10");
for(int i=0;i<10;i++){
ptr[i]=7*(i+1);
printf("\n7 x %d =%d ",i+1,ptr[i]);
}
ptr=realloc(ptr,15*sizeof(int));
printf("\n\n7 Table till 15");
for(int i=0;i<15;i++){
ptr[i]=7*(i+1);
printf("\n7 x %d =%d ",i+1,ptr[i]);
}
return 0;
}
|
C
|
#include<stdlib.h>
#include<string.h>
int main()
{
sigset_t s1,s2;
char buf1[512];
struct sigaction act1,act2;
int ret;
sigemptyset(&s1);
sigaddset(&s1,SIGINT);
sigaddset(&s1,SIGQUIT);
act1.sa_handler = SIG_DFL; //default action to be installed
sigfillset(&act1.sa_mask); // all signals are masked during
// action
act1.sa_flags = 0; // no flags
sigaction(SIGINT,&act1,NULL); // installing the action
// for SIGINT
act1.sa_handler = SIG_DFL; //default action to be installed
sigfillset(&act1.sa_mask); // all signals are masked during
// action
act1.sa_flags = 0; // no flags
sigaction(SIGQUIT,&act1,NULL); // installing the action
// for SIGQUIT
//sigfillset(&s1);
//sigprocmask(SIG_BLOCK,&s1,&s2);
//sigprocmask(SIG_UNBLOCK,&s1,&s2);
//sigprocmask(SIG_SETMASK,&s1,&s2);
//ret = fork();
//if(ret==0) setpgid(0,getpid());
printf("hello world !! in process with pid %d and pgid %d\n",getpid(),getpgid(0));
while(1);
}
|
C
|
#include<stdio.h>
const int WORK_WEEK_MAX_HOURS=40;
const int MAX_NAME=20;
float addOT(float workedHours, float hourly) {
float overtimeHrs, overtimeRate, overtimePaid;
overtimeHrs = workedHours - WORK_WEEK_MAX_HOURS;
overtimeRate = (hourly * 1.5);
overtimePaid = overtimeRate * overtimeHrs;
return overtimePaid;
}
int main() {
char name[MAX_NAME];
float hourly, workedHours, amountPaid, taxesPaid, takeHome, biweekly, monthly, taxes=0.2;
unsigned int i;
for(i=1; i <= 5; i++) {
printf("\nEnter name: ");
scanf("%s", &name[0]);
printf("Enter hourly rate: ");
scanf("%f", &hourly);
printf("Enter hours worked this week: ");
scanf("%f", &workedHours);
printf("\n");
if (workedHours > WORK_WEEK_MAX_HOURS) {
amountPaid = hourly * WORK_WEEK_MAX_HOURS;
amountPaid += addOT(workedHours, hourly);
} else {
amountPaid = hourly * workedHours;
}
taxesPaid = amountPaid * taxes;
takeHome = amountPaid - taxesPaid;
biweekly = takeHome * 2;
monthly = biweekly * 2;
printf("Pay to: %s\n", name);
printf("Hourly Rate: %.2f\n", hourly);
printf("Hours Worked: %.2f\n", workedHours);
printf("Amount Paid: $%.2f\n", amountPaid);
printf("Taxes Paid: $%.2f\n", taxesPaid);
printf("Take Home Weekly: $%.2f\n", takeHome);
printf("Take Home Bi-Weekly: $%.2f\n", biweekly);
printf("Take Home Monthly: $%.2f\n\n", monthly);
}
}
//output:
//-----------------
// Alexs-macbook-pro:c-class alexlarocca$ ./program1
//
// Enter name: Alex
// Enter hourly rate: 10
// Enter hours worked this week: 40
//
// Pay to: Alex
// Hourly Rate: 10.00
// Hours Worked: 40.00
// Amount Paid: $400.00
// Taxes Paid: $80.00
// Take Home Weekly: $320.00
//
// Enter name: Bob
// Enter hourly rate: 10
// Enter hours worked this week: 50
//
// Pay to: Bob
// Hourly Rate: 10.00
// Hours Worked: 50.00
// Amount Paid: $550.00
// Taxes Paid: $110.00
// Take Home Weekly: $440.00
//
// Enter name: Dario
// Enter hourly rate: 20
// Enter hours worked this week: 45
//
// Pay to: Dario
// Hourly Rate: 20.00
// Hours Worked: 45.00
// Amount Paid: $950.00
// Taxes Paid: $190.00
// Take Home Weekly: $760.00
//
// Enter name: Ari
// Enter hourly rate: 14
// Enter hours worked this week: 23
//
// Pay to: Ari
// Hourly Rate: 14.00
// Hours Worked: 23.00
// Amount Paid: $322.00
// Taxes Paid: $64.40
// Take Home Weekly: $257.60
//
// Enter name: Joanna
// Enter hourly rate: 20
// Enter hours worked this week: 60
//
// Pay to: Joanna
// Hourly Rate: 20.00
// Hours Worked: 60.00
// Amount Paid: $1400.00
// Taxes Paid: $280.00
// Take Home Weekly: $1120.00
//
|
C
|
/*
Return the file system path of the object.
If the object is str or bytes, then allow it to pass through with
an incremented refcount. All other types raise a TypeError.
*/
PyObject *
PyOS_RawFSPath(PyObject *path)
{
if (PyObject_HasAttrString(path, "__fspath__")) {
path = PyObject_CallMethodObjArgs(path, "__fspath__", NULL);
if (path == NULL) {
return NULL;
}
}
else {
Py_INCREF(path);
}
if (!PyUnicode_Check(path) && !PyBytes_Check(path)) {
Py_DECREF(path);
return PyErr_Format(PyExc_TypeError,
"expected a string, bytes, or path object, not %S",
path->ob_type);
}
return path;
}
|
C
|
#include "mylib.h"
// Prototypes
void setPixel(int , int , unsigned short );
void drawRect(int row, int col, int height, int width, unsigned short color);
void delay(int n);
void waitForVblank();
int rand();
int canMoveRight(int row, int col);
int isGround(int row, int col);
int canMoveLeft(int row, int col);
unsigned short getPixelColor(int row, int col);
unsigned short *videoBuffer = (unsigned short *)0x6000000;
// setPixel -- set the pixel at (row, col) to color
void setPixel(int row, int col, unsigned short color) {
videoBuffer[OFFSET(row, col, 240)] = color;
}
void drawRect(int row, int col, int height, int width, unsigned short color) {
for(int r=0; r<height; r++) {
for(int c = 0; c<width; c++) {
setPixel(row+r, col+c, color);
}
}
}
void delay(int n) {
volatile int x = 0;
for(int i=0; i<n*8000; i++) {
x++;
}
}
void waitForVblank() {
while(SCANLINECOUNTER > 160)
;
while(SCANLINECOUNTER<160)
;
}
unsigned short getPixelColor(int row, int col){
return videoBuffer[OFFSET(row,col,240)];
}
int isGround(int row, int col){
unsigned short below1 = getPixelColor(row+11, col);
unsigned short below2 = getPixelColor(row+11, col+5);
unsigned short below3 = getPixelColor(row+11, col+10);
if((below1 == WHITE)||(below2==WHITE)||(below3==WHITE)) {
return 1; }
else {
return 0; }
}
int canMoveRight(int row, int col){
unsigned short below1 = getPixelColor(row, col+11);
unsigned short below2 = getPixelColor(row+5, col+11);
unsigned short below3 = getPixelColor(row+9, col+11);
if((below1 == WHITE)||(below2==WHITE)||(below3==WHITE)) {
return 0; }
else {
return 1; }
}
int canMoveLeft(int row, int col){
unsigned short below1 = getPixelColor(row, col-1);
unsigned short below2 = getPixelColor(row+5, col-1);
unsigned short below3 = getPixelColor(row+9, col-1);
if((below1 == WHITE)||(below2==WHITE)||(below3==WHITE)) {
return 0; }
else {
return 1; }
}
void drawImage3 (int r, int c, int width, int height, const unsigned short* image){
for(int i = 0; i<height;i++){
DMA[DMA_CHANNEL_3].src = image + OFFSET(i,0,width);
DMA[DMA_CHANNEL_3].dst = videoBuffer + OFFSET(r+i,c,240);
DMA[DMA_CHANNEL_3].cnt = DMA_ON | width;
}
}
|
C
|
/*
* check_bloomFilter.cpp
*
* Copyright 2010-2012 Yahoo! Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Created on: Oct 2, 2010
* Author: sears
*/
#include <stasis/util/hashFunctions.h>
#include <stasis/util/bloomFilter.h>
#include <assert.h>
#include <stdio.h>
#include <sys/time.h>
#include <stasis/util/crc32.h>
/*
* This file can test CRC and FNV-1 based hash functions. Based on early experiments:
*
* CRC32 insert/lookup: 11/13 seconds, 1.1% false positive
* FNV-1 insert/lookup: 8/9 seconds, 2.8% false positive
*
* Expected false positive rate is 1%.
*/
static uint64_t hash_a(const char* a, int len) {
return stasis_crc32(a,len,0xcafebabe);
}
static uint64_t hash_b(const char* a, int len) {
return stasis_crc32(a,len,0xdeadbeef);
}
static uint64_t hash_a_fnv(const char* a, int len) {
return stasis_util_hash_fnv_1_uint32_t((const byte*)a, len);
}
static uint64_t hash_b_fnv(const char* a, int len) {
return stasis_util_hash_fnv_1_uint64_t((const byte*)a, len);
}
static char * malloc_random_string(int group) {
char * str = 0;
int strlen = 0;
while(!strlen) strlen = 128 + (rand() & 127);
str = stasis_malloc(strlen + 1, char);
str[0] = group;
for(int i = 1; i < strlen; i++) {
str[i] = (rand() & 128) + 1;
}
str[strlen] = 0;
return str;
}
int main(int argc, char * argv[]) {
(void)hash_a; (void)hash_b;
(void)hash_a_fnv; (void)hash_b_fnv;
const int num_inserts = 1000000;
char ** strings = stasis_malloc(num_inserts, char*);
uint64_t sum_strlen = 0;
struct timeval start, stop;
gettimeofday(&start, 0);
printf("seed: %lld\n", (long long)start.tv_sec);
srand(start.tv_sec);
for(int i = 0; i < num_inserts; i++) {
strings[i] = malloc_random_string(1);
sum_strlen += strlen(strings[i]);
}
gettimeofday(&stop,0);
printf("Generated strings in %d seconds. Mean string length: %f\n", (int)(stop.tv_sec - start.tv_sec), (double)(sum_strlen)/(double)num_inserts);
stasis_bloom_filter_t * bf = stasis_bloom_filter_create(hash_a, hash_b, num_inserts, 0.01);
stasis_bloom_filter_print_stats(bf);
gettimeofday(&start, 0);
for(int i = 0; i < num_inserts; i++) {
stasis_bloom_filter_insert(bf,strings[i], strlen(strings[i]));
}
gettimeofday(&stop, 0);
printf("Inserted strings in %d seconds.\n", (int)(stop.tv_sec - start.tv_sec));
gettimeofday(&start, 0);
for(int i = 0; i < num_inserts; i++) {
assert(stasis_bloom_filter_lookup(bf, strings[i], strlen(strings[i])));
}
gettimeofday(&stop, 0);
printf("Looked up strings in %d seconds.\n", (int)(stop.tv_sec - start.tv_sec));
stasis_bloom_filter_print_stats(bf);
uint64_t false_positives = 0;
gettimeofday(&start, 0);
for(int i = 0; i < num_inserts; i++) {
char * str = malloc_random_string(2);
if(stasis_bloom_filter_lookup(bf, str, strlen(str))) {
false_positives ++;
}
assert(stasis_bloom_filter_lookup(bf, strings[i], strlen(strings[i])));
free(str);
}
gettimeofday(&stop, 0);
printf("Generated and looked up non-existant strings in %d seconds\n"
"false positive rate was %f\n", (int)(stop.tv_sec - start.tv_sec),
((double)false_positives)/(double)num_inserts);
return 0;
}
|
C
|
// quickSort.c
#include "stdio.h"
#include "stdlib.h"
void swap(int *a,int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void all(int *array,int length)
{
for (int i = 0; i < length; ++i)
{
printf("%d ",*(array+i));
}
printf("\n");
}
int quickSort(int *a,int left,int right)
{
int pivot;
int i = left,j = right;
if(left>right) return 1;
pivot=*(a+left); //pivot中存的就是基准数
while(i!=j)
{
//顺序很重要,要先从右边开始找
while(*(a+j) >= pivot && i<j) j--;
//再找右边的
while(*(a+i) <= pivot && i<j) i++;
//交换两个数在数组中的位置
if(i<j) swap(a+i,a+j);
}
//最终将基准数归位
*(a+left) = *(a+i);
*(a+i) = pivot;
// all(a,right-left);
quickSort(a,left,i-1);//继续处理左边的,这里是一个递归的过程
quickSort(a,i+1,right);//继续处理右边的 ,这里是一个递归的过程
return 0;
}
int main(int argc, char const *argv[])
{
int *array;
int length = 0;
printf("Please input the length of the array\n");
scanf("%d",&length);
array = (int*) malloc(length * sizeof(int));
for (int i = 0; i < length; ++i)
{
printf("array %d:", i+1);
scanf("%d",array+i);
}
quickSort(array,0,length-1);
all(array,length);
return 0;
}
|
C
|
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
int main(int argc, char *argv[]) {
struct sockaddr_in dest;
struct sockaddr_in serv;
char buffer[513];
int connectSocket;
int len;
int port;
int sock;
socklen_t socksize = sizeof(struct sockaddr_in);
if(argc != 2) {
printf("Format for server connection is ./server [[PORT NUMBER]].\n");
exit(0);
}
port = atoi(argv[1]);
if(!port || port < 0) {
printf("Port must be a number and non-negative.\n");
exit(0);
}
memset(&serv, 0, sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = htonl(INADDR_ANY);
serv.sin_port = htons(port);
sock = socket(AF_INET, SOCK_STREAM, 0);
if(bind(sock, (struct sockaddr*)&serv, sizeof(struct sockaddr)) == -1) {
fprintf(stderr, "Server bind was unsuccessful.\n");
exit(0);
}
listen(sock, 20);
connectSocket = accept(sock, (struct sockaddr*)&dest, &socksize);
while(connectSocket) {
printf("Incoming connection from %s \n", inet_ntoa(dest.sin_addr));
len = recv(connectSocket, buffer, 500, 0);
buffer[len] = '\0';
printf("%s\n%d bytes\n", buffer, len);
send(connectSocket, "File finished sending", 22, 0);
close(connectSocket);
connectSocket = accept(sock, (struct sockaddr *)&dest, &socksize);
}
close(sock);
return 0;
}
|
C
|
/* play_again1.c
*
* purpose: ask if user wants another transaction
* method: ask a question, wait for yes/no answer
* returns: 0=>yes, 1=>no
* better: do no echo inappropriate input
*
* version 0.1
* immediate response
*
*/
#include <stdio.h>
#include <termios.h>
#define QUESTION "Do you want another transaction?"
int get_response(const char *);
int tty_mode(int how);
void set_crmode();
int main(int argc, char *argv[])
{
int response;
tty_mode(0); /* save tty mode */
set_crmode(); /* set char-by-char mode */
response = get_response(QUESTION); /* get response */
tty_mode(1); /* restore tty mode */
return response;
}
int get_response(const char * question)
{
int input;
printf("%s (y/n)?", question);
while(1)
{
switch(input = getchar())
{
case 'y':
case 'Y': printf("\n"); return 0;
case 'n':
case 'N':
case EOF: printf("\n"); return 1;
default :
printf("\ncannot understand %c, ", input);
printf("Please type y or n\n");
}
}
}
void set_crmode()
{
struct termios ttystate;
tcgetattr(0, &ttystate);
ttystate.c_lflag &= ~ICANON; /* no buffering */
ttystate.c_cc[VMIN] = 1; /* get 1 char at a time */
tcsetattr(0, TCSANOW, &ttystate);
}
int tty_mode(int how)
/* how=0 => save current mode,
* how=1 => restore current mode
*/
{
static struct termios original_mode;
if(how == 0)
{
return tcgetattr(0, &original_mode);
}
else
{
return tcsetattr(0, TCSANOW, &original_mode);
}
}
|
C
|
#include <stdio.h>
#include <stdarg.h>
#include "memalloc.h"
#include "list.h"
#include <debug.h>
#include <pthread.h>
#define debug
//#define verbose
static struct list free_list; // list of free blocks
static pthread_mutex_t lock;
/* Comparator for Pintos list functions. */
static bool mem_block_less(const struct list_elem *a, const struct list_elem *b, void *aux) {
return (a < b);
}
/* Return number of elements in free list. */
size_t mem_sizeof_free_list(void) {
return list_size(&free_list);
}
/* Dump a list to screen. */
static void mem_dump_list(struct list *l) {
struct list_elem* elem_p;
struct free_block* free_p;
int i = 0;
for (elem_p = list_begin(l); elem_p != list_end(l); elem_p = list_next(elem_p)) {
free_p = list_entry(elem_p, struct free_block, elem);
printf("\tlist[%d]: @%ld; len=%zu\n", i++, (long)free_p, free_p->length);
}
}
/* Dump free list to screen. */
void mem_dump_free_list(void) {
printf("Dumping free list:\n");
mem_dump_list(&free_list);
}
/* Initialize allocator. */
void mem_init(uint8_t *base, size_t length) {
//initialize list
list_init(&free_list);
//initialize block and push
struct free_block* first_node = (struct free_block*) base;
first_node->length = length;
list_push_front(&free_list, &first_node->elem);
//initialize lock
pthread_mutex_init(&lock, NULL);
#ifdef debug
printf("Initializing memory of size: %zu\nAddress space: ", length);
printf("@%ld to @%ld (total bytes: %ld)\n", (long)base, (long)((void*)base + length), (long)((void*)base + length) - (long)base);
printf("Other info:\n\tsizeof(int): %zu\n", sizeof(int));
printf("\tsizeof(size_t): %zu\n", sizeof(size_t));
printf("\tsizeof(size_t*): %zu\n", sizeof(size_t*));
printf("\tsizeof(struct free_block): %zu\n", sizeof(struct free_block));
printf("\tsizeof(struct used_block): %zu\n\n", sizeof(struct used_block));
#endif
return;
}
/* Allocate by finding free block using first-fit, in address order. */
void * mem_alloc(size_t length) {
struct list_elem* elem_p = NULL;
struct free_block* free_p = NULL;
struct used_block* used_p = NULL;
size_t actual_length;
ASSERT (length % 4 == 0);
actual_length = length + sizeof(struct used_block);
#ifdef debug
printf("MALLOC: length=%zu actual=%zu\n", length, actual_length);
#endif
// if actual length is too small
if (actual_length < sizeof(struct free_block)) {
// set actual length to size of free block header
actual_length = sizeof(struct free_block);
// set user space to size of free block header minus size of used block header
length = actual_length - sizeof(struct used_block);
#ifdef debug
printf("*** requested length too small. new length: %zu; actual_length: %zu\n", length, actual_length);
#endif
}
#ifdef verbose
mem_dump_free_list();
#endif
pthread_mutex_lock(&lock);
for (elem_p = list_begin(&free_list); elem_p != list_end(&free_list); elem_p = list_next(elem_p)) {
free_p = list_entry(elem_p, struct free_block, elem);
if (free_p->length >= actual_length) {
if (free_p->length == actual_length || (free_p->length - actual_length) < sizeof(struct free_block)) {
if (free_p->length != actual_length) {
actual_length = free_p->length;
length = actual_length - sizeof(struct used_block);
#ifdef debug
printf("*** Cannot split, remaining space too small. new length: %zu; actual_length: %zu\n", length, actual_length);
#endif
}
list_remove(elem_p);
used_p = (struct used_block*) free_p;
#ifdef debug
printf("\tUsing a full block. @%ld len=%zd\n", (long) used_p, length);
#endif
} else if (free_p->length > actual_length) {
free_p->length = free_p->length - actual_length;
used_p = (struct used_block*)((void*) free_p + free_p->length);
#ifdef debug
printf("\tSplitting block.\n\t\tfree block: @%ld len=%zu\n", (long) free_p, free_p->length);
printf("\t\tused block: @%ld len=%zu\n", (long) used_p, length);
#endif
}
used_p->length = length;
pthread_mutex_unlock(&lock);
#ifdef debug
printf("<<< Giving user: @%ld len=%zu\n", (long)used_p->data, used_p->length);
#endif
return (void*) used_p->data;
}
}
pthread_mutex_unlock(&lock);
return NULL;
}
/* Determine whether two blocks are adjacent. */
static bool mem_block_is_adjacent(const struct free_block *left, const struct free_block *right) {
return ((void*)left + left->length == (void*)right);
}
/* Coalesce two adjacent blocks. */
static void mem_coalesce(struct free_block *left, struct free_block *right) {
left->length = left->length + right->length;
list_remove(&right->elem);
}
/* Free memory, coalescing free list if necessary. */
void mem_free(void *ptr) {
struct list_elem* temp_elem_p;
struct used_block* used_p;
struct free_block* free_p;
struct free_block* temp_free_p;
size_t actual_length;
#ifdef debug
printf("FREE: %ld\n",(long) ptr);
#endif
#ifdef verbose
printf("Before: ");
mem_dump_free_list();
#endif
pthread_mutex_lock(&lock);
used_p = (struct used_block*) (ptr - sizeof(struct used_block));
actual_length = used_p->length + sizeof(struct used_block);
free_p = (struct free_block*) used_p;
free_p->length = actual_length;
list_insert_ordered(&free_list, &free_p->elem, mem_block_less, NULL);
#ifdef debug
printf(">>> Added free block: @%ld len=%zu\n", (long) free_p, free_p->length);
#endif
#ifdef verbose
printf("After: ");
mem_dump_free_list();
#endif
temp_elem_p = list_prev(&free_p->elem);
if (temp_elem_p != list_head(&free_list)) {
temp_free_p = list_entry(temp_elem_p, struct free_block, elem);
#ifdef verbose
printf("Checking before @%d+%d == %d\n", (int) temp_free_p, temp_free_p->length, (int) free_p);
#endif
if (mem_block_is_adjacent(temp_free_p, free_p)) {
#ifdef verbose
printf("Merging before @%d+%d == %d\n", (int) temp_free_p, temp_free_p->length, (int) free_p);
#endif
mem_coalesce(temp_free_p, free_p);
free_p = temp_free_p;
}
}
temp_elem_p = list_next(&free_p->elem);
if (temp_elem_p != list_tail(&free_list)) {
#ifdef verbose
printf("Checking after @%d+%d == %d\n", (int) free_p, free_p->length, (int) temp_free_p);
#endif
temp_free_p = list_entry(temp_elem_p, struct free_block, elem);
if (mem_block_is_adjacent(free_p, temp_free_p)) {
#ifdef verbose
printf("Merging after @%d+%d == %d\n", (int) free_p, free_p->length, (int) temp_free_p);
#endif
mem_coalesce(free_p, temp_free_p);
}
}
pthread_mutex_unlock(&lock);
}
|
C
|
// Copyright (c) Edgeless Systems GmbH.
// Licensed under the MIT License.
/*
This mmap implementation manages the whole enclave heap memory. The first pages
are reserved for a bitmap that saves the state of all other pages: 1 if the page
is in use, 0 otherwise.
malloc calls mmap to reserve enclave heap space.
*/
#include <openenclave/corelibc/assert.h>
#include <openenclave/corelibc/errno.h>
#include <openenclave/corelibc/mman.h>
#include <openenclave/corelibc/string.h>
#include <openenclave/internal/bitset.h>
#include <openenclave/internal/globals.h>
#include <openenclave/internal/thread.h>
#include <openenclave/internal/utils.h>
static oe_spinlock_t _lock = OE_SPINLOCK_INITIALIZER;
static void* _bitset;
static void* _base;
static size_t _size;
static void _init()
{
const size_t full_size = __oe_get_heap_size();
const size_t bitmap_size =
oe_round_up_to_page_size(full_size / (OE_CHAR_BIT * OE_PAGE_SIZE));
_bitset = (void*)__oe_get_heap_base();
_base = (uint8_t*)_bitset + bitmap_size;
_size = full_size - bitmap_size;
memset(_bitset, 0, bitmap_size);
}
static bool _length_in_range(size_t length)
{
return 0 < length && length < _size;
}
static bool _addr_in_range(void* addr, size_t length)
{
return _base <= addr && (uint8_t*)addr + length <= (uint8_t*)_base + _size;
}
static size_t _to_pos(const void* addr)
{
return (size_t)((uint8_t*)addr - (uint8_t*)_base) / OE_PAGE_SIZE;
}
static void* _map(size_t length)
{
oe_assert(length && length % OE_PAGE_SIZE == 0);
// Naive approach: reserve the first unset range we can find.
const size_t count = length / OE_PAGE_SIZE;
const size_t pos =
oe_bitset_find_unset_range(_bitset, _size / OE_PAGE_SIZE, count);
if (pos == OE_SIZE_MAX)
{
oe_errno = OE_ENOMEM;
return OE_MAP_FAILED;
}
oe_bitset_set_range(_bitset, pos, count);
void* const result = (uint8_t*)_base + pos * OE_PAGE_SIZE;
memset(result, 0, length);
return result;
}
static void* _map_fixed(void* addr, size_t length)
{
if (!_addr_in_range(addr, length))
{
oe_errno = OE_ENOMEM;
return OE_MAP_FAILED;
}
// MAP_FIXED discards overlapped part of existing mappings
oe_bitset_set_range(_bitset, _to_pos(addr), length / OE_PAGE_SIZE);
memset(addr, 0, length);
return addr;
}
void* oe_mmap(
void* addr,
size_t length,
int prot,
int flags,
int fd,
oe_off_t offset)
{
// check for invalid args
if ((uintptr_t)addr % OE_PAGE_SIZE || !length)
{
oe_errno = OE_EINVAL;
return OE_MAP_FAILED;
}
// check for unsupported args
// Accept PROT_EXEC even though the memory is not executable. Python ctypes
// will allocate such memory, but not necessarily make use of it.
if ((prot & ~(OE_PROT_READ | OE_PROT_WRITE | OE_PROT_EXEC)) || fd != -1 ||
offset)
{
oe_errno = OE_ENOSYS;
return OE_MAP_FAILED;
}
length = oe_round_up_to_page_size(length);
void* result = OE_MAP_FAILED;
oe_spin_lock(&_lock);
if (!_base)
_init();
if (!_length_in_range(length))
{
oe_spin_unlock(&_lock);
oe_errno = OE_ENOMEM;
return result;
}
if (!addr && flags == (OE_MAP_ANON | OE_MAP_PRIVATE))
result = _map(length);
else if (addr && flags == (OE_MAP_ANON | OE_MAP_FIXED | OE_MAP_PRIVATE))
result = _map_fixed(addr, length);
else
oe_errno = OE_EINVAL;
oe_spin_unlock(&_lock);
return result;
}
int oe_munmap(void* addr, size_t length)
{
int result = -1;
length = oe_round_up_to_page_size(length);
oe_spin_lock(&_lock);
if (_length_in_range(length) && _addr_in_range(addr, length) &&
(uintptr_t)addr % OE_PAGE_SIZE == 0)
{
oe_bitset_reset_range(_bitset, _to_pos(addr), length / OE_PAGE_SIZE);
result = 0;
}
else
oe_errno = OE_EINVAL;
oe_spin_unlock(&_lock);
return result;
}
OE_WEAK_ALIAS(oe_mmap, mmap);
OE_WEAK_ALIAS(oe_mmap, __mmap);
OE_WEAK_ALIAS(oe_mmap, mmap64);
OE_WEAK_ALIAS(oe_munmap, munmap);
OE_WEAK_ALIAS(oe_munmap, __munmap);
|
C
|
#include <stdio.h>
#include <stdlib.h>
int pilihanawal;
int main()
{
puts("BATTLE OF OLYMPIA");
puts("1. New Game");
puts("2. Load Game");
printf("Masukkan pilihan : ");
scanf("%d", pilihanawal);
switch (pilihanawal) {
case 1 :
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int number[10];
int i = 0;
float media;
printf("Insira 10 numeros: ");
for(i = 0; i < 10; i++){
scanf("%d", &number[i]);
media += number[i];
}
media /= 10;
printf("media: %.2f \n", media);
printf("numeros acima ou igual a media: ");
for (i = 0; i < 10; i++){
if(number[i] >= media)
printf("%d ", number[i]);
}
return 0;
}
|
C
|
#include "AST.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "Util.h"
#include "Error.h"
char const * operator_bin_to_str(Operator_Bin operator) {
switch (operator) {
case OPERATOR_BIN_ASSIGN: return "=";
case OPERATOR_BIN_LOGICAL_AND: return "&&";
case OPERATOR_BIN_LOGICAL_OR: return "||";
case OPERATOR_BIN_PLUS: return "+";
case OPERATOR_BIN_MINUS: return "-";
case OPERATOR_BIN_MULTIPLY: return "*";
case OPERATOR_BIN_DIVIDE: return "/";
case OPERATOR_BIN_MODULO: return "%";
case OPERATOR_BIN_SHIFT_LEFT: return "<<";
case OPERATOR_BIN_SHIFT_RIGHT: return ">>";
case OPERATOR_BIN_LT: return "<";
case OPERATOR_BIN_LE: return "<=";
case OPERATOR_BIN_GT: return ">";
case OPERATOR_BIN_GE: return ">=";
case OPERATOR_BIN_EQ: return "==";
case OPERATOR_BIN_NE: return "!=";
case OPERATOR_BIN_BITWISE_AND: return "&";
case OPERATOR_BIN_BITWISE_XOR: return "^";
case OPERATOR_BIN_BITWISE_OR: return "|";
default: error_internal();
}
}
char const * operator_pre_to_str(Operator_Pre operator) {
switch (operator) {
case OPERATOR_PRE_ADDRESS_OF: return "&";
case OPERATOR_PRE_DEREF: return "*";
case OPERATOR_PRE_INC: return "++";
case OPERATOR_PRE_DEC: return "--";
case OPERATOR_PRE_PLUS: return "+";
case OPERATOR_PRE_MINUS: return "-";
case OPERATOR_PRE_LOGICAL_NOT: return "!";
case OPERATOR_PRE_BITWISE_NOT: return "~";
default: error_internal();
}
}
char const * operator_post_to_str(Operator_Post operator) {
switch (operator) {
case OPERATOR_POST_INC: return "++";
case OPERATOR_POST_DEC: return "--";
default: error_internal();
}
}
AST_Expression * ast_make_expr_const(int line, Token const * token) {
AST_Expression * expr = mem_alloc(sizeof(AST_Expression));
expr->type = AST_EXPRESSION_CONST;
expr->line = line;
expr->height = 0;
expr->expr_const.token = *token;
return expr;
}
AST_Expression * ast_make_expr_var(int line, char const * name) {
AST_Expression * expr = mem_alloc(sizeof(AST_Expression));
expr->type = AST_EXPRESSION_VAR;
expr->line = line;
expr->height = 0;
expr->expr_var.name = name;
return expr;
}
AST_Expression * ast_make_expr_array_access(int line, AST_Expression * expr_array, AST_Expression * expr_index) {
AST_Expression * expr = mem_alloc(sizeof(AST_Expression));
expr->type = AST_EXPRESSION_ARRAY_ACCESS;
expr->line = line;
expr->height = expr_index->height + 1;
expr->expr_array_access.expr_array = expr_array;
expr->expr_array_access.expr_index = expr_index;
return expr;
}
AST_Expression * ast_make_expr_struct_member(int line, AST_Expression * expr_struct, char const * member_name) {
AST_Expression * expr = mem_alloc(sizeof(AST_Expression));
expr->type = AST_EXPRESSION_STRUCT_MEMBER;
expr->line = line;
expr->height = expr_struct->height + 1;
expr->expr_struct_member.expr = expr_struct;
expr->expr_struct_member.member_name = member_name;
return expr;
}
AST_Expression * ast_make_expr_cast(int line, Type const * type, AST_Expression * expr_cast) {
AST_Expression * expr = mem_alloc(sizeof(AST_Expression));
expr->type = AST_EXPRESSION_CAST;
expr->line = line;
expr->height = expr_cast->height + 1;
expr->expr_cast.new_type = type;
expr->expr_cast.expr = expr_cast;
return expr;
}
AST_Expression * ast_make_expr_sizeof(int line, Type const * type) {
AST_Expression * expr = mem_alloc(sizeof(AST_Expression));
expr->type = AST_EXPRESSION_SIZEOF;
expr->line = line;
expr->height = 0;
expr->expr_sizeof.type = type;
return expr;
}
AST_Expression * ast_make_expr_op_bin(int line, Operator_Bin operator, AST_Expression * expr_left, AST_Expression * expr_right) {
AST_Expression * expr = mem_alloc(sizeof(AST_Expression));
expr->type = AST_EXPRESSION_OPERATOR_BIN;
expr->line = line;
expr->height = MAX(expr_left->height, expr_right->height) + 1;
expr->expr_op_bin.operator = operator;
expr->expr_op_bin.expr_left = expr_left;
expr->expr_op_bin.expr_right = expr_right;
return expr;
}
AST_Expression * ast_make_expr_op_pre(int line, Operator_Pre operator, AST_Expression * expr_operand) {
AST_Expression * expr = mem_alloc(sizeof(AST_Expression));
expr->type = AST_EXPRESSION_OPERATOR_PRE;
expr->line = line;
expr->height = expr_operand->height + 1;
expr->expr_op_bin.operator = operator;
expr->expr_op_pre.expr = expr_operand;
return expr;
}
AST_Expression * ast_make_expr_op_post(int line, Operator_Post operator, AST_Expression * expr_operand) {
AST_Expression * expr = mem_alloc(sizeof(AST_Expression));
expr->type = AST_EXPRESSION_OPERATOR_POST;
expr->line = line;
expr->height = expr_operand->height + 1;
expr->expr_op_bin.operator = operator;
expr->expr_op_post.expr = expr_operand;
return expr;
}
AST_Expression * ast_make_expr_call(int line, AST_Expression * expr_function, int arg_count, AST_Call_Arg * args) {
int height = 0;
for (int i = 0; i < arg_count; i++) {
height = MAX(height, args[i].height);
}
AST_Expression * expr = mem_alloc(sizeof(AST_Expression));
expr->type = AST_EXPRESSION_CALL_FUNC;
expr->line = line;
expr->height = height + 1;
expr->expr_call.expr_function = expr_function;
expr->expr_call.arg_count = arg_count;
expr->expr_call.args = args;
return expr;
}
AST_Statement * ast_make_stat_program(int line, Variable_Buffer * globals, Scope * global_scope, AST_Statement * stats) {
AST_Statement * stat = mem_alloc(sizeof(AST_Statement));
stat->type = AST_STATEMENT_PROGRAM;
stat->line = line;
stat->stat_program.globals = globals;
stat->stat_program.global_scope = global_scope;
stat->stat_program.stat = stats;
return stat;
}
AST_Statement * ast_make_stat_stats(int line, AST_Statement * head, AST_Statement * cons) {
AST_Statement * stat = mem_alloc(sizeof(AST_Statement));
stat->type = AST_STATEMENTS;
stat->line = line;
stat->stat_stats.head = head;
stat->stat_stats.cons = cons;
return stat;
}
AST_Statement * ast_make_stat_block(int line, Scope * scope, AST_Statement * stats) {
AST_Statement * stat = mem_alloc(sizeof(AST_Statement));
stat->type = AST_STATEMENT_BLOCK;
stat->line = line;
stat->stat_block.scope = scope;
stat->stat_block.stat = stats;
return stat;
}
AST_Statement * ast_make_stat_expr(int line, AST_Expression * expr) {
AST_Statement * stat = mem_alloc(sizeof(AST_Statement));
stat->type = AST_STATEMENT_EXPR;
stat->line = line;
stat->stat_expr.expr = expr;
return stat;
}
AST_Statement * ast_make_stat_def_var(int line, char const * name, Type const * type, AST_Expression * assign) {
AST_Statement * stat = mem_alloc(sizeof(AST_Statement));
stat->type = AST_STATEMENT_DEF_VAR;
stat->line = line;
stat->stat_def_var.name = name;
stat->stat_def_var.type = type;
stat->stat_def_var.assign = assign;
return stat;
}
AST_Statement * ast_make_stat_def_func(int line, Function_Def * function_def, Variable_Buffer * buffer_args, Variable_Buffer * buffer_vars, Scope * scope_args, AST_Statement * body) {
AST_Statement * stat = mem_alloc(sizeof(AST_Statement));
stat->type = AST_STATEMENT_DEF_FUNC;
stat->line = line;
stat->stat_def_func.function_def = function_def;
stat->stat_def_func.buffer_args = buffer_args;
stat->stat_def_func.buffer_vars = buffer_vars;
stat->stat_def_func.scope_args = scope_args;
stat->stat_def_func.body = body;
return stat;
}
AST_Statement * ast_make_stat_extern(int line, Function_Def * function_def) {
AST_Statement * stat = mem_alloc(sizeof(AST_Statement));
stat->type = AST_STATEMENT_EXTERN;
stat->line = line;
stat->stat_def_func.function_def = function_def;
return stat;
}
AST_Statement * ast_make_stat_export(int line, char const * name) {
AST_Statement * stat = mem_alloc(sizeof(AST_Statement));
stat->type = AST_STATEMENT_EXPORT;
stat->line = line;
stat->stat_export.name = name;
return stat;
}
AST_Statement * ast_make_stat_if(int line, AST_Expression * condition, AST_Statement * case_true, AST_Statement * case_false) {
AST_Statement * stat = mem_alloc(sizeof(AST_Statement));
stat->type = AST_STATEMENT_IF;
stat->line = line;
stat->stat_if.condition = condition;
stat->stat_if.case_true = case_true;
stat->stat_if.case_false = case_false;
return stat;
}
AST_Statement * ast_make_stat_while(int line, AST_Expression * condition, AST_Statement * body) {
AST_Statement * stat = mem_alloc(sizeof(AST_Statement));
stat->type = AST_STATEMENT_WHILE;
stat->line = line;
stat->stat_while.condition = condition;
stat->stat_while.body = body;
return stat;
}
AST_Statement * ast_make_stat_break(int line) {
AST_Statement * stat = mem_alloc(sizeof(AST_Statement));
stat->type = AST_STATEMENT_BREAK;
stat->line = line;
return stat;
}
AST_Statement * ast_make_stat_continue(int line) {
AST_Statement * stat = mem_alloc(sizeof(AST_Statement));
stat->type = AST_STATEMENT_CONTINUE;
stat->line = line;
return stat;
}
AST_Statement * ast_make_stat_return(int line, AST_Expression * expr) {
AST_Statement * stat = mem_alloc(sizeof(AST_Statement));
stat->type = AST_STATEMENT_RETURN;
stat->line = line;
stat->stat_return.expr = expr;
return stat;
}
#define SPRINTF(fmt) (*string_offset += sprintf_s(string + *string_offset, string_size - *string_offset, fmt))
#define VSPRINTF(fmt, ...) (*string_offset += sprintf_s(string + *string_offset, string_size - *string_offset, fmt, __VA_ARGS__))
static void print_indent(int indentation_level, char * string, int * string_offset, int string_size) {
for (int i = 0; i < indentation_level; i++) {
SPRINTF(" ");
}
}
static void print_def_arg(AST_Def_Arg const * arg, char * string, int * string_offset, int string_size) {
char str_type[512];
type_to_string(arg->type, str_type, sizeof(str_type));
VSPRINTF("%s: %s", arg->name, str_type);
}
static void print_expression(AST_Expression const * expr, char * string, int * string_offset, int string_size) {
switch(expr->type) {
case AST_EXPRESSION_CONST: {
char str_token[128];
token_to_string(&expr->expr_const.token, str_token, sizeof(str_token));
VSPRINTF("%s", str_token);
break;
}
case AST_EXPRESSION_VAR: {
VSPRINTF("%s", expr->expr_var.name);
break;
}
case AST_EXPRESSION_ARRAY_ACCESS: {
print_expression(expr->expr_array_access.expr_array, string, string_offset, string_size);
SPRINTF("[");
print_expression(expr->expr_array_access.expr_index, string, string_offset, string_size);
SPRINTF("]");
break;
}
case AST_EXPRESSION_STRUCT_MEMBER: {
print_expression(expr->expr_struct_member.expr, string, string_offset, string_size);
VSPRINTF(".%s", expr->expr_struct_member.member_name);
break;
}
case AST_EXPRESSION_CAST: {
char str_type[128];
type_to_string(expr->expr_cast.new_type, str_type, sizeof(str_type));
VSPRINTF("cast(%s) ", str_type);
print_expression(expr->expr_cast.expr, string, string_offset, string_size);
break;
}
case AST_EXPRESSION_SIZEOF: {
char str_type[128];
type_to_string(expr->expr_sizeof.type, str_type, sizeof(str_type));
VSPRINTF("sizeof(%s)", str_type);
break;
}
case AST_EXPRESSION_OPERATOR_BIN: {
Precedence precedence_here = get_precedence(expr);
Precedence precedence_left = get_precedence(expr->expr_op_bin.expr_left);
Precedence precedence_right = get_precedence(expr->expr_op_bin.expr_right);
bool needs_parentheses_left = precedence_left > precedence_here;
bool needs_parentheses_right = precedence_right > precedence_here;
if (needs_parentheses_left) SPRINTF("(");
print_expression(expr->expr_op_bin.expr_left, string, string_offset, string_size);
if (needs_parentheses_left) SPRINTF(")");
VSPRINTF(" %s ", operator_bin_to_str(expr->expr_op_bin.operator));
if (needs_parentheses_right) SPRINTF("(");
print_expression(expr->expr_op_bin.expr_right, string, string_offset, string_size);
if (needs_parentheses_right) SPRINTF(")");
break;
}
case AST_EXPRESSION_OPERATOR_PRE: {
Precedence precedence_here = get_precedence(expr);
Precedence precedence_inner = get_precedence(expr->expr_op_pre.expr);
bool needs_parentheses = precedence_inner > precedence_here;
VSPRINTF("%s", operator_pre_to_str(expr->expr_op_pre.operator));
if (needs_parentheses) SPRINTF("(");
print_expression(expr->expr_op_pre.expr, string, string_offset, string_size);
if (needs_parentheses) SPRINTF(")");
break;
}
case AST_EXPRESSION_OPERATOR_POST: {
Precedence precedence_here = get_precedence(expr);
Precedence precedence_inner = get_precedence(expr->expr_op_pre.expr);
bool needs_parentheses = precedence_inner > precedence_here;
if (needs_parentheses) SPRINTF("(");
print_expression(expr->expr_op_post.expr, string, string_offset, string_size);
if (needs_parentheses) SPRINTF(")");
VSPRINTF("%s", operator_post_to_str(expr->expr_op_post.operator));
break;
}
case AST_EXPRESSION_CALL_FUNC: {
print_expression(expr->expr_call.expr_function, string, string_offset, string_size);
SPRINTF("(");
for (int i = 0; i < expr->expr_call.arg_count; i++) {
print_expression(expr->expr_call.args[i].expr, string, string_offset, string_size);
if (i != expr->expr_call.arg_count - 1) SPRINTF(", ");
}
SPRINTF(")");
break;
}
default: SPRINTF("Unprintable Expression!\n"); return;
}
}
static void print_statement(AST_Statement const * stat, char * string, int * string_offset, int string_size, int indent) {
switch (stat->type) {
case AST_STATEMENT_PROGRAM: {
print_statement(stat->stat_program.stat, string, string_offset, string_size, indent);
break;
}
case AST_STATEMENTS: {
if (stat->stat_stats.head) print_statement(stat->stat_stats.head, string, string_offset, string_size, indent);
if (stat->stat_stats.cons) print_statement(stat->stat_stats.cons, string, string_offset, string_size, indent);
break;
}
case AST_STATEMENT_BLOCK: {
if (stat->stat_block.stat) print_statement(stat->stat_block.stat, string, string_offset, string_size, indent);
break;
}
case AST_STATEMENT_EXPR: {
print_indent(indent, string, string_offset, string_size);
print_expression(stat->stat_expr.expr, string, string_offset, string_size);
SPRINTF(";\n");
break;
}
case AST_STATEMENT_DEF_VAR: {
char str_type[128];
type_to_string(stat->stat_def_var.type, str_type, sizeof(str_type));
print_indent(indent, string, string_offset, string_size);
VSPRINTF("%s: %s", stat->stat_def_var.name, str_type);
if (stat->stat_def_var.assign) {
SPRINTF("; ");
print_expression(stat->stat_def_var.assign, string, string_offset, string_size);
}
SPRINTF(";\n");
break;
}
case AST_STATEMENT_DEF_FUNC: {
print_indent(indent, string, string_offset, string_size);
VSPRINTF("func %s(", stat->stat_def_func.function_def->name);
for (int i = 0; i < stat->stat_def_func.function_def->arg_count; i++) {
print_def_arg(&stat->stat_def_func.function_def->args[i], string, string_offset, string_size);
}
char str_type[128];
type_to_string(stat->stat_def_func.function_def->return_type, str_type, sizeof(str_type));
VSPRINTF(") -> %s {\n", str_type);
print_statement(stat->stat_def_func.body, string, string_offset, string_size, indent + 1);
print_indent(indent, string, string_offset, string_size);
SPRINTF("}\n");
break;
}
case AST_STATEMENT_EXTERN: {
print_indent(indent, string, string_offset, string_size);
VSPRINTF("extern %s\n", stat->stat_extern.function_def->name);
break;
}
case AST_STATEMENT_IF: {
print_indent(indent, string, string_offset, string_size);
SPRINTF("if (");
print_expression(stat->stat_if.condition, string, string_offset, string_size);
SPRINTF(") {\n");
print_statement(stat->stat_if.case_true, string, string_offset, string_size, indent + 1);
if (stat->stat_if.case_false) {
print_indent(indent, string, string_offset, string_size);
SPRINTF("} else {\n");
print_statement(stat->stat_if.case_false, string, string_offset, string_size, indent + 1);
}
print_indent(indent, string, string_offset, string_size);
SPRINTF("}\n");
break;
}
case AST_STATEMENT_WHILE: {
print_indent(indent, string, string_offset, string_size);
SPRINTF("while (");
print_expression(stat->stat_while.condition, string, string_offset, string_size);
SPRINTF(") {\n");
print_statement(stat->stat_while.body, string, string_offset, string_size, indent + 1);
print_indent(indent, string, string_offset, string_size);
SPRINTF("}\n");
break;
}
case AST_STATEMENT_RETURN: {
print_indent(indent, string, string_offset, string_size);
SPRINTF("return");
if (stat->stat_return.expr) {
SPRINTF(" ");
print_expression(stat->stat_return.expr, string, string_offset, string_size);
}
SPRINTF(";\n");
break;
}
case AST_STATEMENT_BREAK: {
print_indent(indent, string, string_offset, string_size);
SPRINTF("break;\n");
break;
}
case AST_STATEMENT_CONTINUE: {
print_indent(indent, string, string_offset, string_size);
SPRINTF("continue;\n");
break;
}
default: SPRINTF("Unprintable Statement!\n");
}
}
bool ast_is_lvalue(AST_Expression const * expr) {
return
expr->type == AST_EXPRESSION_OPERATOR_PRE ||
expr->type == AST_EXPRESSION_OPERATOR_POST ||
expr->type == AST_EXPRESSION_VAR ||
expr->type == AST_EXPRESSION_ARRAY_ACCESS ||
expr->type == AST_EXPRESSION_STRUCT_MEMBER;
}
bool ast_contains(AST_Expression const * expr, AST_Expression_Type expression_type) {
if (expr->type == expression_type) return true;
switch (expr->type) {
case AST_EXPRESSION_CONST: return false;
case AST_EXPRESSION_VAR: return false;
case AST_EXPRESSION_ARRAY_ACCESS: return
ast_contains(expr->expr_array_access.expr_array, expression_type) ||
ast_contains(expr->expr_array_access.expr_index, expression_type);
case AST_EXPRESSION_STRUCT_MEMBER: return ast_contains(expr->expr_struct_member.expr, expression_type);
case AST_EXPRESSION_CAST: return ast_contains(expr->expr_cast.expr, expression_type);
case AST_EXPRESSION_SIZEOF: return false;
case AST_EXPRESSION_OPERATOR_BIN: return
ast_contains(expr->expr_op_bin.expr_left, expression_type) ||
ast_contains(expr->expr_op_bin.expr_right, expression_type);
case AST_EXPRESSION_OPERATOR_PRE: return ast_contains(expr->expr_op_pre .expr, expression_type);
case AST_EXPRESSION_OPERATOR_POST: return ast_contains(expr->expr_op_post.expr, expression_type);
case AST_EXPRESSION_CALL_FUNC: return false;
default: error_internal();
}
}
#undef SPRINTF
#undef VSPRINTF
void ast_print_expression(AST_Expression const * expr, char * string, int string_size) {
int string_offset = 0;
print_expression(expr, string, &string_offset, string_size);
}
void ast_print_statement (AST_Statement const * stat, char * string, int string_size) {
int string_offset = 0;
print_statement(stat, string, &string_offset, string_size, 0);
}
static void ast_free_expression(AST_Expression * expr) {
if (expr == NULL) return;
switch (expr->type) {
case AST_EXPRESSION_CONST: break;
case AST_EXPRESSION_VAR: break;
case AST_EXPRESSION_OPERATOR_BIN: {
ast_free_expression(expr->expr_op_bin.expr_left);
ast_free_expression(expr->expr_op_bin.expr_right);
break;
}
case AST_EXPRESSION_OPERATOR_PRE: {
ast_free_expression(expr->expr_op_pre.expr);
break;
}
case AST_EXPRESSION_OPERATOR_POST: {
ast_free_expression(expr->expr_op_post.expr);
break;
}
case AST_EXPRESSION_CALL_FUNC: {
ast_free_expression(expr->expr_call.expr_function);
for (int i = 0; i < expr->expr_call.arg_count; i++) {
ast_free_expression(expr->expr_call.args[i].expr);
}
mem_free(expr->expr_call.args);
break;
}
}
}
void ast_free_statement(AST_Statement * stat) {
if (stat == NULL) return;
switch (stat->type) {
case AST_STATEMENT_PROGRAM: {
ast_free_statement(stat->stat_program.stat);
break;
}
case AST_STATEMENTS: {
if (stat->stat_stats.head) ast_free_statement(stat->stat_stats.head);
if (stat->stat_stats.cons) ast_free_statement(stat->stat_stats.cons);
break;
}
case AST_STATEMENT_BLOCK: {
free_scope(stat->stat_block.scope);
ast_free_statement(stat->stat_block.stat);
break;
}
case AST_STATEMENT_EXPR: ast_free_expression(stat->stat_expr.expr); break;
case AST_STATEMENT_DEF_VAR: {
mem_free(stat->stat_def_var.name);
break;
}
case AST_STATEMENT_DEF_FUNC: {
mem_free(stat->stat_def_func.function_def->name);
for (int i = 0; i < stat->stat_def_func.function_def->arg_count; i++) {
mem_free(stat->stat_def_func.function_def->args[i].name);
}
mem_free(stat->stat_def_func.function_def->args);
ast_free_statement(stat->stat_def_func.body);
break;
}
case AST_STATEMENT_EXTERN: {
mem_free(stat->stat_extern.function_def->name);
break;
}
case AST_STATEMENT_EXPORT: {
mem_free(stat->stat_export.name);
break;
}
case AST_STATEMENT_IF: {
ast_free_expression(stat->stat_if.condition);
ast_free_statement(stat->stat_if.case_true);
ast_free_statement(stat->stat_if.case_false);
break;
}
case AST_STATEMENT_WHILE: {
ast_free_expression(stat->stat_while.condition);
ast_free_statement(stat->stat_while.body);
break;
}
case AST_STATEMENT_BREAK: break;
case AST_STATEMENT_CONTINUE: break;
case AST_STATEMENT_RETURN: {
ast_free_expression(stat->stat_return.expr);
break;
}
default: error_internal();
}
mem_free(stat);
}
Precedence get_precedence(AST_Expression const * expr) {
switch (expr->type) {
case AST_EXPRESSION_ARRAY_ACCESS: return PRECEDENCE_ARRAY_ACCESS;
case AST_EXPRESSION_OPERATOR_POST: return PRECEDENCE_UNARY_POST;
case AST_EXPRESSION_OPERATOR_PRE: return PRECEDENCE_UNARY_PRE;
case AST_EXPRESSION_CAST:
case AST_EXPRESSION_SIZEOF: return PRECEDENCE_CAST_SIZEOF;
case AST_EXPRESSION_OPERATOR_BIN: {
switch (expr->expr_op_bin.operator) {
case OPERATOR_BIN_ASSIGN: return PRECEDENCE_ASSIGNMENT;
case OPERATOR_BIN_MULTIPLY:
case OPERATOR_BIN_DIVIDE:
case OPERATOR_BIN_MODULO: return PRECEDENCE_MULTIPLICATIVE;
case OPERATOR_BIN_PLUS:
case OPERATOR_BIN_MINUS: return PRECEDENCE_ADDITIVE;
case OPERATOR_BIN_SHIFT_LEFT:
case OPERATOR_BIN_SHIFT_RIGHT: return PRECEDENCE_SHIFT;
case OPERATOR_BIN_LT:
case OPERATOR_BIN_GT:
case OPERATOR_BIN_LE:
case OPERATOR_BIN_GE: return PRECEDENCE_RELATIONAL;
case OPERATOR_BIN_EQ:
case OPERATOR_BIN_NE: return PRECEDENCE_EQUALITY;
case OPERATOR_BIN_BITWISE_AND: return PRECEDENCE_BITWISE_AND;
case OPERATOR_BIN_BITWISE_XOR: return PRECEDENCE_BITWISE_XOR;
case OPERATOR_BIN_BITWISE_OR: return PRECEDENCE_BITWISE_OR;
case OPERATOR_BIN_LOGICAL_AND: return PRECEDENCE_LOGICAL_AND;
case OPERATOR_BIN_LOGICAL_OR: return PRECEDENCE_LOGICAL_OR;
defaut: error_internal();
}
}
}
return PRECEDENCE_NONE;
}
|
C
|
// Integer overflow for educational reasons, discard the warning of the compiler
#include <stdio.h>
#include <limits.h>
#include <float.h>
int main(void) // demonstration of overflow and underflow behavior of int and float types
{
printf("INT_MAX \t= %d\n", INT_MAX);
printf("INT_MAX + 1 \t= %d\n\n", INT_MAX + 1);
printf("FLT_MAX \t= %e\n", FLT_MAX);
printf("FLT_MAX * 10 \t= %e\n\n", FLT_MAX * 10);
printf("0.000001 / 2 \t= %f\n", 0.000001 / 2);
return 0;
}
/* Rest of file is not compiled, it's just explanation.
OUTPUT:
NT_MAX = 2147483647
INT_MAX + 1 = -2147483648
FLT_MAX = 3.402823e+38
FLT_MAX * 10 = inf
0.000001 / 2 = 0.000000
EXPLANATION:
Integer overflow seems to just go back to negative numbers,
this make sense when we think of the representation of the number
(the first bit represent the sign of the integer).
Float overflow works as expected in the standard (it shows inf).
Float underflow is just loosing precision.
*/
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include"sqlite3.h"
#include<string.h>
int main(int argc,char **argv)
{
// 校验参数有效性
char *dbname = argv[1];
char *tablename = argv[2];
if (argc < 3) {
printf("Error: Must specific a db file and select table name\n");
printf("\nUsage:\n\t%s file.db table_name\n", argv[0]);
exit(1);
}
printf("db file %s:SELECT * FROM %s\n", dbname, tablename);
int rc, i, ncols;
sqlite3 *db;
sqlite3_stmt *stmt;
char *sql;
const char*tail;
// 打开数据
rc = sqlite3_open(dbname, &db);
if(rc) {
fprintf(stderr,"Can'topendatabase:%sn",sqlite3_errmsg(db));
sqlite3_close(db);
exit(1);
}
// 构造执行语句
sql = malloc(strlen("SELECT * FROM ") + strlen(tablename));
if (sql == NULL) {
sqlite3_close(db);
exit(1);
}
sprintf(sql, "SELECT * FROM %s", tablename);
// 预处理
rc = sqlite3_prepare(db, sql, (int)strlen(sql), &stmt, &tail);
if (rc != SQLITE_OK){
fprintf(stderr, "SQLerror:%s\n", sqlite3_errmsg(db));
}
rc = sqlite3_step(stmt);
ncols = sqlite3_column_count(stmt);
while (rc == SQLITE_ROW){
for (i=0; i<ncols; i++){
fprintf(stderr, "'%s'", sqlite3_column_text(stmt, i));
}
fprintf(stderr, "\n");
rc = sqlite3_step(stmt);
}
// 释放statement
sqlite3_finalize(stmt);
// 关闭数据库
sqlite3_close(db);
printf("\n");
return(0);
}
|
C
|
#include<stdio.h>
#include<string.h>
char sen[200];
char tar[200];
int mark[200];
///E --> E+E | E-E | E*E | E/E | (E) | a | b | c
struct st{
int value;
int index;
}ar[200];
void Sort(int n)
{
int i, j, a, b;
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (ar[i].value < ar[j].value)
{
a = ar[i].value; b=ar[i].index;
ar[i].value = ar[j].value;
ar[i].index = ar[j].index;
ar[j].value = a; ar[j].index=b;
}
}
}
}
int main()
{
///'mark' array ke 0 korte hobe
int a, b, i, j=0, n;
char sign;
strcpy(tar, "a+b*d/e");
n=strlen(tar);
printf("Given: %s\n", tar);
for(i=0; tar[i] ; i++)
{
sign=tar[i];
switch (sign){
case '+':
ar[j].index=i; ar[j++].value=1;
break;
case '-':
ar[j].index=i; ar[j++].value=2;
break;
case '*':
ar[j].index=i; ar[j++].value=3;
break;
case '/':
ar[j].index=i; ar[j++].value=4;
break;
}
}
//sort(ar, ar+j, compare);
Sort(j);
int k, l;
printf("E\n");
for(i=0; i<j ; i++)
{
mark[ar[i].index]=1;
mark[ar[i].index-1]=1;
mark[ar[i].index+1]=1;
int ok=1;
for(k=0;k<n;k++){
if(mark[k]){
if(k%2==1){ printf("%c", tar[k]); ok=1;}
else if(ok){printf("E"); ok=0;}
}
}
puts("");
}
for(i=0; i<=j ; i++)
{
for(k=0,l=0;k<n;k++){
if(mark[k]){
if(k%2==1)printf("%c", tar[k]);
else if(l<=i){printf("%c",tar[k]);l++;}
else printf("E");
}
}
puts("");
}
return 0;
}
|
C
|
// EX 1.19
#include <stdio.h>
// a program that reverses the input, one line at a time.
# define MAXLENGTH 1000
char line[MAXLENGTH];
void reverse(char l[], int length);
int getLine(char l[], int lim);
main(){
int len = 0;
while((len = getLine(line, MAXLENGTH)) != 0){
reverse(line,len);
printf("%s\n",line);
}
return 0;
}
int getLine(char line[], int lim){
char c;
int charC = 0;
while((c = getchar()) != '\n' && c != EOF && charC < lim - 1){
line[charC] = c;
++charC;
}
return charC;
}
void reverse(char line[], int len){
int i1 = 0, i2 = len-1;
char temp;
while(i1 < len/2){
temp = line[i1];
line[i1] = line[i2];
line[i2] = temp;
++i1;
--i2;
}
line[len] = '\0';
}
|
C
|
/*for undirected graph by adjacency matrix*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct adjmat
{
int v;
int e;
int **adj;
};
struct adjmat* graph()
{
int i,j,w,m,n;
char x,y;
struct adjmat *z=(struct adjmat*)malloc(sizeof(struct adjmat));
printf("Enter the number of vertex and edge\n");
scanf("%d %d",&z->v,&z->e);
z->adj=(int**)malloc(sizeof(int*)*z->v);
for(i=0;i<z->v;i++)
{
z->adj[i]=(int*)malloc(sizeof(int)*z->v);
}
for(i=0;i<z->v;i++)
{
for(j=0;j<z->v;j++)
{
z->adj[i][j]=0;
}
}
for(i=0;i<z->e;i++)
{
printf("Enter the edges of graph and their weight\n");
scanf(" %c %c %d",&x,&y,&w);
x=toupper(x);
y=toupper(y);
m=x-'A';
n=y-'A';
// printf("\n%d %d\n",m,n);
z->adj[m][n]=w;
z->adj[n][m]=w;
}
return z;
}
void printgraph(struct adjmat*z)
{
int i,j;
printf("\nOutput for undirected graph:-\n");
for(i=0;i<z->v;i++)
{
for(j=0;j<z->v;j++)
{
printf(" %d ",z->adj[i][j]);
}
printf("\n");
}
}
int main()
{
struct adjmat*m=graph();
printgraph(m);
return 0;
}
|
C
|
#include <stdio.h>
void merge(int ary1[5], int ary2[5], int ary3[10]);
int main(void)
{
int ary1[5], ary2[5];
int ary3[10];
int i;
printf("Input arrayA: ");
for(i = 0; i<5; i++)
{
scanf("%d", &ary1[i]);
}
printf("Input arrayB: ");
for(i = 0; i< 5; i++)
{
scanf("%d", &ary2[i]);
}
merge(ary1, ary2, ary3);
printf("Merged array: ");
for(i = 0 ; i <10 ; i++)
printf("%d ", ary3[i]);
printf("\n");
return 0;
}
void merge(int ary1[5], int ary2[5], int ary3[10])
{
int i, j;
int temp;
for(i = 0; i<5; i++)
ary3[i] = ary1[i];
for(i = 0; i<5; i++)
ary3[i+5] = ary2[i];
for(i = 0; i<9; i++)
{
for(j = 0; j<(9-i); j++)
{
if(ary3[j]>= ary3[j+1])
{
temp = ary3[j];
ary3[j] = ary3[j+1];
ary3[j+1] = temp;
}
}
}
}
|
C
|
#include<stdio.h>
#include<GL/gl.h>
#include<GL/glut.h>
#include<string.h>
#include<math.h>
/* Function that returns -1,0,1 depending on whether x */
/* is <0, =0, >0 respectively */
#define sign(x) ((x>0)?1:((x<0)?-1:0))
int ww = 640, wh = 480;
int first = 0;
int xi, yi, xf, yf;
int count=0;
int xmin=-50,ymin=-50,xmax=50,ymax=50;//view port dimensions
void setPixel(GLint x, GLint y) {
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
}
void breshmans(int x1, int y1, int x2, int y2)
{
int dx,dy,Po;
int k=0;
dx=(x2-x1);
dy=(y2-y1);
if(dy<=dx&&dy>0)
{
dx=abs(dx);
dy=abs(dy);
Po=(2*dy)-dx;
setPixel(x1,y1);
int xk=x1;
int yk=y1;
for(k=x1;k<x2;k++)
{
if(Po<0)
{
setPixel(++xk,yk);
Po=Po+(2*dy);
}
else{
setPixel(++xk,++yk);
Po=Po+(2*dy)-(2*dx);
}
}
}
else if(dy>dx&&dy>0)
{
dx=abs(dx);
dy=abs(dy);
Po=(2*dx)-dy;
setPixel(x1,y1);
int xk=x1; int yk=y1;
for(k=y1;k<y2;k++)
{
if(Po<0)
{
setPixel(xk,++yk);
Po=Po+(2*dx);
}
else{
setPixel(++xk,++yk);
Po=Po+(2*dx)-(2*dy);
}
}
}
else if(dy>=-dx)
{
dx=abs(dx);
dy=abs(dy);
Po=(2*dy)-dx;
setPixel(x1,y1);
int xk=x1;
int yk=y1;
for(k=x1;k<x2;k++)
{
if(Po<0)
{
setPixel(++xk,yk);
Po=Po+(2*dy);
}
else{
setPixel(++xk,--yk);
Po=Po+(2*dy)-(2*dx);
}
}
}
else if(dy<-dx)
{
dx=abs(dx);
dy=abs(dy);
Po=(2*dy)-dx;
setPixel(x1,y1);
int xk=x1;
int yk=y1;
for(k=y1;k>y2;k--)
{
if(Po<0)
{
setPixel(xk,--yk);
Po=Po+(2*dx);
}
else{
setPixel(++xk,--yk);
Po=Po+(2*dx)-(2*dy);
}
}
}
glFlush();
}
int test(float p,float q,float *t1,float *t2)
{
float r;
int ret = true;
if(p<0.0){
r=q/p;
if(r>*t2)
ret= false;
else if(r>*t1)
{*t1 = r;}
}
else if(p>0.0){
r= q/p;
if(r<*t1)
ret = false;
else if(r<*t2)
{*t2 = r;}
}
else
{
if(q<0.0)
{ret=false;
}
}
return ret;
}
void lineclip(int xmin,int ymin,int xmax,int ymax, int x1,int y1,int x2,int y2)
{
float t1=0.0,t2=1.0,dx=x2-x1;
//intilaizeP( dx, dy);
//intilaizeQ(x1,y1);
if(test(-dx,x1-xmin,&t1,&t2))
if(test(dx,xmax-x1,&t1,&t2)){
float dy=y2-y1;
if(test(-dy,y1-ymin,&t1,&t2))
if(test(dy,ymax-y1,&t1,&t2)){
if(t2<1.0)
{
x2=x1+t2*dx;
y2=y1+t2*dy;
}
if(t1>0.0){
x1=x1+t1*dx;
y1=y1+t1*dy;
}
glColor3f(0.0,1.0,0.0);
breshmans(x1,y1,x2,y2);
}
}
}
int X1, Y1, X2, Y2;
void *font = GLUT_BITMAP_TIMES_ROMAN_10;
void *fonts[] = {
GLUT_BITMAP_9_BY_15,
GLUT_BITMAP_TIMES_ROMAN_10,
GLUT_BITMAP_TIMES_ROMAN_24
};
void show(int x, int y, char *string){
int len, i;
glRasterPos2f(x, y);
len = (int) strlen(string);
for (i = 0; i < len; i++)
glutBitmapCharacter(font, string[i]);
}
void draw(void)
{
glClear(GL_COLOR_BUFFER_BIT);
int i;
for(i=-320;i<320;i=i+10)
{
setPixel(i,0);
setPixel(0,i);
}
glFlush();
}
int k;
void Keypress(unsigned char key,int x,int y)
{
glClear(GL_COLOR_BUFFER_BIT);
if(key=='c')
{
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
glColor3f(1.0,0.0,0.0);
glBegin(GL_LINES);
glVertex2i(-50,-50);
glVertex2i(-50,50);
glVertex2i(-50,50);
glVertex2i(50,50);
glVertex2i(50,50);
glVertex2i(50,-50);
glVertex2i(50,-50);
glVertex2i(-50,-50);
glEnd();
glFlush();
lineclip(xmin,ymin,xmax,ymax,xi,yi,xf,yf);
}
}
void mouse(int btn, int state, int x, int y)
{
if(btn==GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
char initial[10];
char final[10];
switch(first)
{
case 0:
xi = x-320;
yi = 240-y;
first = 1;
sprintf(initial,"X=%d,Y=%d",xi,yi);
show(xi+5,yi,initial);
break;
case 1:
xf = x-320;
yf = 240-y;
sprintf(final,"X=%d,Y=%d",xf,yf);
show(xf+5,yf,final);
if(xi>xf)
{
int temp=xi;
xi=xf;
xf=temp;
temp=yi;
yi=yf;
yf=temp;
}
breshmans( xi, yi, xf, yf);
first = 0;
break;
}
}
}
void init() {
glViewport(-320,0,320,0);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowPosition(0,0);
glutInitWindowSize(ww, wh);
glutCreateWindow("assignment 2 ");
glClearColor(0.0,0.0,0.0,0);
glColor3f(1.0,1.0,1.0);
gluOrtho2D(-320,320,-240,240);
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
init();
glutDisplayFunc(draw);
glutMouseFunc(mouse);
glutKeyboardFunc(Keypress);
glutMainLoop();
return 0;
}
|
C
|
#include "../opcode.h"
/*
struct opcode_group_one_byte
{
unsigned char byte; the byte of the main opcode
unsigned char reg; what must modrm->reg be ?
enum mode mode; default operand mode
unsigned short operand1; flags
unsigned short operand2; flags
enum opcodes opcode; / constant for mnemonics
};
*/
struct opcode_group_one_byte one_byte_opcode_groups[] =
{
/** okay 0x80 and 0x81 are COMPLETELY EQUIVALENT to 0x82 and 0x83, respectively.
* Instead of using this to my advantage and coming up with some table that
* reduces memory usage, I just duplicated them.
* I might do thatl ater, but premature optimization is never a good idea. */
{0x80, 0, MODE_8, FLG_RM, FLG_IMM8, OPC_ADD },
{0x80, 1, MODE_8, FLG_RM, FLG_IMM8, OPC_OR },
{0x80, 2, MODE_8, FLG_RM, FLG_IMM8, OPC_ADC },
{0x80, 3, MODE_8, FLG_RM, FLG_IMM8, OPC_SBB },
{0x80, 4, MODE_8, FLG_RM, FLG_IMM8, OPC_AND },
{0x80, 5, MODE_8, FLG_RM, FLG_IMM8, OPC_SUB },
{0x80, 6, MODE_8, FLG_RM, FLG_IMM8, OPC_XOR },
{0x80, 7, MODE_8, FLG_RM, FLG_IMM8, OPC_CMP },
{0x80, 0, MODE_8, FLG_RM, FLG_IMM8, OPC_ADD },
{0x81, 0, MODE_DEFAULT, FLG_RM, FLG_IMM, OPC_ADD },
{0x81, 1, MODE_DEFAULT, FLG_RM, FLG_IMM, OPC_OR },
{0x81, 2, MODE_DEFAULT, FLG_RM, FLG_IMM, OPC_ADC },
{0x81, 3, MODE_DEFAULT, FLG_RM, FLG_IMM, OPC_SBB },
{0x81, 4, MODE_DEFAULT, FLG_RM, FLG_IMM, OPC_AND },
{0x81, 5, MODE_DEFAULT, FLG_RM, FLG_IMM, OPC_SUB },
{0x81, 6, MODE_DEFAULT, FLG_RM, FLG_IMM, OPC_XOR },
{0x81, 7, MODE_DEFAULT, FLG_RM, FLG_IMM, OPC_CMP },
{0x82, 0, MODE_8, FLG_RM, FLG_IMM8, OPC_ADD },
{0x82, 1, MODE_8, FLG_RM, FLG_IMM8, OPC_OR },
{0x82, 2, MODE_8, FLG_RM, FLG_IMM8, OPC_ADC },
{0x82, 3, MODE_8, FLG_RM, FLG_IMM8, OPC_SBB },
{0x82, 4, MODE_8, FLG_RM, FLG_IMM8, OPC_AND },
{0x82, 5, MODE_8, FLG_RM, FLG_IMM8, OPC_SUB },
{0x82, 6, MODE_8, FLG_RM, FLG_IMM8, OPC_XOR },
{0x82, 7, MODE_8, FLG_RM, FLG_IMM8, OPC_CMP },
{0x82, 0, MODE_8, FLG_RM, FLG_IMM8, OPC_ADD },
{0x83, 0, MODE_DEFAULT, FLG_RM, FLG_IMM8, OPC_ADD },
{0x83, 1, MODE_DEFAULT, FLG_RM, FLG_IMM8, OPC_OR },
{0x83, 2, MODE_DEFAULT, FLG_RM, FLG_IMM8, OPC_ADC },
{0x83, 3, MODE_DEFAULT, FLG_RM, FLG_IMM8, OPC_SBB },
{0x83, 4, MODE_DEFAULT, FLG_RM, FLG_IMM8, OPC_AND },
{0x83, 5, MODE_DEFAULT, FLG_RM, FLG_IMM8, OPC_SUB },
{0x83, 6, MODE_DEFAULT, FLG_RM, FLG_IMM8, OPC_XOR },
{0x83, 7, MODE_DEFAULT, FLG_RM, FLG_IMM8, OPC_CMP },
{0xC0, 0, MODE_8, FLG_RM, FLG_IMM8, OPC_ROL},
{0xC0, 1, MODE_8, FLG_RM, FLG_IMM8, OPC_ROR},
{0xC0, 2, MODE_8, FLG_RM, FLG_IMM8, OPC_RCL},
{0xC0, 3, MODE_8, FLG_RM, FLG_IMM8, OPC_RCR},
{0xC0, 4, MODE_8, FLG_RM, FLG_IMM8, OPC_SHL},
{0xC0, 5, MODE_8, FLG_RM, FLG_IMM8, OPC_SHR},
{0xC0, 6, MODE_8, FLG_RM, FLG_IMM8, OPC_SAL},
{0xC0, 7, MODE_8, FLG_RM, FLG_IMM8, OPC_SAR},
{0xC1, 0, MODE_DEFAULT, FLG_RM, FLG_IMM8, OPC_ROL},
{0xC1, 1, MODE_DEFAULT, FLG_RM, FLG_IMM8, OPC_ROR},
{0xC1, 2, MODE_DEFAULT, FLG_RM, FLG_IMM8, OPC_RCL},
{0xC1, 3, MODE_DEFAULT, FLG_RM, FLG_IMM8, OPC_RCR},
{0xC1, 4, MODE_DEFAULT, FLG_RM, FLG_IMM8, OPC_SHL},
{0xC1, 5, MODE_DEFAULT, FLG_RM, FLG_IMM8, OPC_SHR},
{0xC1, 6, MODE_DEFAULT, FLG_RM, FLG_IMM8, OPC_SAL},
{0xC1, 7, MODE_DEFAULT, FLG_RM, FLG_IMM8, OPC_SAR},
{0xC6, 0, MODE_8, FLG_RM, FLG_IMM8, OPC_MOV},
{0xC7, 0, MODE_DEFAULT, FLG_RM, FLG_IMM, OPC_MOV},
{0xD0, 0, MODE_8, FLG_RM, FLG_CONST_1, OPC_ROL},
{0xD0, 1, MODE_8, FLG_RM, FLG_CONST_1, OPC_ROR},
{0xD0, 2, MODE_8, FLG_RM, FLG_CONST_1, OPC_RCL},
{0xD0, 3, MODE_8, FLG_RM, FLG_CONST_1, OPC_RCR},
{0xD0, 4, MODE_8, FLG_RM, FLG_CONST_1, OPC_SHL},
{0xD0, 5, MODE_8, FLG_RM, FLG_CONST_1, OPC_SHR},
{0xD0, 6, MODE_8, FLG_RM, FLG_CONST_1, OPC_SAL},
{0xD0, 7, MODE_8, FLG_RM, FLG_CONST_1, OPC_SAR},
{0xD1, 0, MODE_DEFAULT, FLG_RM, FLG_CONST_1, OPC_ROL},
{0xD1, 1, MODE_DEFAULT, FLG_RM, FLG_CONST_1, OPC_ROR},
{0xD1, 2, MODE_DEFAULT, FLG_RM, FLG_CONST_1, OPC_RCL},
{0xD1, 3, MODE_DEFAULT, FLG_RM, FLG_CONST_1, OPC_RCR},
{0xD1, 4, MODE_DEFAULT, FLG_RM, FLG_CONST_1, OPC_SHL},
{0xD1, 5, MODE_DEFAULT, FLG_RM, FLG_CONST_1, OPC_SHR},
{0xD1, 6, MODE_DEFAULT, FLG_RM, FLG_CONST_1, OPC_SAL},
{0xD1, 7, MODE_DEFAULT, FLG_RM, FLG_CONST_1, OPC_SAR},
{0xD2, 0, MODE_8, FLG_RM, FLG_REG_CONST | CL | FLG_8BIT, OPC_ROL},
{0xD2, 1, MODE_8, FLG_RM, FLG_REG_CONST | CL | FLG_8BIT, OPC_ROR},
{0xD2, 2, MODE_8, FLG_RM, FLG_REG_CONST | CL | FLG_8BIT, OPC_RCL},
{0xD2, 3, MODE_8, FLG_RM, FLG_REG_CONST | CL | FLG_8BIT, OPC_RCR},
{0xD2, 4, MODE_8, FLG_RM, FLG_REG_CONST | CL | FLG_8BIT, OPC_SHL},
{0xD2, 5, MODE_8, FLG_RM, FLG_REG_CONST | CL | FLG_8BIT, OPC_SHR},
{0xD2, 6, MODE_8, FLG_RM, FLG_REG_CONST | CL | FLG_8BIT, OPC_SAL},
{0xD2, 7, MODE_8, FLG_RM, FLG_REG_CONST | CL | FLG_8BIT, OPC_SAR},
{0xD3, 0, MODE_DEFAULT, FLG_RM, FLG_REG_CONST | CL | FLG_8BIT, OPC_ROL},
{0xD3, 1, MODE_DEFAULT, FLG_RM, FLG_REG_CONST | CL | FLG_8BIT, OPC_ROR},
{0xD3, 2, MODE_DEFAULT, FLG_RM, FLG_REG_CONST | CL | FLG_8BIT, OPC_RCL},
{0xD3, 3, MODE_DEFAULT, FLG_RM, FLG_REG_CONST | CL | FLG_8BIT, OPC_RCR},
{0xD3, 4, MODE_DEFAULT, FLG_RM, FLG_REG_CONST | CL | FLG_8BIT, OPC_SHL},
{0xD3, 5, MODE_DEFAULT, FLG_RM, FLG_REG_CONST | CL | FLG_8BIT, OPC_SHR},
{0xD3, 6, MODE_DEFAULT, FLG_RM, FLG_REG_CONST | CL | FLG_8BIT, OPC_SAL},
{0xD3, 7, MODE_DEFAULT, FLG_RM, FLG_REG_CONST | CL | FLG_8BIT, OPC_SAR},
{0xF6, 0, MODE_8, FLG_RM, FLG_IMM8, OPC_TEST},
{0xF6, 1, MODE_8, FLG_RM, FLG_IMM8, OPC_TEST},
{0xF6, 2, MODE_8, FLG_RM, FLG_NONE, OPC_NOT},
{0xF6, 3, MODE_8, FLG_RM, FLG_NONE, OPC_NEG},
{0xF6, 4, MODE_8, FLG_RM, FLG_NONE, OPC_MUL},
{0xF6, 5, MODE_8, FLG_RM, FLG_NONE, OPC_IMUL},
{0xF6, 6, MODE_8, FLG_RM, FLG_NONE, OPC_DIV},
{0xF6, 7, MODE_8, FLG_RM, FLG_NONE, OPC_IDIV},
{0xF7, 0, MODE_DEFAULT, FLG_RM, FLG_IMM, OPC_TEST},
{0xF7, 1, MODE_DEFAULT, FLG_RM, FLG_IMM, OPC_TEST},
{0xF7, 2, MODE_DEFAULT, FLG_RM, FLG_NONE, OPC_NOT},
{0xF7, 3, MODE_DEFAULT, FLG_RM, FLG_NONE, OPC_NEG},
{0xF7, 4, MODE_DEFAULT, FLG_RM, FLG_NONE, OPC_MUL},
{0xF7, 5, MODE_DEFAULT, FLG_RM, FLG_NONE, OPC_IMUL},
{0xF7, 6, MODE_DEFAULT, FLG_RM, FLG_NONE, OPC_DIV},
{0xF7, 7, MODE_DEFAULT, FLG_RM, FLG_NONE, OPC_IDIV},
{0xFE, 0, MODE_8, FLG_RM, FLG_NONE, OPC_INC},
{0xFE, 1, MODE_8, FLG_RM, FLG_NONE, OPC_DEC},
{0xFF, 0, MODE_DEFAULT, FLG_RM, FLG_NONE, OPC_INC},
{0xFF, 1, MODE_DEFAULT, FLG_RM, FLG_NONE, OPC_DEC},
/** IFFY ON 3 AND 5 (CALLF AND JMP) */
{0xFF, 2, MODE_DEFAULT, FLG_RM, FLG_NONE, OPC_CALL},
{0xFF, 3, MODE_DEFAULT, FLG_PTR16, FLG_NONE, OPC_CALL},
{0xFF, 4, MODE_DEFAULT, FLG_RM, FLG_NONE, OPC_JMP},
{0xFF, 5, MODE_DEFAULT, FLG_PTR16, FLG_NONE, OPC_CALL},
/* for some reason (google isn't available with no internet), I can't use sizeof() on an
* extern struct [] of this type so I'm marking the end of the array with a bunch of nuls*/
{0,0,0,0,0,0}
};
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
typedef struct _student_info{
unsigned char student_id[20];
unsigned char department_id;
unsigned char department_name[40];
unsigned char grade;
unsigned char name[80];
unsigned char birthday[20];
}student_info;
void Selection_Sort(student_info * p, int cnt, int choice){
int i, j, least;
student_info temp;
switch (choice)
{
case 1://й
for(i=0; i<cnt-1; i++){
least=i;
for(j=i+1; j<cnt; j++){
if(atoi(p[j].student_id) < atoi(p[least].student_id)) least=j;
temp=p[i];
p[i]=p[least];
p[least]=temp;
}
}
break;
case 2://
for(i=0; i<cnt-1; i++){
least=i;
for(j=i+1; j<cnt; j++){
if(strcmp(p[j].name, p[least].name)<0) least=j;
temp=p[i];
p[i]=p[least];
p[least]=temp;
}
}
break;
case 3://а
for(i=0; i<cnt-1; i++){
least=i;
for(j=i+1; j<cnt; j++){
if(strcmp(p[j].department_name, p[least].department_name)<0) least=j;
temp=p[i];
p[i]=p[least];
p[least]=temp;
}
}
break;
case 4://г
for(i=0; i<cnt-1; i++){
least=i;
for(j=i+1; j<cnt; j++){
if(p[j].grade < p[least].grade) least=j;
temp=p[i];
p[i]=p[least];
p[least]=temp;
}
}
break;
case 5://
for(i=0; i<cnt-1; i++){
least=i;
for(j=i+1; j<cnt; j++){
if(strcmp(p[j].birthday, p[least].birthday)<0) least=j;
temp=p[i];
p[i]=p[least];
p[least]=temp;
}
}
break;
}
}
void Insertion_Sort(student_info * p, int cnt, int choice){
int i, j;
student_info key;
switch (choice)
{
case 1://й
for(i=0; i<cnt; i++){
key=p[i];
for(j=i-1; j>=0 && atoi(p[j].student_id)> atoi(key.student_id); j--){
p[j+1]=p[j];
}
}
break;
case 2://
for(i=0; i<cnt; i++){
key=p[i];
for(j=i-1; j>=0 && strcmp(p[j].name, key.name)>0 ; j--){
p[j+1]=p[j];
}
}
break;
case 3://а
for(i=0; i<cnt; i++){
key=p[i];
for(j=i-1; j>=0 && strcmp(p[j].department_name, key.department_name)>0 ; j--){
p[j+1]=p[j];
}
}
break;
case 4://г
for(i=0; i<cnt; i++){
key=p[i];
for(j=i-1; j>=0 && p[j].grade > key.grade ; j--){
p[j+1]=p[j];
}
}
break;
case 5://
for(i=0; i<cnt; i++){
key=p[i];
for(j=i-1; j>=0 && strcmp(p[j].birthday, key.birthday)>0 ; j--){
p[j+1]=p[j];
}
}
break;
}
}
void Bubble_Sort(student_info * p, int cnt, int choice){
int i, j;
student_info temp;
switch (choice)
{
case 1://й
for(i=cnt; i>0; i--){
for(j=0; j<i-1; j++){
if(atoi(p[j].student_id) > atoi(p[j+1].student_id)){
temp=p[j];
p[j]=p[j+1];
p[j+1]=temp;
}
}
}
break;
case 2://
for(i=cnt; i>0; i--){
for(j=0; j<i-1; j++){
if(strcmp(p[j].name, p[j+1].name)>0){
temp=p[j];
p[j]=p[j+1];
p[j+1]=temp;
}
}
}
break;
case 3://а
for(i=cnt; i>0; i--){
for(j=0; j<i-1; j++){
if(strcmp(p[j].department_name, p[j+1].department_name)>0){
temp=p[j];
p[j]=p[j+1];
p[j+1]=temp;
}
}
}
break;
case 4://г
for(i=cnt; i>0; i--){
for(j=0; j<i-1; j++){
if(p[j].grade>p[j+1].grade){
temp=p[j];
p[j]=p[j+1];
p[j+1]=temp;
}
}
}
break;
case 5://
for(i=cnt; i>0; i--){
for(j=0; j<i-1; j++){
if(strcmp(p[j].birthday, p[j+1].birthday)>0){
temp=p[j];
p[j]=p[j+1];
p[j+1]=temp;
}
}
}
break;
}
}
void print(student_info * p, int cnt)
{
int i;
printf("student_id\tdepartment_id\tdepartment_name\t\tgrade\t\tname\tbirthday\n");
for(i=0; i<cnt; i++){
printf("%10s\t%13c\t%15s\t%10c\t%10s\t%8s\n",p[i].student_id, p[i].department_id, p[i].department_name, p[i].grade, p[i].name, p[i].birthday);
}
}
int main(int argc, char *argv[]){
FILE *fp;
fp=fopen("students.txt", "r"); //
int choice;
int cnt, i, num;// Max: л , i: ü
char buf[100];
struct timeb prev, next;// ms
long long int prev_sec, next_sec, duration;
student_info * pFile= (student_info *)malloc(sizeof(student_info)*100); //Ҵ
//
if(fp==NULL){
printf("err \n");
return -1;
}
fgets(buf,100,fp);// students.txt ù° б
i=0;
while(!feof(fp))//ϵ о ü ҴϿ
{
fscanf(fp, "%s %c %s %c %s %s", &pFile[i].student_id, &pFile[i].department_id, &pFile[i].department_name, &pFile[i].grade, &pFile[i].name, &pFile[i].birthday);
i++;
cnt=i;
}
while(1){
printf("ϰ ϴ ʵ带 ϼ. (й: 1, : 2, а: 3, г: 4, : 5)\n\t-->");
scanf("%d", &choice);
/******************** ****************************************/
printf("Selection Sorting...\n");
ftime(&prev);
printf("prev time- %u.%03u\n", prev.time, prev.millitm);
Selection_Sort(pFile, cnt, choice);
ftime(&next);
printf("prev time- %u.%03u\n", next.time, next.millitm);
prev_sec=prev.time*1000+prev.millitm;
next_sec=next.time*1000+next.millitm;
duration=next_sec-prev_sec;
printf("ɸ ð: %d\n", duration);
print(pFile, cnt);
printf("\n\n");
/******************** ****************************************/
printf("Insertion Sorting...\n");
ftime(&prev);
printf("prev time- %u.%03u\n", prev.time, prev.millitm);
Insertion_Sort(pFile, cnt, choice);
ftime(&next);
printf("prev time- %u.%03u\n", next.time, next.millitm);
prev_sec=prev.time*1000+prev.millitm;
next_sec=next.time*1000+next.millitm;
duration=next_sec-prev_sec;
printf("ɸ ð: %d\n", duration);
print(pFile, cnt);
printf("\n\n");
/******************** ****************************************/
printf("Bubble Sorting...\n");
ftime(&prev);
printf("prev time- %u.%03u\n", prev.time, prev.millitm);
Bubble_Sort(pFile, cnt, choice);
ftime(&next);
printf("prev time- %u.%03u\n", next.time, next.millitm);
prev_sec=prev.time*1000+prev.millitm;
next_sec=next.time*1000+next.millitm;
duration=next_sec-prev_sec;
printf("ɸ ð: %d\n", duration);
print(pFile, cnt);
printf("\n\n");
}
free(pFile);
fclose(fp);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define TURE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
typedef int KeyType;
typedef struct BiTNode{
KeyType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
Status Visit(KeyType e)
{
printf("%d\n",e);
return OK;
}
Status SearchBST(BiTree T,KeyType key,BiTree f,BiTree *p) {
if (!T) {
*p = f;
return FALSE;
} else if (key == (T->data)) {
*p=T;
return TURE;
} else if(key<(T->data)){
return SearchBST(T->lchild,key,T,p);
}else{
return SearchBST(T->rchild,key,T,p);
}
}
Status insertBSF(BiTree *T,KeyType keyType){
BiTree p,s;
if(!SearchBST(*T,keyType, NULL,&p)){
s=(BiTree)malloc(sizeof(BiTNode));
s->data=keyType;
s->lchild=NULL;
s->rchild=NULL;
if(!p){
*T=s;
}else if(keyType < p->data){
p->lchild=s;
}else{
p->rchild=s;
}
return TURE;
} else{
return FALSE;
}
}
Status InOrderTraverse(BiTree T,Status(*Visit)(KeyType e))
{
if(T){
if(InOrderTraverse(T->lchild,Visit))
if(Visit(T->data))
if(InOrderTraverse(T->rchild,Visit)) return OK;
return ERROR;
}else {
return OK;
}
}
Status Delete(BiTree *p){
BiTree q,s;
if(!(*p)->rchild){
q=*p;
*p=(*p)->lchild;
free(q);
}else if(!(*p)->lchild){
q=*p;
*p=(*p)->rchild;
free(q);
}else{
q=*p;
s=(*p)->lchild;
while(s->rchild){
q=s;
s=s->rchild;
}
(*p)->data=s->data;
if(q!=(*p)){
q->rchild=s->lchild;
}else{
q->lchild=s->lchild;
}
free(s);
}
return TURE;
}
Status DeleteBSF(BiTree T,KeyType key){
if(!T){
return FALSE;
}else{
if(key == T->data){
return Delete(&T);
}else if(key < (T->data)){
return DeleteBSF(T->lchild,key);
}else{
return DeleteBSF(T->rchild,key);
}
}
}
int main()
{
BiTree T=NULL;
int n;
printf("ڵĸ:");
scanf("%d",&n);
int a[n];
int i,j,k;
for(i=0;i<n;i++){
printf("ڵֵ:");
scanf("%d",&a[i]);
}
for(j=0;j<n;j++){
insertBSF(&T,a[j]);
}
InOrderTraverse(T,Visit);
printf("############\n");
printf("please input the delete node:");
scanf("%d",&k);
DeleteBSF(T,k);
InOrderTraverse(T,Visit);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(void){
char string[1024], word[512][16];
gets(string);
printf("%s\n",string);
int i, len = strlen(string);
int if_l = 0, if_n = 0, count = -1, k = 0;
for(i = 0; i < len; i++){
if((string[i] >= 'a' && string[i] <= 'z') || (string[i] >= 'A' && string[i] <= 'Z'))
if_n = 1;
else if_n = 0;
if(if_n && !if_l){
k = 0;
word[++count][k++] = string[i];
}
else if(if_n && if_l) word[count][k++] = string[i];
else if(!if_n && if_l) if(~count) word[count][k] = '\0';
if_l = if_n;
}
for(i = count; ~i; i--){
printf("%s",word[i]);
}
printf("\n");
return 0;
}
|
C
|
/*
Given a string, reverse only vowels in it. Leave the remaining string as it is.
Input Format
One string.
Constraints
1 <= Length of string <= 10^5
Output Format
One string, the original string with vowels reversed.
Sample Input 0
trumpisshit
Sample Output 0
trimpisshut
Explanation 0
vowels occur in the following order : u, i, i. they are reversed to occur in this order : i, i, u.
*/
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
char ch[100005], v[100005];
scanf("%s", ch);
int j=0;
for(int i=0; ch[i]; i++){
if(ch[i]=='a' ||ch[i]=='e' || ch[i]=='i' || ch[i]=='o' || ch[i]=='u')
v[j++]=ch[i];
}
j=j-1;
for(int i=0; ch[i]; i++)
{
if(ch[i]=='a' ||ch[i]=='e' || ch[i]=='i' || ch[i]=='o' || ch[i]=='u') printf("%c", v[j--]);
else printf("%c", ch[i]);
}
return 0;
}
|
C
|
#include "ArrayList.h"
#ifndef _DEPOSITOS_H
#define _DEPOSITOS_H
typedef struct
{
int idProducto;
char descripcion[50];
int cantidad;
}Depositos;
#endif// _DEPOSITOS_H
Depositos* depositos_new(int idProducto,char* descripcion,int cantidad);
void depositos_delete(Depositos* this);
int depositos_setIdProducto(Depositos* this,int idProducto);
int depositos_setDescripcion(Depositos* this,char* descripcion);
int depositos_setCantidad(Depositos* this,int cantidad);
int depositos_getIdProducto(Depositos* this);
char* depositos_getDescripcion(Depositos* this);
int depositos_getCantidad(Depositos* this);
Depositos* depositos_findByIdProducto(ArrayList* pArray,int idProducto);
Depositos* depositos_findByDescripcion(ArrayList* pArray,char* descripcion);
Depositos* depositos_findByCantidad(ArrayList* pArray,int cantidad);
int depositos_compareByIdProducto(void* pA ,void* pB);
int depositos_compareByDescripcion(void* pA ,void* pB);
int depositos_compareByCantidad(void* pA ,void* pB);
|
C
|
/*
* trsm.h
*/
#pragma once
#include <stdio.h>
#include "matrix.h"
#include "gemm.h"
void trsm_loop(matrix L, matrix B) {
long m = B.n_rows;
long n = B.n_cols;
long i, j, k;
/* n * (m + (m - 1) + ... + 1)
= 1/2 n m (m + 1) */
for (k = 0; k < m; k++) {
real lkk_inv = 1.0 / L(k,k);
/* n (m - k) in this iteration */
/* n */
for (j = 0; j < n; j++)
B(k,j) *= lkk_inv;
/* n * (m - k - 1) */
for (i = k + 1; i < m; i++) {
for (j = 0; j < n; j++) {
B(i,j) -= L(i,k) * B(k,j);
}
}
}
}
void trsm(matrix L, matrix B) {
long m = B.n_rows;
long n = B.n_cols;
assert(m == L.n_rows);
assert(m == L.n_cols);
if (sizeof(real) * m * (m + n) < trsm_threshold) {
trsm_loop(L, B);
} else if (m < n) {
matrix B_[2];
split_v(B, B_);
trsm(L, B_[0]);
trsm(L, B_[1]);
} else {
matrix L_[2][2], B_[2];
split_hv(L, L_);
split_h(B, B_);
trsm(L_[0][0], B_[0]);
gemm_minus(L_[1][0], B_[0], B_[1]);
trsm(L_[1][1], B_[1]);
}
}
int trsm_main(int argc, char ** argv) {
long M = atol(argv[1]);
long N = atol(argv[2]);
int repeat = atoi(argv[3]);
int r;
matrix A(M, M);
matrix X(M, N);
matrix C(M, N);
for (r = 0; r < repeat; r++) {
gen_const_lower_matrix(A, 1.0);
gen_random_matrix(X);
gen_const_matrix(C, 0.0);
gemm_plus(A, X, C);
unsigned long long t0 = rdtscp();
trsm(A, C); // X := A^{-1} C
unsigned long long t1 = rdtscp();
unsigned long long flops = M * (M + 1) * N / 2;
printf("%llu flops/%llu clocks = %f flops/clock\n",
flops, t1 - t0, (double)flops/(double)(t1 - t0));
}
if (matrix_equal(X, C)) {
printf("OK\n");
} else {
printf("NG\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <malloc.h>
int func(int n)
{
int i = 0;
int ret = 0;
int* p = (int*)malloc(sizeof(int) * n);
do
{
if( NULL == p ) break; // 注意这里break的用法
if( n < 5 ) break;
if( n > 100) break;
for(i=0; i<n; i++)
{
p[i] = i;
printf("%d\n", p[i]);
}
ret = 1;
}while( 0 );
printf("free(p)\n");
free(p); // 在任何情况下,free(p)都会被执行,不会泄露内存
return ret;
}
int main()
{
if( func(4) )
{
printf("OK\n");
}
else
{
printf("ERROR\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, x1, y1, x2, y2, i, j;
int** a;
scanf("%d", &n);
a = (int**)malloc((n + 1) * sizeof(int*));
for (i = 1; i <= n; i++){
a[i] = (int*)malloc((n + 1) * sizeof(int));
}
while (1){
scanf("%d", &x1);
if (x1 == 0){
break;
}
scanf("%d %d %d", &y1, &x2, &y2);
for (i = 1; i <= n; i++){
for (j = 1; j <= n; j++){
a[i][j] = i * j;
}
}
for (i = y1; i <= y2; i++, printf("\n"))
for (j = x1; j <= x2; j++)
printf("%*d",7, a[i][j]);
}
for (i = 1; i <= n; i++){
free(a[i]);
a[i] = NULL;
}
free(a);
a = NULL;
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <sys/types.h>
#include "function.h"
#include "pile.h"
#define LG_CHAINE 1024
int *adjM = NULL; // pointeur d'attachement shared memory == matrice d'adjacence
/*
1- Haut
2- Droite
3- Bas
4- Gauche
i = ligne
j = colonne*/
void SetCursorPos(int YPos, int XPos) {
printf("[%d;%d]", YPos + 1, XPos + 1);
//printf("%c[%d;%d]", 0x1B, YPos, XPos);
}
void generateMaze(int M, int N, int sem) {
//tab pour générer le lab
int tabV[M][N];
int tabX[M + 1][N];
int tabY[M][N + 1];
int matAdj[M][N];
int a, b;
int dirTab[4];
//flag pour le check des directions;
int isValidDirect = 0;
int isValidUp = 0;
int isValidRight = 0;
int isValidDown = 0;
int isValidLeft = 0;
int lastdir = 0;
int dir = 0;
//struct utile pour stocker le parcours de l'algo
srand(time(NULL));
int i = (rand() % M);
int j = (rand() % N);
int cpt = 0;
int nbCases = M * N;
Pile *maPile = initialiser();
Coord coordTemp;
Coord depart;
Coord arrive;
//j'initialise les tabs à 0
for (a = 0; a < M; a++) {
for (b = 0; b < N; b++) {
tabV[a][b] = 0;
}
}
for (a = 0; a < M; a++) {
for (b = 0; b < N; b++) {
matAdj[a][b] = 0;
}
}
for (a = 0; a < M + 1; a++) {
for (int b = 0; b < N; b++) {
tabX[a][b] = 0;
}
}
for (a = 0; a < M; a++) {
for (b = 0; b < N + 1; b++) {
tabY[a][b] = 0;
}
}
/* ----- DEBUT DE L'ALGO -------*/
printf("%d:%d\n", i, j);
depart.x = i;
depart.y = j;
tabV[i][j] = 1;
//nbCase a parcourir pour arriver au bout de l'algo
printf("nb Cases: %d\n", nbCases);
while (cpt < nbCases - 1) {
//todo tant que inférieur à nb cases (M*N)
//on checke qu'il puisse aller dans une direction random
isValidDirect = 0;
isValidUp = 0;
isValidRight = 0;
isValidDown = 0;
isValidLeft = 0;
dir = 0;
dirTab[0] = 1;
dirTab[1] = 2;
dirTab[2] = 3;
dirTab[3] = 4;
//tant que la direction n'est pas bonne
do {
printf("je commence le do\n");
printf("position de V=>%d:%d\n", i, j);
tabV[i][j] = 1;
printf("^:%d/>:%d/v:%d/<:%d \n", isValidUp, isValidRight, isValidDown, isValidLeft);
//si toutes les directions ne sont pas bonnes, on retourne au dernier noeud
if ((isValidUp == -1) && (isValidRight == -1) && (isValidDown == -1) && (isValidLeft == -1)) {
printf("%s\n", "Aucune direction Possible !");
coordTemp = depiler(maPile);
i = coordTemp.x;
j = coordTemp.y;
lastdir = coordTemp.lastDir;
isValidUp = 0;
isValidRight = 0;
isValidDown = 0;
isValidLeft = 0;
printf("Je remonte le noeud=> %d:%d\n", i, j);
break;
}
//on ajoute la direction inversé du predecesseur dans le doute qu'on ne se déplace pas ;)
matAdj[i][j] = lastdir;
//printf("%s\n", "----Ecrire dans SHM---");
setMatAdj_SHM(sem, matAdj[i][j], i, j, M);
//on choisi la direction
rand: dir = dirTab[rand() % 4];
if(dir == -1)
goto rand;
printf("%s\n", "Choix direction");
printf("dir = %d\n", dir);
//checker si c'est pas borné
//faire une liste qui stocke les coordonnées courantes avant de se déplacer
//on check si on a pas déjà visité la case vers où on veut aller
printf("si pas borné\n");
switch (dir) {
case 1:
if (i > 0) {
isValidDirect = 1;
printf("petit check oklm\n");
if (tabV[i - 1][j] != 0) {
isValidDirect = 0;
isValidUp = -1;
dirTab[0] = -1;
}
} else
isValidUp = -1;
break;
case 2:
if (j < M - 1) {
isValidDirect = 1;
printf("petit check oklm\n");
if (tabV[i][j + 1] != 0) {
isValidDirect = 0;
isValidRight = -1;
dirTab[1] = -1;
}
} else
isValidRight = -1;
break;
case 3:
if (i < N - 1) {
isValidDirect = 1;
printf("petit check oklm\n");
if (tabV[i + 1][j] != 0) {
isValidDirect = 0;
isValidDown = -1;
dirTab[2] = -1;
}
} else
isValidDown = -1;
break;
case 4:
if (j > 0) {
isValidDirect = 1;
printf("petit check oklm\n");
if (tabV[i][j - 1] != 0) {
isValidDirect = 0;
isValidLeft = -1;
dirTab[3] = -1;
}
} else
isValidLeft = -1;
break;
default:
break;
}
} while (isValidDirect == 0);
//si on est sorti, peut casser le mur
if (isValidDirect == 1) {
switch (dir) {
case 1:
//on casse le mur
tabX[i][j] = 1;
//on ajoute la matrice d'adjacence
matAdj[i][j] = 1 + matAdj[i][j];
//inverse de la dir courante
lastdir = 4;
//on stocke la position courante
coordTemp.x = i;
coordTemp.y = j;
coordTemp.lastDir = matAdj[i][j];
printf("%s\n", "----Ecrire dans SHM---");
setMatAdj_SHM(sem, matAdj[i][j], i, j, M);
printf("adjacence : %d\n", matAdj[i][j]);
empiler(maPile, coordTemp);
//on se déplace
i--;
//on incrémente le compteur
cpt++;
printf("je monte !\n");
break;
case 2:
tabY[i][j + 1] = 1;
matAdj[i][j] = 2 + matAdj[i][j];
//inverse de la dir courante
lastdir = 8;
coordTemp.x = i;
coordTemp.y = j;
coordTemp.lastDir = matAdj[i][j];
printf("%s\n", "----Ecrire dans SHM---");
setMatAdj_SHM(sem, matAdj[i][j], i, j, M);
printf("adjacence : %d\n", matAdj[i][j]);
empiler(maPile, coordTemp);
j++;
//on incrémente le compteur
cpt++;
printf("je vais à droite !\n");
break;
case 3:
tabX[i + 1][j] = 1;
matAdj[i][j] = 4 + matAdj[i][j];
//inverse de la dir courante
lastdir = 1;
coordTemp.x = i;
coordTemp.y = j;
coordTemp.lastDir = matAdj[i][j];
printf("%s\n", "----Ecrire dans SHM---");
setMatAdj_SHM(sem, matAdj[i][j], i, j, M);
printf("adjacence : %d\n", matAdj[i][j]);
empiler(maPile, coordTemp);
i++;
//on incrémente le compteur
cpt++;
printf("je vais en bas !\n");
break;
case 4:
tabY[i][j] = 1;
matAdj[i][j] = 8 + matAdj[i][j];
//inverse de la dir courante
lastdir = 2;
coordTemp.x = i;
coordTemp.y = j;
coordTemp.lastDir = matAdj[i][j];
printf("%s\n", "----Ecrire dans SHM---");
setMatAdj_SHM(sem, matAdj[i][j], i, j, M);
printf("adjacence : %d\n", matAdj[i][j]);
empiler(maPile, coordTemp);
j--;
//on incrémente le compteur
cpt++;
printf("je vais à gauche !\n");
break;
default:
break;
}
printf("------Fin de l'etape : %d--------\n", cpt);
}
}
//last pos
printf("derniere position de V=>%d:%d\n", i, j);
arrive.x = i;
arrive.y = j;
//je visite la last pos
tabV[i][j] = 1;
//je lui ajoute son adjacence
matAdj[i][j] = lastdir;
setMatAdj_SHM(sem, matAdj[i][j], i, j, M);
printf("derniere adjacence: %d\n", matAdj[i][j]);
//On display les matrices pour vérifier le résultat
printf("%s\n", "Afficher Labyrinthe ?");
printf("%s\n", "--TabV--");
for (a = 0; a < M; a++) {
for (b = 0; b < N; b++) {
printf("%d", tabV[a][b]);
}
printf("\n");
}
printf("%s\n", "--TabX--");
for (a = 0; a < M + 1; a++) {
for (b = 0; b < N; b++) {
printf("%d", tabX[a][b]);
}
printf("\n");
}
printf("%s\n", "--TabY--");
//system("clear");
for (a = 0; a < M; a++) {
for (b = 0; b < N + 1; b++) {
printf("%d", tabY[a][b]);
}
printf("\n");
}
printf("%s\n", "--MatAdj--");
for (a = 0; a < M; a++) {
for (b = 0; b < N; b++) {
printf("%d |", matAdj[a][b]);
}
printf("\n");
}
printf("Depart : %d:%d\n", depart.x, depart.y);
printf("Arrivee : %d:%d\n", arrive.x, arrive.y);
//depart
setMatAdj_SHM(sem, depart.x, M+1, N+1, M);
setMatAdj_SHM(sem, depart.y, M+2, N+2, M);
//arrivee
setMatAdj_SHM(sem, arrive.x, M+3, N+3, M);
setMatAdj_SHM(sem, arrive.y, M+4, N+4, M);
//ligMax
setMatAdj_SHM(sem, M, M+5, N+5, M);
//colMax
setMatAdj_SHM(sem, N, M+6, N+6, M);
/*printf("%s\n", "----Lecture dans SHM----");
for (a = 0; a < M; a++) {
for (b = 0; b < N; b++) {
printf("%d |", getMatAdj_SHM(a, b, M));
}
printf("\n");
}*/
}
int generateMatAdj_SHM(key_t key) {
int shm; // identifiant de la memoire partagee
// creation du segment de memoire partagee
if ((shm = shmget(key, LG_CHAINE, IPC_CREAT | 0600)) == -1) {
perror("shmget");
exit(EXIT_FAILURE);
}
printf("Genere SHM id: %d\n", shm);
printf("%s\n", "----Bind matAdj dans SHM---");
// attachement du segment shm sur le pointeur *chaine
if ((adjM = shmat(shm, NULL, 0)) == (void *) -1) {
perror("shmat");
exit(EXIT_FAILURE);
}
return shm;
}
int generateSem(key_t key)
{
int sem; // identifiant du semaphore
union semun u_semun; // initialisation semaphores
unsigned short table[1]; // table de valeur du semaphore
// acces a l'ensemble semaphore (ensemble de 1 semaphore)
if ((sem = semget(key, 1, 0)) == -1) {
// creation de l'ensemble qui n'existe pas
if ((sem = semget(key, 1, IPC_CREAT | IPC_EXCL | 0600)) == -1) {
perror("semget");
exit(EXIT_FAILURE);
}
// initialisation a vide de la chaine en shm
adjM[0] = '\0';
// initialisation de la table de valeur du compteur
table[0] = 1;
// initalisation du troisieme membre de l'union
u_semun.array = table;
// initialisation de la valeur du compteur dansle semaphore
if (semctl(sem, 0, SETALL, u_semun) < 0) perror("semctl");
}
printf("Genere Sem id: %d\n", sem);
return sem;
}
void setMatAdj_SHM(int sem ,int value, int row, int column, int rowMax) {
//entree en section critique / enfin je crois
P(sem);
adjM[row * rowMax + column] = value;
V(sem);
}
int getMatAdj_SHM(int row, int column, int rowMax) {
//printf("valeur retournee: %d\n", adjM[row * rowMax + column]);
return adjM[row * rowMax + column];
}
void destroyMatAdj_SHM(int shm) {
printf("Destruction SHM id: %d\n", shm);
shmctl(shm, IPC_RMID, NULL);
}
int P(int semId)
{
struct sembuf buffer;
buffer . sem_num = 0;
buffer . sem_op = -1;
buffer . sem_flg = SEM_UNDO;
return (semop (semId, & buffer, 1));
}
int V(int semId)
{
struct sembuf buffer;
buffer . sem_num = 0;
buffer . sem_op = 1;
buffer . sem_flg = SEM_UNDO;
return (semop (semId, & buffer, 1));
}
|
C
|
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
void return_pid(char *result);
void return_thread(char *result,char *number);
void return_child(char *result,char *number);
void return_name(char *result,char *number);
void return_state(char *result,char *number);
void return_cmdline(char *result,char *number);
void parent_Pid(char *result,char *number);
void return_ancient(char *result,char *number);
void return_VmSize(char *result,char *number);
void return_VmRss(char *result,char *number);
int main(int argc,char* argv[])
{
char *pointing = malloc(1);
char *number = malloc(1);
number = "694";
return_ancient(pointing,number);
printf("ancient is:%s\n",pointing);
return_pid(pointing);
printf("pid is:%s\n",pointing);
return_thread(pointing,number);
printf("thread is:%s\n",pointing);
return_name(pointing,number);
printf("name is:%s",pointing);
return_state(pointing,number);
printf("state is:%s\n",pointing);
return_cmdline(pointing,number);
printf("cmdline is:%s\n",pointing);
parent_Pid(pointing,number);
printf("parent's Pid is:%s\n",pointing);
//printf("%s\nnum is %d",name,count);
return_VmSize(pointing,number);
printf("VmSize is:%s",pointing);
return_VmRss(pointing,number);
printf("VmRss is:%s",pointing);
return 0;
}
void return_pid(char *result)
{
char test[10];
char buffer[256];
struct dirent* ent = NULL;
DIR *pDir;
if((pDir = opendir("/proc")) == NULL) {
printf("FAILED");
exit(1);
}
int i = 0;
while((ent = readdir(pDir)) != NULL) {
//strcat(buffer,ent->d_name);
//strcat(buffer,"");
strcpy(test,ent->d_name);
if(test[0] == '1')
i = 1;
if(i) {
printf("this is %s ",ent->d_name);
strcat(buffer,ent->d_name);
strcat(buffer," ");
}
}
closedir(pDir);
sprintf(result,"%s",buffer);
}
void return_thread(char *result,char *number)
{
char buffer[20];
struct dirent* ent = NULL;
DIR *pDir;
if((pDir = opendir("/proc/2/task")) == NULL) {
printf("FAILED");
exit(1);
}
int i = 0;
while((ent = readdir(pDir)) != NULL) {
if(i >1) {
strcat(buffer,ent->d_name);
strcat(buffer," ");
}
i++;
}
closedir(pDir);
sprintf(result,"%s",buffer);
}
void return_child(char *result,char *number)
{
FILE *pfile;
char buffer[20] = {};
char output[256] = {};
char addr[50] = {};
char num[10] = {"1"};
strcat(addr,"/proc/");
strcat(addr,number);
strcat(addr,"/task");
strcat(addr,number);
strcat(addr,"/children");
if((pfile = fopen(addr,"r")) == NULL) {
printf("FAILED");
exit(1);
}
fscanf(pfile,"%s",buffer);
fclose(pfile);
sprintf(result,"%s",buffer);
}
void return_name(char *result,char *number)
{
FILE *pfile;
char buffer[20] = {};
char output[256] = {};
char addr[50] = {};
char num[10] = {"1"};
strcat(addr,"/proc/");
strcat(addr,number);
strcat(addr,"/status");
if((pfile = fopen(addr,"r")) == NULL) {
printf("FAILED");
exit(1);
}
int count = 0;
while(fgets(buffer,20,pfile)!=NULL) {
if(count == 1)
break;
strcat(output,buffer);
count++;
}
char name[10]= {};
int i;
int size = strlen(output);
for(i = 6; i < size; i++)
name[i-6] = output[i];
fclose(pfile);
sprintf(result,"%s",name);
}
void return_state(char *result,char *number)
{
FILE *pfile;
char buffer[20] = {};
char output[256] = {};
char addr[50] = {};
char num[10] = {"2"};
strcat(addr,"/proc/");
strcat(addr,number);
strcat(addr,"/status");
if((pfile = fopen(addr,"r")) == NULL) {
printf("FAILED");
exit(1);
}
int count = 0;
while(fgets(buffer,20,pfile)!=NULL) {
if(count == 1) {
strcat(output,buffer);
break;
}
count++;
}
char name[10]= {};
name[0] = output[7];
fclose(pfile);
sprintf(result,"%s",name);
}
void return_cmdline(char *result,char*number)
{
FILE *pfile;
char buffer[32] = {};
char addr[50] = {};
char num[10] = {"2"};
strcat(addr,"/proc/");
strcat(addr,number);
strcat(addr,"/cmdline");
if((pfile = fopen(addr,"r")) == NULL) {
printf("FAILED");
exit(1);
}
fscanf(pfile,"%s",buffer);
fclose(pfile);
sprintf(result,"%s",buffer);
}
void parent_Pid(char *result,char *number)
{
FILE *pfile;
char buffer[20] = {};
char output[256] = {};
char addr[50] = {};
char num[10] = {"2"};
strcat(addr,"/proc/");
strcat(addr,number);
strcat(addr,"/status");
if((pfile = fopen(addr,"r")) == NULL) {
printf("FAILED");
exit(1);
}
int i;
while(fgets(buffer,20,pfile)!=NULL) {
if(buffer[0] == 'P' && buffer[1] == 'P') {
strcat(output,buffer);
break;
}
}
char name[10]= {};
int size = strlen(output);
for(i = 6; i < size-1; i++)
name[i-6] = output[i];
fclose(pfile);
sprintf(result,"%s",name);
}
void return_ancient(char *result,char *number)
{
char buffer[64];
char *test = number;
//printf("%s\n",test);
do {
parent_Pid(result,test);
//printf("%s",result);
if(result[0] != '1') {
strcat(buffer,result);
strcat(buffer," ");
test = result;
}
} while(result[0] != '1');
strcat(buffer,"1");
sprintf(result,"%s",buffer);
}
void return_VmSize(char *result,char *number)
{
FILE *pfile;
char buffer[20] = {};
char output[256] = {};
char addr[50] = {};
char num[10] = {"1"};
strcat(addr,"/proc/");
strcat(addr,number);
strcat(addr,"/status");
if((pfile = fopen(addr,"r")) == NULL) {
printf("FAILED");
exit(1);
}
int i;
while(fgets(buffer,20,pfile)!=NULL) {
if(buffer[0] == 'V' && buffer[2] == 'S') {
strcat(output,buffer);
break;
}
}
char name[10]= {};
int size = strlen(output);
for(i = 8; i < size; i++)
name[i-8] = output[i];
fclose(pfile);
sprintf(result,"%s",name);
}
void return_VmRss(char *result,char *number)
{
FILE *pfile;
char buffer[20] = {};
char output[256] = {};
char addr[50] = {};
char num[10] = {"1"};
strcat(addr,"/proc/");
strcat(addr,number);
strcat(addr,"/status");
if((pfile = fopen(addr,"r")) == NULL) {
printf("FAILED");
exit(1);
}
while(fgets(buffer,20,pfile)!=NULL) {
if(buffer[0] == 'V' && buffer[2] == 'R') {
strcat(output,buffer);
break;
}
}
char name[10]= {};
int i;
int size = strlen(output);
for(i = 7; i < size; i++)
name[i-7] = output[i];
fclose(pfile);
sprintf(result,"%s",name);
}
|
C
|
#include"coordonnee.h"
coordonnee_t creer_coordonnee(int x,int y){
coordonnee_t pos;
pos.x=x;
pos.y=y;
return pos;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
//为qsort准备的比较函数!
int cmp(const void *a,const void *b) {
//把a,b先由一般形式 void *,转化为我们需要的int *形式!
//const是为了保证我们不去修改它!
return *(int *)a-*(int *)b;
}
int main() {
int n,w;
//n代表有n个男孩,也代表有n个女孩!
//w代表茶壶的总容量!
scanf("%d%d",&n,&w);
int i;
//我们创建一个2n长度的数组a!
int *a=malloc(2*n*sizeof(a[0]));
if(a==NULL) {
printf("a don't get memory\n");
}
//读取数据a[i]表示第i个茶杯的容量!
for(i=0; i<2*n; i++) {
scanf("%d",&a[i]);
}
/*
for(i=0; i<2*n; i++) {
printf(" %d",a[i]);
}
printf("\n");
*/
//我利用系统自带的排序函数qsort来快速实现一个排序!
qsort(a,2*n,sizeof(a[0]),cmp);
/*
for(i=0; i<2*n; i++) {
printf(" %d",a[i]);
}
printf("\n");
printf("a0=%d,a%d=%d\n",a[0],n,a[n]);
*/
//a[n]>=2*a[0]
//a0~an-1 an~a2n-1
//女孩子最大拿a0, 这样男孩子要拿2*a0,这里必须保证an至少是2*a0
//即an》=2*a0
//这时的最大茶水容量是n*a0+2*a0*n=3*n*a0
//男孩子最多拿an,这样女孩子要拿an/2,这样a0至少是an/2,
//即a0>=an/2
//这时的最大茶水容量是n*an/2+an*n=3/2*n*an
double res=0.0;
if(a[n]>=2*a[0]) {
res=3.0*n*a[0];
} else {
res=3.0*n*a[n]/2.0;
//要直接进入double运算,如果是3*n*a[n],代码先进行的是整数运算!
}
if(res>w) res=w;
printf("%f\n",res);
free(a);
return 0;
}
|
C
|
// Задача callCost
// Условие задачи
// Считать с клавиатуры 2 целых числа - номер телефона и количество минут.
// Стоимость минуты разговора составляет 1$ за звонок на городской номер и 40$ за
// звонок на короткий номер. За звонок по номерам специальных служб плата не взимается.
// В случае неопределенности вывести -1.
// Пример ввода
// 1488666 10
// Пример вывода
// 10$
// Пояснение
// Коротким номером считается любой трехзначный номер.
// Городским номером считается любой семизначный номер.
// Номера телефонов не могут начинаться с ноля.
// Номера спецслужб: 101, 102, 103, 104, 112.
//code works
#include <stdio.h>
int main() {
int callPhone, callTime;
scanf("%d %d", &callPhone, &callTime);
if ( callPhone > 999999 && callPhone < 10000000 ) {
printf("%d$\n", callTime*1);
} else if ( callPhone == 101 || callPhone == 102 || callPhone == 103 || callPhone == 104 || callPhone == 112 ) {
printf("%d$\n", 0);
} else if ( callPhone > 99 && callPhone < 1000 ) {
printf("%d$\n", callTime*40);
} else {
printf("%d\n", -1);
}
return 0;
}
|
C
|
#include <linux/module.h> //所有模块都需要的头文件
#include <linux/init.h> // init&exit相关宏
MODULE_LICENSE("GPL");
MODULE_AUTHOR("feifei");
MODULE_DESCRIPTION("hello world module");
static int __init hello_init(void){
printk(KERN_ERR "hello world");
return 0;
}
static void __exit hello_exit(void){
printk(KERN_EMERG "hello exit!");
}
module_init(hello_init);
module_exit(hello_exit);
|
C
|
/* This program adds two matrices of order 3x3. */
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{ int x[3][3],y[3][3],z[3][3],r,c; clrscr();
gotoxy(10,3); printf("MATRIX 1");
gotoxy(30,3); printf("MATRIX 2");
gotoxy(50,3); printf("SUM 1 & 2");
gotoxy(22,6); printf("+"); gotoxy(42,6); printf("+");
for(r=0;r<3;r++)
{ for(c=0;c<3;c++)
{ x[r][c]=random(5+c); y[r][c]=random(6+c);
z[r][c]=x[r][c]+y[r][c];
gotoxy(10+(3*c),5+r); printf("%d",x[r][c]);
gotoxy(30+(3*c),5+r); printf("%d",y[r][c]);
gotoxy(50+(3*c),5+r); printf("%d",z[r][c]);
}
}
getch();
}
|
C
|
/*
* input_validation.c
* Author: Gabriel Servia
*/
#include "input_validation.h"
/**
* \brief Verifica si la cadena ingresada es un texto valida
* \param cadena Cadena de caracteres a ser analizada
* \param len Define la longitud de la cadena
* \return Retorna 1 (verdadero) si la cadena es valida y 0 (falso) si no lo es
*/
int esTexto(char* cadena, int len)
{
int i = 0;
int retorno = 1;
if (cadena != NULL && len > 0)
{
for (i = 0; cadena[i] != '\0' && i < len; i++)
{
if (cadena[i] != '.' && cadena[i] != ' ' && (cadena[i] < 'A' || cadena[i] > 'Z' ) && (cadena[i] < 'a' || cadena[i] > 'z' ) && (cadena[i] < '0' || cadena[i] > '9' ) )
{
retorno = 0;
break;
}
}
}
return retorno;
}
/**
* \brief Verifica si la cadena ingresada es numerica
* \param pCadena Cadena de caracteres a ser analizada
* \return Retorna 1 (Verdadero) si la cadena es numerica, 0 (Falso) si no lo es y -1 en caso de Error
*/
int esNumerica(char* pCadena, int limite)
{
int retorno = -1; // Error
int i;
if (pCadena != NULL && limite > 0)
{
retorno = 1; // Verdadero
for(i = 0; i < limite && pCadena[i] != '\0'; i++)
{
if (i == 0 && (pCadena[i] == '+' || pCadena[i] == '-'))
{
continue;
}
if (pCadena[i] < '0'|| pCadena[i] > '9')
{
retorno = 0; // Falso
break;
}
}
}
return retorno;
}
/**
* \brief Verifica si la cadena ingresada es flotante
* \param cadena Cadena de caracteres a ser analizada
* \return Retorna 1 (Verdadero) si la cadena es flotante y 0 (Falso) si no lo es
*/
int esFloat(char* cadena)
{
int i = 0;
int retorno = 1;
int contadorPuntos = 0;
if (cadena != NULL && strlen(cadena) > 0)
{
for (i = 0; cadena[i] != '\0'; i++)
{
if (i == 0 && (cadena[i] == '-' || cadena[i] == '+'))
{
continue;
}
if (cadena[i] < '0' || cadena[i] > '9')
{
if (cadena[i] == '.' && contadorPuntos == 0)
{
contadorPuntos++;
}
else
{
retorno = 0;
break;
}
}
}
}
return retorno;
}
/**
* \brief Verifica si la cadena ingresada es un nombre valido
* \param cadena Cadena de caracteres a ser analizada
* \return Retorna 1 (verdadero) si la cadena es valida y 0 (falso) si no lo es
*
*/
int esNombre(char* cadena, int len)
{
int i = 0;
int retorno = 1;
if (cadena != NULL && len > 0)
{
for (i = 0; cadena[i] != '\0' && i < len; i++)
{
if ((cadena[i] < 'A' || cadena[i] > 'Z' ) && (cadena[i] < 'a' || cadena[i] > 'z' ) && (cadena[i] != ' ') && (cadena[i] != '-'))
{
retorno = 0;
break;
}
}
}
return retorno;
}
|
C
|
#include <stdio.h>
int sumMultiplesOf3And5(int max);
int sumMultipleOfMax(int multiple, int max);
int main(void) {
printf("%i\n", sumMultiplesOf3And5(10)); // 23
printf("%i\n", sumMultiplesOf3And5(1000)); // 233168
return 0;
}
int sumMultiplesOf3And5(int max) {
return sumMultipleOfMax(3, max) + sumMultipleOfMax(5, max)
- sumMultipleOfMax(15, max);
}
int sumMultipleOfMax(int multiple, int max) {
int multipleQuotient = (max - 1) / multiple;
return multiple * (multipleQuotient * (multipleQuotient + 1)) / 2;
}
|
C
|
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <stdbool.h>
#include "../lib/shell.c"
/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) {
char command0[18];
sprintf(command0, "-c %s /bin/ls ; %s", "\"", "\"");
printf("command0 = \"%s\"\n", command0);
processInput(command0, true);
}
static void null_test_failure(void **state) {
assert_false(true || state);
}
int main(void) {
const struct CMUnitTest tests[] = {
cmocka_unit_test(null_test_success),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
|
C
|
#include <stdio.h>
int main() {
int age;
printf("Enter your age;");
scanf("%d", &age);
if( age > 17 ){
printf("You not a kid\n");
}
else if(age < 17){
printf("You a kid :) \n");
}
return 0;
}
|
C
|
#ifndef __GLOBAL_DEFINE_H__
#define __GLOBAL_DEFINE_H__
#define CHECK_NULL(ptr, ret) \
{ \
if (NULL == ptr) \
{ \
printf("ptr is null"); \
return ret; \
} \
}
#endif // __GLOBAL_DEFINE_H__
|
C
|
#include "../../include/netif.h"
#include "../../include/ethernet.h"
#include "../../include/arp.h"
#include "../../include/lib.h"
#define BROADCAST_ADDR ((unsigned char *)"\xff\xff\xff\xff\xff\xff")
/* arp请求,广播 */
void arp_request(struct arpentry *ae){
struct pk_buff *pkb;
struct ethernet_hdr *ehdr;
struct arphdr *ahdr;
pkb = alloc_pkb(ETH_HRD_SZ+ARP_HRD_SZ);
ehdr = (struct ethernet_hdr *)pkb->pk_data;
ahdr = (struct arphdr *)ehdr->eth_data;
ahdr->arp_hrd = _htons(ARPHRD_ETHER);
ahdr->arp_pro = _htons(ETHERNET_TYPE_IP);
ahdr->arp_hlen = ETHERNET_ADDR_LEN;
ahdr->arp_plen = IP_ALEN;
ahdr->arp_op = _htons(ARPOP_REQUEST); /* arp请求 */
/* IP地址均为网络字节序 */
ahdr->arp_sip = ae->ae_dev->net_ipaddr;
hwacpy(ahdr->arp_sha,ae->ae_dev->net_hwaddr);
ahdr->arp_tip = ae->ae_ipaddr;
hwacpy(ahdr->arp_tha,BROADCAST_ADDR);
netdev_tx(ae->ae_dev,pkb,pkb->pk_len-ETH_HRD_SZ,ETHERNET_TYPE_ARP,BROADCAST_ADDR);
}
/* 回复arp请求 */
void arp_reply(struct net_device *dev,struct pk_buff *pkb){
struct ethernet_hdr *ehdr = (struct ethernet_hdr *)pkb->pk_data;
struct arphdr *ahdr = (struct arphdr *)ehdr->eth_data;
ahdr->arp_op = ARPOP_REPLY;
hwacpy(ahdr->arp_tha,ahdr->arp_sha);
ahdr->arp_tip = ahdr->arp_sip;
hwacpy(ahdr->arp_sha,dev->net_hwaddr);
ahdr->arp_sip = dev->net_ipaddr;
arp_hton(ahdr);/* 字节序转换 */
netdev_tx(dev,pkb,ARP_HRD_SZ,ETHERNET_TYPE_ARP,ehdr->eth_src);
}
/* 解析pkb中的arphdr,与现有arp缓存表做对比 */
void arp_recv(struct net_device *dev,struct pk_buff *pkb){
struct ethernet_hdr *ehdr = (struct ethernet_hdr *)pkb->pk_data;
struct arphdr *ahdr = (struct arphdr *)ehdr->eth_data;
struct arpentry *ae;
if(ipv4_is_multicast(ahdr->arp_tip)){
free_pkb(pkb);
}
if(ahdr->arp_tip != dev->net_ipaddr){
free_pkb(pkb);
}
ae = arp_lookup(ahdr->arp_pro,ahdr->arp_sip);
if(ae!=NULL){
if(hwacmp(ae->ae_hwaddr,ahdr->arp_sha) != 0){
ae->ae_state = ARP_PENDING;/* PENDING means a request for this entry has been sent,but the reply has not been received yet,用于等待arp_reply */
arp_queue_send(ae); /* 所以需要再次retry 发送pending packet */
}
ae->ae_state = ARP_RESOLVED;
ae->ae_ttl = ARP_TIMEOUT;
}else if(ahdr->arp_op == ARPOP_REQUEST){ /* 如果判断entry为空,且arp_op 为request,则新插入一条ARP缓存记录 */
arp_insert(dev,ahdr->arp_pro,ahdr->arp_sip,ahdr->arp_sha);
}
if(ahdr->arp_op == ARPOP_REQUEST){
arp_reply(dev,pkb);
return;
}
}
/* 接收数据包,进行层层拆包
判断pk_type、pk_len是否合理
比较arp包中的hardware address是否与eth包中的hardware address相同
判断arp包中的L2、L3协议类型与长度,arp_op code
*/
void arp_in(struct net_device *dev,struct pk_buff *pkb){
/* 层层拆包 */
struct ethernet_hdr *ehdr = (struct ethernet_hdr *)pkb->pk_data;
struct arphdr *ahdr = (struct arphdr *)ehdr->eth_data;
if(pkb->pk_type == PKT_OTHERHOST){
free_pkb(pkb);
}
if(pkb->pk_len < ETH_HRD_SZ+ARP_HRD_SZ){
free_pkb(pkb);
}
if(hwacmp(ahdr->arp_sha,ehdr->eth_src) != 0){
free_pkb(pkb);
}
arp_ntoh(ahdr);
#if defined(ARP_ETHERNET) && defined(ARP_IP)
if(ahdr->arp_hrd != ARPHRD_ETHER || ahdr->arp_pro != ETHERNET_TYPE_IP ||
ahdr->arp_hlen != ETHERNET_ADDR_LEN || ahdr->arp_plen != IP_ALEN){
free_pkb(pkb);
}
#endif
if(ahdr->arp_op != ARPOP_REQUEST && ahdr->arp_op != ARPOP_REPLY){
free_pkb(pkb);
}
/* 经过以上判断,如果成功,则进行接收携带有arp协议的数据包 */
arp_recv(dev,pkb);
return;
}
|
C
|
#include <unistd.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define ALSA_CLIENT_FIFO "/data/alsa_client_%d_fifo"
#define ALSA_DAEMON_FIFO "/data/alsa_daemon_fifo"
#define TIMEOUT_SEC 3
#define TIMEOUT_USEC 0
#define PARAM_MAX_LEN 1024
#define PARAM_MAX_NUM 4
typedef struct alsa_msg
{
char command[16];
pid_t client_pid;
int result;
unsigned char data[PARAM_MAX_NUM][PARAM_MAX_LEN + 1];
}alsa_msg;
/*===========================================================================
Definations and typedefs
===========================================================================*/
#ifndef UPCASE
#define UPCASE( c ) ( ((c) >= 'a' && (c) <= 'z') ? ((c) - 0x20) : (c) )
#endif
/*===========================================================================
FUNCTION dsatutil_atoi
===========================================================================*/
/*!
@brief
string to int
@return
0 ok
@note
*/
/*=========================================================================*/
static int dsatutil_atoi
(
unsigned int *val_arg_ptr, /* value returned */
unsigned char *s, /* points to string to eval */
unsigned int r /* radix */
)
{
int err_ret = -1;
unsigned char c;
unsigned int val, val_lim, dig_lim;
val = 0;
val_lim = (unsigned int) ((unsigned int)0xffffffff / r);
dig_lim = (unsigned int) ((unsigned int)0xffffffff % r);
while ( (c = *s++) != '\0')
{
if (c != ' ')
{
c = (unsigned char) UPCASE (c);
if (c >= '0' && c <= '9')
{
c -= '0';
}
else if (c >= 'A')
{
c -= 'A' - 10;
}
else
{
err_ret = -2; /* char code too small */
break;
}
if (c >= r || val > val_lim
|| (val == val_lim && c > dig_lim))
{
err_ret = -2; /* char code too large */
break;
}
else
{
err_ret = 0; /* arg found: OK so far*/
val = (unsigned int) (val * r + c);
}
}
*val_arg_ptr = val;
}
return err_ret;
}
static int lock_set(int fd,int type)
{
struct flock old_lock,lock;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
lock.l_type = type;
//lock.l_pid = -1;
fcntl(fd,F_GETLK,&lock);
if(lock.l_type != F_UNLCK)
{
if (lock.l_type == F_RDLCK)
{
printf("Read lock already set by %d\n",lock.l_pid);
}
else if (lock.l_type == F_WRLCK)
{
printf("Write lock already set by %d\n",lock.l_pid);
}
}
lock.l_type = type;
if ((fcntl(fd,F_SETLK,&lock)) < 0)
{
printf("Lock failed : type = %d\n",lock.l_type);
return 1;
}
switch (lock.l_type)
{
case F_RDLCK:
{
printf("Read lock set by %d\n",getpid());
}
break;
case F_WRLCK:
{
printf("write lock set by %d\n",getpid());
}
break;
case F_UNLCK:
{
printf("Release lock by %d\n",getpid());
return 1;
}
break;
default:
break;
}
return 0;
}
static int lock_get(int fd)
{
int res;
struct flock region;
region.l_type=F_WRLCK;
region.l_whence=SEEK_SET;
region.l_start=0;
region.l_len=50;
region.l_pid=1;
if((res=fcntl(fd,F_GETLK,®ion))==0)
{
if(region.l_type==F_UNLCK)
{
printf("F_UNLCK.\n");
return 0;
}
else
{
printf("not F_UNLCK.\n");
return 1;
}
}
printf("lock get fail.\n");
return 1;
}
static int send_msg_to_alsa_daemon(alsa_msg send_msg, alsa_msg *rev_msg)
{
int daemon_fifo_fd;
int client_fifo_fd;
char client_fifo_name[64] = {0};
int res = 0;
int retry = 0;
int status;
fd_set fds;
int lock_fd;
lock_fd = open("/data/fck_hello",O_RDWR | O_CREAT, 0644);
struct timeval tv;
send_msg.client_pid = getpid();
sprintf(client_fifo_name, ALSA_CLIENT_FIFO, send_msg.client_pid);
daemon_fifo_fd = open(ALSA_DAEMON_FIFO, O_WRONLY | O_NONBLOCK);
if(daemon_fifo_fd == -1){
printf("open deamon fifo fail\n");
close(lock_fd);
return -1;
}
if (access(client_fifo_name, F_OK) == -1)
{
if (mkfifo(client_fifo_name,0666) < 0){
printf("mkfifo client fifo fail\n");
close(daemon_fifo_fd);
close(lock_fd);
return -1;
}
}
res = write(daemon_fifo_fd, &send_msg, sizeof(alsa_msg));
if(res < 0){
printf("send msg write fail\n");
close(daemon_fifo_fd);
close(lock_fd);
return -1;
}
client_fifo_fd = open(client_fifo_name, O_RDONLY | O_NONBLOCK);
if(client_fifo_fd == -1){
printf("open client fifo fail\n");
close(daemon_fifo_fd);
close(lock_fd);
return -1;
}
FD_ZERO(&fds);
FD_SET(client_fifo_fd, &fds);
tv.tv_sec = TIMEOUT_SEC;
tv.tv_usec = TIMEOUT_USEC;
status = select(client_fifo_fd + 1, &fds, NULL, NULL, &tv);
if(status == -1){
res = -1;
}else if(status == 0){
printf("timeout\n");
res = -1;
}else{
if (FD_ISSET(client_fifo_fd, &fds)){
res = read(client_fifo_fd, rev_msg, sizeof(alsa_msg));
if (res > 0)
{
printf("response cmd = %s\n", rev_msg->command);
printf("response data[0] = %s\n", rev_msg->data[0]);
}else{
res = -1;
}
}
}
while(lock_get(lock_fd) == F_WRLCK)
{
usleep(20*1000);
retry ++;
if(retry > 100)
{
break;
}
}
lock_set(lock_fd, F_WRLCK);
close(client_fifo_fd);
unlink(client_fifo_name);
lock_set(lock_fd, F_UNLCK);
close(lock_fd);
close(daemon_fifo_fd);
return res;
}
#define POC_ALSA_CLIENT_FIFO "/data/poc_alsa_client_%d_fifo"
#define POC_ALSA_DAEMON_FIFO "/data/poc_alsa_daemon_fifo"
static int send_msg_to_ext_dmr(alsa_msg send_msg, alsa_msg *rev_msg)
{
int daemon_fifo_fd;
int client_fifo_fd;
char client_fifo_name[64] = {0};
int res = 0;
int status;
fd_set fds;
struct timeval tv;
send_msg.client_pid = getpid();
sprintf(client_fifo_name, POC_ALSA_CLIENT_FIFO, send_msg.client_pid);
daemon_fifo_fd = open(POC_ALSA_DAEMON_FIFO, O_WRONLY | O_NONBLOCK);
if(daemon_fifo_fd == -1){
printf("open deamon fifo fail\n");
return -1;
}
if (access(client_fifo_name, F_OK) == -1)
{
if (mkfifo(client_fifo_name,0666) < 0){
printf("mkfifo client fifo fail\n");
close(daemon_fifo_fd);
return -1;
}
}
res = write(daemon_fifo_fd, &send_msg, sizeof(alsa_msg));
if(res < 0){
printf("send msg write fail\n");
close(daemon_fifo_fd);
return -1;
}
client_fifo_fd = open(client_fifo_name, O_RDONLY | O_NONBLOCK);
if(client_fifo_fd == -1){
printf("open client fifo fail\n");
close(daemon_fifo_fd);
return -1;
}
FD_ZERO(&fds);
FD_SET(client_fifo_fd, &fds);
tv.tv_sec = TIMEOUT_SEC;
tv.tv_usec = TIMEOUT_USEC;
status = select(client_fifo_fd + 1, &fds, NULL, NULL, &tv);
if(status == -1){
res = -1;
}else if(status == 0){
printf("timeout\n");
res = -1;
}else{
if (FD_ISSET(client_fifo_fd, &fds)){
res = read(client_fifo_fd, rev_msg, sizeof(alsa_msg));
if (res > 0)
{
printf("response cmd = %s\n", rev_msg->command);
printf("response data[0] = %s\n", rev_msg->data[0]);
}else{
res = -1;
}
}
}
close(client_fifo_fd);
close(daemon_fifo_fd);
unlink(client_fifo_name);
return res;
}
int set_clvl_value(int clvl_value)
{
alsa_msg send_msg;
alsa_msg rev_msg;
int res;
if(clvl_value < 0 || clvl_value > 5)
{
return -1;
}
memset(&send_msg, 0, sizeof(alsa_msg));
memset(&rev_msg, 0, sizeof(alsa_msg));
sprintf(send_msg.command, "%s", "CLVL");
sprintf(send_msg.data[0], "%d", clvl_value);
res = send_msg_to_alsa_daemon(send_msg, &rev_msg);
if((rev_msg.result<0) || (res<0))
{
return -1;
}
return 0;
}
int get_clvl_value(void)
{
alsa_msg send_msg;
alsa_msg rev_msg;
int res;
int clvl_value;
memset(&send_msg, 0, sizeof(alsa_msg));
memset(&rev_msg, 0, sizeof(alsa_msg));
sprintf(send_msg.command, "%s", "CLVL");
sprintf(send_msg.data[0], "%s", "?");
res = send_msg_to_alsa_daemon(send_msg, &rev_msg);
if((rev_msg.result<0) || (res<0))
{
return -1;
}
if(0 != dsatutil_atoi(&clvl_value, (unsigned char *)rev_msg.data[0], 10))
{
return -1;
}
return clvl_value;
}
int set_micgain_value(int micgain_value)
{
alsa_msg send_msg;
alsa_msg rev_msg;
int res;
memset(&send_msg, 0, sizeof(alsa_msg));
memset(&rev_msg, 0, sizeof(alsa_msg));
if(micgain_value < 0 || micgain_value > 8)
{
return -1;
}
sprintf(send_msg.command, "%s", "CMICGAIN");
sprintf(send_msg.data[0], "%d", micgain_value);
res = send_msg_to_alsa_daemon(send_msg, &rev_msg);
if((rev_msg.result<0) || (res<0))
{
return -1;
}
send_msg_to_ext_dmr(send_msg, &rev_msg);
return 0;
}
int get_micgain_value(void)
{
alsa_msg send_msg;
alsa_msg rev_msg;
int res;
int micgain_value;
memset(&send_msg, 0, sizeof(alsa_msg));
memset(&rev_msg, 0, sizeof(alsa_msg));
sprintf(send_msg.command, "%s", "CMICGAIN");
sprintf(send_msg.data[0], "%s", "?");
res = send_msg_to_alsa_daemon(send_msg, &rev_msg);
if((rev_msg.result<0) || (res<0))
{
return -1;
}
if(0 != dsatutil_atoi(&micgain_value, (unsigned char *)rev_msg.data[0], 10))
{
return -1;
}
return micgain_value;
}
int set_csdvc_value(int csdvc_value)
{
alsa_msg send_msg;
alsa_msg rev_msg;
int res;
memset(&send_msg, 0, sizeof(alsa_msg));
memset(&rev_msg, 0, sizeof(alsa_msg));
if((csdvc_value != 1) && (csdvc_value != 3))
{
return -1;
}
sprintf(send_msg.command, "%s", "CSDVC");
sprintf(send_msg.data[0], "%d", csdvc_value);
res = send_msg_to_alsa_daemon(send_msg, &rev_msg);
if((rev_msg.result<0) || (res<0))
{
return -1;
}
send_msg_to_ext_dmr(send_msg, &rev_msg);
return 0;
}
int get_csdvc_value(void)
{
alsa_msg send_msg;
alsa_msg rev_msg;
int res;
int csdvc_value;
memset(&send_msg, 0, sizeof(alsa_msg));
memset(&rev_msg, 0, sizeof(alsa_msg));
sprintf(send_msg.command, "%s", "CSDVC");
sprintf(send_msg.data[0], "%s", "?");
res = send_msg_to_alsa_daemon(send_msg, &rev_msg);
if((rev_msg.result<0) || (res<0))
{
return -1;
}
if(0 != dsatutil_atoi(&csdvc_value, (unsigned char *)rev_msg.data[0], 10))
{
return -1;
}
return csdvc_value;
}
|
C
|
#define _GNU_SOURCE
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
long int get_ncpus_sched()
{
int i;
long int count;
cpu_set_t cs;
CPU_ZERO(&cs);
if(sched_getaffinity(0, sizeof(cs), &cs)==-1){
perror("sched_getaffinity");
exit(EXIT_FAILURE);
}
count=0;
for(i=0; i<CPU_SETSIZE; i++)
if(CPU_ISSET(i, &cs))
count++;
return count;
}
|
C
|
#include <array.h>
#include <string.h>
Array *newArray(size_t element_size)
{
Array *array = malloc(sizeof(Array));
void *content = malloc(element_size);
if (array != NULL && content != NULL) {
array->content = content;
array->element_size = element_size;
array->size = 0;
array->capacity = 1;
} else {
if (array == NULL) free(array);
if (content == NULL) free(content);
array = NULL;
}
return array;
}
void deleteArray(Array **array)
{
if (*array != NULL) {
void *content = (*array)->content;
if (content != NULL) {
free(content);
}
free(*array);
*array = NULL;
}
}
int resize(Array *array, int new_size)
{
int success = 0;
if (array->size <= new_size) {
void *tmp = realloc(array->content, new_size * array->element_size);
if (tmp != NULL) {
array->content = tmp;
array->capacity = new_size;
success = 1;
}
}
return success;
}
void push(Array *array, void *data)
{
if (array->size >= array->capacity) {
void *prevloc = NULL;
if ((char*)data >= (char*)array->content &&
(char*)data < (char*)array->content + (array->element_size * array->size))
{ // array is copying itself, update pointer
prevloc = array->content;
}
if (!resize(array, array->capacity * 2)) return;
if (prevloc) {
data = (char*)data + ((long)array->content - (long)prevloc);
}
}
memcpy((char*)array->content + (array->element_size * array->size++),
(char*)data,
array->element_size);
}
void pushobj(Array *array, void *data) {
push(array, data);
free(data);
}
void *pop(Array *array)
{
void *index = NULL;
if (array->size > 0) {
int size = array->size--;
int capacity = array->capacity;
index = (char*)array->content + (array->size * array->element_size);
if (size > 1 && size < capacity / 4) {
resize(array, capacity / 2);
}
}
return index;
}
int popobj(Array *array, void(*freefunc)(void*)) {
void *index = pop(array);
if (index != NULL) {
freefunc(index);
return 1;
}
return 0;
}
void *at(Array *array, int index)
{
if (index >= 0 && index < array->size) {
return (char*)array->content + (index * array->element_size);
}
return NULL;
}
void *last(Array *array)
{
if (array->size) return (char*)array->content + ((array->size - 1) * array->element_size);
return NULL;
}
void *rem(Array *array, int index)
{
void *rem = NULL;
if (index >= 0 && index < array->size) {
void *tmp = malloc(array->element_size);
if (tmp) {
memcpy(tmp, (char*)array->content + (index * array->element_size), array->element_size);
memcpy((char*)array->content + (index * array->element_size),
(char*)array->content + ((index + 1) * array->element_size),
(array->size - index) * array->element_size);
rem = (char*)array->content + (--array->size * array->element_size);
memcpy(rem, tmp, array->element_size);
free(tmp);
}
}
return rem;
}
void set(Array *array, int index, void *value)
{
if (index >= 0 && index < array->size) {
memcpy((char*)array->content + (index * array->element_size), value, array->element_size);
}
}
void clear(Array *array)
{
array->size = 0;
}
void combine(Array* a, Array *b)
{
void *elem;
if (a->element_size == b->element_size) {
while ((elem = pop(b))) {
push(a, b);
}
}
deleteArray(&b);
}
void insert(Array *array, int index, void *data)
{
if (array->size >= array->capacity) {
void *prevloc = NULL;
if ((char*)data >= (char*)array->content &&
(char*)data < (char*)array->content + (array->element_size * array->size))
{ // array is copying itself, update pointer
prevloc = array->content;
}
if (!resize(array, array->capacity * 2)) return;
if (prevloc) {
data = (char*)data + ((long)array->content - (long)prevloc);
}
}
// Array is copying the moving part
if ((char*)data >= (char*)array->content + index * array->element_size &&
(char*)data < (char*)array->content + array->size * array->element_size) {
data = (char*)data + array->element_size;
}
memcpy((char*)array->content + (index + 1) * array->element_size,
(char*)array->content + index * array->element_size,
(array->size++ - index ) * array->element_size);
memcpy((char*)array->content + index * array->element_size,
(char*)data, array->element_size);
}
void *in(Array *array, void *data)
{
void *contains = NULL;
for (int i = 0; i < array->size; i++) {
void *tmp = (char*)array->content + i * array->element_size;
if(!memcmp((char*)data, tmp, array->element_size)) {
contains = tmp;
break;
}
}
return contains;
}
int indexof(Array *array, void *data)
{
int index = -1;
for (int i = 0; i < array->size; i++) {
if(!memcmp((char*)data, (char*)array->content + i * array->element_size, array->element_size)) {
index = i;
break;
}
}
return index;
}
|
C
|
#include "matrix.h"
void init_mat(Mat* mat)
{
mat->internal = (int *) malloc(sizeof(int) * mat->rows * mat->cols);
mat->data = (int **) malloc(sizeof(int*) * mat->rows);
for(int i = 0; i < mat->rows; i++)
mat->data[i] = &mat->internal[i * mat->cols];
}
void read_mat(char *file_name, Mat *mat)
{
FILE *file = fopen(file_name, "r");
if (!file)
{
perror("File does not exist");
exit(EXIT_FAILURE);
}
// Reads the matrix row and column in the format specified
if (fscanf(file, "row=%d col=%d", &mat->rows, &mat->cols) != 2 || mat->rows <= 0 || mat->cols <= 0)
{
perror("invalid format");
exit(EXIT_FAILURE);
}
// Dynamically allocate memory data
init_mat(mat);
for(int i = 0; i < mat->rows;i++)
for(int j = 0; j < mat->cols; j++)
if(fscanf(file, "%d", &ELEM(mat, i, j)) != 1)
{
perror("Not enough elements in the file");
exit(EXIT_FAILURE);
}
// close the file
fclose(file);
}
// Write the matrix to the supplied file name
void export_mat( char *file_name, Mat *mat)
{
FILE *file = fopen(file_name, "w");
if (!file)
{
perror("File does not exist");
exit(EXIT_FAILURE);
}
fprintf(file, "row=%d col=%d\n", mat->rows, mat->cols);
for (int i = 0; i < mat->rows; i++)
{
for (int j = 0; j < mat->cols; j++)
fprintf(file, "%d\t", ELEM(mat, i, j));
fprintf(file, "\n");
}
fclose(file);
}
// Deallocates matrix data
void cleanup(Mat *mat_a, Mat *mat_b, Mat *mat_c)
{
free(mat_a->data);
free(mat_a->internal);
free(mat_b->data);
free(mat_b->internal);
free(mat_c->data);
free(mat_c->internal);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "rnglong.h"
#define L 128 /* Linear dimension */
#define N (L*L)
#define EMPTY (-N-1)
int ptr[N]; /* Array of pointers */
int nn[N][4]; /* Nearest neighbors */
int order[N]; /* Occupation order */
void boundaries()
{
int i;
for (i=0; i<N; i++) {
nn[i][0] = (i+1)%N;
nn[i][1] = (i+N-1)%N;
nn[i][2] = (i+L)%N;
nn[i][3] = (i+N-L)%N;
if (i%L==0) nn[i][1] = i+L-1;
if ((i+1)%L==0) nn[i][0] = i-L+1;
}
}
void permutation()
{
int i,j;
int temp;
for (i=0; i<N; i++) order[i] = i;
for (i=0; i<N; i++) {
j = i + (N-i)*RNGLONG;
temp = order[i];
order[i] = order[j];
order[j] = temp;
}
}
int findroot(int i)
{
if (ptr[i]<0) return i;
return ptr[i] = findroot(ptr[i]);
}
void percolate()
{
int i,j;
int s1,s2;
int r1,r2;
int big=0;
for (i=0; i<N; i++) ptr[i] = EMPTY;
for (i=0; i<N; i++) {
r1 = s1 = order[i];
ptr[s1] = -1;
for (j=0; j<4; j++) {
s2 = nn[s1][j];
if (ptr[s2]!=EMPTY) {
r2 = findroot(s2);
if (r2!=r1) {
if (ptr[r1]>ptr[r2]) {
ptr[r2] += ptr[r1];
ptr[r1] = r2;
r1 = r2;
} else {
ptr[r1] += ptr[r2];
ptr[r2] = r1;
}
if (-ptr[r1]>big) big = -ptr[r1];
}
}
}
printf("%i %i\n",i+1,big);
}
}
main()
{
rngseed(0);
boundaries();
permutation();
percolate();
}
|
C
|
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include "pdig_ptrace.h"
#include "pdig_debug.h"
#include <stdint.h>
#include <sys/ptrace.h>
#include <sys/uio.h>
#include <sys/user.h>
#ifndef MIN
#define MIN(X,Y) ((X) < (Y)? (X):(Y))
#endif
static inline void* page_align(void* ptr)
{
uintptr_t aligned = ((uintptr_t)ptr & ~(PAGE_SIZE - 1));
return (void*)aligned;
}
static inline const void* next_page(const void* ptr)
{
uintptr_t aligned = ((uintptr_t)ptr & ~(PAGE_SIZE - 1)) + PAGE_SIZE;
return (const void*)aligned;
}
unsigned long copy_from_user(pid_t pid, void* to, const void* from, unsigned long n)
{
struct iovec local_iov[] = {{
.iov_base = to,
.iov_len = n,
}};
int first_page = ((uintptr_t)from) / PAGE_SIZE;
int last_page = ((uintptr_t)from + n) / PAGE_SIZE;
int npages = last_page - first_page + 1;
struct iovec remote_iov[npages];
const void *ptr = from;
unsigned long to_read = n;
for(int p = 0; p < npages; ++p)
{
const void* next_ptr = next_page(ptr);
unsigned long chunk = MIN(to_read, next_ptr - ptr);
remote_iov[p].iov_base = (void*)ptr;
remote_iov[p].iov_len = chunk;
to_read -= chunk;
ptr = next_ptr;
}
int ret = n - process_vm_readv(pid, local_iov, 1, remote_iov, npages, 0);
return ret;
}
unsigned long copy_to_user(pid_t pid, void* from, void* to, unsigned long n)
{
struct iovec local_iov[] = {{
.iov_base = from,
.iov_len = n,
}};
struct iovec remote_iov[] = {{
.iov_base = to,
.iov_len = n,
}};
if (process_vm_writev(pid, local_iov, 1, remote_iov, 1, 0) >= 0) {
return 0;
}
if(n % sizeof(long) != 0) {
abort();
}
unsigned long *ulfrom = (unsigned long*) from;
unsigned long *ulto = (unsigned long*) to;
for (unsigned long i = 0; i < n / sizeof(long); ++i) {
EXPECT(ptrace(PTRACE_POKETEXT, pid, (void*) ulto, *ulfrom));
ulfrom++;
ulto++;
}
return 0;
}
|
C
|
//N = 10
//
//un processo padre crea N processi figli ( https://repl.it/@MarcoTessarotto/crea-n-processi-figli )
//
//shared variables: countdown, process_counter[N], shutdown
//
//usare mutex per regolare l'accesso concorrente a countdown
//
//dopo avere avviato i processi figli, il processo padre dorme 1 secondo e poi imposta il valore di countdown al valore 100000.
//
//quando countdown == 0, il processo padre imposta shutdown a 1.
//
//aspetta che terminino tutti i processi figli e poi stampa su stdout process_counter[].
//
//i processi figli "monitorano" continuamente countdown:
//- processo i-mo: se countdown > 0, allora decrementa countdown ed incrementa process_counter[i]
//- se shutdown != 0, processo i-mo termina
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include <pthread.h>
#include <semaphore.h>
#define N 10
#define COUNTDOWN_VALUE 100
#define CHECK_ERR(a,msg) {if ((a) == -1) { perror((msg)); exit(EXIT_FAILURE); } }
int countdown, process_counter[N], shutdown;
int process_count;
sem_t * semaphore;
char * addr;
void child_process(int index) {
while(1){
if(addr[countdown] == 0){
addr[shutdown] = 1;
}
if(addr[shutdown] != 0){
exit(EXIT_SUCCESS);
}
if (sem_wait(semaphore) == -1) {
perror("sem_wait");
exit(EXIT_FAILURE);
}
if(addr[countdown] > 0){
addr[countdown] -= 1;
addr[process_count+index] += 1;
}
if (sem_post(semaphore) == -1) {
perror("sem_post");
exit(EXIT_FAILURE);
}
}
}
int main() {
int s;
semaphore = malloc(sizeof(sem_t));
s = sem_init(semaphore,1, 1);
CHECK_ERR(s,"sem_init")
addr = mmap(NULL, sizeof(int)+sizeof(process_counter)+sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
countdown = 0;
process_count = sizeof(int);
shutdown = sizeof(int)+sizeof(process_counter);
addr[countdown] = COUNTDOWN_VALUE;
for (int i = 0; i < N; i++) {
switch (fork()) {
case 0:
child_process(i);
break;
case -1:
perror("fork() error");
exit(EXIT_FAILURE);
default:
;
}
}
for(int i = 0; i < N; i++){
if(wait(NULL) == -1){
perror("wait() error");
}
}
for(int i = 0; i < N; i++){
printf("processo figlio %d: %d\n", i, addr[process_count+i]);
}
return 0;
}
|
C
|
#include "key.h"
void Key_Init(void) {
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE, ENABLE);
/* 配置 S1 S2 S3 按键*/
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_4;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; // 设置为输入上拉模式
GPIO_Init(GPIOE, &GPIO_InitStructure);
/* 配置 S4 按键*/
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD; // 设置为输入下拉模式
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
const int MAX_SIZE = 100;
void error( char *msg ){
perror( msg );
exit(1);
}
void main(){
int client_socket_fd, new_socket_fd, portno, clilen;
struct sockaddr_in server_addr;
bzero((char *)&server_addr, sizeof(server_addr));
// creat socket with ip = local m/c , scoket type = tcp
// and check if its created
client_socket_fd = socket(AF_INET, SOCK_STREAM, 0);
if( client_socket_fd < 0){
error ( " Socket creation failed ");
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8084);
server_addr.sin_addr.s_addr = INADDR_ANY;
// connect to server
if( connect (client_socket_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0 ){
close(client_socket_fd);
error ("Connection Failed");
}
char buffer[MAX_SIZE];
int nbytes=0;
// read and send file name to server
scanf( "%s", buffer);
// strcpy(buffer, "test.txt");
size_t filelen = strlen(buffer)+1;
send( client_socket_fd, buffer, filelen, 0);
int read_fd = open("output.txt",O_WRONLY | O_CREAT | O_TRUNC, 0644);
int del =0,count =0,words=0,byte_rec=0,delim=1,j=0;
if(read_fd < 0)
{
perror("[ERROR] Can't create a file\n");
close(client_socket_fd);
exit(1);
}
while ((byte_rec = recv(client_socket_fd, buffer, MAX_SIZE, 0))>0)
{
// writing data to the file
j=0;
write(read_fd,buffer,strlen(buffer));
printf("%s", buffer);
while (j < byte_rec&&buffer[j] != '\0')
{
nbytes++;
// count the number of bytes and words
if (buffer[j] == ' ' || buffer[j] == '\t' ||
buffer[j] == '\n' || buffer[j] == ';' || buffer[j] == ',' ||
buffer[j] == ':' || buffer[j] == '.')
delim=1;
else
{
if(delim==1)
{
words++;
delim=0;
}
}
j++;
}
// for (int i = 0; i < MAX_SIZE; i++) buffer[i] = '\0';
}
if(byte_rec <= 0&& nbytes == 0)
{
printf("File not found");
exit(1);
}
printf("\nThe file transfer is successful. Words: %d, Bytes: %d\n", words, nbytes );
close(client_socket_fd);
close(read_fd);
}
|
C
|
void ft_swap(int *a, int *b)
{
int aux;
aux = *a;
*a = *b;
*b = aux;
}
void ft_rev_int_tab(int *tab, int size)
{
int start;
int end;
end = size - 1;
start = 0;
while (start < end)
{
ft_swap(&tab[start], &tab[end]);
end--;
start++;
}
}
#include <stdio.h>
#include <stdlib.h>
void ft_rev_int_tab(int *tab, int size);
int main(void)
{
int *tab;
int counter;
tab = calloc(10, sizeof(int));
counter = 0;
while (counter < 10)
{
tab[counter] = counter;
counter++;
}
counter = 0;
while (counter < 10)
{
printf("%d ", tab[counter]);
counter++;
}
printf("\n");
ft_rev_int_tab(tab, 10);
counter = 0;
while (counter < 10)
{
printf("%d ", tab[counter]);
counter++;
}
printf("\n");
return (0);
}
|
C
|
#include<conio.h>
#include<stdio.h>
void main()
{
int n;
printf("Enter a number = ");
scanf("d",&n);
if (n%2==0)
printf("Even");
else
printf("odd")
getch();
}
|
C
|
/******************************************************************************
* The Linux Programming Interface practices.
* File: p5.c
*
* Author: garyparrot
* Created: 2019/07/25
* Description: Chapter 18 Exercise 5
******************************************************************************/
#define _XOPEN_SOURCE 500
#include <ftw.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include "tlpi_hdr.h"
static void usageError(const char *progName, const char *msg){
if(msg != NULL)
fprintf(stderr, "%s\n", msg);
fprintf(stderr, "Usage: %s [-d] [-m] [-p] [directory-path]\n", progName);
fprintf(stderr, "\t-d Use FTW_DEPTH flag\n");
fprintf(stderr, "\t-m Use FTW_MOUNT flag\n");
fprintf(stderr, "\t-p Use FTW_PHYS flag\n");
exit(EXIT_FAILURE);
}
int regCount, dirCount, symCount;
static int dirTree(const char *pathname, const struct stat *sbuf, int type, struct FTW *ftwb){
if(S_ISREG(sbuf->st_mode)) regCount++;
if(S_ISDIR(sbuf->st_mode)) dirCount++;
if(S_ISLNK(sbuf->st_mode)) symCount++;
return 0;
}
int main(int argc, const char *argv[]){
int flags = 0, opt;
while((opt = getopt(argc, argv, "dmp")) != -1){
switch(opt){
case 'd': flags |= FTW_DEPTH; break;
case 'm': flags |= FTW_MOUNT; break;
case 'p': flags |= FTW_PHYS; break;
deafult: usageError(argv[0], NULL); break;
}
}
if(argc > optind + 1)
usageError(argv[0], NULL);
if(nftw((argc > optind) ? argv[optind] : "." , dirTree, 10, flags) == -1){
perror("nftw");
exit(EXIT_FAILURE);
}
double sum = regCount + dirCount + symCount;
printf("Regular file : %8d (%6.3lf%%)\n", regCount, (regCount) / sum * 100);
printf("Directory file : %8d (%6.3lf%%)\n", dirCount, (dirCount) / sum * 100);
printf("Symbolic file : %8d (%6.3lf%%)\n", symCount, (symCount) / sum * 100);
return 0;
}
|
C
|
int ji,m;
void fang(int a,int b)
{
int i;
if(b==1) ji++;
else
{
for(i=m;i<=(a/b);i++)
{
m=i;
fang(a-i,b-1);
}
}
}
main()
{
int k,n,p,q;
scanf("%d",&n);
for(k=1;k<=n;k++)
{
scanf("%d %d",&p,&q);
ji=0;
m=0;
fang(p,q);
printf("%d\n",ji);
}
}
|
C
|
#include <stdio.h>
#include <fcntl.h>
#include <libgen.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdlib.h>
#define RETURN_IF_ERROR(expr) \
do { \
int err = (expr); \
if (err == -1) { \
fprintf(stderr, "Error calling " #expr " : %s\n", strerror(errno)); \
return 1; \
} \
} while(0);
int main(int argc, char ** argv) {
if (argc != 2) {
fprintf(stderr, "USAGE: %s FILEPATH\n", argv[0]);
return 1;
}
char* filepath = argv[1];
int fd = openat(AT_FDCWD, filepath, O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0644);
struct flock flck = {
.l_type = F_RDLCK,
.l_whence = SEEK_SET,
.l_start = 0,
.l_len = 1,
};
RETURN_IF_ERROR(fcntl(fd, F_SETLK, &flck))
printf("Success.\n");
return 0;
}
|
C
|
/**
* Carter Bourette (Feb 2017)
* [email protected]
*
* A string library containing common string functions.
* Edit: NONE.
**/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "stringy.h"
/**
* newSplit
* Return a structure of type split, splits on a delimeter.
*
* IN: (char*) string, (char*) delimeter.
* RETURN: (Split*) the structure containing substrings.
* NOTE: Caller must free.
*
**/
Split* newSplit(char* string, char* delim) {
Split* s = (Split*)malloc(sizeof(Split));
s->substring = (char**)malloc(sizeof(char*) * 250);
s->rows = 0;
s->last = 0;
int i = 0, k = 0, cols = 0, found = 0, stringLength = strlen(string);
char temp[999];
/* Crawl through string character by character */
for (i = 0; i < stringLength; i++) {
/* Check to see if the current character is a delimeter */
for (k = 0; k < strlen(delim); k++) {
if (string[i] == delim[k]) { found = 1; break; }
}
/* delim or last character add it to the substring array */
if (found || (i == stringLength - 1 && !found)) {
if (i == stringLength - 1 && !found) {
temp[cols] = string[i];
cols = cols + 1;
}
temp[cols] = '\0';
if (strcmp(temp,"") != 0) {
s->substring[s->rows] = (char*)malloc(sizeof(char) * cols + 1);
strcpy(s->substring[s->rows],temp);
s->rows = s->rows + 1;
}
cols = 0;
} else {
temp[cols] = string[i];
cols = cols + 1;
} found = 0;
}
return s;
}
/**
* newSplitIgnoreSubDelimeters
* Return a structure of type split, splits on a delimeter.
*
* IN: (char*) string, (char*) delimeter, (char*) ignore.
* RETURN: (Split*) the structure containing substrings.
* NOTE: Caller must free.
*
**/
Split* newSplitIgnoreSubDelimeters(char* string, char* delim, char* ignore) {
Split* s = (Split*)malloc(sizeof(Split));
s->substring = (char**)malloc(sizeof(char*) * 150);
s->rows = 0;
s->last = 0;
int i = 0, k = 0, cols = 0, found = 0, inIgnore = 0, stringLength = strlen(string);
char temp[999];
/* name="add" */
/* Crawl through string character by character */
for (i = 0; i < stringLength; i++) {
/* Check to see if the current character is a delimeter */
for (k = 0; k < strlen(delim); k++) {
if (string[i] == delim[k]) { found = 1; break; }
}
if (!inIgnore) {
/* Check to see if the current character is an ignored character */
for (k = 0; k < strlen(ignore); k++) { if (string[i] == ignore[k]) inIgnore = 1; }
} else {
/* Check to see if ignored character if so we no longer ignore */
for (k = 0; k < strlen(ignore); k++) { if (string[i] == ignore[k]) inIgnore = 0; }
}
/* delim or last character add it to the substring array */
if ((found && !inIgnore) || (i == stringLength - 1 && !found)) {
if (i == stringLength - 1 && !found) {
temp[cols] = string[i];
cols = cols + 1;
}
temp[cols] = '\0';
if (strcmp(temp,"") != 0) {
s->substring[s->rows] = (char*)malloc(sizeof(char) * cols + 1);
strcpy(s->substring[s->rows],temp);
s->rows = s->rows + 1;
}
cols = 0;
} else {
temp[cols] = string[i];
cols = cols + 1;
} found = 0;
}
return s;
}
/**
* freeSplit
* Free the memory allocated by the split function.
*
* IN: (Split*) The split structure.
* RETURN: NONE.
*
**/
void freeSplit(Split* s) {
if (s->substring == NULL) return;
int i;
for (i = 0; i < s->rows; i++)
free(s->substring[i]);
free(s->substring);
}
/**
* newBuffer
* Create a new buffer of given size.
*
* IN: (int) Buffer size.
* RETURN: (char*).
*
**/
Buffer* newBuffer(int size) {
Buffer* b = (Buffer*)malloc(sizeof(Buffer));
b->buffer = (char*)malloc(sizeof(char) * size);
if (b == NULL || b->buffer == NULL) printError("Buffer allocation failed.",1);
strcpy(b->buffer,"");
b->size = size;
b->currentIndex = 0;
return b;
}
/**
* bufferAppend
* Append a string to the end of the buffer.
*
* IN: (Buffer*) the current buffer, (char*) the string to append.
* RETURN: NONE.
*
**/
void bufferAppend(Buffer* buf, char* string) {
int length = strlen(string);
/* Extend buffer, if needed */
if (length + buf->currentIndex >= buf->size) {
buf->buffer = (char*) realloc(buf->buffer, buf->size * 1.5);
if (buf->buffer == NULL) printError("Buffer allocation failed.",1);
buf->size += buf->size * 1.5;
}
/* Copy string into buffer */
strcat(buf->buffer,string);
buf->currentIndex = buf->currentIndex + length;
}
/**
* clearBuffer
* Reset the index of the buffer.
*
* IN: (Buffer*) the buffer to clear.
* RETURN: NONE.
*
**/
void bufferClear(Buffer* b) {
b->currentIndex = 0;
b->buffer[b->currentIndex] = '\0';
}
/**
* freeBuffer
* Free the memory allocated to a buffer.
*
* IN: (Buffer*) the buffer.
* RETURN: NONE.
*
**/
void freeBuffer(Buffer* b) {
free(b->buffer);
free(b);
}
/**
* stringify
* allocate a string.
*
* IN: NONE.
* RETURN: (char*) Pointer to the string.
* NOTE: Caller must free.
*
**/
char* stringify(char* str) {
char *newstring = (char*) malloc(strlen(str)*sizeof(char) + 1);
if (newstring == NULL) printError("Unable to allocate memory.",1);
strcpy(newstring, str);
return newstring;
}
/**
* chomp
* Remove trailing newline character.
*
* IN: (char*) the string.
* RETURN: NONE.
*
**/
void chomp(char* str) {
if (!str) return;
int end = strlen(str)-1;
if (str[end] == '\n') str[end] = '\0';
}
/**
* printError
* Prints an error message.
*
* IN: (char*) message, (int) fatal error.
* RETURN: NONE.
*
**/
void printError(char* message, int fatal) {
printf("%s\n", message);
if(fatal) exit(1);
}
|
C
|
#include<stdio.h>
#include<unistd.h>
#include<sys/wait.h>
int main(void)
{
pid_t pid;
printf("Main process id : %d.\n",getpid());
pid = fork();//fork1
if(pid==0){
printf("Fork1, I'm the child %d, my parent is %d.\n",getpid(),getppid());
}
else{
wait(NULL);
}
if(pid==0){
pid=fork();//fork2
if(pid==0){
printf("Fork2, I'm the child %d, my parent is %d.\n",getpid(),getppid());
}
else{
wait(NULL);
}
}
pid=fork();//fork3
if(pid==0){
printf("Fork3, I'm the child %d, my parent is %d.\n",getpid(),getppid());
}
else{
wait(NULL);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
/**
* main - prints numbers 0 to 9 only using putchar.
* Return: 0
*/
int main(void)
{
int number = 48;
while (number < 58)
{
putchar(number);
number++;
}
putchar('\n');
return (0);
}
|
C
|
// Phillip Stewart
// CPSC 351, Spring 2015
#include <sys/shm.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "msg.h"
#define SHARED_MEMORY_CHUNK_SIZE 1000
const char recvFileName[] = "recvfile";
FILE* fp;
/* Shared memory */
int shmid = 0;
void* smp = 0;
/* Sender pid */
int sender_pid = 0;
/* 'count' tracks the bytes in shared mem */
volatile sig_atomic_t count;
/* 'go' acts as a sort of mutex:
* It is initially set to 0 and used for busy-waiting,
* when signaled, the value is set to 1,
* and then reset to 0 as soon as the busy-wait exits. */
volatile sig_atomic_t go = 0;
/* Sets pid in shared mem and waits to get pid from sender. */
void pidswap()
{
int pid = getpid();
*(int*)smp = pid;
pause();
go = 0;
sender_pid = *(int*)smp;
}
/* Sets up the shared memory segment and message queue,
* calls pidswap() */
void init()
{
/* Use ftok in order to generate a key. */
int key;
if ((key = ftok("keyfile.txt", 'a')) == -1) {
perror(" line 52, recv ftok error");
exit(1);
}
/* Get the id of the shared memory segment of size SHARED_MEMORY_CHUNK_SIZE */
if ((shmid = shmget(key, SHARED_MEMORY_CHUNK_SIZE, 0666 | IPC_CREAT)) == -1) {
perror(" line 58, recv shmget error");
exit(1);
}
/* Attach to the shared memory */
if ((int)(smp = shmat(shmid, NULL, 0)) == -1) {
perror(" line 64, recv shmat error");
exit(1);
}
pidswap();
// printf("key : %d smp: %p\n", key, smp);
// printf("my pid: %d\n", getpid());
// printf("sender pid: %d\n", sender_pid);
}
/* Signals sender that it's ready for the count.
* receives signals while spinning, and then resets spinlock.
*/
void get_count()
{
count = 0;
kill(sender_pid, SIGUSR1);
/* A cheap self locking spinlock...
* (reseting the lock is not atomic, but it's good enough)
*/
while (!go);
go = 0;
}
/* The main loop for receiving data */
void receive()
{
/* Open the file for writing */
fp = fopen(recvFileName, "w");
/* Error checks */
if(!fp)
{
perror(" line 96, recv fopen error");
exit(-1);
}
/* Loop and receive until the sender sets the size to 0, indicating that
* there is no more data to send */
int bytes_written;
do {
get_count();
if (count == 0) break;
/* Save the shared memory to file */
bytes_written = fwrite(smp, sizeof(char), count, fp);
if(bytes_written != count) {
perror(" line 110, recv fwrite error");
exit(1);
}
} while (1);
/* Close the file */
fclose(fp);
}
/* Perfoms the cleanup functions */
void cleanUp()
{
/* Detach from shared memory */
if (smp) {
if (shmdt(smp) == -1) {
perror(" line 128, recv shmdt error");
exit(1);
}
}
if (shmid) {
if (shmctl(shmid, IPC_RMID, NULL) == -1) {
perror(" line 135, recv shmctl error");
exit(1);
}
}
if (fp)
fclose(fp);
}
/* Handles the exit signal */
void ctrlCSignal(int signal)
{
cleanUp();
exit(130); // 130 is ^C exit code
}
/* Signal for incrementing the counter manually */
void sig1()
{
count++;
}
/* Signal for spinlock */
void sig2()
{
go = 1;
}
/* Signal for setting count to the full buffer size */
void set_full()
{
count = SHARED_MEMORY_CHUNK_SIZE;
}
/* Main */
int main(int argc, char** argv)
{
/* Set signal handler for ^C */
signal(SIGINT, ctrlCSignal);
/* Set message signals */
signal(SIGUSR1, sig1);
signal(SIGUSR2, sig2);
signal(SIGALRM, set_full);
/* run the program */
init();
receive();
cleanUp();
return 0;
}
|
C
|
/*RUN:
PO_SPEW_LEVEL=info ./threadPool_runTaskTimeout
*/
#include <unistd.h>
#include <stdint.h>
#include <stdio.h>
#include <errno.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <alloca.h>
#include <time.h>
#include <stdarg.h>
#include <inttypes.h>
#include "debug.h"
#include "tIme.h"
#include "define.h"
#include "threadPool.h"
#if 1
static void* fasttask(void *p)
{
int i = 0;
++i;
i -= 3;
return NULL;
}
#endif
static void* task(void *p)
{
usleep(300000); // microseconds sec/1,000,000
return NULL;
}
#define TOTAL_TASKS 30
#define MAX_WORKERS 10
#define QUEUE_MAX (TOTAL_TASKS - MAX_WORKERS)
int main(int argc, char **argv)
{
ASSERT(TOTAL_TASKS > 2);
struct POThreadPool *p;
p = poThreadPool_create(MAX_WORKERS /*maxNumThreads*/,
QUEUE_MAX /*maxQueueLength*/,
// With this short maxIdleTime we should see the number of
// worker thread ramp up and down.
100 /*maxIdleTime milli-seconds 1s/1000*/);
uint32_t i, j;
const uint32_t NLOOPS = 10;
for(j=0; j<NLOOPS; ++j)
{
if(j)
sleep(1);
printf("loop %"PRIu32" of %"PRIu32"\n", j+1, NLOOPS);
ASSERT(!poThreadPool_runTask(p, 0, 0 /*tract*/, fasttask, 0));
ASSERT(!poThreadPool_runTask(p, 10, 0 /*tract*/, fasttask, 0));
ASSERT(!poThreadPool_runTask(p, 0, 0 /*tract*/, fasttask, 0));
ASSERT(!poThreadPool_runTask(p, 10, 0 /*tract*/, fasttask, 0));
for(i=0; i<TOTAL_TASKS-2; ++i)
ASSERT(!poThreadPool_runTask(p, PO_LONGTIME, 0 /*tract*/, task, 0));
ASSERT(!poThreadPool_runTask(p, 100, 0 /*tract*/, task, 0));
ASSERT(!poThreadPool_runTask(p, 100, 0 /*tract*/, task, 0));
for(i=0; i<4; ++i)
ASSERT(PO_ERROR_TIMEOUT ==
poThreadPool_runTask(p, 10/*timeOut milliseconds*/,
0 /*tract*/, task, 0));
}
// These 4 calls should timeout.
ASSERT(poThreadPool_tryDestroy(p, 10/*timeOut milliseconds*/) == TOTAL_TASKS);
ASSERT(poThreadPool_tryDestroy(p, 10/*timeOut milliseconds*/) == TOTAL_TASKS);
ASSERT(poThreadPool_tryDestroy(p, 10/*timeOut milliseconds*/) == TOTAL_TASKS);
ASSERT(poThreadPool_tryDestroy(p, 10/*timeOut milliseconds*/) == TOTAL_TASKS);
// This call should not timeout.
ASSERT(poThreadPool_tryDestroy(p, 100000/*timeOut milliseconds*/) == 0);
printf("%s SUCCESS\n", argv[0]);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_aux.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sboilard <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/12/27 16:52:00 by sboilard #+# #+# */
/* Updated: 2018/01/04 21:07:59 by sboilard ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
#include <stdlib.h>
#include "internal/get_next_line.h"
#include "libft_str.h"
static char *pop_data(t_fd_data *fd_data, const char *split)
{
size_t line_size;
size_t rem_size;
char *line;
char *rem;
line_size = split - fd_data->data;
rem_size = fd_data->size - line_size;
line = (char *)malloc(line_size);
if (line == NULL)
return (NULL);
rem = rem_size > 0 ? (char *)malloc(rem_size) : NULL;
if (rem == NULL && rem_size > 0)
{
free(line);
return (NULL);
}
ft_memcpy(line, fd_data->data, line_size - 1);
line[line_size - 1] = '\0';
ft_memcpy(rem, fd_data->data + line_size, rem_size);
free(fd_data->data);
fd_data->size = rem_size;
fd_data->data = rem;
return (line);
}
static int push_data(t_fd_data *fd_data, const char *buffer, size_t size)
{
char *tmp;
if (size == 0)
return (1);
tmp = ft_memjoin(fd_data->data, fd_data->size, buffer, size);
if (tmp == NULL)
return (0);
free(fd_data->data);
fd_data->data = tmp;
fd_data->size += size;
return (1);
}
static int perform_reads(t_fd_data *fd_data, char **found_out)
{
char buffer[BUFF_SIZE];
char *found;
int read_size;
read_size = 0;
while ((found = ft_memchr(buffer, '\n', read_size)) == NULL)
{
read_size = read(fd_data->fd, buffer, BUFF_SIZE);
if (read_size < 0)
return (-1);
if (read_size == 0)
{
if (fd_data->data == NULL)
return (0);
buffer[0] = '\n';
read_size = 1;
}
if (!push_data(fd_data, buffer, read_size))
return (-1);
}
*found_out = fd_data->data + fd_data->size - read_size + (found - buffer);
return (1);
}
int get_next_line_aux(t_fd_data *fd_data, char **line)
{
char *found;
int ret;
found = ft_memchr(fd_data->data, '\n', fd_data->size);
if (found == NULL)
{
ret = perform_reads(fd_data, &found);
if (ret <= 0)
return (ret);
}
*line = pop_data(fd_data, found + 1);
if (*line == NULL)
return (-1);
return (1);
}
|
C
|
#include<stdio.h>
int add(int,int);
int sub(int,int);
int main(int argc,char const *argv[])
{
printf("Addition: %d\n",add(10,20));
printf("Differ: %d\n",sub(10,20));
return 0;
}
|
C
|
#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#define SIZE 128
int main()
{
time_t curTime;
struct tm * timeInfo;
unlink("file_fifo");
if((mkfifo("file_fifo", 0666)) == -1)
{
printf("Can\'t create FIFO!\n");
_exit(1);
}
int fileDescr;
pid_t child;
child = fork();
if(child == 0)
{
sleep(1);
ssize_t size = 0;
char res[SIZE];
if((fileDescr = open("file_fifo", O_RDONLY)) < 0)
{
printf("Cant open FIFO to read!\n");
_exit(1);
}
size = read(fileDescr, res , SIZE);
close(fileDescr);
if(size <= 0)
{
printf("Can\'t read string.\n");
_exit(1);
}
printf("Child read : %ld ", (size_t)size);
time(&curTime);
timeInfo = localtime(&curTime);
printf("%s\n", res);
printf("Children time : %s\n", asctime(timeInfo));
}
else if(child > 0)
{
time(&curTime);
timeInfo = localtime(&curTime);
char strToPipe[SIZE];
sprintf(strToPipe, "from PID : %d\nParent time : %s", getpid(), asctime(timeInfo));
ssize_t size = 0;
if((fileDescr = open("file_fifo", O_WRONLY)) < 0)
{
printf("Cant open FIFO to write!");
_exit(1);
}
size = write(fileDescr, (void*)strToPipe, strlen(strToPipe));
close(fileDescr);
printf("\nParent write : %ld.\n", (size_t)size);
printf("Parent exit.\n\n");
waitpid(child, 0, 0);
}
else
{
printf("Can't create a child process!");
_exit(1);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
void FIFO();
void LRU();
void OPTIMAL();
int n,nf,i,j,pos;
int queue[100];
int a[50];
int front=-1;
int rare=-1;
int insert();
int insertn();
void display();
void main()
{
int op;
printf("\nselect one page replacement algorithm\n");
printf("1.FIFO\n");
printf("2.LRU\n");
printf("3.OPTIMAL\n");
do
{
printf("\n enter your option\n");
scanf("%d",&op);
switch(op)
{
case 1:
FIFO();
break;
case 2:
LRU();
break;
case 3:
OPTIMAL();
break;
default:
printf("Invalid option\n");
break;
}
}while(op<4);
}
void FIFO()
{
int i,j,a[50],frame[10],n,nf,k,hit,count=0;
printf("enter no.of elements");
scanf("%d",&n);
printf("enter elements");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("enter no.of frames");
scanf("%d",&nf);
for(i=0;i<nf;i++)
{
frame[i]=-1;
}
j=0;
printf("page frames\n");
for(i=0;i<n;i++)
{
printf("%d\t\t",a[i]);
hit=0;
for(k=0;k<nf;k++)
{
if(frame[k]==a[i])
{
hit=1;}
}
if(hit==0)
{
frame[j]=a[i];
j=(j+1)%nf;
count++;
}
for(k=0;k<nf;k++)
{
printf("%d\t",frame[k]);
}
printf("\n");
}
printf("page faults is %d",count);
return 0;
}
void LRU()
{
int hit=0,count=0;
printf("enter page frames");
scanf("%d",&nf);
printf("enter number of page requests");
scanf("%d",&n);
for(j=0;j<n;j++)
{
scanf("%d",&a[j]);
}
for(i=0;i<n;i++)
{
for(j=front;j<=rare;j++)
{
if(queue[j]==a[i])
{
hit=1;
pos=j;
break;
}
}
if(hit==1)
{
insertn();
}
else
{ count++;
insert();
}
}
display();
printf("page faults is %d",count);
}
int insert()
{
int l;
if(front==-1&&rare==-1)
{
front=0;
rare=0;
queue[rare]=a[i];
}
else if(front==0&&rare==nf-1)
{
for(l=0;l<rare;l++)
{
queue[l]=queue[l+1];
}
queue[rare]=a[i];
}
else
{
rare++;
queue[rare]=a[i];
}
}
insertn()
{
int k;
for(k=pos;k<rare;k++)
{
queue[k]=queue[k+1];
}
queue[rare]=a[i];
}
void display()
{ int d;
for(d=front;d<=rare;d++)
{
printf("%d",queue[d]);
}
}
void OPTIMAL()
{
int no_of_frames, no_of_pages, frames[10], pages[30], temp[10], flag1, flag2, flag3, i, j, k, pos, max, faults = 0;
printf("Enter number of frames: ");
scanf("%d", &no_of_frames);
printf("Enter number of pages: ");
scanf("%d", &no_of_pages);
printf("Enter page reference string: ");
for(i = 0; i < no_of_pages; i++){
scanf("%d", &pages[i]);
}
for(i = 0; i < no_of_frames; i++){
frames[i] = -1;
}
for(i = 0; i < no_of_pages; i++){
flag1 = flag2 = 0;
for(j = 0; j < no_of_frames; j++){
if(frames[j] == pages[i]){
flag1 = flag2 = 1;
break;
}
}
if(flag1 == 0){
for(j = 0; j < no_of_frames; j++){
if(frames[j] == -1){
faults++;
frames[j] = pages[i];
flag2 = 1;
break;
}
}
}
if(flag2 == 0){
flag3 =0;
for(j = 0; j < no_of_frames; j++){
temp[j] = -1;
for(k = i + 1; k < no_of_pages; k++){
if(frames[j] == pages[k]){
temp[j] = k;
break;
}
}
}
for(j = 0; j < no_of_frames; j++){
if(temp[j] == -1){
pos = j;
flag3 = 1;
break;
}
}
if(flag3 ==0){
max = temp[0];
pos = 0;
for(j = 1; j < no_of_frames; j++){
if(temp[j] > max){
max = temp[j];
pos = j;
}
}
}
frames[pos] = pages[i];
faults++;
}
printf("\n");
for(j = 0; j < no_of_frames; j++){
printf("%d\t", frames[j]);
}
}
printf("\n\nTotal Page Faults = %d", faults);
}
|
C
|
/**
\package Common
This package contains the base class for all classes in the toolbox (IASObject).
The base class provides a simple management of the settings using a
parameter pool. See Common.Settings and Common.IASObject. The Common package is still
under construction, but the main functionality that is required is there. The parameter
pool functionality is implemented by two main classes:
- Common.Settings: This class represents a parameter pool. There is a global parameter pool
which can be accessed by Common.Settings(). There is also the option to create individual
parameter pools. The parameter pool maintains a list of parameters and the corresponding
values. Whenever a value is changed, the objects that maintain this parameter will
be informed (and their data member will be changed). However, this basic functionality
so far only works at the creation of the objects, if a parameter is changed on runtime
the other objects will NOT be informed.
- Common.SettingsClient: Every IASObject is a SettingsClient. Clients can link properties to the global
parameter pool with the method Common.SettingsClient.linkProperties. Properties can be linked with the
same name as used within the class or with a different external name. If a property is linked and the
property alreay exists in the parameter pool, the value from the parameter pool is used to overwrite the
value of the property of the object. If the property does not exist in the parameter pool, it
property is registered in the parameter pool. The value in the parameter pool is in this case set
to the current value of the local property.
Please also consult the test scripts (+Common/+tests/testSettings.m) as small tutorial.
*/
|
C
|
/*
* Revision Control Information
*
* $Source: /users/pchong/CVS/sis/sis/st/st_bench1.c,v $
* $Author: pchong $
* $Revision: 1.1.1.1 $
* $Date: 2004/02/07 10:14:46 $
*
*/
#include <stdio.h>
#include "array.h"
#include "st.h"
#include "util.h"
#define MAX_WORD 1024
extern long random();
/* ARGSUSED */
main(argc, argv)
char *argv;
{
array_t *words;
st_table *table;
char word[MAX_WORD], *tempi, *tempj;
register int i, j;
long time;
#ifdef TEST
st_generator *gen;
char *key;
#endif
/* read the words */
words = array_alloc(char *, 1000);
while (gets(word) != NIL(char)) {
array_insert_last(char *, words, util_strsav(word));
#ifdef TEST
if (array_n(words) == 25) break;
#endif
}
/* scramble them */
for(i = array_n(words)-1; i >= 1; i--) {
j = random() % i;
tempi = array_fetch(char *, words, i);
tempj = array_fetch(char *, words, j);
array_insert(char *, words, i, tempj);
array_insert(char *, words, j, tempi);
}
#ifdef TEST
(void) printf("Initial data is\n");
for(i = array_n(words)-1; i >= 0; i--) {
(void) printf("%s\n", array_fetch(char *, words, i));
}
#endif
/* time putting them into an st tree */
time = util_cpu_time();
table = st_init_table(strcmp, st_strhash);
for(i = array_n(words)-1; i >= 0; i--) {
(void) st_insert(table, array_fetch(char *, words, i), NIL(char));
}
(void) printf("Elapsed time for insert of %d objects was %s\n",
array_n(words), util_print_time(util_cpu_time() - time));
#ifdef TEST
(void) printf("st data is\n");
st_foreach_item(table, gen, &key, NIL(char *)) {
(void) printf("%s\n", key);
}
#endif
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFSIZE 128
void exit_if_null(void *ptr, const char *msg);
int
main(int argc, char const *argv[]) {
FILE *filename;
char buffer[BUFFSIZE];
char *sequence;
char **ipinfo;
int str_size = 10, str_count = 0, i;
filename = fopen("ips.txt", "r");
if (filename == NULL) {
fprintf(stderr, "%s\n", "Error Reading File!");
exit(EXIT_FAILURE);
}
ipinfo = malloc(str_size * sizeof(*ipinfo));
exit_if_null(ipinfo, "Initial Allocation");
while (fgets(buffer, BUFFSIZE, filename) != NULL) {
sequence = strtok(buffer, "-\n");
while (sequence != NULL) {
if (str_size == str_count) {
str_size *= 2;
ipinfo = realloc(ipinfo, str_size * sizeof(*ipinfo));
exit_if_null(ipinfo, "Reallocation");
}
ipinfo[str_count] = malloc(strlen(sequence)+1);
exit_if_null(ipinfo[str_count], "Initial Allocation");
strcpy(ipinfo[str_count], sequence);
str_count++;
sequence = strtok(NULL, "-\n");
}
}
for (i = 0; i < str_count; i++) {
printf("%s\n", ipinfo[i]);
free(ipinfo[i]);
ipinfo[i] = NULL;
}
free(ipinfo);
ipinfo = NULL;
fclose(filename);
return 0;
}
void
exit_if_null(void *ptr, const char *msg) {
if (!ptr) {
printf("Unexpected null pointer: %s\n", msg);
exit(EXIT_FAILURE);
}
}
|
C
|
/*******************************************************************************
*(c) Copyright 2015 Microsemi SoC Products Group. All rights reserved.
*
* CoreGPIO example program.
*
* Please refer to the file README.txt for further details about this example.
*
* SVN $Revision: 8017 $
* SVN $Date: 2015-10-13 13:19:09 +0530 (Tue, 13 Oct 2015) $
*/
#include "hal/hal.h"
#include "platform.h"
#include "drivers/CoreGPIO/core_gpio.h"
gpio_instance_t g_gpio;
//#define INPUT_TO_OUTPUT_BIT_OFFSET 4
#define INPUT_TO_OUTPUT_BIT_OFFSET 0
/******************************************************************************
* main function.
*****************************************************************************/
int main( void )
{
uint32_t io_state;
/**************************************************************************
* Initialize the CoreGPIO driver with the base address of the CoreGPIO
* instance to use and the initial state of the outputs.
*************************************************************************/
GPIO_init( &g_gpio, COREGPIO_BASE_ADDR, GPIO_APB_32_BITS_BUS );
/**************************************************************************
* Configure the GPIOs.
*************************************************************************/
// GPIO_config( &g_gpio, GPIO_0, GPIO_OUTPUT_MODE );
// GPIO_config( &g_gpio, GPIO_1, GPIO_OUTPUT_MODE );
GPIO_config( &g_gpio, GPIO_0, GPIO_INOUT_MODE );
GPIO_config( &g_gpio, GPIO_1, GPIO_INOUT_MODE );
GPIO_config( &g_gpio, GPIO_2, GPIO_OUTPUT_MODE );
// GPIO_config( &g_gpio, GPIO_3, GPIO_OUTPUT_MODE );
// GPIO_config( &g_gpio, GPIO_4, GPIO_INPUT_MODE );
// GPIO_config( &g_gpio, GPIO_5, GPIO_INPUT_MODE );
/**************************************************************************
* Infinite Loop.
*************************************************************************/
while(1)
{
/**********************************************************************
* Read inputs.
*********************************************************************/
io_state = GPIO_get_inputs( &g_gpio );
/**********************************************************************
* Write state of inputs back to the outputs.
*********************************************************************/
io_state = io_state >> INPUT_TO_OUTPUT_BIT_OFFSET;
GPIO_set_outputs( &g_gpio, io_state );
}
}
|
C
|
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <signal.h>
#define SERVER_PORT ((uint16_t)7007)
#define BUFF_SIZE (1024 * 4)
int udp_echo(int client_fd)
{
char buff[BUFF_SIZE] = {0};
ssize_t len = 0;
struct sockaddr_in source_addr;
socklen_t addr_len = sizeof(source_addr);
(void)memset(&source_addr, 0, addr_len);
len = recvfrom(client_fd, buff, BUFF_SIZE, 0,
(struct sockaddr *)&source_addr, &addr_len);
if (len < 1) {
perror("recvfrom(2) error");
goto err;
}
len = sendto(client_fd, buff, len, 0,
(struct sockaddr *)&source_addr, addr_len);
if (len < 1) {
perror("sendto(2) error");
goto err;
}
printf("Served client %s:%hu\n",
inet_ntoa(source_addr.sin_addr),
ntohs(source_addr.sin_port));
fflush(stdout);
return EXIT_SUCCESS;
err:
return EXIT_FAILURE;
}
int main(void)
{
int server_sock;
struct sockaddr_in server_addr;
socklen_t sock_len = sizeof(server_addr);
server_sock = socket(AF_INET, SOCK_DGRAM, 0);
if (server_sock < 0) {
perror("socket(2) error");
goto create_err;
}
(void)memset(&server_addr, 0, sock_len);
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(SERVER_PORT);
if (bind(server_sock, (struct sockaddr *)&server_addr, sizeof(server_addr))) {
perror("bind(2) error");
goto err;
}
while (true) {
if (udp_echo(server_sock) != EXIT_SUCCESS) {
goto err;
}
}
perror("exit with:");
close(server_sock);
return EXIT_SUCCESS;
err:
close(server_sock);
create_err:
fprintf(stderr, "server error");
return EXIT_FAILURE;
}
|
C
|
#include <stdio.h>
#include <math.h>
int input(int *n, int *arr);
double count(int *n, int *arr);
void output(double *s);
int main()
{
int n, flag;
printf("Введите количество элементов массива: ");
int flag1 = ((scanf("%d", &n) != 1) || (n < 1) || (n > 10));
if (!(flag1))
{
int arr[10];
int flag2 = input(&n, arr);
if (!(flag2))
{
double s = count(&n, arr);
if (s == 0)
flag2 = 1;
else
{
output(&s);
}
}
else
printf("Ошибка ввода элемента массива \n");
flag = flag2;
}
else
{
printf("Ошибка ввода количества элементов\n");
flag = flag1;
}
return flag;
}
void output(double *s)
{
printf("%f\n", *s);
}
int input(int *n, int *arr)
{
int flag2 = 0;
for (int i = 0; i < *n; i++)
{
printf("Введите элемент массива: ");
int pc = (scanf("%d", &*(arr + i)));
if (pc != 1)
flag2 = 1;
}
return flag2;
}
double count(int *n, int *arr)
{
double s;
int k;
s = 1;
k = 0;
for (int i = 0; i < *n; i++)
{
if (*(arr + i) > 0)
{
k++;
s *= *(arr + i);
}
}
if (k != 0)
{
s = pow(s, 1.0 / (k));
}
else
s = 0;
return s;
}
|
C
|
#include <stdio.h>
#include <math.h>
int main() {
int power;
long gig_2 = (long)pow(2, 30);
long gig_10 = (long)pow(10, 9);
scanf("%d", &power);
printf("%ld", (gig_2*power - gig_10*power));
return 0;
}
|
C
|
#include <stdio.h>
short sss[100000];
int num = 0;
main ()
{
FILE *fp;
fp = fopen ("wor16.asc", "rb");
while (!feof (fp))
{
fread (&sss[num], sizeof (short), 1, fp);
num++;
}
fclose (fp);
fp = fopen ("desc.dat", "rb");
while (!feof (fp))
{
unsigned char c = fgetc (fp), c2;
short ssss;
int i;
if (c < 0x80)
continue;
c2 = fgetc (fp);
ssss = (c2 << 8) | c;
for (i = 0; i < num; i++)
if (sss[i] == ssss)
break;
if (i < num)
continue;
sss[num++] = ssss;
}
fclose (fp);
fp = fopen ("wor161.asc", "wb");
fwrite (sss, sizeof (short), num, fp);
fclose (fp);
}
|
C
|
#include "head.h"
void set(char *fomula, polyNode **array)
{
int state=STATE_COEF,i=0;
char coef[MAX]={}, expo[MAX]={};
// printf("set fomula:%s\n",fomula);
for(;*fomula!='\0';fomula++)
{
switch(state)
{
case STATE_COEF: // coef state
if(char_parity(*fomula,"0123456789."))
coef[i++]=*fomula;
else if(char_parity(*fomula,"x"))
{
if(coef[0]=='\0' || (coef[0]=='-'&&coef[1]=='\0'))
coef[i++]='1';
state=STATE_EXPO;
i=0;
}
break;
case STATE_EXPO: // expo state
if(char_parity(*fomula,"^"))
fomula++;
if(char_parity(*fomula,"012345789"))
expo[i++]=*fomula;
break;
}
if(char_parity(*fomula,"+-)"))
{
// printf("*fomula%c\n",*fomula);
if(coef[0]=='\0' && *fomula=='-')
{
coef[i++]='-';
continue;
}
if(expo[0]=='\0')
{
if(state==STATE_EXPO)
expo[0]='1';
else
expo[0]='0';
}
addPolyNode(array,atof(coef),atoi(expo));
memset(coef,'\0',sizeof(coef));
memset(expo,'\0',sizeof(expo));
state=STATE_COEF;
i=0;
if(*fomula=='-')
coef[i++]='-';
}
}
// for(p=array;p;p=p->next)
// printf("[%f] [%d] \n",p->coef,p->expo);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define LEN 100
main () {
FILE *fp;
int i, k;
double x, data[LEN];
if ((fp = fopen("random.dat", "w")) == NULL ) {
printf("Errore nell'apertura del file random.dat\n");
exit(EXIT_FAILURE);
}
for (i = 1; i <= LEN; i++) {
x = (double)rand() / (double)RAND_MAX;
fprintf(fp, "%d %f\n", i, x);
}
fclose(fp);
fp = fopen("random.dat", "r+");
for (i = 1; i <= LEN; i++) {
fscanf(fp, "%d %lf", &k, &x);
*(data + LEN - k) = x;
}
fprintf(fp, "\n INVERSIONE \n");
for (i = 1; i <= LEN; i++) {
fprintf(fp, "%d %f\n", i, *(data + i - 1));
}
fclose(fp);
}
|
C
|
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/list.h>
#include <linux/slab.h>
#define PDEBUG(fmt, args...) printk("[%s:%d]" fmt, __FUNCTION__, __LINE__, ## args)
struct simplelist
{
struct list_head node;
char buffer;
};
LIST_HEAD(mylist);
struct simplelist *create_list_node(void)
{
struct simplelist *p;
p = (struct simplelist *)kmalloc(sizeof(struct simplelist),GFP_KERNEL);
return p;
}
int create_simple_list(int size)
{
int i=0;
struct simplelist *p;
for(i = 0; i < size; i++) {
p = create_list_node();
p->buffer = 0x31+i;
list_add_tail(&p->node,&mylist);
}
return 0;
}
void each_simple_list(void)
{
struct simplelist* slistp;
list_for_each_entry(slistp, &mylist, node) {
PDEBUG("find a list buffer is %c\n", slistp->buffer);
}
return ;
}
static int demo_module_init(void)
{
PDEBUG("demo_module_init\n");
create_simple_list(5);
each_simple_list();
return 0;
}
static void demo_module_exit(void)
{
PDEBUG("demo_module_exit\n");
}
module_init(demo_module_init);
module_exit(demo_module_exit);
MODULE_DESCRIPTION("simple list module");
MODULE_LICENSE("GPL");
|
C
|
//Calendar.h
#include<iostream>
#include<cstring>
#include<conio.h>
#include<iomanip>
class Calendar
{
private:
int month;
int year;
int firstday;
public:
Calendar(int =2, int =2017);
void setFirstDay();
void print();
};
//Calendar.cpp
Calendar :: Calendar (int _month, int _year){
month = _month;
year = _year;
}
void Calendar :: setFirstDay(){
//This part determines which day will be the first day of that year (0 for Sunday, 1 for Monday, etc.)
int day=1;
int y = year - (14-month)/12;
int m = month +12 * ((14-month) / 12) -2;
firstday= (day + y + y / 4 - y / 100 + y / 400 + (31 * m / 12)) % 7;
}
void Calendar :: print(){
int NumberOfDaysInMonth;
int FirstDayOfMonth = 0;
int DayOfWeekCounter = 0;
int DateCounter = 1;
switch (month)
{
case 1:
cout<<setw(21)<<"January "<<year;
NumberOfDaysInMonth = 31;
break;
case 2:
cout<<setw(21)<<"February "<<year;
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
NumberOfDaysInMonth = 29;
else
NumberOfDaysInMonth = 28;
break;
case 3:
cout<<setw(21)<<"March "<<year;
NumberOfDaysInMonth = 31;
break;
case 4:
cout<<setw(21)<<"April "<<year;
NumberOfDaysInMonth = 30;
break;
case 5:
cout<<setw(21)<<"May "<<year;
NumberOfDaysInMonth = 31;
break;
case 6:
cout<<setw(21)<<"June "<<year;
NumberOfDaysInMonth = 30;
break;
case 7:
cout<<setw(21)<<"July "<<year;
NumberOfDaysInMonth = 31;
break;
case 8:
cout<<setw(21)<<"August "<<year;
NumberOfDaysInMonth = 31;
break;
case 9:
cout<<setw(21)<<"September "<<year;
NumberOfDaysInMonth = 30;
break;
case 10:
cout<<setw(21)<<"October "<<year;
NumberOfDaysInMonth = 31;
break;
case 11:
cout<<setw(21)<<"November "<<year;
NumberOfDaysInMonth = 30;
break;
case 12:
cout<<setw(21)<<"December "<<year;
NumberOfDaysInMonth = 31;
break;
}
//Display the days at the top of each month
cout<<"\nSun Mon Tue Wed Thu Fri Sat";
cout<<"\n\n"<<setw(2);
//Determine where the first day begins
for (FirstDayOfMonth; FirstDayOfMonth < firstday; ++FirstDayOfMonth)
{
cout<<setw(14);
}
int tempfirstday=firstday;
DateCounter = 1;
DayOfWeekCounter = tempfirstday;
//This loop represents the date display and will continue to run until
//the number of days in that month have been reached
for (DateCounter; DateCounter <= NumberOfDaysInMonth; ++DateCounter)
{
cout<<DateCounter<<setw(6);
++DayOfWeekCounter;
if (DayOfWeekCounter > 6)
{
cout<<"\n\n"<<setw(2);
DayOfWeekCounter = 0;
}
}
cout << " \n" ;
tempfirstday = DayOfWeekCounter + 1;
}
/*
int main() //This was to just be able to run your class...
{
Calendar c;
//clrscr();
c.setFirstDay();
c.print();
getch();
return 0;
}
*/
|
C
|
#include <stdio.h>
struct process{
int p[50];
float at[50];
float bt[50];
float ct[50];
float tat[50];
float wt[50];
}o, a, b, c;
int i, j, n, pos;
float min, temp, temp1, temp2, total;
void user_input(){
printf("Enter the number of processes you wish to enter: ");
scanf("%d", &n);
printf("Enter arrival time and burst time for the processes: ");
for(i = 0; i < n; i++){
a.p[i] = i+1;
printf("p%d:\n", i+1);
printf("Arrival time : ");
scanf("%f", &a.at[i]);
printf("Burst time : ");
scanf("%f", &a.bt[i]);
}
}
void result(struct process p){
float avg = 0;
total = 0;
printf("\n\tP.No.\tAT\tBT\tCT\tTAT\tWT\n");
for(i = 0; i < n; i++){
printf("\t%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\n", p.p[i], p.at[i], p.bt[i], p.ct[i], p.tat[i], p.wt[i]);
total += p.tat[i];
}
avg = total/n;
printf("\n\tThe average turnaround time is : %.2f secs\n\n", avg);
}
void mnm(float arr[]){
min = arr[0];
while(i < n){
if(arr[i] < min){
min = arr[i];
i++;
}
}
}
void sort(float arr[], float arr1[], int arr2[]){
for(i = 1; i < n; i++){
temp = arr[i];
temp1 = arr1[i];
temp2 = arr2[i];
j = i-1;
while((temp < arr[j]) && (arr[j] >= 0)){
arr[j+1] = arr[j];
arr1[j+1] = arr1[j];
arr2[j+1] = arr2[j];
j--;
}
arr[j+1] = temp;
arr1[j+1] = temp1;
arr2[j+1] = temp2;
}
}
void fcfs(){
b = a;
sort(b.at, b.bt, b.p);
total = b.at[0];
for(i = 0; i < n; i++){
total += b.bt[i];
b.ct[i] = total;
b.tat[i] = b.ct[i] - b.at[i];
b.wt[i] = b.tat[i] - b.bt[i];
}
printf("\n\tAfter applying First Come First Serve.\n");
result(b);
}
void sjf(){
c = a;
mnm(c.at);
sort(c.bt, c.at, c.p);
for(i = 0; i < n; i++){
if(c.at[i] == min){
pos = i;
temp = c.p[pos];
temp1 = c.at[pos];
temp2 = c.bt[pos];
for(j = pos; j > 0; j--){
c.p[j] = c.p[j-1];
c.at[j] = c.at[j-1];
c.bt[j] = c.bt[j-1];
}
c.p[0] = temp;
c.at[0] = temp1;
c.bt[0] = temp2;
}
}
total = c.at[0];
for(i = 0; i < n; i++){
total += c.bt[i];
c.ct[i] = total;
c.tat[i] = c.ct[i] - c.at[i];
c.wt[i] = c.tat[i] - c.bt[i];
}
printf("\n\tAfter applying Shortest Job First.\n");
result(c);
}
void sjfi(){
b = a;
sort(b.bt, b.at, b.p);
for(i = 0; i < n; i++){
if(b.at[i] >= 1.00){
pos = i;
temp = b.p[pos];
temp1 = b.at[pos];
temp2 = b.bt[pos];
for(j = pos; j > 0; j--){
b.p[j] = b.p[j-1];
b.at[j] = b.at[j-1];
b.bt[j] = b.bt[j-1];
}
b.p[0] = temp;
b.at[0] = temp1;
b.bt[0] = temp2;
}
}
printf("\n\tAfter applying Shortest Job First with idle time = 1.\n");
total = b.at[0];
for(i = 0; i < n; i++){
total += b.bt[i];
b.ct[i] = total;
b.tat[i] = b.ct[i] - b.at[i];
b.wt[i] = b.tat[i] - b.bt[i];
}
result(b);
}
int main(){
user_input();
fcfs();
sjf();
sjfi();
return 0;
}
|
C
|
/*
* ============================================================================
*
* Filename: stoi.c
*
* Description: 将输入的字符串中16进制数字提取出来,并计算其10进制的值
*
* Version: 1.0
* Created: 07/01/2020 10:02:26 AM
* Revision: none
* Compiler: gcc
*
* Author: lin chuan , [email protected]
* Organization:
*
* ============================================================================
*/
#include <stdio.h>
#include <math.h>
int char2int(char c);
int isHex(char c);
int main() {
char s[80];
scanf("%s", s);
// 将s中的合法16进制字符提取出来, 放到new中
char new[80];
int i = 0;
int n = 0;
while(s[i] != 0) {
if (isHex(s[i])) {
new[n] = s[i];
n++;
}
i++;
}
new[n] = 0;
printf("new is %s\n", new);
// 将new里面的字符串转成10进制数字
int value = 0;
for (int j = 0; j < n; j++) {
// value = value + char2int(new[j]) * pow(16, n-j-1);
// value = value * 16 + char2int(new[j]);
value = (value << 4) + char2int(new[j]);
}
printf("%d\n", value);
return 0;
}
int char2int(char c) {
if (c >= '0' && c <= '9')
return c-'0';
else if (c >= 'a' && c <= 'f')
return 10 + c - 'a';
else
return 10 + c - 'A';
}
int isHex(char c) {
if ((c >= '0' && c <= '9')
|| (c >= 'a' && c <= 'f')
|| (c >= 'A' && c <= 'F')) {
return 1;
}
else {
return 0;
}
}
|
C
|
/*17mutex.c
Usando mutex
*/
//Miguel Angel Mendoza Guadarrama
//02 - abril - 2018
#include <stdio.h>
#include <pthread.h>
#define NUM_HILOS 2
#define CICLO 100
double b;
void* hiloDeposito(void *i){
double m = *(double *) (i);
int j;
printf("Entrando a hiloDeposito \n");
for(j = 0; j < CICLO + 1; j++){
b += m;
//sleep(1);
}
}
void* hiloRetiro(void *i){
double m = *(double *) (i);
int j;
printf("Entrando a hiloRetiro \n");
for(j = 0; j < CICLO; j++){
b -= m;
//sleep(1);
}
}
int main(){
int i;
double bi;
double q = 10.0;
printf("Antes de crear tipo de hilos \n");
pthread_t tid[NUM_HILOS];
b = 100000.0;
bi = b;
printf("Antes de crear los hilos \n");
pthread_create(&tid[0], NULL, hiloDeposito, (void *) (&q));
pthread_create(&tid[1], NULL, hiloRetiro, (void *) (&q));
for(i = 0; i < NUM_HILOS; i++){
pthread_join(tid[i], NULL);
}
printf("El balance inicial es: %.2lf \nEl balance final es: %.2lf \n", bi, b);
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
char str[100];
char srt[100];
printf("ENTER STRINGS:\n");
gets(str);
gets(srt);
int i,j,check=0;
for(i=0;str[i]!='\0' || srt[i]!='\0';i++)
{
if(str[i]!=srt[j])
{
check=1;
}
}
if(check==0)
{
printf("strings are same\n");
}
else if(check==1)
{
printf("strings are different\n");
}
}
|
C
|
int sum(int n){
int res = 0;
res = (n+1)*n/2;
return res;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include "choose.h"
int choose(int numOfUsers){
int ans;
printf("\n\nPlease select which user you would like to provide friend suggestions for.\n");
printf("(E.g. Enter '1' for your first user, '2' for your second user etc): \n");
scanf("%d", &ans);
//if the user enters a number greater than the number of users or less than or equal to zero, we make them choose again, until they pick a vlaid number
//i feel this is better than just force closing the program
while (ans > numOfUsers || ans <= 0)
{
printf("You have not inputted that many users, please choose again: ");
scanf("%d", &ans);
}
ans = ans-1;
//we return our answer into the variable choice
return ans;
}
|
C
|
#include <stdio.h>
float approx_pi(int);
int main(){
int n;
scanf("%d", &n);
printf("%.6f\n", approx_pi(n));
return 0;
}
float approx_pi(int reps){
int i;
int sign = 1;
float pi = 0;
for(i = 0; i < reps; i++){
pi += sign * 4.0 / (2*i + 1);
sign *= -1;
}
return pi;
}
|
C
|
#include <stdio.h>
int main()
{
char ch;
int a[201],b[201],sum[102];
int i,m,n,max;
while(scanf("%c",&ch)!=EOF){
i=101;
do{
if(ch>='0'&&ch<='9') a[i++]=ch-'0';
else a[i++]=ch-'a'+10;
}while((ch=getchar())!='\n');
m=i;
i=101;
while((ch=getchar())!='\n'){
if(ch>='0'&&ch<='9') b[i++]=ch-'0';
else b[i++]=ch-'a'+10;
}
n=i;
max=((m>n)?m:n)-101;
for(i=101-max;i<101;i++){
a[i]=b[i]=0;
}
sum[0]=0;
for(i=1;i<=max+1;i++){
sum[i]=a[m-i]+b[n-i];
if(sum[i-1]>=20){
sum[i-1]-=20;
sum[i]+=1;
}
}
if(sum[max+1])
for(i=max+1;i>=1;i--){
if(sum[i]>=0&&sum[i]<=9) printf("%c",sum[i]+'0');
else printf("%c",sum[i]-10+'a');
}
else
for(i=max;i>=1;i--){
if(sum[i]>=0&&sum[i]<=9) printf("%c",sum[i]+'0');
else printf("%c",sum[i]-10+'a');
}
printf("\n");
}
return 0; /* NZEC */
}
/*DONE*/
/* //Run ID Submit time Judge Status Problem ID Language Run time Run memory User Name */
/* //2461227 2007-05-24 22:33:00 Accepted 1205 C 00:00.00 388K 錄 */
/* //Run ID Submit time Judge Status Problem ID Language Run time Run memory User Name */
/* //2464509 2007-05-26 23:05:49 Accepted 1205 C 00:00.01 388K 錄 */
// 2012-09-07 02:57:46 | Accepted | 1205 | C | 0 | 160 | watashi | Source
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
/* Variables and functions */
int /*<<< orphan*/ printf (char*) ;
__attribute__((used)) static void usage() {
printf("Usage: yc "
"[-h] [-v] [-d] [-t] [-s SERVER] [-p PORT] [-c COMPRESS] COMMAND ...\n\n"
"Options:\n"
" -h print help and exit.\n"
" -v print version information.\n"
" -d turn on debug messages.\n"
" -t turn on text protocol mode.\n"
" -q Use quiet commands, if possible.\n"
" -s connect to SERVER. Default: localhost\n"
" -p TCP port number. Default: 11211\n"
" -c compression threshold. Default: 16384\n\n"
"Commands:\n"
" noop\n"
" ping the server.\n"
" get KEY\n"
" get an object.\n"
" getk KEY\n"
" get an object with key.\n"
" gat KEY EXPIRE\n"
" get and touch an object.\n"
" gatk KEY EXPIRE\n"
" get and touch an object with key.\n"
" lag KEY\n"
" lock and get an object.\n"
" lagk KEY\n"
" lock and get an object with key.\n"
" touch KEY EXPIRE\n"
" touch an object.\n"
" set KEY FILE [EXPIRE [FLAGS [CAS]]]\n"
" store FILE data. If FILE is \"-\", stdin is used.\n"
" replace KEY FILE [EXPIRE [FLAGS [CAS]]]\n"
" update an existing object. FILE is the same as set.\n"
" add KEY FILE [EXPIRE [FLAGS [CAS]]]\n"
" create a new object. FILE is the same as set.\n"
" rau KEY FILE [EXPIRE [FLAGS]]\n"
" replace a locked object then unlock it.\n"
" Since this command always fails, do not use this.\n"
" incr KEY VALUE [INITIAL [EXPIRE]]\n"
" increments an exiting object's value by VALUE.\n"
" If INITIAL is given, new object is created when KEY\n"
" is not found. EXPIRE is used only when an object is\n"
" created.\n"
" decr KEY VALUE [INITIAL [EXPIRE]]\n"
" decrements an exiting object's value by VALUE.\n"
" If INITIAL is given, new object is created when KEY\n"
" is not found. EXPIRE is used only when an object is\n"
" created.\n"
" append KEY FILE\n"
" append FILE data FILE is the same as set.\n"
" prepend KEY FILE\n"
" prepend FILE data FILE is the same as set.\n"
" delete KEY\n"
" delete an object.\n"
" lock KEY\n"
" locks an object.\n"
" unlock KEY\n"
" this command always fails. Do not use this.\n"
" unlockall\n"
" this command has no effect.\n"
" flush [DELAY]\n"
" flush all unlocked items immediately or after DELAY seconds.\n"
" stat [settings|items|sizes]\n"
" obtain general or specified statistics.\n"
" keys [PREFIX]\n"
" dump keys matching PREFIX.\n"
" version\n"
" shows the server version.\n"
" quit\n"
" just quits. Not much interesting.\n"
);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
//Variablen werden deklariert
int a, b, c;
//Ein offset wird eingegebe
printf("Offset: ");
scanf("%i", &a);
srand(time(NULL) + a);
//Die Größer der Klasser wird eingegeben
printf("Größe der Klasse: ");
scanf("%i", &b);
//Es wird öfters gewürfelt
for(int i = 0; i < rand() % 21; i++) {
c = 1 + (rand() % b);
}
//Ausgabe der Zahl
printf("Schüler Nr: %i\n", c);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jterrazz <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/07/27 20:47:31 by jterrazz #+# #+# */
/* Updated: 2019/07/27 20:49:52 by jterrazz ### ########.fr */
/* */
/* ************************************************************************** */
#include "./test.h"
#include <stdio.h>
int assert(int cond)
{
if (cond) {
printf("Success\n");
return 1;
}
printf("Failure\n");
return 0;
}
int main(int argc, char **argv)
{
test_ft_bzero();
test_ft_isalpha();
test_ft_isupper();
test_ft_islower();
test_ft_isdigit();
test_ft_isalnum();
test_ft_isascii();
test_ft_isprint();
test_ft_toupper();
test_ft_tolower();
test_ft_strlen();
test_ft_puts();
test_ft_memset();
test_ft_memcpy();
test_ft_strdup();
test_ft_memalloc();
test_ft_strcat();
test_ft_putnbr();
test_ft_memdel();
test_ft_memmove();
test_ft_strncpy();
test_ft_strrchr();
test_ft_cat(argc, argv);
}
|
C
|
#include "test_kvtree.h"
#include "test_kvtree_util.h"
#include "kvtree_mpi.h"
#include <mpi.h>
#include <stdio.h>
//This is the test of kvtree_write_gather/kvtree_read_scatter functionality. The former writes a hash from multiple processes to files with specified prefex,
//and the latter reads them from files.
int main(int argc, char** argv){
kvtree* recv;
kvtree* send;
//int rc = TEST_PASS;
int rank, ranks, kvtree_rc;
int val_of_one, val_of_two, val_of_three;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &ranks);
if( ranks != 3){
printf("test_kvtree_write_gather, tests require 3 processes; actual # is %d\n", ranks);
return TEST_FAIL;
}
send = kvtree_new();
recv = kvtree_new();
if(rank == 0){
kvtree_util_set_int(send, "ONE", 1);
kvtree_util_set_int(send, "TWO", 2);
}
if(rank == 2){
kvtree_util_set_int(send, "ONE", -1);
kvtree_util_set_int(send, "THREE", 3);
}
kvtree_rc = kvtree_write_gather("PREFIX", send, MPI_COMM_WORLD);
if (kvtree_rc != KVTREE_SUCCESS){
printf("test_kvtree_write_gather, kvtree_write_gather operation failed");
printf ("Error in line %d, file %s, function %s.\n", __LINE__, __FILE__, __func__);
return TEST_FAIL;
}
kvtree_rc = kvtree_read_scatter("PREFIX", recv, MPI_COMM_WORLD);
if (kvtree_rc != KVTREE_SUCCESS){
printf("test_kvtree_write_gather, kvtree_read_scatter operation failed");
printf ("Error in line %d, file %s, function %s.\n", __LINE__, __FILE__, __func__);
return TEST_FAIL;
}
if (recv == NULL){
printf("test_kvtree_write_gather, kvtree_read_scatter operation returned NULL kvtree");
printf ("Error in line %d, file %s, function %s.\n", __LINE__, __FILE__, __func__);
return TEST_FAIL;
}
printf("rank=%d, send\n", rank);
kvtree_print(send, 4);
printf("rank=%d, recv\n", rank);
kvtree_print(recv, 4);
if(rank == 0){
kvtree_rc = kvtree_util_get_int(recv, "ONE", &val_of_one);
if (kvtree_rc != KVTREE_SUCCESS){
printf("test_kvtree_write_gather, rank=0, recv read of 'ONE' failed");
printf ("Error in line %d, file %s, function %s.\n", __LINE__, __FILE__, __func__);
return TEST_FAIL;
}
if(val_of_one != 1){
printf("test_kvtree_write_gather, rank=0, recv read of 'ONE' returned wrong value");
printf ("Error in line %d, file %s, function %s.\n", __LINE__, __FILE__, __func__);
return TEST_FAIL;
}
kvtree_rc = kvtree_util_get_int(recv, "TWO", &val_of_two);
if (kvtree_rc != KVTREE_SUCCESS){
printf("test_kvtree_write_gather, rank=0, recv read of 'TWO' failed");
printf ("Error in line %d, file %s, function %s.\n", __LINE__, __FILE__, __func__);
return TEST_FAIL;
}
if(val_of_two != 2){
printf("test_kvtree_write_gather, rank=0, recv read of 'TWO' returned wrong value");
printf ("Error in line %d, file %s, function %s.\n", __LINE__, __FILE__, __func__);
return TEST_FAIL;
}
}
if(rank == 2){
kvtree_rc = kvtree_util_get_int(recv, "ONE", &val_of_one);
if (kvtree_rc != KVTREE_SUCCESS){
printf("test_kvtree_write_gather, rank=2, recv read of 'ONE' failed");
printf ("Error in line %d, file %s, function %s.\n", __LINE__, __FILE__, __func__);
return TEST_FAIL;
}
if(val_of_one != -1){
printf("test_kvtree_write_gather, rank=2, recv read of 'ONE' returned wrong value");
printf ("Error in line %d, file %s, function %s.\n", __LINE__, __FILE__, __func__);
return TEST_FAIL;
}
kvtree_rc = kvtree_util_get_int(recv, "THREE", &val_of_three);
if (kvtree_rc != KVTREE_SUCCESS){
printf("test_kvtree_write_gather, rank=2, recv read of 'THREE' failed");
printf ("Error in line %d, file %s, function %s.\n", __LINE__, __FILE__, __func__);
return TEST_FAIL;
}
if(val_of_three != 3){
printf("test_kvtree_write_gather, rank=2, recv read of 'THREE' returned wrong value");
printf ("Error in line %d, file %s, function %s.\n", __LINE__, __FILE__, __func__);
return TEST_FAIL;
}
}
if(rank ==1){
if(kvtree_size(recv) != 0){
printf("test_kvtree_write_gather, rank=1, sending hash of size 0 resulted in non-zero receive");
printf ("Error in line %d, file %s, function %s.\n", __LINE__, __FILE__, __func__);
return TEST_FAIL;
}
}
kvtree_delete(&send);
if (send != NULL){
printf("test_kvtree_write_gather, deletion of kvtree failed");
printf ("Error in line %d, file %s, function %s.\n", __LINE__, __FILE__, __func__);
return TEST_FAIL;
}
kvtree_delete(&recv);
if (recv != NULL){
printf("deletion of recv failed");
printf ("Error in line %d, file %s, function %s.\n", __LINE__, __FILE__, __func__);
return TEST_FAIL;
}
MPI_Finalize();
return TEST_PASS;
}
|
C
|
/*
* AI - Computational Search Using A* Search Algorithm.
*
* http://en.wikipedia.org/wiki/A*_search_algorithm
*
* To allow this A* Search algorithm to be used on any problem,
* the search is written independent of the Model State, the Actions, etc.
*
* Actions and Model States have 'data' field for data specific to a problem.
* Likewise all implementation specific functions are passed into the search.
* e.g. Successor Function, Transition Function.
*
* Please see the test_ai_search_demo.c for an implementation example.
*
* Created on: 6 Jan 2015
* Author: xenomorpheus
*/
#include <ai_search.h>
#include <logging.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Constructor for an Action.
ai_action *ai_action_constructor(void *data) {
ai_action *action = (ai_action *)malloc(sizeof(ai_action));
check(action, "ai_action_constructor malloc failed");
action->data = data;
action->next = NULL;
return action;
error:
return NULL;
}
// Alias for ai_action_constructor
ai_path *ai_path_constructor(void *data) {
return (ai_path *)ai_action_constructor(data);
}
// Assumes that action's "next" is already set to correct value.
// E.g. NULL, or linked to next action if appending a path.
void _ai_path_append_action(ai_path **path, ai_action *action) {
check(path, "_ai_path_append_action path was NULL");
check(action, "_ai_path_append_action action was NULL");
if (*path) {
ai_path *ptr = *path;
// Find end
while (ptr->next) {
ptr = ptr->next;
}
ptr->next = action;
} else {
*path = action;
}
return;
error:
return;
}
// ai_path *new_path = _ai_path_duplicate(old_path);
ai_path *_ai_path_duplicate(ai_action_data_duplicator action_data_duplicator,
ai_path *old) {
ai_path *new = NULL;
while (old) {
ai_action *new_action =
ai_action_constructor(action_data_duplicator(old->data));
_ai_path_append_action(&new, new_action);
old = old->next;
}
return new;
}
// ai_model_state *model_state = ai_model_state_constructor(data);
ai_model_state *ai_model_state_constructor(void *data) {
ai_model_state *model_state =
(ai_model_state *)malloc(sizeof(ai_model_state));
check(model_state, "ai_model_state_constructor malloc failed");
model_state->data = data;
return model_state;
error:
return NULL;
}
// ai_successor *successor = ai_successor_constructor(model_state, action,
// cost);
ai_successor *ai_successor_constructor(ai_model_state *model_state,
ai_action *action, float cost) {
ai_successor *successor = (ai_successor *)malloc(sizeof(ai_successor));
check(successor, "ai_successor_constructor malloc failed");
successor->model_state = model_state;
successor->action = action;
successor->cost = cost;
// TODO cheat? Allow a linked list of successors
successor->next = NULL;
return successor;
error:
return NULL;
}
// Constructor for a Fringe Element. Used when searching.
// ai_fringe_element *fe = ai_fringe_element_constructor(model_state,
// path_so_far, 0.0f, 0.0f);
ai_fringe_element *ai_fringe_element_constructor(ai_model_state *model_state,
ai_path *path_so_far,
float cost_so_far,
float est_total_cost) {
ai_fringe_element *fe =
(ai_fringe_element *)malloc(sizeof(ai_fringe_element));
check(fe, "ai_fringe_element_constructor malloc failed");
fe->model_state = model_state;
fe->path_so_far = path_so_far;
fe->cost_so_far = cost_so_far;
fe->est_total_cost = est_total_cost;
fe->next = NULL;
return fe;
error:
return NULL;
}
ai_fringe_element *
_ai_fringe_element_list_pop(ai_fringe_element **fringe_element_list) {
ai_fringe_element *head = *fringe_element_list;
if (head) {
*fringe_element_list = head->next;
}
return head;
}
// Add Fringe Element to the list.
// The list is sorted by est_total_cost, low first.
void _ai_fringe_element_list_add_by_total_cost(
ai_fringe_element **fringe_element_list, ai_fringe_element *node) {
ai_fringe_element *prev, *current;
float est_total_cost = node->est_total_cost;
// Remove this if we need to add lists to lists.
node->next = NULL;
if (!*fringe_element_list) {
*fringe_element_list = node;
} else {
prev = NULL;
current = *fringe_element_list;
while (current && current->est_total_cost <= est_total_cost) {
prev = current;
current = current->next;
}
if (!current) {
prev->next = node;
} else {
if (prev) {
node->next = prev->next;
prev->next = node;
} else {
node->next = *fringe_element_list;
*fringe_element_list = node;
}
}
}
}
// Free the path and any implementation specific data
void _ai_path_free(ai_path *ptr, ai_action_data_free action_data_free) {
ai_path *next = NULL;
while (ptr) {
next = ptr->next;
// Implementation should provide the method to free the action data
// because action data may be immutable and reused, hence should not be
// freed.
if (ptr->data && action_data_free) {
action_data_free(ptr->data);
}
free(ptr);
ptr = next;
}
}
// Duplicate the Model State and data.
ai_model_state *_ai_model_state_duplicate(
ai_model_state *model_state,
ai_model_state_data_duplicator model_state_data_duplicator) {
void *dup_data = model_state_data_duplicator(model_state->data);
return ai_model_state_constructor(dup_data);
}
// Free the Model State and data.
void _ai_model_state_free(ai_model_state *model_state,
ai_model_state_data_free model_state_data_free) {
if (model_state) {
if (model_state->data && model_state_data_free) {
model_state_data_free(model_state->data);
}
free(model_state);
}
}
// private - AStar search algorithm
ai_path *
_ai_search_astar_find_path_to_goal(ai_search_astar *astar,
ai_model_state *initial_model_state) {
// Aliases for functions that are Model State and Action specific.
ai_model_state_evaluator *model_state_evaluator =
astar->model_state_evaluator;
ai_successor_function successor_function =
model_state_evaluator->successor_function;
ai_transition_function transition_function =
model_state_evaluator->transition_function;
ai_is_goal_state_function is_goal_state_function =
model_state_evaluator->is_goal_state_function;
ai_goal_est_cost_function goal_est_cost_function =
model_state_evaluator->goal_est_cost_function;
ai_model_state_data_duplicator model_state_data_duplicator =
model_state_evaluator->model_state_data_duplicator;
ai_model_state_data_free model_state_data_free =
model_state_evaluator->model_state_data_free;
ai_action_data_duplicator action_data_duplicator =
model_state_evaluator->action_data_duplicator;
ai_action_data_free action_data_free =
model_state_evaluator->action_data_free;
// Init
ai_model_state *dup_initial_model_state = _ai_model_state_duplicate(
initial_model_state, model_state_data_duplicator);
// Technically the cost should be remaining distance to goal, but
// it is the only item in the fringe so will be popped regardless.
ai_fringe_element *fringe_list =
ai_fringe_element_constructor(dup_initial_model_state, NULL, 0, 0);
ai_path *result_path = NULL;
// Begin of fringe expansion loop.
while ((fringe_list != NULL) &&
((astar->fringe_expansion_max == 0) ||
(astar->fringe_expansion_count < astar->fringe_expansion_max))) {
astar->fringe_expansion_count++;
ai_fringe_element *fringe = _ai_fringe_element_list_pop(&fringe_list);
ai_model_state *current_model_state = fringe->model_state;
ai_path *current_path_so_far = fringe->path_so_far;
float cost_so_far = fringe->cost_so_far;
free(fringe);
if (is_goal_state_function(current_model_state)) {
result_path = current_path_so_far;
break;
}
ai_successor *successor_list =
successor_function(current_model_state, transition_function);
ai_successor *successor_next = NULL;
for (ai_successor *successor = successor_list; successor != NULL;
successor = successor_next) {
ai_model_state *successor_model_state = successor->model_state;
// TODO check if we have seen this state before
// TODO add this model state to states we have seen.
ai_path *new_path_so_far =
_ai_path_duplicate(action_data_duplicator, current_path_so_far);
_ai_path_append_action(&new_path_so_far, successor->action);
float new_cost_so_far = cost_so_far + successor->cost;
successor_next = successor->next;
free(successor);
successor = NULL;
float cost_to_goal_est = 0;
if (goal_est_cost_function != NULL) {
cost_to_goal_est = goal_est_cost_function(successor_model_state);
}
ai_fringe_element *fringe_element_new = ai_fringe_element_constructor(
successor_model_state, new_path_so_far, new_cost_so_far,
new_cost_so_far + cost_to_goal_est);
_ai_fringe_element_list_add_by_total_cost(&fringe_list,
fringe_element_new);
}
// TODO free as much mem as possible
_ai_path_free(current_path_so_far, action_data_free);
current_path_so_far = NULL;
_ai_model_state_free(current_model_state, model_state_data_free);
current_model_state = NULL;
}
// Free the fringe
ai_fringe_element *current_fe = NULL;
while ((current_fe = _ai_fringe_element_list_pop(&fringe_list)) != NULL) {
_ai_model_state_free(current_fe->model_state, model_state_data_free);
_ai_path_free(current_fe->path_so_far, action_data_free);
free(current_fe);
}
return result_path;
}
// ai_search_astar *astar = ai_search_astar_constructor(model_state_evaluator);
// ai_path *path = astar->find_path_to_goal(astar, model_state );
ai_search_astar *
ai_search_astar_constructor(ai_model_state_evaluator *model_state_evaluator) {
ai_search_astar *astar = (ai_search_astar *)malloc(sizeof(ai_search_astar));
check(astar, "ai_search_astar_constructor malloc failed");
astar->find_path_to_goal = _ai_search_astar_find_path_to_goal;
astar->model_state_evaluator = model_state_evaluator;
astar->fringe_expansion_count = 0;
astar->fringe_expansion_max = 0;
return astar;
error:
return NULL;
}
|
C
|
//Pogram liczy 2^n
#include<stdio.h>
main(){
int n, i, wynik=1;
printf("Podaj wykładnik: ");
scanf("%d", &n);
if (n>=0){
for (i=0; n>i; ++i)
wynik=wynik*2;
printf("%d", wynik);
}
else printf("Podałeś złą liczbę!");
}
|
C
|
//Copyright (C) 2013 Steve Taylor ([email protected]), Davis E. King
//License: Boost Software License. See LICENSE.txt for full license.
#ifndef DLIB_NUMERIC_CONSTANTs_H_
#define DLIB_NUMERIC_CONSTANTs_H_
// pi -- Pi
const double pi = 3.1415926535897932385;
// e -- Euler's Constant
const double e = 2.7182818284590452354;
// sqrt_2 -- The square root of 2
const double sqrt_2 = 1.4142135623730950488;
// sqrt_3 -- The square root of 3
const double sqrt_3 = 1.7320508075688772935;
// log10_2 -- The logarithm base 10 of two
const double log10_2 = 0.30102999566398119521;
// light_spd -- The speed of light in vacuum in meters per second
const double light_spd = 2.99792458e8;
// newton_G -- Newton's gravitational constant (in metric units of m^3/(kg*s^2))
const double newton_G = 6.67384e-11;
// planck_cst -- Planck's constant (in units of Joules * seconds)
const double planck_cst = 6.62606957e-34;
// golden_ratio -- The Golden Ratio
const double golden_ratio = 1.6180339887498948482;
// euler_gamma -- The Euler Mascheroni Constant
const double euler_gamma = 0.5772156649015328606065;
// catalan -- Catalan's Constant
const double catalan = 0.91596559417721901505;
// glaisher -- Glaisher Kinkelin constant
const double glaisher = 1.2824271291006226369;
// khinchin -- Khinchin's constant
const double khinchin = 2.6854520010653064453;
// apery -- Apery's constant
const double apery = 1.2020569031595942854;
#endif //DLIB_NUMERIC_CONSTANTs_H_
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.