language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C | #include<stdio.h>
int main()
{
float units,cost=0;
printf("Enter number of units consumed: ");
scanf("%f",&units);
if(units>0 && units<=100){
cost=units*5;
} else if(units>100 && units<=130){
cost=(100*5)+(units-100)*5.5;
} else if(units>130 && units<=150){
cost=(100*5)+(30*5.5)+(units-130)*6;
} else if(units>150){
cost=(100*5)+(30*5.5)+(20*6)+(units-150)*7;
}
printf("The total bill is %.2f\n",cost);
}
|
C | /* ISC license. */
#include <skalibs/nonposix.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <skalibs/uint16.h>
#include <skalibs/bytestr.h>
#include <skalibs/socket.h>
int socket_bind4 (int s, char const *ip, uint16 port)
{
struct sockaddr_in sa ;
byte_zero(&sa, sizeof sa) ;
sa.sin_family = AF_INET ;
uint16_big_endian((char *)&port, 1) ;
sa.sin_port = port ;
byte_copy((char *)&sa.sin_addr.s_addr, 4, ip) ;
return bind(s, (struct sockaddr *)&sa, sizeof sa) ;
}
|
C | #include <iostream>
#include <string>
#include <array>
using std::string;
using std::size_t;
using std::cout;
using std::endl;
string make_plural(size_t ctr, const string &word, const string &ending = "s")
{
return (ctr > 1) ? word + ending : word;
}
int main()
{
cout << make_plural(1, "success","es") << endl;
cout << make_plural(2, "success","es") << endl;
cout << make_plural(1, "failure") << endl;
cout << make_plural(2, "failure") << endl;
return 0;
}
|
C | #include <signal.h>
static void sig_child(int);
int main(void) {
pid_t pid;
int i;
printf("before signal\n");
signal(SIGCHLD, sig_child);
printf("task\n");
pid = fork();
printf("bye!\n");
if (pid == 0) {
sleep(1);
exit(0);
}
while(1) { i = i; }
}
static void sig_child(int signo){
pid_t pid; int status;
pid = wait(&status);
printf("child %d finished\n", pid);
} |
C | /*Program 9
Design, develop, and execute a program in C to read a sparse matrix of integer values and to search the sparse matrix for an element specified by the user. Print the result of the search appropriately. Use the triple <row, column, value> to represent an element in the sparse matrix.
*/
#include<stdio.h>
typedef struct{
int row,col,value;
}smatrix;
int main(){
smatrix m[10];
int i,n,key;
printf("enter the no of elements\n");
scanf("%d",&n);
printf("enter the elements of the sparse matrix in triple<row, column, value> \n");
for(i=0;i<n;i++)
scanf("%d%d%d",&m[i].row,&m[i].col,&m[i].value);
printf("enter the key element\n");
scanf("%d",&key);
for (i=0;i<n;i++)
if(m[i].value==key){
printf("\nElement found\nrow=%d\tcol=%d\tvalue=%d\n",m[i].row, m[i].col,m[i].value);
return 0;
}
printf("the key element not found");
} |
C | #include "dz2.h"
#include "dz3.h"
#include "dz5.h"
#include <stdio.h>
void shellSortArray(TrapezeArray *theArray,FILE *file)
{
Trapeze *tmp;
int in = 0;
int out = 0;
int h = 1; // start h = 1
//1. Calculate start value of h
while (h <= theArray->count/2)
{
h = h*2 + 1;
}
//2. Sequental decrease h to 1
while (h > 0)
{
for (out = h; out < theArray->count; out ++)
{
tmp = theArray->trapezes[out];
in = out;
// the first sub-array {0, 4, 8}
while (in > h-1 && areaTrapeze(theArray->trapezes[in - h]) >= areaTrapeze(tmp))
{
theArray->trapezes[in] = theArray->trapezes[in - h];
in -= h;
}
theArray->trapezes[in] = tmp;
}
h = (h - 1) / 3; //decrease h
}
writeArrayToJSON(file, theArray);
}
int searchTrapezeToArea(TrapezeArray *theArray, float area)
{
int first = 0,
last = theArray->count - 1,
middle = (first + last)/2;
if(theArray == NULL) return 0;
while(first < last)
{
printf("1\n");
if(areaTrapeze(theArray->trapezes) == area)
{
printf("index = %d\n",middle);
return 1;
}
if(areaTrapeze(theArray->trapezes) < area)
{
first = middle + 1;
}else{
last = middle;
}
middle = (first + last)/2;
}
return 0;
}
|
C | #include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
char* deal(char*);
int main(){
//设置服务器ip(点分十进制或者域名都可以)
const char *host = "127.0.0.1";
//选择要打开的端口或者服务
const int server = 4578;
// 打开套接字
int serv_sock = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in serv_addr;
//清空Serv_add中不需要设置的内容
memset(&serv_addr,0,sizeof(struct sockaddr_in));
serv_addr.sin_family = AF_INET; //设置为IPv4地址
serv_addr.sin_addr.s_addr = inet_addr(host); // 设置ip地址
serv_addr.sin_port = htons(server);
// 告诉内核,将描述符与套接字关联
bind(serv_sock,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
// 将主动套接装换为被动套接字
listen(serv_sock,1024);
// 开始使用accept来等待客户端连接
struct sockaddr_in cli_addr;
int cli_sock;
while(1){
socklen_t cli_addr_size = sizeof(cli_addr);
cli_sock = accept(serv_sock,(struct sockaddr*)&cli_addr,&cli_addr_size);
char *str;
char message[40];
// 读取客户机发来的信息
read(cli_sock,message,sizeof(message));
str = deal(message);
// 向客户端写入数据
write(cli_sock,str,sizeof(str));
printf("客户端发送过来的信息为: %s\n",message);
}
close(cli_sock);
close(serv_sock);
exit(0);
}
char* deal(char *message){
int choice = 0;
for(int i=0;i<strlen(message);i++){
choice *= 10;
choice += message[i] - '0';
}
printf("你的选择为: %d\n",choice);
switch(choice){
case 1:
printf("Good Morning\n");
return "Good Morning";
break;
case 2:
printf("Good Night\n");
return "Good Night";
break;
default:
printf("Good Everning\n");
return "Good Everning";
break;
}
}
|
C | #include <stdint.h>
#include "data.h"
#include "deepfreeze.h"
#include "dfserv.h"
#include "shared.h"
#pragma pack(push,1)
typedef struct {
uint32_t id;
uint32_t offset;
uint32_t size;
uint32_t size_2;
uint32_t unknown[4];
} tail_entry_t;
#pragma pack(pop)
#pragma pack(push,1)
typedef struct {
uint32_t header_size;
uint32_t unknowns_1[3];
uint32_t entry_count;
uint32_t unknowns_2[4];
uint32_t full_size;
uint32_t unknowns_3[2];
uint32_t xor_keys[4];
tail_entry_t dir_entry;
} tail_header_t;
#pragma pack(pop)
#define TAIL_HEADER_SIZE (sizeof(tail_header_t))
/**
* Set the given tail_entry_t from memory.
* @param entry - Entry to set.
* @param src - Memory to read from.
*/
static void DFS_SetTailEntry(tail_entry_t *entry, const void *src)
{
memcpy(entry, src, sizeof(*entry));
}
/**
* Set the given tail_header_t from memory.
* @param header - Header to set.
* @param src - Memory to read from.
*/
static void DFS_SetTailHeader(tail_header_t *header, const void *src)
{
memcpy(header, src, sizeof (*header));
}
static void DFS_Decrypt1(uint8_t *dest, const uint8_t *src, size_t size)
{
size_t i;
uint8_t al = 0x5, cl = 0x25;
for (i = 0; i < size; i++) {
cl++;
dest[i] = src[i] ^ al ^ cl;
al++;
}
}
static void DFS_Decrypt2(uint8_t *dest, const uint8_t *src, size_t size)
{
size_t i;
uint8_t al = 0x0, cl = 0x78;
for (i = 0; i < size; i++) {
cl++;
dest[i] = src[i] ^ al ^ cl;
al++;
}
}
/**
* Decrypt 16 bytes of src to dest using the hardcoded table.
*/
static void DFS_DecryptFromTable(uint8_t *dest, const uint8_t *src)
{
size_t i;
uint8_t copy[0x10];
// Use a copy buffer in case dest == src
memcpy(copy, src, 0x10);
for (i = 0; i < 4; i++)
dest[i*4] = table_g[copy[i*4]];
dest[0xD] = table_g[copy[0x9]];
dest[0x9] = table_g[copy[0x5]];
dest[0x5] = table_g[copy[0x1]];
dest[0x1] = table_g[copy[0xD]];
dest[0x2] = table_g[copy[0xA]];
dest[0xA] = table_g[copy[0x2]];
dest[0x6] = table_g[copy[0xE]];
dest[0xE] = table_g[copy[0x6]];
dest[0x3] = table_g[copy[0x7]];
dest[0x7] = table_g[copy[0xB]];
dest[0xB] = table_g[copy[0xF]];
dest[0xF] = table_g[copy[0x3]];
}
/**
* Build the key buffer.
* @param src - Initial buffer, must be at least 0x20 in size.
* @param dest - Destination buffer, must be at least 0xF0 in size.
*/
static void DFS_BuildKeyBuffer(uint8_t *dest, const uint8_t *src)
{
uint32_t i, j, s;
const uint8_t *table = key_buffer_table_g,
*small_table = key_buffer_small_table_g;
uint8_t arr[4], *block, x1, x2, x3, x4;
block = dest;
// Copy first 0x20 bytes of src into dest
memcpy(dest, src, 0x20);
for (i = 8; i < 0x3C; i++, block += 4) {
x1 = block[0x1C];
x2 = block[0x1D];
x3 = block[0x1E];
x4 = block[0x1F];
if ((i & 7) == 0) {
x1 = table[block[0x1D]] ^ small_table[i >> 3];
x2 = table[block[0x1E]];
x3 = table[block[0x1F]];
x4 = table[block[0x1C]];
} else if ((i & 7) == 4) {
x1 = table[x1];
x2 = table[x2];
x3 = table[x3];
x4 = table[x4];
}
s = ((i << 2) - 0x20);
arr[0] = x1 ^ block[0];
arr[1] = x2 ^ dest[s + 1];
arr[2] = x3 ^ dest[s + 2];
arr[3] = x4 ^ dest[s + 3];
memcpy(block + 0x20, arr, 4);
}
}
/**
* What the fuck.
*/
static void DFS_Wtf(uint8_t *dest, const uint8_t *src)
{
uint8_t a, b, copy[0x10], i, j, m;
struct {
uint8_t index;
uint8_t t[4];
} s[] = {
{ 0x0, { 3, 1, 2, 0 } },
{ 0x5, { 0, 3, 1, 2 } },
{ 0xA, { 2, 0, 3, 1 } },
{ 0xF, { 1, 2, 0, 3 } },
{ 0x4, { 3, 1, 2, 0 } },
{ 0x9, { 0, 3, 1, 2 } },
{ 0xE, { 2, 0, 3, 1 } },
{ 0x3, { 1, 2, 0, 3 } },
{ 0x8, { 3, 1, 2, 0 } },
{ 0xD, { 0, 3, 1, 2 } },
{ 0x2, { 2, 0, 3, 1 } },
{ 0x7, { 1, 2, 0, 3 } },
{ 0xC, { 3, 1, 2, 0 } },
{ 0x1, { 0, 3, 1, 2 } },
{ 0x6, { 2, 0, 3, 1 } },
{ 0xB, { 1, 2, 0, 3 } }
};
for (i = 0; i < 0x10; i++) {
a = 0;
m = (i / 4) * 4;
for (j = 0; j < 4; j++) {
b = src[m + j]; // Original byte from src
a ^= wtf_tables_g[s[i].t[j]][b];
}
copy[s[i].index] = a;
}
for (i = 0; i < 0x10; i++) {
dest[i] = another_table_g[copy[i]];
}
}
// Decrypt 0x10 bytes, key_buffer is 0xF0 bytes
static void DFS_DecryptWhatever(uint8_t *dest, uint8_t *key_buffer)
{
int i;
uint8_t buffer[0x10];
memcpy(buffer, dest, 0x10);
// Xor the first 0x10 bytes by the bytes at offset 0xE0
XorBytes(buffer, (key_buffer + 0xE0), 0x10);
for (i = 0xD; i >= 0; i--) {
// Decrypt first 0x10 bytes of key_buffer
DFS_DecryptFromTable(buffer, buffer);
XorBytes(buffer, (key_buffer + (i * 0x10)), 0x10);
if (i != 0) {
DFS_Wtf(buffer, buffer);
}
}
memcpy(dest, buffer, 0x10);
}
/**
* Build the initial seed (used for decrypting the tail data) from
* the DFServ.exe tail header.
**/
static int32_t DFS_BuildSeed(const tail_header_t *header)
{
int32_t i, key = 0;
for (i = 0; i < 4; i++)
key ^= header->xor_keys[i];
key ^= (key >> 16);
return key;
}
static uint8_t DFS_GetNextSeed(int32_t seed)
{
seed = OTP_HL((int16_t)seed);
return ((seed & 0xFF00) >> 8) ^ (seed & 0xFF);
}
/**
* Decrypt the tail data found at the end of DFServ.exe.
**/
static void DFS_DecryptTailData(uint8_t *dest, const uint8_t *src,
const tail_header_t *header, size_t size)
{
size_t i;
uint32_t seed;
seed = DFS_BuildSeed(header);
for (i = 0; i < size; i++) {
dest[i] = src[i] ^ DFS_GetNextSeed(seed + i);
}
}
/**
* Perform a "triple decrypt" on some data.
* @param dest - Buffer to decrypt.
*/
static void DFS_TripleDecrypt(uint8_t *dest, size_t size, const int* version)
{
uint8_t key_buffer[0xF0];
if (DF_IsVersionOrGreater(8, 11, version) && size >= 0x10) {
DFS_BuildKeyBuffer(key_buffer, key_buffer_init_g);
DFS_DecryptWhatever(dest, key_buffer);
}
if (version[0] > 5) {
DFS_Decrypt1(dest, dest, size);
DFS_Decrypt2(dest, dest, size);
}
}
static size_t DFS_GetTailDataSize(const tail_header_t *header)
{
if (header->full_size < header->header_size)
return 0;
else
return header->full_size - header->header_size;
}
static BOOL DFS_FindAndReadTail(tail_header_t *header, uint8_t **data, FILE *file)
{
size_t end_offset, /* tail_size, */ tail_data_size;
long int file_size;
uint8_t raw_tail_header[TAIL_HEADER_SIZE];
if (!FindEndOfLastSection(&end_offset, file)) {
fprintf(stderr, "DFServ.exe does not appear to be a valid PE\n");
return FALSE;
}
// Read the DFServ.exe tail header
fseek(file, end_offset, SEEK_SET);
if (fread(raw_tail_header, 1, TAIL_HEADER_SIZE, file) != TAIL_HEADER_SIZE) {
fprintf(stderr, "Unable to read the tail header\n");
return FALSE;
}
DFS_SetTailHeader(header, raw_tail_header);
// Header size should be 0x60
if (header->header_size != TAIL_HEADER_SIZE) {
fprintf(stderr, "Unexpected tail header size: 0x%08x\n", header->header_size);
return FALSE;
}
// Allocate memory for tail data
tail_data_size = DFS_GetTailDataSize(header);
*data = (uint8_t*)malloc(sizeof(uint8_t) * tail_data_size);
if (*data == NULL) {
fprintf(stderr, "Unable to allocate memory for tail data\n");
return FALSE;
}
// Read tail data
if (fread(*data, 1, tail_data_size, file) != tail_data_size) {
fprintf(stderr, "Unable to read all tail data\n");
free(*data);
return FALSE;
}
return TRUE;
}
static BOOL DFS_IsEntryDataInScope(const tail_entry_t *entry, const tail_header_t *header)
{
return (header->header_size <= entry->offset)
&& (header->full_size >= (entry->offset + entry->size));
}
/**
* Extract the token from the DFServ.exe binary.
* @param token - Assigned the token upon success.
* @return TRUE if successful, FALSE if not.
*/
BOOL DFS_ExtractToken(uint32_t *token, const int *version)
{
// --- Read DFServ.exe and grab its tail
size_t end_offset, tail_size;
long int file_size;
char file_path[MAX_PATH];
uint8_t *dir_data, *entries, *entry_data, *tail_data;
tail_header_t tail_header = { 0 };
tail_entry_t entry = { 0 };
FILE *file;
// In v8.11 or greater, the data we want is in DFServ.exe
// Otherwise, it is in FrzState2k.exe
if (DF_IsVersionOrGreater(8, 11, version)) {
DF_GetServPath(file_path, MAX_PATH);
} else {
DF_GetFrzState2kPath(file_path, MAX_PATH);
}
file = fopen(file_path, "rb");
if (file == NULL) {
fprintf(stderr, "Unable to open DFServ.exe, may not be installed?\n");
return FALSE;
}
if (!DFS_FindAndReadTail(&tail_header, &tail_data, file)) {
fprintf(stderr, "Unable to read DFServ.exe tail\n");
return FALSE;
}
if (!DFS_IsEntryDataInScope(&(tail_header.dir_entry), &tail_header)) {
fprintf(stderr, "Directory entry data is out-of-scope\n");
free(tail_data);
return FALSE;
}
// Decrypt the "directory" data
dir_data = tail_data + (tail_header.dir_entry.offset - tail_header.header_size);
DFS_DecryptTailData(dir_data, dir_data, &tail_header, tail_header.dir_entry.size);
entries = tail_data;
for (uint32_t i = 0; i < tail_header.entry_count; i++, entries += sizeof(entry)) {
DFS_SetTailEntry(&entry, entries);
if (entry.id == 0xFFFFFFF0)
break;
}
if (entry.id != 0xFFFFFFF0) {
fprintf(stderr, "Unable to find FFFFFFF0 entry\n");
free(tail_data);
return FALSE;
}
if (!DFS_IsEntryDataInScope(&entry, &tail_header)) {
fprintf(stderr, "FFFFFFF0 entry data is out-of-scope\n");
free(tail_data);
return FALSE;
}
entry.offset -= tail_header.header_size;
// Decrypt the entry data
entry_data = tail_data + entry.offset;
DFS_DecryptTailData(entry_data, entry_data, &tail_header, entry.size);
if (DF_IsVersionOrGreater(8, 31, version)) {
if (entry.size >= 8
&& *(uint32_t*)(entry_data + (entry.size - 4)) == 0xDCBA1234) {
entry.size -= 0x8;
}
}
// "Triple decrypt" the entry data
DFS_TripleDecrypt(entry_data, entry.size, version);
// After the 3-way decryption, first 4 bytes is the token
// (unsure if the other data is useful in any way?)
*token = *(uint32_t*)entry_data;
free(tail_data);
return TRUE;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_hooks.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: edavid <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/09 10:02:09 by edavid #+# #+# */
/* Updated: 2021/07/16 18:32:58 by edavid ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdio.h>
#include "mlx/mlx.h"
#include "ft_hooks.h"
#include "ft_colors.h"
#include "ft_utils.h"
#include "libft/libft.h"
#include "ft_structs.h"
static void init_neighbour_chars(t_node (*neighbour_chars)[4],
t_mystruct *mystruct, t_point *current_position)
{
(**neighbour_chars).value = *(*(*mystruct->map + current_position->y - 1)
+ current_position->x);
(**neighbour_chars).name = "up_char";
(**neighbour_chars).next = 0;
(*(*neighbour_chars + 1)).value = *(*(*mystruct->map + current_position->y)
+ current_position->x - 1);
(*(*neighbour_chars + 1)).name = "left_char";
(**neighbour_chars).next = 0;
(*(*neighbour_chars + 2)).value = *(*(*mystruct->map + current_position->y
+ 1) + current_position->x);
(*(*neighbour_chars + 2)).name = "down_char";
(*(*neighbour_chars + 2)).next = 0;
(*(*neighbour_chars + 3)).value = *(*(*mystruct->map + current_position->y)
+ current_position->x + 1);
(*(*neighbour_chars + 3)).name = "right_char";
(*(*neighbour_chars + 3)).next = 0;
}
static void init_neighbour_chars2(t_node (*neighbour_chars)[4],
t_node **cur_node, t_point *previous_position, t_point *current_position)
{
(*(*neighbour_chars)).next = *neighbour_chars + 1;
(*(*neighbour_chars + 1)).next = *neighbour_chars + 2;
(*(*neighbour_chars + 2)).next = *neighbour_chars + 3;
(*(*neighbour_chars + 3)).next = *neighbour_chars;
if (previous_position->y - 1 == current_position->y)
*cur_node = *neighbour_chars + 3;
else if (previous_position->x - 1 == current_position->x)
*cur_node = *neighbour_chars;
else if (previous_position->y + 1 == current_position->y)
*cur_node = *neighbour_chars + 1;
else if (previous_position->x + 1 == current_position->x)
*cur_node = *neighbour_chars + 2;
else
*cur_node = *neighbour_chars;
}
void get_next_position(t_mystruct *mystruct, t_point *current_position,
t_point *previous_position)
{
t_node neighbour_chars[4];
t_node *cur_node;
int i;
char *str;
init_neighbour_chars(&neighbour_chars, mystruct, current_position);
init_neighbour_chars2(&neighbour_chars, &cur_node, previous_position,
current_position);
i = -1;
while (++i < 5 && cur_node->value == '1')
cur_node = cur_node->next;
if (i != 5)
{
*previous_position = *current_position;
str = cur_node->name;
if (!ft_strncmp(str, "up_char", 2))
current_position->y -= 1;
else if (!ft_strncmp(str, "left_char", 2))
current_position->x -= 1;
else if (!ft_strncmp(str, "down_char", 2))
current_position->y += 1;
else
current_position->x += 1;
}
}
static int check_collision(t_mystruct *mystruct, struct s_three_points *ABC,
int *number_of_enemies, int *number_of_calls)
{
int i;
i = -1;
while (++i < *number_of_enemies)
{
if (*(*(*mystruct->map + (ABC->enemy_positions + i)->y)
+ (ABC->enemy_positions + i)->x) == 'G'
|| *(*(*mystruct->map + (ABC->enemy_positions + i)->y)
+ (ABC->enemy_positions + i)->x) == 'P')
{
free(ABC->enemy_positions);
free(ABC->enemy_previous_positions);
*number_of_calls = 0;
*number_of_enemies = 0;
reset_map(mystruct);
return (1);
}
}
return (0);
}
int patrol_enemy(t_mystruct *mystruct)
{
static t_point exit;
static t_point *enemy_positions;
static t_point *enemy_previous_positions;
static int number_of_enemies;
static int number_of_calls;
if (*mystruct->need_reset || !number_of_calls)
{
get_exit_coords(mystruct, &exit);
initialize_vars(&enemy_positions, &enemy_previous_positions,
&number_of_enemies, mystruct);
}
if (number_of_calls == 9999)
patrol_enemy2(mystruct, number_of_enemies, &(struct s_three_points){
exit, enemy_positions, enemy_previous_positions});
if (check_collision(mystruct, &(struct s_three_points){exit,
enemy_positions, enemy_previous_positions}, &number_of_enemies,
&number_of_calls))
return (0);
number_of_calls++;
if (number_of_calls == 10000)
number_of_calls = 1;
return (0);
}
|
C | //
// Created by Jost Luebbe on 2019-09-02.
//
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#define PORT 5555
int main() {
int sock;
struct sockaddr_in server;
char server_reply[2000];
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket could not be created");
exit(EXIT_FAILURE);
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_port = htons(PORT);
if (connect(sock, (struct sockaddr *) &server, sizeof(server)) < 0) {
perror("client connection");
exit(EXIT_FAILURE);
}
char message[2000];
printf("Input lowercase sentence: ");
fgets(message, 2000, stdin);
if (send(sock, message, strlen(message), 0) < 0) {
puts("message send failed");
exit(EXIT_FAILURE);
}
bzero(server_reply, 2000);
if (recv(sock, server_reply, 2000, 0) < 0) {
puts("server reply failed");
exit(EXIT_FAILURE);
}
printf("Server reply: %s\n", server_reply);
close(sock);
return 0;
}
|
C | /*
** EPITECH PROJECT, 2017
** navy
** File description:
** navy
*/
#include "../include/my.h"
#include "../include/navy.h"
char **create_my_board(char *pos, int a, int c, int b)
{
int k = 2;
char **enemy = create_enemy_board();
while (k != 6) {
b = find_the_letter(pos[a], enemy, 1);
a = a + 1;
c = find_the_letter(pos[a], enemy, 0);
if (enemy[c][b] != '.')
return NULL;
enemy[c][b] = k + 48;
if (pos[a + 2] == pos[a - 1])
enemy = set_my_vertical_ligne(enemy, k, c, b);
else
enemy = set_my_horizontal_ligne(enemy, k, c, b);
k = k + 1;
b = 0;
a = a + 7;
c = 0;
}
return enemy;
}
int find_the_letter(char pos, char **enemy, int a)
{
int b = 0;
if (a == 1) {
while (pos != enemy[0][b])
b = b + 1;
}
else {
while (pos != enemy[b][0])
b = b + 1;
}
return b;
}
char **create_enemy_board(void)
{
int b = 0;
char **board = malloc(sizeof(char *) * (11));
for (b = 0; b < 11; b = b + 1)
board[b] = malloc(sizeof(char) * (20));
my_strcpy(board[0], " |A B C D E F G H");
my_strcpy(board[1], "-+---------------");
my_strcpy(board[2], "1|. . . . . . . .");
my_strcpy(board[3], "2|. . . . . . . .");
my_strcpy(board[4], "3|. . . . . . . .");
my_strcpy(board[5], "4|. . . . . . . .");
my_strcpy(board[6], "5|. . . . . . . .");
my_strcpy(board[7], "6|. . . . . . . .");
my_strcpy(board[8], "7|. . . . . . . .");
my_strcpy(board[9], "8|. . . . . . . .");
return board;
}
char *my_strcpy(char *dest, char const *src)
{
int i = 0;
while (src[i] != '\0') {
dest[i] = src[i];
i++;
}
dest[i] = '\0';
return (dest);
}
int navy(int pid, char *buff, int turn)
{
ingame_t *game = set_game(buff);
static int printer = 0;
if (game->my_map == NULL)
return 84;
print_board2(game->my_map, game->en_map);
while (game->my_boat != 0 && game->en_boat != 0) {
if (turn % 2 == 0) {
game->en_boat -= my_turn(pid, game);
if (game->en_boat <= -50)
return (0);
}
else
game->my_boat -= en_turn(pid, game);
turn = turn + 1;
printer++;
if (printer == 2) {
print_board2(game->my_map, game->en_map);
printer = 0;
}
}
return check_winner(game->en_boat, game);
}
|
C | #include <stdio.h>
int queue[100005];
int b=0;
int f=0;
void push (int a)
{
queue[f++]=a;
}
int pop (void)
{
if(empty())
return -1;
else
{
return queue[b++];
}
}
int size (void)
{
return f-b;
}
int empty (void)
{
if(b==f)
return 1;
else
return 0;
}
int front_func (void)
{
if(b==f)
return -1;
else
{
return queue[b];
}
}
int back_func (void)
{
if(b==f)
return -1;
else
{
return queue[f-1];
}
}
int main(void)
{
int N,i,num;
char array[10];
scanf("%d",&N);
for(i=0;i<N;i++)
{
scanf("%s",array);
switch(array[0])
{
case 112:
if(array[1]==117)
{
scanf("%d",&num);
push(num);
}
else
{
printf("%d \n",pop());
}
break;
case 115:
printf("%d \n",size());
break;
case 101:
printf("%d \n",empty());
break;
case 102:
printf("%d \n",front_func());
break;
case 98:
printf("%d \n",back_func());
break;
}
}
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
typedef struct Friend_{
char name;
struct Friend_ *next;
}Friend;
typedef struct Node_{
char name;
struct Friend_ *friend;
struct Node_ *next;
}Node;
Node* addNode(char name){
Node* new = malloc(sizeof(Node*));
new->name = name;
new->friend = NULL;
new->next = NULL;
return new;
}
void addFriend(Friend **list, char name){
if(*list == NULL){
Friend *new = malloc(sizeof(Friend*));
new->name = name;
new->next = NULL;
*list = new;
}
else{
while(1){
if(*list->name == name){break;}
else if(*list->next == NULL){
Friend *new = malloc(sizeof(Friend*));
new->name = name;
new->next = NULL;
*list->next = new;
break;
}
*list = *list->next;
}
}
}
int main(){
char n1, n2;
int i, n;
Node *head = malloc(sizeof(Node*));
Node *p1, *p2;
scanf("%d", &n);
for(i=0; i<n ;i++){
scanf("%c %c", &n1, &n2);
p1 = addNode(n1);
p2 = addNode(n2);
if(i==1){
head->next = p1;
p1->next = p2;
addFriend(&p1->friend, n2);
addFriend(&p2->friend, n1);
}
else{
Node *current = head->next;
Friend *list = NULL;
while(1){
if(current->name == n1){
list = current->friend;
addFriend(list, n2);
break;
}
else if(current->next == NULL){
current->next = addNode(n1);
current = current->next;
list = current->friend;
addFriend(list, n2);
break;
}
else{
current = current->next;
}
}
current = head->next;
while(1){
if(current->name == n2){
list = current->friend;
addFriend(list, n1);
break;
}
else if(current->next == NULL){
current->next = addNode(n2);
current = current->next;
list = current->friend;
addFriend(list, n1);
break;
}
else{
current = current->next;
}
}
}
}
} |
C | #include <unistd.h>
#include <fcntl.h>
#define TAM 1000
void main(int argc, char* argv[]){
int r, fd = open(argv[1], O_RDONLY), i;
char buff[TAM];
r = read(fd, buff, TAM);
for(i=0; i<r && buff[i] != '\n'; i++);
write(1, buff, i+1);
} |
C | #include<stdio.h>
typedef unsigned short u_int;
typedef unsigned short u_short;
typedef unsigned char u_char;
u_char little_endian()
{
u_short word=0x1234;
u_char * p = (u_char *) &word;
return (p[0] == 0x12) ? 0 : 1;
}
int count_bits(u_int data)
{
int cnt=0;
while(data != 0)
{
printf("%x %x %x\n",data,(data -1),data & (data - 1));
data = data & (data - 1);
cnt++;
}
return cnt;
}
int main()
{
printf("%d bits set\n",count_bits(0xFFF7));
return 0;
}
|
C | #include<stdio.h>
#include<malloc.h>
int mean(int num[], int n);
int avg(int num[], int n);
void sort(int num[], int n);
int cen(int num[], int n);
void min(int num[], int t);
int main() {
int n;
int *num;
scanf("%d", &n);
num = (int*)malloc(sizeof(int)*n);
for (int t = 0; t < n; t++) {
scanf("%d", &num[t]);
}
printf("%d\n", avg(num, n));
printf("%d\n", cen(num, n));
min(num, 0);
printf("%d\n",num[n - 1] - num[0]);
free(num);
return 0;
}
int mean(int num[],int n) {
int sum = 0;
if (n > 0) {
sum += num[n-1] + mean(num, n - 1);
}
return sum;
}
int avg(int num[], int n) {
return ((mean(num, n) / (float)n) - (mean(num, n) / n) >= 0.5) ? mean(num, n) / n + 1 : mean(num, n) / n;
}
void sort(int num[], int n) {
int t;
for (int a = 0; a < n; a++) {
for (int b = a + 1; b < n; b++) {
if (num[a] > num[b]) {
t = num[b];
num[b] = num[a];
num[a] = t;
}
}
}
}
int cen(int num[], int n) {
sort(num, n);
return num[n / 2];
}
void min(int num[],int t) {
int tem = 1;
for (char a = 1; num[a] == num[a - 1]; a++) {
tem++;
}
if (tem == 1) {
printf("%d\n", num[0]);
}
else {
printf("%d\n", num[tem]);
}
}
|
C | /*
Copyright 2012-2014 Scianta Analytics LLC All Rights Reserved.
Reproduction or unauthorized use is prohibited. Unauthorized
use is illegal. Violators will be prosecuted. This software
contains proprietary trade and business secrets.
Module: saListDir
Description:
Write a list of files contained in a directory, based on a filter, to a FILE stream
Functions:
saListDir
*/
#include <dirent.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
inline void saListDir(char *dir, char *filter, bool stripFilter, FILE *outfile, char *header)
{
if (dir == NULL || *dir == '\0')
return;
if (filter == NULL)
filter = "";
if (header == NULL)
fprintf(outfile, "file\n");
else
fprintf(outfile, "%s\n", header);
DIR *d = opendir(dir);
struct dirent *f;
int filter_len = strlen(filter);
while((f = readdir(d)) != NULL)
{
char *fname = f->d_name;
if (strlen(fname) >= filter_len)
{
if (!filter_len || !strcmp(fname+strlen(fname)-filter_len, filter))
{
if (stripFilter == true)
fname[strlen(fname)-filter_len] = '\0';
fprintf(outfile, "%s\n", fname);
}
}
}
closedir(d);
}
|
C | // 40个3和30个2凑100
#include <stdio.h>
int main(int argc, char *argv[])
{
int arr[][2] = {4,7,5,5,4,3,2,2};
int target = 70;
int kinds = sizeof(arr)/sizeof(int)/2;
int i, j;
for (i = 0; i < kinds; ++i) {
for (j = 0; j< arr[i][0]; j++) {
if (target < arr[i][1]) break;
target -= arr[i][1];
printf("debug: %d %d %d\n", target, arr[i][1], j);
if (target < arr[i][1]) break;
}
}
printf("%s\n", target == 0 ? "能凑够" : "不能凑够");
return 0;
}
|
C | /*
** A word guess game that gives the player three tries to guess
** a word (pulled randomly from a file) -- a hint is given before
** each guess
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *word1 = "lobster";
char *word2 = "teddybear";
char *word3 = "smartphone";
char *word4 = "purse";
char *word5 = "lipstick";
int word_1(void);
int word_2(void);
int word_3(void);
int word_4(void);
int word_5(void);
int main(void)
{
FILE *fp;
int ch;
int ch2;
int i;
int select = 0;
int word_count = 0;
int random; //instead of uint32_t
int index = 0;
char buf[256];
char *token;
char tmp_buf[256];
char *selected_word;
fp = fopen("word_guess.txt", "r");
if (fp == NULL)
{
printf("Failed to open and read from the file\n");
return (0);
}
while ((ch = fgetc(fp)) != EOF)
{
if (ch == ' ' || ch == '\n')
word_count++;
}
random = (int)(arc4random_uniform(word_count) + 1);
printf("%d\n", random);
rewind(fp);
while ((fgets(buf, sizeof(buf), fp)) != NULL)
{
while (buf[index] != '\0')
{
tmp_buf[index] = buf[index];
index++;
}
tmp_buf[index] = '\0';
}
printf("%s", tmp_buf);
printf("Rules: You have three tries to guess the correct word. A hint \\
will be given to you before each of your guesses. Good luck!\n");
if (strcmp(word1, selected_word) == 0)
{
word_1();
return (0);
}
else if (strcmp(word2, selected_word) == 0)
{
word_2();
return (0);
}
else if (strcmp(word3, selected_word) == 0)
{
word_3();
return (0);
}
else if (strcmp(word4, selected_word) == 0)
{
word_4();
return (0);
}
else if (strcmp(word5, selected_word) == 0)
{
word_5();
return (0);
}
fclose(fp);
return (0);
}
int word_1(void)
{
char *guess1;
char *guess2;
char *guess3;
printf("It lives in the ocean, but you're more likely to see it somewhere else\n");
scanf("%s", guess1);
if (strcmp(word1, guess1) == 0)
{
printf("Congratulations! You guessed correctly!\n");
return (0);
}
else
printf("Sorry! That wasn't right. Try again.\n");
printf("It's red in color\n");
scanf("%s", guess2);
if (strcmp(word1, guess2) == 0)
{
printf("Congratulations! You guessed correctly!\n");
return (0);
}
else
printf("Sorry! That wasn't right. Try again.\n");
printf("It's considered a delicacy by many seafood lovers\n");
scanf("%s", guess3);
if (strcmp(word1, guess3) == 0)
{
printf("Congratulations! You guessed correctly!\n");
return (0);
}
else
printf("Sorry! That wasn't right. You lose :(\n");
return (0);
}
int word_2(void)
{
char *guess1;
char *guess2;
char *guess3;
printf("It's a common child's toy\n");
scanf("%s", guess1);
if (strcmp(word1, guess1) == 0)
{
printf("Congratulations! You guessed correctly!\n");
return (0);
}
else
printf("Sorry! That wasn't right. Try again.\n");
printf("Can't get a Ruxpin? Try getting a Ted\n");
scanf("%s", guess2);
if (strcmp(word1, guess2) == 0)
{
printf("Congratulations! You guessed correctly!\n");
return (0);
}
else
printf("Sorry! That wasn't right. Try again.\n");
printf("Not a teddylion or a teddytiger...\n");
scanf("%s", guess3);
if (strcmp(word1, guess3) == 0)
{
printf("Congratulations! You guessed correctly!\n");
return (0);
}
else
printf("Sorry! That wasn't right. You lose :(\n");
return (0);
}
int word_3(void)
{
char *guess1;
char *guess2;
char *guess3;
printf("These days, you almost can't live without one\n");
scanf("%s", guess1);
if (strcmp(word1, guess1) == 0)
{
printf("Congratulations! You guessed correctly!\n");
return (0);
}
else
printf("Sorry! That wasn't right. Try again.\n");
printf("It performs many of the functions of a computer\n");
scanf("%s", guess2);
if (strcmp(word1, guess2) == 0)
{
printf("Congratulations! You guessed correctly!\n");
return (0);
}
else
printf("Sorry! That wasn't right. Try again.\n");
printf("Take a bite out of an apple or run a sprint to get one\n");
scanf("%s", guess3);
if (strcmp(word1, guess3) == 0)
{
printf("Congratulations! You guessed correctly!\n");
return (0);
}
else
printf("Sorry! That wasn't right. You lose :(\n");
return (0);
}
int word_4(void)
{
char *guess1;
char *guess2;
char *guess3;
printf("Throw it on your shoulder and go\n");
scanf("%s", guess1);
if (strcmp(word1, guess1) == 0)
{
printf("Congratulations! You guessed correctly!\n");
return (0);
}
else
printf("Sorry! That wasn't right. Try again.\n");
printf("It's the perfect place to store small personal items\n");
scanf("%s", guess2);
if (strcmp(word1, guess2) == 0)
{
printf("Congratulations! You guessed correctly!\n");
return (0);
}
else
printf("Sorry! That wasn't right. Try again.\n");
printf("You can get one from Louis, Michael, or Chanel...\n");
scanf("%s", guess3);
if (strcmp(word1, guess3) == 0)
{
printf("Congratulations! You guessed correctly!\n");
return (0);
}
else
printf("Sorry! That wasn't right. You lose :(\n");
return (0);
}
int word_5(void)
{
char *guess1;
char *guess2;
char *guess3;
printf("You put it on your lips\n");
scanf("%s", guess1);
if (strcmp(word1, guess1) == 0)
{
printf("Congratulations! You guessed correctly!\n");
return (0);
}
else
printf("Sorry! That wasn't right. Try again.\n");
printf("Nude, Dusty Rose, and Apricot are favorites for spring\n");
scanf("%s", guess2);
if (strcmp(word1, guess2) == 0)
{
printf("Congratulations! You guessed correctly!\n");
return (0);
}
else
printf("Sorry! That wasn't right. Try again.\n");
printf("You can put it on a pig but the pig will still be a pig\n");
scanf("%s", guess3);
if (strcmp(word1, guess3) == 0)
{
printf("Congratulations! You guessed correctly!\n");
return (0);
}
else
printf("Sorry! That wasn't right. You lose :(\n");
return (0);
}
|
C | #include <stdlib.h>
#include <stdio.h>
main(int argc, char* argv[]) {
int i;
pid_t parentpid = getpid();
printf("Proces macierzysty %d exit:\n", getpid());
for (i = 0; i < argc; i++){
pid_t pid;
if((pid = fork()) == 0) {
int j;
for(j=0; j<(int)strtol(argv[i+2], NULL, 10); j++) {
printf("Potomny %d: PID: %d krok: %d\n",i,getpid(),j);
sleep(1);
}
exit(i);
}
}
if (getpid() == parentpid){
int j;
for(j=0; j<(int)strtol(argv[1], NULL, 10); j++) {
printf("macierzysty: PID: %d krok: %d\n",getpid(),j);
sleep(1);
}
}
for (i = 0; i < argc; i++){
int status;
pid_t pid = wait(&status);
printf("Zakonczono %d exit: %d\n", pid, WEXITSTATUS(status));
}
}
|
C | /*
* =====================================================================================
* Description: solution for practice 9.2
* Version: 1.0
* Created: 08/08/2018 03:58:47 PM
* Author: xiaochen.jiang (kl), [email protected]
* =====================================================================================
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <common.h>
#include <sys/wait.h>
int main(int argc, const char *argv[])
{
pid_t pid;
if ((pid = fork()) < 0) {
err_sys("fork error");
} else if (pid == 0) { /* child */
chk_nega(setsid());
//check is group leader
printf("child %s process group leader\n",
getpid() == getpgid(0) ? "is" : "isn't");
//check has controlling terminal
printf("child %s controlling terminal\n",
tcgetpgrp(STDOUT_FILENO) == -1 ? "hasn't" : "has");
} else { /* parent */
waitpid(pid, NULL, 0);
}
return 0;
}
|
C | #include<stdio.h>
int main()
{
int i=0;
double k,s=0;
while(scanf("%lf",&k) != EOF){
i++;
s += k;
}
printf("%.3lf",s/i);
}
/**************************************************************
Problem: 1417
User: 201901060610
Language: C
Result: Accepted
Time:0 ms
Memory:748 kb
****************************************************************/
|
C | // https://www.hackerrank.com/challenges/the-hurdle-race
#include <stdio.h>
int findMax(int n, int A[n]);
int main()
{
int n, k, max, magic;
scanf("%d %d",&n,&k);
int H[n];
for(int i = 0; i < n; i++)
scanf("%d",&H[i]);
max = findMax(n, H);
magic = max - k;
if (magic < 0)
magic = 0;
printf("%d\n", magic);
return 0;
}
int findMax(int n, int A[n])
{
int max = A[0];
for (int i = 1; i < n; i++)
if (A[i] > max)
max = A[i];
return max;
} |
C | #include <std.h>
inherit ARMOUR;
void create(){
::create();
set_name("spiked boots");
set_id(({ "boots", "boot", "shoe", "shoes", "spiked boots" }));
set_short("%^RESET%^%^ORANGE%^S%^WHITE%^p%^ORANGE%^i%^WHITE%^k%^ORANGE%^e%^WHITE%^d %^ORANGE%^Boots%^RESET%^");
set_obvious_short("%^RESET%^%^ORANGE%^hiking boots%^RESET%^");
set_long(
@AVATAR
%^RESET%^%^ORANGE%^This is a pair of rugged hiking boots. They are made from thick leather
that has been broken in long ago and will fit comfortably. The laces are
also made of durable leather, and tie up around the ankles. The bottoms of
the boots are covered in tiny, wicked spikes. They would make climbing
through rough terrain easier, but could also inflict quite a lot of pain.%^RESET%^
AVATAR
);
set_weight(5);
set_value(1300);
set_lore(
@AVATAR
Although not particularly attractive, hiking boots like these require some
relatively refined smithing technology to manufacture. Long ago, when
Druids walked the forests surrounding Shadow, they approached the dwarves
of Echo Mountains and asked them to make superior gear for their Ranger
allies. A few of these boots remain, the finer examples having been
enchanted long ago.
AVATAR
);
set_property("lore difficulty",9);
set_type("clothing");
set_limbs(({ "right foot", "left foot" }));
set_size(2);
set_property("enchantment",1);
set_wear((:TO,"wear_func":));
set_remove((:TO,"remove_func":));
set_struck((:TO,"strike_func":));
}
int wear_func(){
tell_room(environment(ETO),""+ETOQCN+" %^RESET%^%^ORANGE%^laces up their boots tightly%^RESET%^",ETO);
tell_object(ETO,"%^RESET%^%^ORANGE%^You lace up the boots tightly%^RESET%^");
return 1;
}
int remove_func(){
tell_room(environment(ETO),""+ETOQCN+" %^RESET%^%^ORANGE%^struggles, then finally removes the hiking boots%^RESET%^",ETO);
tell_object(ETO,"%^RESET%^%^ORANGE%^With a little grunt, you finally remove the boots%^RESET%^");
return 1;
}
int strike_func(int damage, object what, object who){
if(random(1000) < 180){
tell_room(environment(query_worn()),""+ETOQCN+" %^RESET%^%^ORANGE%^counters the attack with a spiked kick at "+who->QCN+"%^RESET%^",({ETO,who}));
tell_object(ETO,"%^RESET%^%^ORANGE%^You counter the attack with a swift, spiked kick!%^RESET%^");
tell_object(who,""+ETOQCN+" %^RESET%^%^ORANGE%^answers your attack with a swift kick from their spiked boots!%^RESET%^");
who->do_damage("torso",random(4));
return damage; }
} |
C | #include <stdio.h>
#include "fileManager.h"
int main(int argc,char * argv[]){
int matrix[10][10];
int distance=0;
int i=0;
openFile("distances_10.txt",matrix);
distance+=matrix[0][atoi(argv[1])];
//printf("%d\t%d\n",0,atoi(argv[1]));
for (i=1;i<(argc-1);i++){
distance+=matrix[atoi(argv[i])][atoi(argv[i+1])];
//printf("%d\t%d\n",atoi(argv[i]),atoi(argv[i+1]));
}
distance+=matrix[atoi(argv[9])][atoi(argv[0])];
// printf("%d\t%d\n",atoi(argv[99]),atoi(argv[0]));
printf("Distancia: %d\n",distance);
}
|
C |
#include <stdio.h>
int interpolationSearch(int arr[], int lo, int hi, int x)
{
int pos;
if (lo <= hi && x >= arr[lo] && x <= arr[hi])
{
pos = lo + (((double)(hi - lo) / (arr[hi] - arr[lo])) * (x - arr[lo]));
if (arr[pos] == x)
return pos;
if (arr[pos] < x)
return interpolationSearch(arr, pos + 1, hi, x);
if (arr[pos] > x)
return interpolationSearch(arr, lo, pos - 1, x);
}
return -1;
}
int main()
{
int n;
scanf("%d", &n);
int arr[n];
printf("Enter product id one by one in ascending order:");
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
int x;
printf("Enter the PRODUCT_ID to be searched");
scanf("%d", &x);
int index = interpolationSearch(arr, 0, n - 1, x);
if (index != -1)
printf("PRODUCT_ID is present in the array at position %d", index + 1);
else
printf("PRODUCT_ID not found.");
return 0;
} |
C | #include <darknet.h>
void fill_image_f32(image* im, int w, int h, int c, float* data) {
int i;
for (i = 0; i < w*h*c; i++) {
im->data[i] = data[i];
}
}
void set_data_f32_val(float* data, int index, float value) {
data[index] = value;
}
|
C | #include <stdbool.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <png.h>
#include "quadtree.h"
#include "diskcache.h"
#include "png.h"
#include "pngloader.h"
#define HEAP_SIZE 100000
#define TILESIZE 256 // rgb pixels per side
#ifndef __BIGGEST_ALIGNMENT__ // FIXME: hack to compile with clang
#define __BIGGEST_ALIGNMENT__ 16
#endif
// Structure for memory read I/O:
struct io {
size_t len;
const char *buf;
const char *cur;
};
static __thread char *heap = NULL;
static __thread char *heap_head = NULL;
static __thread bool initialized = false;
static __thread volatile bool cancel_flag = false;
static bool
load_png_file (int fd, unsigned int *height, unsigned int *width, char **rawbits)
{
bool ret = false;
char *data;
struct stat stat;
size_t len;
ssize_t nread;
// Get file size:
if (fstat(fd, &stat))
return false;
// Allocate buffer:
if ((data = malloc(len = stat.st_size)) == NULL)
return false;
// Read in entire file, check carefully for cancellation:
for (size_t total = 0; total < len; total += nread) {
nread = read(fd, data + total, len - total);
if (cancel_flag || nread <= 0) {
free(data);
return false;
}
}
// Pass to png loader:
ret = png_load(data, len, height, width, rawbits);
// Clean up buffer:
free(data);
return ret;
}
void
pngloader_main (void *data)
{
int fd = -1;
struct pngloader *p = data;
unsigned int width;
unsigned int height;
char *rawbits = NULL;
if (!initialized) {
free(p);
return;
}
// Reset heap pointer:
heap_head = heap;
cancel_flag = false;
// Get a file descriptor to the file. We just want a file descriptor to
// associate with this thread so that we know what to clean up, and not
// wait for the disk to actually deliver, so we issue a nonblocking call:
if ((fd = diskcache_open(p->req.zoom, p->req.x, p->req.y)) < 0 || cancel_flag)
goto exit;
// Now that we have the fd, make it properly blocking:
if (fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) & ~O_NONBLOCK) < 0 || cancel_flag)
goto exit;
if (!load_png_file(fd, &height, &width, &rawbits) || cancel_flag)
goto exit;
if (fd >= 0) {
close(fd);
fd = -1;
}
if (height != TILESIZE || width != TILESIZE) {
free(rawbits);
rawbits = NULL;
goto exit;
}
// Got tile, run callback:
p->on_completed(p, rawbits);
exit: if (fd >= 0)
close(fd);
free(p);
}
void
pngloader_on_cancel (void)
{
cancel_flag = true;
}
void
pngloader_on_init (void)
{
// Allocate a block of heap memory:
if ((heap = heap_head = malloc(HEAP_SIZE)) != NULL)
initialized = true;
}
void
pngloader_on_exit (void)
{
free(heap);
}
|
C | #include <stdio.h>
int main(void)
{
printf("First off, this part is about how the Raspberry Pi boots.\n");
stage1_of_boot();
endSoFar();
}
int stage1_of_boot(void)
{
printf("The Pi cannot boot from the SD card yet, because the CPU\n");
printf("hasn't been started yet.\n");
printf("The Pi uses the GPU to start up the CPU using the firmware's\n");
printf("routines described in it's code to boot.\n");
}
int endSoFar(void)
{
printf("Until I know a bit better about the RPi firmware\n");
printf("The documentation will have to end here.\n");
}
|
C | #include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
int i,j,k;
double thres;
FILE *outfile;
int NumFADC[8];
for(i=0;i<8;i++) NumFADC[i]=0;
if (argc<2){
printf("few argument...\n");
exit(-1);
}
for(i=1;i<argc;i++){
sscanf(argv[i],"%d",&(NumFADC[i-1]));
}
printf("Thres?: ");
scanf("%lf",&thres);
if ((outfile=fopen("pedestal.txt","w"))==NULL){
printf("Cannot open file...\n"); exit(0);
}
for(i=0;i<8;i++){
for(j=0;j<NumFADC[i];j++){
for(k=0;k<16;k++){
fprintf(outfile,"%d %d %d %f 3.\n",i,j,k,thres);
}
}
}
fclose(outfile);
exit(0);
}
|
C |
// program odf sorting using bubble sort*/
// Author udhayamoorthi
// the bubble sort scanning the list and excange the adjacent if they are out of order with respect to each other.
#include<stdio.h>
#define MAX 100// all lines that start with # are prepocessed by preprocessor
int main()
{
int arr[MAX],i,k,j,n,temp,xchanges;
printf("Enter the num of ele:");// program has to enter the value
scanf("%d",&n);
/*bumble sort*/
for(i=0;i<n-1;i++)//value n-1
{
xchanges =0;
for(j=0;j<n-1-i;j++)//value n-1-i
{
if(arr[j]>arr[j+1])//a[j] will be compared with arr[j+1]
{
temp=arr[j];/* if arr[j]>arr[j+1] then they will be swapped*/
arr[j]=arr[j+1];
arr[j+1]=temp;
xchanges++;
}
}
if(xchanges==0)/*if lis is sorted*/
break;
}
printf("sorted list is:\n");//this printf for print the output
for(i=0;i<n;i++)
printf("%d",arr[i]);
}/*end of line*/
|
C | #include <stdio.h>
#include <stdlib.h>
int main()
{
char a,b,c;
printf("es de maniana?\n");
a=getche();
printf("\nEl llamado es de tu casa?\n");
b=getche();
printf("\nEstas en clase?\n");
c=getche();
if(c=='s'||c=='S')
{
printf("\nno debe atender");
}
else
{
if (a=='s'||a=='S')
{
if (b=='s'||b=='S')
{
printf("\ndebe atender");
}
else
{
printf("\nno debe atender");
}
}
else
{
printf("\ndebe atender");
}
}
return 0;
}
|
C | /*this is a module in DomU to create a Grant Reference,
* and this will pass manaully to the Dom0,then dom0
* can access the page in DomU by the GR
* */
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <asm/pgtable.h>
#include <xen/page.h>
#include <asm/sync_bitops.h>
#include <xen/interface/grant_table.h>
#include <xen/interface/xen.h>
#include <xen/grant_table.h>
#include "dbg_kernel.h"
unsigned long page;
grant_ref_t gref;
//grant to which domain
//
#define DOMO_ID 0
int init_module(void){
int mfn;
page = __get_free_pages(GFP_KERNEL,1);
check(page , "xen: could not grant foreign access\n");
mfn = virt_to_mfn(page);
gref = gnttab_grant_foreign_access(DOMO_ID , mfn,0);
check(gref, "xen: could not grant foreign access\n");
printk("\n page = %d, mfn=%d\n", page,mfn);
printk("the grant table ref is %d.\n",gref);
printk("....\n...");
return 0;
error:
if(page)
free_page((unsigned long)page);
return -1;
}
void cleanup_module(void){
printk("Cleanup the gref\n");
if (gnttab_query_foreign_access(gref) == 0) {
printk("No map with the gref %d\n",gref);
gnttab_end_foreign_access(gref, 0, page);
}
else{
printk("The gref %d has been mapped.\n",gref);
gnttab_end_foreign_access(gref,0, page);
}
}
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Wuzhe Yin");
MODULE_DESCRIPTION("the module grant an page to the other doamin");
|
C | /*
* A procfs tic-tac-toe game and general playground for developing kernel
* loadable modules in Linux 3.10 and later.
*
* - Uses the procfs API in 3.10+
* - Implements read and write.
*/
#ifndef __KERNEL__
#define __KERNEL__
#define MODULE
#endif
#include <asm/uaccess.h>
#include <linux/delay.h>
#include <linux/ctype.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("donp");
MODULE_DESCRIPTION("In-kernel tic-tac-toe");
/* ************************************************************************ */
/* Game logic */
#define TTT_NONE '-'
#define TTT_OVER '+'
#define TTT_O 'O'
#define TTT_X 'X'
#define TTT_WINNER 0
static char ttt_game[10]; /* pos 0 is winner */
static char ttt_turn = TTT_NONE;
static char ttt_count = 0;
static void ttt_reset(void)
{
memset(ttt_game, TTT_NONE, sizeof(char) * 10);
ttt_turn = TTT_O; /* O always goes first */
ttt_count = 0;
}
static void ttt_check_winner(void)
{
if ((ttt_game[1] == ttt_game[5]) &&
(ttt_game[5] == ttt_game[9]) &&
(ttt_game[9] == TTT_NONE)) {
ttt_game[TTT_WINNER] = TTT_NONE;
} else if ((ttt_game[1] == ttt_game[2]) &&
(ttt_game[2] == ttt_game[3]) &&
(ttt_game[3] != TTT_NONE)) {
ttt_game[TTT_WINNER] = ttt_game[1];
} else if ((ttt_game[4] == ttt_game[5]) &&
(ttt_game[5] == ttt_game[6]) &&
(ttt_game[6] != TTT_NONE)) {
ttt_game[TTT_WINNER] = ttt_game[4];
} else if ((ttt_game[7] == ttt_game[8]) &&
(ttt_game[8] == ttt_game[9]) &&
(ttt_game[9] != TTT_NONE)) {
ttt_game[TTT_WINNER] = ttt_game[7];
} else if ((ttt_game[1] == ttt_game[4]) &&
(ttt_game[4] == ttt_game[7]) &&
(ttt_game[7] != TTT_NONE)) {
ttt_game[TTT_WINNER] = ttt_game[1];
} else if ((ttt_game[2] == ttt_game[5]) &&
(ttt_game[5] == ttt_game[8]) &&
(ttt_game[8] != TTT_NONE)) {
ttt_game[TTT_WINNER] = ttt_game[2];
} else if ((ttt_game[3] == ttt_game[6]) &&
(ttt_game[6] == ttt_game[9]) &&
(ttt_game[9] != TTT_NONE)) {
ttt_game[TTT_WINNER] = ttt_game[3];
} else if ((ttt_game[1] == ttt_game[5]) &&
(ttt_game[5] == ttt_game[9]) &&
(ttt_game[9] != TTT_NONE)) {
ttt_game[TTT_WINNER] = ttt_game[1];
} else if ((ttt_game[3] == ttt_game[5]) &&
(ttt_game[5] == ttt_game[7]) &&
(ttt_game[7] != TTT_NONE)) {
ttt_game[TTT_WINNER] = ttt_game[3];
} else {
ttt_game[TTT_WINNER] = TTT_NONE;
}
if (ttt_game[TTT_WINNER] != TTT_NONE)
ttt_turn = TTT_NONE;
if (ttt_count >= 9)
ttt_turn = TTT_OVER;
}
static void ttt_take_turn(char player, int pos)
{
if (ttt_turn != player)
return;
if (pos < 1 || pos > 9)
return;
if (ttt_game[pos] == TTT_NONE) {
ttt_game[pos] = player;
ttt_turn = (ttt_turn == TTT_O) ? TTT_X : TTT_O;
ttt_count++;
}
ttt_check_winner();
}
/* ************************************************************************ */
/* Proc file */
#define TTT_PROC_NAME "ttt"
static struct proc_dir_entry *ttt_proc;
static const mode_t TTT_MODE = 0666;
/* Proc file contents */
#define TTT_OUTPUT_LENGTH 36
static char ttt_output[TTT_OUTPUT_LENGTH];
static size_t ttt_output_size;
/*
* Update the file data.
*/
static void ttt_update(void)
{
char state[16];
if (ttt_turn == TTT_OVER)
strncpy(state, "game over", sizeof(state));
else if (ttt_turn == TTT_NONE)
snprintf(state, sizeof(state), "winner is %c",
ttt_game[TTT_WINNER]);
else
snprintf(state, sizeof(state), "turn is %c", ttt_turn);
ttt_output_size = snprintf(ttt_output, TTT_OUTPUT_LENGTH,
"%c %c %c\n%c %c %c\n%c %c %c\n%s\n",
ttt_game[1], ttt_game[2], ttt_game[3],
ttt_game[4], ttt_game[5], ttt_game[6],
ttt_game[7], ttt_game[8], ttt_game[9],
state);
if (ttt_output_size > TTT_OUTPUT_LENGTH)
printk(KERN_ALERT "TTT output buffer overflow\n");
}
/*
* Called when the file is read from
* file -- ?
* buffer OUT the buffer to write into
* bufsize IN the size of the write buffer
* offset IN the offset in the output data to start at
* OUT the next position in the output data to start from
* return: the number of bytes written to the buffer
*
*/
static ssize_t ttt_proc_read(struct file *file, char *buffer, size_t bufsize,
loff_t *offset)
{
int nbytes;
if (*offset > ttt_output_size)
return 0;
nbytes = ttt_output_size - *offset;
if (nbytes > bufsize)
nbytes = bufsize;
printk(KERN_INFO "TTT READ bytes to copy %d\n", nbytes);
if (copy_to_user(buffer, ttt_output + *offset, nbytes)) {
printk(KERN_ALERT "TTT READ copy_to_user failed\n");
return -EFAULT;
}
*offset += nbytes;
return nbytes;
}
/*
* Called when the file is written to
*/
static ssize_t ttt_proc_write(struct file *file, const char *buffer,
size_t bufsize, loff_t *offset)
{
char input[16] = { 0 };
int nbytes;
if (*offset > bufsize)
return 0;
if (bufsize > sizeof(input) + *offset)
nbytes = sizeof(input);
else
nbytes = bufsize - *offset;
if (copy_from_user(input, buffer + *offset, nbytes)) {
printk(KERN_ALERT "TTT WRITE copy_from_user failed\n");
return -EFAULT;
}
input[nbytes] = 0;
printk(KERN_INFO "TTT WRITE [%d] %s", nbytes, input);
if (strncmp(input, "reset", 5) == 0) {
ttt_reset();
ttt_update();
} else if (bufsize >= 2) {
char player = toupper(input[0]);
int position = input[1] - '0';
ttt_take_turn(player, position);
ttt_update();
}
*offset += nbytes;
return nbytes;
}
static struct file_operations ttt_file_ops = {
.owner = THIS_MODULE,
.read = ttt_proc_read,
.write = ttt_proc_write
};
/*
* Allow other kernel modules to play TTT by submitting turns.
* player -- X or O
* position -- in 1 to 9, inclusive
* Return: 0 on success, 1 on failure.
*/
static int ttt_set_turn(char player, int position)
{
int result = 1;
player = toupper(player);
position--;
if (player == TTT_O || player == TTT_X) {
ttt_take_turn(player, position);
ttt_update();
result = 0; /* SUCCESS */
}
return result;
}
/*
* Get the symbol of the next player's turn, O or X.
* A '+' indicates the game is over.
* Return: 0 on success, 1 on failure.
*/
static int ttt_get_turn(char *player)
{
int result = 1;
if (player) {
*player = ttt_turn;
result = 0; /* SUCCESS */
}
return result;
}
/*
* Get the symbol of the winner, 'O' or 'X'.
* If the game is not over
*
* Return: 0 on success, 1 on failure.
*/
static int ttt_get_winner(char *winner)
{
int result = 1;
if (winner && ttt_game[0]) {
*winner = ttt_game[0];
result = 0; /* SUCCESS */
}
return result;
}
EXPORT_SYMBOL(ttt_get_turn);
EXPORT_SYMBOL(ttt_set_turn);
EXPORT_SYMBOL(ttt_get_winner);
/*
* Initialize the kernel module.
*/
static __init int ttt_init( void )
{
struct proc_dir_entry *parent = NULL;
ttt_proc = proc_create(TTT_PROC_NAME, TTT_MODE, parent, &ttt_file_ops);
if (!ttt_proc) {
printk(KERN_ALERT "TTT failed to create proc file\n" );
return -ENOMEM;
}
ttt_reset();
ttt_update();
/* Log success */
printk(KERN_ALERT "TTT loaded\n" );
return 0;
}
/*
* Clean up the module.
*/
static __exit void ttt_exit( void )
{
if (ttt_proc)
remove_proc_entry(TTT_PROC_NAME, NULL);
printk(KERN_ALERT "TTT unloaded\n" );
}
module_init(ttt_init);
module_exit(ttt_exit);
/* vim: set ts=8 */
|
C | #include<stdio.h>
#include"../headers/errno.h"
#include"../headers/nheaders.h"
#include"../headers/lheaders.h"
#define start (*_list)->lstart
/**************************************************** DELETION FUNCTIONS ********************************************************/
/*Always deletes the first element in the que */
int del_first(list_t **_list){
que_t *tmp = start;
/*Q has no ele*/
if(!tmp){
errno = EEPTY;
return FAILURE;
}
/*it has some elements >0*/
start = tmp->next;
tmp->next = NULL;
(*_list)->cnt--;//used to display how many nodes in a list..
free(tmp);
return (errno = SUCCESS);
}
/*always delete last ele in the Q*/
int del_last(list_t **_list){
que_t *tmp = start;
if(!tmp){//already que empty
errno = EEPTY;
return FAILURE;
}
/*only one ele in que*/
if(!tmp->next){
start = NULL;
(*_list)->cnt--;
free(tmp);
return (errno = SUCCESS);
}
que_t *prev;
while(tmp->next){
prev = tmp; //to make "prev_node->next" of deleting node to NULL we take its back up into prev. Since rear end of the que must be end with NULL..
tmp = tmp->next;
}
prev -> next = NULL;
(*_list)->cnt--;
free(tmp);
return (errno = SUCCESS);
}
int del_ele(list_t **_list){
int val;
printf("enter the ele: ");
scanf(" %d",&val);
que_t *tmp = start;
if(!tmp){
errno = EEPTY;
return FAILURE;
}
/*if delting ele is 1st ele in que*/
if(tmp -> data == val){
start = tmp -> next;
(*_list)->cnt--;
free(tmp);
return SUCCESS;
}
/*if some ele are there in que >1; u r deleting middle(not first/last) ele */
que_t *prev;
while(tmp->data != val){
prev = tmp;
if(!tmp->next){//ele is not found
errno = EFOUND;
return FAILURE;
}
tmp = tmp->next;
}
prev -> next = tmp->next;
(*_list)->cnt--;
free(tmp);
/*del ele is last ele*/
//even for last element case above function will work
return (errno = SUCCESS);
}
int flush(list_t **_list){//delete entire list
while(start){
que_t *next = start ->next;
free(start);
start = next;
}
(*_list)->cnt = 0;
// start = NULL; no need bcoz by the time start comes out of loop(fails bcoz of NULL) its value = NULL only na..
return (errno = SUCCESS);
}
|
C | ////////////////////////////////////////////////////////////////////////////////
// File: trapezoidal_method.c //
// Routines: //
// Trapezoidal_Method //
// Trapezoidal_Integral_Curve //
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// //
// Description: //
// The trapezoidal method is an implicit method for approximating the //
// solution of the differential equation y'(x) = f(x,y) with initial //
// condition y(a) = c. The trapezoidal method can be derived by //
// expanding y(x+h) in a Taylor series about x, //
// y(x+h) = y(x) + h*y'(x) + (h^2 / 2)*y''(x) + (h^3 / 6)*y'''(x) +... //
// and substituting (y'(x+h)-y'(x))/h for y''(x) and y'(x) = f(x,y(x)), //
// y(x+h) = y(x) + (h/2) * (f(x+h,y(x+h) - f(x,h)) + O(h^3). //
// //
// Let y[n] = y(a + nh), x[n] = a + nh, then the recursion formula for //
// the trapezoidal method is: //
// y[n+1] = y[n] + (h/2) * ( f(x[n],y[n]) + f(x[n+1],y[n+1]) ) //
// //
// I.e. y[n+1] is the solution y to: //
// y - (h/2)*(f(x[n+1],y) = y[n] + (h/2)*f(x[n],y[n]). //
// //
// Thus locally the trapezoidal method is a third order method and //
// globally a second order method. //
// //
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// double Trapezoidal_Method( double (*f)(double, double), //
// double (*g)(double,double,double), double y0, double x0, //
// double h, int number_of_steps ); //
// //
// Description: //
// This routine uses the trapezoidal method to approximate the solution //
// at x = x0 + h * number_of_steps of the initial value problem y'=f(x,y),//
// y(x0) = y0. //
// //
// Arguments: //
// double *f //
// Pointer to the function which returns the slope at (x,y) of the //
// integral curve of the differential equation y' = f(x,y) which //
// passes through the point (x0,y0). //
// double *g //
// Pointer to the function g(x,h,u) which returns the value y //
// such that y - h * f(x,y) = u. //
// double y0 //
// The initial value of y at x = x0. //
// double x0 //
// The initial value of x. //
// double h //
// The step size. //
// int number_of_steps //
// The number of steps. Must be a nonnegative integer. //
// //
// Return Values: //
// The solution of the initial value problem y' = f(x,y), y(x0) = y0 at //
// x = x0 + number_of_steps * h. //
// //
////////////////////////////////////////////////////////////////////////////////
// //
double Trapezoidal_Method( double (*f)(double, double),
double (*g)(double,double,double), double y0, double x0,
double h, int number_of_steps ) {
double u;
double h2 = 0.5 * h;
while ( --number_of_steps >= 0 ) {
u = y0 + h2 * f(x0,y0);
x0 += h;
y0 = g(x0, h2, u);
}
return y0;
}
////////////////////////////////////////////////////////////////////////////////
// void Trapezoidal_Integral_Curve( double (*f)(double, double), //
// double (*g)(double,double,double), double y[], double x0, //
// double h, int number_of_steps_per_interval, //
// int number_of_intervals ); //
// //
// Description: //
// This routine uses the trapezoidal method to approximate the solution //
// of the differential equation y'=f(x,y) with the initial condition //
// y = y[0] at x = x0. The values are returned in y[n] which is the //
// value of y evaluated at x = x0 + n * m * h, where m is the number of //
// steps per interval and n is the interval number, //
// 0 <= n <= number_of_intervals. //
// //
// Arguments: //
// double *f //
// Pointer to the function which returns the slope at (x,y) of the //
// integral curve of the differential equation y' = f(x,y) which //
// which passes through the point (x0,y[0]). //
// double *g //
// Pointer to the function g(x,h,u) which returns the value y //
// such that y - h/2 f(x,y) = u. //
// double y[] //
// On input y[0] is the initial value of y at x = x0. On output //
// y[n+1] = y[n] + m*h*f(a + n*m*h, y[n] ), where m is the number //
// of steps per interval and n is the interval number. //
// double x0 //
// Initial value of x. //
// double h //
// Step size //
// int number_of_steps_per_interval //
// The number of steps of length h used to calculate y[i+1] //
// starting from y[i]. //
// int number_of_intervals //
// The number of intervals, y[] should be dimensioned at least //
// number_of_intervals + 1. //
// //
// Return Values: //
// This routine is of type void and hence does not return a value. //
// The solution of y' = f(x,y) from x = x0 to x = x0 + n * m * h, //
// where n is the number of intervals and m is the number of steps per //
// interval, is stored in the input array y[]. //
// //
////////////////////////////////////////////////////////////////////////////////
// //
void Trapezoidal_Integral_Curve( double (*f)(double, double),
double (*g)(double,double,double), double y[], double x0, double h,
int number_of_steps_per_interval, int number_of_intervals ) {
double u;
double h2 = 0.5 * h;
int i;
while ( --number_of_intervals >= 0 ) {
*(y+1) = *y;
y++;
for (i = 0; i < number_of_steps_per_interval; i++) {
u = *y + h2 * f(x0,*y);
x0 += h;
*y = g(x0, h2, u);
}
}
}
|
C | #ifndef _HWE_COMMON_H_
#define _HWE_COMMON_H_
#include <stdint.h>
#include <stdbool.h>
/*
* Common definition for all events
*/
/*
* version of trace (present in HWE_INFO event)
*/
#define HWE_VERSION_MAJOR 1
#define HWE_VERSION_MINOR 3
#define HWE_VERSION (256*HWE_VERSION_MAJOR + HWE_VERSION_MINOR)
/**********************************************************************
******** HWE_HEADER ******************************************
**********************************************************************/
/*
* Common header for every event.
*
* Mapping:
* hwe_id_dev_t devid;
* hwe_head_t head;
* hwe_date_t dates[0..HWE_DATE_MAX];
* hwe_id_t nrefs[0..HWE_REF_MAX];
*/
/*
* Dependencies/References rules:
* There is always 2 events involved:
* - the 'referenced' event
* - the 'referencing' event (which contains the id of the 'referenced' event)
*
* There is rules for dependencies contained into an event.
* An event cannot depend on any event, there is some constraints.
* All rules are here to bound the "life" of each event:
* If we do not know if an event will still be referenced, we can't close/delete/process it.
*
* There 2 types of dependencies/references: "expected" and "local".
*
* * Expected dependencies:
*
* Some events expect to be referenced by others (ex: a memory access).
* For each event the number of expected reference is known when reading the
* event, this allows to 'close' an event when all 'expected' references have
* been found.
* Theses references can be put in events from any device.
*
* * Local dependencies:
*
* It is always possible to make 'local' references (ie: to reference an event
* issued by the same device without being expected).
* An event can be localy referenced until an event (excluding HWE_ID/HWE_NULL) that does not
* reference it is issued. I.E.: a reference to an event can be done
* - before it is issued
* - just after it is issued
*/
/*
* Type of an event
*/
typedef enum hwe_type_t {
/* HWE_ID:
* not a real event (see below)
* used to reset the current id to a given value when the id
* field has not enough range to express the new id of the next event
*/
HWE_ID = 0,
/*
* HWE_NULL:
* null/empty event (just a header),
* should be used either as a dependencies container or to commit
* a canceled event (as every event must be commited)
*/
HWE_NULL = 1,
/*
* HWE_INFO:
* Information on device (see hwe_info.h)
* Every device trace must start with one HWE_INFO event
*/
HWE_INFO = 2,
/*
* HWE_SPREAD:
* Modify number of expected references (see hwe_spread.h)
*/
HWE_SPREAD = 3,
/*
* Memory accesses (see hwe_mem.h)
*/
HWE_MEMGL = 4, // global memory access
HWE_MEM32, // 32bits address memory access (must be acknowledged (or relayed) once)
HWE_MEMACK, // indicate that a mem access has been taken into account
/*
* Instruction related events (see hwe_inst.h)
*/
HWE_INST32 = 8, // instruction on 32bits A/D architecture
HWE_EXCEP32, // exception in 32bits A/D architecture
HWE_CPU_MEM, // Request to memory
HWE_CPU_IO, // Request to IO
/*
* Event in RABBITS platform to commit events after that execution
*/
HWE_COMMIT,
HWE_SPARE,
} hwe_type_t;
/*
* ID of an event
*/
typedef uint64_t hwe_id_ind_t;
#define HWE_PRI_ID PRIu64
typedef int32_t hwe_id_ind_st;//signed version of hwe_id_ind_t
typedef uint8_t hwe_id_dev_t;
typedef struct hwe_id_t {
hwe_id_dev_t devid; // device identifier
hwe_id_ind_t index; // index inside device events
} __attribute__((__packed__)) hwe_id_t;
static const hwe_id_t HWE_ID_NULL = { 0, 0 };
/*
* header
*/
typedef struct hwe_head_t {
// type
hwe_type_t type:4;
// id relative to the previous event one in the trace
int rid:4;
// indicate the number of dates that follow this header
unsigned ndates:2;
// indicate the number of references that follow this header
unsigned nrefs:6;
// indicate the number of expected followers (ie: events which refer to this one)
unsigned expected:32;
//
unsigned nchild:32;
unsigned com_child:32; // :8 before flushes
} __attribute__((__packed__)) hwe_head_t;
/*
* some defines (max elements in array of dates and refs max differntial id)
*/
#define HWE_REF_MAX 16
// #define HWE_EXP_MAX 255
#define HWE_EXP_MAX 16384
#define HWE_DATE_MAX 2
#define HWE_RID_MAX 7
#define HWE_RID_MIN (-8)
#define HWE_CHILD_MAX 32768
/*
* date:
* if there is:
* * 2 dates -> begin "[0]" and end "[1]" date
* * 1 date -> the date "[0]"
* * 0 date -> ...
*
*/
typedef uint64_t hwe_date_t;
#define HWE_PRI_DATE PRIu64
/*
* container
*/
typedef struct hwe_head_cont hwe_head_cont;
typedef uintptr_t hwe_ref_t;
#define HWE_REF_NULL ((hwe_ref_t) NULL)
struct hwe_head_cont {
hwe_id_t id; // whole id
hwe_ref_t self;
hwe_head_t head; // header
hwe_date_t dates[HWE_DATE_MAX]; // dates
hwe_ref_t refs[HWE_REF_MAX];
// ptr to next container (it's a linekd list)
hwe_head_cont *refnext;
// ptr to last container (if this event is the head of the list)
hwe_head_cont *reflast;
// Events which were generated by this one
hwe_head_cont *child[HWE_CHILD_MAX];
// Its generator
hwe_head_cont *parent;
//Its identification on parent's child list
uint32_t child_slot;
};
/**********************************************************************
******** HWE_ID **********************************************
**********************************************************************/
/*
* Fake event used to set the id index to an absolute value (when relative
* header field is not enough wide)
*
* Mapping:
* HEADER;
* hwe_id_ind_t id;
*/
#endif // _HWE_COMMON_H_
/**********************************************************************
******** TOOLS ***********************************************
**********************************************************************/
#ifdef HWE_USE_TOOLS
#ifndef _HWE_TOOLS_COMMON_H_
#define _HWE_TOOLS_COMMON_H_
#include <stdio.h>
#include <inttypes.h>
#include <stdlib.h>
#include <string.h>
static inline void hwe_head_init(hwe_head_cont *cont)
{
cont->id = HWE_ID_NULL;
cont->head.type = HWE_NULL;
cont->head.ndates = 0;
cont->head.nrefs = 0;
cont->head.expected = 0;
cont->head.nchild = 0;
cont->head.com_child = 0;
cont->child[0] = 0;
// memset((void*)cont->child,0,sizeof(struct hwe_head_cont**)*HWE_CHILD_MAX);
cont->refnext = NULL;
cont->reflast = cont;
cont->parent = NULL;
cont->child_slot = 0;
}
static inline void hwe_head_extend(hwe_head_cont *main, hwe_head_cont *ext)
{
main->reflast->refnext = ext;
main->reflast = ext;
ext->reflast = NULL;
}
/*
* get & set a reference
*/
static inline unsigned hwe_getnref(const hwe_head_cont *cont)
{
return cont->head.nrefs;
}
static inline hwe_ref_t hwe_getref(const hwe_head_cont *cont, unsigned n)
{
//n sould be < HWE_REF_MAX
return cont->refs[n];
}
static inline void hwe_setref(hwe_head_cont *cont, unsigned n, hwe_ref_t ref)
{
//n sould be < HWE_REF_MAX
cont->refs[n] = ref;
}
/*
* string for event type
*/
#define CASE(foo) case HWE_##foo : return #foo ;
static inline const char * hwe_type_getname(hwe_type_t type) {
switch (type) {
CASE(ID)
CASE(NULL)
CASE(INFO)
CASE(SPREAD)
CASE(MEMGL)
CASE(MEM32)
CASE(MEMACK)
CASE(INST32)
CASE(EXCEP32)
CASE(CPU_MEM)
CASE(CPU_IO)
CASE(COMMIT)
CASE(SPARE)
}
return NULL;
}
#undef CASE
/*
* fill the id fields (rid + device) of the header depending on the last id index
* if the field has not enough range:
* + set it to zero and return false
* + an HWE_ID event must be generated
*/
static inline bool hwe_head_rid_compute(hwe_head_cont *cont, hwe_id_ind_t prev_id)
{
// rid
hwe_id_ind_st diff = cont->id.index - prev_id;
if (diff < HWE_RID_MIN || diff > HWE_RID_MAX) {
cont->head.rid = 0;
return false;
}
cont->head.rid = diff;
return true;
}
/*
* set the rid field to 0
*/
static inline void hwe_head_rid_zero(hwe_head_cont *cont)
{
cont->head.rid = 0;
}
/*
* set the whole id of container using header id field and previous id
*/
static inline void hwe_id_compute(hwe_head_cont *cont, hwe_id_ind_t prev_id)
{
// index
cont->id.index = prev_id + ((hwe_id_ind_st) cont->head.rid);
}
/*
* compute the size needed to store an header of an event
*/
static inline size_t hwe_head_sizeof(const hwe_head_cont *cont)
{
size_t res = sizeof(hwe_id_dev_t) + sizeof(hwe_head_t);
res += sizeof(hwe_date_t) * cont->head.ndates;
res += sizeof(hwe_id_t) * cont->head.nrefs;
return res;
}
/*
* write the header to the given memory location
* which must have enough allocated space
* return the address following the header
*/
static inline void * hwe_head_write(const hwe_head_cont *cont, hwe_id_t *idrefs, void *dest)
{
size_t nbytes;
nbytes = sizeof(hwe_id_dev_t);
memcpy(dest, &cont->id.devid, nbytes);
dest += nbytes;
nbytes = sizeof(hwe_head_t);
memcpy(dest, &cont->head, nbytes);
dest += nbytes;
nbytes = sizeof(hwe_date_t) * cont->head.ndates;
memcpy(dest, &cont->dates, nbytes);
dest += nbytes;
nbytes = sizeof(hwe_id_t) * cont->head.nrefs;
memcpy(dest, idrefs, nbytes);
dest += nbytes;
return dest;
}
/*
* read
*/
static inline size_t hwe_head_read(hwe_head_cont *cont, hwe_id_t *idrefs, const void *buf, const size_t size)
{
size_t need, cur, cur2;
need = sizeof(hwe_head_t) + sizeof(hwe_id_dev_t);
if (size < need)
return 0;
memcpy(&cont->id.devid, buf, sizeof(hwe_id_dev_t));
buf += sizeof(hwe_id_dev_t);
memcpy(&cont->head, buf, sizeof(hwe_head_t));
buf += sizeof(hwe_head_t);
cur = sizeof(hwe_date_t) * cont->head.ndates;
cur2 = sizeof(hwe_id_t) * cont->head.nrefs;
need += cur + cur2;
if (size < need)
return 0;
memcpy(&cont->dates, buf, cur);
buf += cur;
memcpy(idrefs, buf, cur2);
cont->id.index = 0;
return need;
}
/*
* print
*/
typedef hwe_id_t (*hwe_ref2id_f) (hwe_ref_t);
static inline void hwe_head_print(FILE *stream, const hwe_head_cont *cont, hwe_ref2id_f ref2id)
{
const char *tname = hwe_type_getname(cont->head.type);
if (tname == NULL)
tname = "UNKNOWN";
fprintf(stream, "HWE %u.%"HWE_PRI_ID" %s\n", cont->id.devid, cont->id.index, tname);
if (cont->head.expected) {
fprintf(stream, "\t expected %u reference(s)\n", cont->head.expected);
}
if (cont->head.ndates != 0) {
fprintf(stream, "\t dates=[");
for (unsigned int i = 0; i < cont->head.ndates; i++) {
fprintf(stream, " %"HWE_PRI_DATE, cont->dates[i]);
}
fprintf(stream, " ]\n");
}
if (cont->head.nrefs != 0) {
fprintf(stream, "\t refs=[");
for (const hwe_head_cont *cur = cont; cur != NULL; cur = cur->refnext) {
for (unsigned int i = 0; i < cur->head.nrefs; i++) {
if (ref2id == NULL) {
fprintf(stream, " ?.?");
} else {
hwe_id_t id = ref2id(cur->refs[i]);
fprintf(stream, " %u.%"HWE_PRI_ID, id.devid, id.index);
}
}
if (cur->refnext != NULL)
fprintf(stream, " |");
}
fprintf(stream, " ]\n");
}
}
/*
* desc
*/
static inline int hwe_head_desc(const hwe_head_cont *cont, hwe_ref2id_f ref2id, char *str, int len)
{
const char *tname = hwe_type_getname(cont->head.type);
if (tname == NULL)
tname = "UNKNOWN";
int cur = 0;
if (cont->head.expected)
cur = snprintf(str, len, "%u.%"HWE_PRI_ID"[X%u] %s", cont->id.devid, cont->id.index,
cont->head.expected, tname);
else
cur = snprintf(str, len, "%u.%"HWE_PRI_ID" %s", cont->id.devid, cont->id.index,
tname);
switch (cont->head.ndates) {
case 1:
cur += snprintf(str + cur, len - cur, "[D%"HWE_PRI_DATE"]", cont->dates[0]);
break;
case 2:
cur += snprintf(str + cur, len - cur, "[D%"HWE_PRI_DATE"+%"HWE_PRI_DATE"]", cont->dates[0], cont->dates[1] - cont->dates[0]);
break;
default:
break;
}
unsigned nrefs = 0;
for (const hwe_head_cont *cur = cont; cur != NULL; cur = cur->refnext)
nrefs += cur->head.nrefs;
switch (nrefs) {
case 0:
break;
case 1:
if (ref2id != NULL) {
hwe_id_t id = ref2id(cont->refs[0]);
cur += snprintf(str+cur, len - cur, "[R %u.%"HWE_PRI_ID"]", id.devid, id.index);
} else {
cur += snprintf(str+cur, len - cur, "[R ?.?]");
}
break;
default:
cur += snprintf(str+cur, len - cur, "[R #%u]", nrefs);
break;
}
return cur;
}
/*
* compute the size needed to store an header of an event
*/
static size_t HWE_ID_SIZEOF = sizeof(hwe_id_dev_t) + sizeof(hwe_head_t) + sizeof(hwe_id_ind_t);
/*
* write the HWE_ID event corresponding to the given memory location
* which must have enough allocated space
* return the address following the event
*/
static inline void * hwe_id_write(const hwe_head_cont *cont, void *dest)
{
struct {
hwe_id_dev_t devid;
hwe_head_t head;
hwe_id_ind_t index;
} __attribute__((__packed__)) hwe_id = {
.devid = cont->id.devid,
.head = {
.type = HWE_ID,
.rid = 0,
.expected = 0,
.nrefs = 0,
.ndates = 0
},
.index = cont->id.index
};
size_t nbytes = sizeof(hwe_id);
memcpy(dest, &hwe_id, nbytes);
return dest + nbytes;
}
/*
* read
*/
static inline size_t hwe_id_read(hwe_head_cont *cont,
const void *buf, const size_t size)
{
size_t need = sizeof(hwe_id_ind_t);
if (size < need) return 0;
memcpy(&cont->id.index, buf, need);
return need;
}
#endif // _HWE_TOOLS_COMMON_H_
#endif // HWE_USE_TOOLS
|
C |
#ifndef _PARSE_EXP_H
#define _PARSE_EXP_H
#include "stack.h"
#include "token.h"
#include "ast.h"
#include "hashtable.h"
#define AST_STACK 0
#define OP_STACK 1
typedef uint32_t parse_exp_disallow_t; // A bit mask
#define PARSE_EXP_ALLOWALL 0x00000000
#define PARSE_EXP_NOCOMMA 0x00000001 // Do not allow outermost ','
#define PARSE_EXP_NOCOLON 0x00000002 // Do not allow outermost ':'
typedef struct {
// Either AST_STACK or OP_STACK; do not need save because a shift will happen
int last_active_stack;
stack_t *stacks[2];
stack_t *tops[2];
stack_t *prev_active;
token_cxt_t *token_cxt;
} parse_exp_cxt_t;
parse_exp_cxt_t *parse_exp_init(char *input);
void parse_exp_reinit(parse_exp_cxt_t *cxt, char *input);
void parse_exp_free(parse_exp_cxt_t *cxt);
int parse_exp_isoutermost(parse_exp_cxt_t *cxt);
int parse_exp_isallowed(parse_exp_cxt_t *cxt, token_t *token, parse_exp_disallow_t disallow);
int parse_exp_isexp(parse_exp_cxt_t *cxt, token_t *token, parse_exp_disallow_t disallow);
int parse_exp_isprimary(parse_exp_cxt_t *cxt, token_t *token);
int parse_exp_la_isdecl(parse_exp_cxt_t *cxt);
int parse_exp_size(parse_exp_cxt_t *cxt, int stack_id);
token_t *parse_exp_peek(parse_exp_cxt_t *cxt, int stack_id);
token_t *parse_exp_peek_at(parse_exp_cxt_t *cxt, int stack_id, int index);
int parse_exp_isempty(parse_exp_cxt_t *cxt, int stack_id);
void parse_exp_recurse(parse_exp_cxt_t *cxt);
void parse_exp_decurse(parse_exp_cxt_t *cxt);
token_t *parse_exp_next_token(parse_exp_cxt_t *cxt, parse_exp_disallow_t disallow);
void parse_exp_shift(parse_exp_cxt_t *cxt, int stack_id, token_t *token);
token_t *parse_exp_reduce(parse_exp_cxt_t *cxt, int op_num_override, int allow_paren);
void parse_exp_reduce_preced(parse_exp_cxt_t *cxt, token_t *token);
token_t *parse_exp_reduce_all(parse_exp_cxt_t *cxt);
token_t *parse_exp(parse_exp_cxt_t *cxt, parse_exp_disallow_t disallow);
#endif |
C | #include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[]) {
int n, capacity, current, summation = 0, i = 0;
scanf("%d %d", &n, &capacity);
while(n--) {
scanf("%d", ¤t);
summation += current;
if(summation > capacity)
break;
else
i++;
}
printf("%d\n", i);
return 0;
} |
C | #include<stdio.h>
void f(int *p)
{
*p = 100;
return;
}
int main(void)
{
int i = 99;
f(&i);
printf("i = %d\n", i);
return 0;
} |
C | #include<stdio.h>
#include<string.h>
int main()
{
int n;
scanf("%d ", &n);
char words[n][20];
char ch;
for(int i = 0; i < n; i++)
scanf("%s ", &words[i]);
scanf("%c", &ch);
for(int i = 0; i < n; i++)
for(int j = 0; j < strlen(words[i]); j++)
if(words[i][j] == ch)
{
printf("%s\n", words[i]);
break;
}
} |
C | //
// Created by Administrator on 9/12/19.
//
#include "Ejercicio8.h"
char ** eliminar_mrt(char * pal)
{
char *ei = "MU_TEST(";
char *ef = ")";
int longitudei = (int)(strlen(ei));
char *pi,*pf;
pi = pal;
char *result = malloc(sizeof(char));
int tmp,c;
c = 1;
while((pi = strstr(pi,ei)) != NULL)
{
pi += longitudei;
pf = strstr(pf=pi,ef);
tmp = pf - pi;
if(pf == NULL)
{
break;
}
else if(pi != NULL)
{
result[c-1] = malloc((tmp+1) * sizeof(char));
result[c-1] = strncpy(result[c-1],pi,tmp);
result[c-1][tmp] = '\0';
c++;
result = realloc(result,c * sizeof(char*));
}
}
return result;
}
char **comparar(char **a,char **b)
{
char *i,*j;
char *result = malloc(sizeof(char));
int c =1,n;
for(i=a;*i != NULL;i++)
{
n=0;
for(j=b;*j !=NULL;j++)
{
if(strcmp(*i,*j)== 0)
{
n = 1;
break;
}
}
if(n == 0)
{
result[c-1] = malloc(strlen(*i) * sizeof(char));
result[c-1] = strcpy(result[c-1],*i);
c++;
result = realloc(result,c * sizeof(char*));
}
}
return result;
}
char * agregar_mrt(char *minunit, char **palabra)
{
int i;
char *ei = "MU_TEST_SUITE", *ef = "}", *ptri,*ptrf;
ptri = minunit;
ptri = strstr(ptri,ei);
ptri = strstr(ptri,"{");
ptri += 1;
for(i= 0;i > -1;i++)
{
if(palabra[i] == NULL)
break;
ptri = agregar_mrt(ptri,palabra[i]);
}
return minunit;
}
FILE* escribir_archivo(const char *min);
{
FILE * archivo;
archivo = fopen("minunit", "wt");
if(archivo == NULL)
{
return 0;
}
else
{
while(fputc(*min,archivo) != EOF){}
}
fclose(archivo);
return archivo;
}
FILE* leer_archivo(char *cadena)
{
FILE * archivo;
int i = 0;
archivo = fopen("minunit", "r");
if(archivo == NULL)
{
return NULL;
}
else
{
while((cadena[i] = fgetc(archivo)) != EOF) {i++;}
}
fclose(archivo);
return archivo;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: erobert <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2013/12/17 17:38:45 by erobert #+# #+# */
/* Updated: 2015/02/23 13:12:39 by erobert ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include <termcap.h>
#include <curses.h>
#include <termios.h>
#include "ft_minishell1.h"
static void ft_backspaces_to_spaces(char *line)
{
int i;
i = 0;
while (line[i])
{
if (line[i++] == '\t')
line[i - 1] = ' ';
}
}
static void ft_command_line(char **line, char ***env)
{
t_cmd cmd;
char **tab;
while (*line)
{
tab = ft_strsplit(*line, ' ');
if (*tab && !ft_strcmp(tab[0], "exit"))
{
ft_mode(0);
exit(0);
}
else if (!ft_strcmp(tab[0], "cd"))
ft_cd(tab, *env);
else
ft_exec(1, &cmd, *line, env);
line++;
}
}
static int ft_init(void)
{
char *term;
if ((term = getenv("TERM")) == NULL)
{
ft_putstr_fd("Error: terminal\n", 2);
return (-1);
}
if (tgetent(0, term) != 1)
{
ft_putstr_fd("Error: tgetent\n", 2);
return (-1);
}
return (0);
}
static int ft_read_line(int fd, char **line)
{
char *str;
char *tmp;
char buf[2];
str = malloc(sizeof(*str));
str[0] = '\0';
buf[0] = '\0';
buf[1] = '\0';
while (*buf != '\n')
{
read(fd, buf, 1);
write(1, buf, 1);
tmp = str;
str = ft_strjoin(str, buf);
free(tmp);
}
str[ft_strlen(str) - 1] = '\0';
*line = str;
return (1);
}
int main(void)
{
char *line;
char **tab;
char **env;
env = ft_cpyenv();
if (ft_init())
return (-1);
ft_mode(1);
ft_putprompt(env);
while (ft_read_line(0, &line))
{
ft_backspaces_to_spaces(line);
tab = ft_strsplit(line, ';');
ft_command_line(tab, &env);
ft_putprompt(env);
}
return (0);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include "md4.h"
#include "ed2k.h"
#include <sys/stat.h>
long get_filesize(char *FileName)
{
struct stat file;
if(!stat(FileName,&file))return file.st_size;
return 0;
}
int main(int argc, char *argv[])
{
int i;
uchar o1[16],o2[32];
FILE *f;
long size;
if (argc > 1)
for (i = 1; i < argc; i++)
{
f = fopen (argv[i], "rb");
if(f!=NULL){
size = get_filesize(argv[i]);
//printf("%d\n",size);
//CreateMD4FromFile(f, size, o1);
CreateHashFromFile(f, size, o1);
Encode(o2,o1);
//cout<<o2<<endl;
printf("%s",o2);
fclose(f);
}
printf("\n");
}
//system("PAUSE");
return EXIT_SUCCESS;
}
|
C | #ifndef _SINGLETON_H_
#define _SINGLETON_H_
#define DECLARE_SINGLETON(theClass) \
public: \
static theClass *Instance() \
{ \
static theClass *m_pInstance = 0; \
if (0 == m_pInstance) \
{ \
static theClass inst;\
m_pInstance = &inst; \
} \
return m_pInstance; \
} \
private: \
theClass(theClass const &); \
theClass &operator =(theClass &); \
#endif
|
C | //
// Sim3D2DConverter.c
// chenSDLtest1
//
// Created by Chen Sokolovsky on 7/7/16.
// Copyright © 2016 chen. All rights reserved.
//
/*
LICENSE
5dv - Five Dimensional Vision - File/Stream protocol, Encoder & Decoder
@copywrite Chen Sokolovsky 2012-2017
This software is not open source. You may not use it commenrically, distribute
or sublicense it without authorization. You may not upload it to any public or private server or
cloud service without authorization. You may not send it via email or LAN without authorization.
You may download it, read the code, modify it and run it for personal use only,
on a local machine. If you wish to share it with others you may share a link
to this repository.
The software is provided without warranty of any kind. In no event shall the
authors or copyright holders be liable for any claim, damages or other
liability.
*/
#include <stdio.h>
#import "Sim3D2DConverter.h"
void initDrawingWithShape ( struct drawing* d, struct zShape* shape) {
d->totalLines = shape->totalLines;
d->lines = (line*)malloc (sizeof(line) * d->totalLines);
}
// rotates a single point on a single axis
void rotate (float x, float y, float ang, float* resX, float * resY) {
// rotate the x axis
float xDist = sqrtf(x * x + y * y);
float add = 0;
if (x < 0) add = M_PI;
if (x > 0 && y < 0) add = 2 * M_PI;
float ang1 = atan(y / x);
ang1 += ang + add;
*resX = xDist * cos (ang1);
*resY = xDist * sin (ang1);
}
// converts a 3d point into 2 d according to 3 rotation angles
void convertPoint(float x1, float y1, float z1,float xAng,float yAng, float zAng,float* xRes, float* yRes) {
int debug = 0;
if (debug) printf("************************\n");
if (debug) printf("input point : %.0f, %.0f , %.0f\n",x1,y1,z1);
float radXAng = M_PI * xAng / 180.0;
float radYAng = M_PI * yAng / 180.0;
float radZAng = M_PI * zAng / 180.0;
// rotate the x axis
float z2,y2;
rotate(z1, y1, radXAng, &z2, &y2);
if (debug) printf("after rotating x by %.0f degrees point is: %.0f, %.0f, %.0f\n" ,xAng,x1,y2,z2);
float x3,z3;
rotate(x1,z2,radYAng,&x3,&z3);
if (debug) printf("after rotating y by %.0f degrees point is: %.0f, %.0f, %.0f\n", yAng, x3, y2, z3);
float x4,y4;
rotate(x3, y2, radZAng, &x4, &y4);
if (debug) printf("after rotating %.0f final point is: %.0f, %.0f\n",zAng,x4,y4);
*xRes = x4;
*yRes = y4;
}
void convertPoints (struct zPoint* zp, SDL_Point* p, float xAng, float yAng, float zAng) {
float resX;
float resY;
convertPoint(zp->x, zp->y, zp->z, xAng, yAng, zAng,&resX, &resY);
p->x = resX;
p->y = resY;
}
void convertTV(TVSize size,SDL_Point* pts,float totalPixels, float xAng, float yAng, float zAng) {
int i=0;
for (int tvh = 0; tvh < size.height; tvh++) {
for (int tvw=0; tvw< size.depth; tvw++) {
for (int tvd = 0; tvd < size.width; tvd++) {
SDL_Point* twodpoint = &(pts[i]);
zPoint threedpoint;
threedpoint.x = tvw;
threedpoint.y = tvh;
threedpoint.z = tvd;
convertPoints(&threedpoint, twodpoint, xAng, yAng, zAng);
i++;
}
}
}
}
void convertDrawing(struct zShape* shape, struct drawing* drawing, float xAng, float yAng, float zAng) {
for (int i = 0; i < shape->totalLines; i++) {
struct zLine shapeLine = (shape->zLines)[i];
line* drawingLine = &((drawing->lines)[i]);
// from point
convertPoint(shapeLine.x1,shapeLine.y1,shapeLine.z1,xAng,yAng,zAng,&(drawingLine->x1), &(drawingLine->y1));
// to point
convertPoint(shapeLine.x2,shapeLine.y2,shapeLine.z2,xAng,yAng,zAng,&(drawingLine->x2), &(drawingLine->y2));
}
}
|
C | #include<stdio.h>
int power_1(int a,int b);
void main(){
power_1(5,5);
}
int power_1(int base,int n){
int p;
for(p=1;n>0;--n){
p = p*base;
}
printf("%d\n",p);
} |
C | #include "common.h"
#include "graph.h"
#include "list.h"
void
help (char *cmd);
int
da (ugraph_struct *graph);
int
main (int argc, char **argv)
{
int opt;
unsigned int nodenr = 0, linknr = 0;
ugraph_struct g;
char name[32];
if (argc <= 1) {
help (argv[0]);
exit (-1);
}
while ((opt = getopt (argc, argv, "N:n:l:h")) != -1) {
switch (opt) {
case 'N':
strcpy (name, optarg);
break;
case 'n':
nodenr = atoi (optarg);
break;
case 'l':
linknr = atoi (optarg);
break;
case 'h':
default:
help (argv[0]);
exit (-1);
}
}
g.nodenr = nodenr;
g.linknr = linknr;
strcpy (g.name, name);
load_ugraph (&g);
da (&g);
delete_ugraph (&g);
return 0;
}
void
help (char *cmd)
{
fprintf (stderr, "usage:\n");
fprintf (stderr, "\t%s -N <name> -n <nodenr> -l <linknr>\n", cmd);
return;
}
int
da (ugraph_struct *graph)
{
int i = -1, j = -1;
unsigned int *links = NULL;
unsigned long du, dv, jiki = 0, jipluski = 0, ji2pluski2 = 0;
unsigned int linknr = 0;
long double r = 0.0, tmp = 0.0, numerator = 0.0, denominator = 0.0;
for (i = 0; i < graph->nodenr; ++i) {
du = graph->nodes[i].lknr;
links = get_ulinks (graph, i + 1);
for (j = 0; j < du; ++j) {
if (links[j] < i + 1) {
continue;
}
++linknr;
dv = graph->nodes[links[j] - 1].lknr;
jiki += (du * dv);
jipluski += (du + dv);
ji2pluski2 += (du * du + dv * dv);
}
}
tmp = (long double)jipluski / (2.0 * (long double)linknr);
tmp *= tmp;
numerator = ((long double)jiki / (long double)linknr) - tmp;
denominator = ((long double)ji2pluski2 / (2.0 * (long double)linknr)) - tmp;
r = numerator / denominator;
fprintf (stdout, "r = %0.9Lf, linknr = %u\n", r, linknr);
return 0;
}
|
C | #include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<locale.h>
int main(){
setlocale(LC_ALL,"");
float vetorA [20];
float vetorB [20];
int i, j;
for ( i = 0; i < 20; i++) {
printf ("\nDigite os valores do vetor: ");
scanf ("%f", &vetorA [i]);
}
for ( i = 19; i >= 0; i--) {
if ( i == 19 ){
printf ("Vetor B\n");
}
vetorB[i] = vetorA[i];
printf ("%.2f\n", vetorB[i]);
printf ("\n");
}
for ( i = 0; i <= 19; i++) {
if ( i == 0 ){
printf ("Vetor A\n");
}
printf ("%.2f\n", vetorA[i]);
printf ("\n");
}
return 0;
}
|
C | // rank 6
#include <std.h>
inherit "/d/magic/mon/naturesally/natureally.c";
void create()
{
::create();
set_id(({"natures ally","elephant","lumbering elephant"}));
set_short("%^BOLD%^%^BLACK%^hu%^RESET%^l%^BOLD%^%^BLACK%^ki%^RESET%^n%^BOLD%^%^BLACK%^g %^RESET%^el%^BOLD%^%^BLACK%^e%^RESET%^pha%^BOLD%^%^BLACK%^n%^RESET%^t%^RESET%^");
set_long("%^BOLD%^%^BLACK%^Standing thirteen feet tall, this "
"elephant casts a wide shadow. Its head features a long "
"trunk offset by two %^RESET%^%^BOLD%^tusks%^BOLD%^%^BLACK%^ "
"that look sharp enough to skewer a human. Wide ears spread "
"to either side of the elephant's head, fanning lightly when "
"the elephant is standing still and pinning back against its "
"head when it is angered. The beast's thick frame and sheer "
"mass make it a formidable foe in battle.%^RESET%^");
set_race("elephant");
set_body_type("quadruped");
set_fake_limbs(({"head","torso","right front leg","right rear leg","left front leg","left rear leg","right tusk","left tusk" }));
set_attack_limbs(({"head","right tusk","left tusk"}));
set_base_damage_type("piercing");
}
void my_special(object target)
{
if(!objectp(target)) return;
tell_object(target,"%^RESET%^%^RED%^The elephant trumpets its rage before charging you with its tusks!%^RESET%^");
tell_room(ETO,"%^RESET%^%^RED%^The elephant trumpets its rage before charging "+target->QCN+" with its tusks!%^RESET%^",target);
TO->set_property("magic",1);
target->do_damage("torso",random(60)+mylevel);
TO->remove_property("magic");
} |
C | // UNSUPPORTED: armv6m-target-arch
// RUN: %clang_builtins %s %librt -o %t && %run %t
// REQUIRES: librt_has_bswapsi2
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
extern uint32_t __bswapsi2(uint32_t);
int test__bswapsi2(uint32_t a, uint32_t expected) {
uint32_t actual = __bswapsi2(a);
if (actual != expected)
printf("error in test__bswapsi2(0x%0X) = 0x%0X, expected 0x%0X\n", a,
actual, expected);
return actual != expected;
}
int main() {
if (test__bswapsi2(0x12345678, 0x78563412))
return 1;
if (test__bswapsi2(0x00000001, 0x01000000))
return 1;
return 0;
}
|
C | //给定一个存放整数的数组,重新对数组排序使得数组的左边为奇数,右边为偶数,要求空间复杂度为O(1)。
//void sort(int* arr, int len);
//有快排的影子
#include <stdio.h>
#include <string.h>
void sort(int* arr, int len) {
int l = 0, r = len - 1;
while (l < r) {
int t = arr[l];
while (l < r && arr[r] % 2 == 0) r--;
arr[l] = arr[r];
while (l < r && arr[l] % 2 == 1) l++;
arr[r] = arr[l];
arr[l] = t;
}
}
int main() {
int a[] = { 1,2,3,4,5,6,7,8,9 };
int i,len = sizeof(a) / sizeof(9);
sort(a, len);
for(i=0;i<len;i++)
printf("%d ", a[i]);
return 0;
}
|
C | /*
* @lc app=leetcode id=62 lang=c
*
* [62] Unique Paths
*/
// @lc code=start
// Solution 2: DP
int uniquePaths(int m, int n)
{
int dp[m + 1][n + 1];
memset(dp, 0, (m + 1) * (n + 1) * sizeof(int));
dp[0][1] = 1;
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
return dp[m][n];
}
// @lc code=end
// Note: DP
// Solution 1:
// int uniquePaths(int m, int n)
// {
// long ans = 1;
// for (int i = 1; i <= n - 1; ++i)
// ans = ans * (m - 1 + i) / i;
// return ans;
// } |
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_LIMIT 256
void* reader() {
char *str;
char aux[BUFFER_LIMIT];
printf("Enter a string : ");
fgets(aux, BUFFER_LIMIT, stdin);
printf("You entered: %s", aux);
str = malloc(sizeof(char) * strlen(aux));
strcpy(str, aux);
return str;
}
void mark_and_replace(char token, char replaced_by, char *str) {
int token_count = 0;
int str_length = strlen(str);
int i = 0;
for ( ; i < str_length ; i++) {
if ( str[i] == token ) {
token_count++;
str[i] = replaced_by;
}
}
if (token_count > 0) {
printf("Yeahh, we find %i a, checkout the new string: %s\n", token_count, str );
} else {
printf("Ow no, we find %i a\n", token_count );
}
}
int main(int argc, char const *argv[]) {
char *str_1 = reader();
mark_and_replace('a', 'b', str_1);
free(str_1);
return 0;
}
|
C | #include "nn.h"
void fc(int m, int n, const float *x, const float *A, const float *b, float *y) {
int i,j,k;
k = 0;
for(i=0; i<m; i++) {
float z = 0;
for(j=0; j<n; j++) {
z += *(A+j+k) * *(x+j);
}
*(y+i) = z + *(b+i);
k += n;
}
}
void relu(int n, const float *x, float *y) {
int i;
for(i=0; i<n; i++) {
if (*(x+i)>0) {
*(y+i) = *(x+i);
} else if (*(x+i)<=0) {
*(y+i) = 0;
}
}
}
void softmax(int n, const float *x, float *y) {
int i,z=0;
float max = *x;
for (i=1; i<n; i++) {
if (max <= *(x+i)) {
max = *(x+i);
}
}
for(i=0; i<n; i++) {
z += exp(*(x+i)+max);
}
for(i=0; i<n; i++) {
*(y+i) = (exp(*(x+i)+max)) / z;
}
}
void print(int m, int n, const float *y) {
int i,j,k;
k = 0;
for(i=0; i<m; i++) {
for(j=0; j<n; j++) {
printf("%.4f ", *(y+j+k));
}
printf("\n");
k += n;
}
}
int inference3(float *y) {
float max = *y;
int i,num = 0;
for (i=1; i<10; i++) {
if (max < *(y+i)) {
num = i;
}
}
return num;
}
void softmaxwithloss_bwd(int n, const float *y, unsigned char t, float *dx) {
int i;
for(i=0;i<n;i++){
*(dx+i) = *(y+i) - t;
}
}
void relu_bwd(int n, const float *x, const float *dy, float *dx) {
int i;
for(i=0;i<n;i++)
if (*(x+i)>0) {
*(dx+i) = *(dy+i);
} else if (*(x+i)<=0) {
*(dx+i) = 0;
}
}
void fc_bwd(int n, int m, const float *x, const float *dy, const float * A, float *dA, float *db, float *dx) {
int i,j;
float B[10][784];
for (i=0;i<10;i++) {
for (j=0;j<784;j++) {
B[i][j] = A[784*i+j];
}
}
for (i=0;i<n;i++) {
float z = 0;
for (j=0;j<m;j++) {
// *(*(A+i)+j) = *(*(A+j)+i); //Aを転置
B[i][j] = B[j][i]; //転置行列
z += B[i][j] * x[j];
}
*(dx+i) = z + *(db+i);
} // dx = A(T) × dy
for (i=0;i<m;i++) {
for (j=0;j<n;j++) {
*(dA+i*n+j) = *(dy+i) * *(x+j);
} // dA = dy・x(T)
*(db+i) = *(dy+i); // db = dy
}
}
int main() {
float * train_x = NULL;
unsigned char * train_y = NULL;
int train_count = -1;
float * test_x = NULL;
unsigned char * test_y = NULL;
int test_count = -1;
int width = -1;
int height = -1;
load_mnist(&train_x, &train_y, &train_count,
&test_x, &test_y, &test_count,
&width, &height);
float *y = malloc(sizeof(float)*10);
//計算(1)(2)(4)
fc(10, 784, train_x, A_784x10, b_784x10, y);
relu(10, y, y);
softmax(10, y, y);
print(1, 10, y);
//推論(3層)
int ans = inference3(y);
printf("%d %d\n", ans, train_y[0]);
//正解率(3層)
int i,sum = 0;
for(i=0; i<test_count; i++) {
if(ans == test_y[i]) {
sum++;
}
}
printf("%f%%\n", sum * 100.0 / test_count);
//------------
softmaxwithloss_bwd(10, y, ans, y);
relu_bwd(10, y, y, y);
print(1, 10, y);
// fc_bwd(10, 784, train_x, A_784x10, b_784x10, y)
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jkangas <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/10 14:08:35 by jkangas #+# #+# */
/* Updated: 2021/06/10 16:44:11 by jkangas ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_lib.h"
#include <fcntl.h>
#include <unistd.h>
#define DIR {ft_putstr_err(argv[1]); ft_putstr(" Is a directory.\n"); return ;}
#define NONE {ft_putstr_err("No such file or directory found.\n"); return ;}
void ft_display_file(int argc, char **argv)
{
int file;
if (argc == 2)
{
if (ft_strcmp(argv[1], ".") == 0 || ft_strcmp(argv[1], "/") == 0
|| ft_strcmp(argv[1], "..") == 0 || ft_strcmp(argv[1], "./") == 0
|| ft_strcmp(argv[1], "../") == 0)
DIR;
file = open(argv[1], O_RDONLY);
if (file == -1)
NONE;
ft_print_file(file);
close(file);
}
if (argc > 2)
ft_putstr_err("Too many arguments.\n");
if (argc < 2)
ft_putstr_err("File name missing.\n");
}
int main(int argc, char **argv)
{
ft_display_file(argc, argv);
return (0);
}
|
C | /* ========================================
*
* Copyright YOUR COMPANY, THE YEAR
* All Rights Reserved
* UNPUBLISHED, LICENSED SOFTWARE.
*
* CONFIDENTIAL AND PROPRIETARY INFORMATION
* WHICH IS THE PROPERTY OF your company.
*
* ========================================
*/
#include "project.h"
#include "USBCom.h"
#include "SerialCom.h"
//USBFS Defines
#define USBFS_DEVICE (0u)
/* Active endpoints of USB device. */
#define IN_EP_NUM (1u)
#define OUT_EP_NUM (2u)
/* Size of SRAM buffer to store endpoint data. */
#define BUFFER_SIZE (64u)
/* There are no specific requirements to the buffer size and alignment for
* the 8-bit APIs usage.
*/
char buffer[BUFFER_SIZE];
uint8_t USBConfigured = 0;
/**
* @function USBCom_Init(void)
* @param None
* @return None
* @brief Initializes
* @author Barron Wong 01/31/19
*/
void USBCom_Init(void){
/* Start USBFS operation with 5V operation. */
USBFS_Start(USBFS_DEVICE, USBFS_5V_OPERATION);
/* Wait until device is enumerated by host. */
while(USBFS_GetConfiguration() == 0){}
/* Enable OUT endpoint to receive data from host. */
USBFS_EnableOutEP(OUT_EP_NUM);
}
/**
* @function USBCom_CheckConfiguration(void)
* @param None
* @return None
* @brief Checks to see if configuration has changed. If it has it
* will reenable the output endpoint. Used by USBCom_Init()
* and USBCom_CheckRecievedData()
* @author Barron Wong 01/31/19
*/
void USBCom_CheckConfiguration(void){
/* Check if configuration is changed. */
if (0u != USBFS_IsConfigurationChanged())
{
/* Re-enable endpoint when device is configured. */
if (0u != USBFS_GetConfiguration())
{
/* Enable OUT endpoint to receive data from host. */
USBFS_EnableOutEP(OUT_EP_NUM);
}
}
}
/**
* @function USBCom_CheckConfiguration(void)
* @param None
* @return None
* @brief Must Call USBCom_Init() before using. Checks to see if configuration has changed. If it has it
* will reenable the output endpoint
* @author Barron Wong 01/31/19
*/
int USBCom_CheckReceivedData(char * buffer){
uint16 length = 0;
if(USBFS_GetConfiguration() != 0){
USBCom_CheckConfiguration();
for(uint i = 0; i < BUFFER_SIZE; i++)
buffer[i] = 0;
/* Check if data was received. */
if (USBFS_OUT_BUFFER_FULL == USBFS_GetEPState(OUT_EP_NUM)){
/* Read number of received data bytes. */
length = USBFS_GetEPCount(OUT_EP_NUM);
/* Trigger DMA to copy data from OUT endpoint buffer. */
USBFS_ReadOutEP(OUT_EP_NUM,(uint8*) buffer, length);
/* Wait until DMA completes copying data from OUT endpoint buffer. */
while (USBFS_OUT_BUFFER_FULL == USBFS_GetEPState(OUT_EP_NUM)){
}
}
/* Enable OUT endpoint to receive data from host. */
USBFS_EnableOutEP(OUT_EP_NUM);
if(length == 0){
buffer = NULL;
}
}
return length;
}
/**
* @function USBCom_SendData(void)
* @param None
* @return None
* @brief Must Call USBCom_Init() before using. Checks to see if configuration has changed. If it has it
* will reenable the output endpoint
* @author Barron Wong 01/31/19
*/
void USBCom_SendData(char * msg){
int length = 0;
/* Wait until IN buffer becomes empty (host has read data). */
while (USBFS_IN_BUFFER_EMPTY != USBFS_GetEPState(IN_EP_NUM))
{
}
/* Trigger DMA to copy data into IN endpoint buffer.
* After data has been copied, IN endpoint is ready to be read by the
* host.
*/
length = strlen(msg);
USBFS_LoadInEP(IN_EP_NUM,(uint8*) msg, length);
}
#ifdef USBCOM_TEST
/*******************************************************************************
* File Name: main.c
*
* Version: 3.0
*
* Description:
* This example project demonstrates how to establish communication between
* the PC and Vendor-Specific USB device. The device has two endpoints:
* BULK IN and BULK OUT. The OUT endpoint allows the host to write data into
* the device and the IN endpoint allows the host to read data from the device.
* The data received in the OUT endpoint is looped back to the IN endpoint.
*
********************************************************************************
* Copyright 2015, Cypress Semiconductor Corporation. All rights reserved.
* This software is owned by Cypress Semiconductor Corporation and is protected
* by and subject to worldwide patent and copyright laws and treaties.
* Therefore, you may use this software only as provided in the license agreement
* accompanying the software package from which you obtained this software.
* CYPRESS AND ITS SUPPLIERS MAKE NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* WITH REGARD TO THIS SOFTWARE, INCLUDING, BUT NOT LIMITED TO, NONINFRINGEMENT,
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*******************************************************************************/
#include <project.h>
#include <SerialCom.h>
/*******************************************************************************
* Function Name: main
********************************************************************************
*
* Summary:
* The main function performs the following actions:
* 1. Starts the USBFS component.
* 2. Waits until the device is enumerated by the host.
* 3. Enables the OUT endpoint to start communication with the host.
* 4. Waits for OUT data coming from the host and sends it back on a
* subsequent IN request.
*
* Parameters:
* None.
*
* Return:
* None.
*
*******************************************************************************/
int main()
{
CyGlobalIntEnable;
USBCom_Init();
SerialCom_Init();
uint16 length = 0;
for(;;)
{
USBCom_CheckConfiguration();
length = USBCom_CheckRecievedData(buffer);
if(length > 0)
printf("%s", buffer);
USBCom_SendData("Hello Bitch ass trick");
}
}
#endif
/* [] END OF FILE */
|
C | /*
* Olexandr Matveyev
* Programm 1, CSCI 112
* 2/14/2017
*/
//Including derectivs
#include <stdio.h>
#include <math.h>
#include <float.h>
//Declaration of the functions
int is_valid(int);
int get_input(void);
void print_pattern(int);
//The definition of functions
int
main(void)
{
//Declaration of the variables
//===========================================================//
int isValid = 0;
int num = 0;
//===========================================================//
//===========================================================//
while(isValid == 0)
{
printf("Enter an odd number less than or equal to 9 and greater than 0 > ");
num = get_input();
isValid = is_valid(num);
}
//===========================================================//
print_pattern(num);
return(0);
}
//Check if entered number is valid
int is_valid(int num)
{
//Declaration of the variables
//===========================================================//
int isValid = 0;
//===========================================================//
//===========================================================//
if(num < 1)
{
printf("You have entered a number less than 1. Please try again.\n");
isValid = 0;
}
else if(num > 9)
{
printf("You have entered a number greater than 9. Please try again.\n");
isValid = 0;
}
else
{
if(num % 2 == 0)
{
printf("You have entered an even number. Please try again.\n");
isValid = 0;
}
else
{
printf("You have entered an odd number.\n");
isValid = 1;
}
}
//===========================================================//
return isValid;
}
//Get user input
int get_input(void)
{
//Declaration of the variables
//===========================================================//
int tmp = 0;
//===========================================================//
//===========================================================//
scanf("%d", &tmp);
//===========================================================//
return tmp;
}
//Display result
void print_pattern(int num)
{
//Declaration of the variables
//===========================================================//
int tmp = num;
int i = 0, j = 0;
//===========================================================//
//Printing top and bottom part
//===========================================================//
for(i = 1; i <= num; i++)
{
//Printing top part
//===========================================================//
if(i % 2 != 0)
{
int x = 1;
printf("%*s", (num - i), " ");
while(x <= i)
{
printf("%d ", x);
x++;
}
printf("\n");
}
//===========================================================//
//Printing bottom part
//===========================================================//
if(i == num)
{
for(j = (num - 2); j >= 1; j--)
{
if(j % 2 != 0)
{
int y = 1;
printf("%*s", (j - num), " ");
while(y <= j)
{
//printf("You entered %*s", num, " ");
printf("%d ", y);
y++;
}
printf("\n");
}
}
}
//===========================================================//
}
//===========================================================//
} |
C | /* The request reply BLE packet structure for the Eir watch app. This uses the
* watch_service for the transport mechanism. Well formed packets consist are
* 1 to 20 bytes inclusive in length. A well formed packet will always begin
* with a byte containing the PACKET_TYPE in the bits 0-6 and bit 7 as a flag
* indicating when set that this packet is the last of the transmission
* sequence. The next byte is the data length byte. The remaining bytes are the
* data bytes.
*
* Data buffer (20 bytes)
* +------------------------+-------------+-----------+
* | Byte 0 | Byte 1 | Byte 2-19 |
* +------------------------+-------------+-----------+
* | bit 7: terminal packet | data length | data |
* | bits 0-6: packet type | | |
* +------------------------+-------------+-----------+
*/
#ifndef PACKETS_H
#define PACKETS_H
#include <stdint.h>
#include <stdbool.h>
#define PACKET_BUF_LEN 20
#define PACKET_TYPE_INVALID 0x00
#define PACKET_TYPE_REQUEST_PED_STEP_COUNT 0x01
#define PACKET_TYPE_REQUEST_GPS_DATA 0x02
#define PACKET_TYPE_REQUEST_GPS_LOG 0x03
#define PACKET_TYPE_REQUEST_BATTERY_LEVEL 0x04
#define PACKET_TYPE_REQUEST_HEART_RATE 0x05
#define PACKET_TYPE_REPLY_PED_STEP_COUNT 0x01
#define PACKET_TYPE_REPLY_GPS_LATITUDE 0x02
#define PACKET_TYPE_REPLY_GPS_LONGITUDE 0x03
#define PACKET_TYPE_REPLY_GPS_SPEED 0x04
#define PACKET_TYPE_REPLY_GPS_LOG 0x05
#define PACKET_TYPE_REPLY_BATTERY_LEVEL 0x06
#define PACKET_TYPE_REPLY_HEART_RATE 0x07
/**
* Decode the type of a request packet.
*
* packet -- a buffer containing the request packet.
* len -- the length of the buffer.
*
* Returns the type of the request packet.
*/
extern uint8_t packets_decode_request_packet(
uint8_t packet[PACKET_BUF_LEN],
uint8_t len);
/**
* Encode data into a request packet.
*
* packet -- a buffer that will store the encoded packet.
* data -- a buffer holding the data to be encoded.
* data_len -- then length of the data buffer.
* terminal_packet -- is this the last packet in the transmission sequence?
*
* Returns true if the data was of valid length. Returns false otherwise.
*/
extern bool packets_build_reply_packet(
uint8_t packet[PACKET_BUF_LEN],
uint8_t type,
void * data,
uint8_t data_len,
bool terminal_packet);
#endif
|
C |
#include <stdio.h>
int main ( void )
{
int matrixA[4][5] = {
{1, 2, 3, 4, 5 },
{6, 7, 8, 9, 10},
{11,12,13,14,15},
{16,17,18,19,20},
};
int matrixB[5][4];
void transposeMatrix (int matrixA[][5], int matrixB[][4]);
void displayMatrix (int matrixB[][4]);
transposeMatrix ( matrixA, matrixB);
displayMatrix ( matrixB);
return 0;
}
void transposeMatrix ( int matrixA[][5], int matrixB[][4] )
{
int row, col;
for ( row = 0; row < 4; row++){
for ( col = 0; col < 5; col++)
matrixB[col][row] = matrixA[row][col];
}
}
void displayMatrix ( int matrixB[][4] )
{
int row, col;
for ( row = 0; row < 5; row++) {
for ( col = 0; col < 4; col++)
printf ( "%5i", matrixB[row][col] );
printf ( "\n" );
}
}
|
C | #include "_bpt.h"
// Delete
page_t * remove_entry_from_node(int table_id, page_t * page, int64_t key) {
int i;
int num_pointers;
// Remove the pointer and shift other pointers accordingly.
// First determine number of pointers.
num_pointers = page->is_leaf ? page->num_keys : page->num_keys + 1;
i = 0;
// Case.(leaf or internal)
if (page->is_leaf) {
leaf_page * page_leaf;
page_leaf = (leaf_page *)calloc(1, sizeof(leaf_page));
buf_get_page(table_id, page->offset, (page_t *)page_leaf);
while (page_leaf->pointers[i].key != key)
i++;
for (++i; i<page_leaf->num_keys; i++) {
page_leaf->pointers[i - 1] = page_leaf->pointers[i];
}
// Delete last one.
page_leaf->pointers[page->num_keys - 1] = make_record(0, "");
// One key fewer.
page_leaf->num_keys--;
page->num_keys--;
// Write in on-disk.
buf_put_page(table_id, page->offset, (page_t *)page_leaf);
free(page_leaf);
}
else {
in_page * page_internal;
page_internal = (in_page *)calloc(1, sizeof(in_page));
buf_get_page(table_id, page->offset, (page_t *)page_internal);
while (page_internal->keys[i] != key)
i++;
for (++i; i<page_internal->num_keys; i++) {
page_internal->keys[i - 1] = page_internal->keys[i];
page_internal->offsets[i] = page_internal->offsets[i + 1];
}
// Delete last one.
page_internal->keys[page->num_keys - 1] = 0;
page_internal->offsets[page->num_keys] = 0;
// One key fewer.
page_internal->num_keys--;
page->num_keys--;
// Write in on-disk;
buf_put_page(table_id, page->offset, (page_t *)page_internal);
free(page_internal);
}
return page;
}
page_t * adjust_root(int table_id) {
leaf_page * new_root;
// Case: nonempty root.
if (root[table_id]->num_keys > 0)
return (page_t *)root[table_id];
// Allocate memory to new_root
new_root = (leaf_page *)calloc(1, sizeof(leaf_page));
// Case: empty root.
// Case: it has a child(only child)
if (!root[table_id]->is_leaf) {
buf_get_page(table_id, root[table_id]->offsets[0], (page_t *)new_root);
new_root->parent_offset = 0;
buf_free_page(table_id, root[table_id]->offset);
root[table_id] = (in_page *)new_root;
header[table_id]->root_offset = root[table_id]->offset;
}
// Case: it is a leaf(no child)
else {
free(new_root);
buf_free_page(table_id, root[table_id]->offset);
root[table_id] = NULL;
header[table_id]->root_offset = 0;
}
// Write in on-disk page.
buf_put_page(table_id, root[table_id]->offset, (page_t *)root[table_id]);
buf_put_page(table_id, header[table_id]->offset, (page_t *)header[table_id]);
return (page_t *)new_root;
}
int get_neighbor_index(int table_id, page_t * page) {
int i;
in_page * parent;
// Allocate memory to parent.
parent = (in_page *)calloc(1, sizeof(in_page));
buf_get_page(table_id, page->parent_offset, (page_t *)parent);
// Return the index if the key to the left of the pointer in the parent pointing to page.
// If page is the leftmost child, this means return -1.
int p = 0;
int q = parent->num_keys;
i = (p + q) / 2;
while (page->offset != parent->offsets[i]) {
if (page->offset < parent->offsets[i]) {
q = i;
}
else {
p = i + 1;
}
i = (p + q) / 2;
}
return i - 1;
}
page_t * merge_nodes(int table_id, page_t * page, page_t * neighbor, int neighbor_index, int64_t k_prime) {
int i;
page_t * tmp;
in_page * parent;
int64_t new_k_prime;
// Allocate memory to parent.
parent = (in_page *)calloc(1, sizeof(in_page));
buf_get_page(table_id, page->parent_offset, (page_t *)parent);
// Suppose that page->num_keys == 0(right node is empty), by delaying merge.
// Swap neighbor with page if page is on the extreme left and neighbor is to its right.
// neighbor page means leaf side page.
if (neighbor_index == -1) {
tmp = page;
page = neighbor;
neighbor = tmp;
}
if (!neighbor->is_leaf) {
in_page * tmp_page;
in_page * tmp_neighbor;
page_t * tmp_child;
tmp_page = (in_page *)calloc(1, sizeof(in_page));
tmp_neighbor = (in_page *)calloc(1, sizeof(in_page));
tmp_child = (page_t *)calloc(1, sizeof(page_t));
buf_get_page(table_id, page->offset, (page_t *)tmp_page);
buf_get_page(table_id, neighbor->offset, (page_t *)tmp_neighbor);
// Appends k_prime and following pointer.
tmp_neighbor->keys[tmp_neighbor->num_keys] = k_prime;
tmp_neighbor->num_keys++;
int split = cut(tmp_page->num_keys + tmp_neighbor->num_keys);
// Shift tmp_page's keys and offsets to neighbor(left <- right)
for (int i = 0; i < split && tmp_page->keys[0] != 0; i++) {
// Move the key and pointer from page to neighbor.
tmp_neighbor->keys[tmp_neighbor->num_keys] = tmp_page->keys[i];
tmp_neighbor->offsets[tmp_neighbor->num_keys + 1] = tmp_page->offsets[i];
tmp_neighbor->num_keys++;
// Shift the key and pointer and remove the last one in page.
tmp_page->keys[i] = tmp_page->keys[i + 1];
tmp_page->offsets[i] = tmp_page->offsets[i + 1];
tmp_page->keys[tmp_page->num_keys - 1] = 0;
tmp_page->offsets[tmp_page->num_keys] = 0;
tmp_page->num_keys--;
}
tmp_neighbor->offsets[tmp_neighbor->num_keys + 1] = tmp_page->offsets[tmp_page->num_keys];
new_k_prime = tmp_page->keys[0];
// Change tmp_page's offsets's parent
for (int i = 0; i <= tmp_neighbor->num_keys; i++) {
buf_get_page(table_id, tmp_neighbor->offsets[i], (page_t *)tmp_child);
tmp_child->parent_offset = tmp_neighbor->offset;
buf_put_page(table_id, tmp_child->offset, (page_t *)tmp_child);
}
buf_put_page(table_id, neighbor->offset, (page_t *)tmp_neighbor);
buf_put_page(table_id, page->offset, (page_t *)tmp_page);
free(tmp_page);
free(tmp_neighbor);
free(tmp_child);
}
else {
leaf_page * tmp_page;
leaf_page * tmp_neighbor;
tmp_page = (leaf_page *)calloc(1, sizeof(leaf_page));
tmp_neighbor = (leaf_page *)calloc(1, sizeof(leaf_page));
buf_get_page(table_id, page->offset, (page_t *)tmp_page);
buf_get_page(table_id, neighbor->offset, (page_t *)tmp_neighbor);
int split = cut(tmp_page->num_keys + tmp_neighbor->num_keys);
// Shift tmp_page's keys and offsets to neighbor(left <- right)
for (int i = 0; i < split && tmp_page->num_keys != 0; i++) {
if(tmp_neighbor->num_keys == 0) {
// Move the key and pointer from page to neighbor.
tmp_neighbor->pointers[tmp_neighbor->num_keys] = tmp_page->pointers[i];
tmp_neighbor->num_keys++;
// Shift the key and pointer and remove the last one in page.
tmp_page->pointers[i] = tmp_page->pointers[i + 1];
tmp_page->pointers[tmp_page->num_keys - 1] = make_record(0,"");
tmp_page->num_keys--;
}
else {
// Move the key and pointer from page to neighbor.
tmp_page->pointers[i] = tmp_neighbor->pointers[tmp_neighbor->num_keys - 1];
tmp_page->num_keys++;
// Remove the last one in page.
tmp_neighbor->pointers[tmp_page->num_keys - 1] = make_record(0, "");
tmp_neighbor->num_keys--;
}
}
new_k_prime = tmp_page->pointers[0].key;
if(tmp_page->num_keys == 0) {
tmp_neighbor->next_offset = tmp_page->next_offset;
}
buf_put_page(table_id, neighbor->offset, (page_t *)tmp_neighbor);
buf_put_page(table_id, page->offset, (page_t *)tmp_page);
free(tmp_page);
free(tmp_neighbor);
}
// If page's num_keys is 0 free an on-disk page to the free page list.
buf_get_page(table_id, page->offset, (page_t *)page);
if(page->num_keys == 0) {
buf_free_page(table_id, page->offset);
// Write in on-disk page.
buf_put_page(table_id, header[table_id]->offset, (page_t *)header[table_id]);
return delete_entry(table_id, (page_t *)parent, k_prime);
}
// Else the page remains and the keys of parent were changed.
else {
return replace_entry(table_id, (page_t *)parent, new_k_prime);
}
}
page_t * delete_entry(int table_id, page_t * page, int64_t key) {
page_t * neighbor;
in_page * parent;
int neighbor_index;
int64_t k_prime;
int k_prime_index;
page = remove_entry_from_node(table_id, page, key);
// Case: deletion from the root.
if (page->offset == root[table_id]->offset)
return adjust_root(table_id);
// Case: deletion from a node below the root.
// Delayed merge.
// Until num_keys == 0, no merge operation.
if (page->num_keys == 0) {
// Allocate memory to parent, neighbor.
parent = (in_page *)calloc(1, sizeof(in_page));
neighbor = (page_t *)calloc(1, sizeof(page_t));
neighbor_index = get_neighbor_index(table_id, (page_t *)page);
k_prime_index = neighbor_index == -1 ? 0 : neighbor_index;
// Read page.
buf_get_page(table_id, page->parent_offset, (page_t *)parent);
k_prime = parent->keys[k_prime_index];
neighbor->offset = neighbor_index == -1 ? parent->offsets[1] : parent->offsets[neighbor_index];
buf_get_page(table_id, neighbor->offset, neighbor);
return merge_nodes(table_id, page, neighbor, neighbor_index, k_prime);
}
return (page_t *)root[table_id];
}
page_t * replace_entry(int table_id, page_t * page, int64_t new_k_prime) {
int i;
int num_pointers;
in_page * tmp_parent;
tmp_parent = (in_page *)calloc(1, sizeof(in_page));
buf_get_page(table_id, page->offset, (page_t *)tmp_parent);
i = 0;
// Find proper index to replace with new_k_prime.
while(tmp_parent->keys[i] < new_k_prime) {
i++;
}
// Change the value of the key.
tmp_parent->keys[i - 1] = new_k_prime;
// Write on disk-page.
buf_put_page(table_id, page->offset, (page_t *)tmp_parent);
return page;
}
int delete(int table_id, int64_t key) {
leaf_page * key_leaf;
char * key_value;
// Find key's record and page.
key_leaf = find_leaf(table_id, key);
key_value = find(table_id, key);
// Case: The key exist.
if (key_value != NULL && key_leaf != NULL) {
delete_entry(table_id, (page_t *)key_leaf, key);
return 0;
}
// Case: The key not exist.
else {
printf("There is no %" PRId64 "in tree\n", key);
return -1;
}
}
void destroy_tree(int table_id, in_page * root) {
int i;
if (root->is_leaf) {
for (i = 0; i<root->num_keys; i++) {
buf_free_page(table_id, root->offsets[i]);
}
}
else {
in_page * c;
for (i = 0; i<root->num_keys; i++) {
buf_get_page(table_id, root->offsets[i], (page_t *)c);
destroy_tree(table_id, c);
}
}
free(root->offsets);
free(root->keys);
free(root);
} |
C | #include "toplista.h"
#include "egyeb.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*! @file toplista.c
* \brief A toplista betltst s szerkesztst ler fggvnyeket tartlmaz modul.
*
*/
/**
* Fjlbl betlti a lementett toplistt.
* Ha nem tallja, akkor ltrehozza.
* Ha nem tudja megynitni a fjlt, vagy az rvnytelen, kilp a kilep() fggvnnyel.
* @param tl Dinamikus tmb, amibe betlti az eredmnyeket.
* @param meretek A Szintek mreteit s tmbjt tartalmaz struktra
*/
void toplista_betolt(Toplista *tl, Szintek meretek) {
FILE *fp = fopen("toplista.fs", "r");
if (fp == NULL) {
FILE *fp2 = fopen("toplista.fs", "w");
if (fp2 == NULL) {
kilep(10, "rvnytelen toplista fjl!", meretek);
}
fprintf(fp2, "%d\n", 0);
fclose(fp2);
fp = fopen("toplista.fs", "r");
}
if(fscanf(fp, "%d", &(tl->meret)) != 1) {
fclose(fp);
kilep(11, "rvnytelen toplista fjl!", meretek);
} else {
fgetc(fp);
tl->hs = (Eredmeny *) malloc(tl->meret * sizeof(Eredmeny));
if (tl->hs == NULL) {
fclose(fp);
kilep(2, "", meretek);
}
for (int i = 0; i < tl->meret; i++) {
if (fscanf(fp, "%d %d", &(tl->hs[i].hely), &(tl->hs[i].pont)) != 2) {
free(tl->hs);
fclose(fp);
kilep(12, "rvnytelen toplista fjl!", meretek);
} else {
fgetc(fp);
fgets((tl->hs[i].nev), 51, fp);
strtok(tl->hs[i].nev, "\n");
}
}
}
fclose(fp);
}
/**
* Megllaptja egy j eredmnyrl, hogy az felkerl-e a toplistra. Ha igen, bekri a felhasznltl a nevt,
* s meghvja az eredmeny_felvesz() fggvnyt, majd az j toplistt fjlba rja a toplista_fajlba() fggvnnyel.
* @param tl Dinamikus tmb
* @param pont Az j eredmny pontszma
* @param meretek A Szintek mreteit s tmbjt tartalmaz struktra
*/
void uj_eredmeny(Toplista *tl, int pont, Szintek meretek) {
int helyezes = tl->meret;
for (int i = 0; i < tl->meret; i++) {
if (pont >= tl->hs[i].pont) {
helyezes = i;
break;
}
}
if (helyezes < 10) {
printf("Gratullok, felkerltl a toplistra! Krlek, add meg a neved (max 50 karkter)!\n");
char name[51];
fgets(name, 51, stdin);
if (strlen(name) == 50) {
scanf("%*[^\n]");
}
strtok(name, "\n");
Eredmeny new;
new.hely = helyezes;
new.pont = pont;
strcpy(new.nev, name);
eredmeny_felvesz(tl, new, meretek);
toplista_fajlba(*tl);
}
else {
printf("Szp munka, de a toplistra sajnos nem kerltl fel.\n");
}
}
/**
* Egy eredmnyt berak a dinamikus tmbbe. Ha szksges, meg is nyjtja a tmbt (egybknt az utols eredmnyt eldobja).
* Habr a dinamius tmb megnyjtsa hossz mvelet is lehetne, itt maximum 9 elem tmbt kell msolni, ami nem problma a mai gpeknek.
* @param tl Dinamikus tmb
* @param new Az eredmny, amit berak a tmbbe
* @param meretek A Szintek mreteit s tmbjt tartalmaz struktra
*/
static void eredmeny_felvesz(Toplista *tl, Eredmeny new, Szintek meretek) {
if (tl->meret < 10) {
Eredmeny *temp = (Eredmeny *) realloc(tl->hs, (tl->meret + 1) * sizeof(Eredmeny));
if (temp == NULL) {
free(tl->hs);
kilep(2, "", meretek);
}
tl->hs = temp;
tl->meret++;
}
if (tl->meret == 1) {
(tl->hs)[0] = new;
return;
}
for (int i = tl->meret - 1; i > new.hely; i--) {
(tl->hs)[i] = (tl->hs)[i - 1];
}
(tl->hs)[new.hely] = new;
for(int i = new.hely + 1; i < tl->meret; i++) {
if ((tl->hs)[i].pont < (tl->hs)[i - 1].pont) {
(tl->hs)[i].hely++;
} else {
(tl->hs)[i].hely = (tl->hs)[i - 1].hely;
}
}
}
/**
* Kinyomtatja a kpernyre az aktulis toplistt, majd felszabadtja a dinamikus tmbt.
* A toplista nyomtatsa utn mr sosincs szksgnk a toplistra, ezrt innen is fel lehet szabadtani.
* @param tl A toplista dinamikus tmbje
*/
void toplista_nyomtat(Toplista tl) {
printf("\nTOPLISTA\n");
if (tl.meret == 0) {
printf("Mg nincsenek eredmnyek!\n");
} else {
for (int i = 0; i < tl.meret; i++) {
printf("%d. %s: %d pont\n", tl.hs[i].hely + 1, tl.hs[i].nev, tl.hs[i].pont);
}
}
printf("\n");
free(tl.hs);
}
/**
* Fjlba rja az toplistt.
* @param tl A toplista dinamikus tmbje
*/
static void toplista_fajlba(Toplista tl) {
FILE *fp = fopen("toplista.fs", "w");
if (fp == NULL) {
printf("rvnytelen toplista fjl!\n");
} else {
fprintf(fp, "%d\n", tl.meret);
for (int i = 0; i < tl.meret; i++) {
fprintf(fp, "%d %d %s\n", tl.hs[i].hely, tl.hs[i].pont, tl.hs[i].nev);
}
}
fclose(fp);
}
|
C | #include <zlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "kseq.h"
#include "khash.h"
KSEQ_INIT(gzFile, gzread);
KHASH_SET_INIT_STR(s)
#define BUF_SIZE 2048
char *strstrip(char *s) // function for striping lines
{
size_t size;
char *end;
size = strlen(s);
if (!size)
return s;
end = s + size - 1;
while (end >= s && isspace(*end))
end--;
*(end + 1) = '\0';
while (*s && isspace(*s))
s++;
return s;
}
int writeSequence(char *idFile, char *fqFile, int mode){
//function for write fastq//
fprintf(stderr,"Reading file: %s\nFrom %s...\n" ,idFile,fqFile);
//declare variable
char buf[BUF_SIZE];
gzFile fp;
kseq_t *seq;
int lineno = 0, ret, l, seqCount = 0 ,flag;
char *id, *sequence, *qual, *comment;
// hashing id file
khint_t k;
khash_t(s) *h = kh_init(s);
fp = fopen(idFile, "rb");
while (fgets(buf, BUF_SIZE, fp)){
kh_put(s, h, strstrip(strdup(buf)), &ret);
}
fclose(fp);
//open fastq file
fp = gzopen(fqFile,"r"); // open fastq file for kseq parsing
seq = kseq_init(fp);
//================================================================
// filter id
while ((l = kseq_read(seq)) >= 0)
{
id = seq -> name.s;
comment = seq -> comment.s;
qual = seq -> qual.s;
sequence = seq -> seq.s;
flag = kh_get(s, h, id);
if (mode == 1 && flag == kh_end(h))
{
// print out seqeunce in fastq format
printf("@%s\t%s\n%s\n+\n%s\n", id,comment,sequence,qual);
seqCount ++;
}
else if (mode == 0 && flag < kh_end(h))
{
// print out seqeunce in fastq format
printf("@%s\t%s\n%s\n+\n%s\n", id,comment,sequence,qual);
seqCount ++;
}
}
fprintf(stderr,"Written %i sequences from %s.\n",seqCount,fqFile);
kh_destroy(s,h);
return 0;
}
// main function
int main(int argc, char **argv){
char *fqFile, *idFile;
int mode = 0;
int c;
if (argc == 1){
fprintf(stderr,"usage: filterFastq [options]\n\n"
"[options]\n"
"\t-q\t<fastq file>\n"
"\t-i\t<idFile>\n"
"\t-v\tinverted match (same as grep -v)\n");
return 1;
}
opterr = 0;
// print usage if not enough argumnets
while ((c = getopt(argc, argv, "vq:i:")) != -1){
switch (c){
case 'q':
fqFile = optarg;
break;
case 'i':
idFile = optarg;
break;
case 'v':
mode = 1;
break;
case '?':
if (optopt == 'q' || optopt == 'i'){
fprintf(stderr,"usage: filterFastq [options]\n\n"
"[options]\n"
"\t-q\t<fastq file>\n"
"\t-i\t<idFile>\n"
"\t-v\tinverted match (same as grep -v)\n");
}
else if (isprint (optopt)){
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
}
else {
fprintf(stderr,"usage: filterFastq [options]\n\n"
"[options]\n"
"\t-q\t<fastq file>\n"
"\t-i\t<idFile>\n"
"\t-v\tinverted match (same as grep -v)\n");
}
return 1;
default:
abort();
}
}
// pass variable to fnuction
writeSequence(idFile,fqFile,mode);
}
|
C | /********************* cp.c file ****************/
#include "ucode.c"
int main(int argc, char* argv[]) {
int fd, gd, n;
char buf[1024];
// 1. fd = open src for READ;
fd = open(argv[1], O_RDONLY);
if (fd < 0) {
printf("FAILED TO OPEN SRC\n");
exit(1);
}
// 2. gd = open dst for WR | CREAT;
gd = open(argv[2], O_WRONLY);
if (gd < 0) {
creat(argv[2]);
gd = open(argv[2], O_WRONLY);
}
while (n = read(fd, buf, 1024))
{
write(gd, buf, n);
}
printf("\n\r");
close(fd);
close(gd);
}
|
C | //
// Created by 王勇椿 on 2020/12/16.
//
/**
* (不正确地)使用select得到TCP带外数据通知的接收程序
* 不正确的地方:select一直指示一个异常条件,直到进程的读入越过带外数据。同一个带外数据不能读入多次,因为首次读入之后,内核就清空这个单字节的缓冲区。
* 再次指定MSG_OOB标志调用recv时,它就返回EINVAL
* 解决办法:读入普通数据后才select异常条件
*/
#include "../lib/unp.h"
#include <stdbool.h>
int
main(int argc, char *argv[]){
int listenfd, connfd;
char buf[100];
fd_set rset, xset;
if (argc == 2){
listenfd = Tcp_connect(NULL, argv[1], NULL);
} else if (argc == 3){
listenfd = Tcp_connect(argv[1], argv[2], NULL);
} else{
err_quit("usage: tcprecv02 [ <host> ] <port#>");
}
connfd = Accept(listenfd, NULL, NULL);
FD_ZERO(&rset);
FD_ZERO(&xset);
while (true){
FD_SET(connfd, &rset);
FD_SET(connfd, &xset);
Select(connfd + 1, &rset, NULL, &xset, NULL);
if (FD_ISSET(connfd, &xset)){
n = Recv(connfd, buf, sizeof(buf) - 1, MSG_OOB);
buf[n] = 0; //null terminated
printf("read %d OOB byte: %s\n", n, buf);
}
if (FD_ISSET(connfd, &rset)){
if ((n = Read(connfd, buf, sizeof(buf) - 1)) == 0){
printf("received EOF\n");
exit(0);
}
buf[n] = 0; //null terminated
printf("read %d bytes: %s\n", n, buf);
}
}
}
|
C | #ifndef _NEWRAPH_H
#define _NEWRAPH_H
#include <stdio.h>
#include "funcoes.h"
#define JMAX 4000000 /*definido o número máximo de iterações.*/
/* Função que através do método de Newton-Raphson
retorna a raíz da função desejada.
Recebe como parâmetros um valor chute de raiz e o erro
absoluto epsilon (erroAbs) */
float metodoNewRaph(float x1, float tolerancia, char opTolerancia) {
int j;
float dx, imagemAtual, xAtual, xProximo, delta;
xAtual = x1; //Valor inicial de chute
printf("\n");
for (j=1;j<=JMAX;j++) { //Início das iterações
imagemAtual = f(xAtual);
dx = (imagemAtual/fLinha(xAtual));
xProximo = xAtual - dx; //Calcula o próxima suposta raiz
delta = (xProximo - xAtual) / xProximo; //Calculo da tolerancia
printf("Para iteração %d temos x = %f | f(x) = %f | Tolerância = %f \n", j, xAtual, imagemAtual, fabs(delta));
if (fabs(dx)>10000){ //Se a divisao f(x)/f'(x), raiz não converge
printf("\nNão converge.\n");
return 0.0;
}
/* Define qual será condição de parada */
if(opTolerancia == 'e' || opTolerancia == 'E'){ //Se epsilon, usar a imagem do ponto atual
if (fabs(imagemAtual) < tolerancia)
return xAtual; //Retorna valor da raiz para uma dada tolerancia
}
else{ //Senão, tolerancia = (Xk+1 - Xk)/Xk+1
if(fabs(delta) < tolerancia)
return xAtual;
}
xAtual = xProximo; //Se condicao de parada não validada, o ponto calculado é inserido novamente na iteração
}
printf("\nNúmero de iterações excedeu o limite\n");
return 0.0; /* Nunca chegue aqui*/
}
#endif
|
C | /**
* @file main.c
* @brief Description
* @date 2018-1-1
* @author name of author
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include "debug.h"
#include "memory.h"
#include "args.h"
struct gengetopt_args_info args;
void trata_sinal_info(int signal, siginfo_t *siginfo, void *context);
int continua = 1;
int main(int argc, char *argv[]){
if(cmdline_parser(argc, argv, &args))
ERROR(1, "Erro: execução de cmdline_parser\n");
struct sigaction act_info;
act_info.sa_sigaction = trata_sinal_info;
sigemptyset(&act_info.sa_mask);
act_info.sa_flags = 0; //fidedigno
act_info.sa_flags |= SA_SIGINFO; //info adicional sobre o sinal
//act_info.sa_flags |= SA_RESTART; //recupera chamadas bloqueantes
printf("[INFO] Processing signal from [MIN:%d, MAX:%d]\n", args.min_arg, args.max_arg);
for(int i = args.min_arg; i<= args.max_arg; i++){
if(sigaction(i, &act_info, NULL) < 0)
printf("[WARNING] Can't install handler for signal '' (%d)\n",i);
}
printf("[INFO] Terminate: kill -s SIGKILL %d | kill -s SIGINT %d\n",getpid(),getpid());
while(continua){
pause();
}
cmdline_parser_free(&args);
return 0;
}
void trata_sinal_info(int signal, siginfo_t *siginfo, void *context)
{
(void)context;
/* Cópia da variável global errno */
int aux = errno;
printf("[PID:%d] Got signal '%s' (%d) from process '%ld'\n",getpid(),strsignal(signal),signal,(long)siginfo->si_pid);
if(signal == SIGINT){
printf("Got SIGINT -- terminating\n");
continua = 0;
}else{
printf("Waiting for a signal\n");
}
/* Restaura valor da variável global errno */
errno = aux;
}
|
C | #include<cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include "bmp.h"
int main(int argc, char* argv[])
{
if (argc != 3)
{
printf("Invalid input, please provide all data \n");
return 1;
}
FILE* clue_picture = fopen(argv[1], "r");
if (clue_picture == NULL)
{
printf("Sorry... I am not able to open the file \n");
return 1;
}
FILE* solution = fopen(argv[2], "w");
if (solution == NULL)
{
fclose(clue_picture);
printf("Sorry... I am not able to create the file \n");
return 1;
}
int fh_size = sizeof(BITMAPFILEHEADER);
int ih_size = sizeof(BITMAPINFOHEADER);
//fread(&data, size, number, inptr)
BITMAPFILEHEADER fh;
fread(&fh, fh_size, 1, clue_picture);
BITMAPINFOHEADER ih;
fread(&ih, ih_size, 1, clue_picture);
if ((ih.biSize != 40) || (ih.biCompression != 0) || (ih.biBitCount != 24) || (fh.bfOffBits != 54))
{
fclose(solution);
fclose(clue_picture);
printf("Invalid format \n");
}
//fwrite(&data, size, number, outputr);
fwrite(&fh, sizeof(BITMAPFILEHEADER), 1, solution);
fwrite(&ih, sizeof(BITMAPINFOHEADER), 1, solution);
//calculate padding
int padding = (4 - (ih.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;
for (int i = 0, biHeight = abs(ih.biHeight); i < biHeight; i++)
{
for (int j = 0; j < ih.biWidth; j++)
{
RGBTRIPLE triple;
fread(&triple, sizeof(RGBTRIPLE), 1, clue_picture);
if(triple.rgbtRed == 255 && triple.rgbtGreen == 0 && triple.rgbtBlue == 0)
triple.rgbtRed = 0;
if(triple.rgbtRed == 255 && triple.rgbtGreen == 255 && triple.rgbtBlue == 255)
{
triple.rgbtRed = 0;
triple.rgbtGreen = 255;
triple.rgbtBlue = 255;
}
if(triple.rgbtRed == 000 && triple.rgbtGreen == 000 && triple.rgbtBlue == 000)
{
triple.rgbtRed = 255;
triple.rgbtGreen = 255;
triple.rgbtBlue = 255;
}
fwrite(&triple, sizeof(RGBTRIPLE), 1, solution);
}
// fsee(inptr, amount, from)
fseek(clue_picture, padding, SEEK_CUR);
for (int k = 0; k < padding; k++)
{
fputc(0x00, solution);
}
}
fclose(clue_picture);
fclose(solution);
printf("Thank you for using my program, check out the solution file in your folder \n");
printf("%ld", sizeof(RGBTRIPLE));
return 0;
} |
C | #include "tools.h"
#include "tools.c"
//=============================================================================
#define MAXREAD "255"
#define MAXSIZE 256
char INPUT[MAXSIZE];
char OUTPUT[MAXSIZE];
char KEYWORD[MAXSIZE];
char REPLACE[MAXSIZE];
char HOLD[MAXSIZE];
//=============================================================================
//=============================================================================
void getInfo(void);
int ioFile(void);
int check(int x, cstream inputFile, cstream outputFile);
//=============================================================================
int main(void)
{
banner();
getInfo();
ioFile();
bye();
}
/*=============================================================================
Gets a user inputted input file, output file, keyword, and replacement word
=============================================================================*/
void getInfo(void)
{
printf("Input File: ");
scanf("%" MAXREAD "s", INPUT);
printf("Output File: ");
scanf("%" MAXREAD "s", OUTPUT);
printf("Keyword: ");
scanf("%" MAXREAD "s", KEYWORD);
printf("Replace: ");
scanf("%" MAXREAD "s", REPLACE);
}
/*=============================================================================
Reads input file and writes to output file, replacing keyword with replacement
============================================================================*/
int ioFile(void)
{
int x;
cstream inputFile = fopen(INPUT, "r");
cstream outputFile = fopen(OUTPUT, "w");
if(!inputFile) fatal("Cannot open file at %s", INPUT);
else if(!outputFile) fatal("Cannot open file at %s", OUTPUT);
else for(;;)
{
x = fgetc(inputFile);
if(x == EOF) break;
if(x == 0)
{
fatal("File Read Error");
return 0;
}
if(x == KEYWORD[0]) check(x, inputFile, outputFile);
else fprintf(outputFile, "%c", x);
}
fclose(inputFile);
fclose(outputFile);
return 0;
}
/*=============================================================================
Checks if the word matches the keyword. If so, word is replaces.
=============================================================================*/
int check(int x, cstream inputFile, cstream outputFile)
{
HOLD[0] = x;
for(int k = 1; k < strlen(KEYWORD); k++)
{
char m = fgetc(inputFile);
HOLD[k] = m;
}
if(!strcmp(KEYWORD, HOLD)) fprintf(outputFile, "%s", REPLACE);
else fprintf(outputFile, "%s", HOLD);
return 0;
}
|
C | // Problem:
// Given an array of n positive integers and a positive integer s, find the
// minimal length of a contiguous subarray of which the sum ≥ s. If there isn't
// one, return 0 instead.
//
// Example:
// Input: [2,3,1,2,4,3], s = 7
// Output: 2 ([4,3])
//
// Solution:
// Use a "sums" array where sums[i] = nums[0] + ... + nums[i - 1], and sums[0]
// is 0. The difference of any 2 numbers in the sums array represents the sum
// of a subarray in nums array. Use to pointers i and j running from forwardly
// on sums array, i is on the right of j. When sums[i] - sums[j] < s, increment
// i, otherwise increment j until sums[i] - sums[j] < s, then the current
// shortest subarray is found. Keep the length updated as i and j increment
// until i reaches the end.
#include <stdio.h>
int minSubArrayLen(int s, int* nums, int numsSize);
int main()
{
return 0;
}
/********** Solution **********/
int minSubArrayLen(int s, int* nums, int numsSize)
{
if (numsSize == 0)
return 0;
int sums[numsSize + 1], len, i, j;
for (sums[0] = 0, i = 0; i < numsSize; i++)
sums[i + 1] = sums[i] + nums[i];
// All numbers add up still not enough
if (sums[i] < s)
return 0;
// Initial length as the largest possible length
i = 1, j = 0, len = numsSize;
while (1) {
while (i < numsSize + 1 && sums[i] - sums[j] < s)
i++;
// Check boundary
if (i >= numsSize + 1)
break;
while (sums[i] - sums[j] >= s)
j++;
if (len > i - j + 1)
len = i - j + 1;
}
return len;
} |
C | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.c
* Author: Hp
*
* Created on Ngày 02 tháng 3 năm 2020, 19:11
*/
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
int checkPos(double x, double y, double r);
int main(int argc, char** argv) {
double x, y, r;
int result;
printf("Enter the x: ");
scanf("%lf", &x);
printf("Enter the y: ");
scanf("%lf", &y);
while (x == 0 && y == 0)
{
printf("The point given is the center of the circle !!!\n");
printf("Enter the x: ");
scanf("%lf", &x);
printf("Enter the y: ");
scanf("%lf", &y);
}
do
{
printf("Enter the radius r > 0: ");
scanf("%lf", &r);
} while (r <= 0);
result = checkPos(x, y, r);
if (result == 1)
{
printf("The point (%.2lf; %.2lf) is IN the circle whose center is O(0; 0) and radius is r = %.2lf", x, y, r);
}
else if (result == 0)
{
printf("The point (%.2lf; %.2lf) is ON the circle whose center is O(0; 0) and radius is r = %.2lf", x, y, r);
}
else
{
printf("The point (%.2lf; %.2lf) is OUT OF the circle whose center is O(0; 0) and radius is r = %.2lf", x, y, r);
}
return (EXIT_SUCCESS);
}
int checkPos(double x, double y, double r)
{
double d, rr;
d = x*x + y*y;
rr = r*r;
if (d < rr) {
return 1;
}
else if (d == rr) {
return 0;
}
else {
return -1;
}
} |
C | /*
* Universidade Federal do Rio de Janeiro
* Escola Politecnica
* Departamento de Eletronica e de Computacao
* EEL270 - Computacao II - Turma 2019/2
* Prof. Marcelo Luiz Drumond Lanza
*
* Autor: Luiz Fernando Loureiro Leitao
* Descricao: implementacao do programa de testes da funcao GerarPisPasep.
*
* $Author: luiz.leitao $
* $Date: 2019/10/03 05:33:51 $
* $Log: aula0610.c,v $
* Revision 1.1 2019/10/03 05:33:51 luiz.leitao
* Initial revision
*
*/
/* Inclusao dos arquivos de cabecalho da biblioteca padrao da linguagem. */
#include <stdio.h>
#include <stdlib.h>
/* Inclusao do arquivo de cabecalho personalizado para o trabalho. */
#include "aula0608.h"
/* Definicao da macro. */
#define NUMERO_DE_ARGUMENTOS 1
/* Implementacao do programa de testes. */
int
main(int argc, char **argv)
{
/* Utilizacao de variaveis locais dentro da funcao principal. */
char pisPasep[PIS_PASEP_COM_DIGITO_VERIFICADOR_SEM_HIFEN + 1];
unsigned indiceDigito;
tipoErros resultado;
/* Verificacao da quantidade de argumentos passados ao programa. */
/* Informacao da quantidade invalida de argumentos passados ao programa (Erro #1). */
if (argc != NUMERO_DE_ARGUMENTOS)
{
printf("\n\n\nErro #%i: quantidade de argumentos invalida.\n", NUMERO_DE_ARGUMENTOS_INVALIDO);
printf("Uso: %s \n\n\n\n", *argv);
exit(NUMERO_DE_ARGUMENTOS_INVALIDO); /* Programa abortado. */
} /* if */
/* Chamada da funcao GerarPisPasep. */
resultado = GerarPisPasep(pisPasep);
/* Verificacao da existencia de erro no retorno da funcao. */
/* Informacao da existencia de argumento nulo passado ao programa. (Erro #6) */
if (resultado == argumentoNulo)
{
printf("\n\n\nErro #%i: impossivel passar argumento nulo.\n", ARGUMENTO_NULO);
printf("Uso: %s\n\n\n\n", *argv);
exit(ARGUMENTO_NULO);
} /* if */
/* Exibicao do resultado na tela. */
printf("\n\n\nPisPasep: ");
for (indiceDigito = 0; indiceDigito < PIS_PASEP_SEM_DIGITO_VERIFICADOR; indiceDigito++)
printf("%u", pisPasep[indiceDigito]);
printf("-%c\n\n\n\n", pisPasep[PIS_PASEP_COM_DIGITO_VERIFICADOR_SEM_HIFEN - 1]);
return OK; /* Codigo retornado com sucesso. */
} /* main */
/* $RCSfile: aula0610.c,v $ */
|
C | #ifndef INDEX_IMPL_H
#define INDEX_IMPL_H
#include "DataStructures/linkedList.h"
#include "index.h"
struct indexNode;
struct Entry;
struct EntryList;
#ifdef __cplusplus
extern "C" {
#endif
struct EntryList {
LinkedList<Entry>* list;
Node<Entry> * current;
};
typedef struct EntryList EntryList;
struct Index {
indexNode* headNode;
MatchType type;
};
typedef struct Index Index;
#ifdef __cplusplus
}
#endif
struct indexNode{
Entry* vP;
EntryList* list;
indexNode* inRad;
indexNode* offRad;
int rad;
indexNode(){
vP=NULL;
list=NULL;
inRad=NULL;
offRad=NULL;
rad=-1;
}
~indexNode(){
if(vP!=NULL)
DestroyEntry(vP);
if(list!=NULL)
delete list;
if(inRad!=NULL)
delete inRad;
if(offRad!=NULL)
delete offRad;
}
};
#endif /* INDEX_IMPL_H */
|
C | /*
Source: https://github.com/miloyip/itoa-benchmark/blob/master/src/branchlut.cpp
License: https://github.com/miloyip/itoa-benchmark/blob/master/license.txt
Code is modified for benchmark.
*/
#if defined(__clang__)
# define clang_attribute __has_attribute
#else
# define clang_attribute(x) 0
#endif
#if !defined(force_inline)
# if clang_attribute(always_inline) || (defined(__GNUC__) && __GNUC__ >= 4)
# define force_inline __inline__ __attribute__((always_inline))
# elif defined(__clang__) || defined(__GNUC__)
# define force_inline __inline__
# elif defined(_MSC_VER) && _MSC_VER >= 1200
# define force_inline __forceinline
# elif defined(_MSC_VER)
# define force_inline __inline
# elif defined(__cplusplus) || (defined(__STDC__) && __STDC__ && \
defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L)
# define force_inline inline
# else
# define force_inline
# endif
#endif
#include <stdint.h>
static const char gDigitsLut[200] = {
'0','0','0','1','0','2','0','3','0','4','0','5','0','6','0','7','0','8','0','9',
'1','0','1','1','1','2','1','3','1','4','1','5','1','6','1','7','1','8','1','9',
'2','0','2','1','2','2','2','3','2','4','2','5','2','6','2','7','2','8','2','9',
'3','0','3','1','3','2','3','3','3','4','3','5','3','6','3','7','3','8','3','9',
'4','0','4','1','4','2','4','3','4','4','4','5','4','6','4','7','4','8','4','9',
'5','0','5','1','5','2','5','3','5','4','5','5','5','6','5','7','5','8','5','9',
'6','0','6','1','6','2','6','3','6','4','6','5','6','6','6','7','6','8','6','9',
'7','0','7','1','7','2','7','3','7','4','7','5','7','6','7','7','7','8','7','9',
'8','0','8','1','8','2','8','3','8','4','8','5','8','6','8','7','8','8','8','9',
'9','0','9','1','9','2','9','3','9','4','9','5','9','6','9','7','9','8','9','9'
};
#define BEGIN2(n) \
do { \
int t = (n); \
if(t < 10) *p++ = '0' + t; \
else { \
t *= 2; \
*p++ = gDigitsLut[t]; \
*p++ = gDigitsLut[t + 1]; \
} \
} while(0)
#define MIDDLE2(n) \
do { \
int t = (int)((n) * 2); \
*p++ = gDigitsLut[t]; \
*p++ = gDigitsLut[t + 1]; \
} while(0)
#define BEGIN4(n) \
do { \
int t4 = (int)(n); \
if(t4 < 100) BEGIN2(t4); \
else { BEGIN2(t4 / 100); MIDDLE2(t4 % 100); } \
} while(0)
#define MIDDLE4(n) \
do { \
int t4 = (int)(n); \
MIDDLE2(t4 / 100); MIDDLE2(t4 % 100); \
} while(0)
#define BEGIN8(n) \
do { \
uint32_t t8 = (uint32_t)(n); \
if(t8 < 10000) BEGIN4(t8); \
else { BEGIN4(t8 / 10000); MIDDLE4(t8 % 10000); } \
} while(0)
#define MIDDLE8(n) \
do { \
uint32_t t8 = (uint32_t)(n); \
MIDDLE4(t8 / 10000); MIDDLE4(t8 % 10000); \
} while(0)
#define MIDDLE16(n) \
do { \
uint64_t t16 = (n); \
MIDDLE8(t16 / 100000000); MIDDLE8(t16 % 100000000); \
} while(0)
static force_inline char *branchlut2(uint32_t x, char* p) {
if(x < 100000000) BEGIN8(x);
else { BEGIN2(x / 100000000); MIDDLE8(x % 100000000); }
// *p = 0;
return p;
}
char *itoa_u32_branchlut2(uint32_t x, char* p) {
return branchlut2(x, p);
}
char *itoa_i32_branchlut2(int32_t x, char* p) {
uint64_t t;
if(x >= 0) t = x;
else { *p++ = '-'; t = (uint32_t)-(int32_t)(x); }
return branchlut2((uint32_t)t, p);
}
static force_inline char *branchlut2_64(uint64_t x, char* p) {
if(x < 100000000) BEGIN8(x);
else if(x < 10000000000000000) { BEGIN8(x / 100000000); MIDDLE8(x % 100000000); }
else { BEGIN4(x / 10000000000000000); MIDDLE16(x % 10000000000000000); }
//*p = 0;
return p;
}
char *itoa_u64_branchlut2(uint64_t x, char* p) {
return branchlut2_64(x, p);
}
char *itoa_i64_branchlut2(int64_t x, char* p) {
uint64_t t;
if(x >= 0) t = x;
else { *p++ = '-'; t = (uint64_t)-(int64_t)(x); }
return branchlut2_64(t, p);
}
/* benckmark config */
int itoa_branchlut2_available_32 = 1;
int itoa_branchlut2_available_64 = 1;
|
C | /*
** name: mradius
**
** author: bjr
** created: 30 mar 2017
** last modified: 16 apr 2017
**
*/
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<netdb.h>
#include<assert.h>
#include<unistd.h>
#include<openssl/md5.h>
#include<openssl/sha.h>
#include "mradius.h"
int g_verbose = 0 ;
int g_debug = 0 ;
char* find_attribute(char* attributes, short attr, int rp_len) {
int offset = 0;
while(offset < rp_len - 24) {
if( attr == ntohs(*((short *)(attributes + offset)))) {
return strndup(attributes + offset + 4, *((short*)(attributes + offset + 2)));
}
offset += 4 + ntohs(*((short *)(attributes + offset + 2)));
}
if ( g_verbose ) printf("attribute (%d) not found\n", attr);
return NULL;
}
void encrypt_password(char dest[32], char* pw, char* ra, char* shared_key) {
MD5_CTX context;
char src[32];
int i;
memset(&src, 0, 32);
memcpy(src, pw, 20);
MD5_Init(&context);
MD5_Update(&context, shared_key, strlen(shared_key));
MD5_Update(&context, ra, MD5_DIGEST_LENGTH);
MD5_Final((unsigned char *)dest, &context);
for(i = 0; i < MD5_DIGEST_LENGTH; i++) {
dest[i] ^= src[i];
}
MD5_Init(&context);
MD5_Update(&context, shared_key, strlen(shared_key));
MD5_Update(&context, dest, MD5_DIGEST_LENGTH);
MD5_Final((unsigned char *)dest + 16, &context);
for(i = MD5_DIGEST_LENGTH; i < 2 * MD5_DIGEST_LENGTH; i++) {
dest[i] ^= src[i];
}
}
void decrypt_password(char dest[20], char* pw, char* ra, char* shared_key) {
MD5_CTX context;
char buf[32];
int i;
MD5_Init(&context);
MD5_Update(&context, shared_key, strlen(shared_key));
MD5_Update(&context, pw, MD5_DIGEST_LENGTH);
MD5_Final((unsigned char *)buf + 16, &context);
for(i = MD5_DIGEST_LENGTH; i < 2 * MD5_DIGEST_LENGTH; i++) {
buf[i] ^= pw[i];
}
MD5_Init(&context);
MD5_Update(&context, shared_key, strlen(shared_key));
MD5_Update(&context, ra, MD5_DIGEST_LENGTH);
MD5_Final((unsigned char *)buf, &context);
for(i = 0; i < MD5_DIGEST_LENGTH; i++) {
buf[i] ^= pw[i];
}
memcpy(dest, buf, SHA_DIGEST_LENGTH);
}
int main(int argc, char * argv[]) {
int ch ;
struct Params params ;
memset( ¶ms, 0, sizeof(struct Params)) ;
params.port = DEFAULT_PORT ;
params.shared_key = DEFAULT_SHARED_KEY ;
while ((ch = getopt(argc, argv, "vRWLk:p:h:D:n:")) != -1) {
switch(ch) {
case 'v':
g_verbose ++ ;
g_debug |= DEBUGFLAG_VERBOSE ;
break ;
case 'D':
g_debug |= atoi(optarg) ;
break ;
case 'R':
params.no_randomness ++ ;
g_debug |= DEBUGFLAG_NORANDOM ;
break ;
case 'L':
params.no_loop = 1 ;
break ;
case 'h':
params.host = strdup(optarg) ;
break ;
case 'p':
params.port = atoi(optarg) ;
break ;
case 'k':
params.shared_key = strdup(optarg) ;
break ;
case 'n':
params.is_hashchain = 1 ;
params.hashchain_len = atoi(optarg) ;
break ;
case 'W':
params.use_otp = 1 ;
break ;
case '?':
default:
printf("%s\n",USAGE_MESSAGE) ;
return 0 ;
}
}
argc -= optind;
argv += optind;
if ( (argc!=1 && !params.host ) || (argc!=2 && params.host ) ) {
fprintf(stderr,"%s\n",USAGE_MESSAGE) ;
exit(0) ;
}
if ( params.is_hashchain ) {
params.upass = strdup(argv[0]) ;
mradius_hashchain( ¶ms ) ;
}
else if ( !params.host ) {
params.pwfile = strdup(argv[0]) ;
mradius_server( ¶ms ) ;
}
else {
params.uname = strdup(argv[0]) ;
params.upass = strdup(argv[1]) ;
mradius_client( ¶ms ) ;
}
return 0 ;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* do_type.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jmaynard <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/07/12 19:11:01 by jmaynard #+# #+# */
/* Updated: 2019/07/25 09:20:40 by jmaynard ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_printf.h"
int ft_t1(char *fmt, t_flags *param)
{
int f;
f = 0;
if (*fmt == 'd' || *fmt == 'i' || *fmt == 'D')
{
if (*fmt == 'D')
{
free(param->size);
param->size = ft_strdup("l");
}
param->type = 0;
f = 1;
}
else if (*fmt == 'X')
{
param->type = 4;
f = 1;
}
else if (*fmt == 'x')
{
f = 1;
param->type = 3;
}
return (f);
}
int ft_t4(char *fmt, t_flags *param)
{
int f;
f = 0;
if (*fmt == 'o' || *fmt == 'O')
{
if (*fmt == 'O')
{
free(param->size);
param->size = ft_strdup("l");
}
param->type = 1;
f = 1;
}
else if (*fmt == 'c' || *fmt == 'C')
{
if (*fmt == 'C')
{
free(param->size);
param->size = ft_strdup("l");
}
param->type = 6;
f = 1;
}
return (f);
}
int ft_t2(char *fmt, t_flags *param)
{
int f;
f = 0;
if (*fmt == 'u' || *fmt == 'U')
{
if (*fmt == 'U')
{
free(param->size);
param->size = ft_strdup("l");
}
param->type = 2;
f = 1;
}
else if (*fmt == 'f')
{
if (param->pres == -1)
param->pres = 6;
param->type = 5;
f = 1;
}
return (f);
}
int ft_t3(char *fmt, t_flags *param)
{
int f;
f = 0;
if (*fmt == 's' || *fmt == 'S')
{
if (*fmt == 'S')
{
free(param->size);
param->size = ft_strdup("l");
}
param->type = 7;
f = 1;
}
else if (*fmt == 'p')
{
param->type = 8;
f = 1;
}
else if (*fmt == '%')
{
param->type = 10;
f = 1;
}
return (f);
}
char *ft_type(char *fmt, t_flags *param)
{
if (ft_t1(fmt, param))
return (fmt + 1);
else if (ft_t2(fmt, param))
return (fmt + 1);
else if (ft_t3(fmt, param))
return (fmt + 1);
else if (ft_t4(fmt, param))
return (fmt + 1);
return (fmt);
}
|
C | /*
* For license: see LICENSE file at top-level
*/
#include "collect.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "util/util.h"
#include "util/debug.h"
#define CSV
#include "util/run.h"
#define VERIFYx
#define PRINTx
#define WARMUP
#define EQUAL
typedef void (*collect_impl)(void *, const void *, size_t, int, int, int, long *);
static inline void shcoll_collect32_shmem(void *dest, const void *source, size_t nelems, int PE_start,
int logPE_stride, int PE_size, long *pSync) {
shmem_collect32(dest, source, nelems, PE_start, logPE_stride, PE_size, pSync);
}
#ifdef EQUAL
double test_collect32(collect_impl fcollect, int iterations, size_t nelem,
long SYNC_VALUE, size_t COLLECT_SYNC_SIZE) {
long *pSync = shmem_malloc(COLLECT_SYNC_SIZE * sizeof(long));
for (int i = 0; i < COLLECT_SYNC_SIZE; i++) {
pSync[i] = SYNC_VALUE;
}
shmem_barrier_all();
int npes = shmem_n_pes();
int me = shmem_my_pe();
size_t total_nelem = nelem * npes;
uint32_t *src = shmem_malloc(nelem * sizeof(uint32_t));
uint32_t *dst = shmem_malloc(total_nelem * sizeof(uint32_t));
for (int i = 0; i < nelem; i++) {
src[i] = (uint32_t) (total_nelem - me * nelem - i);
}
#ifdef WARMUP
shmem_barrier_all();
for (int i = 0; i < iterations / 10; i++) {
memset(dst, 0, total_nelem * sizeof(uint32_t));
shmem_barrier_all();
fcollect(dst, src, nelem, 0, 0, npes, pSync);
for (int j = 0; j < total_nelem; j++) {
if (total_nelem - j != dst[j]) {
gprintf("i:%d [%d] dst[%d] = %d; Expected %zu\n", i, shmem_my_pe(), j, dst[j], total_nelem - j);
abort();
}
}
}
#endif
shmem_barrier_all();
unsigned long long start = current_time_ns();
for (int i = 0; i < iterations; i++) {
#ifdef VERIFY
memset(dst, 0, total_nelem * sizeof(uint32_t));
#endif
shmem_sync_all();
fcollect(dst, src, nelem, 0, 0, npes, pSync);
#ifdef PRINT
for (int b = 0; b < npes; b++) {
shmem_barrier_all();
if (b != me) {
continue;
}
gprintf("%2d: %2d", shmem_my_pe(), dst[0]);
for (int j = 1; j < total_nelem; j++) { gprintf(", %2d", dst[j]); }
gprintf("\n");
if (me == npes - 1) {
gprintf("\n");
}
}
#endif
#ifdef VERIFY
for (int j = 0; j < total_nelem; j++) {
if (total_nelem - j != dst[j]) {
gprintf("i:%d [%d] dst[%d] = %d; Expected %zu\n", i, shmem_my_pe(), j, dst[j], total_nelem - j);
abort();
}
}
#endif
}
shmem_barrier_all();
unsigned long long end = current_time_ns();
shmem_free(pSync);
shmem_free(src);
shmem_free(dst);
return (end - start) / 1e9;
}
#else
double test_collect32(collect_impl collect, int iterations, size_t count, long SYNC_VALUE, size_t COLLECT_SYNC_SIZE) {
long *pSync = shmem_malloc(COLLECT_SYNC_SIZE * sizeof(long));
for (int i = 0; i < COLLECT_SYNC_SIZE; i++) {
pSync[i] = SYNC_VALUE;
}
shmem_barrier_all();
int npes = shmem_n_pes();
int me = shmem_my_pe();
size_t nelems = count * (me + 1);
size_t total_size = (size_t) (count * (1 + npes) * npes / 2);
uint32_t *dst = shmem_malloc(total_size * sizeof(uint32_t));
uint32_t *src = shmem_malloc(count * npes * sizeof(uint32_t));
for (int i = 0; i < nelems; i++) {
src[i] = (uint32_t) ((me + 1) * (i + 1));
}
shmem_barrier_all();
unsigned long long start = current_time_ns();
for (int i = 0; i < iterations; i++) {
#ifdef VERIFY
memcpy(dst, src, total_size * sizeof(uint32_t));
#endif
shmem_barrier_all();
collect(dst, src, nelems, 0, 0, npes, pSync);
#ifdef PRINT
for (int b = 0; b < npes; b++) {
shmem_barrier_all();
if (b != me) {
continue;
}
gprintf("%2d: %2d", shmem_my_pe(), dst[0]);
for (int j = 1; j < total_size; j++) { gprintf(", %2d", dst[j]); }
gprintf("\n");
}
#endif
#ifdef VERIFY
int j = 0;
for (int p = 0; p < npes; p++) {
for (int k = 0; k < (p + 1) * count; k++, j++) {
if (dst[j] != (p + 1) * (k + 1)) {
gprintf("[%d] dst[%d] = %d; Expected %d\n", shmem_my_pe(), j, dst[j], (p + 1) * (k + 1));
abort();
}
}
}
#endif
}
shmem_barrier_all();
unsigned long long end = current_time_ns();
shmem_free(pSync);
shmem_free(src);
shmem_free(dst);
return (end - start) / 1e9;
}
#endif
int main(int argc, char *argv[]) {
int iterations;
size_t count;
time_ns_t start = current_time_ns();
shmem_init();
time_ns_t end = current_time_ns();
int me = shmem_my_pe();
int npes = shmem_n_pes();
if (me == 0) {
#ifdef CSV
gprintf("shmem_init: %lf\n", (end - start) / 1e9);
#else
gprintf("PEs: %d\n", npes);
#endif
}
// @formatter:off
for (int i = 1; i < argc; i++) {
sscanf(argv[i], "%d:%zu", &iterations, &count);
RUN(collect32, shmem, iterations, count, SHMEM_SYNC_VALUE, SHMEM_COLLECT_SYNC_SIZE);
RUNC(count >= 256, collect32, ring, iterations, count, SHCOLL_SYNC_VALUE, SHCOLL_COLLECT_SYNC_SIZE);
RUNC(!((npes - 1) & npes), collect32, rec_dbl, iterations, count, SHCOLL_SYNC_VALUE, SHCOLL_COLLECT_SYNC_SIZE);
RUNC(!((npes - 1) & npes), collect32, rec_dbl_signal, iterations, count, SHCOLL_SYNC_VALUE, SHCOLL_COLLECT_SYNC_SIZE);
RUN(collect32, bruck, iterations, count, SHCOLL_SYNC_VALUE, SHCOLL_COLLECT_SYNC_SIZE);
RUN(collect32, bruck_no_rotate, iterations, count, SHCOLL_SYNC_VALUE, SHCOLL_COLLECT_SYNC_SIZE);
RUNC(npes <= 16, collect32, linear, iterations, count, SHCOLL_SYNC_VALUE, SHCOLL_COLLECT_SYNC_SIZE);
RUN(collect32, all_linear, iterations, count, SHCOLL_SYNC_VALUE, SHCOLL_COLLECT_SYNC_SIZE);
RUN(collect32, all_linear1, iterations, count, SHCOLL_SYNC_VALUE, SHCOLL_COLLECT_SYNC_SIZE);
if (me == 0) {
#ifdef CSV
gprintf("\n\n\n\n");
#else
gprintf("\n");
#endif
}
}
// @formatter:on
shmem_finalize();
} |
C | #include <stdio.h>
int to_upper(int character)
{
return character -= 32;
} |
C | #include <stdio.h>
main () {
int Num, Nums, rest;
printf("Insert an odd number \n");
Nums = -1;
rest = 0;
do {
scanf("%d", &Num);
rest = Num % 2;
Nums++;
}
while (rest == 0);
printf("You insert %d even numbers.", Nums);
return 0;
}
|
C | /*************************************************************************
> File Name: read大数据.c
> Author:
> Mail:
> Created Time: Wed 26 Apr 2017 09:30:54 PM PDT
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//定义文件最大有MAX_SIZE,每行字符串的最大长度MAX_LEN;
#define MAX_SIZE 10000
#define MAX_LEN 1000
#include<time.h>
int main()
{
FILE *fp;
int i = 0, len = 0;
char buf[MAX_LEN];
char *arr[MAX_SIZE];
int start = clock();
if(!(fp = fopen("/home/lyzgit/JSKquestions/testcount", "r")))
{
printf("打开失败!");
}
while(fgets(buf, MAX_LEN, fp))
{
len = strlen(buf);
arr[i] = (char *)malloc(len + 1);
if(!arr)
{
break;
}
strcpy(arr[i ++], buf);
}
fclose(fp);
i--;
while(i >= 0&& arr[i])
{
printf("%s\n", arr[i]);
free(arr[i--]);
}
}
|
C | /* Software systems mini project : Railway ticket booking system
*
*/
#include<stdio.h>
#include<fcntl.h>
#include <stdlib.h>
#include<unistd.h>
#include<string.h>
#include "../include/dataStructs.h"
#include "../include/admin.h"
#include "../include/normal.h"
/* Modules of admin */
int loginVerify(struct login user){
int accType = user.accType;
int uid = user.uid;
int pin = user.pin;
char* filename = "credentials.txt";
int fd;
int rec;
struct flock fl;
struct credentials crd;
fd = open(filename,O_RDONLY);
fl.l_type = F_RDLCK;
fl.l_whence = SEEK_SET;
fl.l_start = sizeof(struct credentials)*(uid-1);
fl.l_len = sizeof(struct credentials);
fl.l_pid = getpid();
if(fcntl(fd,F_SETLKW,&fl) == -1)
return 0;
// printf("Lock acquired\n");
lseek(fd,sizeof(struct credentials)*(uid-1),SEEK_SET);
if(read(fd,&crd,sizeof(crd)) != sizeof(crd)){
// printf("No Data Found\n");
return 0;
}
printf("Uid : %d\n",crd.uid);
printf("Pin : %d\n",crd.pin);
printf("AccType : %d\n",crd.accType);
fl.l_type = F_UNLCK;
fcntl(fd,F_SETLKW,&fl);
//printf("Lock released\n");
if(crd.uid == uid && crd.pin==pin && crd.accType==accType)
return 1;
else
return 0;
}
int addNewCredentials(struct credentials cred){
char* filename = "credentials.txt";
int fd;
struct flock fl;
int uid = cred.uid;
struct credentials c = {cred.uid,cred.pin,cred.accType};
fd = open(filename,O_CREAT|O_WRONLY,0777);
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = sizeof(struct credentials)*(uid-1);
fl.l_len = sizeof(struct credentials);
fl.l_pid = getpid();
//printf("Before Critical section\n");
if(fcntl(fd,F_SETLKW,&fl) == -1)
return 0;
//printf("Lock acquired\n");
lseek(fd,sizeof(struct credentials)*(uid-1),SEEK_SET);
if(write(fd,&c,sizeof(c)) != sizeof(c)){
printf("write error\n");
return 0;
}
fl.l_type = F_UNLCK;
fcntl(fd,F_SETLKW,&fl);
//printf("Lock released\n");
return 1;
}
int addNewAccount(struct account acc){
char* filename = "accounts.txt";
int fd;
struct flock fl;
int uid = acc.uid;
fd = open(filename,O_CREAT|O_WRONLY,0777);
//printf("fd2 = %d\n",fd);
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = sizeof(struct account)*(uid-1);
fl.l_len = sizeof(struct account);
fl.l_pid = getpid();
//printf("Before Critical section\n");
if(fcntl(fd,F_SETLKW,&fl) == -1)
return 0;
//printf("Lock acquired\n");
lseek(fd,sizeof(struct account)*(uid-1),SEEK_SET);
if(write(fd,&acc,sizeof(acc)) != sizeof(acc)){
printf("write error\n");
return 0;
}
fl.l_type = F_UNLCK;
fcntl(fd,F_SETLKW,&fl);
//printf("Lock released\n");
return 1;
}
int deleteAccount(int uid){
char* filename = "accounts.txt";
char* filename2 = "credentials.txt";
int fd;
int fd2;
struct flock fl;
struct flock fl2;
struct account acc;
struct account invalidData;
struct credentials invalidCred;
invalidData.uid = -1;
strcpy(invalidData.name,"invalid guy");
printf("uid: %d\n",uid);
invalidCred.uid = -1;
if(!searchAccount(&acc,uid)){
return 0;
}
fd = open(filename,O_WRONLY,0777);
fd2 = open(filename2,O_WRONLY,0777);
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = sizeof(struct account)*(uid-1);
fl.l_len = sizeof(struct account);
fl.l_pid = getpid();
//printf("Before Critical section\n");
if(fcntl(fd,F_SETLKW,&fl) == -1)
return 0;
fl2.l_type = F_WRLCK;
fl2.l_whence = SEEK_SET;
fl2.l_pid = getpid();
fl2.l_start = sizeof(struct credentials)*(uid-1);
fl2.l_len = sizeof(struct credentials);
if(fcntl(fd2,F_SETLKW,&fl2) == -1)
return 0;
//printf("Lock acquired\n");
lseek(fd,sizeof(struct account)*(uid-1),SEEK_SET);
if(write(fd,&invalidData,sizeof(struct account)) != sizeof(struct account)){
printf("write error\n");
return 0;
}
lseek(fd2,sizeof(struct credentials)*(uid-1),SEEK_SET);
if(write(fd2,&invalidCred,sizeof(struct credentials)) != sizeof(struct credentials)){
printf("write error\n");
return 0;
}
fl.l_type = F_UNLCK;
fcntl(fd,F_SETLKW,&fl);
fl2.l_type = F_UNLCK;
fcntl(fd2,F_SETLKW,&fl2);
/* cancel all previous booking */
for(int i=0;i<acc.totalBookings;i++){
if(!cancelTrainSeat(&acc.booked[i])){
printf("cancelling all failed\n");
return 0;
}
}
//printf("Lock released\n");
return 1;
}
int searchAccount(struct account *acc,int uid){
char* filename = "accounts.txt";
int fd;
struct flock fl;
fd = open(filename,O_RDONLY,0777);
//printf("fd = %d\n",fd);
fl.l_type = F_RDLCK;
fl.l_whence = SEEK_SET;
fl.l_start = sizeof(struct account)*(uid-1);
fl.l_len = sizeof(struct account);
fl.l_pid = getpid();
//printf("Before Critical section\n");
if(fcntl(fd,F_SETLKW,&fl) == -1){
return 0;
}
//printf("Lock acquired\n");
lseek(fd,sizeof(struct account)*(uid-1),SEEK_SET);
if(read(fd,acc,sizeof(struct account)) != sizeof(struct account)){
printf("Read error\n");
return 0;
}
fl.l_type = F_UNLCK;
fcntl(fd,F_SETLKW,&fl);
if((*acc).uid!=uid){
return 0;
}
printf("Account Found\n");
printf("Uid : %d\nName : %s\n",(*acc).uid,(*acc).name);
switch((*acc).accType){
case 1:
printf("Account type : ADMIN\n");
break;
case 2:
printf("Account type : AGENT\n");
break;
case 3:
printf("Account type : NORMAL\n");
break;
}
return 1;
}
int modifyAccount(struct account *acc,int uid)
{
char* filename = "accounts.txt";
char *creden = "credentials.txt";
int fd;
struct flock fl;
struct account oldAcc;
struct credentials c;
fd = open(filename,O_RDWR,0777);
//printf("fd = %d\n",fd);
fl.l_type = F_RDLCK;
fl.l_whence = SEEK_SET;
fl.l_start = sizeof(struct account)*(uid-1);
fl.l_len = sizeof(struct account);
fl.l_pid = getpid();
printf("Before Critical section\n");
if(fcntl(fd,F_SETLKW,&fl) == -1){
return 0;
}
printf("Lock acquired\n");
lseek(fd,sizeof(struct account)*(uid-1),SEEK_SET);
if(read(fd,&oldAcc,sizeof(struct account)) != sizeof(struct account)){
printf("Read error\n");
return 0;
}
fl.l_type = F_UNLCK;
fcntl(fd,F_SETLKW,&fl);
if(oldAcc.uid!=uid){
return 0;
}
printf("Read Account");
for(int i=0;i<20;i++)
oldAcc.name[i] = acc->name[i];
oldAcc.accType = acc->accType;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = sizeof(struct account)*(uid-1);
fl.l_len = sizeof(struct account);
fl.l_pid = getpid();
printf("Before Critical section\n");
if(fcntl(fd,F_SETLKW,&fl) == -1){
return 0;
}
printf("Lock acquired\n");
lseek(fd,sizeof(struct account)*(uid-1),SEEK_SET);
if(write(fd,&oldAcc,sizeof(struct account)) != sizeof(struct account)){
printf("write error\n");
return 0;
}
fl.l_type = F_UNLCK;
fcntl(fd,F_SETLKW,&fl);
/* modify account type in credentials file */
fd = open(creden,O_RDWR,0777);
fl.l_type = F_RDLCK;
fl.l_whence = SEEK_SET;
fl.l_start = sizeof(struct credentials)*(uid-1);
fl.l_len = sizeof(struct credentials);
fl.l_pid = getpid();
//printf("Before Critical section\n");
if(fcntl(fd,F_SETLKW,&fl) == -1)
return 0;
//printf("Lock acquired\n");
lseek(fd,sizeof(struct credentials)*(uid-1),SEEK_SET);
if(read(fd,&c,sizeof(c)) != sizeof(c)){
printf("read error\n");
return 0;
}
c.accType = acc->accType;
fl.l_type = F_UNLCK;
fcntl(fd,F_SETLKW,&fl);
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = sizeof(struct credentials)*(uid-1);
fl.l_len = sizeof(struct credentials);
fl.l_pid = getpid();
//printf("Before Critical section\n");
if(fcntl(fd,F_SETLKW,&fl) == -1)
return 0;
//printf("Lock acquired\n");
lseek(fd,sizeof(struct credentials)*(uid-1),SEEK_SET);
if(write(fd,&c,sizeof(c)) != sizeof(c)){
printf("write error\n");
return 0;
}
fl.l_type = F_UNLCK;
fcntl(fd,F_SETLKW,&fl);
return 1;
}
int addNewTrain(struct train newTrain)
{
char* filename = "trains.txt";
int fd;
struct flock fl;
int trainNo = newTrain.trainNo;
fd = open(filename,O_CREAT|O_WRONLY,0777);
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = sizeof(struct train)*(trainNo-1);
fl.l_len = sizeof(struct train);
fl.l_pid = getpid();
//printf("Before Critical section\n");
if(fcntl(fd,F_SETLKW,&fl) == -1)
return 0;
//printf("Lock acquired\n");
lseek(fd,sizeof(struct train)*(trainNo-1),SEEK_SET);
if(write(fd,&newTrain,sizeof(newTrain)) != sizeof(newTrain)){
printf("write error\n");
return 0;
}
fl.l_type = F_UNLCK;
fcntl(fd,F_SETLKW,&fl);
// printf("Lock released\n");
return 1;
}
int deleteTrain(int trainNo){
char* filename = "trains.txt";
int fd;
struct flock fl;
char emptyChar = 'n';
struct train tr;
struct train invalidData;
invalidData.trainNo = -1;
strcpy(invalidData.trainName,"invalid express");
if(!searchTrain(&tr,trainNo)){
return 0;
}
printf("no : %d\n",trainNo);
fd = open(filename,O_WRONLY,0777);
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = sizeof(struct train)*(trainNo-1);
fl.l_len = sizeof(struct train);
fl.l_pid = getpid();
//printf("Before Critical section\n");
if(fcntl(fd,F_SETLKW,&fl) == -1)
return 0;
//printf("Lock acquired\n");
lseek(fd,sizeof(struct train)*(trainNo-1),SEEK_SET);
if(write(fd,&invalidData,sizeof(struct train)) != sizeof(struct train)){
printf("write error\n");
return 0;
}
fl.l_type = F_UNLCK;
fcntl(fd,F_SETLKW,&fl);
//printf("Lock released\n");
return 1;
}
int searchTrain(struct train *tr,int trainNo){
char* filename = "trains.txt";
int fd;
struct flock fl;
fd = open(filename,O_RDONLY,0777);
fl.l_type = F_RDLCK;
fl.l_whence = SEEK_SET;
fl.l_start = sizeof(struct train)*(trainNo-1);
fl.l_len = sizeof(struct train);
fl.l_pid = getpid();
printf("Before Critical section\n");
if(fcntl(fd,F_SETLKW,&fl) == -1){
perror("");
return 0 ;
}
printf("Lock acquired\n");
lseek(fd,sizeof(struct train)*(trainNo-1),SEEK_SET);
if(read(fd,tr,sizeof(struct train)) != sizeof(struct train)){
perror("read error: ");
return 0;
}
fl.l_type = F_UNLCK;
fcntl(fd,F_SETLKW,&fl);
if(trainNo!=(*tr).trainNo){
printf("train no invalid\n");
return 0;
}
printf("Train details Found\n");
printf("Train No : %d\nName : %s\n",(*tr).trainNo,(*tr).trainName);
printf("Total seats Booked :%d \n",(*tr).totalBooked);
printf("Available Seats : ");
for(int i=0;i<TOTAL_SEATS_IN_TRAIN;i++){
if((*tr).seatsBooked[i]==0)
printf("%d ",i);
}
printf("\n");
return 1;
}
int modifyTrain(struct train *tr,int trainNo)
{
char* filename = "trains.txt";
int fd1,fd2;
struct flock fl1,fl2;
struct train oldTrain;
fd1 = open(filename,O_RDWR,0777);
//printf("fd = %d\n",fd);
fl1.l_type = F_WRLCK;
fl1.l_whence = SEEK_SET;
fl1.l_start = sizeof(struct train)*(trainNo-1);
fl1.l_len = sizeof(struct train);
fl1.l_pid = getpid();
printf("Before Critical section read 2\n");
if(fcntl(fd1,F_SETLKW,&fl1) == -1){
return 0;
}
printf("Lock acquired\n");
lseek(fd1,sizeof(struct train)*(trainNo-1),SEEK_SET);
if(read(fd1,&oldTrain,sizeof(struct train)) != sizeof(struct train)){
printf("Read error\n");
fl1.l_type = F_UNLCK;
fcntl(fd1,F_SETLKW,&fl1);
return 0;
}
if(oldTrain.trainNo!=trainNo){
printf("Read invalid\n");
fl1.l_type = F_UNLCK;
fcntl(fd1,F_SETLKW,&fl1);
return 0;
}
for(int i=0;i<MAX_CHAR;i++)
oldTrain.trainName[i] = tr->trainName[i];
printf("Lock acquired\n");
lseek(fd1,sizeof(struct train)*(trainNo-1),SEEK_SET);
if(write(fd1,&oldTrain,sizeof(struct train)) != sizeof(struct train)){
printf("write error\n");
fl1.l_type = F_UNLCK;
fcntl(fd1,F_SETLKW,&fl1);
return 0;
}
fl1.l_type = F_UNLCK;
fcntl(fd1,F_SETLKW,&fl1);
return 1;
}
int getAllUsers(int uid,int userLockFd,struct dataBase *db){
char* filename = "accounts.txt";
int fd;
int fd2;
struct flock fl;
struct flock fl2;
struct account acc;
struct credentials cred;
int itr;
int noUsers = 1;
int bytesRead;
char adminName[5] = "ADMIN";
fd = open(filename,O_CREAT|O_RDONLY,0777);
fd2 = open("credentials.txt",O_CREAT|O_RDONLY,0777);
db->acc[0].uid = 1;
db->acc[0].accType = 1;
db->acc[0].totalBookings = 0;
for(int j=0;j<5;j++)
db->acc[0].name[j] = adminName[j];
db->cred[0].uid = 1;
db->cred[0].pin = 1234;
db->noUsers = noUsers;
//printf("fd2 = %d\n",fd);
for(itr=2;itr<1000;itr++){
fl.l_type = F_RDLCK;
fl.l_whence = SEEK_SET;
fl.l_start = sizeof(struct account)*(itr-1);
fl.l_len = sizeof(struct account);
fl.l_pid = getpid();
fl2.l_type = F_RDLCK;
fl2.l_whence = SEEK_SET;
fl2.l_start = sizeof(struct credentials)*(itr-1);
fl2.l_len = sizeof(struct credentials);
fl2.l_pid = getpid();
//printf("Before Critical section\n");
if(fcntl(fd,F_SETLKW,&fl) == -1)
return 1;
if(fcntl(fd2,F_SETLKW,&fl2) == -1)
return 1;
//printf("Lock acquired\n");
lseek(fd,sizeof(struct account)*(itr-1),SEEK_SET);
bytesRead = read(fd,&acc,sizeof(acc));
fl.l_type = F_UNLCK;
fcntl(fd,F_SETLKW,&fl);
if(bytesRead == 0){
printf("EOF\n");
return 1;
}
else if(bytesRead != sizeof(acc)){
printf("Read error\n");
return 0;
}
lseek(fd2,sizeof(struct credentials)*(itr-1),SEEK_SET);
bytesRead = read(fd2,&cred,sizeof(cred));
fl2.l_type = F_UNLCK;
fcntl(fd2,F_SETLKW,&fl2);
if(bytesRead == 0){
printf("EOF\n");
return 1;
}
else if(bytesRead != sizeof(cred)){
printf("Read error\n");
return 0;
}
printf("uid read : %d\n acc type : %d\n name : %s\npin: %d\n",acc.uid,acc.accType,acc.name,cred.pin);
if(acc.uid>0){
db->acc[(++noUsers)-1].uid = acc.uid;
db->acc[noUsers-1].accType = acc.accType;
db->acc[noUsers-1].totalBookings = acc.totalBookings;
for(int i=0;i<20;i++)
db->acc[noUsers-1].name[i] = acc.name[i];
db->cred[noUsers-1].uid = cred.uid;
db->cred[noUsers-1].pin = cred.pin;
db->noUsers = noUsers;
}
//printf("Lock released\n");
}
return 1;
}
int getAllTrains(struct dataBase *db){
int fd;
int itr;
char *filename = "trains.txt";
struct train tr;
struct flock fl;
int noTrains=0;
int bytesRead;
fd = open(filename,O_RDONLY,0777);
for(itr=1;itr<1000;itr++){
fl.l_type = F_RDLCK;
fl.l_whence = SEEK_SET;
fl.l_start = sizeof(struct train)*(itr-1);
fl.l_len = sizeof(struct train);
fl.l_pid = getpid();
printf("Trains : Before Critical section\n");
lseek(fd,sizeof(struct train)*(itr-1),SEEK_SET);
bytesRead = read(fd,&tr,sizeof(tr));
fl.l_type = F_UNLCK;
fcntl(fd,F_SETLKW,&fl);
if(bytesRead == 0){
printf("EOF\n");
return 1;
}
else if(bytesRead != sizeof(tr)){
printf("Read error\n");
return 0;
}
if(tr.trainNo>0){
db->tr[(++noTrains)-1].trainNo = tr.trainNo;
for(int i=0;i<MAX_CHAR;i++){
db->tr[noTrains-1].trainName[i] = tr.trainName[i];
}
db->tr[noTrains-1].totalBooked = tr.totalBooked;
db->noTrains = noTrains;
}
}
return 1;
}
|
C | //Alocacao Dinam 1
//Operador sizeof
#include <stdio.h>
typedef struct ponto {
float x, y;
}Ponto;
int main() {
int x, f, d, c;
x = sizeof(int);
f = sizeof(float);
d = sizeof(double);
c = sizeof(char);
printf("Tamanho do int = %d bytes\n", x);
printf("Tamanho do float = %d bytes\n", f);
printf("Tamanho do double = %d bytes\n", d);
printf("Tamanho do char = %d bytes\n", c);
printf("Tamanho da struct ponto = %d bytes", sizeof(Ponto));
return 0;
}
|
C | #include <stdio.h>
int main()
{
char c;
int n;
c=getchar();
if(c!='\n')
{
n = c-'0';
printf("%d",n);
}
}
|
C | #include <stdio.h>
void format_float()
{
float f;
printf("Enter a number \n");
scanf("%f", &f);
printf("value = %f \n", f);
}
void getchar_putchar() {
int c;
printf("Enter value: \n");
c = getchar();
printf("\n You entered:\n");
putchar(c);
printf("\n");
}
void gets_puts() {
char str[100];
printf("Enter a value: \n");
gets(str);
printf("\n You entered: \n");
puts(str);
}
void scanf_printf() {
char str[100];
int i;
printf("Enter a value \n");
scanf("%s %d", str, &i);
printf("\nYou entered: %s %d\n", str, i);
printf("\n");
}
int main(int argc, char const *argv[])
{
// format_float();
// getchar_putchar();
// gets_puts();
scanf_printf();
return 0;
}
|
C | #include <stdio.h>
int main(int argc, char *argv[]) {
char buffer [256];
/* Initialize file_name */
FILE *file = fopen("test1", "rb");
/*
The file position indicator needs to be set to 1 before you call ungetc() else there is unpredictable behavior.
*/
//fseek(file, 1, SEEK_SET);
printf("Current position is %lu\n",ftell(file));
/*
If file pointer position is 0, ungetc() generates unpredictable results. The file pointer value is a random number,
and ungetc() doesn't replace the pos-1 character at all... just prints the pushed character with the entire stream.
The point is to never have th file position indicator set to 0 when calling ungetc()
*/
ungetc('+',file);
printf("Current position if position is 0 when ungetc is called is %lu\n",ftell(file));
fgets(buffer, 255, file);
fputs(buffer, stdout);
fclose(file);
file = fopen("test1", "wb");
fputs(argv[1], file);
/*
The docs recommend never to use SEEK_END as it is not portable. But using it with the right offset seems to work okay. Not sure what
the problem is :)
The reason for unpredictability is apparently...because null characters can be part of the stream that's written to the file. But fputs
anyway ignores all null characters. So this is all unclear :)
*/
fseek(file,ftell(file),SEEK_SET);
//fseek(file, 0, SEEK_END);
printf("\nCurrent position is %lu\n",ftell(file));
fputs("crap\n", file);
fclose(file);
}
|
C | #include <stdio.h>
int price[1001], m[1001];
int makeMax(int x);
int main() {
int n;
scanf("%d", &n);
getchar();
for(int i=1; i<=n; i++) {
scanf("%d", &price[i]);
getchar();
}
for(int i=1; i<=n; i++)
m[i] = -1;
m[1] = price[1];
printf("%d\n", makeMax(n));
// n 만드는 최대 가격
return 0;
}
int makeMax(int x) {
int max, temp;
if(m[x] != -1)
return m[x];
max = price[x];
for(int i=1; i<=x/2; i++) {
if((temp = makeMax(i) + makeMax(x-i)) > max)
max = temp;
}
return m[x] = max;
} |
C | //Print half Pyramid pattern in c
/*
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
*/
#include <stdio.h>
int main()
{
int i,j,rows = 5;
for(i=1;i<=rows;i++)
{
for(j=1;j<=i;j++)
{
//printf("%d ",j); //output number after space
//we change the number to other pattern like *
printf("* ");//* after space
}
printf("\n"); //newline break;
}
return 0;
}
|
C | #include "funciones.h"
int power(int base,int potencia){
int i,resultado = 1;
for (i=0;i<potencia;i++){
resultado *= base;
}
return resultado;
}
char **split(char *phrase, const size_t length, const char delimiter, size_t *n_tokens)
{
int words = 1;
size_t n;
for (n = 0; n < length; n++)
words += phrase[n] == delimiter;
char **input = malloc(sizeof(char*) * words);
int j = 0;
char *token = strtok(phrase, &delimiter);
while (token != NULL) {
input[j] = malloc(sizeof(char) * strlen(token) + sizeof(char));
strcpy(input[j++], token);
token = strtok(NULL, &delimiter);
}
*n_tokens = words;
return input;
}
char *linea_archivo(FILE *archivo){ //entrega un string con la linea de un archivo.
int i = 1;
char c,*linea;
linea = malloc(sizeof(char)); //c para cada caracter, linea para la linea entera.
while (1){
c = fgetc(archivo);
if (c == '\n' || c == EOF) break;
else{
linea = realloc(linea,sizeof(char) * i); //memoria para un caracter mas.
linea[i-1] = c;
i++;
}
}
return linea;
}
char *nombre_archivo(char *string){ //entrega el ultimo token (generalmente el nombre del archivo)
int i,largo_nombre;
size_t valor,*n,largo;
char **tokens,*filename;
valor = 0;
n = &valor;
largo = strlen(string);
tokens = split(string,largo,' ',n); //LIBERAR ESTO Y PROBAR DE NUEVO.
largo = strlen(tokens[(int) *n -1]);
largo_nombre = (int) largo;
filename = malloc(sizeof(char) * largo_nombre);
for (i = 0;i<largo_nombre;i++) filename[i] = tokens[(int) *n -1][i];
return filename;
}
int string_to_int(char *string){ // convierte un string a entero, asumiendo que el entero va desde -X a +Y.
int i,suma,valor;
size_t largo;
largo = (int) strlen(string);
suma = 0;
for (i=0;i<largo;i++){
valor = (int) string[i] - '0';
valor *= power(10,largo-1-i);
suma += valor;
}
return suma;
}
void Terminar_programa(char *string){ //leer archivo, imprimir texto.
char *nombre,noargs[] = "noargs";
nombre = nombre_archivo(string);
if (strcmp(nombre,noargs) != 0){
FILE *input;
input = fopen(nombre,"r");
if (input == NULL){
printf("Archivo %s no existe\n",nombre);
free(nombre);
exit(0);
}
char *texto;
texto = linea_archivo(input);
printf("%s",texto);//asumiendo que el archivo tiene 1 sola linea.
fclose(input);
free(texto);
}
free(nombre);
//liberar memoria almacenada en el arbol.
exit(0);
}
void Insertar(char *string){
int linea;
char *nombre;
FILE *input,*archivo;
nombre = nombre_archivo(string);
input = fopen(nombre,"r");
if (input != NULL){
while (1){
char **palabras,*filename,*file_line;
size_t *n,valor;
file_line = malloc( sizeof(char) * 128);
file_line = fgets(file_line, sizeof(char) * 128, input);
valor = 0;
n = &valor;
if (feof(input)) break;
palabras = split(file_line,strlen(file_line),' ',n);
filename = palabras[0];
linea = string_to_int(palabras[1]);
archivo = fopen(filename,"r");
if (archivo == NULL){
printf("Archivo %s no encontrado.\n",filename);
continue;
}
else{
FILE *temp = fopen("aux.txt", "w");
char *datos;
int i,insertada = 0,cont = 0;
datos = malloc( sizeof(char) * 128);
datos = fgets(datos, sizeof(char) * 128, archivo);
while (1){
if (cont == linea){
for (i = 2; i < valor; i++){
fprintf(temp, "%s", palabras[i]);
if (i != valor -1) fprintf(temp,"%c", ' ');
}
insertada = 1;
}
fprintf(temp,"%s",datos);
datos = fgets(datos, sizeof(char) * 128, archivo);
cont++;
if ( feof(archivo) ){
if (linea < 0){
for (i = 2; i < valor; i++){
fprintf(temp, "%s", palabras[i]);
if (i != valor -1) fprintf(temp,"%c", ' ');
}
insertada = 1;
}
if (insertada == 0){
printf("Linea %d no existe en %s\n",linea,filename);
fclose(temp);
remove("aux.txt");
}
break;
}
}
fclose(archivo);
if (insertada == 1){
fclose(temp);
remove(filename);
rename("aux.txt",filename);
}
}
free(file_line);
free(palabras);
free(filename);
}
}
}
void Eliminar_por_linea(char *string){
int linea;
char *nombre;
FILE *input,*archivo;
nombre = nombre_archivo(string);
input = fopen(nombre,"r");
if (input != NULL){
while (1){
char **palabras,*filename,*file_line,**aux;
size_t *n,valor;
int i,largo;
file_line = malloc( sizeof(char) * 64);
file_line = fgets(file_line, sizeof(char) * 64, input);
valor = 0;
n = &valor;
if (feof(input)) break;
palabras = split(file_line,strlen(file_line),' ',n);
aux = split(palabras[1],strlen(palabras[1]),'\n',n);
filename = palabras[0];
linea = string_to_int(aux[0]);
free(aux);
archivo = fopen(filename,"r");
if (archivo == NULL){
printf("Archivo %s no encontrado.\n",filename);
continue;
}
else{
int cont,eliminada;
char *datos;
FILE *temp;
temp = fopen("aux.txt","w");
datos = malloc( sizeof(char) * 128 );
datos = fgets(datos, sizeof(char) * 128, archivo);
cont = 0;
while (1){
if (cont == linea){
datos = fgets(datos, sizeof(char) * 128, archivo);
eliminada = 1;
}
if (feof(archivo)){
if (eliminada != 1){
printf("linea %d no encontrada en %s\n",linea,filename);
eliminada = 0;
}
break;
}
fprintf(temp,"%s",datos);
datos = fgets(datos, sizeof(char) * 128, archivo);
cont++;
}
free(datos);
fclose(temp);
fclose(archivo);
if (eliminada == 1){
remove(filename);
rename("aux.txt",filename);
}
}
}
}
}
void Eliminar_por_coincidencia(char *string){
char *nombre;
FILE *input,*archivo;
nombre = nombre_archivo(string);
input = fopen(nombre,"r");
if (input != NULL){
while (1){
char **palabras,**aux,*filename,*file_line,*keyword;
size_t *n,valor;
int i,indice,largo;
file_line = malloc( sizeof(char) * 64);
file_line = fgets(file_line, sizeof(char) * 64, input);
valor = 0;
n = &valor;
if (feof(input)) break;
palabras = split(file_line,strlen(file_line),' ',n);
aux = split(palabras[2],strlen(palabras[2]),'\n',n);
filename = palabras[0];
keyword = aux[0];
indice = string_to_int(palabras[1]);
archivo = fopen(filename,"r");
if (archivo == NULL){
printf("Archivo %s no encontrado.\n",filename);
continue;
}
else{
int eliminada;
char *datos;
FILE *temp;
temp = fopen("aux.txt","w");
datos = malloc( sizeof(char) * 128 );
datos = fgets(datos, sizeof(char) * 128, archivo);
while (1){
char **tokens,**ultimo;
int i;
size_t *n,valor = 0;
n = &valor;
tokens = split(datos,strlen(datos),' ',n);
ultimo = split(tokens[valor-1],strlen(tokens[valor-1]),'\n',n);
if (!strcmp(keyword,tokens[indice])){
datos = fgets(datos, sizeof(char) * 128, archivo);
eliminada = 1;
}
if (indice = (int)valor -1){
if (!strcmp(keyword,ultimo[0])){
datos = fgets(datos, sizeof(char) * 128, archivo);
eliminada = 1;
}
}
free(ultimo);
free(tokens);
if (feof(archivo)){
if (eliminada != 1){
printf("keyword %s no encontrado en %s\n",keyword,filename);
eliminada = 0;
}
break;
}
fprintf(temp,"%s",datos);
datos = fgets(datos, sizeof(char) * 128, archivo);
}
free(datos);
fclose(temp);
fclose(archivo);
if (eliminada == 1){
remove(filename);
rename("aux.txt",filename);
}
if (eliminada == 0) remove("aux.txt");
}
}
}
}
void Mostrar_por_linea(char *string){//caso en que linea no existe.
int linea;
char *nombre;
FILE *input,*archivo;
nombre = nombre_archivo(string);
input = fopen(nombre,"r");
if (input != NULL){
while (1){ //recorriendo el archivo de input linea a linea.
char **palabras,*datos,*filename,*file_line = linea_archivo(input);
size_t *n,valor;
valor = 0;
n = &valor;
if (feof(input)) break;
palabras = split(file_line,strlen(file_line),' ',n); //separar nombre del archivo de la linea que se busca.
filename = palabras[0];
linea = string_to_int(palabras[1]);
archivo = fopen(filename,"r");
if (archivo != NULL){
int i;
for (i = 0;i < linea;i++){ //recorriendo el archivo.
datos = linea_archivo(archivo);
if (i == linea-1){ //linea buscada.
printf("%s: %s\n",filename,datos);
free(datos);
break;
}
if (feof(archivo)){ //final del archivo.
printf("Linea %d no existe en '%s'\n",linea,filename);
free(datos);
break;
} //liberar memoria si la linea no es la buscada.
if (i != linea -1 && datos != NULL) free(datos);
}
fclose(archivo);
}
else{
printf("Archivo '%s' no encontrado\n",filename);
fclose(archivo);
}
free(palabras);
free(file_line);
}
}
else printf("%s","Archivo de input no encontrado\n");
fclose(input);
free(nombre);
}
void Crear_archivo(char *string){//leer archivo de input y crear un archivo por cada linea.
FILE *input,*archivo;
char *nombre;
nombre = nombre_archivo(string);
input = fopen(nombre,"r");
if (input != NULL){
while (1){
char *line = linea_archivo(input);
if (feof(input)) break;
archivo = fopen(line,"w");
fclose(archivo);
printf("Archivo '%s' creado\n",line);
free(line);
}
}
else printf("%s","Archivo de input no encontrado\n");
fclose(input);
free(nombre);
}
void Eliminar_archivo(char *string){//string es el input completo: <token> ... <token> <nombre archivo>
FILE *input; //archivos en directorio db;
char *nombre;
nombre = nombre_archivo(string);
input = fopen(nombre,"r");
if (input != NULL){
while (1){
int r;
char *line = linea_archivo(input);
if (feof(input)) break;
r = remove(line);
if (r == 0) printf("Archivo '%s' eliminado exitosamente.\n",line);
else printf("Error al intentar eliminar %s\n",line);
free(line);
}
}
else printf("%s","Archivo de input no encontrado\n");
fclose(input);
free(nombre);
}
void Truncar_archivo(char *string){
FILE *input,*archivo;
char *nombre;
nombre = nombre_archivo(string);
input = fopen(nombre,"r");
if (input != NULL){
while (1){
char *line = linea_archivo(input);
if (feof(input)) break;
archivo = fopen(line,"r");
if (archivo != NULL){
archivo = freopen(line,"w",archivo);
fclose(archivo);
printf("Archivo '%s' limpiado\n",line);
}
else{
printf("Archivo '%s' no encontrado\n",line);
fclose(archivo);
}
free(line);
}
}
else printf("%s","Archivo de input no encontrado\n");
fclose(input);
free(nombre);
}
|
C | #include <stdio.h>
unsigned int ft_strlcat(char* dest, char* src, unsigned int size);
int main(int argc, char const *argv[])
{
char test[256] = "\0zxcvzxcvzxcvxzcvzxcv";
printf("%d-", ft_strlcat(test, "asdf", 16));
printf("%s\n", test);
printf("%d-", ft_strlcat(test, "asdf", 6));
printf("%s\n", test);
printf("%d-", ft_strlcat(test, "asdf", 4));
printf("%s\n", test);
printf("%d-", ft_strlcat(test, "", 16));
printf("%s\n", test);
printf("%d-", ft_strlcat(test, "asdf", 0));
printf("%s\n", test);
printf("t%d-", ft_strlcat(test, "asdf", 10));
printf("%s\n", test);
printf("t%d-", ft_strlcat(test, "asdf", 5));
printf("%s\n", test);
return (0);
} |
C | /*
** EPITECH PROJECT, 2018
** rpg
** File description:
** init_pause
*/
#include <stdlib.h>
#include "rpg.h"
#include "struct.h"
#include "menu.h"
#include "free.h"
#include "init.h"
#define BUTTON_NB 3
#define RESUME "./asset/Resume.png"
#define QUIT_GAME "./asset/QuitGame.png"
#define STATS "./asset/Stats.png"
#define MENU "./asset/BackMenu.png"
void init_the_button(button_t *new_game, sfVector2f pos, char *path)
{
new_game->rect.left = 0;
new_game->rect.top = 0;
new_game->rect.width = 600;
new_game->rect.height = 300;
new_game->button_tx = sfTexture_createFromFile(path, NULL);
new_game->button_r = sfRectangleShape_create();
sfRectangleShape_setTexture(new_game->button_r, new_game->button_tx,
sfTrue);
sfRectangleShape_setTextureRect(new_game->button_r, new_game->rect);
sfRectangleShape_setSize(new_game->button_r, (sfVector2f){600, 300});
sfRectangleShape_setScale(new_game->button_r, (sfVector2f){0.80, 0.80});
sfRectangleShape_setPosition(new_game->button_r, pos);
}
int init_buttons_pause(button_t **button_arr)
{
button_t *resume;
button_t *quit_game;
button_t *back_menu;
resume = malloc(sizeof(button_t));
quit_game = malloc(sizeof(button_t));
back_menu = malloc(sizeof(button_t));
init_the_button(resume, (sfVector2f){100, 100}, RESUME);
init_the_button(quit_game, (sfVector2f){700, 900}, QUIT_GAME);
init_the_button(back_menu, (sfVector2f){1300, 100}, MENU);
button_arr[0] = resume;
button_arr[1] = quit_game;
button_arr[2] = back_menu;
return (0);
} |
C | /* Copyright (c) 2013 MIT License by 6.172 Staff
*
* DON'T USE THE FOLLOWING SOFTWARE, IT HAS KNOWN BUGS, AND POSSIBLY
* UNKNOWN BUGS AS WELL.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*/
#define _POSIX_C_SOURCE 200112L
#define _GNU_SOURCE
#include <pthread.h>
#include <stdio.h>
#define HLOCKS 16
pthread_mutex_t hashlock[HLOCKS];
#define HASHLOCK_SLOT(l) &hashlock[(l) & (HLOCKS - 1)]
void hashlock_init() {
int i;
pthread_mutexattr_t recursive;
pthread_mutexattr_init(&recursive);
pthread_mutexattr_settype(&recursive, PTHREAD_MUTEX_RECURSIVE);
for (i = 0; i < HLOCKS; i++) {
pthread_mutex_init(&hashlock[i], &recursive);
}
}
void hashlock_lock(int l) {
pthread_mutex_lock(HASHLOCK_SLOT(l));
#ifdef UNIT_TEST
printf("lock %d\n", l);
#endif
}
void hashlock_unlock(int l) {
pthread_mutex_unlock(HASHLOCK_SLOT(l));
#ifdef UNIT_TEST
printf("unlock %d\n", l);
#endif
}
#ifdef UNIT_TEST
int main() {
hashlock_init();
printf("lock size %ld\n", sizeof(hashlock[0]));
hashlock_lock(2);
hashlock_lock(2);
hashlock_lock(5);
hashlock_unlock(2);
hashlock_unlock(5);
return 0;
}
#endif
|
C | //*************************************************WINDOW WATCHDOG TIMER PRACTISE***************************************************************************//
#include "stm32f4xx.h" // Device header
#define CLK 8000000UL
// Function prototype //
void RCC_Config(void);
void GPIO_Init(void);
void WWDG_Init(void);
void delay(uint32_t time);
uint32_t count = 0 ;
int main()
{
RCC_Config();
GPIO_Init();
WWDG_Init();
while(1)
{
GPIOA->ODR ^= (1<<5);
delay(CLK/10);
}
}
void RCC_Config() // Fosc=8MHz
{
RCC->CR |= (1<<16); // HSE ON
while(!(RCC->CR &(1<<17))); // HSE ready waiting
RCC->CFGR |= (1<<12); // APB1 PSC=0
RCC->CFGR &= ~(7<<13); // APB2 PSC=0
RCC->CFGR |= (10<<4); // AHB PSC=8
RCC->PLLCFGR &= ~(0xFFFFFFFF); // APB2 PSC=0
RCC->PLLCFGR |= (1<<22); // HSE selected
RCC->PLLCFGR &= ~(3<<16); // PLLP=2
RCC->PLLCFGR |= (64<<6); // PLLN=64
RCC->PLLCFGR |= (1<<2); // PLLM=4
RCC->PLLCFGR |= (1<<29); // PLLR=2
RCC->PLLCFGR |= (1<<25); // PLLQ=2
RCC->CR |= (1<<24); // PLL ON
while(!(RCC->CR &(1<<25))); // PLL ready waiting
}
void GPIO_Init()
{
RCC->AHB1ENR |= (1<<0); // GPIOA clock enable
GPIOA->MODER |= (1<<10); // PA5 Output mode
GPIOA->OTYPER &= ~(1<<5); // Push-Pull select
GPIOA->PUPDR &= ~(3<<10); // No push-No pull select
}
void WWDG_Init(void)
{
RCC->APB1ENR |= (1<<11); // Window watchdog clock enabled
WWDG->CFR |= (1<<8); // CK Counter Clock (PCLK1 div 4096) div 4
WWDG->CFR |= 0x3F; // These bits contain the window value to be compared to the downcounter.
WWDG->CR |= (1<<7); // Watchdog enabled
WWDG->CR |= (0x3F); // These bits contain the value of the watchdog counter. It is decremented every (4096 x 2WDGTB[1:0]) PCLK1 cycles. A reset is produced when it rolls over from 0x40 to 0x3F (T6 becomes cleared).
}
void delay(uint32_t time)
{
while(time--);
}
|
C | #include <stdlib.h>
#include <string.h>
#include <cell.h>
static int bit_at_index(char byte, int index);
static void free_subtape(cell *current, cell *previous);
/*
* We assume index is between 0 & 7, and create a bit mask to extract only that
* bit from byte. Finally, we double negate it to convert it to 0 or 1, because
* our bitmask extracts bits as powers of two.
*/
int
bit_at_index(char byte, int index)
{
return !!(byte & 1 << index);
}
/*
* Because a new cell has no links (i.e., they're null), the cell we return is
* blank except for the symbol in the cell, 0 or 1. As boolean 'true' is 1,
* we can just write it into the cell.
*/
cell *
cell_from_bit(bool b)
{
cell *result;
result = malloc(sizeof *result);
if (!result) return 0;
*result = b;
return result;
}
/*
* Because it's simplest to iterate over bits in our tape than over bytes in
* our buffer, we will write out bits one by one, which requires zeroing the
* bytes before we first write to them. We have chosen to do this upfront with
* memset rather than having the logic inside the main loop.
*/
void
copy_tape_into_buffer(char *buffer, size_t length, cell *tape)
{
struct walker walker[1];
size_t i;
int b;
memset(buffer, 0, length);
walker_begin(walker, tape, 0);
for (i=0; i/8<length; ++i) {
b = *walker->current & 1;
buffer[i/8] |= b << i%8;
walker_step(walker);
if (!walker->current) return;
}
}
/*
* Because free_tape() needs to free in both directions, this function handles
* freeing in a particular direction. Two pointers specify a direction, and
* this function only frees one of them. See free_tape() itself for quick
* justification.
*/
void
free_subtape(cell *current, cell *previous)
{
struct walker walker[1];
walker_begin(walker, current, previous);
while (walker->current) {
free(walker->current);
walker_step(walker);
}
}
/*
* For convenience, this function will free an entire tape, no matter where
* the right and left pointers indicate. Because of this, it defers to
* free_subtape(), with left & right taking turns as the current & previous
* pointers.
*/
void
free_tape(cell *left, cell *right)
{
free_subtape(left, right);
free_subtape(right, left);
}
cell *
get_next_cell(cell *current, cell *previous)
{
cell temp;
if (!current) return 0;
temp = *current;
temp &= ~1;
temp ^= (cell)previous;
return (cell *)temp;
}
/*
* The number of links in a cell is indistinguishable, so it is up
* to the caller to ensure lef & rit only have one.
*/
void
link_cells(cell *lef, cell *rit)
{
*lef ^= (cell)rit;
*rit ^= (cell)lef;
}
/*
* Tapes are stored in little endian fashion. This is also how bytes are
* addressed, so i%8 goes from lowest bit to highest, and i/8 goes from
* lowest offset to highest. Thus, 'b' becomes every bit from buffer in
* order.
*/
cell *
tape_from_buffer(char *buffer, size_t length)
{
cell *tape_head=0;
cell *tape_tail;
cell *new_cell;
size_t i;
int b;
for (i=0; i/8<length; ++i) {
b = bit_at_index(buffer[i/8], i%8);
new_cell = cell_from_bit(b);
if (!new_cell) goto fail;
if (tape_head) link_cells(tape_tail, new_cell);
else tape_head = new_cell;
tape_tail = new_cell;
}
return tape_head;
fail:
free_tape(tape_head, 0);
return 0;
}
/* TODO: use a walker here */
cell *
walk_tape(cell *current, cell *previous)
{
cell *next;
while (next = get_next_cell(current, previous)) {
previous = current;
current = next;
}
return current;
}
void
walker_begin(struct walker *walker, cell *current, cell *previous)
{
walker->current = current;
walker->previous = previous;
walker->next = get_next_cell(current, previous);
}
void
walker_step(struct walker *walker)
{
walker->previous = walker->current;
walker->current = walker->next;
walker->next = get_next_cell(walker->current, walker->previous);
}
|
C | #include <stdlib.h>
typedef int ElemType;
#define maxsize 50//数组,栈等最大空间
//!!以下为顺序结构!!
// 顺序表的结构定义
typedef struct
{
int data[maxsize]; // 存放数组的数组
int length; // 顺序表的实际长度
}SeqList; // 顺序表类型名为SeqList
// 单链表的类型定义
typedef struct node
{
int data; // 数据域
struct node *next; // 指针域
}Node, *LinkList;
// 双向循环链表结点的类型定义
typedef struct DNode
{
int data;
struct DNode *prior;
struct DNode *next;
}DNode, *DLinkList;
// 顺序栈
typedef struct seqstack
{
int data[maxsize];
int top; // 标志栈顶位置的变量
}SeqStk;
// 链栈
typedef struct lnode
{
int data;
struct lnode *next;
}LStk;
// 顺序队列
typedef struct seqque
{
int data[maxsize];
int front, rear;
}SqQue;
//循环队列,实则与上一样
typedef struct cycque
{
int data[maxsize];
int front,rear;
}CyQue;
// 链式队列类型定义
typedef struct LQueueNode
{
int data;
struct LQueueNode *next;
}LQueNode;
typedef struct LQueue
{
LQueNode *front, *rear;
}LQue;
//!!以下为矩阵及广义表!!
//矩阵转置、相加、相乘(较简单)
//三元组(较简单)
//上三角、下三角矩阵 存储到一维数组(较简单)
//稀疏矩阵“十字链表” 的 数据结点 和 头节点
typedef struct sznode
{
int row,col;//行号和列号
//最左和最上不存储data,其row和clo设为-1
struct sznode *right,*down; //指向右边及下方结点指针
float data;//值域
}SZNode;
//头结点,左上角那一个
typedef struct
{
SZNode *r,*c;//指向两头结点数组
int m,n,k;//存储整个十字链表 行、列、非空结点总数
}CrossList;
// !!以下为树结构!!
// 二叉链表的类型定义
typedef struct btnode
{
int data;//默认int型,按需修改
struct btnode *lchild, *rchild; // 指向左右孩子的指针
}BTNode, *BinTree;
// 三叉链表的类型定义
typedef struct ttnode
{
int data;
struct ttnode *lchild, *parent, *rchild;
}*TBinTree;
//线索二叉树
typedef struct TBTNode
{
int data;
int ltag; //左标识位,为0时,lchild指向左孩子;为1时,指向前驱
int rtag; //右标识位,为0时,lchild指向右孩子;为1时,指向后继
struct TBTNode *lchild;
struct TBTNode *rchild;
}TBTNode;
//!!以下为图的基本结构!!
//邻接矩阵(顺序)
typedef struct gp
{
int vexs[maxsize]; // 顶点data信息
int edges[maxsize][maxsize]; // 邻接矩阵核心,无权图用int:1表示邻接
//有权图换作float记录权值,若无邻接用极大数表示
int vexnum, edgenum; // 顶点数,边数
}MGraph;
// 邻接表(链式)
// 边结点
typedef struct arcnode
{
int adjvex; // 通过该边邻接的后继结点编号
int weight; // 权值
struct arcnode *nextarc;
}ArcNode;
// 顶点结点
typedef struct vexnode
{
int vextex; // 顶点编号
ArcNode *firstarc; // 指向第一条边的指针
}VexNode;
typedef struct agp
{
VexNode adjlist[maxsize];//邻接表
int vexnum, arcnum; // 顶点和边数
}AGraph;
//逆邻接表
//任一表头结点下的边结点的数量是图中该结点入度的弧的数量,与邻接表相反。
//图的邻接表,反映的是节点的出度邻接情况;图的逆邻接表反映的是节点的入度邻接情况。 |
C | #include <stdio.h>
int main()
{
int s,m,h,q; //* s is seconds, m is minutes, q is quantity of seconds and h for hours
printf("recieve a quantity of seconds and show its equivalence in format hours,:minutes,:seconds \n")
printf("which is the quantity of seconds?")
scanf("%d",&q);
h=(q/3600);
m=((q-h*3600)/60);
s=q-(h*3600+m*60);
printf("%d:%d:%d",h,m,s);
return 0;
}
|
C | #include<stdio.h>
main()
{
int a[6][6],d[6][6],b,c;
printf("Enter the elements of matrix 1\n");
for(b=0;b<=5;b++)
{
for(c=0;c<=5;c++)
{
scanf("%d\t",&a[b][c]);
}
}
printf("Enter the elements of matrix 2\n");
for(b=0;b<=5;b++)
{
for(c=0;c<=5;c++)
{
scanf("%d\t",&d[b][c]);
}
}
printf("\nThe elements of matrix 1 are:\n");
for(b=0;b<=5;b++)
{
for(c=0;c<=5;c++)
{
printf("%d\t",a[b][c]);
}
printf("\n");
}
printf("\nThe elements of matrix 2 are:\n");
for(b=0;b<=5;b++)
{
for(c=0;c<=5;c++)
{
printf("%d\t",d[b][c]);
}
printf("\n");
}
printf("\nSum:\n");
for(b=0;b<=5;b++)
{
for(c=0;c<=5;c++)
{
printf("%d\t",a[b][c]+d[b][c]);
}
printf("\n");
}
}
|
C | #define INCL_DOSPROCESS /* Process and thread values */
#define INCL_DOSERRORS /* DOS error values */
#include <os2.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(USHORT argc, PCHAR argv[] ) {
APIRET rc = NO_ERROR; /* Return code */
TID tidToKill = 0; /* Kill this thread */
if ( argc < 2 ) {
printf("kthread error: Need to pass TID of thread to kill.\n");
return 1;
} else {
tidToKill = (TID) atoi ( argv[1] );
} /* endif */
rc = DosKillThread ( tidToKill ); /* Kill specified thread */
if (rc != NO_ERROR) {
printf("DosKillThread error: return code = %u\n", rc);
return 1;
} else {
printf ("DosKillThread complete.\n");
} /* endif */
return NO_ERROR;
}
|
C | #include <string.h>
#include <time.h>
#include "helpers.h"
#include "shared.h"
#ifndef OPTIONS_H
#define OPTIONS_H
/**
* the index of the cash register array that is occupied by each denomination,
*if there are any of that denomination
**/
enum denom_ind
{
FIVE_CENTS_IND,
TEN_CENTS_IND,
TWENTY_CENTS_IND,
FIFTY_CENTS_IND,
ONE_DOLLAR_IND,
TWO_DOLLAR_IND,
FIVE_DOLLAR_IND,
TEN_DOLLAR_IND
};
enum denom_val
{
FIVE_CENTS_VAL = 5,
TEN_CENTS_VAL = 10,
TWENTY_CENTS_VAL = 20,
FIFTY_CENTS_VAL = 50,
ONE_DOLLAR_VAL = 100,
TWO_DOLLAR_VAL = 200,
FIVE_DOLLAR_VAL = 500,
TEN_DOLLAR_VAL = 1000
};
struct denomination
{
enum denom_ind index;
enum denom_val value;
int count;
};
struct currency
{
int dollars;
int cents;
};
#define NUM_DENOMS 8
#define MAX_CHANGES 50
typedef struct denomination cash_register[NUM_DENOMS];
typedef struct currency change_requests[MAX_CHANGES];
struct falsible_register
{
BOOLEAN success;
cash_register theregister;
};
#define ONE_CHAR 1
enum ttt_board_cell
{
TTT_EMPTY_CELL,
TTT_X_CELL,
TTT_O_CELL,
TTT_INVALID = -1
};
enum ttt_char
{
X_UPPER_CHAR = 'X',
X_LOWER_CHAR = 'x',
O_UPPER_CHAR = 'O',
O_LOWER_CHAR = 'o',
SPACE_CHAR = ' '
};
#define BOARDHEIGHT 3
#define BOARDWIDTH BOARDHEIGHT
enum ttt_result
{
TTT_X,
TTT_O,
TTT_DRAW,
TTT_ONGOING,
TTT_INVALID_RESULT = -1
};
typedef enum ttt_board_cell ttt_board[BOARDHEIGHT][BOARDWIDTH];
void reverse_string(char[]);
void guess_a_number(long);
char* fold(char[], unsigned);
struct falsible_register can_give_change(const cash_register,
const change_requests, int);
BOOLEAN ttt_init_board(ttt_board, const char[]);
enum ttt_result ttt_check_win(ttt_board);
void display_help(void);
#endif
|
C | /* alloc.c -- memory allocation code.
*
* Memory is initialized at the beginning of execution and at the end of
* each resource (spec, body, or combined). No attempt is made to reclaim
* space at any other time.
*/
#include "compiler.h"
typedef struct hunk { /* layout of a hunk of allocated memory */
int used; /* number of bytes in use */
struct hunk *prev; /* pointer to previous hunk */
char data [ALCSIZE]; /* data bytes */
} Hunk;
static Hunk *cur; /* current hunk */
/* initmem () -- [re]initialize memory */
void
initmem ()
{
Hunk *p;
while (cur) { /* return any memory in current use */
p = cur->prev;
free ((char *) cur);
cur = p;
}
nwarnings = nfatals = 0; /* initialize error counts */
initnames (); /* initialize names */
initsig (); /* initialize signatures */
initsym (); /* initialize symbol table */
initprotos (); /* initialize prototype list */
initops (); /* initialize op and class lists */
}
/* ralloc(n) -- allocate n zero bytes with resource lifetime */
char *
ralloc (n)
int n;
{
char *p;
Hunk *h;
n = (n + ALCGRAN - 1) & ~(ALCGRAN - 1); /* round up size */
ASSERT (n <= ALCSIZE);
if (!cur || (cur->used + n > ALCSIZE)) { /* if need new hunk of mem */
h = (Hunk *) alloc (sizeof (Hunk));
h->used = 0;
h->prev = cur;
memset (h->data, 0, ALCSIZE); /* zero the memory */
cur = h;
}
p = cur->data + cur->used;
cur->used += n;
return p;
}
/* rsalloc(s) -- allocate string with resource lifetime.
* If a null pointer is passed, a null pointer is returned.
*/
char *
rsalloc (s)
char *s;
{
if (s)
return strcpy (ralloc (strlen (s) + 1), s);
else
return NULL;
}
|
C | #include <stdio.h>
#include <poll.h>
int main(void)
{
struct pollfd pfds[1]; // More if you want to monitor more
pfds[0].fd = 0; // Standard input
pfds[0].events = POLLIN; // Tell me when ready to read
// If you needed to monitor other things, as well:
//pfds[1].fd = some_socket; // Some socket descriptor
//pfds[1].events = POLLIN; // Tell me when ready to read
printf("Hit RETURN or wait 2.5 seconds for timeout\n");
int num_events = poll(pfds, 1, 2500); // 2.5 second timeout
if (num_events == 0) {
printf("Poll timed out!\n");
} else {
int pollin_happened = pfds[0].revents & POLLIN;
if (pollin_happened) {
printf("File descriptor %d is ready to read\n", pfds[0].fd);
} else {
printf("Unexpected event occurred: %d\n", pfds[0].revents);
}
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.