language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include "libmx.h"
char *mx_file_to_str(const char *file) {
int read_file = open(file, O_RDONLY);
if(read_file < 0)
return NULL;
//чтение - запись
int i = 0;
int size_file = 0;
char buffer[1];
while(read(read_file, buffer, 1)) {
size_file++;
}
if (close(read_file) < 0)
return NULL;
char *str = mx_strnew(size_file);
int read_file2 = open(file, O_RDONLY);
while(size_file) {
read(read_file2, buffer, 1);
str[i] = buffer[0];
i++;
size_file--;
}
if (close(read_file2) < 0)
return NULL;
return str;
}
|
C
|
#include <stdio.h>
void fill_numbers(int n, int* numbers);
void move_numbers(int n, int* numbers);
void delete_numbers(int n, int* numbers);
int main() {
int n = 0;
scanf("%d", &n);
int numbers[128] = {0};
fill_numbers(n, numbers);
while(numbers[2] != 0) {
delete_numbers(n, numbers);
move_numbers(n, numbers);
}
printf("%d\n", numbers[1]);
return 0;
}
void fill_numbers(int n, int* numbers) {
for(int i = 0 ; i <= n ; i++) {
numbers[i] = i;
}
}
void move_numbers(int n, int* numbers) {
for(int i = 0 ; i <= n ; i++) {
if(i % 2 == 0) {
numbers[i/2] = numbers[i];
numbers[i] = 0;
}
}
}
void delete_numbers(int n, int* numbers) {
for(int i = 0 ; i <= n ; i++) {
if(i % 2 == 1) numbers[i] = 0;
}
}
|
C
|
/*
* File: ast.h
* Project: C--_Compiler
* File Created: 2020-02-22
* Author: Zangwei Zheng (zzw@smail.nju.edu.cn)
* -----
* Copyright 2020 NJU, Zangwei Zheng
*/
#ifndef _AST_H
#define _AST_H
typedef struct abstract_syntax_tree{
char name[64];
char original_val[128];
char val[128];
int lineno;
int child_num;
struct abstract_syntax_tree* child[10];
} AST_node;
AST_node* ast_create(char* name, char* original_val, char *val, int lineno);
int ast_append(AST_node* cur, int child_num, ...);
void ast_print(AST_node* root, int depth);
extern AST_node* ast_root;
#define astcmp(i, str) \
(cur->child_num > (i) && strcmp(cur->child[i]->name, #str) == 0)
#endif
/*--------------------------------------------------------------------
* ast.h
*------------------------------------------------------------------*/
|
C
|
/*
** move.c for tekadv in /home/maxence.fourrier/Documents/Project_C/tekadv/src
**
** Made by maxence.fourrier
** Login <maxence.fourrier@epitech.eu>
**
** Started on Mon Sep 11 13:44:10 2017 maxence.fourrier
** Last update Sun Oct 8 11:05:30 2017 maxence.fourrier
*/
#include "explo.h"
sfVector2f get_dir_with_map(sfVector2f dir, sfVector2i size,
sfVector2f pos, int **map)
{
sfVector2f ret;
if (pos.x + dir.x < MAP_BORDER * SPRITE_FLOOR_SIZE
|| pos.x + dir.x >= (size.x - MAP_BORDER) * SPRITE_FLOOR_SIZE)
ret.x = 0;
else
ret.x = dir.x;
if (pos.y + dir.y < MAP_BORDER * SPRITE_FLOOR_SIZE
|| pos.y + dir.y >= (size.y - MAP_BORDER) * SPRITE_FLOOR_SIZE)
ret.y = 0;
else
ret.y = dir.y;
if (ret.x == 0 && ret.y == 0)
{
dir.x = 0;
dir.y = 0;
}
return (ret);
}
void check_move_dir(t_explo *explo, t_placed_mod *placed,
sfVector2f pos, sfVector2f dir)
{
while (placed != NULL)
{
if (pos.x + dir.x >= placed->pos.x
+ explo->game->move_pos[placed->type]->top.x
&& pos.x + dir.x <= placed->pos.x
+ explo->game->move_pos[placed->type]->bot.x
&& pos.y + dir.y >= placed->pos.y
+ explo->game->move_pos[placed->type]->top.y
&& pos.y + dir.y <= placed->pos.y
+ explo->game->move_pos[placed->type]->bot.y)
{
if (pos.x < placed->pos.x
+ explo->game->move_pos[placed->type]->top.x
|| pos.x > placed->pos.x
+ explo->game->move_pos[placed->type]->bot.x)
explo->player->dir.x = 0;
if (pos.y < placed->pos.y
+ explo->game->move_pos[placed->type]->top.y
|| pos.y > placed->pos.y
+ explo->game->move_pos[placed->type]->bot.y)
explo->player->dir.y = 0;
}
placed = placed->next;
}
}
int check_dir(t_explo *explo, sfVector2f dir, sfVector2f pos)
{
if ((dir.x == 0
&& (dir.y <= HIT_SPEED_MIN && dir.y >= -HIT_SPEED_MIN))
|| (dir.y == 0
&& (dir.x <= HIT_SPEED_MIN && dir.x >= -HIT_SPEED_MIN)))
{
explo->player->dir.x = 0;
explo->player->dir.y = 0;
}
else if (((int)pos.x >= explo->player->click.x - PROB_ERROR
&& (int)pos.x <= explo->player->click.x + PROB_ERROR
&& (int)pos.y <= explo->player->click.y + PROB_ERROR
&& (int)pos.y >= explo->player->click.y - PROB_ERROR))
{
explo->player->dir.x = 0;
explo->player->dir.y = 0;
}
else
{
change_move_pos(explo);
return (1);
}
return (SUCCESS);
}
int move(t_explo *explo)
{
sfVector2f dir;
if (check_dir(explo, explo->player->dir, explo->player->pos))
{
check_move_dir(explo, explo->game->placed,
explo->player->pos, explo->player->dir);
if (!(explo->player->dir.x == 0 && explo->player->dir.y == 0))
check_rock_dir(explo, explo->game->rock,
explo->player->pos, explo->player->dir);
dir = get_dir_with_map(explo->player->dir, explo->game->size,
explo->player->pos, explo->game->map);
sfView_move(explo->graph->view, dir);
explo->player->pos = sfView_getCenter(explo->graph->view);
if (!(explo->day->day > NB_HOUR / 2
&& explo->day->day <= NB_HOUR))
break_egg(explo);
}
return (SUCCESS);
}
|
C
|
#include <stdio.h>
#include <stdint.h>
#include "qrcode.h"
void qrcode_print(const QRCode *qrcode) {
printf("\x1b[1;47m ");
for (uint8_t x = 0; x < qrcode->size; x++)
printf(" ");
printf(" \x1b[0m\n");
for (uint8_t y = 0; y < qrcode->size; y++) {
printf("\x1b[1;47m \x1b[40m");
for (uint8_t x = 0; x < qrcode->size; x++) {
if (qrcode_getModule((QRCode *)qrcode, x, y)) {
printf(" ");
} else {
printf("\x1b[1;47m \x1b[40m");
}
}
printf("\x1b[1;47m \x1b[0m\n");
}
printf("\x1b[1;47m ");
for (uint8_t x = 0; x < qrcode->size; x++)
printf(" ");
printf(" \x1b[0m\n");
}
|
C
|
#include <stdio.h> // printf
#include <stdlib.h> // malloc
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
/* 本题难点在对函数参数的理解上
* 建议nums加const修饰,表示入参不可修改
* returnSize这个应该是出参
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
for(int i=0;i<numsSize-1;i++)
{
for(int j=i+1;j<numsSize;j++)
{
if((nums[i] + nums[j]) == target)
{
int* ret = malloc(sizeof(int)*2);
ret[0] = i;
ret[1] = j;
*returnSize = 2;
return ret;
}
}
}
*returnSize = 0;
return NULL;
}
int main(){
// 创建整数数组
int numsSize = 4;
int nums[4] = {1,7,1,2};
int target = 20;
int* ret;
int returnSize;
ret = twoSum(nums,numsSize,target,&returnSize);
if (ret!=NULL)
{
printf("the result is: %d,%d\n",ret[0],ret[1]); // the result is: 1,3
// printf("the result is: %d,%d\n",*ret,*(ret++)); // the result is: 3,1
}
else
{
printf("the result is NULL\n");
}
}
/* 本题涉及C语言知识点:函数如何返回数组(指针)
参考:https://segmentfault.com/q/1010000018689506/a-1020000018689706
数组名实际上就是指针,因此返回数组就是返回一个指针。但有一点要特别注意的是:不要返回指向局部变量的指针或引用
局部变量的生命周期仅限于定义它的函数作用域内,离开函数局部变量就无效了,此时再通过指针访问该变量将导致不可预
知的结果。
通常解决这个问题的方式有两种:
1.将数组声明为静态的
2.使用malloc()动态分配内存
*/
|
C
|
/**
* \file gpio_hal.h
* \copyright Copyright (c) 2017 Verizon. All rights reserved.
* \brief Hardware abstraction layer for GPIO pins
* \details This header defines a platform independent API to read and write
* GPIO pins. It also offers a utility routine to control the power to the GPIO
* submodule. GPIO interrupts are not handled as a part of this API.
*/
#ifndef GPIO_HAL_H
#define GPIO_HAL_H
#include "port_pin_api.h"
/**
* \brief Type that represents a bit value.
*/
typedef enum bit_value {
PIN_HIGH, /**< Logical HIGH */
PIN_LOW /**< Logical LOW */
} bit_value_t;
/**
* \brief Configure the pin to act as GPIO.
* \details This function must be called on the given pin prior to calling any
* other GPIO HAL routines. Failing to do so may result in undefined behavior.
*
* \param[in] config Pointer to a \ref gpio_config_t data structure describing
* the pin configuration
* \param[in] pin_name Name of the pin
*
* \retval true Pin was initialized successfully
* \retval false Failed to initialize the pin as GPIO
*/
bool gpio_init(pin_name_t pin_name, const gpio_config_t *config);
/**
* \brief Read the value of the GPIO pin.
* \param[in] pin_name Name of the pin to be read
* \retval PIN_HIGH The pin held at logical HIGH
* \retval PIN_LOW The pin is held at logical LOW
* \pre \ref gpio_init must be called on this pin before reading from it.
*/
bit_value_t gpio_read(pin_name_t pin_name);
/**
* \brief Write a value to the GPIO pin.
* \param[in] pin_name Name of the pin to be written to
* \param[in] bit Bit value that needs to be written to the GPIO
* \pre \ref gpio_init must be called on this pin before writing to it.
*/
void gpio_write(pin_name_t pin_name, bit_value_t bit);
/**
* \brief Turn on or off the power to the GPIO port associated with the pin.
* \param[in] pin_name Name of the pin
* \param[in] state \arg Set to \b true to turn on the power
* \arg Set to \b false to turn off the power
* \pre \ref gpio_init must be called on this pin before reading from it.
*/
void gpio_pwr(pin_name_t pin_name, bool state);
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* print_path.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: francis <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/04/08 16:49:52 by francis #+# #+# */
/* Updated: 2020/05/11 09:58:46 by francis ### ########.fr */
/* */
/* ************************************************************************** */
#include "lem_in.h"
void print_all_links(t_graph *graph)
{
size_t i;
i = 0;
while (i < graph->size)
{
ft_printf("---------------Node %d--------------\n", i);
print_link_available(graph->array[i]);
i++;
}
}
void print_path(t_path *path)
{
t_path *tmp;
if (path != NULL)
{
ft_printf("BFS path found:\n");
tmp = path;
ft_printf("Path: ");
while (tmp != NULL)
{
if (tmp->vertex == 0)
{
ft_printf("len = %d\t", tmp->len);
ft_printf("%d", tmp->vertex);
}
else
ft_printf(" -> %d", tmp->vertex);
tmp = tmp->next;
}
ft_printf("\n");
}
}
void print_all_path(t_darray *all_path)
{
t_path *path;
size_t i;
i = 0;
ft_printf("{c_green}------------ Path sequence --------------{c_end}\n");
while (i <= all_path->end)
{
path = all_path->contents[i];
if (path != NULL)
{
print_path(path);
ft_printf("Path length = %d\n\n", path->len);
}
i++;
}
}
void print_all_path_len(t_darray *all_path)
{
t_path *path;
size_t i;
i = 0;
ft_printf("{c_green}------------ Path sequence ----------------{c_end}\n");
while (i <= all_path->end)
{
path = all_path->contents[i];
if (path != NULL)
ft_printf("Path length = %d\t|\t", path->len);
else
ft_printf("\tNULL\t\t|\t");
if ((i + 1) % 7 == 0)
ft_printf("\n");
i++;
}
ft_printf("\n");
}
void print_all_solution(t_lemin *lemin)
{
t_solution *begin;
begin = lemin->result;
while (lemin->result != NULL)
{
ft_printf("{c_blue}------------ Path sequence ------------{c_end}\n");
print_all_path(lemin->result->path);
lemin->result = lemin->result->next;
}
lemin->result = begin;
rewind_solution(lemin);
}
|
C
|
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void *my_entry_function(void *param)
{
int* value = (int*) param;
while (--(*value)) /* NOP */ ;
printf("Finished decrementing x\n");
return NULL;
}
int main()
{
srand(time(NULL));
int x = rand() % (1000 * 1000); // Random initial value
int y = rand() % (1000 * 1000); // Random initial value
printf("x = %d, y = %d\n", x, y);
// Create a thread that decrements the x parameter
pthread_t thread0;
pthread_create(&thread0, NULL, my_entry_function, &x);
// Decrement the y parameter in the main thread.
while (--y) /* NOP */ ;
printf("Finished decrementing y\n");
pthread_join(thread0, NULL);
printf("Joined the x decrementer thread\n");
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int a[5], i, j, temp;
printf("Enter 5 Element: \n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct student
{
int number;//学号
char name[1024];//姓名
int dailyScore;//平时成绩
int generalSocre;//实验成绩
int finalSocre;//期末成绩
int score;//总成绩
int place;//名词
};
void main()
{
struct student stu[0]={2017000001 "姚期智" 90 85 98 0 0};
struct student stu[1]={2017000002 "周光远" 85 87 92 0 0};
struct student stu[2]={2017000003 "孙家栋" 89 84 96 0 0};
struct student stu[3]={2017000004 "杨芙清" 95 76 98 0 0};
struct student stu[4]={2017000005 "张朝阳" 78 80 88 0 0};
struct student stu[5]={2017000007 "李彦弘" 82 90 85 0 0};
int i;
//填入总成绩
for(i=0;i<6;i++){
stu[i].score=stu[i].dailyScore*0.2+stu[i].generalSocre*0.2+ stu[i].finalSocre;
}
//冒泡排序进行名次排序
int t,k,p;
int j=0;
for(k=0;k<6;k++){
stu[k].place=k+1;
for(j=k;j<6;j++){
if(stu[j].score > stu[k].score){
stu[j].place=stu[k].place;
stu[k].place=stu[j].place+1;
}
}
}//(youwenti)
//第二题打印出学生信息
printf("学号: 姓名:平时成绩:实验成绩:期末成绩:总成绩 排名:\n");
for (i = 0; i < 6; i++){
printf("%d,%s,%d ,%d,%d,%d,%d /n", stu[i].number,stu[i].name,stu[i].dailyScorescore,generalScore[i],stu[i].finalScore,stu[i].score,stu[i].place);
printf("\n");
}
//第三题根据学号看排名
int n;
printf("print in number");
scanf(%d,&p);
for(n=0;n<6;n++){
if(stu[i].number==p){
printf(%d\n",stu[i].place);
}
}
//第四题求方差和均值
int variance l ;
int average h;
int he=0;
int x=0;
for(h=1;h<6;h++){
he=stu[h].score+he;
}
average=he/6;
for(l=0;l<6;l++){
x=(averge-stu[l].score)*(averge-stu[l].score)+x;
}
variance=x/6;
|
C
|
/*
** EPITECH PROJECT, 2018
** nf.sh
** File description:
** nf
*/
#include <unistd.h>
#include <stdlib.h>
int get_modulo(int len_nb)
{
int modulo = 1;
for (int i = 0; i < len_nb; i++)
modulo *= 10;
return (modulo);
}
int my_power(int index, int base)
{
int value = 1;
for (int i = 0; i < index; i++)
value *= base;
return (value);
}
int get_sizenb(int nb)
{
int maxv = 1;
int i = 0;
for (; nb >= maxv; i++)
maxv *= 10;
return (i);
}
int my_getnbr(char const *str)
{
int i = 0;
int len_nb = 0;
int nb = 0;
int neg = 1;
int count = 0;
if (str == NULL)
return (-84);
for (len_nb = 0; str[len_nb] && str[len_nb] >= '0' && str[len_nb] <= '9';
len_nb++, count++);
if (str[0] == '-')
neg = -1;
for (int modulo = get_modulo(count - 1); modulo >= 0 && str[i] &&
str[i] >= '0' && str[i] <= '9'; i++, modulo /= 10)
nb += (str[i] - 48) * modulo;
return (nb * neg);
}
char *int_to_char(int nb)
{
int len_nb = get_sizenb(nb);
char *nb_ret = malloc(sizeof(char) * (len_nb + 1));
for (int mod = my_power(len_nb - 1, 10), i = 0; mod > 0; mod /= 10, i++) {
nb_ret[i] = (nb / mod);
if (nb > 10)
nb -= mod * (nb_ret[i] - '0');
nb_ret[i + 1] = '\0';
}
return (nb_ret);
}
|
C
|
/*
* COAL Video Lecture: 45
* Programmer: Arif Butt
* ex1.c: A sample C program that calls an assembly function from proc1.o
* compile: gcc -c ex1.c
* link: gcc ex1.o proc1.o -o myexe
* usage: ./myexe
*/
#include <stdio.h>
#include <stdlib.h>
extern long maxofthree(long, long, long);
int main() {
printf("maxofthree(15,-23,7) = %ld\n", maxofthree(15, -23, 7));
printf("maxofthree(10,5,24) = %ld\n", maxofthree(10, 5, 24));
printf("maxofthree(-19,-138,-10) = %ld\n", maxofthree(-19, -138, -10));
return 0;
}
|
C
|
#include <stdio.h>
int main() {
long long sumOfSquares = 0;
long long squareOfSums = 0;
int i;
for (i = 1; i <= 100; i++) {
sumOfSquares += i*i;
squareOfSums += i;
}
squareOfSums *= squareOfSums;
squareOfSums -= sumOfSquares;
printf("%lld\n", squareOfSums);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
int bus,kelas,i,n;
//Deklarasi untuk Outpus Pesan
char Nama[100][100],Jenis[100][100],Bus[100][100],Jalur[100][100];
int NoKursi[100],Nik[100];
//Deklarasi Login/Registrasi
struct akun{
char nama[100], username[100], password[100];
int umur;
};struct akun asliAkun, tempAkun[100]; //pendeklarasian struct akun
//Deklarasi Data PenumpNG
struct DataPenumpang{
int harga,total,nokursi,NIK;
char nama[100];
char jalur[100];
char jenis[100],bus[100];
};struct DataPenumpang penumpang, temppenumpang[100]; //deklarasi data penumpang
void registrasiAkun() //operasifile registrasi akun
{
system("cls");
TampilanAwal();
FILE *user;
user = fopen("User.txt", "a+");
printf(" Masukkan Username : "); fflush(stdin);
gets(asliAkun.username);
printf(" Masukkan Password : ");
gets(asliAkun.password);
printf(" Masukkan Nama Anda : ");
gets(asliAkun.nama);
printf(" Masukkan Umur Anda : ");
scanf("%d", &asliAkun.umur);
i = 0;
n = 0;
int kondisi=0;
while(!feof(user))
{
fscanf(user, "%[^#]#%[^#]#%[^#]#%d\n", &tempAkun[i].username, &tempAkun[i].password, &tempAkun[i].nama, &tempAkun[i].umur);
n++;
i++;
}
for(i=0;i<n;i++){
if (strcmp(asliAkun.username,tempAkun[i].username)==0){
kondisi=0;
} else
kondisi=1;
}
if (kondisi==0){
printf(" Maaf username yang anda masukkan sudah ada\n");
printf(" Silahkan menggunakan username lain\n");
system("pause");
registrasiAkun();}
else{
fprintf(user, "%s#%s#%s#%d\n", asliAkun.username, asliAkun.password, asliAkun.nama, asliAkun.umur);}
fclose(user);
//Back to menu
menuUtama();
}
void loginAkun() //login akun
{
system("cls");
TampilanAwal();
int i, n;
FILE *user;
user = fopen("User.txt", "r");
/*Pembacaan File User.txt*/
i = 0;
n = 0;
if (!user){
printf("Tidak ada File (Silahkan Registrasi dulu)\n");
system("pause");
menuUtama();
}else{
while(!feof(user)) {
fscanf(user, "%[^#]#%[^#]#%[^#]#%d\n", &tempAkun[i].username, &tempAkun[i].password, &tempAkun[i].nama, &tempAkun[i].umur);
n++;
i++;
}
fclose(user);
/*End of read File User.txt*/
char usernameLogin[100], passwordLogin[100];
printf(" Masukkan Username: ");
gets(usernameLogin);
printf(" Masukkan Passord: ");
gets(passwordLogin);
/*Pencarian username dan password*/
int kondisi = 0; //variabel sementara untuk kondisi perulangan
for(i=0; i<n; i++)
{
if(strcmp(usernameLogin, tempAkun[i].username) == 0 && strcmp(passwordLogin, tempAkun[i].password) == 0)
{
//Aksi Selanjutnya jika berhasil
printf("===================================================\n");
printf(" ~ SELAMAT DATANG %s ~\n", tempAkun[i].nama);
printf("===================================================\n");
system("pause");
kondisi = 0;
break; //Jangan lupa untuk break, karena kalau tidak dia akan kembali pada perulangan ini
}
else{
kondisi = 1; //kondisi jika gagal login
}
}
/*Akhir dari pencarian username dan password */
if(kondisi != 0)//JIka data tidak ada
{
printf("\n---------------------------------------------------------------------------\n");
printf("Username atau Password tidak terdaftar silahkan Registrasi Terlebih dahulu!\n\n");
system("pause");
menuUtama(); //kembali ke MenuUtama
}
}
}
void menuUtama() //Pemilihan menu untuk registrasi & login
{
system("cls");
TampilanAwal();
int pilihanMenuUtama;
printf(
" Silahkan Login/Registrasi Terlebih Dahulu\n\n"
" 1. Registrasi\n"
" 2. Login\n"
" 3. Keluar\n"
);
printf("------------------------------------------\n");
printf("\n Masukkan menu yang anda inginkan: ");
scanf("%d", &pilihanMenuUtama);
fflush(stdin);
switch(pilihanMenuUtama)
{
case 1: registrasiAkun();break;
case 2: loginAkun();break;
default : exit(0);
}
}
void PemilihanData() //Pemilihan setelah berhasil login
{
system("cls");
int pilihan;
TampilanAwal();
printf("\n 1. Pemesanan Tiket\n");
printf(" 2. Data Penumpang\n");
printf(" 3. Keluar \n\n");
printf("-------------------------------------------\n");
printf(" Pilih Fitur Yang Ingin Digunakan: ");
scanf("%d",&pilihan);
if (pilihan==1) Pemesanan();
else if(pilihan==2){
OutputData();
}
else exit(0);
}
void DaftarBus1() //Data bus Bandung - Jakart
{
system("cls");
TampilanAwal();
printf("\t-----------------------------------------\n");
printf("\tDaftar Harga Bus Bandung - Jakarta\n");
printf("\t-----------------------------------------\n");
printf("\t\t|1.Eksekutif\t| Rp 100.000\n\t1.Bus A\t|2.Bisnis\t| Rp 89.900\n\t\t|3.Ekonomi\t| Rp 76.000\n");
printf("\t-----------------------------------------\n");
printf("\t\t|1.Eksekutif\t| Rp 99.000\n\t2.Bus B\t|2.Bisnis\t| Rp 88.900\n\t\t|3.Ekonomi\t| Rp 75.500\n");
printf("\t-----------------------------------------\n");
printf("\t\t|1.Eksekutif\t| Rp 95.000\n\t3.Bus C\t|2.Bisnis\t| Rp 80.000\n\t\t|3.Ekonomi\t| Rp 70.000\n");
printf("\t-----------------------------------------\n");
printf("\tNB: Pembelian Lebih Dari 5 Tiket Akan Mendapat Bonus Sebesar 10 persen\n\n");
printf("\tPilihan Bus : ");scanf("%d",&bus); //Pemilihan Bus
printf("\tTentukan Kelas : ");scanf("%d",&kelas); //Pemilihan Kelas
printf(" Masukkan Banyak Penumpang : ");scanf("%d",&n); //Input banyak penumpang
if (bus==1){
strcpy(penumpang.bus,"Bus A");
switch(kelas){
case 1 :
penumpang.harga=100000;
strcpy(penumpang.jenis,"Eksekutif");
if (n>=5) //Jika Penumpang lebih dari 5 maka akan mendapat diskon
penumpang.total=HargaDiskon(penumpang.harga,n);
else //Jika kurang dari 5 tidak mendapat diskon
HargaTotal(&penumpang.total,penumpang.harga,n);break;
case 2 :
penumpang.harga=89900;
strcpy(penumpang.jenis,"Bisnis");
if (n>=5)
penumpang.total=HargaDiskon(penumpang.harga,n);
else
HargaTotal(&penumpang.total,penumpang.harga,n);break;
case 3 :
penumpang.harga=76000;
strcpy(penumpang.jenis,"Ekonomi");
if (n>=5)
penumpang.total=HargaDiskon(penumpang.harga,n);
else
HargaTotal(&penumpang.total,penumpang.harga,n);
}
}else if (bus==2){
strcpy(penumpang.bus,"Bus B");
switch(kelas){
case 1 :
penumpang.harga=99000;
strcpy(penumpang.jenis,"Eksekutif");
if (n>=5)
penumpang.total=HargaDiskon(penumpang.harga,n);
else
HargaTotal(&penumpang.total,penumpang.harga,n);break;
case 2 :
penumpang.harga=88900;
strcpy(penumpang.jenis,"Bisnis");
if (n>=5)
penumpang.total=HargaDiskon(penumpang.harga,n);
else
HargaTotal(&penumpang.total,penumpang.harga,n);break;
case 3 :
penumpang.harga=75500;
strcpy(penumpang.jenis,"Ekonomi");
if (n>=5)
penumpang.total=HargaDiskon(penumpang.harga,n);
else
HargaTotal(&penumpang.total,penumpang.harga,n);
}
}else if (bus==3){
strcpy(penumpang.bus,"Bus C");
switch(kelas){
case 1 :{
penumpang.harga=95000;
strcpy(penumpang.jenis,"Eksekutif");
if (n>=5)
penumpang.total=HargaDiskon(penumpang.harga,n);
else
HargaTotal(&penumpang.total,penumpang.harga,n);break;}
case 2 :{
penumpang.harga=80000;
strcpy(penumpang.jenis,"Bisnis");
if (n>=5)
penumpang.total=HargaDiskon(penumpang.harga,n);
else
HargaTotal(&penumpang.total,penumpang.harga,n);break;}
case 3 :{
penumpang.harga=70000;
strcpy(penumpang.jenis,"Ekonomi");
if (n>=5)
penumpang.total=HargaDiskon(penumpang.harga,n);
else
HargaTotal(&penumpang.total,penumpang.harga,n);}
}
}
}
void DaftarBus2() //Data bus Bandung-Surabaya
{
system("cls");
TampilanAwal();
printf("\t-----------------------------------------\n");
printf("\tDaftar Harga Bus Bandung - Surabaya\n");
printf("\t-----------------------------------------\n");
printf("\t1.Bus A\t|Eksekutif\t| Rp 260.000\t|\n");
printf("\t-----------------------------------------\n");
printf("\t2.Bus B\t|Eksekutif\t| Rp 270.000\t|\n");
printf("\t-----------------------------------------\n");
printf("\tNB: Pembelian Lebih Dari 5 Tiket Akan Mendapat Bonus Sebesar 10 persen\n\n");
printf("\tTentukan Pilihan Anda : "); scanf("%d",&bus); //pemilihan Bus
printf(" Masukkan Banyak Penumpang : ");scanf("%d",&n);//Input banyak penumpang
if (bus==1) {
strcpy(penumpang.bus,"Bus A");
penumpang.harga=260000;
strcpy(penumpang.jenis,"Eksekutif");
if (n>=5){ //Jika Penumpang lebih dari 5 maka akan mendapat diskon
penumpang.total=HargaDiskon(penumpang.harga,n);}
else{
HargaTotal(&penumpang.total,penumpang.harga,n);}
}else if(bus==2){
strcpy(penumpang.bus,"Bus B");
penumpang.harga=270000;
strcpy(penumpang.jenis,"Eksekutif");
if (n>=5){ //Jika Penumpang lebih dari 5 maka akan mendapat diskon
penumpang.total=HargaDiskon(penumpang.harga,n);}
else{
HargaTotal(&penumpang.total,penumpang.harga,n);}
}
}
void DaftarBus3() //Data Bus Bandung-Yogyakarta
{
system("cls");
TampilanAwal();
printf("\t-----------------------------------------\n");
printf("\tDaftar Harga Bus Bandung - Yogyakarta\n\n");
printf("\t-----------------------------------------\n");
printf("\t\t|1.Eksekutif\t| Rp 200.000\n\t1.Bus A\t|2.Bisnis\t| Rp 180.000\n\t\t|\n");
printf("\t-----------------------------------------\n");
printf("\t\t|1.Eksekutif\t| Rp 160.000\n\t2.Bus B\t|2.Bisnis\t| Rp 152.000\n\t\t|3.Ekonomi\t| Rp 135.000\n");
printf("\t-----------------------------------------\n");
printf("\t\t|1.Eksekutif\t| Rp 159.000\n\t3.Bus C\t|2.Bisnis\t| Rp 148.000\n\t\t|3.Ekonomi\t| Rp 126.000\n");
printf("\t-----------------------------------------\n");
printf("\tNB: Pembelian Lebih Dari 5 Tiket Akan Mendapat Bonus Sebesar 10 persen\n\n");
printf("\tPilihan Bus : ");scanf("%d",&bus);
printf("\tTentukan Kelas : ");scanf("%d",&kelas);
printf(" Masukkan Banyak Penumpang : ");scanf("%d",&n);
if (bus==1){
strcpy(penumpang.bus,"Bus A");
switch(kelas){
case 1 : {
penumpang.harga=200000;
strcpy(penumpang.jenis,"Eksekutif");
if (n>=5){ //Jika Penumpang lebih dari 5 maka akan mendapat diskon
penumpang.total=HargaDiskon(penumpang.harga,n);}
else{
HargaTotal(&penumpang.total,penumpang.harga,n);}break;}
case 2 :{
penumpang.harga=180000;
strcpy(penumpang.jenis,"Bisnis");
if (n>=5){ //Jika Penumpang lebih dari 5 maka akan mendapat diskon
penumpang.total=HargaDiskon(penumpang.harga,n);}
else{
HargaTotal(&penumpang.total,penumpang.harga,n);}}
}
}else if (bus==2){
strcpy(penumpang.bus,"Bus B");
switch(kelas){
case 1 :{
penumpang.harga=160000;
strcpy(penumpang.jenis,"Eksekutif");
if (n>=5){ //Jika Penumpang lebih dari 5 maka akan mendapat diskon
penumpang.total=HargaDiskon(penumpang.harga,n);}
else{
HargaTotal(&penumpang.total,penumpang.harga,n);}break;}
case 2 :{
penumpang.harga=152000;
strcpy(penumpang.jenis,"Bisnis");
if (n>=5){ //Jika Penumpang lebih dari 5 maka akan mendapat diskon
penumpang.total=HargaDiskon(penumpang.harga,n);}
else{
HargaTotal(&penumpang.total,penumpang.harga,n);}break;}
case 3 :{
penumpang.harga=135000;
strcpy(penumpang.jenis,"Ekonomi");
if (n>=5){ //Jika Penumpang lebih dari 5 maka akan mendapat diskon
penumpang.total=HargaDiskon(penumpang.harga,n);}
else{
HargaTotal(&penumpang.total,penumpang.harga,n);}}
}
}else if (bus==3){
strcpy(penumpang.bus,"Bus C");
switch(kelas){
case 1 :{
penumpang.harga=159000;
strcpy(penumpang.jenis,"Eksekutif");
if (n>=5) //Jika Penumpang lebih dari 5 maka akan mendapat diskon
penumpang.total=HargaDiskon(penumpang.harga,n);
else
HargaTotal(&penumpang.total,penumpang.harga,n);break;}
case 2 :{
penumpang.harga=148000;
strcpy(penumpang.jenis,"Bisnis");
if (n>=5) //Jika Penumpang lebih dari 5 maka akan mendapat diskon
penumpang.total=HargaDiskon(penumpang.harga,n);
else
HargaTotal(&penumpang.total,penumpang.harga,n);break;}
case 3 :{
penumpang.harga=126000;
strcpy(penumpang.jenis,"Ekonomi");
if (n>=5) //Jika Penumpang lebih dari 5 maka akan mendapat diskon
penumpang.total=HargaDiskon(penumpang.harga,n);
else
HargaTotal(&penumpang.total,penumpang.harga,n);}
}
}
}
void Pemesanan() //Pemilihan Rute Bus
{
system("cls");
int rute;
TampilanAwal();
printf("-------------------------------\n");
printf("| Rute Bus |\n");
printf("-------------------------------\n");
printf("| 1. Bandung - Jakarta |\n");
printf("| 2. Bandung - Surabaya |\n");
printf("| 3. Bandung - Yogyakarta |\n");
printf("-------------------------------\n\n");
printf("\nSilahkan Pilih Rute Anda: ");
scanf("%d",&rute);
switch(rute){
case 1 : strcpy(penumpang.jalur,"Bandung-Jakarta");DaftarBus1();break;
case 2 : strcpy(penumpang.jalur,"Bandung-Jakarta");DaftarBus2();break;
case 3 : strcpy(penumpang.jalur,"Bandung-Yogyakarta");DaftarBus3();
}
}
// Perhitungan Harga Total Tiket
int HargaTotal(int *hasil,int harga, int banyak)
{
*hasil=harga*banyak;
return *hasil;
}
//Perhitungan Harga Total Tiket dengan Diskon 10%
int HargaDiskon(int Harga, int Banyak)
{
int Total;
Harga=Harga*Banyak;
Total=Harga-(Harga*10/100);
return Total;
}
void InputData() //Perintah input data penumpang pada file penumpang
{
system("cls");
TampilanAwal();
printf("\n------------------------------------------------------\n");
for(i=0;i<n;i++){
FILE *Penumpang;
Penumpang = fopen("Penumpang.txt", "a");
printf("%d\tMasukkan Nama : ",i+1);fflush(stdin);
gets(penumpang.nama);
printf("\tMasukkan Nomor Kursi : ",i+1);
scanf("%d",&penumpang.nokursi);
printf("\tMasukkan NIK : ",i+1);
scanf("%d",&penumpang.NIK);
printf("----------------------------------------------------\n");
fprintf(Penumpang, "%s#%s#%s#%s#%d#%d\n",penumpang.nama,penumpang.jalur,penumpang.bus,penumpang.jenis,penumpang.NIK,penumpang.nokursi);
//Pengisian data pada variabel sementara untuk OutputPesan
strcpy(Nama[i],penumpang.nama);
strcpy(Jenis[i],penumpang.jenis);
strcpy(Bus[i],penumpang.bus);
strcpy(Jalur[i],penumpang.jalur);
NoKursi[i]=penumpang.nokursi;
Nik[i]=penumpang.NIK;
fclose(Penumpang);
}
}
void OutputData() //Output data pada PemilihanData Data Penumpang
{
system("cls");
TampilanAwal();
int i, n;
FILE *Penumpang;
Penumpang = fopen("Penumpang.txt", "r");
if (!Penumpang){
printf(" File data penumpang tidak ada\n");
printf(" Silahkan lakukan pemesanan terlebih dahulu\n\n");
system("pause");
PemilihanData();
}
else{
/*Pembacaan File Penumpang.txt*/
i = 0;
n = 0;
while(!feof(Penumpang))
{
fscanf(Penumpang, "%[^#]#%[^#]#%[^#]#%[^#]#%d#%d\n",&temppenumpang[i].nama,&temppenumpang[i].jalur,&temppenumpang[i].bus,&temppenumpang[i].jenis,&temppenumpang[i].NIK,&temppenumpang[i].nokursi);
n++;
i++;
}
fclose(Penumpang); /*End of read File Penumpang.txt*/
for(i=0;i<n;i++){
printf("%d\tNo Kursi : %d\n",i+1,temppenumpang[i].nokursi);
printf("\tNama : %s\n",temppenumpang[i].nama);
printf("\tNIK : %d\n",temppenumpang[i].NIK);
printf("\tJalur : %s\n",temppenumpang[i].jalur);
printf("\tJenis Kereta : %s %s\n",temppenumpang[i].bus,temppenumpang[i].jenis);
}
system("pause");
system("cls");
TampilanAwal();
int cari,pass;
printf("---------------------------------------\n");
printf("| 1. Urutkan Berdasarkan Nomor Kursi |\n");
printf("| 2. Cari Data Berdasarkan NIK |\n");
printf("---------------------------------------\n");
printf(" Pilih Fitur: ");
scanf("%d",&cari);
//Proses Sorting
if (cari==1){
system("cls");
TampilanAwal();
//selection sort
for (pass = 0; pass < n; ++pass){
for (i = pass + 1; i < n; ++i){
if (temppenumpang[pass].nokursi > temppenumpang[i].nokursi){
penumpang = temppenumpang[ pass ];
temppenumpang[pass] = temppenumpang[i];
temppenumpang[i] = penumpang;
}
}
}
printf("\n Data Diurutkan Berdasarkan Nomor Kursi :\n");
printf("---------------------------------------------\n");
for (i= 0; i < n; ++i){
printf("%d\tNo Kursi : %d\n",i+1,temppenumpang[i].nokursi);
printf("\tNama : %s\n",temppenumpang[i].nama);
printf("\tNIK : %d\n",temppenumpang[i].NIK);
printf("\tJalur : %s\n",temppenumpang[i].jalur);
printf("\tJenis Kereta : %s %s\n",temppenumpang[i].bus,temppenumpang[i].jenis);
}
system("pause");
PemilihanData();}
//Proses Searching binary
else if (cari==2){
system("cls");
TampilanAwal();
int idx,low,high,mid;
//selection sort
for (pass = 0; pass < n; ++pass){
for (i = pass + 1; i < n; ++i){
if (temppenumpang[pass].NIK > temppenumpang[i].NIK){
penumpang = temppenumpang[ pass ];
temppenumpang[pass] = temppenumpang[i];
temppenumpang[i] = penumpang;}
}}
printf(" Data diurutkan berdasarkan NIK \n");
printf("--------------------------------------------------\n");
for (i= 0; i < n; ++i){
printf("%d\tNo Kursi : %d\n",i+1,temppenumpang[i].nokursi);
printf("\tNama : %s\n",temppenumpang[i].nama);
printf("\tNIK : %d\n",temppenumpang[i].NIK);
printf("\tJalur : %s\n",temppenumpang[i].jalur);
printf("\tJenis Kereta : %s %s\n",temppenumpang[i].bus,temppenumpang[i].jenis);}
printf("--------------------------------------------------\n");
printf(" Cari data dengan NIK : ");
scanf("%d",&cari);
printf("-----------------------------\n");
low=1; high=n; idx=0;
while((low<=high)&&(idx==0)){
mid=(low+high)/2;
if (temppenumpang[mid].NIK==cari)
idx=mid;
else if (temppenumpang[mid].NIK<cari)
low=mid+1;
else high=mid-1;}
if (idx>=0) printf("\n Data ditemukan pada Nomor :%2d\n\n",idx+1);
else printf("\n Data tidak ditemukan"); system("pause");
PemilihanData();
}
}
}
void OutputPesan() //Output Data pada PemilihanData Pemesanan
{
system("cls");
TampilanAwal();
printf("------------------------------------------------\n");
for (i=0;i<n;i++){
printf("%d\tNo Kursi : %d\n",i+1,NoKursi[i]);
printf("\tNama : %s\n",Nama[i]);
printf("\tNIK : %d\n",Nik[i]);
printf("\tJalur : %s\n",Jalur[i]);
printf("\tJenis Kereta : %s %s\n",Bus[i],Jenis[i]);
}
printf("------------------------------------------------\n");
//Output jika mendapatkan diskon 10%
if(n>=5) printf("\tSelamat Anda Mendapat Diskon 10 persen\n");
printf("\tHarga Total Tiket : Rp %d\n\n\n",penumpang.total);
system("pause");
PemilihanData();
}
//Program Utama
int main()
{
TampilanAwal();
printf(" SELAMAT DATANG DI\n");
printf(" APLIKASI MANAJEMEN PEMESANAN TIKET BUS\n\n");
printf(" \t Oleh:\n");
printf(" \t Muhammad Faisal Hidayatullah\n\t Taufiq Salman Sya'bani\n\n");
printf(" \t Teknik Komputer 43-03\n\n");
system("pause");
menuUtama();
PemilihanData();
InputData();
OutputPesan();
return 0;
}
//Header pada aplikasi
void TampilanAwal()
{
printf(" ======================= \n");
printf(" ====================================\n");
printf(" || PEMESANAN TIKET BUS INDONESIA ||\n");
printf(" ====================================\n\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
double convert_age(int years)
{
double cf = 3.156e7;
return (cf * years);
}
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("Hey, pass an integer as argument.\n");
return 1;
}
int years = atoi(argv[1]);
printf("Your age in seconds is %f.\n", convert_age(years));
return 0;
}
|
C
|
/*---------------------------------------------------------------------------------------
* FileName:Knapsack.c
* author:doodlesomething@163.com
* date:1-5-2014
* version:1.0
* description:0-1背包问题
-------------------------------------------------------------------------------------------*/
#include <stdio.h>
int count[5][20];
int max(int a,int b) {
return a > b ? a : b;
}
/*
* @description:0-1背包问题
* @param int weight[] 各个物品的重量
* @param int price[] 各个物品的价格
* @param int cap 背包容量
* @param int n 总的物品数量
*/
int Knapsack(int weight[],int price[],int cap,int n) {
int i,j;
//01背包问题,初始化
for(i = 0; i < 5; i++)
for(j = 0; j < 20; j++)
count[i][j] = 0;
for(i = 1; i <= n ; i++) {
for(j = 1; j <= cap; j++) {
if(weight[i] > j)
count[i][j] = count[i - 1][j];
else
count[i][j] = max(count[i - 1][j], count[i - 1][j - weight[i]] + price[i]);
}
}
return count[n][cap];
}
int main(void) {
int i,j;
int weight[] = {0,3,4,7,8,9};
int price[] = {0,4,5,10,11,13};
int result = Knapsack(weight,price,20,5);
printf("total:%d\n",result);
return 0;
}
|
C
|
/*
* CS 261 Assignment 5
* Name: Christian Roccanova
* Date: 8/5/2017
*/
#include "dynamicArray.h"
#include "task.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
/**
* Loads into heap a list from a file with lines formatted like
* "priority, name".
* @param heap
* @param file
*/
void listLoad(DynamicArray* heap, FILE* file)
{
const int FORMAT_LENGTH = 256;
char format[FORMAT_LENGTH];
snprintf(format, FORMAT_LENGTH, "%%d, %%%d[^\n]", TASK_NAME_SIZE);
Task temp;
while (fscanf(file, format, &temp.priority, &temp.name) == 2)
{
dyHeapAdd(heap, taskNew(temp.priority, temp.name), taskCompare);
}
}
/**
* Writes to a file all tasks in heap with lines formatted like
* "priority, name".
* @param heap
* @param file
*/
void listSave(DynamicArray* heap, FILE* file)
{
for (int i = 0; i < dySize(heap); i++)
{
Task* task = dyGet(heap, i);
fprintf(file, "%d, %s\n", task->priority, task->name);
}
}
/**
* Prints every task in heap.
* @param heap
*/
void listPrint(DynamicArray* heap)
{
DynamicArray* temp = dyNew(1);
dyCopy(heap, temp);
while (dySize(temp) > 0)
{
Task* task = dyHeapGetMin(temp);
printf("\n");
taskPrint(task);
printf("\n");
dyHeapRemoveMin(temp, taskCompare);
}
dyDelete(temp);
}
/**
* Handles the given command.
* @param list
* @param command
*/
void handleCommand(DynamicArray* list, char command)
{
// FIXME: Implement
char* file = malloc(sizeof(char) * 256);
char* description = malloc(sizeof(char) * 256);
int priority;
//switch implements the main menu based on character input
switch (command)
{
// loads a file, asks for file name
case 'l':
//prompts user for file name
printf("Please enter the name of the file to be loaded.\n");
fgets(file, 200, stdin);
//loads data from file if it exists
FILE* readFile = fopen(file, "r");
if (readFile != NULL)
{
listLoad(list, readFile);
printf("Load successful. \n");
fclose(readFile);
}
//if file does not exist, prints that it was not found
else
{
printf("File not found.\n");
}
break;
// saves to a file, asks for file name
case 's':
//prompts user for file name
printf("Please enter the name of the file to be saved.\n");
fgets(file, 200, stdin);
//writes data to a file
FILE* writeFile = fopen(file, "w+");
listSave(list, writeFile);
printf("Save successful. \n");
fclose(writeFile);
break;
// adds a new task, asks for a descriptin and priority
case 'a':
//gets description
printf("Please enter the description of your task.\n");
fgets(description, 200, stdin);
//gets priority
printf("Please enter the priority of your task as an integer.\n");
scanf("%d", &priority);
//creates a new task and adds it to the heap
Task* newTask = taskNew(priority, description);
dyHeapAdd(list, newTask, taskCompare);
printf("Task successfully added.\n");
break;
case 'g':
//if list is empty prints that it is so
if (dySize(list) == 0)
{
printf("Sorry, your list is empty. \n");
}
//if list is not empty, prints first item
else
{
printf("The first task on your list is: %s\n");
}
break;
case 'r':
//if list is empty prints that it is so
if (dySize(list) == 0)
{
printf("Sorry, your list is empty. \n");
}
//if list is not empty, removes first item
else
{
struct Task* firstTask = (struct Task*)dyHeapGetMin(list);
dyHeapRemoveMin(list, taskCompare);
taskDelete(firstTask);
printf("The first task has been removed.\n");
}
break;
case 'p':
//if list is empty prints that it is so
if (dySize(list) == 0)
{
printf("Sorry, your list is empty. \n");
}
//if list is not empty, prints list
else
{
listPrint(list);
}
break;
case 'e':
//exits program
break;
}
}
int main()
{
// Implement
printf("\n\n** TO-DO LIST APPLICATION **\n\n");
DynamicArray* list = dyNew(8);
char command = ' ';
do
{
printf("Press:\n"
"'l' to load to-do list from a file\n"
"'s' to save to-do list to a file\n"
"'a' to add a new task\n"
"'g' to get the first task\n"
"'r' to remove the first task\n"
"'p' to print the list\n"
"'e' to exit the program\n"
);
command = getchar();
// Eat newlines
while (getchar() != '\n');
handleCommand(list, command);
}
while (command != 'e');
/* free dynamically allocated List pointers in array to avoid memory leaks */
/* Fix it */
for (int i = 0; i < dySize(list); i++)
{
Task* t = dyGet(list, i);
taskDelete(t);
}
dyDelete(list);
return 0;
}
|
C
|
/****************************************************************************************************/
/* @FileName : spi.c */
/* @Author : zhengbaiqiu */
/* @Version : v1.0 */
/* @Date : 2019.11.12 */
/****************************************************************************************************/
/* Includes --------------------------------------------------------------------*/
#include "stm32f10x.h"
/* Project ---------------------------------------------------------------------*/
#include "spi.h"
/* Variable --------------------------------------------------------------------*/
/* Function --------------------------------------------------------------------*/
void SPI1_Configure(void);
void SPI_SetSpeed(SPI_TypeDef* SPIx,u8 Speeds);
u8 SPI_WriteByte(SPI_TypeDef* SPIx,u8 Byte);
/*****************************************************************************
* @name :void SPI2_Configure(void)
* @date :2020-09-19
* @author :zhengbaiqiu
* @function :spi configure
* @parameters :None
* @retvalue :None
******************************************************************************/
void SPI1_Configure(void)
{
SPI_InitTypeDef SPI_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
//SPI1ܽ
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//SPI1ѡ
SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2;
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_InitStructure.SPI_CRCPolynomial = 7;
SPI_Init(SPI1, &SPI_InitStructure);
//ʹSPI1
SPI_Cmd(SPI1, ENABLE);
}
/*****************************************************************************
* @name :void SPI_SetSpeed(SPI_TypeDef* SPIx,u8 Speeds)
* @date :2020-09-19
* @author :zhengbaiqiu
* @function :set spi speed
* @parameters :SPIx: SPI type,x for 1,2,3
Speed:SPIx speed = APB1 / 2^(Speeds + 1)
* @retvalue :None
******************************************************************************/
void SPI_SetSpeed(SPI_TypeDef* SPIx,u8 Speeds)
{
SPIx->CR1 &= 0xFFC7;
SPIx->CR1 |= Speeds<<3;
SPIx->CR1|=1<<6; //SPI豸ʹ
// SPI_Cmd(SPIx,ENABLE);
}
/*****************************************************************************
* @name :u8 SPI_WriteByte(SPI_TypeDef* SPIx,u8 Byte)
* @date :2020-09-19
* @author :zhengbaiqiu
* @function :Write a byte of data using STM32's hardware SPI
* @parameters :SPIx: SPI type,x for 1,2,3
Byte:Data to be written
* @retvalue :Data received by the bus
******************************************************************************/
u8 SPI_WriteByte(SPI_TypeDef* SPIx,u8 Byte)
{
while((SPIx->SR&SPI_I2S_FLAG_TXE)==RESET); //ȴ
SPIx->DR=Byte; //һbyte
while((SPIx->SR&SPI_I2S_FLAG_RXNE)==RESET); //ȴһbyte
return SPIx->DR; //յ
}
// void SPI_SetSpeed(SPI_TypeDef* SPIx,u8 SpeedSet)
// {
// SPIx->CR1&=0XFFC7;
// if(SpeedSet==1)//
// {
// SPIx->CR1|=SPI_BaudRatePrescaler_2;//Fsck=Fpclk/2
// }
// else//
// {
// SPIx->CR1|=SPI_BaudRatePrescaler_32; //Fsck=Fpclk/32
// }
// SPIx->CR1|=1<<6; //SPI豸ʹ
// }
|
C
|
#include <stdio.h>
void lervetor(int vet[],int n){
for(int i=0;i<n;i++){
scanf("%d",&vet[i]);
}
}
void imprimevetor(int vet[],int n){
for(int i=0;i<n;i++){
printf("%d ",vet[i]);
}
printf("\n");
}
void somavet(int v1[], int v2[], int n){
int v3[n];
for(int i=0;i<n;i++){
v3[i]=v2[i]+v1[i];
}
imprimevetor(v3,n);
}
int main()
{
int vet1[5],vet2[5];
lervetor(vet1,5);
lervetor(vet2,5);
somavet(vet1,vet2,5);
}
|
C
|
# include <stdlib.h>
# include <stdio.h>
# include <math.h>
# include "cube_integrals.h"
int main ( );
void test01 ( );
/******************************************************************************/
int main ( )
/******************************************************************************/
/*
Purpose:
MAIN is the main program for CUBE_INTEGRALS_PRB.
Discussion:
CUBE_INTEGRALS_PRB tests the CUBE_INTEGRALS library.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
19 January 2014
Author:
John Burkardt
*/
{
timestamp ( );
printf ( "\n" );
printf ( "CUBE_INTEGRALS_PRB\n" );
printf ( " C version\n" );
printf ( " Test the CUBE_INTEGRALS library.\n" );
test01 ( );
/*
Terminate.
*/
printf ( "\n" );
printf ( "CUBE_INTEGRALS_PRB\n" );
printf ( " Normal end of execution.\n" );
printf ( "\n" );
timestamp ( );
return 0;
}
/******************************************************************************/
void test01 ( )
/******************************************************************************/
/*
Purpose:
TEST01 estimates integrals over the unit cube in 3D.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
19 January 2014
Author:
John Burkardt
*/
{
int *e;
double error;
double exact;
int i;
int j;
int m = 3;
int n = 4192;
double result;
int seed;
int test;
int test_num = 20;
double *value;
double *x;
printf ( "\n" );
printf ( "TEST01\n" );
printf ( " Compare exact and estimated integrals\n" );
printf ( " over the interior of the unit cube in 3D.\n" );
/*
Get sample points.
*/
seed = 123456789;
x = cube01_sample ( n, &seed );
printf ( "\n" );
printf ( " Number of sample points is %d\n", n );
/*
Randomly choose exponents.
*/
printf ( "\n" );
printf ( " Ex Ey Ez MC-Estimate Exact Error\n" );
printf ( "\n" );
for ( test = 1; test <= test_num; test++ )
{
e = i4vec_uniform_ab_new ( m, 0, 7, &seed );
value = monomial_value ( m, n, e, x );
result = cube01_volume ( ) * r8vec_sum ( n, value ) / ( double ) ( n );
exact = cube01_monomial_integral ( e );
error = fabs ( result - exact );
printf ( " %2d %2d %2d %14.6g %14.6g %10.2e\n",
e[0], e[1], e[2], result, exact, error );
free ( value );
}
free ( x );
return;
}
|
C
|
#include <stdio.h>
#include <locale.h>
int main()
{
setlocale(0,"Russian");
int A,k,l,m;
printf("Введите трехзначное число: ");
scanf("%d", &A);
printf("Цифры данного числа образуют возрастающую или убывающую последовательность\n");
if (A>99 && A<1000){
k=A/100;
l=A%100;
m=l%10;
l=l/10;
if((k>l && l>m)|| (k<l && l<m))
printf("Истина");
else
printf("Ложь");
}
else
printf("Ошибка");
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int** maze;
void print_maze(void) {
int i, j, k = 0;
int row, col;
int view_i, view_j, d, chk_cnt;
int move[4][2] = { {-2,0},{2,0},{0,-2},{0,2} };//¿
struct room {
int r;
int c;
}*unknown;
struct candidate_room {
int r;
int c;
int d;
}*candidate;
row = 21;
col = 21;
//2 迭ó maze
maze = (int**)malloc(sizeof(int*) * row);
for (i = 0; i < row; i++) maze[i] = (int*)malloc(sizeof(int) * col);
//̷ ü .
chk_cnt = (row / 2) * (col / 2);
// Ʈ غ
unknown = (struct room*)malloc(sizeof(struct room) * chk_cnt);
//ĺ ̷ Ʈ غ
candidate = (struct candidate_room*)malloc(sizeof(struct candidate_room) * chk_cnt);
//̷ ü (0) ä, Ʈ ʷ
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
maze[i][j] = 0;
if (i % 2 == 1 && j % 2 == 1) {
unknown[k].r = i;
unknown[k].c = j;
k++;
}
}
}
srand((unsigned int)time(NULL));
// ϰ ̷ ǥ
k = (int)rand() % chk_cnt;
maze[unknown[k].r][unknown[k].c] = 1;
// Ʈ . ǥ k ̵
chk_cnt--; // Ʈ ϳ
unknown[k].r = unknown[chk_cnt].r;
unknown[k].c = unknown[chk_cnt].c;
// Ʈ ݺ
while (chk_cnt > 0) {
//
k = (int)rand() % chk_cnt;
i = unknown[k].r;
j = unknown[k].c;
//ĺ ̷ Ʈ ߰
k = 0;
candidate[k].r = i;
candidate[k].c = j;
maze[i][j] = 2;
//̷ ݺ
while (1) {
d = (int)rand() % 4;
view_i = i + move[d][0];
view_j = j + move[d][1];
//̷ ̸ ٽ
if (view_i < 1 || view_i > row - 2 || view_j < 1 || view_j > col - 2) continue;
//̷ ̸ ϰ
candidate[k].d = d;
// ̵ ϴ ĺ ߰
k++;
candidate[k].r = view_i;
candidate[k].c = view_j;
// ̸ ϰ ĺ ̷ ǥ
if (maze[view_i][view_j] == 0) {
i = view_i;
j = view_j;
maze[i][j] = 2;
}
else if (maze[view_i][view_j] == 1)break; //̷θ
else { //maze[view_i][view_j] == 2 , ĺ ̷θ Ƿ Ŭ
// ĺ
k--;
do { //(view_i, view_j)
// ǵ 鼭 ĺ(2) (0)
maze[candidate[k].r][candidate[k].c] = 0;
k--;
} while (candidate[k].r != view_i || candidate[k].c != view_j);
//Ŭ ƿ ٽ ̷ ã
i = view_i;
j = view_j;
}
}
// ̷θ ̷ ǥϰ ̷ι渶 Ʈ
for (i = 0; i < k; i++) {
maze[candidate[i].r][candidate[i].c] = 1;
switch (candidate[i].d) {
case 0: maze[candidate[i].r - 1][candidate[i].c] = 1; break;
case 1: maze[candidate[i].r + 1][candidate[i].c] = 1; break;
case 2: maze[candidate[i].r][candidate[i].c - 1] = 1; break;
case 3: maze[candidate[i].r][candidate[i].c + 1] = 1;
}
// Ʈ ϳ
chk_cnt--;
//ĺ ġ Ž
for (j = 0; j < chk_cnt; j++) if (candidate[i].r == unknown[j].r && candidate[i].c == unknown[j].c) break;
//ĺ ̷η Ǹ鼭 Ʈ . ǥ j ̵
unknown[j].r = unknown[chk_cnt].r;
unknown[j].c = unknown[chk_cnt].c;
}
}
maze[0][1] = 1;
//----------
// ĭ 1 DZ
/*maze[11][24] = 1;
maze[6][24] = 1;
maze[21][24] = 1;*/
//̷θ
printf("\n\nWilson's Algorithm\n\n");
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
if (maze[i][j] == 0) printf("");
else printf("");
}
printf("\n");
}
}
int main() {
print_maze();
return 0;
}
|
C
|
/*
*********************************************************************************************************
*
* 模块名称 : ADS1256 驱动模块(8通道带PGA的24位ADC)
* 文件名称 : bsp_ads1256.h
*
* Copyright (C), 2013-2014, 安富莱电子 www.armfly.com
*
*********************************************************************************************************
*/
#ifndef _BSP_ADS1256_H
#define _BSP_ADS1256_H
/* 增益选项 */
typedef enum
{
ADS1256_GAIN_1 = (0), /* 增益1(缺省) */
ADS1256_GAIN_2 = (1), /* 增益2 */
ADS1256_GAIN_4 = (2), /* 增益4 */
ADS1256_GAIN_8 = (3), /* 增益8 */
ADS1256_GAIN_16 = (4), /* 增益16 */
ADS1256_GAIN_32 = (5), /* 增益32 */
ADS1256_GAIN_64 = (6), /* 增益64 */
}ADS1256_GAIN_E;
/* 采样速率选项 */
/* 数据转换率选择
11110000 = 30,000SPS (default)
11100000 = 15,000SPS
11010000 = 7,500SPS
11000000 = 3,750SPS
10110000 = 2,000SPS
10100001 = 1,000SPS
10010010 = 500SPS
10000010 = 100SPS
01110010 = 60SPS
01100011 = 50SPS
01010011 = 30SPS
01000011 = 25SPS
00110011 = 15SPS
00100011 = 10SPS
00010011 = 5SPS
00000011 = 2.5SPS
*/
typedef enum
{
ADS1256_30000SPS = 0,
ADS1256_15000SPS,
ADS1256_7500SPS,
ADS1256_3750SPS,
ADS1256_2000SPS,
ADS1256_1000SPS,
ADS1256_500SPS,
ADS1256_100SPS,
ADS1256_60SPS,
ADS1256_50SPS,
ADS1256_30SPS,
ADS1256_25SPS,
ADS1256_15SPS,
ADS1256_10SPS,
ADS1256_5SPS,
ADS1256_2d5SPS,
ADS1256_DRATE_MAX
}ADS1256_DRATE_E;
#define ADS1256_DRAE_COUNT = 15;
typedef struct
{
ADS1256_GAIN_E Gain; /* 增益 */
ADS1256_DRATE_E DataRate; /* 数据输出速率 */
int32_t AdcNow[8]; /* 8路ADC采集结果(实时)有符号数 */
uint8_t Channel; /* 当前通道 */
}ADS1256_VAR_T;
void bsp_InitADS1256(void);
void ADS1256_CfgADC(ADS1256_GAIN_E _gain, ADS1256_DRATE_E _drate);
uint8_t ADS1256_ReadChipID(void);
int32_t ADS1256_ReadAdc(uint8_t _ch);
void ADS1256_StartScan(void);
void ADS1256_StopScan(void);
int32_t ADS1256_GetAdc(uint8_t _ch);
extern ADS1256_VAR_T g_tADS1256;
#endif
/***************************** 安富莱电子 www.armfly.com (END OF FILE) *********************************/
|
C
|
/**
* common.h
*
* Some commonly used defines and configuration options.
* Mostly flags to toggle debug code or to tweak the
* search algorithm.
*
*/
#ifndef _COMMON_H_
#define _COMMON_H_
/*******************************************************************************************
* Specifics for Windows and *nix
*/
#if defined(_WIN32) && defined(__GNUC__)
// Disabled threading on Win32 by not defining THREADS.
// Disabled utf8-output on win32 by not defining UNICODE_OUTPUT.
// Enable attempted unicode fix:
#define UNICODE_FIX
#else
#define UNICODE_OUTPUT
#define THREADS
#endif
/*******************************************************************************************
* Multithreading
*/
// To disable threading it's better to disable #define THREADS
// than to set the thread count to 0, to remove multithreading overhead.
#define MAX_THREADS (4)
/*******************************************************************************************
* Options to tweak the algorithm
*/
// This option is defined when compiling
// with -DDEBUG (when using gcc, at least)
// or building with `make debug`
#ifndef DEBUG
// Minimum ply depth. Except for the standard alpha/beta behaviour,
// the search depth will not be altered to be less than this, only deeper.
#define __MIN_PLY_DEPTH (5)
// If 1, only the moves of the current players are regarded (not the countermoves)
// and are NOT evaluated. Quite useless, so always use > 2.
// Depth 1 will almost certainly not properly detect when the game has ended, too.
#define MAX_PLY_DEPTH (6)
// Responses to check do not count as a ply while searching ('check extension'),
// to prevent eternal loops, there's a maximum of extensions allowed per search path:
#define MAX_EXTRA_PLY_DEPTH (2)
#else
#define __MIN_PLY_DEPTH (3)
#define MAX_PLY_DEPTH (3)
#define MAX_EXTRA_PLY_DEPTH (0)
// Prints the reasoning behind evaluation
//#define PRINT_EVAL (1)
// Prints all moves at root level
//#define PRINT_MOVES (1)
// Prints the entire thinking tree.
// Disable PRINT_MOVES when you use this instead.
#define PRINT_ALL_MOVES (1)
// Prints a few moves, that are being considered
//#define PRINT_THINKING (1)
// Shuffling add randomization (different alpha-beta cutoffs) while
// not impacting quality. Keeping them sorted helps with consistent
// debugging.
#define DEBUG_KEEP_MOVES_SORTED (1)
// Only for some serious testing: this disables alpha-beta cutoffs
// entirely, causing a much larger search space
//#define DISABLE_ALPHA_BETA (1)
// Disable multithreading
#undef THREADS
#endif
// Minimum fitness that a board evaluation can produce. Means black wins.
#define MIN_FITNESS (-1000000)
// Maximum fitness that a board evaluation can produce. Means white wins.
#define MAX_FITNESS (1000000)
// When the mininum ply depth is X, this value should be MAX_PLY_DEPTH - X
#define MIN_PLY_DEPTH_REMAINDER (MAX_PLY_DEPTH - __MIN_PLY_DEPTH)
// Max ply depth used when calculating for the opening book
// Minimum ply depth will be OPENING_BOOK_MAX_PLY_DEPTH - MIN_PLY_DEPTH_REMAINDER
// Not used at the moment.
#define OPENING_BOOK_MAX_PLY_DEPTH (5)
// If a branch of moves has a quiescence score that is above the threshold,
// it won't be branched at the minimum ply depth.
#define QUIESCENCE_THRESHOLD (100)
// A move adds this many 'points' to its score when it is a capture
#define QUIESCENCE_PENALTY_CAPTURE (100)
// A move adds this many 'points' to its score when a piece is pinned
//#define QUIESCENCE_PENALTY_PINNED (60)
// A move adds this many 'points' to its score when a piece is 'hanging'
// (i.e. attacked and not covered)
//#define QUIESCENCE_PENALTY_HANGING (60)
// Evaluate moves in random order. Useful for unpredictability,
// but cannot be used when alpha/beta in root level
#define MOVE_RANDOMIZE (false)
/*******************************************************************************************
* Some flags for enabling debug output
*/
#define PRINT_STATS (false)
#endif
|
C
|
#include <bmp_header.h>
#include <carrier.h>
#include <encrypt.h>
#include <hidden_file.h>
#include <jobs.h>
#include <lsb.h>
#include <payload.h>
#include <stdio.h>
#include <testing_suite.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <rc4.h>
void lsb1_insert_0();
void lsb4_insert_1();
void lsb1_insert_2();
void lsb4_insert_4();
void lsb1_insert_3();
void lsb4_insert_image_0();
void lsb1_insert_image_1();
int main()
{
create_suite("Insert Tests");
add_test(lsb1_insert_0);
add_test(lsb4_insert_1);
add_test(lsb1_insert_2);
add_test(lsb1_insert_3);
add_test(lsb4_insert_4);
add_test(lsb4_insert_image_0);
add_test(lsb1_insert_image_1);
run_suite();
clear_suite();
}
//inserta con lsb1 a ladoLSB1.bmp la imagen original.png
void lsb1_insert_image_1()
{
bmp_file bmp_f = read_bmp("files_for_testing/ladoLSB1.bmp");
bmp_header bmp_h = bmp_f->header;
carrier c = create_carrier(bmp_f->data, bmp_h->image_size_bytes, bmp_h->width_px, bmp_h->height_px);
hfs example_hf = process_hf("tests_input/gladiator_chicken.png");
uint8_t *payload_insert = concat_hf(example_hf);
//poner total size en la estructura de hf
payload p = create_payload(payload_insert, sizeof(uint32_t) + example_hf->size + example_hf->ext_size);
lsb l = create_lsb(1);
lsb_steg(l, c, p);
payload p1 = extract_payload(l, c);
char *file_path = "tests_output/lbs1_insert_original.png";
FILE *f = fopen(file_path, "w");
if (f == NULL)
{
printf("File Not Found! %s\n", file_path);
return;
}
fwrite(p1->content, sizeof(uint8_t), p1->size, f);
fclose(f);
destroy_lsb(l);
destroy_carrier(c);
destroy_payload(p);
assert_true(1 == 1);
}
//inserta con lsb4 a ladoLSB1.bmp la imagen original.png
void lsb4_insert_image_0()
{
bmp_file bmp_f = read_bmp("files_for_testing/ladoLSB1.bmp");
bmp_header bmp_h = bmp_f->header;
carrier c = create_carrier(bmp_f->data, bmp_h->image_size_bytes, bmp_h->width_px, bmp_h->height_px);
hfs example_hf = process_hf("tests_input/gladiator_chicken.png");
uint8_t *payload_insert = concat_hf(example_hf);
//poner total size en la estructura de hf
payload p = create_payload(payload_insert, sizeof(uint32_t) + example_hf->size + example_hf->ext_size);
lsb l = create_lsb(4);
lsb_steg(l, c, p);
payload p1 = extract_payload(l, c);
FILE *f = fopen("tests_output/lbs4_insert_original.png", "w");
fwrite(p1->content, sizeof(uint8_t), p1->size, f);
fclose(f);
destroy_lsb(l);
destroy_carrier(c);
destroy_payload(p);
assert_true(1 == 1);
}
//inserta con lsb1 a ladoLSB1.bmp el texto test1.txt
void lsb1_insert_0(){
bmp_file bmp_f = read_bmp("files_for_testing/ladoLSB1.bmp");
bmp_header bmp_h = bmp_f->header;
carrier c = create_carrier(bmp_f->data, bmp_h->image_size_bytes, bmp_h->width_px, bmp_h->height_px);
hfs example_hf = process_hf("tests_input/test1.txt");
uint8_t *payload_insert = concat_hf(example_hf);
//poner total size en la estructura de hf
payload p = create_payload(payload_insert, sizeof(uint32_t) + example_hf->size + example_hf->ext_size);
lsb l = create_lsb(1);
int status = lsb_steg(l, c, p);
if(status == 0){
payload p1 = extract_payload(l, c);
char *file_path = "tests_output/lbs1_insert_text1.txt";
FILE *f = fopen(file_path, "w+");
if (f == NULL) {
printf("File Not Found! %s\n", file_path);
return;
}
fwrite(p1->content, sizeof(uint8_t), p1->size, f);
fclose(f);
}
destroy_lsb(l);
destroy_carrier(c);
destroy_payload(p);
assert_true(1 == 1);
}
//inserta con lsb4 a ladoLSB1.bmp el texto test1.txt
void lsb4_insert_1()
{
bmp_file bmp_f = read_bmp("files_for_testing/ladoLSB1.bmp");
bmp_header bmp_h = bmp_f->header;
carrier c = create_carrier(bmp_f->data, bmp_h->image_size_bytes, bmp_h->width_px, bmp_h->height_px);
hfs example_hf = process_hf("tests_input/test1.txt");
uint8_t *payload_insert = concat_hf(example_hf);
//poner total size en la estructura de hf
payload p = create_payload(payload_insert, sizeof(uint32_t) + example_hf->size + example_hf->ext_size);
lsb l = create_lsb(4);
int status = lsb_steg(l, c, p);
if(status == 0){
payload p1 = extract_payload(l, c);
//payload_ext(p);
FILE *f = fopen("tests_output/lbs4_insert_text1.txt", "w");
fwrite(p1->content, sizeof(uint8_t), p1->size, f);
fclose(f);
}
destroy_lsb(l);
destroy_carrier(c);
destroy_payload(p);
assert_true(1 == 1);
}
//inserta con lsb1 a ladoLSB1.bmp el texto test2.txt
void lsb1_insert_2()
{
bmp_file bmp_f = read_bmp("files_for_testing/ladoLSB1.bmp");
bmp_header bmp_h = bmp_f->header;
carrier c = create_carrier(bmp_f->data, bmp_h->image_size_bytes, bmp_h->width_px, bmp_h->height_px);
hfs example_hf = process_hf("tests_input/test2.txt");
uint8_t *payload_insert = concat_hf(example_hf);
payload p = create_payload(payload_insert, sizeof(uint32_t) + example_hf->size + example_hf->ext_size);
lsb l = create_lsb(1);
int status = lsb_steg(l, c, p);
if(status == 0){
payload p1 = extract_payload(l, c);
FILE *f = fopen("tests_output/lbs1_insert_text2.txt", "w");
fwrite(p1->content, sizeof(uint8_t), p1->size, f);
fclose(f);
}
destroy_lsb(l);
destroy_carrier(c);
destroy_payload(p);
assert_true(1 == 1);
}
//inserta con lsb1 a ladoLSB1.bmp el texto test4.txt
void lsb1_insert_3()
{
bmp_file bmp_f = read_bmp("files_for_testing/ladoLSB1.bmp");
bmp_header bmp_h = bmp_f->header;
carrier c = create_carrier(bmp_f->data, bmp_h->image_size_bytes, bmp_h->width_px, bmp_h->height_px);
hfs example_hf = process_hf("tests_input/test4.txt");
uint8_t *payload_insert = concat_hf(example_hf);
payload p = create_payload(payload_insert, sizeof(uint32_t) + example_hf->size + example_hf->ext_size);
lsb l = create_lsb(1);
int status = lsb_steg(l, c, p);
if(status == 0){
payload p1 = extract_payload(l, c);
FILE *f = fopen("tests_output/lsb1_insert_text4.txt", "w");
fwrite(p1->content, sizeof(uint8_t), p1->size, f);
fclose(f);
}
destroy_lsb(l);
destroy_carrier(c);
destroy_payload(p);
assert_true(1 == 1);
}
//inserta con lsb4 a ladoLSB1.bmp el texto test4.txt
void lsb4_insert_4()
{
bmp_file bmp_f = read_bmp("files_for_testing/ladoLSB1.bmp");
bmp_header bmp_h = bmp_f->header;
carrier c = create_carrier(bmp_f->data, bmp_h->image_size_bytes, bmp_h->width_px, bmp_h->height_px);
hfs example_hf = process_hf("tests_input/test4.txt");
uint8_t *payload_insert = concat_hf(example_hf);
payload p = create_payload(payload_insert, sizeof(uint32_t) + example_hf->size + example_hf->ext_size);
lsb l = create_lsb(4);
int status = lsb_steg(l, c, p);
if(status == 0){
payload p1 = extract_payload(l, c);
FILE *f = fopen("tests_output/lsb4_insert_text4.txt", "w");
fwrite(p1->content, sizeof(uint8_t), p1->size, f);
fclose(f);
}
destroy_lsb(l);
destroy_carrier(c);
destroy_payload(p);
assert_true(1 == 1);
}
|
C
|
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <json.h>
#include <nemoattr.h>
#include "util.h"
#define BUF_SIZE 100
static bool
_json_find(struct json_object *obj, const char *names, struct nemoattr *attr)
{
bool ret = false;
char *_names = strdup(names);
char *name = strtok(_names, ":");
struct json_object_iterator it;
struct json_object_iterator itEnd;
it = json_object_iter_begin(obj);
itEnd = json_object_iter_end(obj);
while (!json_object_iter_equal(&it, &itEnd)) {
json_object *cobj = json_object_iter_peek_value(&it);
const char *_name = json_object_iter_peek_name(&it);
json_type type = json_object_get_type(cobj);
if (!strcmp(_name, name)) {
if (json_type_boolean == type) {
json_bool val = json_object_get_boolean(cobj);
nemoattr_seti(attr, val);
} else if (json_type_double == type) {
double val = json_object_get_double(cobj);
nemoattr_setd(attr, val);
break;
} else if (json_type_int == type) {
int val = json_object_get_int(cobj);
nemoattr_seti(attr, val);
break;
} else if (json_type_string == type) {
const char *val = json_object_get_string(cobj);
nemoattr_sets(attr, val, json_object_get_string_len(cobj));
break;
} else if ((json_type_object == type) ||
json_type_array == type) {
name = name + strlen(name) + 1;
if (json_type_object == type) {
if (_json_find(cobj, name, attr)) {
break;
}
} else {
int i = 0;
for (i = 0; i < json_object_array_length(cobj) ; i++) {
struct json_object *ccobj;
ccobj = json_object_array_get_idx(cobj, i);
if (_json_find(ccobj, name, attr)) {
break;
}
}
}
} else {
ERR("%s have wrong json type(%d)", name, type);
}
}
json_object_iter_next(&it);
}
free(_names);
return ret;
}
int main()
{
#if 1
size_t json_str_size = 0;
char *json_str = NULL;
char buf[BUF_SIZE];
FILE *fp = fopen("./json.json", "r");
while (fgets(buf, BUF_SIZE - 1, fp)) {
json_str_size += strlen(buf);
json_str = realloc(json_str, json_str_size + 1);
strncat(json_str, buf, strlen(buf));
}
fclose(fp);
if (!json_str) {
return -1;
}
#endif
struct json_object *obj;
obj = json_object_from_file("./json.json");
//obj = json_tokener_parse(json_str);
struct nemoattr attr;
memset(&attr, 0, sizeof(struct nemoattr));
bool ret;
ret = _json_find(obj, "weather:id", &attr);
ERR("ret: %d, %d", ret, nemoattr_geti(&attr));
memset(&attr, 0, sizeof(struct nemoattr));
ret = _json_find(obj, "weather:main", &attr);
ERR("ret: %d, %s", ret, nemoattr_gets(&attr));
memset(&attr, 0, sizeof(struct nemoattr));
ret = _json_find(obj, "sys:sunrise", &attr);
ERR("ret: %d, %d", ret, nemoattr_geti(&attr));
memset(&attr, 0, sizeof(struct nemoattr));
ret = _json_find(obj, "clouds:id", &attr);
ERR("ret: %d, %d", ret, nemoattr_geti(&attr));
free(json_str);
return 0;
}
|
C
|
/**
* @file integrate_orbit.c
* @brief Functions to perform the integration of the galaxy orbit
*/
#include "allvars.h"
#include "readparameterfile.h"
#include "proto.h"
/** Minimum allowed subhalo mass (in code units). */
#define MINSUBMASS 1.0e-7
/** Minimum value allowed for code units. */
#define MINUNITS 1.0e-6
/** Minimum value to check for energy/angular momentum conservation.
For Target simulation, this can be as small as 1e-6. For DolagClusters
simulations, this needs to be 1e-4. */
#define MINCHECK 1.0e-4
/**
* @brief Integrate orbit of a type 2 satellite.
* @param p Index of selected galaxy
* @param central Index of the corresponding central galaxy
* @param tmax Maximum integration time
* @param dt Integration timestep
* @param eps Softening to use in the potential
* @return 0 on success, -1 if energy increases (try reducing the
* softening)
*
* Note that this function uses its own system of units, where the unit of
* mass is the host halo mass, the unit length is the host halo radius
* and the unit velocity is set so that G = 1 (i.e. it should be the virial
* velocity).
* Important: elements Posrel, Vrel, Orbit(X,Y,Z) in struct GALAXY are
* assumed to store information in physical units.
* Note new galaxy type 4: disrupted subhalo
*/
int integrate_type2_orbit(int p, int central, double tmax, double dt,
double eps)
{
int elements, k, nstep;
int trigger=0;
double r[3], v[3], a[3], j[3];
double mhalo, lambda_c, v2, vhalo, j2, j2_0, djdt;
double j2prev;
double r2, dr, rscale, rgx, rdyn;
double ekin, epot, e_fin, e_in;
double omega;
double t, t_out, dtout;
double tdyn;
double tdyn_orbital;
double mass, minit, radius, rtidal, rperi, rapo;
double unitlength, unitmass, unittime, unitvel, unitenergy;
double m_of_r, mstrip;
struct GALAXY galaxySave;
EmergencyStop = 0;
if (GalaxyA[p].Type != 2) {
fprintf(stderr, "Error (integrate_type2_orbit): "
"function called for galaxy not type 2\n"
"GalaxyA[%d].Type = %d - Exit\n", p, GalaxyA[p].Type);
fflush(stderr);
exit(EXIT_FAILURE);
}
galaxySave = GalaxyA[p];
/* NEW: satellites of type 1 galaxies can be stripped away, and they
orbit the central galaxy of the FOF. Update the definition of
central and the relative position and velocity accordingly */
if (GalaxyA[p].Relocated == 1)
central = FirstGalInFOFGroup_A[GalaxyA[p].ParentGroup];
/* Use the host halo mass as unit mass */
unitmass = (double)GalaxyA[central].Mvir;
/*printf("p, central, unitmass: %d %d %g (PartMass %g)\n", p, central,
GalaxyA[central].Mvir, PartMass); fflush(stdout);*/
/* Use the host halo virial radius as unit length */
unitlength = (double)GalaxyA[central].Rvir;
/* Unit velocity in code units (usually km/s) */
unitvel = sqrt(G*unitmass/unitlength);
/* Unit time in main code units */
unittime = (unitlength/unitvel);
unitenergy = unitmass*unitvel*unitvel;
tmax /= unittime; /* Max time to internal units */
dtout = tmax/STEPS; /* Time interval to store the orbit */
#ifdef DEBUG
printf("Unit velocity: %g km/s (virial velocity %g)\n", unitvel,
GalaxyA[central].Vvir);
printf("Unit time: %g Myr\n", unittime*UnitTime_in_s /
SEC_PER_MEGAYEAR / Hubble_h);
/* Note that, unlike testorbit, we don't need to multiply by the
conversion from km to kpc because we use G in code units */
printf("Maximum time: %g Myr\n", tmax*unittime*UnitTime_in_s /
SEC_PER_MEGAYEAR / Hubble_h);
printf("Output timestep: %g Myr\n", dtout*unittime*UnitTime_in_s /
SEC_PER_MEGAYEAR / Hubble_h);
fflush(stdout);
#endif
if (unittime < MINUNITS || unitvel < MINUNITS || unitmass < MINUNITS
|| unitlength < MINUNITS) {
fprintf(stderr, "Error (integrate_type2_orbit): "
"error while setting up units - Exit\n");
fprintf(stderr,
" p, central: %d %d\n"
" Unit length: %g\n"
" Unit time: %g\n"
" Unit velocity: %g\n"
" Unit mass: %g\n",
p, central, unitlength, unittime, unitvel, unitmass);
fflush(stderr);
exit(EXIT_FAILURE);
}
/* TOMAS 2013-04-24: with the new units, this is 1 */
/*rhalo = GalaxyA[central].Rvir*UnitLength_in_kpc/ULENGTH_ORBIT;*/
/* Initial conditions for integration: start with the last recorded
satellite position, velocity, mass and outer radius */
mass = (double)GalaxyA[p].OrbitMass[STEPS-1]/unitmass;
minit = mass;
radius = (double)GalaxyA[p].Rdm/unitlength;
/* Coordinates and velocities relative to the central galaxy */
r2 = 0.0;
v2 = 0.0;
for (k=0; k<3; k++) {
r[k] = (double)GalaxyA[p].Posrel[k]/unitlength;
v[k] = (double)GalaxyA[p].Vrel[k]*UnitVelocity_in_cm_per_s/unitvel/
1.0e5;
r2 += r[k]*r[k];
v2 += v[k]*v[k];
}
rperi = sqrt(r2);
rapo = rperi;
/*if (rperi > 1) {
printf("WARNING: galaxy %d initial radius r=%g exceeds host "
"Rvir\n", p, rperi); fflush(stdout);
}*/
/* Angular momentum */
j[0] = r[1]*v[2] - r[2]*v[1];
j[1] = r[2]*v[0] - r[0]*v[2];
j[2] = r[0]*v[1] - r[1]*v[0];
djdt = 0.0;
j2 = 0.0;
for (k=0; k<3; k++)
j2 += j[k]*j[k];
#ifdef DEBUG
printf("Angular momentum (previous): %g\n",
sqrt(GalaxyA[p].Jorb[0]*GalaxyA[p].Jorb[0] +
GalaxyA[p].Jorb[1]*GalaxyA[p].Jorb[1] +
GalaxyA[p].Jorb[2]*GalaxyA[p].Jorb[2]));
printf("Angular momentum (initial): %g\n", sqrt(GalaxyA[p].J2init));
printf("Angular momentum: %g (%g)\n",
sqrt(j2)*unitlength*unitvel, sqrt(j2));
#endif
/* Convert the initial angular momentum to local units */
j2_0 = (double)GalaxyA[p].J2init/(unitlength*unitlength)/
(unitvel*unitvel);
/* Time-scale for tidal stripping: we will use the subhalo
dynamical time */
/* TOMAS 2013-03-26: for a SIS host halo, if the outer radius of the
subhalo is the tidal radius as in Tormen, Diaferio & Syer 1998, the
dynamical time scales linearly with the subhalo's distance to the
centre. I don't know if this is appropriate... Maybe as a first order
treatment we should use the dynamical time at infall */
omega = sqrt(j2)/r2;
tdyn_orbital = 2*M_PI/omega;
if (TSTimescaleSelect == TSTIME_SUBHALO)
tdyn = sqrt(radius*radius*radius/mass);
if (TSTimescaleSelect == TSTIME_SUBINFALL) {
rdyn = (double)GalaxyA[p].Rvir/unitlength;
tdyn = sqrt(rdyn*rdyn*rdyn*unitmass/((double)GalaxyA[p].Mvir));
}
dt = tmax/dt;
#ifdef DEBUG
printf("Subhalo dynamical time: %g Myr\n",
tdyn*unittime*UnitTime_in_s/SEC_PER_MEGAYEAR/Hubble_h);
/*printf("Orbital dynamical time: %g Myr\n\n",
tdyn_orbital*unittime/SEC_PER_MEGAYEAR);*/
printf("Timestep: %g Myr\n", dt*unittime*UnitTime_in_s /
SEC_PER_MEGAYEAR/Hubble_h);
printf("Output timestep: %g Myr\n", dtout*unittime*UnitTime_in_s/
SEC_PER_MEGAYEAR/Hubble_h);
printf("Softening: %g h^-1 kpc\n", unitlength*eps);
fflush(stdout);
#endif
/* Store the initial conditions, in PHYSICAL coordinates */
GalaxyA[p].OrbitX[0] = r[0]*unitlength;
GalaxyA[p].OrbitY[0] = r[1]*unitlength;
GalaxyA[p].OrbitZ[0] = r[2]*unitlength;
GalaxyA[p].OrbitVx[0] = v[0]*unitvel;
GalaxyA[p].OrbitVy[0] = v[1]*unitvel;
GalaxyA[p].OrbitVz[0] = v[2]*unitvel;
GalaxyA[p].OrbitMass[0] = mass*unitmass;
GalaxyA[p].OrbitType[0] = GalaxyA[p].Type;
/*
* Integrate the orbit using a kick-drift-kick scheme
*/
t = 0.0;
t_out = 0.0;
nstep = 0;
ekin = 0.5*(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
/*epot = log(sqrt(r2)/rhalo)/rhalo;*/
/* Softened isothermal sphere potential */
epot = potential_sis(r[0], r[1], r[2], 1, 1, eps);
/*log(sqrt(r2)) + 0.5*log(1 + r2/(eps*eps)) -
log(sqrt(r2)/eps) + eps*atan(sqrt(r2)/eps)/sqrt(r2);*/
e_in = ekin + epot;
#ifdef DEBUG
Nprints = 0;
output(e_in*unitenergy, ekin*unitenergy, epot*unitenergy);
#endif
/* Initial acceleration. */
for (k=0; k<3; k++)
a[k] = accel(r[k], v[k], r2, v2, mass, (double)GalaxyA[p].Coulomb, eps);
while (t < tmax) {
for (k=0; k<3; k++) { /* First kick, then drift */
v[k] += 0.5*dt*a[k];
r[k] += dt*v[k];
}
r2 = r[0]*r[0] + r[1]*r[1] + r[2]*r[2];
v2 = v[0]*v[0] + v[1]*v[1] + v[2]*v[2];
for (k=0; k<3; k++) { /* Second kick */
a[k] = accel(r[k], v[k], r2, v2, mass, (double)GalaxyA[p].Coulomb,
eps);
v[k] += 0.5*dt*a[k];
}
t += dt;
/* Find the pericentre of the orbit */
if (sqrt(r2) <= rperi) rperi = sqrt(r2);
/* Find also the apocentre */
if (sqrt(r2) >= rapo) rapo = sqrt(r2);
/* When the galaxy loses all of its initial specific angular momentum,
a merger has happened */
j2prev = j[0]*j[0] + j[1]*j[1] + j[2]*j[2];
j[0] = r[1]*v[2] - r[2]*v[1];
j[1] = r[2]*v[0] - r[0]*v[2];
j[2] = r[0]*v[1] - r[1]*v[0];
j2 = j[0]*j[0] + j[1]*j[1] + j[2]*j[2];
/* Check energy */
ekin = 0.5*(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
epot = potential_sis(r[0], r[1], r[2], 1, 1, eps);
/* If dynamical friction is enabled, a galaxy should lose energy,
never gain it. Jumps in energy may be caused by an inadequate
choice of softening or integration timestep */
/* TOMAS 2013-05-14 Apparently, reducing the softening does not solve
the problem for some cases */
if ((ekin+epot)-e_in > MINCHECK) {
printf("\nWARNING (integrate_type2_orbit): energy increasing "
"for galaxy %d (%g) (snap %d)\n", p, (ekin+epot)-e_in,
Snapshot);
/*printf("Retrying with smaller softening... (current %g)\n\n", eps);*/
printf("Retrying with smaller timestep... (current %g)\n\n", dt);
fflush(stdout);
if (dt < 1.0e-13) {
printf("WARNING: very small timestep - perhaps you should try "
"with a smaller EpsGrav...\n"); fflush(stdout);
}
GalaxyA[p] = galaxySave;
//return -1;
return -2;
}
#ifdef DEBUG
/*if (Snapshot == 43 && p == 21) {
printf("Checking angular momentum: j/j0 = %g (previous), %g "
"(current), r = %g, E = %g\n", sqrt(j2prev/j2_0),
sqrt(j2/j2_0), sqrt(r2), ekin+epot); fflush(stdout);
}*/
#endif
if (sqrt(j2/j2_0) < SAT_MINJORB) {
if (GalaxyA[p].Type == 2) {
GalaxyA[p].Type = 3;
GalaxyA[p].TypeT[Snapshot] = 3;
}
GalaxyA[p].MergTimeActual += (float)(t*unittime);
GalaxyA[p].MergTimeSat += (float)(t*unittime);
GalaxyA[p].MergerType = 1;
break;
}
/*
* Control for jumps in the angular momentum. As the galaxy sinks
* towards the halo centre, accelerations become large and the
* timestep may have to be adjusted. Exit and retry the orbit
*/
djdt = (sqrt(j2) - sqrt(j2prev))/dt;
if (djdt > MINCHECK) {
printf("\nWARNING: increasing j (djdt=%g) for galaxy %d (type %d) "
"(snap %d)\n", djdt, p, GalaxyA[p].Type, Snapshot);
printf("r = %g - v = %g - j/j0 = %g jprev/j0 = %g djdt = %g\n",
sqrt(r2)*unitlength, sqrt(v2)*unitvel, sqrt(j2/j2_0),
sqrt(j2prev/j2_0), djdt);
printf("E_in = %g, E_curr = %g\n", e_in, ekin+epot);
printf("Retrying with smaller timestep... (current %g)\n\n", dt);
fflush(stdout);
if (dt < 1.0e-13) {
printf("WARNING: very small timestep - perhaps you should try "
"with a smaller EpsGrav...\n"); fflush(stdout);
}
GalaxyA[p] = galaxySave;
return -2;
//exit(EXIT_FAILURE);
}
/* TOMAS 2012-08-28 NEW: consider also mergers by proximity */
if (ProximityMergerOn == 1) {
rgx = 0.1; /* Consider the typical size of a central galaxy
to be 10 per cent the halo size */
/* TOMAS 2013-04-25: this is based on the Shen et al
(2003) results for z ~ 0, so its probably not
accurate for high redshift */
if (rperi < rgx) {
/*printf("rgx = %g kpc\n", rgx*ULENGTH_ORBIT);*/
if (GalaxyA[p].Type == 2) {
GalaxyA[p].Type = 3;
GalaxyA[p].TypeT[Snapshot] = 3;
}
GalaxyA[p].MergTimeActual += (float)(t*unittime);
GalaxyA[p].MergTimeSat += (float)(t*unittime);
GalaxyA[p].MergerType = 2;
break;
}
}
/* Mass loss due to tidal stripping */
if (TidalStrippingOn == 1) {
/* Mass of host halo within the position of the satellite */
m_of_r = sqrt(r2);
/* Calculate the tidal radius */
rtidal = sqrt(r2)*pow(mass/m_of_r, 1.0/3.0);
if (rtidal < radius) {
/* Find the mass beyond rtidal in the satellite */
mstrip = mass*(1.0 - rtidal/radius);
/*printf("p, mass, mstrip, mstrip*dt/tdyn: %d %g %g %g\n",
p, mass, mstrip, mstrip*dt/tdyn); fflush(stdout);*/
/* Remove a fraction dt/tstrip of the mass beyond rtidal,
and update the bounding radius of the satellite */
if (dt/tdyn < 1) mstrip *= dt/tdyn;
if (fabsf(mass - mstrip)*unitmass > MINSUBMASS) {
radius *= (mass - mstrip)/mass;
mass -= mstrip;
GalaxyA[p].StrippedMass += (float)(unitmass*mstrip);
}
else {
GalaxyA[p].StrippedMass += (float)mass;
radius = 0.0;
mass = 0.0;
}
if (mass < 0.0) {
fprintf(stderr, "Error (integrate_type2_orbit): mass = %g < 0"
" for galaxy %d - Exit\n", mass, p); fflush(stderr);
exit(EXIT_FAILURE);
}
}
}
/* Flag galaxies as disrupted */
if (mass/minit <= SAT_DISRUPT) {
GalaxyA[p].Type = 4;
GalaxyA[p].TypeT[Snapshot] = 4;
break; /* OJO no se si esta bien cortar aca */
}
/* Store the data, in physical coordinates for pos and vel */
if (t >= t_out) {
nstep++;
if (nstep >= STEPS) break;
GalaxyA[p].OrbitX[nstep] = (float)(r[0]*unitlength);
GalaxyA[p].OrbitY[nstep] = (float)(r[1]*unitlength);
GalaxyA[p].OrbitZ[nstep] = (float)(r[2]*unitlength);
GalaxyA[p].OrbitVx[nstep] =(float)(v[0]*unitvel*1.0e5/
UnitVelocity_in_cm_per_s);
GalaxyA[p].OrbitVy[nstep] = (float)(v[1]*unitvel*1.0e5/
UnitVelocity_in_cm_per_s);
GalaxyA[p].OrbitVz[nstep] = (float)(v[2]*unitvel*1.0e5/
UnitVelocity_in_cm_per_s);
GalaxyA[p].OrbitMass[nstep] = (float)(mass*unitmass);
GalaxyA[p].OrbitType[nstep] = GalaxyA[p].Type;
/*printf("r_DM, r_tidal: %g %g\n", radius, rtidal); fflush(stdout);*/
#ifdef DEBUG
output(e_in*unitenergy, ekin*unitenergy, epot*unitenergy);
#endif
t_out += dtout; /* Advance output clock */
}
/* Alternative: control the angular momentum loss
(but see the observation above) */
/*if (fabsf(j2/j2_0) > 1) {
if (EmergencyStop == 0) {
fprintf(stderr, "Error (integrate_type2_orbit): specific angular "
"momentum increasing for galaxy %d\n"
"j/j_0 = %g\n\n", p, sqrt(j2/j2_0));
fflush(stderr);
}
EmergencyStop++;
}*/
} /* Close while t < tmax */
/* If galaxy has merged, or completely disrupted (zero mass), fill out
the data with zeros and the galaxy type along the orbit with the final
state, but save the last DM radius and bound mass */
if ((GalaxyA[p].Type == 3) && nstep <= STEPS-1) {
for (k=nstep; k<STEPS; k++) {
GalaxyA[p].OrbitX[k] = 0.0;
GalaxyA[p].OrbitY[k] = 0.0;
GalaxyA[p].OrbitZ[k] = 0.0;
GalaxyA[p].OrbitVx[k] = 0.0;
GalaxyA[p].OrbitVy[k] = 0.0;
GalaxyA[p].OrbitVz[k] = 0.0;
GalaxyA[p].OrbitMass[k] = GalaxyA[p].OrbitMass[nstep-1];
GalaxyA[p].OrbitType[k] = GalaxyA[p].Type;
}
}
/* Update position, velocity, DM bounding radius of galaxy */
GalaxyA[p].Posrel[0] = GalaxyA[p].OrbitX[STEPS-1];
GalaxyA[p].Posrel[1] = GalaxyA[p].OrbitY[STEPS-1];
GalaxyA[p].Posrel[2] = GalaxyA[p].OrbitZ[STEPS-1];
GalaxyA[p].Vrel[0] = GalaxyA[p].OrbitVx[STEPS-1];
GalaxyA[p].Vrel[1] = GalaxyA[p].OrbitVy[STEPS-1];
GalaxyA[p].Vrel[2] = GalaxyA[p].OrbitVz[STEPS-1];
GalaxyA[p].Rdm = (float)(radius*unitlength);
GalaxyA[p].Mdm = GalaxyA[p].OrbitMass[STEPS-1];
GalaxyA[p].Jorb[0] =
GalaxyA[p].Posrel[1]*GalaxyA[p].Vrel[2] -
GalaxyA[p].Posrel[2]*GalaxyA[p].Vrel[1];
GalaxyA[p].Jorb[1] =
GalaxyA[p].Posrel[2]*GalaxyA[p].Vrel[0] -
GalaxyA[p].Posrel[0]*GalaxyA[p].Vrel[2];
GalaxyA[p].Jorb[2] =
GalaxyA[p].Posrel[0]*GalaxyA[p].Vrel[1] -
GalaxyA[p].Posrel[1]*GalaxyA[p].Vrel[0];
/* Advance merging clock for non-merged / non-disrupted galaxies */
if (GalaxyA[p].Type < 3) {
GalaxyA[p].MergTimeActual += (float)(tmax*unittime);
GalaxyA[p].MergTimeSat += (float)(tmax*unittime);
}
GalaxyA[p].EnergyLoss += (float)((e_in - ekin - epot)*unitenergy);
GalaxyA[p].Rpericentre = (float)(rperi*unitlength);
GalaxyA[p].Rapocentre = (float)(rapo*unitlength);
#ifdef DEBUG
if (GalaxyA[p].Type >= 3)
printf("Final time: %g Myr\n", t*unittime*UnitTime_in_s /
SEC_PER_MEGAYEAR / Hubble_h);
else
printf("Final time: %g Myr\n", tmax*unittime*UnitTime_in_s/
SEC_PER_MEGAYEAR / Hubble_h);
if (DynamicalFrictionOn == 1) {
printf("Expected merger time: %g Myr (final time = %g times the "
"expected time)\n",
GalaxyA[p].MergTime*UnitTime_in_s/SEC_PER_MEGAYEAR/Hubble_h,
t*unittime/GalaxyA[p].MergTime);
printf("Angular momentum (final): %g\n",
sqrt(GalaxyA[p].Jorb[0]*GalaxyA[p].Jorb[0] +
GalaxyA[p].Jorb[1]*GalaxyA[p].Jorb[1] +
GalaxyA[p].Jorb[2]*GalaxyA[p].Jorb[2]));
printf("Angular momentum loss: %g\n",
sqrt((GalaxyA[p].Jorb[0]*GalaxyA[p].Jorb[0] +
GalaxyA[p].Jorb[1]*GalaxyA[p].Jorb[1] +
GalaxyA[p].Jorb[2]*GalaxyA[p].Jorb[2])/GalaxyA[p].J2init));
if (GalaxyA[p].Type == 3)
printf("Merger happened: Yes\n");
else if (GalaxyA[p].Type <= 2)
printf("Merger happened: No\n");
else
printf("Subhalo disrupted!\n");
}
printf("Orbital pericentre: %g h^-1 kpc\n",
rperi*unitlength*UnitLength_in_kpc);
printf("Orbital apocentre: %g h^-1 kpc\n",
rapo*unitlength*UnitLength_in_kpc);
printf("Final galaxy mass: %g h^-1 M_Sun (%.1f per cent of initial "
"mass)\n", GalaxyA[p].OrbitMass[STEPS-1]*UnitMass_in_Msun,
GalaxyA[p].OrbitMass[STEPS-1]*100.0/minit/unitmass);
printf("Total mass lost: %g h^-1 M_Sun\n",
GalaxyA[p].StrippedMass*UnitMass_in_Msun);
fflush(stdout);
#endif
return 0;
}
/**
* Calculate a single component of the acceleration for the galaxy,
* including dynamical friction if enabled.
* @param x Position coordinate of galaxy (either x, y or z)
* @param dxdt The corresponding velocity component of galaxy
* @param r2 Square of the current halocentric radius of the galaxy
* @param v2 Square of current galaxy velocity
* @param mass Mass of the galaxy
* @param lnC Coulomb logarithm at infall
* @param eps Softening length used in the gravitational potential
* @return Acceleration in internal code units
*/
double accel(double x, double dxdt, double r2, double v2, double mass,
double lnC, double eps)
{
double a, rad, vel, vel2;
/* TOMAS 2013-04-24: with the new choice of system of units, the host
halo virial quantities are all 1 */
rad = sqrt(r2);
vel = sqrt(v2);
/* Gravitational potential term */
/*a = -x/(r0*r2);*/
/* NEW 2013-04-18: to avoid excessively large accelerations close to
the centre, we will use a softened isothermal sphere instead */
a = -(1.0/rad)*(1.0 - eps*atan(rad/eps)/rad) * x/rad;
/* Dynamical friction term */
if (DynamicalFrictionOn == 1) {
a -= (mass/r2)*lnC * (1.0/v2) *
(erf(vel) - 0.5*sqrt(M_PI)*vel*exp(-v2)) * dxdt/vel;
}
return a;
}
#ifdef DEBUG
/**
* Output information on the orbit integration to the standard output
* @param ekin Kinetic energy of the galaxy
* @param epot Potential energy of the galaxy
*/
void output(double e0, double ekin, double epot)
{
if (Nprints == 0) {
printf("===================================================================\n");
printf("| E_kinetic | E_potential | E_total | E var. |\n");
printf("===================================================================\n");
}
printf("| %le | %le | %le | %le |\n", ekin, epot, ekin+epot,
(ekin+epot)-e0);
Nprints++;
return;
}
#endif
|
C
|
#include "btree.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void setup(btree_tree *tmp)
{
uint32_t data_idx;
/* Testing with full root node */
btree_insert(tmp, 'F', &data_idx);
btree_insert(tmp, 'Q', &data_idx);
btree_insert(tmp, 'Z', &data_idx);
btree_insert(tmp, 'E', &data_idx);
btree_insert(tmp, 'A', &data_idx);
btree_insert(tmp, 'B', &data_idx);
btree_insert(tmp, 'N', &data_idx);
btree_insert(tmp, 'G', &data_idx);
btree_insert(tmp, 'R', &data_idx);
btree_insert(tmp, 'Y', &data_idx);
btree_insert(tmp, 'H', &data_idx);
btree_insert(tmp, 'C', &data_idx);
btree_insert(tmp, 'D', &data_idx);
btree_insert(tmp, 'I', &data_idx);
btree_insert(tmp, 'L', &data_idx);
btree_insert(tmp, 'T', &data_idx);
btree_insert(tmp, 'q', &data_idx);
btree_insert(tmp, 'w', &data_idx);
btree_insert(tmp, 'e', &data_idx);
btree_insert(tmp, 'r', &data_idx);
btree_insert(tmp, 't', &data_idx);
btree_insert(tmp, 'y', &data_idx);
btree_insert(tmp, 'u', &data_idx);
btree_insert(tmp, 'i', &data_idx);
btree_insert(tmp, 'o', &data_idx);
btree_insert(tmp, 'p', &data_idx);
btree_insert(tmp, 'S', &data_idx);
btree_insert(tmp, 'W', &data_idx);
btree_insert(tmp, 'U', &data_idx);
}
int main(void)
{
btree_tree *tmp;
uint32_t data_idx;
tmp = btree_create("test.mmap", 3, 400, 1024);
if (!tmp) {
printf("Couldn't create tree from disk image.\n");
exit(1);
}
setup(tmp);
btree_insert(tmp, 'd', &data_idx);
btree_insert(tmp, 'f', &data_idx);
btree_insert(tmp, 'v', &data_idx);
btree_delete(tmp, 'i');
btree_delete(tmp, 'f');
btree_delete(tmp, 'e');
btree_delete(tmp, 'y');
btree_delete(tmp, 't');
btree_dump_dot(tmp);
btree_free(tmp);
return 0;
}
|
C
|
# include <stdio.h>
int main(){
char str[1000], Stack[10];
int i, StackN = 0, bracket = 0, ErrorCheck = 0;
gets(str);
for (i = 0 ; str[i] != '\0' ; i++){
if (str[i] == '[' || str[i] == '{' || str[i] == '(' || str[i] == ')' || str[i] == '}' || str[i] == ']'){
bracket++;
}
if (StackN == 0){
if (str[i] == '[' || str[i] == '{' || str[i] == '('){
Stack[StackN] = str[i];
StackN++;
}
else if (str[i] == ')' || str[i] == '}' || str[i] == ']'){
ErrorCheck = 1;
}
}
else {
if (Stack[StackN - 1] == '['){
if (str[i] == ']'){
StackN--;
}
else if (str[i] == '[' || str[i] == '{' || str[i] == '('){
Stack[StackN] = str[i];
StackN++;
}
else if (str[i] == ')' || str[i] == '}'){
ErrorCheck = 1;
}
}
else if (Stack[StackN - 1] == '{'){
if (str[i] == '}'){
StackN--;
}
else if (str[i] == '[' || str[i] == '{' || str[i] == '('){
Stack[StackN] = str[i];
StackN++;
}
else if (str[i] == ')' || str[i] == ']'){
ErrorCheck = 1;
}
}
else if (Stack[StackN - 1] == '('){
if (str[i] == ')'){
StackN--;
}
else if (str[i] == '[' || str[i] == '{' || str[i] == '('){
Stack[StackN] = str[i];
StackN++;
}
else if (str[i] == '}' || str[i] == ']'){
ErrorCheck = 1;
}
}
}
}
if (StackN != 0){
ErrorCheck = 1;
}
if (ErrorCheck == 0){
printf("OK_%d\n", bracket);
}
else {
printf("Wrong_%d\n", bracket);
}
return 0;
}
|
C
|
/*
,* Copyright © 2013, Malcolm Sparks <malcolm@congreve.com>. All Rights Reserved.
,*
,* A program to convert USB firing events from the Dream Cheeky 'Big Red Button' to MQTT events.
,*/
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LID_CLOSED 21
#define BUTTON_PRESSED 22
#define LID_OPEN 23
int main(int argc, char **argv)
{
int fd;
int i, res, desc_size = 0;
char buf[256];
/* Use a udev rule to make this device */
fd = open("/dev/big-red-button", O_RDWR|O_NONBLOCK);
if (fd < 0) {
perror("Unable to open device");
return 1;
}
int prior = LID_CLOSED;
while (1) {
memset(buf, 0x0, sizeof(buf));
buf[0] = 0x08;
buf[7] = 0x02;
res = write(fd, buf, 8);
if (res < 0) {
perror("write");
exit(1);
}
memset(buf, 0x0, sizeof(buf));
res = read(fd, buf, 8);
if (res >= 0) {
if (prior == LID_CLOSED && buf[0] == LID_OPEN) {
printf("Ready to fire!\n");
fflush(stdout);
} else if (prior != BUTTON_PRESSED && buf[0] == BUTTON_PRESSED) {
printf("Fire!\n");
system("sudo /usr/local/bin/big-red-button-command.sh");
fflush(stdout);
} else if (prior != LID_CLOSED && buf[0] == LID_CLOSED) {
printf("Stand down!\n");
fflush(stdout);
}
prior = buf[0];
}
usleep(20000); /* Sleep for 20ms*/
}
}
|
C
|
#include<stdio.h>
int main()
{
int n,f1=0,i,sum=0,f2=1;
scanf("%d",&n);
for(i=2;i<=n;i++)
{
sum=f1+f2;
f1=f2;
f2=sum;
}
printf("%d",f2);
}
|
C
|
#include<stdio.h>
#include<string.h>
main()
{
int a=-4%3;
printf("%d",a);
//int a;
//scanf("%2d",&a);
//printf("%4d",a);
//char s[]="this is garvit";
//char *c=strstr(s,"is");
//printf("%s",c);
//int a=getch();
//printf("U pressed %c",a);
//int a=sizeof(int);
//printf("%d",a);
//int a=floor(-0.5);
//printf("%d",a);
//int val='9'-'a';
//int a=1<< val;
//printf("%d %d",a,val);
}
|
C
|
/*
* Date: 2018-11-08
*
* Description:
* Given a binary array, find the maximum number zeros in an array with one flip
* of a subarray allowed. A flip operation switches all 0s to 1s and 1s to 0s.
*
* Approach:
* - Count number of 0s in original array, call it orig_zeros.
* - Consider all subarrays and find subarary having maximum difference count of
* 1s and 0s, this is the subarray which needs to be swapped to get max 0s.
* - Result would be sum of orig_zeros and max(count_1 - count_0).
*
* Complexity:
* O(N^2)
*
* Reference:
* https://www.geeksforgeeks.org/maximize-number-0s-flipping-subarray/
*/
#include "stdio.h"
#include "stdlib.h"
int main() {
int i = 0, j = 0;
int n = 0;
int *a = NULL;
int orig_zeros = 0, max_1_0_diff = 0;
int count0 = 0, count1 = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
a = (int *)malloc(sizeof(int)*n);
for (i = 0; i < n; i++) {
printf("Enter element[%d]: ", i);
scanf("%d", &a[i]);
}
for (i = 0; i < n; i++) {
count1 = 0;
count0 = 0;
if (!a[i])
orig_zeros++;
for (j = i; j < n; j++) {
(!a[j]) ? count0++ : count1++;
max_1_0_diff = (max_1_0_diff > count1 - count0) ? max_1_0_diff : count1 - count0;
}
}
printf("Max 0's after subarray flip is: %d\n", (orig_zeros + max_1_0_diff));
return 0;
}
/*
* Output:
* ---------------
* Enter number of elements: 9
* Enter element[0]: 0
* Enter element[1]: 1
* Enter element[2]: 0
* Enter element[3]: 0
* Enter element[4]: 1
* Enter element[5]: 1
* Enter element[6]: 0
* Enter element[7]: 1
* Enter element[8]: 1
* Max 0's after subarray flip is: 7
*/
|
C
|
/* ====================================================================
* This file is part of Polylogarithm.
*
* Polylogarithm is licenced under the MIT License.
* ==================================================================== */
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
/** Clausen function with n=2 */
double cl2(double x);
/** Clausen function with n=3 */
double cl3(double x);
/** Clausen function with n=4 */
double cl4(double x);
/** Clausen function with n=5 */
double cl5(double x);
/** Clausen function with n=6 */
double cl6(double x);
/** Clausen function with n=2 with long double precision */
long double cl2l(long double x);
/** Clausen function with n=3 with long double precision */
long double cl3l(long double x);
/** Clausen function with n=4 with long double precision */
long double cl4l(long double x);
/** Clausen function with n=5 with long double precision */
long double cl5l(long double x);
/** Clausen function with n=6 with long double precision */
long double cl6l(long double x);
/** real polylogarithm with n=2 (dilogarithm) */
double li2(double x);
/** real polylogarithm with n=3 (trilogarithm) */
double li3(double x);
/** real polylogarithm with n=4 (trilogarithm) */
double li4(double x);
/** real polylogarithm with n=2 (dilogarithm) with long double precision */
long double li2l(long double x);
/** complex polylogarithm with n=2 (dilogarithm) */
void cli2_c(double re, double im, double* res_re, double* res_im);
/** complex polylogarithm with n=2 (dilogarithm) with long double precision */
void cli2l_c(long double re, long double im, long double* res_re, long double* res_im);
/** complex polylogarithm with n=3 (trilogarithm) */
void cli3_c(double re, double im, double* res_re, double* res_im);
/** complex polylogarithm with n=3 (trilogarithm) with long double precision */
void cli3l_c(long double re, long double im, long double* res_re, long double* res_im);
/** complex polylogarithm with n=4 */
void cli4_c(double re, double im, double* res_re, double* res_im);
/** complex polylogarithm with n=4 with long double precision */
void cli4l_c(long double re, long double im, long double* res_re, long double* res_im);
/** complex polylogarithm with n=5 */
void cli5_c(double re, double im, double* res_re, double* res_im);
/** complex polylogarithm with n=5 with long double precision */
void cli5l_c(long double re, long double im, long double* res_re, long double* res_im);
/** complex polylogarithm with n=6 */
void cli6_c(double re, double im, double* res_re, double* res_im);
/** complex polylogarithm with n=6 with long double precision */
void cli6l_c(long double re, long double im, long double* res_re, long double* res_im);
#ifdef __cplusplus
}
#endif
|
C
|
/* get_passwd.c
* part of watchlist_monitor
*/
#include "watchlist_monitor.h"
int get_passwd(char * password) {
struct termios oflags, nflags;
// disable echo
tcgetattr(fileno(stdin), &oflags);
nflags = oflags;
nflags.c_lflag &= ~ECHO;
nflags.c_lflag |= ECHONL;
if (tcsetattr(fileno(stdin) ,TCSANOW, &nflags) != 0) {
puts("Error setting up STDIN for password prompt");
Cleanup(EXIT_FAILURE);
}
printf("Enter password for db: ");
fgets(password, sizeof(password),stdin);
password[strlen(password)-1] = 0;
// restore terminal echo
if (tcsetattr(fileno(stdin) ,TCSANOW, &oflags) != 0) {
puts("Error setting up STDIN for password prompt");
Cleanup(EXIT_FAILURE);
}
return(EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
#include <string.h>
int main()
{
char a[100],b[100],c[100];
int i;
printf("\nEnter any thing");
gets(a);
printf("\nEnter any thing");
gets(b);
for(i=0;i<strlen(a);i++)
{
c[i]=a[i];
}
for(i=0;i<strlen(b);i++)
{
c[i+strlen(a)]=b[i];
}
printf("\nThe mix is %s",c);
return 0;
}
|
C
|
#include <stdio.h>
int main() {
printTemperatureChange();
return 0;
}
/**
* print C = (5/9)(F-32) ϶Ⱥ϶ȶ
*/
int printTemperatureChange(){
int fahr, celsius;
int lower, upper, step;
lower = 0;//¶ȵ
upper = 300;//¶ȵ
step = 20;//
fahr = lower;
while (fahr <= upper){
celsius = 5 * (fahr - 32) / 9;
printf("%d\t%d\n", fahr, celsius);
fahr = fahr + step;
}
}
|
C
|
/*
* ascensore.c
*
* Created on: 23 dic 2016
* Author: Daniele
*/
#include <stdlib.h>
#include <conio.h>
#include <dos.h>
#include <stdio.h>
void main(void)
{
int pI,
v=0,
row=25,
pF;
clrscr();
//ciclo che disegna quadro ascensore
for (v=0;v<10;v++)
{
gotoxy(8,16+v); putch(57-v);
gotoxy(6,16+v); putch('');
gotoxy(14,16+v); putch('');
}
for (v=0;v<9;v++)
{
gotoxy(6+v,15); putch('_');
}
gotoxy(12,25); putch('');
//---------------------------------------------------
do //ciclo generale si esce per esc
{
do //inserimento del piano
{
gotoxy(20,12); puts("Inserire il piano");
gotoxy(20,13); pI = getch();
} while(! ( (pI>47 && pI < 58) ||(pI==27))); //condizione per far inserire solo numeri tra 0 e 9 o ESC
//---------------------------------------------------
if(pI != 27)
{
pF= 25 - (pI - 48); //(pI - 48) converte il numero in codice ascii
//---------------------------------------------------
if (row!=pF) //se il pI uguale alla pF la cabina non si muove
{
if (row>pF) v=-1; //decremento della riga se la cabina sale
else v=1; // incremento della riga se la cabina scende
do // movimento della cabina
{
gotoxy(12,row); putch(' ');
delay(150);
row+=v;
gotoxy(12,row); putch('');
if (v == -1) //struttura del disegno
{
gotoxy (12,row+1); putch('');
}
if (v == 1)
{
gotoxy (12,row); putch('');
}
if (row == pF)
{
delay(1000);
gotoxy (11,row); printf(" ");
delay(2000);
gotoxy (11,row); printf(" ");
}
//---------------------------------------------------
}while(row!=pF);
}
}
}
while(pI != 27);
}
|
C
|
#ifndef MERGESORT_H
#define MERGESORT_H
// Includes
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
// Structs
typedef struct node{
int data;
struct node* next;
} Node;
// Function declarations
// @description: merges two sorted lists in ascending order and returns a pointer to the head of the list
// @pre: head1 points to the head of list 1, head2 points to the head of list 2. Both lists
// are sorted.
// @post: Returns a pointer to the head in the resulting sorted list.
// @usage: Node* newSortedList = merge(head1, head2);
Node* merge(Node* head1, Node* head2);
// @description: sorts a linked list in ascending order and returns a pointer to the head of the list
// @pre: lhead is a pointer to the first item in the list. lsize contains the size of the list
// @post: Returns a pointer to a sorted list
// @usage: Node* newptr = mergesort(head1, listSize);
Node* mergesort(Node* lhead, int lsize);
// @description: Creates a new node in heap memory
// @pre: data contains the number that should be considered the data item in the node
// @post: Returns a pointer to a node that now exists in the heap
// @usage: Node* newNode = createNode(6);
Node* createNode(int data);
// @description: Creates a linked list of a desired size.
// @pre: size contains the desired size of the linked list
// @post: Returns a pointer to the first node in a linked list of size 'size'
// @usage: Node* newLinkedList = createLinkedList(10);
Node* createLinkedList(int size);
// @description: Returns the size of a linked list
// @pre: head is a pointer to the first node of a linked list
// @post: Returns the size of the linked list
// @usage: int LLSize = getSize(head);
int getSize(Node* head);
// @description: Generates and returns a random number
// @pre: None
// @post: Returns a random number
// @usage: int newRandNum = randNum();
int randNum();
// @description: Prints an error message in case of running out of memory
// @pre: Memory has been overloaded and the function is called from error handler
// @post: Prints an error message to the screen.
// @usage: if (newptr == NULL) { printErrorMemory(); }
void printErrorMemory();
// @description: Prints the contents of a linked list
// @pre: head is a pointer to the first node in a linked list
// @post: Prints the linked list in a nice way
// @usage: printLinkedList(head);
void printLinkedList(Node* head);
// @description: Prints a single node. Helper function for printLinkedList.
// @pre: node is a pointer to the node being printed
// @post: The contents of the node are printed
// @usage: printNode(nodeptr);
void printNode(Node* node);
// @description: Prints an arrow. Helper function for printLinkedList.
// @pre: None
// @post: Prints an arrow to separate Node contents
// @usage: printArrow();
void printArrow();
#endif
|
C
|
// Write the following parameterized macros.
// MEDIAN(x,y,z) - Finds the median of x, y, and z
#include <stdio.h>
#define MAX(x,y) ((x>y) ? (x):(y) )
#define MIN(x,y) ((x<y) ? (x):(y) )
#define MEDIAN(x,y,z) MIN(MIN(MAX(x,y),MAX(y,z)),MAX(z,x))
int main (void)
{
int x, y, z;
printf("Enter three integer: ");
scanf(" %d %d %d", &x, &y, &z);
printf("Median of %d %d %d is %d.\n", x, y, z, MEDIAN(x,y,z));
return 0;
}
|
C
|
#include<stdio.h>
#include<libvirt/libvirt.h>
static int USAGE_THRESHOLD = 60;
struct DomainsList{
virDomainPtr *domains;
int num_domains;
}list;
struct DomainStats{
virDomainPtr domain;
double usage;
long unsigned vcpu_time;
int vcpu_id;
};
int num_cpus=0;
virDomainPtr *dom;
void pinCpus(virDomainPtr *domain, int num_domains, int num_cpus){
printf("Pin CPU\n");
unsigned char a ;
for(int i=0; i<num_domains;){
for(int j=0; j<num_cpus;j++){
a = 1<<(j%num_cpus);
printf("hellosss\n");
virDomainPinVcpu(dom[i],0,&a,VIR_CPU_MAPLEN(num_cpus));
printf("%d\n",i);
i++;
}
}
printf("Pin Cpu exits");
}
unsigned long collectPcpuStats(virConnectPtr conn , int num_cpus){
virNodeCPUStatsPtr params;
int nparams = 0;
unsigned long pcpu_usage_time = 0;
double pcpu[num_cpus];
if (virNodeGetCPUStats(conn, num_cpus, NULL, &nparams, 0) == 0 && nparams != 0) {
if ((params = malloc(sizeof(virNodeCPUStats) * nparams)) == NULL)
goto error;
memset(params, 0, sizeof(virNodeCPUStats) * nparams);
for(int i=0; i<num_cpus; i++)
{
virNodeGetCPUStats(conn, i, params, &nparams, 0);
for (int i=0; i<nparams ; i++){
if(strcmp(params[i].field, VIR_NODE_CPU_STATS_USER) == 0){
pcpu[i] = params[i].value;
pcpu_usage_time += params[i].value;
}
else if(strcmp(params[i].field, VIR_NODE_CPU_STATS_KERNEL) == 0){
pcpu[i] = params[i].value;
pcpu_usage_time += params[i].value;
}
printf("pCPUs: %s usage time: %llu nanosec\n", params[i].field, params[i].value);
}
}
}
return pcpu_usage_time;
error:
exit(1);
}
int main(int arg){
virConnectPtr conn ;
virNodeCPUStatsPtr cpu_stats;
virNodeInfo info;
virDomainPtr *domains;
double pcpu_avg_usage;
double vcpu_avg_usage;
double *cpu_usage;
unsigned char *cpumaps;
struct DomainStats *prev_vcpu_stats = calloc(0, sizeof(prev_vcpu_stats));
struct DomainStats *curr_vcpu_stats = calloc(0, sizeof(prev_vcpu_stats));
unsigned long prev_pcpu_time, curr_pcpu_time;
virDomainStatsRecordPtr *records = NULL;
// connect to the Hypervisor
conn = virConnectOpen("qemu:///system");
if (conn == NULL) {
printf("Error connecting to qemu:///system\n");
return 1;
}
//get all active running virtual machines
list.num_domains = virConnectListAllDomains(conn, &domains, VIR_CONNECT_LIST_DOMAINS_RUNNING);
virConnectListAllDomains(conn, &dom, VIR_CONNECT_LIST_DOMAINS_RUNNING);
list.domains = domains;
printf ("num of domains: %d\n", list.num_domains);
num_cpus = virNodeGetCPUMap(conn, NULL, NULL, 0);
prev_pcpu_time = collectPcpuStats(conn, num_cpus);
if (virNodeGetInfo(conn, &info) == -1){
printf("Error getting node info");
}
while (list.num_domains>0){
curr_pcpu_time = collectPcpuStats(conn, num_cpus);
pcpu_avg_usage = (curr_pcpu_time - prev_pcpu_time)*100/(arg*1000000000/info.cpus);
prev_pcpu_time = curr_pcpu_time;
printf("Average pCPU Usage: %f\n",pcpu_avg_usage);
//connect to the Hypervisor
if (virDomainListGetStats(list.domains, VIR_DOMAIN_STATS_VCPU, &records, 0) == -1){
printf("Error retrieving VCPU stats");
}
for (int i=0; i<list.num_domains; i++){
curr_vcpu_stats[i].domain = list.domains[i];
curr_vcpu_stats[i].vcpu_time = records[i]->params[3].value.ul;
curr_vcpu_stats[i].vcpu_id = i;
curr_vcpu_stats[i].usage = 0;
printf("Domain: %s %s : %lu\n",virDomainGetName(list.domains[i]), records[i]->params[3].field, curr_vcpu_stats[i].vcpu_time);
printf("vCPU Id : %d", curr_vcpu_stats[i].vcpu_id);
printf("Current Vcpu time: %lu\n", curr_vcpu_stats[i].vcpu_time);
printf("Previous Vcpu time: %lu\n\n", prev_vcpu_stats[i].vcpu_time);
curr_vcpu_stats[i].usage = (curr_vcpu_stats[i].vcpu_time - prev_vcpu_stats[i].vcpu_time)*100/(arg*1000000000);
printf("Current Vcpu Usage: %f\n", curr_vcpu_stats[i].usage);
printf("Previous Vcpu Usage: %f\n\n", prev_vcpu_stats[i].usage);
prev_vcpu_stats[i].vcpu_time = curr_vcpu_stats[i].vcpu_time;
prev_vcpu_stats[i].vcpu_id = curr_vcpu_stats[i].vcpu_id;
prev_vcpu_stats[i].usage = curr_vcpu_stats[i].usage;
vcpu_avg_usage += curr_vcpu_stats[i].usage;
}
vcpu_avg_usage = vcpu_avg_usage/list.num_domains;
pinCpus(list.domains,list.num_domains, num_cpus);
sleep(arg);
}
}
|
C
|
/* Program to copy n chars of first string to end of another String*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
int no;
char *str1,*str2;
void xstrncat(char* str1,char* str2,int no);
str1=(char*)malloc(1000);
str2=(char*)malloc(1000);
// Get the Strings from the user
printf("\nEnter First String: ");
gets(str1);
printf("\nEnter Second String: ");
gets(str2);
printf("\nEnter Number of Chars To Be copied: ");
scanf("%d",&no);
realloc(str1,sizeof(char)*(strlen(str1)+1+n));
realloc(str2,sizeof(char)*(strlen(str2)+1));
xstrncat(str1,str2,no);
puts(str1);
}
/*
*Function which copies n chaechters of String2 at the end of String1.
*Parameters : Base add. of String1(Target String)
: Base add. of String2(Source String)
: Integer representing no. of charecters to be copied.
*Returns : void
*/
void xstrncat(char* str1,char* str2,int no)
{
while(*(str1++) !='\0');// Take Pointer to the end of target String.
// Copy n charecters of Source String to the Target String.
for(str1--;no!=0;no--,str1++,str2++)
if(str2 != '\0')
*str1=*str2;
*str1='\0';
}
|
C
|
#ifndef __LISTA_H
#define __LISTA_H
/*-----------------------------------------------------------------
TAD Lista
-------------------------------------------------------------------
*/
typedef int TipoL;
typedef struct ListaNodo
{ TipoL info;
struct ListaNodo *ant, *sig;
} ListaNodo, *pListaNodo;
typedef struct TLista
{ pListaNodo primero, ultimo, ventana;
int longitud;
} TLista, *Lista;
typedef pListaNodo Ventana;
/*-------------------------------------------------------------------*/
/* OPERACIONES */
/*-------------------------------------------------------------------*/
/*-------------------------------------------------------------------*/
/* Constructora */
/*-------------------------------------------------------------------*/
/* Crea y retorna una lista vac�a */
Lista inicLista(void);
/*-------------------------------------------------------------------*/
/* Modificadoras */
/*-------------------------------------------------------------------*/
/* Agrega un elemento despu�s de la ventana */
void anxLista(Lista lst, TipoL elem);
/* Agrega un elemento antes de la ventana */
void insLista(Lista lst, TipoL elem);
/* Elimina el elemento que se encuentra en la ventana */
void elimLista(Lista lst,void (*pf)(void *));
/* Avanza la ventana una posicion */
void sigLista(Lista lst);
/* Coloca la ventana sobre el primer elemento de la lista */
void primLista(Lista lst);
/* Coloca la ventana sobre el �ltimo elemento de la lista */
void ultLista(Lista lst);
/* Coloca la ventana sobre el pos-�simo elemento de la lista */
void posLista(Lista lst, int pos);
/* Coloca la ventana de una lista sobre la marca dada */
void situarLista(Lista lst, Ventana vent);
/* Concatenar Lista */
void concatenarLista(Lista lst1, Lista lst2);
/*-------------------------------------------------------------------*/
/* Analizadoras */
/*-------------------------------------------------------------------*/
/* Retorna el elemento de la ventana */
TipoL infoLista(Lista lst);
/* Retorna el n�mero de elementos de la lista */
int longLista(Lista lst);
/* Informa si la ventana esta indefinida */
int finLista(Lista lst);
/* Retorna una marca sobre la ventana actual de la lista */
Ventana ventanaLista(Lista lst);
/* Recorrer lista */
void recorrerLista(Lista lst, void (*f)(int));
/*-------------------------------------------------------------------*/
/* Destructora */
/*-------------------------------------------------------------------*/
/* Destruye el objeto abstracto, retornando toda la memoria ocupada por �ste */
void destruirLista(Lista lst,void (*pf)(void *));
/*-------------------------------------------------------------------*/
/* Persistencia */
/*-------------------------------------------------------------------*/
/* Construye una lista a partir de la informaci�n de un archivo */
Lista cargarLista(FILE *fp);
/* Salva la lista en un archivo */
void salvarLista(Lista lst, FILE *fp);
/*-------------------------------------------------------------------*/
/* Depuracion */
/*-------------------------------------------------------------------*/
/* Muestra por pantalla toda la lista y la posici�n de la ventana */
void impLista(Lista lst);
/*--------------------------------------------------------------------*/
#endif
|
C
|
/**
Extremely simple singly-linked list of ints.
Everything is IN the list, no external pointers.
*/
#ifndef INLIST_H
#define INLIST_H
#include <stdbool.h>
#include <stdlib.h>
struct inlist_item
{
int data;
struct inlist_item* next;
};
struct inlist
{
struct inlist_item* head;
struct inlist_item* tail;
int size;
};
struct inlist* inlist_create(void);
struct inlist_item* inlist_add(struct inlist* target, int data);
#define inlist_push(target, data) inlist_add(target, data)
struct inlist* inlist_parse(char* s);
int inlist_search(struct inlist* target, int data);
int inlist_random(struct inlist* target);
bool inlist_remove(struct inlist* target, int data);
int inlist_pop(struct inlist* target);
int inlist_peek(struct inlist* target);
int inlist_poll(struct inlist* target);
struct inlist_item* inlist_ordered_insert(struct inlist* target,
int data);
bool inlist_contains(struct inlist* target, int data);
void inlist_printf(struct inlist* target);
/*
int inlist_tostring(char* str, size_t size,
struct inlist* target); */
char* inlist_serialize(struct inlist* target);
void inlist_free(struct inlist* target);
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define flags ((volatile char*)(0x1000))
void inline sieve(void) {
int i, prime, kv, count, iter, size;
size=600;
for (iter = 1;iter < 10;iter ++) {
count = 0;
for (i = 0; i <= size; i++) {
flags[i] = 1;
}
for (i = 0; i <= size; i++) {
if (flags[i]) {
prime = i + i + 3;
kv = 1 + prime;
while (kv <= size) {
flags[kv] = 0;
kv += prime;
}
count = count + 1;
}
}
}
}
int main(uint8_t a, uint8_t b) {
uint8_t k = 0, sum = 0, i;
do {
k--;
uint8_t l = k + k;
*(uint8_t*)(0x200 + k) = l;
*(uint8_t*)(0x300 + l) = k;
} while (k > 0);
sum = 0;
for (i = 0; i < a; ++i) {
sum += b;
}
sieve();
return sum;
}
|
C
|
#include<stdio.h>
#include"stack.h"
#include"dirlist.h"
#define V 8
link_t adj[V];
int visited[V]={0};
void visit(int vertex)
{
printf("%d ",vertex);
}
void Push(link_t head)
{
if(head==NULL)
return;
Push(Next(head));
if(visited[Item(head)]==0)
stackPush(Item(head));
}
void traverse(int k,void (*visit)(int))
{
link_t x;
int t;
stackInit(100);
stackPush(k);
while(!stackEmpty()){
t=stackPop();
if(visited[t]==0)
visit(t);
visited[t]=1;
Push(adj[t]);
}
}
void print_list(link_t head[])
{
link_t x;
int i;
for(i=0;i<V;i++){
printf("%d:",Item(head[i]));
for(x=Next(head[i]);x!=NULL;x=Next(x))
printf("%d ",Item(x));
putchar('\n');
}
}
int main(void)
{
link_t t;
int i,j,start=0;
FILE *fp;
fp=fopen("adjacency_list_graph_traversal_depth_first_search_stack.dat","r");
for(i=0;i<V;i++){
adj[i]=allocNode(i);
adj[i]->next=NULL;
}
while(fscanf(fp,"%d%d",&i,&j)==2){
t=allocNode(j);
insertNext(adj[i],t);
t=allocNode(i);
insertNext(adj[j],t);
}
fclose(fp);
print_list(adj);
putchar('\n');
puts("traverse:");
traverse(start,visit);
putchar('\n');
return(0);
}
|
C
|
/* run.config
OPT: -wp-no-print -wp-rte -no-warn-signed-overflow
*/
/* run.config_qualif
OPT: -then -wp-rte -no-warn-signed-overflow -wp
*/
// note: exo hors vérification de l'absence de débordements
/* ************/
/* Solution de TP donné par Julien à L'IFIPS */
/* ************/
/* Un sous-tableau [b] d'un tableau [a] est un sous-ensemble d'éléments
contigüs de [a]. Par exemple, si a = { 0, 3, -1, 4 }, des sous-tableaux
possibles sont {}, { 0 }, { 3, -1 }, { 0, 3, -1, 4 }.
Un sous-tableau de [a] est dit maximal si la somme de ses éléments est au
moins aussi grande que celle de n'importe quel autre sous-tableau de
[a]. L'unique sous-tableau maximal de l'exemple précédent est { 3, -1, 4 }.
Les sous-tableaux de taille 0 étant autorisés, un tableau avec uniquement des
valeurs négatives a une somme maximale de 0.
La fonction [max_subarray(a, len)] retourne la somme d'un sous-tableau
maximal de [a], [len] étant la longueur de [a]. */
/*
Questions:
1. Donner une spécification en ACSL de cette fonction. Vous pouvez vous aider
de la fonction logique [sum(int *a, integer low, integer high, integer len)]
calculant la somme des éléments entre les indices [low] et [high] (inclus)
d'un tableau [a] de longueur [len] et dont une version axiomatisée est
fournie.
2. Modifier le programme de manière à ajouter 3 variables ghosts [cur_low],
[low] et [high] calculant respectivement:
- l'indice minimum du sous-tableau duquel on est en train de calculer la
somme courante [cur];
- l'indice minimum du sous-tableau maximal courant;
- l'indice maximum du sous-tableau maximal courant;
3. Prouver cette fonction avec WP et Alt-Ergo. Prouver la terminaison et
l'absence d'accès mémoire indéfini, mais pas l'absence de débordements
arithmétiques. Les options à fournir à Frama-C pour cela sont, dans cet
ordre: -rte -no-warn-signed-overflow -then -wp
*/
/*@ axiomatic Sum {
logic integer sum(int *a, integer low, integer high, integer len)
reads a[low..high];
axiom base: \forall integer low, high,len; \forall int *a;
low > high ==> sum(a, low, high, len) == 0;
axiom ind: \forall integer low, high,len; \forall int *a;
0 <= low <= high < len ==>
sum(a, low, high, len) == a[high] + sum(a, low, high-1, len);
} */
/*@ requires len >= 0;
@ requires \valid(a+(0..len-1));
@ ensures \forall integer l, h;
@ 0 <= l <= h <= len ==> sum(a,l,h-1,len) <= \result;
@ ensures \exists integer l, h;
@ 0 <= l <= h <= len && sum(a,l,h-1,len) == \result;
@ assigns \nothing;
@ */
int max_subarray(int *a, int len) {
int max = 0;
int cur = 0;
/*@ ghost int cur_low = 0, low = 0, high = 0; */
/*@ loop invariant 0 <= i <= len;
@ loop invariant 0 <= low <= high <= i;
@ loop invariant 0 <= cur_low <= i;
@
@ loop invariant cur <= max;
@ loop invariant cur == sum(a,cur_low,i-1,len);
@ loop invariant max == sum(a,low,high-1,len);
@
@ loop invariant \forall integer l;
@ 0 <= l <= i ==> sum(a,l,i-1,len) <= cur;
@
@ loop invariant \forall integer l, h;
@ 0 <= l <= h <= i <= len ==> sum(a,l,h-1,len) <= max;
@
@ loop assigns i, cur, max, cur_low, low, high;
@ loop variant len - i; */
for(int i = 0; i < len; i++) {
cur = a[i] + cur;
if (cur < 0) {
cur = 0;
/*@ ghost cur_low = i+1; */
}
if (cur > max) {
max = cur;
/*@ ghost low = cur_low; */
/*@ ghost high = i+1; */
}
}
return max;
}
|
C
|
#include<stdio.h>
#include<sys/time.h>
#include<math.h>
#define max 179424673
double getTime(int);
main()
{
double start,stop,elapsedTime;
int n;
long int count=0,cnt=0,i,j,k;
static long int prime[max],p=2;
start=getTime(-6);
printf("%lf\n",start);
prime[0]=prime[1]=1;
for(j = 2;j <= max+1;j++){
if(prime[j] == 0){
i=j;
for(k = 2*i;k <= max+1; k = k+i){
prime[k] = 1;
}
}
}
for(p=2;p<max+1;p++)
{
if(prime[p]==0)
{
count++;
}
}
stop=getTime(-6);
elapsedTime=stop-start;
printf("Elapsed Time: %lf\n",elapsedTime);
printf("Count: %ld\n",count);
}
double getTime(int n)
{
double time;
struct timeval tv;
gettimeofday(&tv,NULL);
printf("%d\n",n);
time=(tv.tv_sec*pow(10,6)+tv.tv_usec)/pow(10,6+(-6));
return time;
}
|
C
|
/**
* This file is part of the FabricDB library
*
* Author: Mark Wardle <mark@themarkside.com>
* Created: March 29, 2015
* Updated: March 29, 2015
*/
#include <stdio.h>
#include <assert.h>
#ifndef _FABRIC_TEST_ALL__
#include "Fabric.c"
#endif
typedef struct EMapDummy {
uint32_t id;
uint32_t value;
} EMapDummy;
EMapDummy **generate_emap_dummies(int value_change) {
EMapDummy **dummies = Fabric_memalloc(50 * sizeof(EMapDummy*));
assert (dummies != NULL);
EMapDummy *dummy;
int i;
for (i = 0; i < 50; i++) {
dummy = Fabric_memalloc(sizeof(EMapDummy));
assert(dummy != NULL);
dummy->id = (i + 1) * 3;
dummy->value = dummy->id + value_change;
dummies[i] = dummy;
}
return dummies;
}
void free_emap_dummies(EMapDummy **dummies) {
int i;
for (i = 0; i < 50; i++) {
Fabric_memfree(dummies[i], sizeof(EMapDummy));
}
Fabric_memfree(dummies, 50 * sizeof(EMapDummy*));
}
void test_entity_map() {
#ifndef _FABRIC_TEST_ALL__
Fabric_meminit();
#endif
error_t status;
int i, id;
EMapDummy **dummies = generate_emap_dummies(0);
EMapDummy **changed_dummies = generate_emap_dummies(1);
EMapDummy *dummy;
size_t mem_used_start = Fabric_memused();
EntityMap *map = Fabric_EntityMap_new(&status);
assert(map != NULL);
assert(status == FABRIC_OK);
assert(mem_used_start < Fabric_memused());
assert(Fabric_EntityMap_get_count(map) == 0);
assert(Fabric_EntityMap_get_capacity(map) == FABRIC_ENTITYMAP_DEFAULT_CAPACITY);
for (i = 0; i < 50; i++) {
dummy = dummies[i];
assert(FALSE == Fabric_EntityMap_has_key(map, dummy->id));
status = Fabric_EntityMap_set(map, dummy->id, dummy);
assert(status == FABRIC_OK);
assert(TRUE == Fabric_EntityMap_has_key(map, dummy->id));
assert(Fabric_EntityMap_get_count(map) == i + 1);
assert(Fabric_EntityMap_get(map, dummy->id) == dummy);
}
assert(Fabric_EntityMap_get_count(map) == 50);
assert(Fabric_EntityMap_get_capacity(map) > 50);
for (id = 4; i <= 150; i += 4) {
if (id % 3 == 0) {
int start_count = Fabric_EntityMap_get_count(map);
assert(TRUE == Fabric_EntityMap_has_key(map, id));
assert(dummies[id / 3 - 1] == Fabric_EntityMap_get(map, id));
Fabric_EntityMap_unset(map, id);
assert(FALSE == Fabric_EntityMap_has_key(map, id));
assert(NULL == Fabric_EntityMap_get(map, id));
assert(start_count - Fabric_EntityMap_get_count(map) == 1 );
assert(Fabric_EntityMap_get_count(map) == 50 - id / 12);
} else {
assert(FALSE == Fabric_EntityMap_has_key(map, id));
assert(NULL == Fabric_EntityMap_get(map, id));
}
}
for (i = 0; i < 50; i++) {
dummy = changed_dummies[i];
if (Fabric_EntityMap_has_key(map, dummy->id)) {
assert(((EMapDummy*)Fabric_EntityMap_get(map, dummy->id))->value == dummy->id);
}
status = Fabric_EntityMap_set(map, dummy->id, dummy);
assert(((EMapDummy*)Fabric_EntityMap_get(map, dummy->id))->value == dummy->id + 1);
}
Fabric_EntityMap_destroy(map);
assert(mem_used_start == Fabric_memused());
free_emap_dummies(dummies);
free_emap_dummies(changed_dummies);
printf("All tests passed for entity map.\n");
}
#ifndef _FABRIC_TEST_ALL__
int main() {
test_entity_map();
return 0;
}
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
struct elt {
struct elt *next;
int value;
};
typedef struct elt *Stack;
#define STACK_EMPTY (0)
void stackPush(Stack *s, int value) {
struct elt *e;
e = malloc(sizeof(struct elt));
assert(e);
e->value = value;
e->next = *s;
*s = e;
}
int stackEmpty(Stack *s) {
return (*s == 0);
}
int stackPop(Stack *s) {
int value;
struct elt *e;
value = (*s)->value;
e = *s;
*s = e->next;
free(e);
return value;
}
void stackPrint(Stack *s) {
struct elt *e;
e = *s;
while (e != 0) {
printf("%d ", e->value);
e = e->next;
}
putchar('\n');
}
void stackPrintReversed(struct stack *first) {
struct stack *elt;
Stack s2;
s2 = stackCreate();
for(elt = first; elt != 0; elt = elt->next) {
s2 = stackPush(s2, elt->book);
}
stackPrint(s2);
stackDestroy(s2);
}
void stackPrintReversedRecursive(struct stack *first) {
if (first != 0) {
stackPrintReversedRecursive(first->next);
puts(first->value);
}
int main(int argc, char **argv) {
int i;
Stack s;
for (i = 0; i < 5; i++) {
printf("pushing %d\n", i);
stackPush(&s, i);
stackPrint(&s);
}
while(!stackEmpty(&s)) {
printf("pop gets %d\n", stackPop(&s));
stackPrint(&s);
}
return 0;
}
|
C
|
#ifndef _BMP_H
#define _BMP_H
/**
* Return reversed string.
*
* Function returns a pointer to the reversed string, which has been created from the input parameter.
* If the input string is NULL or memory could not be allocated, function returns NULL.
*
* @param text - input string
* @return reversed representation of input string, or NULL, if the string could not be created.
*/
char* reverse(const char* text);
/**
* Function for encrypting the given plaintext by applying the Vigenère cipher.
*
* @param key - Reference to a string representing the key which will be used for encrypting the plaintext.
* The key is represented by a single case-insensitive word consisting of only alphabetical characters.
* @param text - Reference to a string representing the plaintext to be encrypted.
* @return the address of a copy of the ciphertext encrypted by the Vigenère cipher,
* or NULL if the encryption was not successful.
*/
char* vigenere_encrypt(const char* key, const char* text);
/**
* Function for decrypting the given ciphertext by applying the Vigenère cipher.
*
* @param key - Reference to a string representing the key which has been used for encrypting the ciphertext.
* The key is represented by a single case-insensitive word consisting of only alphabetical characters.
* @param text - Reference to a string representing the ciphertext to be decrypted.
* @return the address of a copy of the plaintext decrypted by the Vigenère cipher,
* or NULL if the decryption was not successful.
*/
char* vigenere_decrypt(const char* key, const char* text);
/**
* Function for bitwise encryption according to the following process:
* The character about to be encrypted is divided in half (4 bits + 4 bits).
* Subsequently, the bits in the left half are divided into two pairs and the values inside each pair are swapped.
* The four bits created by this way are then used in a bitwise XOR operation with the remaining 4 bits.
*
* @param text - String representing the plaintext to be encrypted.
* @return a pointer to a newly created string containing the ciphertext produced by encrypting the plaintext,
* or NULL if the encryption was not successful.
*/
unsigned char* bit_encrypt(const char* text);
/**
* Function for bitwise decryption - it is the inverse of the bitwise encryption function.
*
* @param text - String representing the ciphertext to be decrypted.
* @return a pointer to a newly created string containing the plaintext produced by decrypting the ciphertext,
* or NULL if the decryption was not successful.
*/
char* bit_decrypt(const unsigned char* text);
/**
* Function for encrypting the given plaintext by applying the BMP cipher.
* The process of encrypting by BMP:
* <ol>
* <li> the provided input string is encrypted by function reverse()
* <li> the acquired string is encrypted by function vigenere_encrypt()
* <li> function bit_encrypt() is applied on the resulting string
* </ol>
*
* @param key - Reference to a string representing the key which will be used for encrypting the plaintext.
* The key is represented by a single case-insensitive word consisting of only alphabetical characters.
* @param text - String representing the plaintext to be encrypted.
* @return the address of a copy of the ciphertext encrypted by the BMP cipher,
* or NULL if the encryption was not successful.
*/
unsigned char* bmp_encrypt(const char* key, const char* text);
/**
* Function for decrypting the given ciphertext by applying the BMP cipher.
* The process of decrypting by BMP is the opposite of BMP encryption.
*
* @param key - Reference to a string representing the key which has been used for encrypting the ciphertext.
* The key is represented by a single case-insensitive word consisting of only alphabetical characters.
* @param text - String representing the ciphertext to be decrypted.
* @return the address of a copy of the plaintext decrypted by the BMP cipher,
* or NULL if the decryption was not successful.
*/
char* bmp_decrypt(const char* key, const unsigned char* text);
int chek_key(const char* key);
int switchbit(const int value, const int position);
int checkbit(const int value, const int position);
int swapbit(const unsigned char value, const int firstbit, const int secondbit);
int bitcpy(unsigned char* source, const int number_starbit_source, const unsigned char destination, const int number_starbit_destination, const int amountbit);
#endif
|
C
|
/**************************************************************************
***************************************************************************
W E G A - Quelle (C) ZFT/KEAW Abt. Basissoftware - 1988
Programm: format.c
Bearbeiter : P. Hoge
Datum : 30.11.89
Version : 1.6
***************************************************************************
WEGA P8000 Floppy-Format
Syntax: format [/dev/rfd...]
***************************************************************************
**************************************************************************/
#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#define FLOPPY 1 /* Major-Nummer des Floppy-Treibers */
#define ACK 0x06
main(argc, argv)
int argc;
char **argv;
{
register char *progname = argv[0];
register char *fdname = "/dev/rfd1";
register dd;
char buf;
struct stat stbuf;
char *ttyname();
if (argc > 2) {
fprintf(stderr,"Usage: %s [/dev/rfd...]\n", progname);
exit(1);
}
if (argc == 2)
fdname = *++argv;
if ((dd = open("/dev/ud", 2)) == -1) {
fprintf(stderr,"%s: unable to work with floppy\n", progname);
exit(1);
}
if (stat(fdname, &stbuf) == -1) {
fprintf(stderr,"%s: unable to open %s\n", progname, fdname);
exit(1);
}
if ((stbuf.st_mode & (S_IFCHR | S_IFBLK)) == 0 || /* special file ? */
(stbuf.st_rdev >> 8) != FLOPPY) { /* floppy ? */
fprintf(stderr,"%s: %s is not a floppy device\n",progname,fdname);
exit(1);
}
/* wenn im Hintergrund keine Abfrage */
if (strcmp(ttyname(0), "/dev/console") == 0) {
printf("Format %s, ready ? ", fdname);
if ((getchar() & 0x5f) != 'Y')
exit(1);
}
/* Programm darf nicht abgebrochen werden */
signal(SIGALRM, SIG_IGN);
signal(SIGHUP, SIG_IGN);
signal(SIGINT, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
signal(SIGTERM, SIG_IGN);
buf = 'F';
write(dd, &buf, 1); /* Start Request F: Format */
buf = stbuf.st_rdev; /* Minornummer (Typ + Drivenr.) */
write(dd, &buf, 1);
read(dd, &buf, 1); /* warten auf ACK oder Fehlerkode */
if (buf != ACK) {
fprintf(stderr,"%s: \007ERROR %x - ", progname, buf&0x0ff);
if (buf == 0x0C2)
fprintf(stderr,"drive not ready\n");
else if (buf == 0x0C3)
fprintf(stderr,"disk is write protected\n");
else
fprintf(stderr,"disk verification error\n");
exit(2);
}
putchar(7); /* Bell */
exit(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char x[101],y[101];
int a,b;
scanf("%s %s",x,y);
a=strlen(x);
b=strlen(y);
if(a>b)
{
printf("%s",x);
}
else if(a==b)
{
printf("%s",x);
}
else
{
printf("%s",y);
}
return 0;
}
|
C
|
#define print(a) printf("The value of " #a " is %d\n", a);
#include <stdio.h>
int main() {
int num = 7;
print(num)
return 0;
}
|
C
|
#include <stdio.h>
int main( void )
{
int integer1; /* first number to be input by user */
int integer2; /* second number to be input by user */
int result; /* variable in which result will be stored */
printf( "Enter first integer:\n" ); /* prompt */
scanf( "%d", &integer1 ); /* read an integer */
printf( "Enter second integer:\n" ); /* prompt */
scanf( "%d", &integer2 ); /* read an integer */
if(integer1 > integer2)
{
printf("integer1 is greater than integer2\n");
}
else if(integer1 < integer2)
{
printf("integer2 is greater than integer1\n");
}
else
{
printf("both numbers are equal\n");
}
return 0;
}
|
C
|
#include <stdio.h>
/**
* main - entry point
* Return: 0
*/
int main(void)
{
int x;
char y;
for (x = 0; x < 16; x++)
{
if (x < 10)
putchar(x + 48);
else
{
y = 97 + x % 10;
putchar(y);
}
}
putchar('\n');
return (0);
}
|
C
|
#include <stdio.h>
//int main() {
// //! showMemory(cursors=[matrix[0], matrix[1]], start=65520)
// //! matrix = showArray2D(matrix, rowCursors=[line], colCursors=[col])
// int matrix[2][3];
// int line, col;
// for(line = 0; line < 2; line++){
// for(col = 0; col < 3; col++){
// scanf("%d", &matrix[line][col]);
// }
// }
// for(line = 0; line < 2; line++){
// for(col = 0; col < 3; col++){
// printf("%d ", matrix[line][col]);
// }
// printf("\n");
// }
// return 0;
//}
////Exercise 9.1 Print String Lengths
//void printStrLen(char **, int);
//
//int main(){
// char *input[3] = {"x", "55", "ab34"};
// printStrLen(input, 3);
//}
//
//void printStrLen(char** input, int num) {
// for (int i = 0; i < num; ++i) {
// int n = 0;
// while (input[i][n] != '\0') {
// n++;
// }
// printf("%d\n", n);
// }
//}
//Assignment 9.1 Copy String
//void copyStr(char *, char *);
//
//int main() {
// char *source = "abc";
// char target[101];
// copyStr(source, target);
// printf("%s", target);
//}
//
//void copyStr(char * source, char * target) {
// while ((*target = *source) != '\0')
// {
// target++;
// source++;
// }
//}
//Assignment 9.2 Count End Char
//int countEndChar(char **, int, char);
//
//int main() {
// char *input[5] = {"breaking", "bad", "abcd", "covid", "panda"};
// printf("%d", countEndChar(input, 5, 'd'));
//}
//
//int countEndChar(char ** input, int size, char endChar) {
// int out = 0;
// for (int i = 0; i < size; ++i) {
// int n = 0;
// while (input[i][n] != '\0') {
// n++;
// }
// if (input[i][n-1] == endChar) {
// out++;
// }
// }
// return out;
//}
//Assignment 9.3 Distinct Characters
int distinctChar(char**, int);
int main() {
char* input[3] = { "abcdea", "bbb", "de" };
printf("%d", distinctChar(input, 3));
//distinctChar(input, 3);
}
int distinctChar(char** input, int size) {
int result = 0;
char appear[256] = {0};
for (int i = 0; i < size; i++) {
char* cur = input[i];
while (*cur) {
appear[(int) (*cur++)] = i == 0;
}
}
for (int i = 0; i < 256; i++) {
result += appear[i];
}
return result;
}
|
C
|
/*2) Elaborar um programa que determine a potncia de um nmero. O usurio informa a base e o expoente e o
programa informa o resultado da base elevada ao expoente. No usar funes prontas do C para fazer o clculo da
potncia.
*/
#include <stdio.h>
int main(void)
{
int num,pote,i,produto=1;
printf("Informe o valor da base: ");
scanf("%d",&num);
printf("Informe o valor do expoente: ");
scanf("%d",&pote);
for (i=1; i<=pote;i++)
{
if (i<pote){
produto= produto * num;
printf("%d * ",num);
}
if (i==pote)
{
produto= produto * num;
printf("%d = ",num);
}
}
printf("%d",produto);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* printf.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ccatoire <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/11/16 14:58:15 by ccatoire #+# #+# */
/* Updated: 2017/11/16 14:58:15 by ccatoire ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
int conv_o(va_list ap, t_flag_list t_fl)
{
unsigned int nb;
char *conv;
size_t size;
//Si nb = 0 ou quon affiche pas la val -> size = 0 (pour le return)
nb = va_arg(ap, unsigned int);
conv = ft_convu_nbase(nb, 8);
size = 0;
if (t_fl.put_val || nb)
size = ft_strlen(conv);
//calcul : width, prec, field | Define : c_sign, c_width
if (!((t_fl.sharp && nb) || (t_fl.sharp && !t_fl.put_val)))
t_fl.sharp = 0;
calc_wp_num_base(&t_fl, size + t_fl.sharp, 0);
//affichage largeur de champ a gauche (sans -)
if (!t_fl.min)
ft_putnchar(t_fl.c_width, t_fl.width);
//affichage de la precision
ft_putnchar('0', t_fl.prec);
//gestion flag #
if ((t_fl.sharp && nb) || (t_fl.sharp && !t_fl.put_val))
ft_putchar('0');
//affichage de la valuer
if (t_fl.put_val || nb)
ft_putstr(conv);
//affichage largeur de champ a droite (avec -)
if (t_fl.min)
ft_putnchar(t_fl.c_width, t_fl.width);
ft_strdel(&conv);
return (t_fl.field);
}
int conv_x(va_list ap, t_flag_list t_fl)
{
// ft_putchar('(');
unsigned int nb;
char *conv;
size_t size;
//Si nb = 0 ou quon affiche pas la val -> size = 0 (pour le return)
nb = va_arg(ap, unsigned int);
conv = ft_convu_nbase(nb, 16);
size = 0;
if (t_fl.put_val || nb)
size = ft_strlen(conv);
if (!nb)
t_fl.sharp = 0;
//calcul : width, prec, field | Define : c_sign, c_width
calc_wp_num_base(&t_fl, size, (t_fl.sharp * 2));
//affichage largeur de champ a gauche (sans -)
if (!t_fl.min)
ft_putnchar(t_fl.c_width, t_fl.width);
//gestion flag #
if (t_fl.sharp && (nb || t_fl.put_val))
ft_putstr("0x");
//affichage de la precision
if(t_fl.put_val)
ft_putnchar('0', t_fl.prec);
//affichage de la valuer
if (t_fl.put_val || nb)
ft_putstr(conv);
//affichage largeur de champ a droite (avec -)
if (t_fl.min)
ft_putnchar(t_fl.c_width, t_fl.width);
ft_strdel(&conv);
// ft_putchar(')');
return (t_fl.field);
}
int conv_xm(va_list ap, t_flag_list t_fl)
{
unsigned int nb;
char *conv;
size_t size;
//Si nb = 0 ou quon affiche pas la val -> size = 0 (pour le return)
nb = va_arg(ap, unsigned int);
conv = ft_convu_nbase(nb, 16);
size = 0;
if (t_fl.put_val || nb)
size = ft_strlen(conv);
if (!nb)
t_fl.sharp = 0;
//calcul : width, prec, field | Define : c_sign, c_width
calc_wp_num_base(&t_fl, size, (t_fl.sharp * 2));
//affichage largeur de champ a gauche (sans -)
if (!t_fl.min)
ft_putnchar(t_fl.c_width, t_fl.width);
//gestion flag #
if (t_fl.sharp && (nb || t_fl.put_val))
ft_putstr("0X");
//affichage de la precision
ft_putnchar('0', t_fl.prec);
//affichage de la valuer
if (t_fl.put_val || nb)
ft_putstr(ft_strupper(conv));
//affichage largeur de champ a droite (avec -)
if (t_fl.min)
ft_putnchar(t_fl.c_width, t_fl.width);
ft_strdel(&conv);
return (t_fl.field);
}
int conv_p(va_list ap, t_flag_list t_fl)
{
unsigned long nb;
char *conv;
size_t size;
//Si nb = 0 ou quon affiche pas la val -> size = 0 (pour le return)
nb = va_arg(ap, unsigned long);
conv = ft_convlu_nbase(nb, 16);
// printf("conv = %s\n", conv);
size = 0;
if (t_fl.put_val || nb)
size = ft_strlen(conv);
//calcul : width, prec, field | Define : c_sign, c_width
calc_wp_num_base(&t_fl, size /*+ 2*/, 2);
//affichage largeur de champ a gauche (sans -)
if (!t_fl.min)
ft_putnchar(t_fl.c_width, t_fl.width);
//affichage de la precision
ft_putstr("0x");
ft_putnchar('0', t_fl.prec);
//affichage de la valuer
if (t_fl.put_val || nb)
ft_putstr(conv);
//affichage largeur de champ a droite (avec -)
if (t_fl.min)
ft_putnchar(t_fl.c_width, t_fl.width);
ft_strdel(&conv);
return (t_fl.field);
}
int conv_zid(va_list ap, t_flag_list t_fl)
{
ssize_t nb;
size_t size;
nb = va_arg(ap, ssize_t);
//Si nb = 0 ou quon affiche pas la val-> size = 0 (pour le return)
size = 0;
if (t_fl.put_val || nb)
size = ft_count_udigit(ft_abs_ll(nb));
//Verifier la negativiter
if (nb < 0)
t_fl.neg = 1;
//calcul : width, prec, field | Define : c_sign, c_width
calc_wp_num(&t_fl, size, 1);
//affichage largeur de champ a gauche (sans -)
if (!t_fl.min && !t_fl.zero)
ft_putnchar(t_fl.c_width, t_fl.width);
//affichage du signage
if (t_fl.plus || t_fl.space || t_fl.neg)
ft_putchar(t_fl.c_sign);
//affiche largeur de champ en 0 apres signage si flag 0
if (!t_fl.min && t_fl.zero)
ft_putnchar(t_fl.c_width, t_fl.width);
//affichage de la precision
ft_putnchar('0', t_fl.prec);
//affichage de la valuer
if (t_fl.put_val || nb)
ft_putunbr(ft_abs_l(nb));
//affichage largeur de champ a droite (avec -)
if (t_fl.min)
ft_putnchar(t_fl.c_width, t_fl.width);
return (t_fl.field);
}
|
C
|
/*3) Faca um programa para calcular a quantidade necessria de latas de tinta para pintar
uma parede com X metros de largura por H metros de altura. Tambm informada a altura e largura da
porta e das janelas e a quantidade de janelas. As janelas possuem o mesmo tamanho.
O usurio informa o consumo de tinta por metro quadrado e a quantidade de litros de tinta de uma lata.
Indicar a quantidade inteira para o nmero de latas de tinta necessrio (arredondar o valor para o prximo inteiro).*/
#include<stdio.h>
int main(void)
{
float largP, alturaP, TotalP, PinturaTotal;
float largJan, alturaJan, TotalJan;
int numPort, numJan, NumTdLatas;
float largPort, alturaPort, TotalPort;
float consTintM4, litrosLata, NumerDTinta;
printf("Informe a largura da parede: ");
scanf("%f",& largP);
printf("Informe a altura da parede: ");
scanf("%f",& alturaP);
printf("Informe o numero de janelas: ");
scanf("%d",& numJan);
printf("Informe a largura da janela: ");
scanf("%f",& largJan);
printf("Informe a altura da janela: ");
scanf("%f",& alturaJan);
printf("Informe o numero de portas: ");
scanf("%d",& numPort);
printf("Informe a altura da porta: ");
scanf("%f",& alturaPort);
printf("Informe a largura da porta: ");
scanf("%f",& largPort);
printf("Informe o consumo de tinta por metro quadrado: ");
scanf("%f",& consTintM4);
printf("Informe quantos litros vem em um lata de tinta: ");
scanf("%f",& litrosLata);
TotalP = largP * alturaP;
TotalJan = numJan * (largJan * alturaJan);
TotalPort = numPort * (largPort * alturaPort);
PinturaTotal = (TotalP - TotalJan) - TotalPort;
NumerDTinta = PinturaTotal / consTintM4;
NumTdLatas = (int)((NumerDTinta / litrosLata) + 0.999999);
printf("Numero de latas de tintas: %d",NumTdLatas);
return(0);
}
|
C
|
#include "../inc/libmx.h"
int mx_count_words(const char *str, char c) {
int count = 0;
int count_s = 0;
if(str == NULL) {
return -1;
}
for(int i = 0; i < mx_strlen(str); i++) {
if(str[i] == c) {
count_s = 0;
} else if(count_s == 0) {
count++;
count_s = 1;
}
}
return count;
}
|
C
|
#include<stdio.h>
void main()
{
char **arr;
char* s[50], temp[50];
int n, i, j, l;
printf("enter the number of strings\n");
scanf("%d", &n);
arr = (char **)malloc(n * sizeof(char *));
printf("enter %d strings\n", n);
for (i = 0; i < n; i++)
{
scanf("\n%[^\n]s", s);
l = strlen(s) + 1;
arr[i] = (char *)malloc((l) * sizeof(char));
strcpy(arr[i], s);
}
for (i = 0; i < n; i++)
{
printf("%s",arr[i]);
}
}
|
C
|
#include <stdio.h>
main()
{
int c,i,j;
int nc[26];
for(i=0;i<26;i++)
nc[i] = 0;
while((c = getchar()) != EOF){
if('a' <= c && c <= 'z'){
nc[c - 'a']++;
}
}
for(i=0;i<26;i++){
printf("%c:\t",'a'+ i);
for(j=0;j<nc[i];j++){
printf("*");
}
printf("\n");
}
}
|
C
|
#include <stdlib.h>
#include "list.h"
#include "dbg.h"
List* list_create()
{
return calloc(1, sizeof(List));
}
void list_destroy(List* list)
{
LIST_FOREACH(list, first, next, cur){
if(cur->prev) {
free(cur->prev);
}
}
free(list->last);
free(list);
}
void list_clear(List* list)
{
LIST_FOREACH(list, first, next, cur) {
free(cur->value);
}
}
void list_clear_destroy(List *list)
{
list_clear(list);
list_destroy(list);
}
void list_push(List* list, void* value)
{
ListNode* node = calloc(1, sizeof(ListNode));
check_mem(node);
node->value = value;
if (list->last == NULL) {
list->first = node;
list->last = node;
} else {
list->last->next = node;
node->prev = list->last;
list->last = node;
}
list->count++;
error:
return;
}
void* list_pop(List* list)
{
ListNode* node = list->last;
return node != NULL? list_remove(list, node) : NULL;
}
void list_unshift(List* list, void* value)
{
ListNode* node = calloc(1, sizeof(ListNode));
check_mem(node);
node->value = value;
if (list->first == NULL) {
list->first = node;
list->last = node;
} else {
node->next = list->first;
list->first->prev = node;
list->first = node;
}
list->count++;
error:
return;
}
void* list_shift(List* list)
{
ListNode* node = list->first;
return node != NULL? list_remove(list, node) : NULL;
}
void* list_remove(List* list, ListNode* node)
{
void* result = NULL;
check(list->first && list->last, "List is empty.");
check(node, "node can not be NULL");
if (node == list->first && node == list->last ) {
list->first = NULL;
list->last = NULL;
} else if (node == list->first) {
list->first = node->next;
check(list->first != NULL, "Invalid list, got first is NULL");
list->first->prev = NULL;
} else if (node == list->last) {
list->last = node->prev;
check(list->last != NULL, "Invalide list, got last is NULL");
list->last->next = NULL;
} else {
node->prev->next = node->next;
node->next->prev = node->prev;
}
list->count --;
result = node->value;
free(node);
error:
return result;
}
int list_bubble_sort(List* list, LIST_CMP_FUNC cmp_func)
{
check(list != NULL, "List can not be null");
check(cmp_func != NULL ,"compare function can not be null");
ListNode* current_node = list->first;
ListNode* next_node = NULL;
void* v = NULL;
while (current_node != NULL) {
for (next_node = current_node->next; next_node != NULL; next_node = next_node->next) {
if (cmp_func(current_node->value, next_node->value) > 0) {
v = current_node->value;
current_node->value = next_node->value;
next_node->value = v;
}
}
current_node = current_node->next;
}
return 0;
error:
return 1;
}
static void _sort_merge_to(List* merged, List* left, List* right, LIST_CMP_FUNC cmp_func)
{
ListNode* left_cur_node = left->first;
ListNode* right_cur_node = right->first;
while (left_cur_node != NULL || right_cur_node != NULL) {
if (left_cur_node != NULL && right_cur_node != NULL) {
if (cmp_func(left_cur_node->value, right_cur_node->value) > 0) {
list_push(merged, right_cur_node->value);
right_cur_node = right_cur_node->next;
} else {
list_push(merged, left_cur_node->value);
left_cur_node = left_cur_node->next;
}
} else if (left_cur_node != NULL) {
list_push(merged, left_cur_node->value);
left_cur_node = left_cur_node->next;
} else {
list_push(merged, right_cur_node->value);
right_cur_node = right_cur_node->next;
}
}
}
List* list_merge_sort(List* list, LIST_CMP_FUNC cmp_func)
{
check(list != NULL, "List can not be null");
check(cmp_func != NULL ,"compare function can not be null");
int group_len = 1;
int list_len = LIST_COUNT(list);
int i = 0;
List* merged_list = NULL;
List* tmp_list = NULL;
List* left_list = NULL;
List* right_list = NULL;
void* v = NULL;
tmp_list = list_create();
LIST_FOREACH(list, first, next, cur) {
list_push(tmp_list, cur->value);
}
while (group_len < list_len) {
merged_list = list_create();
while (LIST_COUNT(tmp_list) > 0) {
left_list = list_create();
right_list = list_create();
for (i=0;i<group_len;i++) {
v = list_shift(tmp_list);
if (v == NULL)
break;
list_push(left_list, v);
}
for (i=0;i<group_len;i++) {
v = list_shift(tmp_list);
if (v == NULL)
break;
list_push(right_list, v);
}
_sort_merge_to(merged_list, left_list, right_list, cmp_func);
list_destroy(left_list);
list_destroy(right_list);
left_list = right_list = NULL;
}
list_destroy(tmp_list);
tmp_list = merged_list;
group_len = group_len << 1;
}
return tmp_list;
error:
return NULL;
}
|
C
|
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/select.h>
#include <fcntl.h>
#include <ctype.h>
#define MAX_BUFFER_LENGTH 100
#define BACKLOG 20
unsigned int gcd(unsigned int u, unsigned int v) {
// simple cases (termination)
if (u == v)
return u;
if (u == 0)
return v;
if (v == 0)
return u;
// look for factors of 2
if (~u & 1) // u is even
if (v & 1) // v is odd
return gcd(u >> 1, v);
else
// both u and v are even
return gcd(u >> 1, v >> 1) << 1;
if (~v & 1) // u is odd, v is even
return gcd(u, v >> 1);
// reduce larger argument
if (u > v)
return gcd((u - v) >> 1, v);
return gcd((v - u) >> 1, u);
}
unsigned int getGCD(unsigned int a, unsigned int b) {
return gcd(a, b);
}
void unpackData(unsigned char* buffer, unsigned int* a, unsigned int* b) {
*a = (buffer[0]<<8)|buffer[1];
*b = (buffer[2]<<8)|buffer[3];
}
void readBuff(unsigned char* buffer) {
unsigned int* a, *b;
a = (unsigned int*) malloc(1);
b = (unsigned int*) malloc(2);
unpackData(buffer, a, b);
printf("\n Received values %d and %d.\n", *a, *b);
unsigned int gcd = getGCD(*a, *b);
printf("\n GCD is %d \n", gcd);
free (a);
free (b);
}
int main(int argc, char *argv[])
{
printf("\n TCP/UDP server \n\n");
// Check argument count.
if (argc != 4) {
fprintf(stderr,"Usage: server tcpPort udpPort \n");
exit(1);
}
unsigned int tcpPort, udpPort;
char* serverAddr;
serverAddr = (char*) malloc(12);
serverAddr = argv[1];
tcpPort = atoi(argv[2]);
udpPort = atoi(argv[3]);
printf(" \n Using server address %s \n", serverAddr);
printf(" \n Using TCP Port %d \n", tcpPort);
printf(" \n Using UDP Port %d \n", udpPort);
/****************************************************************************
* TCP Server
* *************************************************************************/
// Create TCP socket.
int tcp_sd = socket(AF_INET, SOCK_STREAM, 0);
if (tcp_sd <= 0){
printf("\n ERROR: Failed to create TCP socket. \n");
exit(1);
}
// Create TCP address.
struct sockaddr_in tcp_address;
memset(&tcp_address, '\0', sizeof(tcp_address));
tcp_address.sin_family = AF_INET;
tcp_address.sin_port = htons(tcpPort);
tcp_address.sin_addr.s_addr = inet_addr(serverAddr);
tcp_address.sin_addr.s_addr = htonl(INADDR_ANY);
int bind_stat;
bind_stat = bind(tcp_sd, (struct sockaddr*)&tcp_address, sizeof(tcp_address));
if (bind_stat == -1) {
printf("\n ERROR: bind TCP socket failed. \n");
exit(1);
}
if (listen(tcp_sd, BACKLOG) == -1) {
printf("\n Listen on TCP socket failed.\n");
exit(1);
} else {
printf("\n Listening on TCP socket.\n");
}
/****************************************************************************
* UDP Server
* *************************************************************************/
// Create UDP socket.
int udp_sd = socket(AF_INET, SOCK_DGRAM, 0);
if (udp_sd <= 0){
printf("\n ERROR: Failed to create UDP socket. \n");
exit(1);
}
// Create UDP address.
struct sockaddr_in udp_address;
memset(&udp_address, '\0', sizeof(udp_address));
udp_address.sin_family = AF_INET;
udp_address.sin_port = htons(udpPort);
udp_address.sin_addr.s_addr = inet_addr(serverAddr);
udp_address.sin_addr.s_addr = htonl(INADDR_ANY);
//int len_addr = sizeof()
bind_stat = bind(udp_sd, (struct sockaddr*)&udp_address, sizeof(udp_address));
if (bind_stat == -1) {
printf("\n ERROR: bind failed. \n");
exit(1);
}
printf("\n Accepting data on UDP port.\n");
fd_set readfds;
int max_sd, rc;
struct timeval timeout;
timeout.tv_sec = 3 * 60;
timeout.tv_usec = 0;
if (tcp_sd > udp_sd) max_sd = tcp_sd;
else max_sd = udp_sd;
while (1) {
// Set FD sets.
FD_SET(tcp_sd, &readfds);
FD_SET(udp_sd, &readfds);
rc = select(max_sd + 1, &readfds, NULL, NULL, &timeout);
if (rc < 0) {
printf("\n ERROR: select() failed. \n");
exit(1);
}
if (rc == 0) {
printf("\n select() timed out. End program.\n");
exit(1);
}
int i = 0;
for (i = 0; i <= max_sd; i++) {
if (FD_ISSET(i, &readfds)) {
// Receive on UDP port
if (i == udp_sd) {
char recvBuff[100];
memset(recvBuff, '0', sizeof(recvBuff));
unsigned int maxPackSize = sizeof(recvBuff);
struct sockaddr_in from;
socklen_t fromLength = sizeof(from);
int receivedBytes = recvfrom(
udp_sd,
(char*) recvBuff,
maxPackSize,
0,
(struct sockaddr*) &from,
&fromLength);
if (receivedBytes <= 0) break;
readBuff(recvBuff);
// Receive on TCP port
} else if (i == tcp_sd) {
char recvBuff[100];
memset(recvBuff, '0', sizeof(recvBuff));
unsigned int maxPackSize = sizeof(recvBuff);
int incoming_tcp_sd;
struct sockaddr_in from;
socklen_t fromLength = sizeof(from);
incoming_tcp_sd = accept(
tcp_sd,
(struct sockaddr*) &from,
&fromLength);
read(incoming_tcp_sd, recvBuff, sizeof recvBuff);
readBuff(recvBuff);
}
}
} // End For Loop through sockets
} // End While
} // End main()
|
C
|
/**
* @file SPI_Controller.h
* @author Group 1: Christian Despatie, Lena Hsieh, Surbhi Gupta & Kishen Shakespeare
* @version 1.0
*
* @brief Functions to initialize SPI configuration
*
*/
#ifndef __SPI_CONTROLLER_H
#define __SPI_CONTROLLER_H
#include <stm32f4xx.h>
#include <stm32f4xx_spi.h>
/**
* @brief Initialize the SPI
*/
void init_SPI1(void);
/**
* @brief Send data on SPI
* @param data- data to be transmitted to the SPI data register
* @return received data from SPI data register
*/
uint8_t SPI1_send(uint8_t data);
#endif
|
C
|
//biblioteca.c
#include <stdio.h>
#include <stdlib.h>
int numeroVezesC(char *linha1,char *linha2, int tam1, int tam2){
int cont=0,i=0,j=0, n=0;
char aux[tam1]; // string auxiliar para fazer comparações
while (j != tam2){
n++;
while (i!=tam1){
aux[i]=linha2[j];
j++;
i++;
}
j=n; //para garantir que encontrará substrings que serão sobrescritas
i=0;
if (strcmp(linha1, aux)==0){ //strings iguais, achou 1 substring
cont++; //achou a subpalavra
}
}
return cont;
}
|
C
|
static WinBuf *
new_WinBuf(int hi, int wi)
{
WinBuf *wb;
int size, y, x;
char *mem, *chars, *colors, *attrs;
size = sizeof(WinBuf) + hi * wi * 3 + sizeof(char *) * hi * 3;
mem = (char *) calloc(size, 1);
wb = (WinBuf *) mem;
wb->hi = hi;
wb->wi = wi;
chars = (char *) (mem + sizeof(WinBuf));
colors = chars + wi * hi;
attrs = colors + wi * hi;
wb->chars = (char **) (attrs + wi * hi);
wb->colors = (char **) (attrs + wi * hi + sizeof(char *) * hi);
wb->attrs = (char **) (attrs + wi * hi + sizeof(char *) * hi * 2);
for (y = 0; y < hi; y++)
{
wb->chars[y] = chars + wi * y;
wb->colors[y] = colors + wi * y;
wb->attrs[y] = attrs + wi * y;
for (x = 0; x < wi; x++)
{
wb->chars[y][x] = ' ';
wb->colors[y][x] = 7;
wb->attrs[y][x] = 0;
}
}
return wb;
}
|
C
|
Status ListDelete(SqList *L, int i, ElemType *e){
int k;
if (L -> length == 0) {
return ERROR;
}
if (i<1 || i> L->length) {
return ERROR;
}
*e = L ->data[i-1]
if (i< L->length) {
for ( k = i; k < L->length; k++) {
L -> data[k-1] = L-> data[k];
}
}
L->length--;
return OK;
}
|
C
|
/* Author: James Ridey 44805632
* james.ridey@students.mq.edu.au
* Creation Date: 10-08-2016
* Last Modified: Mon 15 Aug 2016 05:59:06 PM AEST
*/
#include <stdlib.h>
#include "file.h"
Data* read_file(FILE* file, Array* array)
{
short tmp;
if(!fread(&tmp, sizeof(short), 1, file)) return NULL;
Data* data = malloc(sizeof(Data));
data->news = tmp;
fread(&data->edge, sizeof(short), 1, file);
fread(&data->error, sizeof(char), 1, file);
fread(&data->cent, sizeof(int), 1, file);
fread(&data->holiday, sizeof(char), 1, file);
fread(&data->shake, sizeof(char), 1, file);
fread(&data->hair, sizeof(float), 1, file);
fread(&data->snakes, sizeof(long), 1, file);
fread(&data->toad, sizeof(char), 1, file);
fread(&data->window, sizeof(char), 1, file);
fread(&data->space, sizeof(short), 1, file);
fread(&data->cemetery, 10*sizeof(char), 1, file);
fread(&data->fang, sizeof(double), 1, file);
fread(&data->chance, sizeof(long), 1, file);
fread(&data->development, sizeof(double), 1, file);
fread(&data->spy, sizeof(int), 1, file);
return data;
}
void write_file(FILE* file, Array* array)
{
int i;
for (i = 0; i < array->counter; i++)
{
Data data = *array->data[i];
fwrite(&data.news, sizeof(short), 1, file);
fwrite(&data.edge, sizeof(short), 1, file);
fwrite(&data.error, sizeof(char), 1, file);
fwrite(&data.cent, sizeof(int), 1, file);
fwrite(&data.holiday, sizeof(char), 1, file);
fwrite(&data.shake, sizeof(char), 1, file);
fwrite(&data.hair, sizeof(float), 1, file);
fwrite(&data.snakes, sizeof(long), 1, file);
fwrite(&data.toad, sizeof(char), 1, file);
fwrite(&data.window, sizeof(char), 1, file);
fwrite(&data.space, sizeof(short), 1, file);
fwrite(&data.cemetery, 10*sizeof(char), 1, file);
fwrite(&data.fang, sizeof(double), 1, file);
fwrite(&data.chance, sizeof(long), 1, file);
fwrite(&data.development, sizeof(double), 1, file);
fwrite(&data.spy, sizeof(int), 1, file);
}
}
|
C
|
/* 十进制-二进制 函数递归实现*/
/* 十进制变二进制,如果是奇数最后以为必定是1,偶数必定是0*/
#include<stdio.h>
void ten_two( unsigned long shi );
int main( void )
{
unsigned long shi;
printf( "请输入一个十进制的数( q to quit ):" );
while( scanf( "%lu", &shi ) == 1 ){//scanf读入一个数
printf( "转换成二进制数是:");
ten_two( shi );//调用函数进行运算
printf( "\n" );
printf( "请输入一个十进制的数( q to quit ):" );
}
printf( "退出。" );
return 0;
}
void ten_two( unsigned long shi )
{
int r; //定义二进制的位数
r = shi % 2;//进行运算得到位数
if ( shi >= 2 )//判断数是不是大于等于2
ten_two( shi / 2 );//让数除以2,减少一位,进行下一步运算
putchar( '0' + r );//输出位数
}
// r
// 3 % 2 = 1 取出二进制位数
// shi
// 3 / 2 = 1 整数运算,然后进行下一步运算
//
//因为1 >= 2 不成立所以直接跳到putchar( '0' + two )
//即是putchar( '0' + 1 )
//
//输出11
//
//
//
// 4 >= 2 成立
// 4 % 2 = 0
// 4 / 2 = 2
//
// 2 >= 2成立
// 2 % 2 = 1
// 2 / 2 = 1
//
// 1 >= 2不成立
// 直接putchar( '0' + 1 )
//
// 输出110
|
C
|
#include<stdio.h>
main()
{
char s[20],d[20],i;
printf("enter string\n");
scanf("%s",s);
printf("before...%s",s);
for(i=0;s[i];i++)
d[i]=s[i];
d[i]=s[i];
printf("after....%s\n",d);
}
|
C
|
int f(int n)
{
if (n==0)
{
cout <<n<<endl;
return 0;
}
if (n<0)
{
cout <<'-';
return f(-n);
}
cout <<n%10;
if (n/10!=0)
return f(n/10);
else cout<<endl;
}
int main()
{
int n;
while(cin>>n)
{
while (n%10==0&&n!=0)
{
n/=10;
}
f(n);
}
return 0;
}
|
C
|
int strcmp_ci(char* str1, char* str2)
{
int str1_size = f_strlen(str1);
int str2_size = f_strlen(str2);
while( (*str1 != '\n') && (*str1 != '\0') && (*str2 != '\n') && (*str2 != '\0'))
{
if( (*str1 >= 'A' && *str1 <= 'Z'))
{
if(!(*str2 >= 'A' && *str2 <= 'Z'))
*str2 = *str2 - 32 ;
}
else if(*str1 >= 'a' && *str1 <= 'z')
{
if( !(*str2 >= 'a' && *str2 <= 'z') )
*str2 = *str2 + 32;
}
if (*str1 > *str2)
return 1;
else if (*str1 < *str2)
return -1;
str1 ++;
str2 ++;
}
if (str1_size == str2_size)
return 0;
else if (str1_size > str2_size)
return 1;
else if (str1_size < str2_size)
return -1;
}
|
C
|
/**
* @file I2C1.c
* @author Seb Madgwick
* @brief I2C master library for dsPIC33EP.
*
* Communication may be achieved using either blocking functions or by composing
* and then executing an interrupt serviced script.
*
* I2C1_INTERRUPT_PRIORITY may be changed as required by the application.
*/
//------------------------------------------------------------------------------
// Includes
#include "I2C1.h"
#include "I2CCommon.h"
#include <stddef.h> // NULL
#include <xc.h>
//------------------------------------------------------------------------------
// Definitions
#define I2C1_INTERRUPT_PRIORITY 4
//------------------------------------------------------------------------------
// Variables
static volatile I2CScript* i2cScriptAddress = NULL;
//------------------------------------------------------------------------------
// Functions
/**
* @brief Initialises the I2C module.
*
* Initialises the I2C module in master mode with specified baud rate. This
* function can be used to reinitialise the module with new settings if it has
* already been initialised.
*
* @param baud Baud rate.
*/
void I2C1Initialise(const uint32_t baud) {
// Ensure default register states
I2C1Disable();
PMD1bits.I2C1MD = 0; // enable peripheral
// Configure module
I2C1BRG = CALCULATE_I2CXBRG(baud);
_DISSLW = 1; // Slew rate control disabled
_SMEN = 1; // Enable I/O pin thresholds compliant with SMBus specification
_I2CEN = 1; // Enables the I2C module and configures the SDA and SCL pins as serial port pins
_MI2C1IP = I2C1_INTERRUPT_PRIORITY; // set interrupt priority
}
/**
* @brief Disable the I2C module.
*
* I2C registers are set to their default values. All I2C pins are controlled
* by PORT functions. The peripheral is put in a minimum power consumption
* state.
*/
void I2C1Disable() {
I2C1CON = 0x0000;
I2C1STAT = 0x0000;
_MI2C1IE = 0; // disable interrupt
_MI2C1IF = 0; // clear interrupt flag
PMD1bits.I2C1MD = 1; // disable peripheral
}
/**
* @brief Execute I2C start event. This is a blocking function.
*/
void I2C1Start() {
_SEN = 1;
while (_SEN);
}
/**
* @brief Execute I2C restart event. This is a blocking function.
*/
void I2C1Restart() {
_RSEN = 1;
while (_RSEN);
}
/**
* @brief Execute I2C stop event. This is a blocking function.
*/
void I2C1Stop() {
_PEN = 1;
while (_PEN);
}
/**
* @brief Execute I2C send event. This is a blocking function.
* @param byte Byte to send.
*/
void I2C1Send(char byte) {
I2C1TRN = byte;
while (I2C1STATbits.TRSTAT);
}
/**
* @brief Returns true if the slave failed to acknowledge the I2C send.
* @return True if the slave failed to acknowledge the I2C send.
*/
bool I2C1AckFailed() {
return I2C1STATbits.ACKSTAT;
}
/**
* @brief Execute I2C receive event. This is a blocking function.
*/
char I2C1Receive() {
_RCEN = 1;
while (_RCEN);
return I2C1RCV;
}
/**
* @brief Execute I2C ACK event. This is a blocking function.
*/
void I2C1Ack() {
_ACKDT = 0;
_ACKEN = 1;
while (_ACKEN);
}
/**
* @brief Execute I2C NACK event. This is a blocking function.
*/
void I2C1Nack() {
_ACKDT = 1;
_ACKEN = 1;
while (_ACKEN);
}
/**
* @brief Runs interrupt serviced I2C script in background. This function will
* have no effect if the script if it is already running.
* @param i2cScript Address of I2CScript.
* @return 0 if successful.
*/
int I2C1RunScript(I2CScript * const i2cScript) {
if (I2C1IsScriptRunning()) {
return 1; // error: script is still running
}
i2cScriptAddress = i2cScript;
i2cScript->index = 0;
_MI2C1IF = 1; // set interrupt flag
_MI2C1IE = 1; // enable interrupt
return 0;
}
/**
* @brief Returns true if interrupt serviced I2C script is still running.
* @return True if interrupt serviced I2C script is still running.
*/
bool I2C1IsScriptRunning() {
return _MI2C1IE;
}
//------------------------------------------------------------------------------
// Functions - Interrupt
/**
* I2C interrupt service routine.
*/
void __attribute__((interrupt, auto_psv))_MI2C1Interrupt(void) {
_MI2C1IF = 0; // clear interrupt flag
const int index = i2cScriptAddress->index++;
switch (i2cScriptAddress->command[index]) {
case I2CScriptCommandStart:
_SEN = 1;
break;
case I2CScriptCommandRestart:
_RSEN = 1;
break;
case I2CScriptCommandStop:
_PEN = 1;
break;
case I2CScriptCommandSend:
I2C1TRN = i2cScriptAddress->data[index];
break;
case I2CScriptCommandReceive:
_RCEN = 1;
break;
case I2CScriptCommandAck:
*i2cScriptAddress->destination[index] = I2C1RCV;
_ACKDT = 0;
_ACKEN = 1;
break;
case I2CScriptCommandNack:
*i2cScriptAddress->destination[index] = I2C1RCV;
_ACKDT = 1;
_ACKEN = 1;
break;
case I2CScriptCommandEndOfScript:
default:
_MI2C1IE = 0; // disable interrupts
if (i2cScriptAddress->scriptCompleteTasks != NULL) {
i2cScriptAddress->scriptCompleteTasks();
}
break;
}
}
//------------------------------------------------------------------------------
// End of file
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define bool int
#define false 0
#define true 1
#define MAX 64
int n, sum, max;
int a[MAX];
int v[MAX];
int origin;
bool f;
int cmp(const void *a, const void *b)
{
return -(*(int *)a - *(int *)b);
}
void def(int d, int len, int u)
{
int i;
if(f) return;
if(len == 0)
{
i = 0;
while(v[i]) i++;
v[i] = true;
def(d + 1, a[i], i+1);
v[i] = false;
}
else if(len == origin)
{
if(d == n)
f = true;
else
def(d, 0, 0);
}
else
{
for(i = u; i < n; i++)
if(!v[i] && len + a[i] <= origin)
{
if(!v[i - 1] && a[i] == a[i - 1]) continue;
v[i] = true;
def(d + 1, len + a[i], i + 1);
v[i] = false;
}
}
}
bool valid(int i)
{
origin = i;
f = false;
def(0, 0, 0);
return f;
}
int main()
{
int i;
while(scanf("%d", &n) && n != 0)
{
max = sum = 0;
memset(v, false, sizeof(v));
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
sum += a[i];
max = a[i] > max?a[i]:max;
}
qsort(a, n, sizeof(a[0]), &cmp);
for(i = max; i <= sum; i++)
{
if(sum % i == 0)
{
if(valid(i))
{
printf("%d\n", i);
break;
}
}
}
}
return 0;
}
|
C
|
#include "holberton.h"
/**
* factorial- Short description, single line
* @n: Description of parameter n
* Return: 0
*/
int factorial(int n)
{
if (n >= 0 && n <= 1)
{
return (1);
}
else if (n < 0)
{
return (-1);
}
else
{
return (n * factorial(n - 1));
}
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(void)
{
char name[100], first_name[100];
gets(name);
for (int i = 0, n = strlen(name); i < n; i++)
{
if (name[i] == ' ')
{
first_name[i] = '\0';
break;
}
first_name[i] = name[i];
}
printf("%s\n", first_name);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, p, d, i;
while(1){
printf("Digite o tamanho do seu cafufa: \n");
scanf("%d", &n);
printf("Digite os numeros cafufados: \n");
scanf("%d %d", &p, &d);
if(!n && !p && !d) return 0;
for(i = 1; i <= n; i++){
if(i%p==0 || i%d==0 || i%10==p || i%10==d)
printf("Cafufa");
else
printf("%d", i);
if(i==n){
printf(".\n\n");
printf("---------------------------------------------------------------\n");
}else
printf(", ");
}
}
return 0;
}
|
C
|
#include <std.h>
inherit DAEMON;
int check_activity(string str);
void move_rubble(string ext, object tp);
int cmd_dig(string str){
string *buried_exits;
object ob;
if(!str){
tell_object(TP, "You dig a hole in the ground.");
tell_room(ETP, TPQCN+" digs a hole in the ground.", TP);
return 1;
}
buried_exits = keys(ETP->query_orig_exits());
if(member_array(str, buried_exits) == -1)
return notify_fail("That exit isn't buried.\n");
ob=new("/cmds/mortal/obj/digob.c");
ob->move(TP);
return ob->begin_dig(str,TP);
}
void help(){
write("
%^CYAN%^NAME%^RESET%^
dig - dig out buried exit
%^CYAN%^SYNOPSIS%^RESET%^
dig %^ORANGE%^%^ULINE%^EXI%^RESET%^T
%^CYAN%^DESCRIPTION%^RESET%^
This command will remove rubble placed on %^ORANGE%^%^ULINE%^EXIT%^RESET%^.
The speed and success of your action will depend largely on your dexterity score.
%^CYAN%^SEE ALSO%^RESET%^
bury, sneak, trap
");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <pthread.h>
#include <fcntl.h>
#define BUF_SIZE 200000010
char *cmd; //argv
int **arr;
int m = 0;
int n = 0;
int **arr2;
int *part; //파트 분배
int gen = 0; //세대 수
int *thread_n;
pthread_t *tid; //tid 배열
pid_t *pid; //pid 배열
struct Nthreads {
int nthread; //n번째 thread
};
struct Buf {
int row;
int column;
int value;
};
struct Nthreads *nth;
struct Buf buf;
void sequential_process(void);
void multi_process(int);
void multi_thread(int);
int ask_multi(void); //생성할 child process/thread 수 입력받는 함수
void ask_gen(void); //세대 수 입력받는 함수
void make_matrixfile(int); //자식세대 파일 생성 함수
void part_division(int); //한 process/thread당 수행할 파트 분배
void *thread_work(void *arg);
void play_game(int); //세포 다음 세대 생사 결정
void read_input(void); //입력 파일 읽는 함수
void sequential_process(void){
read_input(); //입력파일 읽기
//게임진행
for (int k=0; k<gen; k++){
for (int i=0; i<m; i++){
play_game(i); //세포 다음 세대 생사 결정
}
for (int i = 0; i<m;i++){
for(int j=0; j<n; j++){
arr[i][j] = arr2[i][j];
}
}
make_matrixfile(k); //gen_n.matrix 생성
}
}
void multi_process(int processes){
int processes_size = 4*processes;
int pipe_fd[2];
read_input(); //입력파일 읽기
//행분배
part = (int*)malloc(processes_size);
pid = (pid_t*)malloc(processes*sizeof(pid_t));
part_division(processes);
pipe(pipe_fd);
//프로세스 생성 및 실행
for (int k = 0; k<gen; k++){
int count = 0;
memset(pid, 0, processes*sizeof(pid_t));
for (int p = 1; p<=processes; p++){ //현재 p번째 process 수행
int line = 0;
for (int q = 1; q<p; q++){
line += part[q-1];
}
if ((pid[p-1] = fork()) == 0){
for (int g=0; g<part[p-1]; g++){
int i = g+line;
play_game(i);
}
for (int g=0; g<part[p-1]; g++){
int i = g+line;
for (int x=0; x<n; x++){
buf.row = i;
buf.column = x;
buf.value = arr2[i][x];
write(pipe_fd[1], &buf, sizeof(struct Buf));
}
}
exit(0);
}
else if (pid[p-1] < 0){
fprintf(stderr, "fork error\n");
exit(1);
}
else { //부모 프로세스
;
}
}
while((read(pipe_fd[0], &buf, sizeof(struct Buf))) > 0){
int a = buf.row;
int b = buf.column;
arr2[a][b] = buf.value;
count++;
if (count == m*n){
break;
}
}
while( (wait((int*)0)) != -1 ); //자식 프로세스 다 끝날때까지 wait
//pid 출력
printf("pid : ");
for (int a=0; a<processes; a++){
printf("%d ", pid[a]);
}
printf("\n");
//새로운 세대 파일 생성
for (int a=0; a<m; a++){
for (int b=0; b<n; b++){
arr[a][b] = arr2[a][b];
}
}
make_matrixfile(k); //결과 파일 생성
}
return;
}
void multi_thread(int threads){
read_input(); //입력파일 읽기
//행 분배
int threads_size = 4*threads;
nth = (struct Nthreads *)malloc(threads*sizeof(struct Nthreads)); //구조체
tid = (pthread_t *)malloc(threads*sizeof(pthread_t));
part = (int*)malloc(threads_size);
part_division(threads);
//스레드 생성 및 실행
for (int k=0; k<gen; k++){
printf("tid : ");
for (int t = 0; t<threads; t++){
nth[t].nthread = t+1;
if (pthread_create(&tid[t], NULL, thread_work, (void*)&nth[t]) != 0){
fprintf(stderr, "pthread_create error\n");
exit(1);
}
}
for (int i=0; i<threads; i++){
if ((pthread_join(tid[i], NULL)) != 0) {
fprintf(stderr, "pthread_join error\n");
exit(1);
}
}
for (int i = 0; i<m; i++){ //다음 세대 실행 준비
for (int j = 0; j<n; j++){
arr[i][j] = arr2[i][j];
}
}
make_matrixfile(k); //결과 파일 생성
printf("\n");
}
return;
}
void *thread_work(void *arg){
struct Nthreads *t = (struct Nthreads *)arg;
printf("%lu ", pthread_self());
int line = 0;
for (int i=1; i<t->nthread; i++){ //현재까지 수행된 행
line += part[i-1];
}
for (int k=0; k<part[t->nthread-1]; k++){
int i = k+line;
play_game(i);
}
pthread_exit(NULL);
}
void part_division(int multi){
int a = m/multi;
int b = m%multi;
for (int i=0; i<multi; i++){
part[i] = a;
if (i<b)
part[i]++;
}
}
void make_matrixfile(int k){
FILE *fp_gen;
char str1[] = "gen_";
char str2[] = ".matrix";
char gen_n[40]; //파일 이름
char *buf; //2차원 배열을 줄단위로 담을 버퍼
int l = 2*n;
buf = (char*)malloc(l);
int offset = 0;
char c = ' ';
char enter = '\n';
if (k == gen-1){ //최종 결과 파일
fp_gen = fopen("output.matrix", "w+");
}
else { //세대별 중간 결과 파일
memset(gen_n, 0, 40);
sprintf(gen_n, "%s%d%s", str1,k+1,str2);
fp_gen = fopen(gen_n, "w+");
}
fseek(fp_gen, 0, SEEK_SET);
//2차원 배열 -> matrix로
for (int i=0; i<m; i++){
memset(buf, 0, l);
for (int j=0; j<n; j++){
offset = j*2;
sprintf(buf+offset, "%d", arr[i][j]);
if (j == n-1) sprintf(buf+offset+1, "%c", enter);
else sprintf(buf+offset+1, "%c", c);
}
fwrite(buf, l, 1, fp_gen);
}
fclose(fp_gen);
}
int ask_multi(){
int multi=0;
while(1){
printf("생성할 process/thread 수를 입력해주세요 : ");
scanf("%d", &multi);
if (multi < 1){
printf("1 이상의 수를 입력해 주세요\n");
}
else break;
}
return multi;
}
void ask_gen(){
while(1){
printf("세대 수를 입력해주세요 : ");
scanf("%d", &gen);
if (gen < 1){
printf("1 이상의 수를 입력해 주세요\n");
}
else break;
}
return;
}
void play_game(int i){
for (int j =0; j<n; j++){
int count = 0;
if (j==0);
else
if (arr[i][j-1] == 1) count++; //1. arr[i][j-1] 체크
if ((j==0) || (i==0)) ;
else
if (arr[i-1][j-1] == 1) count++; //2. arr[i-1][j-1] 체크
if (i==0) ;
else
if (arr[i-1][j] == 1) count++; //3. arr[i-1][j] 체크
if ((i==0) || (j==n-1)) ;
else
if (arr[i-1][j+1] == 1) count++; //4. arr[i-1][j+1] 체크
if (j == n-1) ;
else
if (arr[i][j+1] == 1) count++; //5. arr[i][j+1] 체크
if ((j== n-1)|| (i== m-1)) ;
else
if (arr[i+1][j+1] == 1) count++; //6. arr[i+1][j+1] 체크
if (i== m-1) ;
else
if (arr[i+1][j] == 1) count++; //7. arr[i+1][j] 체크
if ((i == m-1) || (j==0)) ;
else
if (arr[i+1][j-1] == 1) count++; //8. arr[i+1][j-1] 체크
//다음 세대 세포 생사 결정
if (arr[i][j] == 1){ //현재 살아있을 경우
if (count <= 2 || count >=7) arr2[i][j] = 0;
else if (count >= 3 && count <= 6) arr2[i][j] = 1;
else ;
}
else if (arr[i][j] == 0){ //현재 죽어있을 경우
if (count == 4) arr2[i][j] = 1;
else if (count != 4) arr2[i][j] = 0;
else ;
}
else ;
}
return;
}
void read_input(void){
FILE *fp;
char *buffer;
char *buffer2;
int l=0; //buffer길이
buffer = (char*)malloc(BUF_SIZE);
//m, n 읽어오기
int fd = open(cmd, O_RDONLY);
int file_size = 0, temp=0;
file_size = read(fd, buffer, BUF_SIZE);
while(1){
temp = read(fd, buffer, BUF_SIZE);
if (temp > 0){
file_size += temp;
}
else break;
}
lseek(fd, 0, 0);
read(fd, buffer, BUF_SIZE);
close(fd);
fp = fopen(cmd, "r+");
while(1){
if(buffer[l] == '\n'){
l++;
break;
}
else if (buffer[l] == '0' || buffer[l] == '1'){
n++;
l++;
}
else l++;
}
n = l/2;
m = file_size/(l-1);
buffer2 = (char*)malloc(l);
//2차원 배열에 matrix 값 저장
arr = (int**)malloc(sizeof(int*)*m);
for (int i=0; i<m; i++){
arr[i] = (int*)malloc(sizeof(int)*n);
}
arr2 = (int**)malloc(sizeof(int*)*m);
for (int i=0; i<m; i++){
arr2[i] = (int*)malloc(sizeof(int)*n);
}
fseek(fp, 0, SEEK_SET);
//2차원 배열 초기화
for (int i=0;i<m;i++){
for(int j=0;j<n;j++){
arr[i][j] = 0;
}
}
fseek(fp, 0, SEEK_SET);
for (int i=0; i<m; i++){
memset(buffer2, 0, l);
fread(buffer2, l-1, 1, fp);
int k = 0;
for (int j=0;j<l-1;j++){
if (buffer2[j] == '0'){
arr[i][k] = 0;
k++;
}
else if (buffer2[j] == '1'){
arr[i][k] = 1;
k++;
}
else ;
}
fseek(fp, 1, SEEK_CUR);
}
free(buffer);
free(buffer2);
fclose(fp);
return;
}
int main(int argc, char* argv[]){
int num=0; //동작 번호
//int i=0, j=0, k=0; //반복문
struct timeval start_time, end_time; //시간 측정용
double delay_time;
int nprocess=0, nthread=0;
cmd = argv[1];
//동작 번호 입력
while(1){
printf("번호를 입력해주세요(1: 프로그램 종료/ 2: 순차처리/ 3: Process 병렬처리/ 4: Thread 병렬처리) : ");
scanf("%d", &num);
if (num == 1){
printf("프로그램 종료\n");
exit(0);
}
else if (num == 2){ //순차처리
ask_gen();
gettimeofday(&start_time, NULL); //시간측정 시작
sequential_process(); //순차처리
gettimeofday(&end_time, NULL); //시간측정 종료
delay_time = ((end_time.tv_sec - start_time.tv_sec)*1000) + ((end_time.tv_usec -
start_time.tv_usec)*0.001);
printf("총 수행 시간 : %f ms\n", delay_time);
}
else if (num == 3){ //프로세스 병렬
nprocess = ask_multi(); //생성할 프로세스 수
ask_gen(); //생성할 자식 파일 수
gettimeofday(&start_time, NULL);
multi_process(nprocess);
gettimeofday(&end_time, NULL);
delay_time = ((end_time.tv_sec - start_time.tv_sec) * 1000) + ((end_time.tv_usec -
start_time.tv_usec)*0.001);
//pid, 총 수행시간 출력
printf("총 수행 시간 : %f ms\n", delay_time);
}
else if (num == 4){ //스레드 병렬
nthread = ask_multi(); //생성할 스레드 수
ask_gen(); //생성할 자식 파일 수
gettimeofday(&start_time, NULL);
multi_thread(nthread);
gettimeofday(&end_time, NULL);
delay_time = ((end_time.tv_sec - start_time.tv_sec)*1000) + ((end_time.tv_usec -
start_time.tv_usec)*0.001);
//tid, 총 수행시간 출력
printf("총 수행 시간 : %f ms\n", delay_time);
}
else{
printf("1-4 사이의 수를 입력해주세요\n");
}
}
free(arr);
free(arr2);
exit(0);
}
|
C
|
#include<stdio.h>
#include<conio.h>
long int factorial(int n);
void main(){
int n;
long int fact;
clrscr();
printf("Enter a number: ");
scanf("%d", &n);
fact = factorial(n);
printf("%d! = %ld", n, fact);
getch();
}
long int factorial(int n){
if(n == 0)
return 1;
else
return n * factorial(n - 1);
}
|
C
|
#include "resources.h"
#include <math.h>
#include <ncurses.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define ENOUGH 64
#define DELAY 15000
#define WIDTH getmaxx(stdscr)
#define HEIGHT getmaxy(stdscr)
int main() {
char sheepstr[ENOUGH];
// Setup ncurses
initscr();
curs_set(false);
noecho();
timeout(0);
for (unsigned sheep = 1;; sheep += 1) {
unsigned starting_height = random() % HEIGHT;
// Determine if the sheep moves left-to-right or right-to-left
bool isleft = random() % 2;
unsigned start, stop;
int step;
if (isleft) {
start = WIDTH - 6;
stop = 0;
step = -1;
} else {
start = 0;
stop = WIDTH - 6;
step = 1;
}
for (unsigned x = start; x != stop; x += step) {
// Curve
int y = -(HEIGHT / 4) * sin((M_PI / WIDTH) * x) + starting_height;
// Update sheep position
if (isleft) {
mvprintw(y, x, sheep_left[0]);
mvprintw(y + 1, x, sheep_left[1]);
} else {
mvprintw(y, x, sheep_right[0]);
mvprintw(y + 1, x, sheep_right[1]);
}
// Update number of sheep
sprintf(sheepstr, "%u", sheep);
mvprintw(HEIGHT - 1, WIDTH / 2, sheepstr);
// Update screen
refresh();
usleep(DELAY);
clear();
// Quit?
if (getch() == 'q') {
endwin();
return 0;
}
}
}
endwin();
return 0;
}
|
C
|
// wap to input marks of students in 3 subjects --> eng, maths, science.
// calculate the total marks, percentage and grade
// print --> total marls, percentage and grade
// grade --> percentage --> greater than 80 --> A grade
// greater than 60 and less than 80 --> B grade
// greater than 50 and less than 60 --> C grade
// less than 50 --> D grade
void main(){
int eng, maths, sci, totalMarks;
float percentage;
clrscr();
printf("Enter your marks in English=");
scanf("%d", &eng);
printf("Enter your marks in Maths=");
scanf("%d", &maths);
printf("Enter your marks in Science=");
scanf("%d", &sci);
totalMarks = eng + maths + sci;
percentage = totalMarks/3; //57.90
printf("\nYour total marks are = %d", totalMarks);
printf("\nYour percentage is = %.2f", percentage);
if(percentage >= 80 && percentage<100)
{
printf("\nA Grade");
}else if((percentage >= 60) && (percentage < 80))
{
printf("\nB Grade");
}
else if((percentage >= 50) && (percentage < 60))
{
printf("\nC Grade");
} else if(percentage < 50)
{
printf("\nD Grade");
}
getch();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int N, S, i=1;
printf("Saisir le nombre N : ");
scanf("%d",&N);
S=0;
for(i=0;i<=N;i++)
S=S+i;
printf("La somme S = %d\n",S);
return 0;
}
|
C
|
int main(){
int a, b, x;
printf("Digite o valor para 'a':");
scanf("%d", &a);
b = 3;
x = a+b;
printf("a soma de %d mais 3 é: %d", a, x);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include "dlist.h"
#include "utils.h"
dnode* dnode_create(int data, dnode* prev, dnode* next){
dnode*p = (dnode*)malloc(sizeof(dnode));
p->data= data;
p->prev = prev;
p->next = next;
return p;
}
dlist* dlist_create(void){
dlist *p= (dlist*)malloc(sizeof(dlist));
p->head = NULL;
p->size = 0;
p->tail = NULL;
return p;
}
bool dlist_empty(dlist* list){
return list->size==0;
}
size_t dlist_size(dlist* list){
return list->size;
}
void dlist_popfront(dlist* list){
dnode *p= list->head;
list->head= list->head->next;
list->head->prev= NULL;
free(p);
--list->size;
}
void dlist_popback(dlist* list){
dnode *p = list->head;
dnode*prev= p;
while(p->next!=NULL){prev=p; p=p->next;}
prev->next=NULL;
free(p);
list->tail=prev;
--list->size;
}
void dlist_pushfront(dlist* list, int data){
dnode* p = dnode_create(data,NULL,list->head);
list->head=p;
if(list->size==0){list->tail= p;}
++list->size;
}
void dlist_pushback(dlist* list, int data){
if(list->size==0){dlist_pushfront(list,data); return;}
dnode * p = dnode_create(data, list->size==1?NULL: list->tail,NULL);
list->tail->next=p;
list->tail= p;
++list->size;
}
void dlist_clear(dlist* list){
while(!dlist_empty(list)){
dlist_popback(list);
}
}
void dlist_print(dlist* list, const char* msg){
printf("%s \n", msg);
if(dlist_empty(list)){printf("List is empty \n"); return ;}
dnode *p= list->head;
while(p!=NULL){
printf(" %p <-- %d --> %p \n", p->prev,p->data, p->next);
p=p->next;
}
}
int dlist_front(dlist* list){
return list->head->data;
}
int dlist_back(dlist* list){
return list->tail->data;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../headers/lib.h"
cmd create_command(char *name, char **args){
cmd c = malloc(sizeof(command));
if(c == NULL)
return NULL;
c->name = strdup(name);
c->args = args;
int nbArgs = 0;
while(*(args+nbArgs)!=NULL){
nbArgs++;
}
c->nbArgs = nbArgs;
return c;
}
// Renvoie une commande où args vaut les éléments de arr de start
// (inclus) à end (exclus)
cmd create_command_from_array(array *arr, int start, int end){
char **args = malloc(sizeof(char*)*(end-start+1));
for(int i = start; i < end; ++i){
args[i-start] = get(arr,i);
}
args[end-start] = NULL;
return create_command(args[0], args);
}
//Concatene les tableau d'arguments
void concat_args(cmd command,char **args,int length) {
int new_length = command->nbArgs + length + 1;
command->args = realloc(command->args,
sizeof(char*) * new_length);
for(int i = command->nbArgs; i < (new_length - 1); i++) {
command->args[i] = args[i - command->nbArgs];
}
command->args[new_length - 1] = NULL;
}
int nb_args(cmd tmp){
return tmp->nbArgs;
}
char *get_arg(int i, cmd c){
if(i < c->nbArgs && i >= 0) return *((c->args)+i);
else return NULL;
}
char *get_name(cmd c){
return c->name;
}
void free_cmd(cmd c){
free(c->name);
for(int i = 0; c->args[i] != NULL; i++){
free(c->args[i]);
}
free(c->args);
free(c);
}
void print_command(cmd c){
for(int i = 0; i < c->nbArgs; ++i)
printf("%s ", c->args[i]);
printf("\n");
}
|
C
|
#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
void touch_copied_byte(char * other_buff) {
if (other_buff == NULL) {
printf("Other buff is null!");
return;
}
//In the testcase, don't process this. We should see the label as canonical
//Processing will produce a false positive potentially, so look at taint_sets
if (other_buff[0] == 'a') {
printf("Other buff is a!");
return;
}
return;
}
int main(int argc, char * argv[]) {
if (argc < 2) {
printf("Error, no file specified!");
}
int fd = open(argv[1], O_RDONLY);
if (fd == -1) {
printf("Could not open file!\n");
}
else {
char buff[2048];
memset(buff, 0, sizeof(buff));
char other_buff[2048];
memset(other_buff, 0, sizeof(other_buff));
int bytes_read = read(fd, buff, 10);
memcpy(other_buff, buff, sizeof(other_buff));
touch_copied_byte(other_buff);
close(fd);
}
return 0;
}
|
C
|
/* 给出一个大于或等于3的正整数,判断它是不是一个素数 */
#include <stdio.h>
#include <math.h>
main()
{
int n, i, judge;
judge = 1;
scanf("%d", &n);
for (i = 2; i < sqrt(n) + 1; ++i) {
if (n % i)
continue;
judge = 0;
break;
}
if (judge)
printf("%d is a prime number\n", n);
else
printf("%d is not a prime number\n", n);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int a1;
int a2;
int a3;
int result;
int main()
{
printf("Enter port value\n");
scanf("%d", &a1);
printf("Enter RPM\n");
scanf("%d", &a2);
printf("Enter line frequency (60/50) \n");
scanf("%d", &a3);
result = calculatevalue(a1,a2,a3);
printf("%d\n", result);
}
int calculatevalue(a1,a2,a3)
{
return a1 * a2 / a3;
}
|
C
|
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<sys/wait.h>
int main()
{
pid_t ret;
int status_shell;
int cmd_exec;
char common[10];
printf("Enter your command:");
scanf("%s", common);
ret=fork();
if(ret<0)
{
perror("fork");
exit(1);
}
if(ret==0)
{
cmd_exec=execlp(common,common);
if(cmd_exec<0)
{
perror("execlp");
exit(2);
}
exit(0);
}
else
{
waitpid(-1,&status_shell,0); //wait(&status_shell);
printf("parent--child exit status=%d\n",
WEXITSTATUS(status_shell));
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <pthread.h>
/**********************全局变量定义区*****************/
int fd_fifo; //创建有名管道,用于向mplayer发送命令
int fd_pipe[2]; //创建无名管道,用于从mplayer读取命令
int main(int argc, char *argv[])
{
int fd;
char buf[100];
pid_t pid;
unlink("/tmp/fifo_mplayer"); //如果明明管道存在,则先删除
mkfifo("/tmp/fifo_mplayer",O_CREAT|0666);
perror("mk fifo_mplayer error");
if (pipe(fd_pipe)<0 ) //创建无名管道
{
perror("pipe error\n");
exit(-1);
}
pid=fork();
if(pid<0)
{
perror("fork");
}
if(pid==0) //子进程播放mplayer
{
close(fd_pipe[0]);
dup2(fd_pipe[1],1); //将子进程的标准输出重定向到管道的写端
dup2(fd_pipe[1],2); //将子进程的标准输出重定向到管道的写端
fd_fifo=open("/tmp/fifo_mplayer",O_RDWR);
system("sudo mplayer -slave -quiet -shuffle -input file=/tmp/fifo_mplayer /home/zhaowei/music/* NULL");
// execlp("mplayer","mplayer","-slave","-quiet","-input","file=/tmp/fifo_mplayer","juhuatai.mpg",NULL);
}
else
{
// system("irexec");
while(1)
sleep(5);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "my_binary_search_tree.h"
typedef struct TreeNode
{
ElementType e;
SearchTree left;
SearchTree right;
} aNode;
/**
* 置空
*/
SearchTree make_empty(SearchTree ST)
{
if (ST)
{
make_empty(ST->left);
make_empty(ST->right);
free(ST);
}
return NULL;
}
Position find(ElementType e, SearchTree ST)
{
if (!ST)
return NULL;
if (e < ST->e)
{
find(e, ST->left);
}
else if (e > ST->e)
{
return find(e, ST->right);
}
else
{
return ST;
}
}
Position find_min(SearchTree ST){
if (!ST)
{
return NULL;
}
// if (ST->left)
// {
// return find_min(ST->left);
// }else
// {
// return ST;
// }
Position tmpcell = ST;
while (tmpcell->left)
{
tmpcell = tmpcell->left;
}
return tmpcell;
}
Position find_max(SearchTree ST){
if (!ST)
{
return NULL;
}
while (ST->right)
{
ST = ST->right;
}
return ST;
}
/**
* 插入元素
*/
SearchTree insert(ElementType e, SearchTree ST)
{
if (!ST)
{
ST = (SearchTree)malloc(sizeof(aNode));
if(!ST)
exit(1);
ST->e = e;
ST->left = NULL;
ST->right = NULL;
}else
{
if(e < ST->e)
{
ST->left = insert(e,ST->left);
}else if(e > ST->e)
{
ST->right = insert(e,ST->right);
}
}
return ST;
}
SearchTree delete_min(SearchTree ST)
{
if(!ST)
return NULL;
if(ST->left)
{
ST->left = delete_min(ST->left);
}else
{
/*found element to be deleted*/
Position tmpcell = ST->right;
if(tmpcell){
ST->e = tmpcell->e;
ST->left = tmpcell->left;
ST->right = tmpcell->right;
free(tmpcell);
}else
{
free(ST);
ST = NULL;
}
}
return ST;
}
SearchTree delete_e(ElementType e, SearchTree ST)
{
Position tmpcell = NULL;
if (!ST)
{
return NULL;
}
if (e < ST->e)
{ /*go left*/
ST->left = delete_e(e,ST->left);
}else if(e > ST->e)
{ /*go right*/
ST->right = delete_e(e,ST->right);
}else
{
/*found element to be deleted*/
if(ST->left && ST->right)
{
/*two childs*/
/*find smallest element in right SearchTree*/
tmpcell = find_min(ST->right);
ST->e = tmpcell->e;
// ST->right = delete_e(ST->e,ST->right);
ST->right = delete_min(ST->right);
}else
{
tmpcell = ST;
if(!ST->right)
{
ST = ST->left;
}else
if(!ST->left)
{
ST = ST->right;
}
free(tmpcell);
}
}
return ST;
}
ElementType retrieve(Position P)
{
return P->e;
}
/**
* 前序遍历--递归
*/
void preorder_traversal(SearchTree T)
{
if(T)
{
printf("%2c",T->e);
preorder_traversal(T->left);
preorder_traversal(T->right);
}
}
/**
* 中序遍历--递归
*/
void inorder_traversal(SearchTree T){
if(T)
{
inorder_traversal(T->left);
printf("%2c",T->e);
inorder_traversal(T->right);
}
}
/**
* 后续遍历--递归
*/
void postorder_traversal(SearchTree T)
{
if (T)
{
postorder_traversal(T->left);
postorder_traversal(T->right);
printf("%2c",T->e);
}
}
int main(void)
{
SearchTree T = NULL;
char input = '\0';
while((input = getchar()) != '\n')
{
if(input != 32)
T = insert(input,T);
}
preorder_traversal(T);
printf("\n");
inorder_traversal(T);
printf("\n");
postorder_traversal(T);
printf("\n%2c\n",retrieve(find_max(T)));
printf("\n%2c\n",retrieve(find_min(T)));
T = delete_e('2',T);
preorder_traversal(T);
printf("\n");
inorder_traversal(T);
printf("\n");
postorder_traversal(T);
printf("\n");
T = delete_e('5',T);
preorder_traversal(T);
printf("\n");
inorder_traversal(T);
printf("\n");
postorder_traversal(T);
printf("\n");
T = delete_e('4',T);
preorder_traversal(T);
printf("\n");
inorder_traversal(T);
printf("\n");
postorder_traversal(T);
}
|
C
|
/*
M1 Informatique IM2AG-UGA
Tp SipHash:
Borne Jonathan - Duverney Thomas
Coll_search_stats:
Description:
Mesure du nombre d'itérations de la fonction brentrec néccessaires au calcul
d'une collision de la fonction siphash_fix_32.
Calcule une collision pour 1000 clés différentes et écrit
dans le fichier Collision.csv les valeurs finales des paramètres de la fonction brentrec
à l'issue du calcul de chaque collision.
Structure du fichier csv:
run_id;nb_iter;i;j;x;y;k
0;27658;16383;11276;2591630181;2591630181;0
- run_id: correspond a l'identifiant de la mesure effectuée dans le cas ou l'on lancerai la mesure
plusieurs fois.
- nb_iter: correspond aux nombre d'appel total de la fonction brent_rec.
- i-j: correspond à la periode de la suite u_n définie par
u_0 = sip_hash_fix32(k, 0)
u_n = sip_hash_fix32(k, u_(n-1))
- x: correspond à la valeur de u_i au moment de la collision
- y: correspond à la valeur de u_j au moment de la collision (est égal à x).
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "sipHash.h"
#define N 1000
int main (){
printf("------------------------- \n");
printf("-- coll_search_stats -- \n");
printf("------------------------- \n");
printf("Calcule une collision pour 1000 valeurs de clé différentes et écrit\n");
printf("dans le fichier Collision.csv les valeurs finales des paramètres de la\n");
printf("fonction brentrec à l'issue du calcul de chaque collision.\n");
printf("Structure du fichier csv:\n");
printf(" run_id;nb_iter;i;j;x;y;k\n");
printf(" 0;27658;16383;11276;2591630181;2591630181;0\n\n");
printf(" - run_id: correspond a l'identifiant de la mesure effectuée dans le cas ou l'on lancerai la mesure\n");
printf(" plusieurs fois.\n");
printf(" - nb_iter: correspond aux nombre d'appel total de la fonction brent_rec.\n");
printf(" - i-j: correspond à la periode de la suite u_n définie par\n");
printf(" u_0 = sip_hash_fix32(k, 0)\n");
printf(" u_n = sip_hash_fix32(k, u_(n-1))\n");
printf(" - x: correspond à la valeur de u_i au moment de la collision\n");
printf(" - y: correspond à la valeur de u_j au moment de la collision (est égal à x).\n");
uint32_t k = 0;
int run_id = 0;
int n = 0;
FILE *f = fopen("./Collisions.csv", "w");
fprintf(f, "run_id;nb_iter;i;j;x;y;k\n");
for (n = 0; n < N; n++){
coll_search_stats(f, run_id, k, *sip_hash_fix32);
k += 1;
}
return 0;
}
|
C
|
#include "clar_libgit2.h"
#include "config_backend.h"
#include "config.h"
#include "path.h"
static git_config *cfg;
void test_config_readonly__initialize(void)
{
cl_git_pass(git_config_new(&cfg));
}
void test_config_readonly__cleanup(void)
{
git_config_free(cfg);
cfg = NULL;
}
void test_config_readonly__writing_to_readonly_fails(void)
{
git_config_backend *backend;
cl_git_pass(git_config_backend_from_file(&backend, "global"));
backend->readonly = 1;
cl_git_pass(git_config_add_backend(cfg, backend, GIT_CONFIG_LEVEL_GLOBAL, NULL, 0));
cl_git_fail_with(GIT_ENOTFOUND, git_config_set_string(cfg, "foo.bar", "baz"));
cl_assert(!git_path_exists("global"));
}
void test_config_readonly__writing_to_cfg_with_rw_precedence_succeeds(void)
{
git_config_backend *backend;
cl_git_pass(git_config_backend_from_file(&backend, "global"));
backend->readonly = 1;
cl_git_pass(git_config_add_backend(cfg, backend, GIT_CONFIG_LEVEL_GLOBAL, NULL, 0));
cl_git_pass(git_config_backend_from_file(&backend, "local"));
cl_git_pass(git_config_add_backend(cfg, backend, GIT_CONFIG_LEVEL_LOCAL, NULL, 0));
cl_git_pass(git_config_set_string(cfg, "foo.bar", "baz"));
cl_assert(git_path_exists("local"));
cl_assert(!git_path_exists("global"));
cl_git_pass(p_unlink("local"));
}
void test_config_readonly__writing_to_cfg_with_ro_precedence_succeeds(void)
{
git_config_backend *backend;
cl_git_pass(git_config_backend_from_file(&backend, "local"));
backend->readonly = 1;
cl_git_pass(git_config_add_backend(cfg, backend, GIT_CONFIG_LEVEL_LOCAL, NULL, 0));
cl_git_pass(git_config_backend_from_file(&backend, "global"));
cl_git_pass(git_config_add_backend(cfg, backend, GIT_CONFIG_LEVEL_GLOBAL, NULL, 0));
cl_git_pass(git_config_set_string(cfg, "foo.bar", "baz"));
cl_assert(!git_path_exists("local"));
cl_assert(git_path_exists("global"));
cl_git_pass(p_unlink("global"));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void func(char **a, int n)
{
int i, j, count, k, l,s1,s2, res, temp=0;
int **b=malloc(n*sizeof(int*));
for (i=0;i<n;i++)
b[i]=calloc(n,sizeof(int));
for(i=0;i<n;i++){
s1=strlen(a[i]);
for(j=0;j<n;j++){
if(j==i)
continue;
s2=strlen(a[j]);
k=s1;
l=0;
while(a[i][k]==a[j][l]){
b[i][j]++;
l++;
k--;
}
}
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(b[i][j]>temp){
temp=b[i][j];
k=i;
l=j;
}
for(i=0;i<n;i++)
free(b[i]);
free(b);
}
int main()
{
int i, n;
scanf("%d\n", &n);
char **a=malloc(n*sizeof(char*));
for(i=0;i<n;i++){
a[i]=malloc(20*sizeof(char));
gets(a[i]);
}
func(a, n);
for(i=0;i<n;i++)
free(a[i]);
free(a);
return 0;
}
|
C
|
#include <stdio.h>
#include "libft.h"
#include "ft_stack.h"
int ft_greater_markup(t_stack *a, int i);
int ft_find_greater_markup(t_stack *a);
void ft_greater_markup_marks(t_stack *a, int markup_head_i);
void ft_greater_markup_test(t_stack *a)
{
int i;
i = a->top + 1;
while (--i >= 0)
{
ft_putstr("Head ");
ft_putnbr(a->stack[i]);
ft_putchar('[');
ft_putnbr(i);
ft_putstr("]\tMarkup size = ");
ft_putnbr(ft_greater_markup(a, i));
ft_putchar('\n');
}
}
void ft_find_greater_markup_test(t_stack *a)
{
int markup_head_i;
markup_head_i = ft_find_greater_markup(a);
ft_putstr("Greater markup is ");
ft_putnbr(a->stack[markup_head_i]);
ft_putchar('[');
ft_putnbr(markup_head_i);
ft_putstr("]\n");
}
void ft_greater_markup_marks_test(t_stack *a)
{
int markup_head_i;
int i;
markup_head_i = ft_find_greater_markup(a);
ft_greater_markup_marks(a, markup_head_i);
i = a->top + 1;
ft_putstr("TOP\n");
while (--i >= 0)
{
ft_putnbr(a->stack[i]);
ft_putchar('[');
ft_putnbr(i);
ft_putchar(']');
ft_putstr((a->marks[i] == 1) ? "marked\n" : "\n");
}
}
int main(void)
{
t_stack *a;
a = ft_stack_new(10);
ft_stack_push(a, 9);
ft_stack_push(a, 1);
ft_stack_push(a, 7);
ft_stack_push(a, 6);
ft_stack_push(a, 4);
ft_stack_push(a, 0);
ft_stack_push(a, 3);
ft_stack_push(a, 8);
ft_stack_push(a, 2);
ft_stack_push(a, 5);
ft_greater_markup_test(a);
ft_find_greater_markup_test(a);
ft_greater_markup_marks_test(a);
return (0);
}
|
C
|
/* x14-processes/valentine.c */
/* Copyright (c) 2020 J. M. Spivey */
#include "hardware.h"
#include "microbian.h"
#include "lib.h"
/* heart -- filled-in heart image */
const unsigned heart[] =
IMAGE(0,1,0,1,0,
1,1,1,1,1,
1,1,1,1,1,
0,1,1,1,0,
0,0,1,0,0);
/* small -- small heart image */
const unsigned small[] =
IMAGE(0,0,0,0,0,
0,1,0,1,0,
0,1,1,1,0,
0,0,1,0,0,
0,0,0,0,0);
/* show -- display three rows of a picture n times */
void show(const unsigned *img, int n)
{
while (n-- > 0) {
/* Takes 15msec per iteration */
for (int p = 0; p < 3; p++) {
GPIO_OUT = img[p];
timer_delay(5);
}
}
}
/* heart_task -- show beating heart */
void heart_task(int n)
{
GPIO_DIRSET = 0xfff0;
priority(P_HIGH);
while (1) {
show(heart, 70);
show(small, 10);
show(heart, 10);
show(small, 10);
}
}
/* This is a bit lighter than the earlier example, because we use GCC's
builtin modulo operation, rather than repeated subtraction. That
leaves some CPU time over to look after the blinking lights. */
/* prime -- test for primality */
int prime(int n)
{
for (int k = 2; k * k <= n; k++) {
if (n % k == 0)
return 0;
}
return 1;
}
/* prime_task -- print primes on the serial port */
void prime_task(int arg)
{
int n = 2, count = 0;
while (1) {
if (prime(n)) {
count++;
printf("prime(%d) = %d\n", count, n);
}
n++;
}
}
void init(void)
{
serial_init();
timer_init();
start("Heart", heart_task, 0, STACK);
start("Prime", prime_task, 0, STACK);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.