language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include<stdio.h>
#include<windows.h>
#include<stdlib.h>
int main() {
/*int n = 5;
do
printf("countdown %d !!!\n", n);
while (n-- > 0);
printf("ǡ̾~~\n");*/
//goto
/*goto A;
B:
printf(" 1\n");
printf(" 2\n");
printf(" 3\n");
printf(" 4\n");
printf(" 5\n");
printf(" 6\n");
goto C;
A:
printf(" 7\n");
goto B;
C:*/
//break
/*int breakNumber = 0;
int n = 0;
printf("1~100 ȣ ߿ ϳ :");
scanf_s(" %d", &breakNumber);
for (n = 1; n <= 100; n++) {
if (n == breakNumber)
break;
printf("%d\n",n);
}*/
//continue
/*int checknumber = 0;
int n = 0;
int isOdd = 0;
printf(" Էϼ : ");
scanf_s(" %d", &checknumber);
isOdd = checknumber % 2 == 1;
for (n = 1; n < 100; n++) {
if (n % 2 == isOdd)
continue;
printf("%d\n", n);
}*/
//
/*int start_num, final_num;
printf(" ȣ Էϼ : ");
scanf_s(" %d", &start_num);
printf(" ȣ Էϼ : ");
scanf_s(" %d", &final_num);
while (++start_num < final_num)
printf("%d\n", start_num);*/
//ݺ
/*int loopnum,num,i,j,k;
printf("ݺ Ƚ Էϼ : ");
scanf_s(" %d", &loopnum);
printf("ڸ Էϼ : ");
scanf_s(" %d", &num);
for (i = 0; i < loopnum; i++) {
j = (num % 2) ? -i : i - loopnum+1;
for (; j <= 0; j++)
printf("");
printf("\n");
}
for (i = 0; i < loopnum; i++) {
if (num % 2)
for (j = 0; j < i+1; j++)
printf("");
else
for(j=0;j<loopnum-i;j++)
printf("");
putchar('\n');
}
*/
//迭
/*int n = 0;
int numbers[10] = { 0,1,2,3,4,5,6,7,8 };
printf("numbers addr = %u\n", numbers);
printf("numbers[0] addr = %u\n", &numbers[0]);
for (n = 0; n < 10; n++) {
printf("numbers[%d] addr = %u\n", n,&numbers[n]);
printf("numbers[%d] = %d\n", n, numbers[n]);
}*/
//迭
int numbers[10];
int n,m,number;
printf("ڸ Է ϼ : ");
scanf_s(" %d", &number);
m = (number % 2)? 1:2;
for (n = 0; n < 10; n++) {
numbers[n] = n * 2 + m;
printf("%d\n", numbers[n]);
}
rand();
system("pause");
return 0;
}
|
C
|
#include "tests.h"
int main() {
setup();
Socket * sock = malloc(sizeof(Socket));
*sock = (Socket) {.data = NULL};
assert(netConnect(sock) == ENULL_POINTER && "Did not receive the expected value for null data");
free(sock);
cleanup();
}
|
C
|
//
// Created by Once on 2019/7/22.
//
#ifndef TREE_BTREE_H
#define TREE_BTREE_H
// 键值数组结构
typedef struct column{
int id; // 关键字
char title[70];
} Column;
// B树结点
typedef struct bnode{
int size; // 当前关键字数目
Column **columns; // 键值数组
struct bnode **children; // 儿子指针数组
struct bnode *parent; //父指针
struct bnode *next; //横向顺序查找的链表指针
unsigned int leaf; // 是否为叶子 1是 0否
} BNode;
// B树ADT对外接口
typedef struct btree{
unsigned int degree; // 度数
BNode *root; // 根结点
BNode *head; // 叶子链表的头结点
unsigned int size; // B树结点大小
} BTree;
// B树算法操作声明
extern BTree *btree_init(unsigned int degree); //初始化
extern int btree_is_empty(BTree *btree); //空
extern int btree_add(BTree *btree, Column *column); //添加一个节点
extern int btree_delete_by_id(BTree *btree, int id); // 按id删除一个节点
extern Column *btree_max(BTree *btree); //最大值
extern Column *btree_min(BTree *btree); // 最小值
extern Column *btree_get_by_value(BTree *btree, Column * c); //按值获取一个节点
extern void btree_traverse(BTree *btree, void(*traverse)(BNode*));//遍历
extern int btree_clear(BTree *btree);//释放空间
extern void print_node_data(BNode *node);
extern void print_node(BNode *node);
extern int btree_node_count(BTree *btree);
extern int btree_leaf_count(BTree *btree);
extern void setDebug(int d);
// 最小度数t>=2,度数就是子树个数
// 根结点的关键字数最小为1
// 非叶非根结点的度数:t <= T <= 2t-1
// 非根结点的关键字数:t <= K <= 2t-1
// 关键数K和度数的关系为:K = T。
// 所有叶子结点的深度相同
// 满关键字为2t-1,分裂为两个子树
#endif //TREE_BTREE_H
|
C
|
/* This program is a part of RW mudlib
* See /doc/help/copyright for more info
-----------------------------------------
* File : Lock.c
* Author :
* Date : 2003-05-02
* Note : O
* Update :
* o 2000-00-00
*
-----------------------------------------
*/
#include <map.h>
#include <lock.h>
#include <feature.h>
#include <message.h>
#include <daemon.h>
#include <location.h>
inherit COMMAND;
string help = @HELP
oOiAWݩAؿvA~HLkiXQAWC
lock 'V' - NYӤVW
(north, south, east, west, northeast, northwest, southeast, southwest, up, down)
HELP;
private void do_command(object me, string arg)
{
int locktype;
string option;
mapping exits;
mapping a = ([
"west" : "east",
"east" : "west",
"north" : "south",
"south" : "north",
"northeast" : "southwest",
"northwest" : "southeast",
"southeast" : "northwest",
"southwest" : "northeast",
"up" : "down",
"down" : "up"
]);
object env, to;
env = environment(me);
if( !arg )
return tell(me, pnoun(2, me)+"QnN@ӤVWH\n");
sscanf(arg, "%s %s", arg, option);
switch(option)
{
case "wiz":
if( wizardp(me) )
locktype = WIZLOCKED;
else
locktype = LOCKED;
break;
default:
locktype = LOCKED;
}
if( !env->is_maproom() )
{
if( !wizardp(me) && query("owner", env) != me->query_id(1) )
return tell(me, "ǫäOAؿvALkWC\n");
if( !mapp(exits = query("exits", env)) )
return tell(me, "ǫèSXfAnWOH\n");
if( !exits[arg] )
return tell(me, "ǫèSoӤVALkoVWC\n");
if( arrayp(exits[arg]) )
{
set("lock/"+arg, query("lock/"+arg, env) | locktype, env);
CITY_D->set_coor_data(exits[arg], "lock", CITY_D->query_coor_data(exits[arg], "lock") | locktype);
}
else
{
to = load_object(exits[arg]);
set("lock/"+arg, query("lock/"+arg, env) | locktype, env);
set("lock/"+a[arg], query("lock/"+a[arg], to) | locktype, to);
broadcast(to, "GH "+a[arg] +"VF_ӡC\n");
}
tell(me, pnoun(2, me)+"⩹ "+capitalize(arg)+" VF_ӡC\n");
}
else
{
int x, y, num;
string city;
array loc = query_temp("location", me);
x = loc[X];
y = loc[Y];
city = loc[CITY];
num = loc[NUM];
if( !CITY_D->is_city_location(loc) )
return tell(me, "oSiH"+pnoun(2, me)+"WC\n");
switch(arg)
{
case "north":
loc = arrange_city_location(x, --y, city, num);
break;
case "south":
loc = arrange_city_location(x, ++y, city, num);
break;
case "east":
loc = arrange_city_location(++x, y, city, num);
break;
case "west":
loc = arrange_city_location(--x, y, city, num);
break;
case "northeast":
loc = arrange_city_location(++x, --y, city, num);
break;
case "northwest":
loc = arrange_city_location(--x, --y, city, num);
break;
case "southeast":
loc = arrange_city_location(++x, ++y, city, num);
break;
case "southwest":
loc = arrange_city_location(--x, ++y, city, num);
break;
default:
return tell(me, pnoun(2, me)+"QnN@ӤVWH\n");
}
if( !CITY_D->valid_coordinate(x, y, city, num) )
return tell(me, "ӤVOXzyСC\n");
if( !wizardp(me) && CITY_D->query_coor_data(loc, "owner") != me->query_id(1) )
return tell(me, "ǫäOAؿvALkWC\n");
if( CITY_D->query_coor_data(loc, TYPE) != DOOR )
return tell(me, "̨èSALkWC\n");
if( ESTATE_D->query_loc_estate(loc)["type"] == "land" )
return tell(me, "u@An֡H\n");
CITY_D->set_coor_data(loc, "lock", CITY_D->query_coor_data(loc, "lock") | locktype);
tell(me, pnoun(2, me)+"⩹ "+capitalize(arg)+" VF_ӡC\n");
}
}
|
C
|
#include<stdio.h>
void main(){
const int first;
int second;
const int third;
printf("enter value:\n");
scanf("%d\n",&first);
scanf("%d\n",&second);
scanf("%d\n",&third);
printf("first value=%d\n",first);
printf("second value=%d\n",second);
printf("third value=%d\n",third);
first=first+5;
second=second+3;
third=third+2;
printf("first value=%d\n",first);
printf("second value=%d\n",second);
printf("third value=%d\n",third);
}
|
C
|
#include<stdio.h>
#define m 1000
int fun(int xx[], int n)
{
int cnt = 0;
for(int i = 3; i < n; i++)
{
for(int j = 2; j < i; j++)
if(i % j == 0) xx[cnt++] = i;
}
return cnt;
}
int main()
{
int xx[m];
for(int i = 0; i < m; i++)
xx[i] = 0;
int n = fun(xx, 17);
printf("%d\n",n);
for(int i = 0; xx[i] != 0; i++)
printf("%d ",xx[i]);
printf("\n");
return 0;
}
|
C
|
#include <stdint.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <limits.h>
#include "test.h"
#ifndef PAGE_SIZE
#define PAGE_SIZE sysconf(_SC_PAGE_SIZE)
#endif
#ifndef MAP_ANONYMOUS
#define MAP_ANONYMOUS 0
#endif
/* max mmap size, *start is the largest power-of-2 size considered */
static size_t mmax(int fd, size_t *start)
{
size_t i, n;
void *p;
for (i=n=*start; i>=PAGE_SIZE; i/=2) {
if ((p=mmap(0, n, PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS, fd, 0)) == MAP_FAILED) {
n -= i/2;
} else {
munmap(p, n);
if (n == i)
*start = n;
n += i/2;
}
}
return n & -PAGE_SIZE;
}
/*
fills the virtual memory with anonymous PROT_NONE mmaps,
returns the mappings in *p and *n in decreasing size order,
the return value is the number of mappings or -1 on failure.
*/
int t_vmfill(void **p, size_t *n, int len)
{
int fd = MAP_ANONYMOUS ? -1 : open("/dev/zero", O_RDWR);
size_t start = SIZE_MAX/2 + 1;
size_t m;
void *q;
int i;
for (i=0;;i++) {
m = mmax(fd, &start);
if (!m)
break;
q = mmap(0, m, PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS, fd, 0);
if (q == MAP_FAILED)
return -1;
if (i < len) {
p[i] = q;
n[i] = m;
}
}
return i;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "debug.h"
#include "ss_data.h"
// TODO: I should import the header file with the definition for the
/*
A view in the matrix allows to extract any subset of values from a
matrix.
*/
struct matrix_view {
int lb[3];
int ub[3];
};
/* Generic matrix representation. */
struct matrix {
int dimx, dimy, dimz;
size_t size_elem;
enum storage_type mat_storage;
struct matrix_view mat_view;
void *pdata;
};
/*
Cache structure to "map" a bounding box to corresponding nodes in
the space.
*/
struct sfc_hash_cache {
struct list_head sh_entry;
struct bbox sh_bb;
struct dht_entry **sh_de_tab;
int sh_nodes;
};
static LIST_HEAD(sfc_hash_list);
static int compute_bits(unsigned int n)
{
int nr_bits = 0;
while(n) {
n = n >> 1;
nr_bits++;
}
return nr_bits;
}
int sh_add(const struct bbox *bb, struct dht_entry *de_tab[], int n)
{
struct sfc_hash_cache *shc;
int i, err = -ENOMEM;
shc = malloc(sizeof(*shc) + sizeof(de_tab[0]) * n);
if(!shc)
goto err_out;
shc->sh_bb = *bb;
shc->sh_nodes = n;
shc->sh_de_tab = (struct dht_entry **) (shc + 1);
for(i = 0; i < n; i++)
shc->sh_de_tab[i] = de_tab[i];
list_add_tail(&shc->sh_entry, &sfc_hash_list);
return 0;
err_out:
uloga("'%s()': failed with %d.\n", __func__, err);
return err;
}
int sh_find(const struct bbox *bb, struct dht_entry *de_tab[])
{
struct sfc_hash_cache *shc;
int i;
list_for_each_entry(shc, &sfc_hash_list, sh_entry) {
if(bbox_equals(bb, &shc->sh_bb)) {
for(i = 0; i < shc->sh_nodes; i++)
de_tab[i] = shc->sh_de_tab[i];
return shc->sh_nodes;
}
}
return -1;
}
void sh_free(void)
{
struct sfc_hash_cache *l, *t;
int n = 0;
list_for_each_entry_safe(l, t, &sfc_hash_list, sh_entry) {
free(l);
n++;
}
#ifdef DEBUG
uloga("'%s()': SFC cached %d object descriptors, size = %zu.\n", __func__, n, sizeof(*l) * n);
#endif
}
#if 0 /* DELETE this unused part. */
/*
Allocate and initialize a matrix "view". It allows you to easily
access the elements of sub-matrix described by bounding box bb_loc
from the matrix described by bb_glb. When accessing the sub-matrix,
the indices should be reversed, i.e., A(k, j, i).
*/
static struct matrix *matrix_alloc(struct bbox *bb_glb, struct bbox *bb_loc, void *data, size_t se)
{
struct matrix *mat;
size_t size;
int dimx, dimy, dimz;
int shx, shy, shz;
int i, j;
dimx = bbox_dist(bb_glb, 0);
dimy = bbox_dist(bb_glb, 1);
dimz = bbox_dist(bb_glb, 2);
size = sizeof(*mat) + sizeof(void ***) * dimz + sizeof(void **) * dimx * dimz;
mat = malloc(size);
if(!mat)
return NULL;
mat->data = data;
mat->se = se;
/* X is columns. */
mat->dimx = bbox_dist(bb_loc, 0);
/* Y is rows. */
mat->dimy = bbox_dist(bb_loc, 1);
/* Z is slices of 2d matrices of XxY. */
mat->dimz = bbox_dist(bb_loc, 2);
mat->m = (void ***) (mat + 1);
/*
for (i = 0; i < mat->z_dim; i++) {
mat->m[i] = (double **) (mat->m + mat->z_dim + i * mat->y_dim);
for (j = 0; j < mat->y_dim; j++)
mat->m[i][j] = data +
(i + bb_loc->lb.c[2]) * x_dim * y_dim +
(j + bb_loc->lb.c[1]) * x_dim +
bb_loc->lb.c[0];
}
*/
/* Shift amounts from the initial matrix. */
shx = bb_loc->lb.c[0] - bb_glb->lb.c[0];
shy = bb_loc->lb.c[1] - bb_glb->lb.c[1];
shz = bb_loc->lb.c[2] - bb_glb->lb.c[2];
/* Column major matrix representation. */
for(i = 0; i < mat->dimz; i++) {
mat->m[i] = (void **) (mat->m + dimz + i * dimx);
for(j = 0; j < mat->dimx; j++)
mat->m[i][j] = data +
/* Skip 'i' 2d slices. */
((i + shz) * dimx * dimy +
/* Skip 'j' 1d columns. */
(j + shx) * dimy +
/* Select the line. */
shy) * se;
}
return mat;
}
static void matrix_copy(struct matrix *mat_to, struct matrix *mat_from)
{
int i, j, k;
size_t size;
/*
for (i = 0; i < mat_to->z_dim; i++) {
for (j = 0; j < mat_to->y_dim; j++)
memcpy(mat_to->m[i][j],
mat_from->m[i][j],
sizeof(double) * mat_to->x_dim);
}
*/
size = mat_to->se * mat_to->dimy;
for(i = 0; i < mat_to->dimz; i++) {
for(j = 0; j < mat_to->dimx; j++)
memcpy(mat_to->m[i][j], mat_from->m[i][j], size);
}
}
static void matrix_free(struct matrix *mat)
{
free(mat);
}
#endif /* 0 */
static void matrix_init(struct matrix *mat, enum storage_type st, struct bbox *bb_glb, struct bbox *bb_loc, void *pdata, size_t se)
{
int i;
mat->dimx = bbox_dist(bb_glb, bb_x);
mat->dimy = bbox_dist(bb_glb, bb_y);
mat->dimz = bbox_dist(bb_glb, bb_z);
mat->mat_storage = st;
for(i = bb_x; i <= bb_z; i++) {
mat->mat_view.lb[i] = bb_loc->lb.c[i] - bb_glb->lb.c[i];
mat->mat_view.ub[i] = bb_loc->ub.c[i] - bb_glb->lb.c[i];
}
mat->pdata = pdata;
mat->size_elem = se;
}
static void matrix_copy(struct matrix *a, struct matrix *b)
{
/*
typedef struct {
char size_on_mem[a->size_elem];
} matrix_elem_generic_t;
*/
typedef char matrix_elem_generic_t[a->size_elem];
int ai, aj, ak, bi, bj, bk;
int n;
if(a->mat_storage == column_major && b->mat_storage == column_major) {
matrix_elem_generic_t(*A)[a->dimz][a->dimx][a->dimy] = a->pdata;
matrix_elem_generic_t(*B)[b->dimz][b->dimx][b->dimy] = b->pdata;
/* Column major data representation (Fortran style) */
n = a->mat_view.ub[bb_y] - a->mat_view.lb[bb_y] + 1;
ak = a->mat_view.lb[bb_y];
bk = b->mat_view.lb[bb_y];
for(ai = a->mat_view.lb[bb_z], bi = b->mat_view.lb[bb_z]; ai <= a->mat_view.ub[bb_z]; ai++, bi++) {
for(aj = a->mat_view.lb[bb_x], bj = b->mat_view.lb[bb_x]; aj <= a->mat_view.ub[bb_x]; aj++, bj++)
memcpy(&(*A)[ai][aj][ak], &(*B)[bi][bj][bk], a->size_elem * n);
}
} else if(a->mat_storage == column_major && b->mat_storage == row_major) {
matrix_elem_generic_t(*A)[a->dimz][a->dimx][a->dimy] = a->pdata;
matrix_elem_generic_t(*B)[b->dimz][b->dimy][b->dimx] = b->pdata;
/* ... */
for(ai = a->mat_view.lb[bb_z], bi = b->mat_view.lb[bb_z]; ai <= a->mat_view.ub[bb_z]; ai++, bi++) {
for(aj = a->mat_view.lb[bb_x], bj = b->mat_view.lb[bb_x]; aj <= a->mat_view.ub[bb_x]; aj++, bj++) {
for(ak = a->mat_view.lb[bb_y], bk = b->mat_view.lb[bb_y]; ak <= a->mat_view.ub[bb_y]; ak++, bk++)
memcpy(&(*A)[ai][aj][ak], &(*B)[bi][bk][bj], a->size_elem);
// (*A)[ai][aj][ak] = (*B)[bi][bk][bj];
}
}
} else if(a->mat_storage == row_major && b->mat_storage == column_major) {
matrix_elem_generic_t(*A)[a->dimz][a->dimy][a->dimx] = a->pdata;
matrix_elem_generic_t(*B)[b->dimz][b->dimx][b->dimy] = b->pdata;
/* ... */
for(ai = a->mat_view.lb[bb_z], bi = b->mat_view.lb[bb_z]; ai <= a->mat_view.ub[bb_z]; ai++, bi++) {
for(aj = a->mat_view.lb[bb_y], bj = b->mat_view.lb[bb_y]; aj <= a->mat_view.ub[bb_y]; aj++, bj++) {
for(ak = a->mat_view.lb[bb_x], bk = b->mat_view.lb[bb_x]; ak <= a->mat_view.ub[bb_x]; ak++, bk++)
memcpy(&(*A)[ai][aj][ak], &(*B)[bi][bk][bj], a->size_elem);
// (*A)[ai][aj][ak] = (*B)[bi][bk][bj];
}
}
} else if(a->mat_storage == row_major && b->mat_storage == row_major) {
matrix_elem_generic_t(*A)[a->dimz][a->dimy][a->dimx] = a->pdata;
matrix_elem_generic_t(*B)[b->dimz][b->dimy][b->dimx] = b->pdata;
n = a->mat_view.ub[bb_x] - a->mat_view.lb[bb_x] + 1;
ak = a->mat_view.lb[bb_x];
bk = b->mat_view.lb[bb_x];
for(ai = a->mat_view.lb[bb_z], bi = b->mat_view.lb[bb_z]; ai <= a->mat_view.ub[bb_z]; ai++, bi++) {
for(aj = a->mat_view.lb[bb_y], bj = b->mat_view.lb[bb_y]; aj <= a->mat_view.ub[bb_y]; aj++, bj++)
memcpy(&(*A)[ai][aj][ak], &(*B)[bi][bj][bk], a->size_elem * n);
}
}
}
/* a = destination, b = source. Destination uses iovec_t format. */
static void matrix_copyv(struct matrix *a, struct matrix *b)
{
/*
typedef struct {
char size_on_mem[a->size_elem];
} matrix_elem_generic_t;
*/
typedef char matrix_elem_generic_t[a->size_elem];
int ai, aj, bi, bj, bk; // , ak;
int n;
if(a->mat_storage == column_major && b->mat_storage == column_major) {
// matrix_elem_generic_t (*A)[a->dimz][a->dimx][a->dimy] = a->pdata;
matrix_elem_generic_t(*B)[b->dimz][b->dimx][b->dimy] = b->pdata;
iovec_t *A = a->pdata;
/* Column major data representation (Fortran style) */
n = a->mat_view.ub[bb_y] - a->mat_view.lb[bb_y] + 1;
// ak = a->mat_view.lb[bb_y];
bk = b->mat_view.lb[bb_y];
for(ai = a->mat_view.lb[bb_z], bi = b->mat_view.lb[bb_z]; ai <= a->mat_view.ub[bb_z]; ai++, bi++) {
for(aj = a->mat_view.lb[bb_x], bj = b->mat_view.lb[bb_x]; aj <= a->mat_view.ub[bb_x]; aj++, bj++) {
A->iov_base = &(*B)[bi][bj][bk];
A->iov_len = a->size_elem * n;
A++;
}
/*
memcpy(&(*A)[ai][aj][ak],
&(*B)[bi][bj][bk],
a->size_elem * n);
*/
}
} else if(a->mat_storage == row_major && b->mat_storage == row_major) {
// matrix_elem_generic_t (*A)[a->dimz][a->dimy][a->dimx] = a->pdata;
matrix_elem_generic_t(*B)[b->dimz][b->dimy][b->dimx] = b->pdata;
iovec_t *A = a->pdata;
n = a->mat_view.ub[bb_x] - a->mat_view.lb[bb_x] + 1;
// ak = a->mat_view.lb[bb_x];
bk = b->mat_view.lb[bb_x];
for(ai = a->mat_view.lb[bb_z], bi = b->mat_view.lb[bb_z]; ai <= a->mat_view.ub[bb_z]; ai++, bi++) {
for(aj = a->mat_view.lb[bb_y], bj = b->mat_view.lb[bb_y]; aj <= a->mat_view.ub[bb_y]; aj++, bj++) {
A->iov_base = &(*B)[bi][bj][bk];
A->iov_len = a->size_elem * n;
A++;
}
/*
memcpy(&(*A)[ai][aj][ak],
&(*B)[bi][bj][bk],
a->size_elem * n);
*/
}
}
/*
else if (a->mat_storage == column_major && b->mat_storage == row_major) {
matrix_elem_generic_t (*A)[a->dimz][a->dimx][a->dimy] = a->pdata;
matrix_elem_generic_t (*B)[b->dimz][b->dimy][b->dimx] = b->pdata;
for (ai = a->mat_view.lb[bb_z], bi = b->mat_view.lb[bb_z];
ai <= a->mat_view.ub[bb_z]; ai++, bi++) {
for (aj = a->mat_view.lb[bb_x], bj = b->mat_view.lb[bb_y];
aj <= a->mat_view.ub[bb_x]; aj++, bj++) {
for (ak = a->mat_view.lb[bb_y], bk = b->mat_view.lb[bb_y];
ak <= a->mat_view.ub[bb_y]; ak++, bk++)
memcpy(&(*A)[ai][aj][ak],
&(*B)[bi][bk][bj],
a->size_elem);
// (*A)[ai][aj][ak] = (*B)[bi][bk][bj];
}
}
}
else if (a->mat_storage == row_major && b->mat_storage == column_major) {
matrix_elem_generic_t (*A)[a->dimz][a->dimy][a->dimx] = a->pdata;
matrix_elem_generic_t (*B)[b->dimz][b->dimx][b->dimy] = b->pdata;
for (ai = a->mat_view.lb[bb_z], bi = b->mat_view.lb[bb_z];
ai <= a->mat_view.ub[bb_z]; ai++, bi++) {
for (aj = a->mat_view.lb[bb_y], bj = b->mat_view.lb[bb_y];
aj <= a->mat_view.ub[bb_y]; aj++, bj++) {
for (ak = a->mat_view.lb[bb_x], bk = b->mat_view.lb[bb_x];
ak <= a->mat_view.ub[bb_x]; ak++, bk++)
memcpy(&(*A)[ai][aj][ak],
&(*B)[bi][bk][bj],
a->size_elem);
// (*A)[ai][aj][ak] = (*B)[bi][bk][bj];
}
}
}
*/
}
static struct dht_entry *dht_entry_alloc(struct sspace *ssd, int size_hash)
{
struct dht_entry *de;
int i;
de = malloc(sizeof(*de) + sizeof(struct obj_desc_list) * (size_hash - 1));
if(!de) {
errno = ENOMEM;
return de;
}
memset(de, 0, sizeof(*de));
de->ss = ssd;
de->odsc_size = size_hash;
for(i = 0; i < size_hash; i++)
INIT_LIST_HEAD(&de->odsc_hash[i]);
return de;
}
static void dht_entry_free(struct dht_entry *de)
{
struct obj_desc_list *l, *t;
int i;
//TODO: free the *intv and other resources.
free(de->i_tab);
for(i = 0; i < de->odsc_size; i++) {
list_for_each_entry_safe(l, t, &de->odsc_hash[i], odsc_entry)
free(l);
}
free(de);
}
static struct dht *dht_alloc(struct sspace *ssd, struct bbox *bb_domain, int num_nodes, int size_hash)
{
struct dht *dht;
int i;
dht = malloc(sizeof(*dht) + sizeof(struct dht_entry) * (num_nodes - 1));
if(!dht) {
errno = ENOMEM;
return dht;
}
memset(dht, 0, sizeof(*dht));
dht->bb_glb_domain = *bb_domain;
dht->num_entries = num_nodes;
for(i = 0; i < num_nodes; i++) {
dht->ent_tab[i] = dht_entry_alloc(ssd, size_hash);
if(!dht->ent_tab[i])
break;
}
if(i != num_nodes) {
errno = ENOMEM;
while(--i > 0)
free(dht->ent_tab[i]);
free(dht);
dht = 0;
}
return dht;
}
static void dht_free(struct dht *dht)
{
int i;
for(i = 0; i < dht->num_entries; i++)
free(dht->ent_tab[i]);
free(dht);
}
static int dht_intersect(struct dht_entry *de, struct intv *itv)
{
int i;
if(de->i_virt.lb > itv->ub || de->i_virt.ub < itv->lb)
return 0;
for(i = 0; i < de->num_intv; i++)
if(intv_do_intersect(&de->i_tab[i], itv))
return 1;
return 0;
}
/*
Allocate and init the local storage structure.
*/
static struct ss_storage *ls_alloc(int max_versions)
{
struct ss_storage *ls = 0;
int i;
ls = malloc(sizeof(*ls) + sizeof(struct list_head) * max_versions);
if(!ls) {
errno = ENOMEM;
return ls;
}
memset(ls, 0, sizeof(*ls));
for(i = 0; i < max_versions; i++)
INIT_LIST_HEAD(&ls->obj_hash[i]);
ls->size_hash = max_versions;
return ls;
}
static int ssd_get_max_dim(struct sspace *ss)
{
return ss->max_dim;
}
static int ssd_get_bpd(struct sspace *ss)
{
return ss->bpd;
}
/*
Hash the global geometric domain space to 1d index, and map a piece
to each entry in the dht->ent_tab.
*/
static int dht_construct_hash(struct dht *dht, struct sspace *ssd)
{
const unsigned long sn = bbox_volume(&dht->bb_glb_domain) / dht->num_entries;
struct intv *i_tab, intv;
struct dht_entry *de;
unsigned long len;
int num_intv, i, j;
int err = -ENOMEM;
bbox_to_intv(&dht->bb_glb_domain, ssd->max_dim, ssd->bpd, &i_tab, &num_intv);
/*
printf("Global domain decomposes into: ");
for (i = 0; i < num_intv; i++)
printf("{%u,%u} ", i_tab[i].lb, i_tab[i].ub);
printf("\n");
*/
for(i = 0, j = 0; i < dht->num_entries; i++) {
len = sn;
de = dht->ent_tab[i];
de->rank = i;
de->i_tab = malloc(sizeof(struct intv) * num_intv);
if(!de->i_tab)
break;
// printf("Node rank %d interval cut: ", i);
while(len > 0) {
if(intv_size(&i_tab[j]) > len) {
intv.lb = i_tab[j].lb;
intv.ub = intv.lb + len - 1;
i_tab[j].lb += len;
} else {
intv = i_tab[j++];
}
len -= intv_size(&intv);
de->i_tab[de->num_intv++] = intv;
// printf("{%u,%u} ", intv.lb, intv.ub);
}
de->i_virt.lb = de->i_tab[0].lb;
de->i_virt.ub = de->i_tab[de->num_intv - 1].ub;
de->i_tab = realloc(de->i_tab, sizeof(intv) * de->num_intv);
if(!de->i_tab)
break;
printf("\n");
}
free(i_tab);
if(i == dht->num_entries)
return 0;
uloga("'%s()': failed at entry %d.\n", __func__, i);
return err;
}
/*
Public API starts here.
*/
/*
Allocate the shared space structure.
*/
struct sspace *ssd_alloc(struct bbox *bb_domain, int num_nodes, int max_versions)
{
struct sspace *ssd;
// size_t size;
int max_dim, err = -ENOMEM;
// size = sizeof(*ssd); // + sizeof(struct dht_entry) * num_nodes;
ssd = malloc(sizeof(*ssd));
if(!ssd)
goto err_out;
memset(ssd, 0, sizeof(*ssd));
ssd->storage = ls_alloc(max_versions);
if(!ssd->storage) {
free(ssd);
goto err_out;
}
ssd->dht = dht_alloc(ssd, bb_domain, num_nodes, max_versions);
if(!ssd->dht) {
// TODO: free storage
free(ssd->storage);
free(ssd);
goto err_out;
}
max_dim = max(bb_domain->ub.c[0], bb_domain->ub.c[1]);
if(bb_domain->num_dims > 2)
max_dim = max(max_dim, bb_domain->ub.c[2]);
ssd->max_dim = next_pow_2(max_dim);
ssd->bpd = compute_bits(ssd->max_dim);
err = dht_construct_hash(ssd->dht, ssd);
if(err < 0) {
//TODO: do I need a ls_free() routine to clean up the
// objects in the space ?
dht_free(ssd->dht);
free(ssd->storage);
free(ssd);
goto err_out;
}
return ssd;
err_out:
uloga("'%s()': failed with %d\n", __func__, err);
return NULL;
}
void ssd_free(struct sspace *ssd)
{
// int i;
dht_free(ssd->dht);
//TODO: do I need a ls_free() routine ?
free(ssd->storage);
free(ssd);
sh_free();
}
/*
Initialize the dht structure.
*/
int ssd_init(struct sspace *ssd, int rank)
{
// int err = -ENOMEM;
ssd->rank = rank;
ssd->ent_self = ssd->dht->ent_tab[rank];
return 0;
}
/*
Add an object to the local storage.
*/
void ssd_add_obj(struct sspace *ss, struct obj_data *od)
{
int index;
struct list_head *bin;
struct obj_data *od_existing;
od_existing = ls_find_no_version(ss->storage, &od->obj_desc);
if(od_existing) {
od_existing->f_free = 1;
if(od_existing->refcnt == 0) {
ssd_remove(ss, od_existing);
obj_data_free(od_existing);
} else {
uloga("'%s()': object eviction delayed.\n", __func__);
}
}
index = od->obj_desc.version % ss->storage->size_hash;
bin = &ss->storage->obj_hash[index];
/* NOTE: new object comes first in the list. */
list_add(&od->obj_entry, bin);
ss->storage->num_obj++;
}
/*
*/
int ssd_copy(struct obj_data *to_obj, struct obj_data *from_obj)
{
// struct matrix *to_mat, *from_mat;
struct matrix to_mat, from_mat;
struct bbox bbcom;
// int err = -ENOMEM;
bbox_intersect(&to_obj->obj_desc.bb, &from_obj->obj_desc.bb, &bbcom);
matrix_init(&from_mat, from_obj->obj_desc.st, &from_obj->obj_desc.bb, &bbcom, from_obj->data, from_obj->obj_desc.size);
/*
from_mat = matrix_alloc(&from_obj->obj_desc.bb,
&bbcom, from_obj->data, from_obj->obj_desc.size);
if (!from_mat)
goto err_out;
*/
matrix_init(&to_mat, to_obj->obj_desc.st, &to_obj->obj_desc.bb, &bbcom, to_obj->data, to_obj->obj_desc.size);
/*
to_mat = matrix_alloc(&to_obj->obj_desc.bb,
&bbcom, to_obj->data, to_obj->obj_desc.size);
if (!to_mat) {
free(from_mat);
goto err_out;
}
*/
matrix_copy(&to_mat, &from_mat);
/*
matrix_free(to_mat);
matrix_free(from_mat);
*/
return 0;
/*
err_out:
uloga("'%s()': failed with %d.\n", __func__, err);
return err;
*/
}
int ssd_copyv(struct obj_data *obj_dest, struct obj_data *obj_src)
{
struct matrix mat_dest, mat_src;
struct bbox bbcom;
bbox_intersect(&obj_dest->obj_desc.bb, &obj_src->obj_desc.bb, &bbcom);
matrix_init(&mat_dest, obj_dest->obj_desc.st, &obj_dest->obj_desc.bb, &bbcom, obj_dest->data, obj_dest->obj_desc.size);
matrix_init(&mat_src, obj_src->obj_desc.st, &obj_src->obj_desc.bb, &bbcom, obj_src->data, obj_src->obj_desc.size);
matrix_copyv(&mat_dest, &mat_src);
return 0;
}
/*
*/
int ssd_copy_list(struct obj_data *to, struct list_head *od_list)
{
struct obj_data *from;
// struct matrix *mto, *mfrom;
struct matrix to_mat, from_mat;
struct bbox bbcom;
// int err = -ENOMEM;
list_for_each_entry(from, od_list, obj_entry) {
bbox_intersect(&to->obj_desc.bb, &from->obj_desc.bb, &bbcom);
matrix_init(&from_mat, from->obj_desc.st, &from->obj_desc.bb, &bbcom, from->data, from->obj_desc.size);
/*
mfrom = matrix_alloc(&from->obj_desc.bb,
&bbcom, from->data, from->obj_desc.size);
if (!mfrom) {
matrix_free(mto);
goto err_out;
}
*/
matrix_init(&to_mat, to->obj_desc.st, &to->obj_desc.bb, &bbcom, to->data, to->obj_desc.size);
/*
mto = matrix_alloc(&to->obj_desc.bb,
&bbcom, to->data, to->obj_desc.size);
if (!mto)
goto err_out;
*/
matrix_copy(&to_mat, &from_mat);
/*
matrix_free(mto);
matrix_free(mfrom);
*/
}
return 0;
/*
err_out:
uloga("'%s()': failed with %d.\n", __func__, err);
return err;
*/
}
int ssd_filter(struct obj_data *from, struct obj_descriptor *odsc, double *dval)
{
//TODO: search the matrix to find the min
static int n = 1;
*dval = 2.0 * n;
n++;
return 0;
}
struct obj_data *ssd_lookup(struct sspace *ss, char *name)
{
struct obj_data *od;
struct list_head *list;
int i;
for(i = 0; i < ss->storage->size_hash; i++) {
list = &ss->storage->obj_hash[i];
list_for_each_entry(od, list, obj_entry) {
if(strcmp(od->obj_desc.name, name) == 0)
return od;
}
}
return NULL;
}
void ssd_remove(struct sspace *ss, struct obj_data *od)
{
list_del(&od->obj_entry);
ss->storage->num_obj--;
}
void ssd_try_remove_free(struct sspace *ss, struct obj_data *od)
{
/* Note: we assume the object data is allocated with
obj_data_alloc(), i.e., the data follows the structure. */
if(od->refcnt == 0) {
ssd_remove(ss, od);
if(od->data != od + 1) {
uloga("'%s()': we are about to free an object " "with external allocation.\n", __func__);
}
obj_data_free(od);
}
}
/*
Hash a bounding box 'bb' to the hash entries in dht; fill in the
entries in the de_tab and return the number of entries.
*/
int ssd_hash(struct sspace *ss, const struct bbox *bb, struct dht_entry *de_tab[])
{
struct intv *i_tab;
int i, k, n, num_nodes;
num_nodes = sh_find(bb, de_tab);
if(num_nodes > 0)
/* This is great, I hit the cache. */
return num_nodes;
num_nodes = 0;
// bbox_to_intv(bb, ss->max_dim, ss->bpd, &i_tab, &n);
bbox_to_intv2(bb, ss->max_dim, ss->bpd, &i_tab, &n);
for(k = 0; k < ss->dht->num_entries; k++) {
for(i = 0; i < n; i++) {
if(dht_intersect(ss->dht->ent_tab[k], &i_tab[i])) {
de_tab[num_nodes++] = ss->dht->ent_tab[k];
break;
}
}
}
/* Cache the results for later use. */
sh_add(bb, de_tab, num_nodes);
/*
for (i = 0, k = 0; i < n && k < NUM_NODES;) {
if (node_intersect(&node_tab[k], &i_tab[i])) {
n_tab[num_nodes++] = &node_tab[k];
k++;
}
// else if (node_tab[k].i_tab[node_tab[k].num_itv-1].ub < i_tab[i].lb)
else if (node_tab[k].i_virt.ub < i_tab[i].lb ||
node_tab[k].i_virt.lb > i_tab[i].ub)
k++;
else
i++;
}
*/
free(i_tab);
return num_nodes;
}
static inline void ls_inc_num_objects(struct ss_storage *ls)
{
ls->num_obj++;
}
/*
Find an object in the local storage that has the same name and
version with the object descriptor 'odsc'.
*/
struct obj_data *ls_find(struct ss_storage *ls, const struct obj_descriptor *odsc)
{
struct obj_data *od;
struct list_head *list;
int index;
index = odsc->version % ls->size_hash;
list = &ls->obj_hash[index];
list_for_each_entry(od, list, obj_entry) {
if(obj_desc_equals_intersect(odsc, &od->obj_desc))
return od;
}
return NULL;
}
void print_bb(struct ss_storage *ls)
{
struct obj_data *od;
struct list_head *list;
int index;
index = 0 % ls->size_hash;
list = &ls->obj_hash[index];
list_for_each_entry(od, list, obj_entry) {
printf("%s\n",bbox_sprint(&od->obj_desc.bb));
}
return;
}
/*
Search for an object in the local storage that is mapped to the same
bin, and that has the same name and object descriptor, but may have
different version.
*/
struct obj_data *ls_find_no_version(struct ss_storage *ls, struct obj_descriptor *odsc)
{
struct obj_data *od;
struct list_head *list;
int index;
index = odsc->version % ls->size_hash;
list = &ls->obj_hash[index];
list_for_each_entry(od, list, obj_entry) {
if(obj_desc_by_name_intersect(odsc, &od->obj_desc))
return od;
}
return NULL;
}
/*
Test if the 'odsc' matches any object descriptor in a DHT entry by
name and coordinates, but not version, and return the matching index.
*/
static struct obj_desc_list *dht_find_match(const struct dht_entry *de, const struct obj_descriptor *odsc)
{
struct obj_desc_list *odscl;
int n;
// TODO: delete this (just an assertion for proper behaviour).
if(odsc->version == (unsigned int) -1) {
uloga("'%s()': version on object descriptor is not set!!!\n", __func__);
return 0;
}
n = odsc->version % de->odsc_size;
list_for_each_entry(odscl, &de->odsc_hash[n], odsc_entry) {
if(obj_desc_by_name_intersect(odsc, &odscl->odsc))
return odscl;
}
return 0;
}
#define array_resize(a, n) a = realloc(a, sizeof(*a) * (n))
int dht_add_entry(struct dht_entry *de, const struct obj_descriptor *odsc)
{
struct obj_desc_list *odscl;
int n, err = -ENOMEM;
odscl = dht_find_match(de, odsc);
if(odscl) {
/* There is allready a descriptor with a different
version in the DHT, so I will overwrite it. */
memcpy(&odscl->odsc, odsc, sizeof(*odsc));
return 0;
}
n = odsc->version % de->odsc_size;
odscl = malloc(sizeof(*odscl));
if(!odscl)
return err;
memcpy(&odscl->odsc, odsc, sizeof(*odsc));
list_add(&odscl->odsc_entry, &de->odsc_hash[n]);
de->odsc_num++;
return 0;
}
/*
Search the dht entry 'de' for an object that intersects object
descriptor 'odsc' and return a reference to it.
*/
const struct obj_descriptor *dht_find_entry(struct dht_entry *de, const struct obj_descriptor *odsc)
// __attribute__((__unused__))
{
/*
int i;
for (i = 0; i < de->size_objs; i++) {
if (obj_desc_equals_intersect(&de->od_tab[i], odsc))
return &de->od_tab[i];
}
*/
return NULL;
}
/*
Object descriptor 'q_odsc' can intersect multiple object descriptors
from dht entry 'de'; find all descriptor from 'de' and return their
number and references .
*/
int dht_find_entry_all(struct dht_entry *de, struct obj_descriptor *q_odsc, const struct obj_descriptor *odsc_tab[])
{
int n, num_odsc = 0;
struct obj_desc_list *odscl;
n = q_odsc->version % de->odsc_size;
list_for_each_entry(odscl, &de->odsc_hash[n], odsc_entry) {
if(obj_desc_equals_intersect(&odscl->odsc, q_odsc))
odsc_tab[num_odsc++] = &odscl->odsc;
}
return num_odsc;
}
/*
List the available versions of a data object.
*/
int dht_find_versions(struct dht_entry *de, struct obj_descriptor *q_odsc, int odsc_vers[])
{
struct obj_desc_list *odscl;
int i, n = 0;
for(i = 0; i < de->odsc_size; i++) {
list_for_each_entry(odscl, &de->odsc_hash[i], odsc_entry)
if(obj_desc_by_name_intersect(&odscl->odsc, q_odsc)) {
odsc_vers[n++] = odscl->odsc.version;
break; /* Break the list_for_each_entry loop. */
}
}
return n;
}
#define ALIGN_ADDR_QUAD_BYTES(a) \
unsigned long _a = (unsigned long) (a); \
_a = (_a + 7) & ~7; \
(a) = (void *) _a;
/*
Allocate space for an obj_data structure and the data.
*/
struct obj_data *obj_data_alloc(struct obj_descriptor *odsc)
{
struct obj_data *od = 0;
/*
od = malloc(sizeof(*od) + obj_data_size(odsc) + 7);
if (!od)
return NULL;
memset(od, 0, sizeof(*od));
od->data = od + 1;
ALIGN_ADDR_QUAD_BYTES(od->data);
od->obj_desc = *odsc;
*/
od = malloc(sizeof(*od));
if(!od){
return NULL;
}
memset(od, 0, sizeof(*od));
od->_data = od->data = malloc(obj_data_size(odsc) + 7);
if(!od->_data) {
free(od);
return NULL;
}
ALIGN_ADDR_QUAD_BYTES(od->data);
od->obj_desc = *odsc;
return od;
}
/*
Allocate space for obj_data structure and references for data.
*/
struct obj_data *obj_data_allocv(struct obj_descriptor *odsc)
{
struct obj_data *od;
/*
od = malloc(sizeof(*od) + obj_data_sizev(odsc) + 7);
if (!od)
return 0;
memset(od, 0, sizeof(*od));
od->data = od + 1;
ALIGN_ADDR_QUAD_BYTES(od->data);
od->obj_desc = *odsc;
*/
od = malloc(sizeof(*od));
if(!od)
return NULL;
memset(od, 0, sizeof(*od));
od->_data = od->data = malloc(obj_data_sizev(odsc) + 7);
if(!od->_data) {
free(od);
return NULL;
}
ALIGN_ADDR_QUAD_BYTES(od->data);
od->obj_desc = *odsc;
return od;
}
/*
Allocate space for the obj_data struct only; space for data is
externally allocated.
*/
struct obj_data *obj_data_alloc_no_data(struct obj_descriptor *odsc, void *data)
{
struct obj_data *od;
od = malloc(sizeof(*od));
if(!od)
return NULL;
memset(od, 0, sizeof(*od));
od->obj_desc = *odsc;
od->data = data;
return od;
}
struct obj_data *obj_data_alloc_with_data(struct obj_descriptor *odsc, void *data)
{
struct obj_data *od = obj_data_alloc(odsc);
if(!od)
return NULL;
memcpy(od->data, data, obj_data_size(odsc));
//TODO: what about the descriptor ?
return od;
}
void obj_data_free_with_data(struct obj_data *od)
{
if(od->_data) {
uloga("'%s()': explicit data free on descriptor %s.\n", __func__, od->obj_desc.name);
free(od->_data);
} else
free(od->data);
free(od);
}
void obj_data_free(struct obj_data *od)
{
if(od->_data)
free(od->_data);
/*
else
uloga("'%s()': implicit free for descriptor %s with external data\n",
__func__, od->obj_desc.name);
*/
free(od);
}
// size_t obj_data_size(struct obj_data *od)
size_t obj_data_size(struct obj_descriptor *obj_desc)
{
return obj_desc->size * bbox_volume(&obj_desc->bb);
}
size_t obj_data_sizev(struct obj_descriptor * odsc)
{
size_t size = 1; // sizeof(iovec_t);
static int PTL_MAX_IOV = 65535;
if(odsc->bb.num_dims == 2) {
if(odsc->st == row_major)
size = size * bbox_dist(&odsc->bb, bb_y);
else
size = size * bbox_dist(&odsc->bb, bb_x);
} else if(odsc->bb.num_dims == 3) {
size = size * bbox_dist(&odsc->bb, bb_z);
if(odsc->st == row_major)
size = size * bbox_dist(&odsc->bb, bb_y);
else
size = size * bbox_dist(&odsc->bb, bb_x);
}
/* If we exceed the IOVEC portals limit, should fall back on
the copy method. */
if(size > PTL_MAX_IOV)
return (size_t) - 1;
return size;
}
int obj_desc_equals(const struct obj_descriptor *odsc1, const struct obj_descriptor *odsc2)
{
if(odsc1->owner == odsc2->owner && bbox_equals(&odsc1->bb, &odsc2->bb))
return 1;
else
return 0;
}
int obj_desc_equals_no_owner(const struct obj_descriptor *odsc1, const struct obj_descriptor *odsc2)
{
/* Note: object distribution should not change with
version. */
if( // odsc1->version == odsc2->version &&
strcmp(odsc1->name, odsc2->name) == 0 && bbox_equals(&odsc1->bb, &odsc2->bb))
return 1;
return 0;
}
/*
Test if two object descriptors have the same name and versions and
their bounding boxes intersect.
*/
inline int obj_desc_equals_intersect(const struct obj_descriptor *odsc1, const struct obj_descriptor *odsc2)
{
if(strcmp(odsc1->name, odsc2->name) == 0 && odsc1->version == odsc2->version && bbox_does_intersect(&odsc1->bb, &odsc2->bb)){
return 1;
}
return 0;
}
/*
Test if two object descriptors have the same name and their bounding
boxes intersect.
*/
inline int obj_desc_by_name_intersect(const struct obj_descriptor *odsc1, const struct obj_descriptor *odsc2)
{
if(strcmp(odsc1->name, odsc2->name) == 0 && bbox_does_intersect(&odsc1->bb, &odsc2->bb))
return 1;
return 0;
}
/*
int main(void)
{
double *d1 = malloc(sizeof(double) * 100 * 100);
double *d2 = malloc(sizeof(double) * 10 * 10);
struct bbox b1 = {.num_dims = 2, .lb.c = {0, 0, 0}, .ub.c = {99, 99, 0}};
struct bbox b2 = {.num_dims = 2, .lb.c = {3, 3, 0}, .ub.c = {9, 9, 0}};
struct bbox b3;
struct matrix *mat, *matl;
int i, j;
mat = matrix_alloc(&b1, &b2, d1);
matl = matrix_alloc(&b2, &b2, d2);
for (i = 0; i < 100 * 100; i++)
d1[i] = 1.0 * (i + 1);
matrix_copy(matl, mat);
for (i = 0; i < matl->y_dim; i++) {
for (j = 0; j < matl->x_dim; j++)
printf("%8.1f", matl->m[0][i][j]);
printf("\n");
}
return 0;
}
*/
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
#define SIZE 10000
typedef struct node {
int data;
struct node* leftChild;
struct node* rightChild;
struct node* parent;
int height;
} node_t;
// Define the AVL data structure
typedef struct AVL {
node_t* root;
int size;
} AVL_t;
void traverse(node_t* node) {
if (node == NULL) {
printf("Node is null...\n");
return;
}
if (node->leftChild == NULL) { //most left end of tree
printf("%d ", node->data);
if (node->rightChild != NULL) {
traverse(node->rightChild);
}
} else { //there is a left child
traverse(node->leftChild);
printf("%d ", node->data);
if (node->rightChild != NULL) {
traverse(node->rightChild);
}
}
}
void printTree(node_t* node){
printf("The AVL is: ");
traverse(node);
printf("\n");
}
// Create a node
node_t* makeNode(int data) {
//reserve heap space for node
node_t* newNode = (node_t*)malloc(sizeof(node_t));
if (newNode == NULL) {
return NULL;
}
//initial values for the node
newNode->data = data;
newNode->leftChild = NULL;
newNode->rightChild = NULL;
newNode->parent = NULL;
newNode->height = 1;
return newNode;
}
//Create a tree
AVL_t* makeAVL(){
//reserve space for the tree
AVL_t* newTree = (AVL_t*)malloc(sizeof(AVL_t));
if (newTree == NULL) {
return NULL;
}
//initial values for the AVL
newTree->root = NULL;
newTree->size = 0;
return newTree;
}
// Return larger number
int max(int a, int b) {
return (a > b) ? a : b;
}
// Get the height of given node
int height(node_t* node) {
if (node == NULL)
return 0;
return node->height;
}
// Calculate the balance number
int getBalance(node_t* node){
if (node == NULL)
return 0;
return height(node->leftChild) - height(node->rightChild);
}
// Update height of node and it's ancestors
void heightUpdate(node_t* node){
node->height = max(height(node->leftChild), height(node->rightChild)) + 1;
if (node->parent != NULL){
heightUpdate(node->parent);
}
}
/*
RIGHT ROTATION of a given node
X Y
/ -> \
Y X
1. If old_child has a right subtree, assign node as the parent of
the left subtree of old_child.
2. Make old_child as the parent of node.
*/
node_t* rightRotate(node_t* x){
node_t* y = x->leftChild;
node_t* y_right = y->rightChild;
// Make old as new parent of x
y->rightChild = x;
y->parent = x->parent;
x->parent = y;
// Assign old's right to x
x->leftChild = y_right;
if (y_right != NULL)
y_right->parent = x;
// Update height
x->height = max(height(x->leftChild), height(x->rightChild)) + 1;
y->height = max(height(y->leftChild), height(y->rightChild)) + 1;
return y;
}
/*
LEFT ROTATION of a given node
X Y
\ -> /
Y X
1. If y has a left subtree, assign x as the parent of
the left subtree of y.
2. Make y as the parent of node.
*/
node_t* leftRotate(node_t* x){
node_t* y = x->rightChild;
node_t* y_left = y->leftChild;
// Make old_child as the parent of node
y->leftChild = x;
y->parent = x->parent;
x->parent = y;
// Assign node as the parent to old_child's left
x->rightChild = y_left;
if (y_left != NULL)
y_left->parent = x;
// Update height of changed node
x->height = max(height(x->leftChild), height(x->rightChild)) + 1;
y->height = max(height(y->leftChild), height(y->rightChild)) + 1;
return y;
}
// Get the balance index of a given node
int balanceIndex(node_t* node){
if (node == NULL)
return 0;
return height(node->leftChild) - height(node->rightChild);
}
// Insert a node to a tree
void insert(AVL_t* tree, int value){
if (tree == NULL ){
printf("No tree object");
return;
}
node_t* newNode = makeNode(value);
// Insert a node without balancing
if(tree->root == NULL){
tree->root = newNode;
tree->size++;
} else {
bool inserted = false;
node_t* temp = tree->root;
while (inserted == false) {
// If insert value is smaller than node
if (value < temp->data) {
// If node has no left child
// Asign new node as left child
if (temp->leftChild == NULL) {
temp->leftChild = newNode;
newNode->parent = temp;
tree->size++;
inserted = true;
} else {
// Update temp as the left child
// until finds a node without left child
temp = temp->leftChild;
}
} else if (value > temp->data){
// If node has no right child
if (temp->rightChild == NULL){
temp->rightChild = newNode;
newNode->parent = temp;
tree->size++;
inserted = true;
} else {
temp = temp->rightChild;
}
} else {
printf("Value already exists.");
return;
}
}
// Update height
heightUpdate(temp);
// Balance check
while(temp != NULL){
heightUpdate(temp);
int balance = getBalance(temp);
// printf("balance: %d\n", balance);
// printf("temp: %d\n", temp->data);
/*
Situation 1:
Z Y
/ / \
Y Z right rotate -> X Z
/
X
Here, the balance for Z is 2, and new insert X is smaller than Y
*/
if (balance > 1 && value < temp->leftChild->data){
if (temp->parent != NULL){
node_t* temp_parent = temp->parent;
if (temp_parent->data > temp->data){
temp_parent->leftChild = rightRotate(temp);
} else {
temp_parent->rightChild = rightRotate(temp);
}
} else {
rightRotate(temp);
}
}
/*
Situation 2:
Z Z Y
/ / / \
X X left rotate -> Y Z right rotate -> X Z
\ /
Y X
Here, the balance for Z is 2, and new insert Y is larger than X
*/
else if (balance > 1 && value > temp->leftChild->data){
temp->leftChild = leftRotate(temp->leftChild);
if (temp->parent != NULL){
node_t* temp_parent = temp->parent;
if (temp_parent->data > temp->data){
temp_parent->leftChild = rightRotate(temp);
} else {
temp_parent->rightChild = rightRotate(temp);
}
} else {
rightRotate(temp);
}
}
/*
Situation 3:
Symatric to situation 1
Here, the balance for Z is -2, and new insert X is larger than Y
*/
else if (balance < -1 && value > temp->rightChild->data){
if (temp->parent != NULL){
node_t* temp_parent = temp->parent;
if (temp_parent->data > temp->data){
// printf("temp data: %d\n", temp->data);
// printf("temp parent data: %d\n", temp_parent->data);
temp_parent->leftChild = leftRotate(temp);
} else {
temp_parent->rightChild = leftRotate(temp);
}
} else {
leftRotate(temp);
}
}
/*
Situation 4:
Symatric to situation 2
Here, the balance for Z is -2, and new insert X is smaller than Y
*/
else if (balance < -1 && value < temp->rightChild->data){
temp->rightChild = rightRotate(temp->rightChild);
if (temp->parent != NULL){
node_t* temp_parent = temp->parent;
if (temp_parent->data > temp->data){
temp_parent->leftChild = leftRotate(temp);
} else {
temp_parent->rightChild = leftRotate(temp);
}
} else {
leftRotate(temp);
}
}
if (temp->parent == NULL){
tree->root = temp;
}
// Continue to check parent node
temp = temp->parent;
}
}
}
//to find a num in a avl tree
node_t* find(AVL_t* tree, int num) {
//return NULL if the tree does not exist or the tree does not have a root
if (tree == NULL || tree->root == NULL) {
return NULL;
}
//if tree is not NULL
node_t* found = NULL;
node_t* temp = tree->root;
while (found == NULL) { //while the num looking for has not been found yet
if (num == temp->data) {
//if the num looking for equals to the the data of this node
found = temp; //found the node!
} else if (num < temp->data) { //num is smaller than the data in current node(temp)
if (temp->leftChild != NULL) {
temp = temp->leftChild; //move to the left child
} else { //if there is no left child, reach the left end
return found; //still found == NULL
}
} else { //num is bigger than the data in current node(temp)
if (temp->rightChild != NULL) {
temp = temp->rightChild; //move to the right child
} else { //if there is no right child, react the right end
return found; //still found == NULL
}
}
}
//return found: found = the node if it is found, otherwise found is NULL
if (found == NULL) {
printf("%d not found in this tree", num);
}
return found;
}
// // Delete a node to a tree
void delete(AVL_t* tree, int num) {
//if the num to be deleted is not in the avl tree
if (find(tree, num) == NULL) {
printf("Passed in data is not in the AVL Tree!");
return;
}
//if the num to be deleted is in the avl tree
node_t* temp = find(tree, num);
//if the node to be deleted has no child at all
if (temp->leftChild == NULL && temp->rightChild == NULL) {
if (temp->parent != NULL) { //if temp node has a parent
//if the temp node is the left child of its parent:
if (num < temp->parent->data) {
temp->parent->leftChild = NULL;
} else { //else if the temp node is the right child of its parent
temp->parent->rightChild = NULL;
}
}
// if the node to be deleted has a right child, but no left child.
} else if (temp->leftChild == NULL && temp->rightChild != NULL) {
if (temp->parent != NULL) {
if (num < temp->parent->data) { //temp node is the left child of its parents
temp->parent->leftChild = temp->rightChild;
temp->rightChild->parent = temp->parent;
} else { //temp node is the right child of its parents
temp->parent->rightChild = temp->rightChild;
temp->rightChild->parent = temp->parent;
}
}
// if the node to be deleted has a left child, but no right child.
} else if (temp->leftChild != NULL && temp->rightChild == NULL) {
if (temp->parent != NULL) {
if (num < temp->parent->data) { //temp node is the left child of its parents
temp->parent->leftChild = temp->leftChild;
temp->leftChild->parent = temp->parent;
} else { //temp node is the right child of its parents
temp->parent->rightChild = temp->leftChild;
temp->leftChild->parent = temp->parent;
}
}
//if the node to be deleted has both left child and a right child
} else if (temp->leftChild != NULL && temp->rightChild != NULL) {
if (temp->parent != NULL) {
if (num < temp->parent->data) { //temp node is the left child of its parent
node_t* leastBiggerNode = temp->rightChild;
while (leastBiggerNode->leftChild != NULL) {
leastBiggerNode = leastBiggerNode->leftChild;
}
delete(tree, leastBiggerNode->data);
temp->data = leastBiggerNode->data;
} else { //temp node is the right child of its parents
node_t* leastSmallerNode = temp->leftChild;
while (leastSmallerNode ->rightChild != NULL) {
leastSmallerNode = leastSmallerNode->rightChild;
}
delete(tree, leastSmallerNode->data);
temp->data = leastSmallerNode->data;
}
} else { //when the temp node is the root
node_t* leastBiggerNode = temp->rightChild;
while (leastBiggerNode->leftChild != NULL) {
leastBiggerNode = leastBiggerNode->leftChild;
}
delete(tree, leastBiggerNode->data);
temp->data = leastBiggerNode->data;
}
//tree->size--;
}
// Update height
heightUpdate(temp);
// Balance check
while(temp != NULL){
heightUpdate(temp);
int balance = getBalance(temp);
/*
Situation 1: Right Rotate
Z Y
/ / \
Y Z right rotate -> X Z
/
X
Here, the balance for Z is 2, and new insert X is smaller than Y
*/
if (balance > 1 && getBalance(temp->leftChild) >= 0){
if (temp->parent != NULL){
node_t* temp_parent = temp->parent;
// temp_parent->leftChild = rightRotate(temp);
if (temp_parent->data > temp->data){
temp_parent->leftChild = rightRotate(temp);
} else {
temp_parent->rightChild = rightRotate(temp);
}
} else {
rightRotate(temp);
}
}
/*
Situation 2: Left - Right Rotate
Z Z Y
/ / / \
X X left rotate -> Y Z right rotate -> X Z
\ /
Y X
Here, the balance for Z is 2, and new insert Y is larger than X
*/
else if (balance > 1 && getBalance(temp->leftChild) < 0){
temp->leftChild = leftRotate(temp->leftChild);
if (temp->parent != NULL){
node_t* temp_parent = temp->parent;
if (temp_parent->data > temp->data){
temp_parent->leftChild = rightRotate(temp);
} else {
temp_parent->rightChild = rightRotate(temp);
}
} else {
rightRotate(temp);
}
}
/*
Situation 3: Left Rotate
Symatric to situation 1
Here, the balance for Z is -2, and new insert X is larger than Y
*/
else if (balance < -1 && getBalance(temp->rightChild) <= 0){
if (temp->parent != NULL){
node_t* temp_parent = temp->parent;
if (temp_parent->data > temp->data){
temp_parent->leftChild = leftRotate(temp);
} else {
temp_parent->rightChild = leftRotate(temp);
}
} else {
leftRotate(temp);
}
}
/*
Situation 4: Right - Left Rotate
Symatric to situation 2
Here, the balance for Z is -2, and new insert X is smaller than Y
*/
else if (balance < -1 && getBalance(temp->rightChild) > 0){
temp->rightChild = rightRotate(temp->rightChild);
if (temp->parent != NULL){
node_t* temp_parent = temp->parent;
//temp_parent->rightChild = leftRotate(temp);
if (temp_parent->data > temp->data){
temp_parent->leftChild = leftRotate(temp);
} else {
temp_parent->rightChild = leftRotate(temp);
}
} else {
leftRotate(temp);
}
}
if (temp->parent == NULL){
tree->root = temp;
}
// Continue to check parent node
temp = temp->parent;
}
free(temp);
}
void freeTree(node_t* node) {
if (node == NULL) {
return;
}
freeTree(node->leftChild);
freeTree(node->rightChild);
free(node);
}
void freeAVL(AVL_t* tree){
free(tree);
}
//test test used to insert 10000 numbers (from 1 to 10000)
int testInsert1() {
AVL_t* avlTree1 = makeAVL();
clock_t start, end;
double cpu_time_used;
start = clock();
for (int i = 0; i < SIZE; i++) {
insert(avlTree1, i);
}
printTree(avlTree1->root);
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Time used is: %f\n", cpu_time_used);
freeTree(avlTree1->root);
freeAVL(avlTree1);
return 0;
}
//test test used to insert 10000 numbers (from 10000 to 1)
int testInsert2() {
AVL_t* avlTree2 = makeAVL();
clock_t start, end;
double cpu_time_used;
start = clock();
for (int i = SIZE; i > 0; i--) {
insert(avlTree2, i);
}
printTree(avlTree2->root);
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Time used is: %f\n", cpu_time_used);
freeTree(avlTree2->root);
freeAVL(avlTree2);
return 0;
}
//test test used to insert 10000 numbers (random permutation)
int testInsert3() {
//generate random permutation of 10000 numbers, within range of [0,10000]
AVL_t* avlTree3 = makeAVL();
clock_t start, end;
double cpu_time_used;
int array[SIZE];
int i;
for (i = 0; i < SIZE; i ++){
array[i] = i;
}
for (i = SIZE - 1; i > 1; i--) {
int j = rand() % i;
int tmp = array[j];
array[j] = array[i];
array[i] = tmp;
}
start = clock();
for (i = 0; i < SIZE; i ++){
insert(avlTree3, array[i]);
}
printTree(avlTree3->root);
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Time used is: %f\n", cpu_time_used);
freeTree(avlTree3->root);
freeAVL(avlTree3);
return 0;
}
int testSearch() {
AVL_t* avlTree4 = makeAVL();
clock_t start, end;
double cpu_time_used;
int array[SIZE];
int i;
for (i = 0; i < SIZE; i ++){
array[i] = i;
}
for (i = SIZE - 1; i > 1; i--) {
int j = rand() % i;
int tmp = array[j];
array[j] = array[i];
array[i] = tmp;
}
for (i = 0; i < SIZE; i ++){
insert(avlTree4, array[i]);
}
start = clock();
for (int i = 0; i < SIZE; i++) {
find(avlTree4, i);
}
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Time used is: %f\n", cpu_time_used);
freeTree(avlTree4->root);
freeAVL(avlTree4);
return 0;
}
int main(){
printf("\n<AVL Tree> sorting permutation of 1 to 100000...\n");
for (int i = 0; i < 10; i++) {
testInsert1();
}
printf("\n<AVL Tree> sorting permutation of 100000 to 1...\n");
for (int i = 0; i < 10; i++) {
testInsert2();
}
printf("\n<AVL Tree> sorting random permutations of 100000 integers...\n");
for (int i = 0; i < 10; i++) {
testInsert3();
}
printf("\n<AVL Tree> searching random elements for 100000 times...\n");
for (int i = 0; i < 10; i++) {
testSearch();
}
// AVL_t* tree = makeAVL();
// insert(tree, 1);
// insert(tree, 2);
// insert(tree, 3);
// insert(tree, 4);
// insert(tree, 5);
// insert(tree, 6);
// printTree(tree->root);
}
|
C
|
#include <stdio.h>
int main(int argc, const char * argv[]) {
// insert code here...
int banyakJenis, banyakPotong[5], i;
char jenisPotong[5];
// int h_dada = 2500, h_paha = 2000, h_sayap = 1500;
int h_satuan[5];
// int j_harga[5];
int j_bayar = 0;
int pajak = 0;
// table
printf("GEROBAK FRIED CHICKEN\n");
printf("---------------------------------------\n");
printf("Kode Jenis Harga \n");
printf("---------------------------------------\n");
printf(" D Dada Rp. 2500\n");
printf(" P Paha Rp. 2000\n");
printf(" S Sayap Rp. 1500\n");
printf("---------------------------------------\n");
// input banyak jenis
printf("\nBanyak Jenis : "); scanf("%d", &banyakJenis);
printf("\n");
// optimalisasi banyak jenis
while (!scanf("%d", &banyakJenis)) {
printf("Input tidak valid!\n");
printf("ulangi : "); scanf("%d", &banyakJenis);
// flush buffer
while (getchar() != '\n');
}
// input looping
for (i = 0; i < banyakJenis; i++) {
printf("Jenis ke - %d\n", i + 1);
// flush buffer
while (getchar() != '\n');
// input jenis potong
printf("Jenis Potong [D/P/S] : "); scanf("%c", &jenisPotong[i]);
// optimalisasi jenis potong
while ((jenisPotong[i] != 'D') && (jenisPotong[i] != 'P') && (jenisPotong[i] != 'S') && (jenisPotong[i] != 'd') && (jenisPotong[i] != 'p') && (jenisPotong[i] != 's')) {
// flush buffer
while (getchar() != '\n');
printf("\n");
printf("Pilihan input diluar stok!\n");
jenisPotong[i] = '\0';
printf("Jenis Potong [D/P/S] : "); scanf("%c", &jenisPotong[i]);
}
}
printf("\n\n");
return 0;
}
|
C
|
// 6. Faça um algoritmo que determine se um número é divisível ou não por outro.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int firstNumber = 0, secondNumber = 0;
printf("==*== DIVISÍVEL ==*==\n");
printf("Digite o primeiro número: ");
scanf("%d", &firstNumber);
printf("Digite o segundo número: ");
scanf("%d", &secondNumber);
if (firstNumber % secondNumber == 0)
printf("%d é divisível por %d\n", firstNumber, secondNumber);
else
printf("%d não é divisível por %d\n", firstNumber, secondNumber);
return 0;
}
|
C
|
#include <assert.h>
int main() {
int i;
int c;
if(!(c==0 && i==0))
return 0;
while(i<100) {
c=c+i; i=i+1; if (i<=0) break;
}
assert(c>=0);
return 0;
}
|
C
|
#include "format.h"
#include "string.h"
static inline
char digit_to_ascii (uint_fast8_t digit)
{
if (digit < 10)
return digit + '0';
else
return (digit - 10) + 'A';
}
static inline
void creverse (char* begin, char* end)
{
if (begin == end)
return;
--end;
while (begin < end) {
char tmp = *begin;
*begin = *end;
*end = tmp;
++begin;
--end;
}
}
static inline
void divide_by_zero (void)
{
__asm__ ("int $0x00"::);
}
static inline
void divmod (uint64_t (*quotient), uint64_t (*remainder),
uint64_t numerator, uint64_t denominator)
{
if (denominator == 0)
divide_by_zero ();
uint64_t denscale = 1;
while (denominator < numerator) {
denominator <<= 1;
denscale <<= 1;
}
uint64_t _quotient = 0;
while (denscale != 0) {
if (denominator <= numerator) {
numerator -= denominator;
_quotient += denscale;
}
denominator >>= 1;
denscale >>= 1;
}
(*quotient) = _quotient;
(*remainder) = numerator;
}
// Extern functions
char* numsep (char* bufstr, char sep)
{
size_t n = strlen (bufstr);
size_t m = n + (n - 1)/3;
char* src = bufstr + n - 1;
char* dst = bufstr + m - 1;
for (int i = 0; src != dst;) {
if (i == 3) {
i = 0;
*dst = sep;
}
else {
i = i + 1;
*dst = *src;
--src;
}
--dst;
}
bufstr [m] = '\0';
return bufstr;
}
char* format_int (char* buffer, int64_t value, uint_fast8_t mincol, uint_fast8_t base)
{
if (value < 0) {
char* numstring = format_uint (buffer + 1, -value, mincol, base);
--numstring;
numstring [0] = '-';
return numstring;
}
else
return format_uint (buffer, value, mincol, base);
}
char* format_uint (char* buffer, uint64_t value, uint_fast8_t mincol, uint_fast8_t base)
{
char* cursor = buffer;
do {
uint64_t div, mod;
divmod (&div, &mod, value, base);
*cursor = digit_to_ascii (mod);
value = div;
++cursor;
}
while (value != 0);
while (cursor < buffer + mincol)
*cursor++ = '0';
creverse (buffer, cursor);
*cursor = '\0';
return buffer;
}
|
C
|
#include "nemu.h"
/* We use the POSIX regex functions to process regular expressions.
* Type 'man regex' for more information about POSIX regex functions.
*/
#include <sys/types.h>
#include <regex.h>
enum {
NOTYPE = 256,EQ,NEQ,REG,NUM,HEX,ADD,SUB,MUL,DIV,LP,RP,LSHIFT,RSHIFT,EITHER,BOTH,BIG,SMALL,BE,SE,OR,AND,DEREF,MINUS,MOD,XOR,NOT,NEITHER
/* TODO: Add more token types */
};
static struct rule {
char *regex;
int token_type;
} rules[] = {
/* TODO: Add more rules.
* Pay attention to the precedence level of different rules.
*/
{"-", SUB},
{"\\*", MUL},
{"/", DIV},
{"\\(", LP},
{"\\)", RP},
{"0x[0-9a-fA-F]{1,31}", HEX},
{"[0-9]{1,31}", NUM},
{">>", RSHIFT},
{"<<", LSHIFT},
{"\\|\\|", EITHER},
{"&&", BOTH},
{">=", BE},
{"<=", SE},
{">", BIG},
{"<", SMALL},
{"\\|", OR},
{"&", AND},
{"\\$[A-Za-z]{1,7}", REG},
{"!=", NEQ},
{"\\*", DEREF},
{"-", MINUS},
{"%", MOD},
{"\\^", XOR},
{"~", NOT},
{"!", NEITHER},
{" +", NOTYPE}, // spaces
{"\\+",ADD}, // plus
{"==",EQ}, // equal
};
#define NR_REGEX (sizeof(rules) / sizeof(rules[0]) )
static regex_t re[NR_REGEX];
/* Rules are used for many times.
* Therefore we compile them only once before any usage.
*/
void init_regex() {
int i;
char error_msg[128];
int ret;
for(i = 0; i < NR_REGEX; i ++) {
ret = regcomp(&re[i], rules[i].regex, REG_EXTENDED);
if(ret != 0) {
regerror(ret, &re[i], error_msg, 128);
Assert(ret == 0, "regex compilation failed: %s\n%s", error_msg, rules[i].regex);
}
}
}
typedef struct token {
int type;
char str[32];
} Token;
Token tokens[32];
int nr_token;
static bool make_token(char *e) {
int position = 0;
int i,j;
regmatch_t pmatch;
nr_token = 0;
while(e[position] != '\0') {
/* Try all rules one by one. */
for(i = 0; i < NR_REGEX; i ++) {
if(regexec(&re[i], e + position, 1, &pmatch, 0) == 0 && pmatch.rm_so == 0) {
char *substr_start = e + position;
int substr_len = pmatch.rm_eo;
Log("match rules[%d] = \"%s\" at position %d with len %d: %.*s", i, rules[i].regex, position, substr_len, substr_len, substr_start);
position += substr_len;
/* TODO: Now a new token is recognized with rules[i]. Add codes
* to record the token in the array ``tokens''. For certain
* types of tokens, some extra actions should be performed.
*/
switch(rules[i].token_type) {
case NOTYPE :
break ;
case NUM :
nr_token++;
tokens[nr_token].type=NUM;
if(substr_len>32) {
printf("TOO Much Number!\n");
assert(0);
}
for(j=0;j<31&&j<substr_len;j++)
{
tokens[nr_token].str[j]=substr_start[j];
}
tokens[nr_token].str[substr_len]='\0';
break;
case HEX :
nr_token++;
tokens[nr_token].type=HEX;
if(substr_len>32) {
printf("TOO Much Number!\n");
assert(0);
}
for(j=0;j<31&&j+2<substr_len;j++) {
tokens[nr_token].str[j]=substr_start[j+2];
}
tokens[nr_token].str[substr_len]='\0';
break;
case REG :
nr_token++;
tokens[nr_token].type=REG;
if(substr_len>7)
assert(0);
for(j=0;j<31&&j+1<substr_len;j++) {
tokens[nr_token].str[j]=substr_start[j+1];
}
tokens[nr_token].str[substr_len]='\0';
break;
case ADD :
nr_token++;
tokens[nr_token].type=rules[i].token_type;
break;
case SUB :
nr_token++;
tokens[nr_token].type=rules[i].token_type;
break;
case MUL :
nr_token++;
tokens[nr_token].type=MUL;
break;
case DIV :
nr_token++;
tokens[nr_token].type=DIV;
break;
case LP :
nr_token++;
tokens[nr_token].type=LP;
break;
case RP :
nr_token++;
tokens[nr_token].type=RP;
break;
case RSHIFT :
nr_token++;
tokens[nr_token].type=RSHIFT;
break;
case LSHIFT :
nr_token++;
tokens[nr_token].type=LSHIFT;
break;
case EITHER :
nr_token++;
tokens[nr_token].type=EITHER;
break;
case BOTH :
nr_token++;
tokens[nr_token].type=BOTH;
break;
case BE :
nr_token++;
tokens[nr_token].type=BE;
break;
case SE :
nr_token++;
tokens[nr_token].type=SE;
break;
case BIG :
nr_token++;
tokens[nr_token].type=BIG;
break;
case SMALL :
nr_token++;
tokens[nr_token].type=SMALL;
break;
case EQ :
nr_token++;
tokens[nr_token].type=EQ;
break;
case NEQ :
nr_token++;
tokens[nr_token].type=NEQ;
break;
case OR :
nr_token++;
tokens[nr_token].type=OR;
break;
case AND :
nr_token++;
tokens[nr_token].type=AND;
break;
case MOD :
nr_token++;
tokens[nr_token].type=MOD;
break;
case XOR :
nr_token++;
tokens[nr_token].type=XOR;
break;
case NOT :
nr_token++;
tokens[nr_token].type=NOT;
break;
case NEITHER :
nr_token++;
tokens[nr_token].type=NEITHER;
break;
default: panic("please implement me");
}
break;
}
}
if(i == NR_REGEX) {
printf("no match at position %d\n%s\n%*.s^\n", position, e, position, "");
return false;
}
}
return true;
}
int check_parentheses(int p,int q) {
int flag=1,i=p,fi=0;
while(i<=q) {
if(fi==0&&tokens[i].type!=NUM&&tokens[i].type!=HEX&&tokens[i].type!=LP&&tokens[i].type!=RP)
flag=0;
else if(fi<0)
return -1;
if(tokens[i].type==LP) fi++;
else if(tokens[i].type==RP) fi--;
i++;
}
if(fi!=0) return -1;
else {
if(flag==0) return 0;
else if(flag==1) return 1;
}
assert(0);
}
uint32_t chtonum(int p) {
int n=strlen(tokens[p].str),i=0,mo=10,sum=0;
uint32_t res=0;
if(tokens[p].type==NUM) {
mo=10;
for(;i<n;i++)
res=res*mo+tokens[p].str[i]-'0';
}
else if(tokens[p].type==HEX) {
mo=16;
for(;i<n;i++) {
if(tokens[p].str[i]>='a'&&tokens[p].str[i]<='f')
sum=tokens[p].str[i]-'a'+10;
else if(tokens[p].str[i]>='A'&&tokens[p].str[i]<='F')
sum=tokens[p].str[i]-'A'+10;
else sum=tokens[p].str[i]-'0';
res=res*mo+sum;
}
}
else if(tokens[p].type==REG) {
if(strlen(tokens[p].str)==3) {
for(i=0;i<8;i++) {
if(strcmp(tokens[p].str,regsl[i])==0)
return cpu.gpr[i]._32;
}
if(strcmp(tokens[p].str,"eip")==0)
return cpu.eip;
}
}
return res;
}
int op(int p,int q) {
int fi=0,i,op=-1;
int pos1=-1; // last ||
int pos2=-1; // last &&
int pos3=-1; // last |
int pos4=-1; // last ^
int pos5=-1; // last &
int pos6=-1; // last == or !=
int pos7=-1; // last <=, >=,< or >
int pos8=-1; // last <<or >>
int pos9=-1; // last + or -
int pos10=-1; // last /,*,%
for(i=p;i<=q;i++)
{
if(tokens[i].type==LP)
fi++;
else if(tokens[i].type==RP)
fi--;
if(fi==0)
{
if(tokens[i].type==EITHER)
pos1=i;
else if(tokens[i].type==BOTH)
pos2=i;
else if(tokens[i].type==OR)
pos3=i;
else if(tokens[i].type==XOR)
pos4=i;
else if(tokens[i].type==AND)
pos5=i;
else if(tokens[i].type==EQ||tokens[i].type==NEQ)
pos6=i;
else if(tokens[i].type==SE||tokens[i].type==BE||tokens[i].type ==SMALL||tokens[i].type==BIG)
pos7=i;
else if(tokens[i].type==LSHIFT||tokens[i].type==RSHIFT)
pos8=i;
else if(tokens[i].type ==ADD||tokens[i].type==SUB)
pos9=i;
else if(tokens[i].type==MUL||tokens[i].type==DIV||tokens[i].type==MOD)
pos10=i;
}
else if(fi<0)
return -2;
}
if(pos1!=-1) op=pos1 ;
else if(pos2!=-1) op=pos2;
else if(pos3!=-1) op=pos3;
else if(pos4!=-1) op=pos4;
else if(pos5!=-1) op=pos5;
else if(pos6!=-1) op=pos6;
else if(pos7!=-1) op=pos7;
else if(pos8!=-1) op=pos8;
else if(pos9!=-1) op=pos9;
else if(pos10!=-1) op=pos10;
return op;
}
uint32_t eval(int p,int q) {
int opp;
uint32_t end;
if(p>q) {
return 0;
}
else if(p==q) {
return chtonum(p);
}
else if(check_parentheses(p,q)==1) {
return eval(p+1,q-1);
}
else if(check_parentheses(p,q)==0) {
opp=op(p,q);
if(opp==-2)
{
printf("bad expression\n");
assert(0);
}
else if(opp==-1) {
if(tokens[p].type==NOT)
{
sscanf(tokens[q].str,"%x",&end);
return ~end;
}
if(tokens[p].type==NEITHER)
{
sscanf(tokens[q].str,"%x",&end);
return !end;
}
if(tokens[p].type==MINUS)
{
sscanf(tokens[q].str,"%x",&end);
return -end;
}
if(tokens[p].type==DEREF)
{
sscanf(tokens[q].str,"%x",&end);
end=swaddr_read(end,4);
return end;
}
}
uint32_t val1=eval(p,opp-1);
uint32_t val2=eval(opp+1,q);
switch(tokens[opp].type) {
case ADD : return val1+val2;
case SUB : return val1-val2;
case MUL : return val1*val2;
case DIV : return val1/val2;
case RSHIFT : return val1>>val2;
case LSHIFT : return val1<<val2;
case OR : return val1|val2;
case AND : return val1&val2;
case EITHER : return val1||val2;
case BOTH : return val1&&val2;
case BE : return val1>=val2;
case SE : return val1<=val2;
case BIG : return val1>val2;
case SMALL : return val1<val2;
case EQ : return val1==val2;
case NEQ : return val1!=val2;
case MOD : return val1%val2;
case XOR : return val1^val2;
default : assert(0);
}
}
assert(0);
}
uint32_t expr(char *e, bool *success) {
int i;
if(!make_token(e)) {
*success = false;
return 0;
}
for(i=0;i<nr_token;i++) {
if(tokens[i].type==SUB&&(i==0||tokens[i-1].type==ADD||tokens[i-1].type==SUB||tokens[i-1].type==MUL||tokens[i-1].type==DIV||tokens[i-1].type==LP))
tokens[i].type=MINUS;
}
for(i=0;i<nr_token;i++) {
if(tokens[i].type==MUL&&(i==0||(tokens[i-1].type!=RP&&tokens[i-1].type!=HEX&&tokens[i-1].type!=NUM)))
tokens[i].type=DEREF;
}
return eval(1,nr_token);
/* TODO: Insert codes to evaluate the expression. */
//panic("please implement me");
//return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<math.h>
void binary(int b[],int x)
{
int i;
for(i=0;i<4;i++)
b[i]=0;
i=3;
while(x>0)
{
b[i]=x%2;
x=x/2;
i--;
}
}
int add(int p[],int k[],int carry)
{
int x,j;
for(j=3;j>=0;j--)
{
x=p[j];
p[j]=x^k[j]^carry;
if(((x==1)&&(k[j]==1))||((k[j]==1)&&(carry==1))||((carry==1)&&(x==1)))
{
carry=1;
}
else
carry=0;
}
return carry;
}
void rightshift(int x,int *y)
{
int i;
for(i=3;i>0;i--)
y[i]=y[i-1];
y[0]=x;
}
void main()
{
int M,Q,m[4],q[4],i,j,y,c=0,z=0,s=0;
int a[4]={0,0,0,0};
int ans[8];
clrscr();
printf("\n Enter the Multiplicant: ");
scanf("%d",&M);
printf("\n Enter the Multiplier: ");
scanf("%d",&Q);
binary(m,M);
printf("\n\n Binary conversion of Multiplicant %d is: ",M);
for(i=0;i<4;i++)
{
printf("%d",m[i]);
}
binary(q,Q);
printf("\n\n\ Binary conversion of Multiplier %d is: ",Q);
for(i=0;i<4;i++)
{
printf("%d",q[i]);
}
printf("\n\n\n Operation\tCarry \t Accumulator Multiplier \n");
printf("\n INITIAL ");
printf("\t %d",c);
printf("\t\t");
for(i=0;i<4;i++)
{
printf("%d",a[i]);
}
printf("\t\t");
for(i=0;i<4;i++)
{
printf("%d",q[i]);
}
for(j=0;j<4;j++)
{
if(q[3]==1)
{
printf("\n a=a+m\t ");
c=add(a,m,c) ;
printf("\t %d",c);
printf("\t\t");
for(i=0;i<4;i++)
{
printf("%d",a[i]);
}
printf("\t\t");
for(i=0;i<4;i++)
{
printf("%d",q[i]);
}
}
printf("\n Shift \t");
y=a[3];
rightshift(c,a);
rightshift(y,q);
c=0;
printf("\t %d",c);
printf("\t\t");
for(i=0;i<4;i++)
{
printf("%d",a[i]);
}
printf("\t\t");
for(i=0;i<4;i++)
{
printf("%d",q[i]);
}
}
printf("\n\n The answer in binary form is : ");
for(i=0;i<4;i++)
{
ans[i]=a[i];
}
for(i=0;i<4;i++)
{
ans[i+4]=q[i];
}
for(i=0;i<8;i++)
{
printf("%d",ans[i]);
}
printf("\n\n Its decimal form is: ");
for(i=7;i>=0;i--)
{
s=s+(pow (2,z)*ans[i]);
z++;
}
printf("%d",s);
getch();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/*
使用两次二分查找找到第一个和最后一个K
*/
int getFirstK(int* data, int k, int start, int end) {
if (start > end){
return -1;
}
int middleIndex = (start + end) / 2;
int middleData = data[middleIndex];
if (middleData == k) {
if ((middleIndex > 0 && data[middleIndex - 1] != k) || middleIndex == 0) {
return middleIndex;
}
else if (middleIndex > 0 && data[middleIndex - 1] == k) {
end = middleIndex - 1;
}
}
else if (middleData > k) {
end = middleIndex - 1;
}
else {
start = middleIndex + 1;
}
return getFirstK(data, k, start, end);
}
int getLastK(int* data, int k, int start, int end) {
if (start > end) {
return -1;
}
int middleIndex = (start + end) / 2;
int middleData = data[middleIndex];
if (middleData == k) {
if ((middleIndex < end && data[middleIndex + 1] != k) || middleIndex == end) {
return middleIndex;
}
else if (middleIndex < end && data[middleIndex + 1] == k) {
start = middleIndex + 1;
}
}
else if (middleData > k) {
end = middleIndex - 1;
}
else {
start = middleIndex + 1;
}
return getLastK(data, k, start, end);
}
int getNumberOfK(int* data, int k, int length)
{
int number = 0;
if (data != NULL && length > 0) {
int first = getFirstK(data, k, 0, length-1);
int last = getLastK(data, k, 0, length-1);
if (first != -1 && last != -1) {
number = last - first + 1;
}
}
return number;
}
int main() {
int data[] = {1, 2, 3, 3, 3, 3, 4, 5};
int length = sizeof(data) / sizeof(int);
int number = getNumberOfK(data, 3, length);
printf("%d\n", number);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* printf.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: edelangh <edelangh@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/12/03 14:06:26 by edelangh #+# #+# */
/* Updated: 2016/03/25 14:52:16 by edelangh ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
int ft_printf(char *format, ...)
{
va_list ap;
int len;
int res;
int fd;
char *tmp;
ft_static(&fd, (fd = 1) == 2);
va_start(ap, format);
ft_va_get(ap, 0);
if (!format)
return (-1);
tmp = ft_makecolor(&format);
while (*format)
{
len = ft_len_untill(format, '%');
ft_fwrite(format, len);
format += len;
if (*format == '%' && (res = ft_action(format, ap)) == -1)
return (*((int*)ft_static(0, 1)));
else if (*format == '%')
format += res;
}
va_end(ap);
return (*((int*)ft_static(0, 1)) + ft_free(tmp));
}
int ft_dprintf(int fd, char *format, ...)
{
va_list ap;
int len;
int res;
char *tmp;
ft_static(&fd, 0);
va_start(ap, format);
ft_va_get(ap, 0);
if (!format)
return (-1);
tmp = ft_makecolor(&format);
while (*format)
{
len = ft_len_untill(format, '%');
ft_fwrite(format, len);
format += len;
if (*format == '%' && (res = ft_action(format, ap)) == -1)
return (*((int*)ft_static(0, 1)));
else if (*format == '%')
format += res;
}
va_end(ap);
return (*((int*)ft_static(0, 1)) + ft_free(tmp));
}
int ft_sprintf(char *str, char *format, ...)
{
va_list ap;
int len;
int res;
char *tmp;
if (!format)
return (-1);
ft_static(str, 3);
va_start(ap, format);
ft_va_get(ap, 0);
tmp = ft_makecolor(&format);
while (*format)
{
len = ft_len_untill(format, '%');
ft_fwrite(format, len);
format += len;
if (*format == '%')
{
if ((res = ft_action(format, ap)) == -1)
return (*((int*)ft_static(0, 1)));
format += res;
}
}
va_end(ap);
return (*((int*)ft_static(0, 1)) + ft_free(tmp));
}
int ft_asprintf(char **ret, char *format, ...)
{
va_list ap;
int len;
int res;
char *tmp;
if (!format || !ret)
return (-1);
*ret = NULL;
ft_static(ret, 8);
va_start(ap, format);
ft_va_get(ap, 0);
tmp = ft_makecolor(&format);
while (*format)
{
len = ft_len_untill(format, '%');
ft_fwrite(format, len);
format += len;
if (*format == '%' && (res = ft_action(format, ap)) == -1)
return (*((int*)ft_static(0, 1)));
else if (*format == '%')
format += res;
}
va_end(ap);
return (*((int*)ft_static(0, 1)) + ft_free(tmp));
}
int ft_fprintf(FILE *file, char *format, ...)
{
va_list ap;
int len;
int res;
char *tmp;
ft_static(file, 4);
va_start(ap, format);
ft_va_get(ap, 0);
if (!format || !file)
return (-1);
tmp = ft_makecolor(&format);
while (*format)
{
len = ft_len_untill(format, '%');
ft_fwrite(format, len);
format += len;
if (*format == '%')
{
if ((res = ft_action(format, ap)) == -1)
return (*((int*)ft_static(0, 1)));
format += res;
}
}
va_end(ap);
return (*((int*)ft_static(0, 1)) + ft_free(tmp));
}
|
C
|
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct node{
float val;
struct node *next;
}node;
node *start=NULL;
node *create(node *start){
float num;
printf("\nEnter value: ");
scanf("%f",&num);
node *ptr,*new_node;
while(num!=-1){
new_node=(node *)malloc(sizeof(node));
new_node->val=num;
if(start==NULL){
new_node->next=NULL;
start=new_node;
}
else{
ptr=start;
while(ptr->next!=NULL)
ptr=ptr->next;
ptr->next=new_node;
new_node->next=NULL;
}
printf("\nEnter value: ");
scanf("%f",&num);
}
return start;
}
void display(node *start){
node *ptr;
ptr=start;
while(ptr->next!=NULL){
printf("%.2f\t",ptr->val);
ptr=ptr->next;
}
printf("%.2f",ptr->val);
}
void sumnmean(node *start){
node *ptr;
ptr=start;
float sum=0;
while(ptr->next!=NULL){
sum+=ptr->val;
ptr=ptr->next;
}
sum+=ptr->val;
printf("\nSum = %.2f",sum);
int count=0;
ptr=start;
while(ptr->next!=NULL){
count++;
ptr=ptr->next;
}
count++;
float mean=sum/count;
printf("\nMean = %.2f",mean);
}
int main(){
start=create(start);
printf("\nlist is:\n");
display(start);
sumnmean(start);
return 0;
}
|
C
|
#include "libft.h"
int ft_strncmp(const char *s1, const char *s2, size_t n)
{
size_t i;
if (s1 == NULL && s2 == NULL)
return (0);
i = 0;
while (i < n && (i < ft_strlen(s1) || i < ft_strlen(s2)))
{
if (((unsigned char *)s1)[i] != ((unsigned char *)s2)[i])
return (((unsigned char *)s1)[i] - ((unsigned char *)s2)[i]);
else
i++;
}
return (0);
}
|
C
| ERROR: type should be string, got "https://www.codechef.com/CORU2019/problems/ROBRESC/\n\n/* AUTHOR:AKASH JAIN\n* USERNAME:akash19jain \n* DATE:16/03/2019 \n*/\n#include<stdio.h>\n#include<math.h>\n#include<string.h>\n#include<stdlib.h>\n#include<stdbool.h>\n#define mod 1000000007\nint cmp(const void * a,const void * b)\n{\n return (*(int*)b - *(int*)a);\n}\n\nint main()\n{\n long long t;\n scanf(\"%lld\",&t);\n while(t--)\n {\n long long n,p,q,l,r,x,j;\n scanf(\"%lld%lld%lld\",&n,&p,&q);\n long long arr[n],sum=0,i,coins[q],max=0;\n for(i=0;i<n;i++)\n {\n scanf(\"%lld\",&arr[i]);\n sum+=arr[i];\n }\n for(i=0;i<q;i++)\n {\n scanf(\"%lld%lld%lld\",&l,&r,&x);\n long long z=(r-l+1)*x;\n coins[i]=z;\n //printf(\"%lld \",coins[i]);\n }\n qsort(coins,q,sizeof(coins[0]),cmp);\n for(i=0;i<p;i++)\n {\n sum+=coins[i];\n }\n printf(\"%lld\\n\",sum);\n }\n return 0;\n}\n"
|
C
|
// Copyright (c) 2020 Raytheon BBN Technologies, Inc. All Rights Reserved.
//
// This document does not contain technology or Technical Data controlled under either
// the U.S. International Traffic in Arms Regulations or the U.S. Export Administration
//
// Distribution A: Approved for Public Release, Distribution Unlimited
#include "sockaddr.h"
void inet6_to_long(const struct sockaddr_in6* addr, uint64_t* msb, uint64_t* lsb) {
uint64_t m_lsb = 0;
uint64_t m_msb = 0;
for(int i = 0; i < 8; i++) {
m_msb = m_msb << 8;
m_msb |= addr->sin6_addr.s6_addr[i];
}
for(int i = 8; i < 16; i++) {
m_lsb = m_lsb << 8;
m_lsb |= addr->sin6_addr.s6_addr[i];
}
*msb = m_msb;
*lsb = m_lsb;
}
int compare_inet6_sockaddrs(const struct sockaddr_in6* addr_a, const struct sockaddr_in6* addr_b) {
in_port_t port_a = addr_a->sin6_port;
in_port_t port_b = addr_b->sin6_port;
// Check that the ports are equal.
if(port_a != port_b) {
return 0;
}
uint64_t addr_a_msb = 0;
uint64_t addr_a_lsb = 0;
inet6_to_long(addr_a, &addr_a_msb, &addr_a_lsb);
uint64_t addr_b_msb = 0;
uint64_t addr_b_lsb = 0;
inet6_to_long(addr_b, &addr_b_msb, &addr_b_lsb);
// Check if the addresses are equal.
if(addr_a_msb == addr_b_msb && addr_a_lsb == addr_a_lsb) {
return 1;
}
// Check if one of the addresses matches the other.
// FIXME: This is currently hacked to assume null and loopback match everything.
if(addr_a_msb == 0 && addr_a_lsb == 0) {
return 1;
}
if(addr_a_msb == INET6_LOOPBACK_MSB && addr_a_lsb == INET6_LOOPBACK_LSB) {
return 1;
}
if(addr_b_msb == 0 && addr_b_lsb == 0) {
return 1;
}
if(addr_b_msb == INET6_LOOPBACK_MSB && addr_b_lsb == INET6_LOOPBACK_LSB) {
return 1;
}
return 0;
}
int compare_inet_sockaddrs(const struct sockaddr_in* addr_a, const struct sockaddr_in* addr_b) {
in_port_t port_a = addr_a->sin_port;
in_port_t port_b = addr_b->sin_port;
// Check that the ports are equal.
if(port_a != port_b) {
return 0;
}
uint32_t s_addr_a = addr_a->sin_addr.s_addr;
uint32_t s_addr_b = addr_b->sin_addr.s_addr;
// Check if the addresses are equal.
if(s_addr_a == s_addr_b) {
return 1;
}
// Check if one of the addresses matches the other.
// FIXME: This is currently hacked to assume null and loopback match everything.
if(s_addr_a == 0 || s_addr_a == INET_LOOPBACK) {
return 1;
}
if(s_addr_b == 0 || s_addr_b == INET_LOOPBACK) {
return 1;
}
return 0;
}
int compare_sockaddrs(const struct sockaddr* addr_a, const struct sockaddr* addr_b) {
// Extract the family IDs.
sa_family_t family_a = addr_a->sa_family;
sa_family_t family_b = addr_b->sa_family;
// Make sure the structs are compatible
if(family_a != family_b) {
fprintf(stderr, "ABORT: Tried comparing sockaddrs from different families: %d and %d\n", family_a, family_b);
exit(1);
}
//Run the correct subroutine based on the family.
switch(family_a) {
case AF_INET:
return compare_inet_sockaddrs((const struct sockaddr_in *)addr_a, (const struct sockaddr_in *)addr_b);
case AF_INET6:
return compare_inet6_sockaddrs((const struct sockaddr_in6 *)addr_a, (const struct sockaddr_in6 *)addr_b);
default:
fprintf(stderr, "ABORT: Unhandled family: %d\n", family_a);
exit(1);
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* orientate_sprite.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mribouch <mribouch@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/08/10 15:35:48 by mribouch #+# #+# */
/* Updated: 2020/08/10 17:36:36 by mribouch ### ########.fr */
/* */
/* ************************************************************************** */
#include "game/entities/monster_entity.h"
static float diamond_angle(float x, float y)
{
if (y >= 0)
return (x >= 0 ? y / (x + y) : 1 - x / (-x + y));
else
return (x < 0 ? 2 - y / (-x - y) : 3 + x / (x - y));
}
static float angle_gap(float p, float m)
{
float diff;
diff = p - m;
if (diff < 0)
return (diff + 4);
return (diff);
}
static float compute_angle_to_player(t_monster_entity *self)
{
t_vec3f player_pos;
t_vec3f monster_pos;
t_vec3f dir_to_player;
float monster_angle;
float player_angle;
player_pos = self->player_ref->super.transform.position;
monster_pos = self->super.super.transform.position;
dir_to_player = ft_vec3f(player_pos.x - monster_pos.x,
player_pos.y - monster_pos.y, 0);
monster_angle = diamond_angle(self->super.super.transform.direction.x,
self->super.super.transform.direction.y);
player_angle = diamond_angle(dir_to_player.x, dir_to_player.y);
return (angle_gap(player_angle, monster_angle));
}
static int face4(float a)
{
if (a >= 3.5 || a <= 0.5)
return (0);
if (0.5 <= a && a <= 1.5)
return (3);
if (1.5 <= a && a <= 2.5)
return (2);
return (1);
}
int get_orientate_sprite(t_monster_entity *self)
{
float angle;
int index;
angle = compute_angle_to_player(self);
index = face4(angle);
return (index);
}
|
C
|
/* Copyright: (c) 2005 ImmenStar Inc. All Rights Reserved. */
#include "iros_config.h"
#include "plat_common.h"
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <cyg/infra/cyg_type.h>
#include <stddef.h>
#ifdef HAVE_ZTE_SIJIE
extern cs_status epon_request_onu_reset_set(void);
#endif /*END_HAVE_ZTE_SIJIE*/
int cmd_cmp(char *str, const char *mode)
{
if (strlen(str) != strlen(mode))
return 0;
while (*mode) {
if ((*str == '\0') || (*mode != *str))
return 0;
mode++;
str++;
}
return 1;
}
void dumpPkt(char *comment, int port, unsigned char *buffer, int len)
{
int i = 0, j = 0;
if (!buffer || !len)
return;
if (comment)
diag_printf("#%s port 0x%x len 0x%x\n", comment, port, len);
diag_printf("%06x ", j);
for (i = 0; i < len; i++) {
if (i && (i % 16) == 0) {
j += 0x10;
diag_printf(" .\n");
diag_printf("%06x ", j);
}
diag_printf("%02x ", buffer[i]);
}
diag_printf(" .\n");
}
#define SWITCH_GPIO 4
#define UP_LEVEL 1
#define DOWN_LEVEL 0
#define HOLD_TIME 100 //λ:
extern void sdl_switch_hw_reset(void)
{
gpio_mode_t mode_original;
cs_uint8 level_original;
//ȡԭ
cs_gpio_mode_get(SWITCH_GPIO, &mode_original);
cs_gpio_read(SWITCH_GPIO, &level_original);
//оƬ
cs_gpio_mode_set(SWITCH_GPIO, GPIO_OUTPUT);
cs_gpio_write(SWITCH_GPIO, DOWN_LEVEL);
//ʱ
cs_thread_delay(HOLD_TIME);
//оƬϵ
cs_gpio_write(SWITCH_GPIO, UP_LEVEL);
//ָԭ
cs_gpio_write(SWITCH_GPIO, level_original);
cs_gpio_mode_set(SWITCH_GPIO, mode_original);
}
void iros_system_reset(RESET_TYPE_E reset_type)
{
if (reset_type >= RESET_TYPE_MAX)
return;
switch (reset_type) {
case RESET_TYPE_FORCE:
#ifdef HAVE_SWITCH_HW_RESET
sdl_switch_hw_reset();
#endif
#ifdef HAVE_ZTE_SIJIE
epon_request_onu_reset_set();
#endif /*END_HAVE_ZTE_SIJIE*/
HAL_PLATFORM_RESET();
break;
default:
break;
}
}
static int cs_char2int(char c)
{
int digit = 0;
if(c <= '9' && c >= '0')
digit = c - '0';
else if(c <= 'f' && c >= 'a')
digit = c - 'a' + 10;
else
digit = c - 'A' + 10;
return digit;
}
static char cs_int2char(int num)
{
char c = 0;
if(num >= 0 && num <= 9)
c = '0' + num;
else
c = 'a' + num - 10;
return c;
}
int cs_str2mac(char *mac_str , char *mac_addr)
{
char *c = NULL;
int index = 0;
int parse_state = 0;
int char_type = 0; /*0: decimal number 1: Hex Number,lower case 2: hex number, upper case 3:colon type 4:error type*/
int high_bits = 0, low_bits = 0;
if(mac_str == NULL || mac_addr == NULL)
return -1;
c = mac_str;
while(*c != '\0')
{
if(*c <= '9' && *c >= '0')
char_type = 0;
else if(*c <= 'f' && *c >= 'a')
char_type = 1;
else if(*c <= 'F' && *c >= 'A')
char_type = 2;
else if(*c == ':'||*c == '.')
char_type = 3;
else
char_type = 4;
switch(char_type)
{
case 0:
case 1:
case 2:
if(parse_state == 0 || parse_state == 3)
{
high_bits = cs_char2int(*c);
parse_state = 1;
}
else if(parse_state == 1)
{
low_bits = cs_char2int(*c);
parse_state = 2;
}
else
return -1;
if(index >= 6)
return -1;
c++;
if(*c == '\0')
{
if(parse_state == 1)
{
mac_addr[index++] = high_bits;
}
if(parse_state == 2)
{
mac_addr[index++] = (high_bits<<4)+low_bits;
}
}
break;
case 3:
if(parse_state != 1 && parse_state != 2)
return -1;
if(parse_state == 1)
{
mac_addr[index++] = high_bits;
}
if(parse_state == 2)
{
mac_addr[index++] = (high_bits<<4)+low_bits;
}
parse_state = 3;
c++;
break;
default:
return -1;
}
}
if(index != 6)
return -1;
return 0;
}
int cs_str2hex(char *oui_str , char *oui_value , int maxbytes)
{
char *c = NULL;
int index = 0;
int parse_state = 0;
int char_type = 0; /*0: decimal number 1: Hex Number,lower case 2: hex number, upper case 3:colon type 4:error type*/
int high_bits = 0, low_bits = 0;
if(oui_str == NULL || oui_value == NULL)
return -1;
c = oui_str;
while(*c != '\0')
{
if(*c <= '9' && *c >= '0')
char_type = 0;
else if(*c <= 'f' && *c >= 'a')
char_type = 1;
else if(*c <= 'F' && *c >= 'A')
char_type = 2;
else if(*c == ':'||*c == '.')
char_type = 3;
else
char_type = 4;
switch(char_type)
{
case 0:
case 1:
case 2:
if(parse_state == 0 || parse_state == 3)
{
high_bits = cs_char2int(*c);
parse_state = 1;
}
else if(parse_state == 1)
{
low_bits = cs_char2int(*c);
parse_state = 2;
}
else
return -1;
if(index >= maxbytes)
return -1;
c++;
if(*c == '\0')
{
if(parse_state == 1)
{
oui_value[index++] = high_bits;
}
if(parse_state == 2)
{
oui_value[index++] = (high_bits<<4)+low_bits;
}
}
break;
case 3:
if(parse_state != 1 && parse_state != 2)
return -1;
if(parse_state == 1)
{
oui_value[index++] = high_bits;
}
if(parse_state == 2)
{
oui_value[index++] = (high_bits<<4)+low_bits;
}
parse_state = 3;
c++;
break;
default:
return -1;
}
}
if(index != maxbytes)
return -1;
return 0;
}
int cs_mac2str(char *mac_str , char *mac_addr)
{
char digit = 0;
int i;
int index = 0;
if(mac_str == NULL || mac_addr == NULL)
return -1;
for(i = 0 ; i < 6 ; i++)
{
digit = mac_addr[i];
mac_str[index++] = cs_int2char((digit>>4)&0x0F);
mac_str[index++] = cs_int2char(digit&0x0F);
if(i < 5)
mac_str[index++] = ':';
}
mac_str[index] = '\0';
return 0;
}
int cs_str2ip(char *ip_str , unsigned int *ipaddr)
{
char *c = NULL;
int parse_state = 0;
int index = 0;
int ip[4];
if(ip_str == NULL || ipaddr == NULL)
return -1;
c = ip_str;
while(*c != '\0')
{
switch(*c)
{
case '0':
if(parse_state == 0)
return -1;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if(parse_state == 0 || parse_state == 2)
{
ip[index++] = atoi(c);
if(ip[index-1] > 255 || ip[index-1] < 0)
return -1;
}
c++;
parse_state = 1;
break;
case '.':
if(parse_state != 1)
return -1;
c++;
parse_state = 2;
break;
default:
return -1;
}
}
if(parse_state != 1)
return -1;
*ipaddr = (unsigned int)(((ip[0]<<24)&0xFF000000)|((ip[1]<<16)&0xFF0000)|((ip[2]<<8)&0xFF00)|((ip[3]<<0)&0xFF));
return 0;
}
int cs_ip2str(char *ip_str , unsigned int ipaddr)
{
if(ip_str == NULL)
return -1;
sprintf(ip_str , "%d.%d.%d.%d",(ipaddr>>24)&0xFF,
(ipaddr>>16)&0xFF,
(ipaddr>>8)&0xFF,
(ipaddr>>0)&0xFF);
return 0;
}
static int cs_str2dec(char *str , unsigned int *num)
{
char *c = str;
int len = 0;
int parse_status = 0;
unsigned int temp_num = 0;
/******************************************************************
PARSE_STATUS DESC
------------------------------------------------------
0 init status
1 string length is 1, it must be a dec num.
2 a hex-string, header is '0x'.
3 a decimal-string,start with a digit '1-9'
------------------------------------------------------
******************************************************************/
len = strlen(str);
if(len == 0)
{
*num = 0;
return -1;
}
if(len == 1)
parse_status = 1;
while(*c != '\0')
{
switch(*c)
{
case '0':
if(parse_status == 0)
{
c++;
if(*c != 'x') /*str = 01/02/0a/0b/0h/00, but not '0x'*/
{
*num = 0;
return -1;
}
else
{
parse_status = 2;
if(len > 10)/*the max len of a hex-string must less than 10. Eg. '0x12345678'*/
{
*num = 0;
return -1;
}
}
}
else if(parse_status == 1) /*just one byte,and it is '0'.*/
{
*num = 0;
return 0;
}
else if(parse_status == 2)
{
temp_num = temp_num<<4;
}
else if(parse_status == 3)
{
temp_num = 10*temp_num;
}
else
{
*num = 0;
return -1;
}
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if(parse_status == 0)
{
temp_num = *c-'0';
parse_status = 3;
}
else if(parse_status == 1)
{
*num = atoi(str);
return 0;
}
else if(parse_status == 2)
{
temp_num = (temp_num<<4) + *c - '0';
}
else if(parse_status == 3)
{
temp_num = (temp_num*10) + *c - '0';
}
else
{
*num = 0;
return -1;
}
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
if(parse_status == 0 || parse_status == 1 || parse_status == 3)
{
*num = 0;
return -1;
}
if(parse_status == 2)
{
temp_num = (temp_num<<4) + *c - 'a' + 10;
}
else
{
*num = 0;
return -1;
}
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
if(parse_status == 0 || parse_status == 1 || parse_status == 3)
{
*num = 0;
return -1;
}
if(parse_status == 2)
{
temp_num = (temp_num<<4) + *c - 'A' + 10;
}
else
{
*num = 0;
return -1;
}
break;
default:
*num = 0;
return -1;
}
c++;
}
*num = temp_num;
return 0;
}
int cs_isdigit(char c)
{
if(('0' <= c) && (c <= '9'))
return 1;
return 0;
}
int cs_isdigit_str(char *str)
{
char *c = str;
while(*c != '\0')
{
if(!cs_isdigit(*c))
return 0;
}
return 1;
}
int cs_isalpha(char c)
{
if((c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z'))
return 1;
return 0;
}
int cs_atoi(char *str)
{
unsigned int num=0;
if(cs_str2dec(str, &num) != 0)
return 0;
return num;
}
void cs_str2lower(char *str)
{
int len = strlen(str);
int i;
for(i = 0 ; i < len ; i++)
{
if(!cs_isalpha(str[i]))
continue;
if(str[i] >= 'A' && str[i] <= 'Z')
str[i] = str[i]-'A'+'a';
}
return;
}
void cs_str2upper(char *str)
{
int len = strlen(str);
int i;
for(i = 0 ; i < len ; i++)
{
if(!cs_isalpha(str[i]))
continue;
if(str[i] >= 'a' && str[i] <= 'z')
str[i] = str[i]-'a'+'A';
}
return;
}
int cs_strxcmp(char *src , char *dst)
{
if(strlen(src) != strlen(dst))
return 1;
return strcmp(src, dst);
}
int cs_strcmp(char *src , char *dst)
{
return strcmp(src, dst);
}
|
C
|
#ifndef MY_ESCAPE_H
#define MY_ESCAPE_H
#include "myAbstractSyntax.h"
///
/// \brief find and record escapes in the given expression.
/// \param[in] exp the expression inside which to look for.
/// \return this function has no return value.
///
/// \remark after called, variable escape information is holded,
/// call Escape_isVarEscape() to get an available one.
void Escape_findEscape(myExp exp);
///
/// \brief check if the given variable is escaped.
/// \param[in] varName the name of a variable.
/// \return a bool.
///
/// \remark variables inside nested scopes can not be check any more!!
bool Escape_isVarEscaped(mySymbol varName);
///
/// \brief get escape environment which is actually a table.
/// \param this function has no parameters.
/// \return the environment.
///
/// \remark it's a checked runtime error when calling this before
/// any information is entered.
// \note to make code testable, it is necessary.
myTable Escape_getEscapeEnvironment(void);
///
/// \brief set escape environment which is actually a table.
/// \param escapeEnv the environmet to set.
/// \return this function has no return value.
///
/// \remark it's a checked runtime error to pass a NULL environment.
// \note to make code testable, it is necessary.
void Escape_setEscapeEnvironment(myTable escapeEnv);
#endif
|
C
|
#include <intrinsics.h>
#include "indicator.h"
unsigned char number[] =
{
0x3f, //0
0x06, //1
0x5b, //2
0x4f, //3
0x66, //4
0x6d, //5
0x7d, //6
0x07, //7
0x7f, //8
0x6f //9
};
volatile unsigned char data[3];
volatile unsigned char LEDS[];
void IND_Init(void)
{
//, .
PORT_IND = 0xff;
DDR_IND = 0xff;
//, .
PORT_K &= ~((1<<KAT3)|(1<<KAT2)|(1<<KAT1));
DDR_K |= (1<<KAT3)|(1<<KAT2)|(1<<KAT1);
PORT_PLUS = 0xff;
DDR_PLUS = 0xff;
PORT_BASE &= ~((1<<BASE5)|(1<<BASE4)|(1<<BASE3)|(1<<BASE2)|(1<<BASE1));
DDR_BASE |= ((1<<BASE5)|(1<<BASE4)|(1<<BASE3)|(1<<BASE2)|(1<<BASE1));
data[0] = 0;
data[1] = 0;
data[2] = 0;
}
void ioinit(void){
DDRA = 0x3f;
PORTA = 0x00;
}
void output_led_state(unsigned char __led_state_col, unsigned char __led_state_row)
{
SH_CP_row_low();
ST_CP_row_low();
SH_CP_col_low();
ST_CP_col_low();
for(int i = 0; i < 16; i++){
if(bit_is_set(__led_state_row, i))
{
DS_row_high();
DS_row_low();
}
else
DS_row_low();
SH_CP_row_high();
SH_CP_row_low();
if(bit_is_set(__led_state_col, i))
{
DS_col_high();
DS_col_low();
}
else
DS_col_low();
SH_CP_col_high();
SH_CP_col_low();
}
ST_CP_col_high();
ST_CP_row_high();
}
void IND_Conv(unsigned int value)
{
//
unsigned char tmp;
tmp = value % 10;
data[0] = number[tmp];
tmp = value / 10 % 10;
data[1] = number[tmp];
tmp = value / 100;
data[2] = number[tmp];
//
unsigned int x;
unsigned int y;
x = value / 16;
y = value % 16;
output_led_state(_BV(x),_BV(y));
}
void IND_Update(void)
{
//
static unsigned char count = 0;
PORT_K &= ~((1<<KAT3)|(1<<KAT2)|(1<<KAT1));
PORT_IND = data[count];
if (count == 0) PORT_K |= (1<<KAT1);
if (count == 1) PORT_K |= (1<<KAT2);
if (count == 2) PORT_K |= (1<<KAT3);
count++;
if (count == 3) count = 0;
}
|
C
|
/*
ID: wangbn11
LANG: C
TASK: range
*/
/*
* =====================================================================================
*
* Filename: range.c
*
* Description: dp -- caculate the max length one square can make; do from the
* right corner.
*
* Version: 1.0
* Created: 11/26/2012 01:48:58 PM
* Revision: none
* Compiler: gcc
*
* Author: wangbn (nan adair), wangbn15@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
int area[251][251], length[251][251];
int min(int a, int b, int c);
int main()
{
FILE *fin = fopen("range.in", "r");
FILE *fout = fopen("range.out", "w");
int i, j, number, count[251];
fscanf(fin, "%d", &number);
for (i = 0; i < number; i++) {
char buffer[252];
fscanf(fin, "%s", buffer);
for (j = 0; j < number; j++) {
if (buffer[j] == '0')
area[i][j] = 0;
else
area[i][j] = 1;
}
}
for (i = 0; i <= 251; i++)
count[i] = 0;
for (i = 0; i < number; i++)
length[number-1][i] = length[i][number-1] = 1;
for (i = number-2; i >= 0; i--) {
for (j = number-2; j >= 0; j--) {
if (area[i+1][j] == 1 && area[i][j+1] == 1 && area[i+1][j+1] == 1 && area[i][j] == 1)
length[i][j] = min(length[i+1][j], length[i][j+1], length[i+1][j+1]) + 1;
else
length[i][j] = 1;
int k;
for (k = 2; k <= length[i][j]; k++)
count[k]++;
}
}
i = 2;
while (count[i] > 0) {
fprintf(fout, "%d %d\n", i, count[i]);
i++;
}
fclose(fin);
fclose(fout);
}
int min(int a, int b, int c)
{
int d;
d = a > b ? b : a;
d = d > c ? c : d;
return d;
}
|
C
|
#include<stdio.h>
#define INCH 2.54 // 1 inch = 2.54cm
int main(void)
{
float cm;
printf("Enter a height in centimeters:");
scanf("%f",&cm);
while(cm>0)
{
printf("%.1f cm = %d feet, %.1f inches\n",cm,(int)(cm/INCH/12),cm/INCH-(int)(cm/INCH/12)*12);
printf("Enter a height in centimeters(<=0 to quit):");
scanf("%f",&cm);
}
printf("bye\n");
return(0);
}
|
C
|
#include <stdio.h>
int main(){
char txt;
while(1){
scanf("%c",&txt);
if(txt=='\\')break;
else if(txt=='\''||txt=='\"');
else printf("%c",txt);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include"darray_int.h"
void testFunc()
{
darray *myDarr;
int myInt;
int res;
int numOfItems;
AdtStatus tmp;
tmp = darrayCreate(&myDarr,100);
printf("result of create is :%d\n",tmp);
myDarr = darrayAdd(myDarr,8);
myDarr = darrayAdd(myDarr,10);
myDarr = darrayAdd(myDarr,81);
myDarr = darrayAdd(myDarr,82);
darrayDelete(myDarr,&myInt);
print_AD(myDarr);
//res = darrayItemsNum(myDarr,&numOfItems);
//printf("there is numOfItems %d\n",res);
myDarr = darrayAdd(myDarr,2);
darraySort(myDarr, numOfItems);
printf("result after sort \n");
print_AD(myDarr);
darrayDestroy(myDarr);
printf("result after destroy \n");
print_AD(myDarr);
//darrayDelete(myDarr,&myInt);
//printf("%d\n",myInt);
}
int main()
{
testFunc();
return 0;
}
|
C
|
#include "PCA9632.h"
/**
* @brief I2C write
*
* ___________________________________________________________________
* | start | slave_addr + wr_bit + ack | write n bytes + ack | stop |
* --------|---------------------------|----------------------|------|
*
* @param addr slave device adress
* @param data_wr pointer to data buffer
* @param size number of bytes to send
*
* @return
* - ESP_OK Success
* - ESP_ERR_INVALID_ARG Parameter error
* - ESP_FAIL Sending command error, slave doesn't ACK the transfer.
* - ESP_ERR_INVALID_STATE I2C driver not installed or not in master mode.
* - ESP_ERR_TIMEOUT Operation timeout because the bus is busy.
*/
esp_err_t i2c_write(uint8_t addr, uint8_t *data_wr, size_t size)
{
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
i2c_master_write_byte(cmd, (addr << 1) | I2C_MASTER_WRITE, I2C_ACK_CHECK_EN);
i2c_master_write(cmd, data_wr, size, I2C_ACK_CHECK_EN);
i2c_master_stop(cmd);
esp_err_t ret = i2c_master_cmd_begin(I2C_MASTER_NUM, cmd, I2C_TIMEOUT);
i2c_cmd_link_delete(cmd);
return ret;
}
/**
* @brief i2c master initialization
*/
esp_err_t i2c_master_init()
{
i2c_config_t conf;
conf.mode = I2C_MODE_MASTER;
conf.sda_io_num = I2C_MASTER_SDA_IO;
conf.sda_pullup_en = GPIO_PULLUP_ENABLE;
conf.scl_io_num = I2C_MASTER_SCL_IO;
conf.scl_pullup_en = GPIO_PULLUP_ENABLE;
conf.master.clk_speed = I2C_MASTER_FREQ_HZ;
i2c_param_config(I2C_MASTER_NUM, &conf);
return i2c_driver_install(I2C_MASTER_NUM, conf.mode,
I2C_MASTER_RX_BUF_DISABLE,
I2C_MASTER_TX_BUF_DISABLE, 0);
}
void PCA9632_init()
{
uint8_t i2c_tx_buffer[10];
i2c_tx_buffer[0] = 0b10000000; //auto-increment all from beginning
i2c_tx_buffer[1] = 0b00000000; //MODE1 - enable normal mode (should wait 500 us)
i2c_tx_buffer[2] = 0b00100001; //MODE2 - group control blinking
i2c_tx_buffer[3] = 0b00000000; //PWM0 - R
i2c_tx_buffer[4] = 0b00000000; //PWM1 - G
i2c_tx_buffer[5] = 0b00000000; //PWM2 - B
i2c_tx_buffer[6] = 0b00000000; //PWM3 - unused
i2c_tx_buffer[7] = 0b10000000; //GRPPWM
i2c_tx_buffer[8] = 0b00110111; //GRPFREQ - period = (GFRQ[7:0] + 1) / 24 seconds
i2c_tx_buffer[9] = 0b00111111; //LEDOUT - individual mode
ESP_ERROR_CHECK(i2c_write(PCA9632_ADDR, i2c_tx_buffer, sizeof(i2c_tx_buffer) / sizeof(i2c_tx_buffer[0])));
return;
}
/**
* @brief Turn off status LED and put PCA9632 in sleep mode
*/
void PCA9632_off()
{
uint8_t i2c_tx_buffer[2];
i2c_tx_buffer[0] = 0b00001000; //auto-increment off - set LEDOUT
i2c_tx_buffer[1] = 0b00000000; //LEDOUT - all LEDs off
ESP_ERROR_CHECK(i2c_write(PCA9632_ADDR, i2c_tx_buffer, sizeof(i2c_tx_buffer) / sizeof(i2c_tx_buffer[0])));
i2c_tx_buffer[0] = 0b00000000; //auto-increment off - set MODE1
i2c_tx_buffer[1] = 0b00010000; //MODE1 - enter sleep mode
ESP_ERROR_CHECK(i2c_write(PCA9632_ADDR, i2c_tx_buffer, sizeof(i2c_tx_buffer) / sizeof(i2c_tx_buffer[0])));
return;
}
void PCA9632_blink(float duty_cycle, float period)
{
uint8_t grppwm = 255 * duty_cycle;
uint8_t grpfreq = period * 24 - 1;
uint8_t i2c_tx_buffer[3];
i2c_tx_buffer[0] = 0b11000110; //auto-increment for global control registers only
i2c_tx_buffer[1] = grppwm; //GRPPWM
i2c_tx_buffer[2] = grpfreq; //GRPFREQ: period = (GFRQ[7:0] + 1) / 24 seconds
ESP_ERROR_CHECK(i2c_write(PCA9632_ADDR, i2c_tx_buffer, sizeof(i2c_tx_buffer) / sizeof(i2c_tx_buffer[0])));
return;
}
/**
* @brief Set RGB value for status led.
* Values are scaled by the brightness argument
*
* @param r Red value 0-255
* @param g Green value 0-255
* @param b Blue value 0-255
* @param brightness scaling factor 0-1
*
*/
void PCA9632_RGB(uint8_t r, uint8_t g, uint8_t b, float brightness)
{
r *= brightness;
g *= brightness;
b *= brightness;
uint8_t i2c_tx_buffer[4];
i2c_tx_buffer[0] = 0b10100010; //auto-increment for individual brightness registers only, start from PWM0
i2c_tx_buffer[1] = r; //PWM0 - R
i2c_tx_buffer[2] = g; //PWM1 - G
i2c_tx_buffer[3] = b; //PWM2 - B
ESP_ERROR_CHECK(i2c_write(PCA9632_ADDR, i2c_tx_buffer, sizeof(i2c_tx_buffer) / sizeof(i2c_tx_buffer[0])));
return;
}
|
C
|
#include "stdlib.h"
#include "stdio.h"
#include "pthread.h"
#define amount_of_string 4
pthread_key_t global_key;
void* thread(void* tmp);
void add_global_var();
int main() {
pthread_t id_first_thread, id_second_thread, id_third_thread, id_fourth_thread;
pthread_attr_t attribute;
int error_initial = pthread_attr_init(&attribute);
if (error_initial != 0) {
printf("error of pthread_attr_init()\n");
return EXIT_FAILURE;
}
pthread_key_create(&global_key,NULL);
char* string_for_first_thread[] = {"1: hello, i'm first", "1: how are you?", "1: good job, man", "1: bye"};
int error_create_1 = pthread_create(&id_first_thread, &attribute, thread, string_for_first_thread);
if(error_create_1 != 0) {
int error_destroy = pthread_attr_destroy(&attribute);
if(error_destroy != 0) {
printf("error of pthread_create()\n");
printf("error of pthread_attr_destroy()\n");
return EXIT_FAILURE;
}
printf("error of pthread_create()\n");
return EXIT_FAILURE;
}
char* string_for_second_thread[] = {"2: hello, i'm second", "2: i'm fine, thanks", "2: thank you", "2: bye"};
int error_create_2 = pthread_create(&id_second_thread, &attribute, thread, string_for_second_thread);
if(error_create_2 != 0) {
int error_join_1 = pthread_join(id_first_thread, NULL);
if(error_join_1 != 0) {
int error_destroy = pthread_attr_destroy(&attribute);
if(error_destroy != 0) {
printf("error of pthread_create()\n");
printf("error of pthread_join()\n");
printf("error of pthread_attr_destroy()\n");
return EXIT_FAILURE;
}
printf("error of pthread_join()\n");
return EXIT_FAILURE;
}
printf("error of pthread_create()\n");
return EXIT_FAILURE;
}
char* string_for_third_thread[] = {"3: hello, i'm third", "3: heeeey", "3: o-la-la", "3: bye"};
int error_create_3 = pthread_create(&id_third_thread, &attribute, thread, string_for_third_thread);
if(error_create_3 != 0) {
int error_join_1 = pthread_join(id_first_thread, NULL);
if(error_join_1 != 0) {
int error_destroy = pthread_attr_destroy(&attribute);
if(error_destroy != 0) {
printf("error of pthread_create()\n");
printf("error of pthread_join()\n");
printf("error of pthread_attr_destroy()\n");
return EXIT_FAILURE;
}
printf("error of pthread_join()\n");
return EXIT_FAILURE;
}
int error_join_2 = pthread_join(id_second_thread, NULL);
if(error_join_2 != 0) {
int error_destroy = pthread_attr_destroy(&attribute);
if(error_destroy != 0) {
printf("error of pthread_create()\n");
printf("error of pthread_join()\n");
printf("error of pthread_attr_destroy()\n");
return EXIT_FAILURE;
}
printf("error of pthread_join()\n");
return EXIT_FAILURE;
}
printf("error of pthread_create()\n");
return EXIT_FAILURE;
}
char* string_for_fourth_thread[] = {"4: hello, i'm fourth", "4: I forgot everything!", "4: what should I do?", "4: bye"};
int error_create_4 = pthread_create(&id_fourth_thread, &attribute, thread, string_for_fourth_thread);
if(error_create_4 != 0) {
int error_join_1 = pthread_join(id_first_thread, NULL);
if(error_join_1 != 0) {
int error_destroy = pthread_attr_destroy(&attribute);
if(error_destroy != 0) {
printf("error of pthread_create()\n");
printf("error of pthread_join()\n");
printf("error of pthread_attr_destroy()\n");
return EXIT_FAILURE;
}
printf("error of pthread_join()\n");
return EXIT_FAILURE;
}
int error_join_2 = pthread_join(id_second_thread, NULL);
if(error_join_2 != 0) {
int error_destroy = pthread_attr_destroy(&attribute);
if(error_destroy != 0) {
printf("error of pthread_create()\n");
printf("error of pthread_join()\n");
printf("error of pthread_attr_destroy()\n");
return EXIT_FAILURE;
}
printf("error of pthread_join()\n");
return EXIT_FAILURE;
}
int error_join_3 = pthread_join(id_third_thread, NULL);
if(error_join_3 != 0) {
int error_destroy = pthread_attr_destroy(&attribute);
if(error_destroy != 0) {
printf("error of pthread_create()\n");
printf("error of pthread_join()\n");
printf("error of pthread_attr_destroy()\n");
return EXIT_FAILURE;
}
printf("error of pthread_join()\n");
return EXIT_FAILURE;
}
printf("error of pthread_create()\n");
return EXIT_FAILURE;
}
int error_join_1 = pthread_join(id_first_thread, NULL);
int error_join_2 = pthread_join(id_second_thread, NULL);
int error_join_3 = pthread_join(id_third_thread, NULL);
int error_join_4 = pthread_join(id_fourth_thread, NULL);
if(error_join_1 != 0 || error_join_2 != 0 || error_join_3 != 0 || error_join_4 != 0 ) {
printf("error of pthread_join()\n");
int error_destroy = pthread_attr_destroy(&attribute);
if(error_destroy != 0) {
printf("error of pthread_attr_destroy()\n");
return EXIT_FAILURE;
}
return EXIT_FAILURE;
}
pthread_key_delete(global_key);
int error_destroy = pthread_attr_destroy(&attribute);
if(error_destroy != 0) {
printf("error of pthread_attr_destroy()\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
void* thread(void* string_to_print) {
if(NULL == string_to_print) {
printf("error : get NULL pointer\n");
return NULL;
}
int *p = malloc(sizeof(int));
if(NULL == p) {
printf("null pointer in thread()\n");
return NULL;
}
*p = 1;
void * tmp = pthread_getspecific(global_key);
if(NULL == tmp) {
pthread_setspecific(global_key, p);
add_global_var();
pthread_setspecific(global_key, NULL);
free(p);
} else {
printf("pthread_getspecific returned not a NULL\n");
}
for(int i = 0; i < amount_of_string; i++) {
printf("%s\n", ((char**)string_to_print)[i]);
}
printf("\n");
return NULL;
}
void add_global_var() {
int* global_var = pthread_getspecific(global_key);
printf("before modification value is %d\n", *global_var);
*global_var += 1;
printf("after modification value is %d\n", *global_var);
}
|
C
|
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main(){
int n;
scanf("%d",&n);
int a[n];
for(int arr_i = 0; arr_i < n; arr_i++){
scanf("%d",&a[arr_i]);
}
int s,l,v,r;
l=a[0];
for(int t=0;t<n;t++){
if(l<a[t]){l=a[t];}
}
for(int t=0;t<n;t++){
if(l==a[t]){v=t;}
}
a[v]=a[0];
a[0]=l;
/*for(int t=0;t<n;t++){
printf("\t%d",a[t]);
}*/
for(int k=0;a[0]!=0;k++){
r=0;
s=l;
for(int j=0;j<n;j++){
if(a[j]>0){
if(s>a[j]){s=a[j];
//printf("\nthis is small %d",s);
}
}
}
for(int i=0;i<n;i++){
//printf("\nthis is %d of %d",a[i],i);
if(a[i]>0){
a[i]=a[i]-s;
r=r+1;
}
//printf("\nthis is new %d of %d",a[i],i);
}
printf("\n%d",r);
}
return 0;
}
|
C
|
# include <stdio.h>
int main() {
unsigned int a = 60;
unsigned int b = 12;
int c = 0;
c = a&b;
printf("c's value:%d\n",c);
c = a|b;
printf("c's value:%d\n",c);
c = a^b;
printf("c's value:%d\n",c);
c = ~a;
printf("c's value:%d\n",c);
c = a<<2;
printf("c's value:%d\n",c);
c = a>>2;
printf("c's value:%d\n",c);
return 0;
}
|
C
|
#include <stdio.h>
int main(void)
{
int num;
printf("整数を入力してください:");
scanf("%d", &num);
switch(num % 3){
case 0 : puts("その数は3で割り切れます。");
break;
case 1 : puts("その数を3で割った剰余は1です。");
break;
case 2 : puts("その数を3で割った剰余は2です。");
break;
}
return 0;
}
|
C
|
// strcopy1.c - copy using an array iterator.
// compile with: gcc -o strcopy1 strcopy1.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUF_SZ 200
int main(void)
{
char* str = "Be like a headland of rock on \
which the waves break incessantly but it \
stands fast and around it the seething \
of the waters sinks to rest.";
char buffer[BUF_SZ] = "";
int i;
// copy str to buffer, then print buffer
for (i=0; i<strlen(str); i++) {
buffer[i] = str[i];
}
printf("%s\n", buffer);
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Archivo{
char nombre[128];
char tipo;
char usuario[50];
int permiso;
char ruta[1024];
}ARCHIVO;
typedef struct nodo* NODO;
typedef struct nodo* LISTA;
struct nodo {
char elemento;
NODO sig;
};
ARCHIVO arc1;
NODO agregar_elemento (LISTA lista, char elemento);
NODO crear_nodo(char elemento);
void mostrar_lista (LISTA lista);
NODO eliminar_elemento (LISTA lista, char elem);
int main() {
LISTA lista;
strcpy(arc1.nombre,"Miguel");
arc1.tipo='R';
strcpy(arc1.usuario,"marh");
arc1.permiso=644;
strcpy(arc1.ruta,"/home/miguel/");
printf("%s\n",arc1.nombre );
char letra = 'a';
int i=0;
for (i = 0; i < 20; i++) {
printf("Entra\n" );
lista = agregar_elemento (lista, letra + i);
}
mostrar_lista (lista);
printf("================\n");
for (i = 0; i < 5; i++) {
eliminar_elemento (lista, letra + i);
}
agregar_elemento (lista, 'z');
eliminar_elemento (lista, 'n');
mostrar_lista (lista);
return 0;
}
NODO agregar_elemento (LISTA lista, char nuevo) {
NODO tmp = lista;
printf("Entra agregar_elemento\n" );
if (lista == NULL) {
return crear_nodo (nuevo);
}
else {
for (; lista != NULL; lista = lista->sig) {
if (lista->sig == NULL) {
lista->sig = crear_nodo (nuevo);
break;
}
}
lista = tmp;
return lista;
}
}
NODO crear_nodo (char elem) {
NODO tmp;
printf("Entra crear_nodo\n" );
tmp = (NODO ) malloc (sizeof(struct nodo));
tmp->elemento = elem;
tmp->sig = NULL;
return tmp;
}
void mostrar_lista (LISTA lista) {
for (; lista != NULL; lista = lista->sig) {
printf("%c\n", lista->elemento);
}
}
/*
Hay 3 casos:
-> cuando el nodo es el inicial
-> el nodo esta en medio
-> el nodo es el último.
Cuando hace free(lista) elimina el nodo, no toda la lista
*/
NODO eliminar_elemento (LISTA lista, char elem) {
NODO respaldo = lista;
NODO anterior = NULL, siguiente = NULL;
for (; lista != NULL; lista = lista->sig) {
siguiente = lista->sig; // Actualiza siguiente
if (elem == lista->elemento) { // Si es el nodo, lo elimina y ajusta
free (lista);
if (anterior == NULL) { //Inicial
lista = siguiente;
return siguiente;
} else if (siguiente == NULL) { // En medio
anterior->sig = NULL;
return respaldo;
} else { //Al final
anterior->sig = siguiente;
return respaldo;
}
}
anterior = lista; // Actualiza el anterior
}
}
|
C
|
/*
* button.c
*
* Created on: Mar 17, 2021
* Author: Jeff
*/
#include "button.h"
genericSensor_t button_init(GPIO_TypeDef *port, uint16_t pin) {
button_t _btn = {0};
genericSensor_t gBTN = {0};
gBTN.sensorType = GPIO_BUTTON;
gBTN.read = button_read;
gBTN.sensor.button = _btn;
gBTN.interface.PIN.port = port;
gBTN.interface.PIN.pin = pin;
//#ifndef HARDWARE_EMULATOR
gBTN.state = HAL_OK;
//#endif
gBTN.hasUpdate = false;
gBTN.lock = false;
return gBTN;
}
uint8_t button_read(volatile genericSensor_t* sensor) {
bool prevValue = _getBValue(sensor);
bool value = prevValue;
#ifndef HARDWARE_EMULATOR
PIN_t pin = sensor->interface.PIN;
value = HAL_GPIO_ReadPin(pin.port, pin.pin);
if(_getBINV(sensor)) value = !value;
#endif
// Handle Change Flag
if(value != prevValue) _setBChange(sensor);
else _clrBChange(sensor);
// Handle Value Flag;
if(value) _setBValue(sensor);
else _clrBValue(sensor);
if((value != prevValue) && value) _doRToggle(sensor);
if((value != prevValue) && !value) _doFToggle(sensor);
return (uint8_t) value;
}
ButtonState_t button_GetState(volatile genericSensor_t* sensor) {
volatile button_t* btn = &(sensor->sensor.button);
switch(btn->status & _BUTTON_STATE_MASK) {
case 0b00:
return BUTTON_RESET;
break;
case 0b01:
return BUTTON_SET;
break;
case 0b11:
return BUTTON_RISING;
break;
case 0b10:
return BUTTON_FALLING;
break;
default:
return -1;
}
}
void button_Invert(volatile genericSensor_t* sensor) {
_getBINV(sensor) ? _clrBINV(sensor) : _setBINV(sensor);
}
bool button_OnSet(volatile genericSensor_t* sensor) {
return _getBValue(sensor);
}
bool button_OnReset(volatile genericSensor_t* sensor) {
return !_getBValue(sensor);
}
bool button_OnRising(volatile genericSensor_t* sensor) {
return _getBValue(sensor) && _getBChange(sensor);
}
bool button_OnFalling(volatile genericSensor_t* sensor) {
return !_getBValue(sensor) && _getBChange(sensor);
}
bool button_OnRToggle(volatile genericSensor_t* sensor) {
return button_OnRising(sensor) && _getRToggle(sensor);
}
bool button_OnFToggle(volatile genericSensor_t* sensor) {
return button_OnFalling(sensor) && _getFToggle(sensor);
}
// INV
bool _getBINV(volatile genericSensor_t* sensor) {
return EVAL(sensor->sensor.button.status & _BUTTON_INV_MASK);
}
void _setBINV(volatile genericSensor_t* sensor) {
sensor->sensor.button.status |= _BUTTON_INV_MASK;
}
void _clrBINV(volatile genericSensor_t* sensor) {
sensor->sensor.button.status &= INV(_BUTTON_INV_MASK);
}
// Button Rising Toggle
bool _getRToggle(volatile genericSensor_t* sensor) {
return EVAL(sensor->sensor.button.status & _BUTTON_RTOGGLE_MASK);
}
void _setRToggle(volatile genericSensor_t* sensor) {
sensor->sensor.button.status |= _BUTTON_RTOGGLE_MASK;
}
void _clrRToggle(volatile genericSensor_t* sensor) {
sensor->sensor.button.status &= INV(_BUTTON_RTOGGLE_MASK);
}
void _doRToggle(volatile genericSensor_t* sensor) {
(_getRToggle(sensor)) ? (_clrRToggle(sensor)) : (_setRToggle(sensor));
}
// Button Falling Toggle
bool _getFToggle(volatile genericSensor_t* sensor) {
return EVAL(sensor->sensor.button.status & _BUTTON_FTOGGLE_MASK);
}
void _setFToggle(volatile genericSensor_t* sensor) {
sensor->sensor.button.status |= _BUTTON_FTOGGLE_MASK;
}
void _clrFToggle(volatile genericSensor_t* sensor) {
sensor->sensor.button.status &= INV(_BUTTON_FTOGGLE_MASK);
}
void _doFToggle(volatile genericSensor_t* sensor) {
(_getFToggle(sensor)) ? (_clrFToggle(sensor)) : (_setFToggle(sensor));
}
// Button Change
bool _getBChange(volatile genericSensor_t* sensor) {
return EVAL(sensor->sensor.button.status & _BUTTON_CHANGE_MASK);
}
void _setBChange(volatile genericSensor_t* sensor) {
sensor->sensor.button.status |= _BUTTON_CHANGE_MASK;
}
void _clrBChange(volatile genericSensor_t* sensor) {
sensor->sensor.button.status &= INV(_BUTTON_CHANGE_MASK);
}
// Button Value
bool _getBValue(volatile genericSensor_t* sensor) {
return EVAL(sensor->sensor.button.status & _BUTTON_VALUE_MASK);
}
void _setBValue(volatile genericSensor_t* sensor) {
sensor->sensor.button.status |= _BUTTON_VALUE_MASK;
}
void _clrBValue(volatile genericSensor_t* sensor) {
sensor->sensor.button.status &= INV(_BUTTON_VALUE_MASK);
}
uint8_t _getBStatus(volatile genericSensor_t* sensor) {
return sensor->sensor.button.status;
}
|
C
|
#include <stdio.h>
int main()
{
int k, j, p;
for (k = 3; k < 100; k++)
{
p = 0;
for (j = 2; j < k; j++)
{
if ((k % j) == 0)
{
p = 1;
break;
}
}
if (p == 0)
{
printf("%d\n", k);
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "Output.h"
#include "RewriteElement.h"
#include "AddElement.h"
int main(int argc, char *argv[])
{
int answer, N, indx;
printf("Enter the size of array: ");
scanf_s("%d", &N);
int *dynarray = (int*)calloc(N,sizeof(int)); // Allocating memory for array with N number of integer values.
// Block of writing randomized values to dynamic array.
srand(time(0));
printf("Your array is:\n");
for (indx = 0; indx < N; indx++)
{
dynarray[indx] = (rand() % 10 + 1);
printf("%d\t", dynarray[indx]);
}
// Block of rewriting elements.
answer = 1;
while (answer)
{
printf("\nDo you want to rewrite a value at index? (write 0 or 1)\t");
scanf_s("%d", &answer);
if (answer == 0)
break;
RewriteElement(dynarray);
Output(dynarray, N);
}
printf("As you wish :[");
// Block of adding elements.
answer = 1;
while (answer)
{
printf("\nDo you want to add an element? (write 0 or 1)\t");
scanf_s("%d", &answer);
if (answer == 0)
break;
Output(AddElement(dynarray, indx, N), ++N);
}
printf("As you wish :[");
realloc(NULL, dynarray); // Using "realloc" function instead of "free" function.
printf("\n");
system("pause");
return 0;
}
|
C
|
/*
* This file is part of the FDNPKG project
* Copyright (C) Mateusz Viste 2013
*
* Simple test program for the FDNPKG url parser.
*/
#include <stdio.h>
#include "parseurl.h"
int main(int argc, char **argv) {
char host[1024];
char path[1024];
int port;
int proto;
if (argc != 2) {
puts("usage: test-url url");
return(1);
}
proto = parseurl(argv[1], host, &port, path);
printf("Prot: %d\n", proto);
printf("Host: '%s'\n", host);
printf("Port: %d\n", port);
printf("Path: '%s'\n", path);
return(0);
}
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
#include <stdlib.h>
#include "semafory.h"
#include "pamiec.h"
#include "unistd.h"
#include <sys/mman.h>
#define SIZE 41
typedef struct Bufor_Cykliczny
{
int size;
char bufor[SIZE];
} Bufor_Cykliczny;
int rozmiar_pliku(FILE *f) //funkcja obslugujaca plik
{
fseek(f,0,SEEK_END);
int size = ftell(f);
rewind(f);
return size;
}
// funkcja symulujaca opoznienie czasu
void time_delay()
{
int i,j;
for(i=0; i<5000; i++){
for(j=0; j<5000; j++);}
}
int main()
{
// utworzenie/dostep do pamieci dzielonej (odczyt/zapis)
key_t key = ftok("plik",'A');
int shm_id = shmget(key,SIZE,IPC_CREAT|0666);
// utworzenie semafora
sem sem_id = sem_create("plik2",'B',1);
set_val(sem_id,0,1);
Bufor_Cykliczny wpd;
// otwarcie plikow do odczytu/zapisu
FILE *wejscie = fopen("input.txt","r");
FILE *wyjscie = fopen("output.txt","w");
int i=0;//iterator po rozmiarze pliku
int size = rozmiar_pliku(wejscie)+40;
//shmat() dołącza segment pamięci dzielonej Systemu V identyfikowany przez shmid do przestrzeni adresowej procesu, który ją wywołał.
char *control = (char*)(shmat(shm_id, NULL, 0));
char *start = control;
//procesy producenta i konsumenta obsluzone sa w funkcji switch dla argumentu fork()
switch(fork())
{
case -1: perror("Blad funkcji fork \n");
exit(1);
case 0:
while(i<size)
{
fgets(wpd.bufor,40,wejscie);
get_down(sem_id,0);
strcpy(control,wpd.bufor); //kopiuemy do bufora pamieci cyklicznej
get_up(sem_id,0);
printf("Pobrano z pliku 40 znakow, zachowano w pamieci dzielonej\n");
sleep(1);
control =control+ 40;
if(control - start >= SIZE)
control = start;
i =i+ 40;
}
fclose(wejscie);
shmdt((void*)(start));
//shmdt odłącza segment pamięci dzielonej odwzorowany pod adresem podanym w shmaddr z przestrzeni adresowej procesu wywołującego tę funkcję. Przekazany funkcji w parametrze shmaddr adres musi być równy adresowi zwróconemu wcześniej przez wywołanie shmat().
exit(0);
default:
time_delay();
while(i<size)
{
get_down(sem_id,0); //opuszczenie semafora
strcpy(wpd.bufor,control); //kopiujemy do bufora
get_up(sem_id,0); //podniesienie semafora
fputs(wpd.bufor,wyjscie); // z bufora do pliku
printf("Odczytano z pamieci dzielonej 40 znakow, pisano do pliku\n");
sleep(1); //usypiamy
control =control+ 40; //dodajemy do wskaznika 60 znakow
if(control - start >= SIZE)
control = start;
i =i+ 40;
}
fclose(wyjscie);
shmdt((void*)(start));
exit(0);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "Artimatics.h"
#include "Test.h"
#include "Bitwise.h"
#define SQR2(x) (x*x)
inline int SQR(int x)
{
return x*x;
}
int main()
{
int Num1,Num2;
printf("Enter the two numbers\n");
scanf("%d%d",&Num1,&Num2) ;
printf("Result of Sum of %d and %d is %d\n",Num1,Num2,sum(Num1,Num2));
printf("Enter the two numbers\n");
scanf("%d%d",&Num1,&Num2) ;
printf("Result of Sub of %d and %d is %d\n",Num1,Num2,sub(Num1,Num2));
printf("Enter the two numbers\n");
scanf("%d%d",&Num1,&Num2) ;
printf("Result of Mul of %d and %d is %d\n",Num1,Num2,mul(Num1,Num2));
printf("Enter the two numbers\n");
scanf("%d%d",&Num1,&Num2) ;
printf("Result of Div of %d and %d is %d\n",Num1,Num2,Div(Num1,Num2));
printf("Enter the Number to get Factorial\n");
scanf("%d",&Num1) ;
printf("Factorial of %d = %d\n",Num1,Factorial(Num1));
printf("Result of SQR with Marco = %d\n",SQR(7+2)) ;
printf("Result of SQR with Inline = %d\n",SQR2(7+2)) ;
printf("Enter Byte and BitPosition\n");
scanf("%d%d",&Num1,&Num2) ;
printf("Set of bit position %d in Byte %d is %d:\n",Num1,Num2,SetBit(Num1,Num2));
printf("Enter Byte and BitPosition\n");
scanf("%d%d",&Num1,&Num2) ;
printf("Clear of bit position %d in Byte %d is %d:\n",Num1,Num2,ClearBit(Num1,Num2));
printf("Enter Byte and BitPosition\n");
scanf("%d%d",&Num1,&Num2) ;
printf("Toggle of bit position %d in Byte %d is %d:\n",Num1,Num2,ToggleBit(Num1,Num2));
return 0;
}
|
C
|
/*
Author: Abdallah Mahran
Ref: https://leetcode.com/problems/maximum-depth-of-binary-tree/description/
Date: 9/16/2017
*/
// Includes
#include "../common.h"
// Types
// Functions
// solution 1
void dep(TreeNode* node, int *depth, int cd)
{
if(node == NULL)
return;
if(cd == *depth)
*depth++;
dep(node->left, depth, cd+1);
dep(node->right, depth, cd+1);
}
int maxDepth(TreeNode* root)
{
if(root == NULL)
return 0;
int depth = 1;
dep(root, &depth, 0);
return depth;
}
// solution 2
int maxDepth(TreeNode* root) {
if(root == NULL)
return 0;
if(root->left == NULL)
return 1 + maxDepth(root->right);
if(root->right == NULL)
return 1 + maxDepth(root->left);
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
|
C
|
/*
* 问题:让逆波兰运算中支持%运算,注意考虑负数的情况
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h> //主要用于fmod 函数
#include <float.h>
#define MAXOP 100 //最大输入
#define MAXVAL 100 //栈最大空间
#define MAXBUF 100 //存放当前字符
#define NUMBER '0'
int op = 0, bufp = 0;
double val[MAXVAL];
char buf[MAXBUF];
void push(double f);
void ungetch(int c);
double pop(void);
int main(void)
{
int type;
double op2;
char s[MAXVAL];
while((type = getop(s)) != EOF){
switch(type){
case NUMBER:
push(atof(s));
break;
case '+':
push(pop() + pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
break;
case '*':
push(pop() * pop());
break;
case '/':
op2 = pop();
if(op2 != 0.0)
push(pop() / op2);
else
printf("被除数不能为空!\n");
case '%':
op2 = pop();
if(op2 != 0.0)
push(fmod(pop(), op2)); //注意,此时这里不能直接用%运算,因为%不能对double类型进行运算,否则编译失败,如果在gcc编译的时候提示未定义fmod函数,请在gcc编译的时候加-lm 参数
else
printf("被求余不能为空!\n");
break;
case '\n':
printf("结果:%.8g\n", pop());
default:
break;
}
}
return 0;
}
//压栈
void push(double f)
{
if(op < MAXVAL)
val[op++] = f;
else
printf("超出最大值!\n");
}
//出栈
double pop(void)
{
if(op > 0)
return val[--op];
else
printf("栈空!\n");
}
//判断字符类型
int getop(char s[])
{
int i, c;
//获取第一个非空字符
while((s[0] = c = getch()) == ' ' || c == '\t');
s[1] = '\0';
if(!isdigit(c) && c != '.')
return c; //c不是数
//如果是数,获取整个数字
i = 0;
if(isdigit(c))
while(isdigit(s[++i] = c = getch()));
if(c == '.')
while(isdigit(s[++i] = c = getch()));
s[i] = '\0';
if(c != EOF) //将这个字符存起来,不然在使用getchar时,就获取不到这个字符了
ungetch(c);
return NUMBER;
}
int getch(void)
{
return bufp > 0 ? buf[--bufp] : getchar();
}
void ungetch(int c)
{
if(bufp > MAXBUF)
printf("超出最大值!\n");
buf[bufp++] = c;
}
|
C
|
#include <stdio.h>
// as of c11 we are including void since we are not returning anything
// as argument
int main(void)
{
printf("Hey nerds\n");
return 0;
}
|
C
|
//Copyright 2011-2017 Tyler Gilbert; All Rights Reserved
#include "son_local.h"
static int edit_raw_data(son_t * h, const char * key, const void * data, son_size_t size, son_value_t new_data_marker);
int son_edit_float(son_t * h, const char * key, float v){
return edit_raw_data(h, key, &v, sizeof(v), SON_FLOAT);
}
int son_edit_unum(son_t * h, const char * key, u32 v){
return edit_raw_data(h, key, &v, sizeof(v), SON_NUMBER_U32);
}
int son_edit_num(son_t * h, const char * key, s32 v){
return edit_raw_data(h, key, &v, sizeof(v), SON_NUMBER_S32);
}
int son_edit_str(son_t * h, const char * key, const char * v){
return edit_raw_data(h, key, v, strlen(v)+1, SON_STRING);
}
int son_edit_data(son_t * h, const char * key, const void * data, son_size_t size){
return edit_raw_data(h, key, data, size, SON_DATA);
}
int son_edit_bool(son_t * h, const char * key, int v){
size_t pos;
son_store_t store;
son_value_t type;
int read_length;
char buffer[SON_BUFFER_SIZE];
int ret = 0;
if( son_local_verify_checksum(h) < 0 ){ return -1; }
read_length = son_local_read_raw_data(h, key, buffer, SON_BUFFER_SIZE, &store);
if(read_length < 0){
ret = -1;
} else {
if (v == 0){
type = SON_FALSE;
} else {
type = SON_TRUE;
}
son_local_store_set_type(&store, type);
pos = son_local_phy_lseek_current(h, -1*(s32)sizeof(store));
son_local_store_set_next(&store, pos+sizeof(son_store_t));
ret = son_local_store_write(h, &store);
}
son_local_assign_checksum(h);
return ret;
}
int edit_raw_data(son_t * h, const char * key, const void * data, son_size_t size, son_value_t new_data_marker){
son_size_t data_size;
son_store_t son;
int ret;
if( son_local_verify_checksum(h) < 0 ){ return -1; }
if( son_local_store_seek(h, key, &son, &data_size) < 0 ){
ret = -1;
} else {
if( son_local_store_type(&son) != new_data_marker ){
h->err = SON_ERR_EDIT_TYPE_MISMATCH;
ret = -1;
} else {
if( size > data_size ){
size = data_size;
}
ret = son_phy_write(&(h->phy), data, size);
}
}
son_local_assign_checksum(h);
return ret;
}
|
C
|
// Task2:
// Write the swap16, swap32, swap64 functions that swap bytes in
// uint16_t, uint32_t, and uint64_t (endianness conversions)
#include "ProCamp_Task_2_swap.h"
void task2_main_swap()
{
printf("Task 2: swap \n");
printf("Start \n\n");
uint16_t a16_old = 0xA1B2;
uint16_t a16_new = swap16(a16_old);
uint32_t a32_old = 0xA1B2C3D4;
uint32_t a32_new = swap32(a32_old);
uint64_t a64_old = 0xA1B2C3D4E5F60102ULL;
uint64_t a64_new = swap64(a64_old);
printf("uint16_t a16_old = 0x%04X \n", a16_old);
printf("uint16_t a16_new = 0x%04X \n\n", a16_new);
printf("uint32_t a32_old = 0x%08X \n", a32_old);
printf("uint32_t a32_new = 0x%08X \n\n", a32_new);
printf("uint64_t a64_old = 0x%016jX \n", a64_old);
printf("uint64_t a64_new = 0x%016jX \n\n", a64_new);
printf("Task 2: swap \n");
printf("Stop \n\n");
}
uint16_t swap16(uint16_t val)
{
return ((val << 8) | (val >> 8));
}
uint32_t swap32(uint32_t val)
{
val = ((val << 8) & MASK32H8) | ((val >> 8) & MASK32L8);
return (val << 16) | (val >> 16);
}
uint64_t swap64(uint64_t val)
{
val = ((val << 8) & MASK64H8) | ((val >> 8) & MASK64L8);
val = ((val << 16) & MASK64H16) | ((val >> 16) & MASK64L16);
return (val << 32) | (val >> 32);
}
|
C
|
/** Autor: Gabriel Dias **/
/**
* Faa um algoritmo que realize a leitura do saldo de uma conta. Em seguida, o algoritmo
* dever apresentar um menu ao usurio com as seguintes opes:
*
* 1. Exibir saldo;
* 2. Realizar saque;
* 3. Realizar depsito;
*
* -> A opo 1 dever apresentar o saldo digitado pelo usurio;
*
* -> A opo 2 dever simular uma operao de saque da conta. Caso o valor do saque seja
* maior ao saldo do cliente, o programa no dever permitir a realizao da operao;
*
* -> A opo 3 dever simular uma operao de depsito na conta.
*
**/
// Bibliotecas padro
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int main(){
// Configura o idioma de acordo com a localizao
setlocale(LC_ALL, "portuguese");
// Variveis
int opcao;
float saldo, deposito, saque, resto, novo_saldo;
// Processamento
printf("Informe o saldo: ");
scanf("%f", &saldo);
printf("\nEscolha uma opo: \n");
printf("\n1 - Exibir saldo\n");
printf("2 - Realizar saque\n");
printf("3 - Realizar depsito\n");
scanf("%d", &opcao);
switch(opcao){
case 1:
printf("O saldo informado de %.2f: \n", saldo);
break;
case 2:
printf("Informe o valor que deseja sacar: ");
scanf("%f", &saque);
if(saque > saldo){
printf("No possvel realizar essa operao! Seu saldo insuficiente.\n");
}else{
resto = saldo - saque;
printf("Seu saldo atual : %.2f\n", resto);
}
break;
case 3:
printf("Informe o valor que deseja depositar: ");
scanf("%f", &deposito);
novo_saldo = saldo + deposito;
printf("Seu saldo atual : %.2f\n", novo_saldo);
break;
}
system("pause");
}
|
C
|
#ifndef UNIFORMS_H
#define UNIFORMS_H
#include "math/mat4.h"
#include <vulkan/vulkan.h>
#include "graphics/texture.h"
#include <stdint.h>
#define CS_WHOLE_SIZE -1
typedef struct
{
mat4 model;
mat4 view;
mat4 proj;
} TransformType;
typedef struct DescriptorPool DescriptorPool;
// A struct containing an entire descriptor set and data of where it is from
// Contains descriptor sets for all possible frames in flight
typedef struct
{
// The index of the pool
uint32_t pool_index;
// The sum of uniform_count and sampler_count describes the 'size' of the pool it takes
// Represents how many uniform types is allocated
uint32_t uniform_count;
// Represents how many sampler types is allocated
uint32_t sampler_count;
// How many descriptor set it holds
uint32_t count;
VkDescriptorSet sets[3];
} DescriptorPack;
typedef struct UniformBuffer UniformBuffer;
// Creates a descriptor set layout from the specified bindings
// Used when creating descriptors and during pipeline creation
int descriptorlayout_create(VkDescriptorSetLayoutBinding* bindings, uint32_t binding_count, VkDescriptorSetLayout* dst_layout);
// Creates multiple descriptors, one for each frame in flight (swapchain_image_count)
// Writes the buffers and samplers to each frame's descriptor as specified in bindings
// The number of uniformbuffers should match the bindings
// The number of textures should match the bindings
// dst_descriptors should be an array of swapchain_image_count length. Arrays data will be overwritten
int descriptorpack_create(VkDescriptorSetLayout layout, VkDescriptorSetLayoutBinding* bindings, uint32_t binding_count,
UniformBuffer** uniformbuffers, Texture** textures, DescriptorPack* dst_pack);
// Destroys a descriptor pack, and if necessary, destroy the pool
void descriptorpack_destroy(DescriptorPack* pack);
// Creates and allocates memory for a uniform buffer
// Internally holds one buffer per frame in flight to avoid simultaneous read and writes
// Uniform buffer is completely agnostic to the shader layout and binding
// To bind a uniform buffer you need to create a descriptor layout and set
UniformBuffer* ub_create(uint32_t size, uint32_t binding);
// Maps the uniform buffer data for specified frame and returns a pointer to it
// Note: you can not map the same frame simulataneously
void* ub_map(UniformBuffer* ub, uint32_t offset, uint32_t size, uint32_t frame);
// Unmaps a uniform buffer
void ub_unmap(UniformBuffer* ub, uint32_t frame);
// Updates a uniform buffer
// Maps memory from the GPU to the CPU
// If size is -1 or CS_WHOLE_SIZE, the rest of the buffer will be written after offset
// Writes size amount of bytes from data after offset
// The frame specifies which of the internal buffers to map
// If frame is -1, the current frame to render will be used (result of renderer_get_frame)
// NOTE: offset + size should be less than or equal to size of the uniform buffer
void ub_update(UniformBuffer* ub, void* data, uint32_t offset, uint32_t size, uint32_t frame);
void ub_destroy(UniformBuffer* ub);
// Destroys all UniformBuffer pools in the end of the programs
// The pools were first created implicitly when a UniformBuffer was created
void ub_pools_destroy();
#endif
|
C
|
/******************************************************************************
* LibGHT, software to manage point clouds.
* LibGHT is free and open source software provided by the Government of Canada
* Copyright (c) 2012 Natural Resources Canada
*
* Nouri Sabo <nsabo@NRCan.gc.ca>, Natural Resources Canada
* Paul Ramsey <pramsey@opengeo.org>, OpenGeo
*
******************************************************************************/
#include "ght_internal.h"
#include "ght_mem.h"
struct GhtContext_t
{
GhtAllocator alloc;
GhtReallocator realloc;
GhtDeallocator free;
GhtMessageHandler err;
GhtMessageHandler warn;
GhtMessageHandler info;
};
static struct GhtContext_t ght_context;
static void *
default_allocator(size_t size)
{
return malloc(size);
}
static void
default_freeor(void *mem)
{
free(mem);
}
static char *
default_strdup(const char *str)
{
return strdup(str);
}
static void *
default_reallocator(void *mem, size_t size)
{
return realloc(mem, size);
}
static void
default_msg_handler(const char *label, const char *fmt, va_list ap)
{
char newfmt[1024];
memset(newfmt, 0, 1024);
snprintf(newfmt, 1024, "%s%s\n", label, fmt);
newfmt[1023] = '\0';
vfprintf(stderr, newfmt, ap);
}
static void
default_info_handler(const char *fmt, va_list ap)
{
default_msg_handler("INFO: ", fmt, ap);
}
static void
default_warn_handler(const char *fmt, va_list ap)
{
default_msg_handler("WARNING: ", fmt, ap);
}
static void
default_error_handler(const char *fmt, va_list ap)
{
default_msg_handler("ERROR: ", fmt, ap);
va_end(ap);
exit(1);
}
void ght_init(void)
{
ght_context.alloc = default_allocator;
ght_context.realloc = default_reallocator;
ght_context.free = default_freeor;
ght_context.err = default_error_handler;
ght_context.warn = default_warn_handler;
ght_context.info = default_info_handler;
xmlGcMemSetup(
(xmlFreeFunc) ght_free,
(xmlMallocFunc) ght_malloc,
(xmlMallocFunc) ght_malloc,
(xmlReallocFunc) ght_realloc,
(xmlStrdupFunc) ght_strdup
);
}
void ght_set_handlers(GhtAllocator allocator, GhtReallocator reallocator,
GhtDeallocator deallocator, GhtMessageHandler error_handler,
GhtMessageHandler info_handler, GhtMessageHandler warn_handler)
{
ght_context.alloc = allocator;
ght_context.realloc = reallocator;
ght_context.free = deallocator;
ght_context.err = error_handler;
ght_context.warn = warn_handler;
ght_context.info = info_handler;
xmlGcMemSetup(
(xmlFreeFunc) ght_free,
(xmlMallocFunc) ght_malloc,
(xmlMallocFunc) ght_malloc,
(xmlReallocFunc) ght_realloc,
(xmlStrdupFunc) ght_strdup
);
}
void ght_set_allocator(GhtAllocator allocator)
{
ght_context.alloc = allocator;
}
void ght_set_deallocator(GhtDeallocator deallocator)
{
ght_context.free = deallocator;
}
void *
ght_malloc(size_t size)
{
void *mem = ght_context.alloc(size);
if ( ! mem )
{
ght_error("%s: unable to allocate %zu bytes", __func__, size);
return NULL;
}
memset(mem, 0, size); /* Always clean memory */
return mem;
}
char *
ght_strdup(const char *str)
{
size_t len = strlen(str) + 1;
char *newstr = ght_malloc(len);
if ( ! newstr )
{
ght_error("%s: memory allocation failed", __func__);
return NULL;
}
memcpy(newstr, str, len);
return newstr;
}
void *
ght_realloc(void * mem, size_t size)
{
void *newmem = ght_context.realloc(mem, size);
if ( ! newmem )
{
ght_error("%s: unable to reallocate %zu bytes", __func__, size);
return NULL;
}
return newmem;
}
void
ght_free(void * mem)
{
ght_context.free(mem);
}
void
ght_error(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
(*ght_context.err)(fmt, ap);
va_end(ap);
}
void
ght_info(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
(*ght_context.info)(fmt, ap);
va_end(ap);
}
void
ght_warn(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
(*ght_context.warn)(fmt, ap);
va_end(ap);
}
|
C
|
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
/* Copyright (c) 2020
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*/
#ifndef _PROCESS_H_
#define _PROCESS_H_
// TTY_NAME_LEN is the maximum length of the TTY name
#define TTY_NAME_LEN 16
// process_ctx_t Contains all the process context collected for a file system event
struct process_ctx_t
{
// Process data
u64 timestamp;
u32 pid;
u32 tid;
u32 uid;
u32 gid;
char tty_name[TTY_NAME_LEN];
char comm[TASK_COMM_LEN];
};
// fill_process_data fills the provided process_ctx_t with the process context available from eBPF
__attribute__((always_inline)) static u64 fill_process_data(struct process_ctx_t *data)
{
// Process data
struct task_struct *task = (struct task_struct *)bpf_get_current_task();
// TTY
struct signal_struct *signal;
bpf_probe_read(&signal, sizeof(signal), &task->signal);
struct tty_struct *tty;
bpf_probe_read(&tty, sizeof(tty), &signal->tty);
bpf_probe_read_str(data->tty_name, TTY_NAME_LEN, tty->name);
// Comm
bpf_get_current_comm(&data->comm, sizeof(data->comm));
// Pid & Tid
u64 id = bpf_get_current_pid_tgid();
data->pid = id >> 32;
data->tid = id;
// UID & GID
u64 userid = bpf_get_current_uid_gid();
data->uid = userid >> 32;
data->gid = userid;
return id;
}
#endif
|
C
|
/*File name: message.c
*Type: C source file
*Date: 2017/04/24
*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <sys/msg.h>
#include <string.h>
#include "msgdata.h"
void msgreceive(int msginfo_fd)
{
int msgid = -1;
struct message_info_struct msginfo;
long int msgtype = 0;
//Creat the message list
msgid = msgget((key_t)msginfo_fd, 0666|IPC_CREAT);
if(msgid == -1)
{
perror("msgget failed");
printf("PID:%d, Failed to creat the message queue\n", getpid());
exit(EXIT_FAILURE);
}
else
printf("PID:%d, Success to Creat the message queue\n", getpid());
while(1)
{
if(msgrcv(msgid, (void*)&msginfo, MSG_SZ, msgtype, 0) == -1)
{
perror("msgrcv failed");
printf("PID:%d, Failed to receive the message from %d\n", getpid(), msgid);
exit(EXIT_FAILURE);
}
else
printf("PID:%d, Received the message from %d:%s\n", getpid(),msgid, msginfo.text);
sleep(1);
}
if(msgctl(msgid, IPC_RMID, 0) == -1)
{
printf("PID:%d, Failed to delete the message queue %d\n", getpid(), msgid);
exit(EXIT_FAILURE);
}
else
printf("PID:%d, Success to delete the message queue %d\n", getpid(),msgid);
}
void msgsend(int msginfo_fd)
{
int msgid = -1;
struct message_info_struct msginfo;
msginfo.msg_type = 1;
static char Data_WR[MSG_SZ] = {"This is test for message queue"};
//Creat the message list
msgid = msgget((key_t)msginfo_fd, 0666|IPC_CREAT);
if(msgid == -1)
{
perror("msgget failed");
printf("PID:%d, Failed to creat the message queue\n", getpid());
exit(EXIT_FAILURE);
}
else
printf("PID:%d, Success to Creat the message queue\n", getpid());
while(1)
{
printf("PID:%d, Send the date:\n", getpid());
strncpy(msginfo.text, Data_WR, MSG_SZ);
printf("PID:%d, Send the data into msginfo.text:%s\n", getpid(), msginfo.text);
if(msgsnd(msgid, (void*)&msginfo, MSG_SZ, 0) == -1)
{
perror("msgsnd failed");
printf("PID:%d, Failed to send the message to %d\n", getpid(), msgid);
exit(EXIT_FAILURE);
}
else
printf("PID:%d, Success to send the message to %d:%s\n", getpid(),msgid, msginfo.text);
sleep(1);
}
if(msgctl(msgid, IPC_RMID, 0) == -1)
{
printf("PID:%d, Failed to delete the message queue %d\n", getpid(), msgid);
exit(EXIT_FAILURE);
}
else
printf("PID:%d, Success to delete the message queue %d\n", getpid(),msgid);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <curl/curl.h>
#include "get_url.c"
#define maxitem 100 //max item digits
#define MAX_TITLE 1000
#define MAX_LINK 10000
#define MAX_DATE 100
#define MAX_DES 100000
#define MAX_CAT 1000
#define MAXN_CAT 20
#define maxchar 1000000
typedef struct NewsStruct News;
struct NewsStruct
{
char title[MAX_TITLE];
char link[MAX_LINK];
char pubDate[MAX_DATE];
char description[MAX_DES];
char category[MAXN_CAT][MAX_CAT];
int catNum;
};
void News_to_Trie(News* object, int request);
void JsonFormatPoster(News* object);
void postNews(char jsonstr[]);
void write_category(News* object, int catName);
//***************************************
bool cmp(char* str1, char* str2, int a) //str1 from a to b ?= str2
{
int i;
int len = strlen(str2);
for (i = 0; i < len; i++)
if (str1[i + a] != str2[i])
return false;
return true;
}
void copy(char* str1, char* str2, int a, int b) //copy str1 from str1[a] to str1[b] to str2
{
int i;
for (i = a; i < b; i++)
{
if(str1[i] == '\n' || str1[i] == '\t')
str2[i - a] = ' ';
else
str2[i - a] = str1[i];
}
str2[i] = '\0';
}
FILE* get_item(FILE * item, int request)
{
News* news;
news = (News*)calloc(1, sizeof(News));
int step = 1;
char str[maxchar] = {'\0'};
char tempstr[maxchar] = {'\0'};
news -> catNum = 0;
while(step < 5)
{
fgets(str, maxchar, item);
//strcpy(tempstr, "\0");
char tempstr[maxchar] = {'\0'};
int i, len = strlen(str);
for(i = 0; i < len; i++)
{
if (str[i] == '<')
{
if (step == 1 && cmp(str, "title", i + 1))
{
int j = i + 1;
while (str[j] != '<')
j++;
copy(str, news -> title, i + 7, j);
//printf("title : %s\n", news -> title);
step++;
break;
}
else if (step == 2 && cmp(str, "link", i + 1))
{
int j = i + 6;
if(str[j] == '\0' || str[j + 1] == '\0')
{
fgets(tempstr, maxchar, item);
for(i = 0; i < strlen(tempstr); i++)
{
if(tempstr[i] == 'h')
{
break;
}
}
copy(tempstr, news -> link, i, strlen(tempstr));
}
else
{
while (str[j] != '<' && str[j] != '\0')
j++;
copy(str, news -> link, i + 6, j);
}
step++;
//printf("link : %s\n", news -> link);
break;
}
else if (step == 3 && cmp(str, "pubDate", i + 1))
{
int j = i + 1;
while (str[j] != '<')
j++;
copy(str, news -> pubDate, i + 9, j);
//printf("pubDate : %s\n", news -> pubDate);
step++;
break;
}
else if (step == 4 && cmp(str, "category>", i + 1))
{
int j = i + 10;
if(str[j] == '\0' || str[j + 1] == '\0' || str[j + 2] == '\0')
{
fgets(tempstr, maxchar, item);
for(i = 0; i < strlen(tempstr); i++)
{
if(tempstr[i] == 'T')
{
break;
}
}
copy(tempstr, news -> category[news -> catNum], i + 4, strlen(tempstr) - 5);
}
else
{
while (str[j] != ']')
j++;
copy(str, news -> category[news -> catNum], i + 19, j);
}
//printf("category : %s\n", news -> category[news -> catNum]);
news -> catNum++;
break;
}
else if (step == 4 && cmp(str, "description>", i + 1))
{
int j = i + 13;
if(str[j] == '\0' || str[j + 1] == '\0' || str[j + 2] == '\0')
{
fgets(tempstr, maxchar, item);
fgets(tempstr, maxchar, item);
i = 0;
while ((tempstr[i] < 'a' || tempstr[i] > 'z') && (tempstr[i] < 'A' || tempstr[i] > 'Z') && (tempstr[i] < '0' || tempstr[i] > '9'))
i++;
copy(tempstr, news -> description, i, strlen(tempstr));
if(news -> description[strlen(news -> description) - 1] == '\n')
news -> description[strlen(news -> description) - 1] = '\0';
}
else
{
while (str[j] != ']')
j++;
//MODIFY DESCRIPTION
int k; //counter -> 0 to len
int c = 0; //counter : news -> description length
bool inTag = false;
int len = strlen(str);
for (k = 24; k < len - 2; k++)
{
if (str[k] == '<')
{
inTag = true;
continue;
}
if (str[k] == '>')
{
inTag = false;
continue;
}
if (!inTag && str[k] != ']')
{
news -> description[c] = str[k];
c++;
}
}
news -> description[c] = '\0';
}
//printf("description : %s\n", news -> description);
step++;
break;
}
}
}
}
if(request == 1)
{
//struct to JSON format
JsonFormatPoster(news);
}
else if(request == 2 || request == 3 || request == 4)
{
//if(request == 3)
//printf("request sent!\n");
News_to_Trie(news, request);
}
// else if(request == 4)
// {
// f(news);
// }
free(news);
return item;
}
void RSS_Processor(char fileName[], int request)
{
//printf("RSS_Processor\n");
FILE * rss;
rss = fopen(fileName, "r");
char str[maxchar];
printf("FILE NAME %s\n", fileName);
while (fgets(str, maxchar, rss) != NULL)
{
int i, len = strlen(str);
for (i = 0; i < len; i++)
{
if (str[i] == '<')
if (cmp(str, "item", i + 1))
{
rss = get_item(rss, request);
break;
}
}
}
fclose(rss);
}
void postNews(char jsonstr[])
{
curl_global_init( CURL_GLOBAL_ALL );
CURL *myHandle;
CURLcode result;
myHandle = curl_easy_init ( ) ;
struct curl_slist *headers = NULL;
//headers
headers = curl_slist_append(headers, "X-Requested-With: XMLHttpRequest");
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "charsets: utf-8");
//posting
curl_easy_setopt(myHandle, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(myHandle, CURLOPT_URL, "http://team46:pkz1376hmd1377@www.fop-project.ir/news");
curl_easy_setopt(myHandle, CURLOPT_POSTFIELDS, jsonstr);
result = curl_easy_perform( myHandle );
printf("sent\n");
curl_easy_cleanup( myHandle );
}
void JsonFormatPoster(News* object)
{
char jsonstr[maxchar];
int i = 0;
strcpy(jsonstr, "{");
strcat(jsonstr, "\"title\":\"");
strcat(jsonstr, object -> title);
strcat(jsonstr, "\",");
strcat(jsonstr, "\"date\":\"");
strcat(jsonstr, object -> pubDate);
strcat(jsonstr, "\",");
strcat(jsonstr, "\"description\":\"");
strcat(jsonstr, object -> description);
strcat(jsonstr, "\",");
strcat(jsonstr, "\"categorized\":");
strcat(jsonstr, "false,");
strcat(jsonstr, "\"categories\":[");
for(i = 0; i < object -> catNum; i++)
{
strcat(jsonstr, "\"");
strcat(jsonstr, object -> category[i]);
strcat(jsonstr,"\"");
if(i < (object -> catNum - 1) )
strcat(jsonstr, ", ");
}
strcat(jsonstr, "]");
strcat(jsonstr, "}");
printf("%s\n", jsonstr);
// int c = 1, d = 1;
// for ( c = 1 ; c <= 32767 ; c++ )
// for ( d = 1 ; d <= 32767 ; d++ )
// {}
// curl_global_init( CURL_GLOBAL_ALL );
// printf("sent299\n");
// CURL *myHandle;
// printf("sent301\n");
// CURLcode result;
// printf("sent303\n");
// myHandle = curl_easy_init ( ) ;
// printf("sent305\n");
// struct curl_slist *headers = NULL;
// printf("sent307\n");
// //headers
// headers = curl_slist_append(headers, "X-Requested-With: XMLHttpRequest");
// printf("sent310\n");
// headers = curl_slist_append(headers, "Content-Type: application/json");
// printf("sent312\n");
// headers = curl_slist_append(headers, "charsets: utf-8");
// printf("sent314\n");
// //posting
// curl_easy_setopt(myHandle, CURLOPT_HTTPHEADER, headers);
// printf("sent317\n");
// curl_easy_setopt(myHandle, CURLOPT_URL, "http://team46:pkz1376hmd1377@www.fop-project.ir/news");
// printf("sent319\n");
// curl_easy_setopt(myHandle, CURLOPT_POSTFIELDS, jsonstr);
// printf("sent321\n");
// result = curl_easy_perform( myHandle );
// printf("sent324\n");
// curl_easy_cleanup( myHandle );
// printf("sent326\n");
//postNews(jsonstr);
}
void write_category(News* object, int cat)
{
strcpy(object -> category[0], "\0");
if(cat == 1)
strcpy(object -> category[0], "sport");
if(cat == 2)
strcpy(object -> category[0], "business");
if(cat == 3)
strcpy(object -> category[0], "entertainment");
if(cat == 4)
strcpy(object -> category[0], "us");
if(cat == 5)
strcpy(object -> category[0], "world");
if(cat == 6)
strcpy(object -> category[0], "health");
if(cat == 7)
strcpy(object -> category[0], "sci_tech");
object -> catNum = 1;
JsonFormatPoster(object);
}
|
C
|
#include <stdio.h>
#include <string.h>
int main() {
int test;
scanf("%d", &test);
while (test--) {
int input[85][2] = { 0, }, check[85] = { 0, }, result[85] = { 0, };
char a[85] = { 0, }, b[85] = { 0, };
scanf("%s %s", &a, &b);
for (int i = 0; i < strlen(a); i++) {
input[i][0] = a[(strlen(a) - 1) - i] - '0';
}
for (int i = 0; i < strlen(b); i++) {
input[i][1] = b[(strlen(b) - 1) - i] - '0';
}
int len = strlen(a) > strlen(b) ? strlen(a) : strlen(b);
for (int i = 0; i <= len; i++) {
int sum = input[i][0] + input[i][1] + check[i];
if (sum == 0) result[i] = 0;
else if (sum == 1) result[i] = 1;
else if (sum == 2) result[i] = 0, check[i + 1] = 1;
else if (sum == 3) result[i] = 1, check[i + 1] = 1;
}
int cnt = 0;
for (int i = len; i >= 0; i--) {
if (result[i] == 0) cnt++;
else break;
}
if (cnt - 1 == len) {
printf("0\n");
}
else {
for (int i = len - cnt; i >= 0; i--) {
printf("%d", result[i]);
}
printf("\n");
}
}
}
|
C
|
#include <stdio.h>
int main(void) {
// pointers to a character array to define simple strings
char * name = "John Smith";
/**
* This method creates a string which we can only use for reading.
* If we wish to define a string which can be manipulated, we will
* need to define it as a local character array
*/
char name[] = "John Smith";
/**
* This notation is different because it allocates an array variable
* so we can manipulate it. The empty brackets notation [] tells the
* compiler to calculate the size of the array automatically. This is
* in fact the same as allocating it explicitly, adding one to the
* length of the string:
*/
char name[] = "John Smith";
/* is the same as */
char name[11] = "John Smith";
// string formatting
char * name = "John Smith";
int age = 27;
/* prints out 'John Smith is 27 years old.' */
printf("%s is %d years old.\n", name, age);
// function to return string length
strlen(stringName);
// string concatenation
char dest[20]="Hello";
char src[20]="World";
strncat(dest,src,3);
printf("%s\n",dest);
strncat(dest,src,20);
printf("%s\n",dest);
}
|
C
|
#include<stdio.h>
void main()
{ int arr[100],n, ch, pos=-1, i;
printf("Enter the size of array: ");
scanf("%d", &n);
printf("Enter the elements of the array\n");
for(i=0; i<n; i++)
{ printf("\nNum %d:", i+1);
scanf("%d", &arr[i]);
}
printf("Enter the element you want to find: ");
scanf("%d", &ch);
for(i=0; i<n; i++)
{ if (arr[i]==ch)
{pos=i;
break;}
}
if(pos==-1)
printf("Element not found\n");
else
printf("Element found at index %d\n", i);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char line[10], *ptr;
int len, i, result=1, total=0;
while(scanf("%s", line)!=EOF){
len=strlen(line);
ptr=line;
while(*ptr!='\0'){
result=1;
for(i=0; i<len-1; i++){
result*=26;
}
total+=(*ptr-64)*result;
ptr++;
len--;
result=0;
}
printf("%d\n", total);
total=result=0;
}
return 0;
}
|
C
|
#include "drivers/mouse/mouse.h"
#include <stdint.h>
#include "drivers/gpio/gpio.h"
#include "lib/printk.h"
int32_t usleep(uint32_t usecs) {
int i;
for (i = 0; i < usecs*8e3; i++);
}
static const int gpio_clock = 23;
static const int gpio_data = 24;
static int mouse_x = 0,
mouse_y = 0;
// TODO Syscalls and init code all works.
// Interrupts are not firing though..
int mouse_init(void) {
int status;
// Request the clock and data pins.
status = gpio_request(gpio_clock, "mouse_clock");
if (status < 0) return -1;
status = gpio_request(gpio_data, "mouse_data");
if (status < 0) return -1;
// Those are inputs.
gpio_direction_input(gpio_clock);
gpio_direction_input(gpio_data);
// Get the IRQ number for the clock,
// since that's what we'll be watching.
int irq = gpio_to_irq(gpio_clock);
if (irq < 0) return -1;
// Watch the falling edge and enable.
gpio_set_falling(gpio_clock);
irq_enable(irq);
// TODO Send the "Enable Data Reporting" command.
// See the README for details on this whole process.
// TODO Init code.
gpio_set_value(gpio_clock, 0);
usleep(100);
gpio_set_value(gpio_data, 0);
gpio_set_value(gpio_clock, 1);
printk("mouse_init successful.\n");
return 0;
}
void mouse_cleanup(void) {
// Release the GPIO pins.
gpio_free(gpio_data);
gpio_free(gpio_clock);
}
static void mouse_update(unsigned char bytes[4]) {
// Refer to the table in the README.
// Mouse movement delta signs.
const int sy = (bytes[0] >> 7) & 1 ? -1 : 1,
sx = (bytes[0] >> 6) & 1 ? -1 : 1;
// Deltas.
const int dx = bytes[1] * sy,
dy = bytes[2] * sx;
mouse_x += dx;
mouse_y += dy;
// Print the mouse coordinates.
//printk("x: %03d, y: %03d\n", mouse_x, mouse_y);
}
int mouse_interrupt_handler(void) {
static int byte_counter = 0,
bit_counter = 0,
parity = 0;
static unsigned char bytes[4] = { 0, 0, 0, 0 };
int bit;
printk("Oh my god an interrupt\n");
return 0;
bit = gpio_get_value(gpio_data);
switch (bit_counter) {
case 0: // Start bit.
if (bit != 0) {
printk("Invalid start bit %x.\n", bit);
goto mouse_interrupt_handler_failure;
}
break;
case 9: // Parity bit.
parity += bit;
if (parity & 1 == 0) { // It's even (should be odd!).
printk("Invalid parity %x.\n", parity);
goto mouse_interrupt_handler_failure;
}
parity = 0;
break;
case 10: // Stop bit.
if (bit != 1) {
printk("Invalid stop bit %x.\n", bit);
goto mouse_interrupt_handler_failure;
}
byte_counter = (byte_counter + 1) % 3; // TODO Set to 4 if scroll wheel.
if (byte_counter == 0) {
// We just finished reading the final byte.
mouse_update(bytes);
}
break;
default: // Data bits.
// Put the bit into the byte and add to parity.
bytes[byte_counter] |= bit << (bit_counter-1);
parity += bit;
break;
}
// Increment bit_counter.
bit_counter = (bit_counter + 1) % 11;
return 0;
mouse_interrupt_handler_failure:
bit_counter = 0;
parity = 0;
byte_counter = 0;
bytes[0] = 0;
bytes[1] = 0;
bytes[2] = 0;
bytes[3] = 0;
return -1;
}
int mouse_get(int *x, int *y) {
*x = mouse_x;
*y = mouse_y;
}
|
C
|
/*
copyright xu(xusiwei1236@163.com), all right reserved.
Valid Anagram
==============
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
*/
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isAnagram(const char* s, const char* t) {
char cs[256] = {0}, ct[256] = {0};
while (*s) cs[*s++]++;
while (*t) ct[*t++]++;
return !memcmp(cs, ct, sizeof(cs));
}
int main(int argc, char* argv[])
{
const char* s = "anagram";
const char* t = "nagaram";
if (argc > 2) {
s = argv[1];
t = argv[2];
}
printf("isAnagram(%s, %s): %s\n", s, t, isAnagram(s, t) ? "true" : "false");
return 0;
}
|
C
|
#include <stdlib.h>
#include "basic_operation.h"
#include "utils.h"
bool * add(bool * a, bool * b, int length, bool carry_in) {
// use one additional bit to store the most significant bit
// useful in some cases
bool * sum = (bool *)malloc(sizeof(bool) * (length + 1));
bool carry_out;
for (int i = 0; i < length; ++i) {
full_adder(a[i], b[i], carry_in, sum + i, &carry_out);
carry_in = carry_out;
}
sum[length] = carry_out;
return sum;
}
bool * sub(bool * a, bool * b, int length) {
bool * b_inverse = (bool *)malloc(sizeof(bool) * length);
for (int i = 0; i < length; ++i)
b_inverse[i] = !b[i];
bool * diff = add(a, b_inverse, length, true);
return diff;
}
bool * mul(bool * a, bool * b, int length) {
// initialization
int product_length = length * 2;
bool * product = (bool *)malloc(sizeof(bool) * product_length);
bool * temp = (bool *)malloc(sizeof(bool) * product_length);
for (int i = 0; i < product_length; ++i) {
product[i] = false;
temp[i] = false;
}
// perform add and left shift
for (int i = 0; i < length; ++i) {
for (int j = 0; j < length; ++j) {
temp[j] = a[j] & b[i];
temp[length + j] = false;
}
left_shift(temp, i, product_length);
product = add(product, temp, product_length, false);
}
return product;
}
bool * divide(bool * a, bool * b, int length) {
// initialize
int double_length = 2 * length;
bool * quotient = (bool *)malloc(sizeof(bool) * double_length);
bool * remainer = (bool *)malloc(sizeof(bool) * double_length);
for (int i = 0; i < double_length; ++i) {
quotient[i] = false;
remainer[i] = false;
}
bool * extended_b = (bool *)malloc(sizeof(bool) * double_length);
for (int i = 0; i < length; ++i) {
extended_b[i] = b[i];
extended_b[length + i] = false;
}
// compute
bool * temp = NULL;
// compute the integer part of the quotient
for (int shift = length - 1; shift >= 0; --shift) {
left_shift(remainer, 1, double_length);
remainer[0] = a[shift];
temp = sub(remainer, extended_b, double_length);
// remainer >= b
if (temp[double_length - 1] == false) {
for (int i = 0; i < double_length; ++i)
remainer[i] = temp[i];
quotient[length + shift] = true;
}
}
// compute the decimal part of the quotient
for (int shift = length - 1; shift >= 0; --shift) {
left_shift(remainer, 1, double_length);
temp = sub(remainer, extended_b, double_length);
// remainer >= b
if (temp[double_length - 1] == false) {
for (int i = 0; i < double_length; ++i)
remainer[i] = temp[i];
quotient[shift] = true;
}
}
return quotient;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
/* Function which checks for the < symbol
Takes a list of arguements and size of list as paramaters
Returns the location of the special character or -1 if not found*/
int redirectStdout(char** arg_list, int size){
for(int i = 0; i < size; i++){
if(arg_list[i][0] == '<') return i;
}
return -1;
}
/* Function which checks for the > symbol
T akes a list of arguements and size of list as paramaters
Returns the location of the special character or -1 if not found*/
int redirectStdin(char** arg_list, int size){
for(int i = 0; i < size; i++){
if(arg_list[i][0] == '>') return i;
}
return -1;
}
/* Function which checks for the | symbol
Takes a list of arguements and size of list as paramaters
Returns the location of the special character or -1 if not found*/
int pipeChecker(char** arg_list, int size){
for(int i = 0; i < size; i++){
if(arg_list[i][0] == '|') return i;
}
return -1;
}
int parseReverseArray(char *buffer, char **arg_list){
//strip the newline from the end of the buffer
strtok(buffer, "\n");
/*-----------Parsing section---------------*/
/* This section is responsible for parsing
the commands into an array and reversing
the order of the arguements*/
char *commands[50];
char* token = strtok(buffer, " ");
int arg_list_size = 0;
while (token != NULL){
commands[arg_list_size] = token;
arg_list_size++;
token = strtok(NULL, " ");
}
arg_list[arg_list_size] = NULL;
int count = 0;
for(int i = arg_list_size-1; i>=0; i--){
arg_list[count] = commands[i];
count++;
}
return arg_list_size;
/*-----------Parsing section---------------*/
}
//Work in progress functions
// void execFg(char **arg_list) {
//
// }
//
// void execBg(char **arg_list) {
//
// }
int main(){
const int BUFFER_SIZE = 1000;
char buffer[BUFFER_SIZE]; //buffer array
pid_t bg_process = 0; //pid of the background process. 0 if doesnt exist
//inital prompt message
printf("Welcome to the Funny Shell created by Seth Tummillo. Type 'exit' to exit.\n" );
do{
// make sure the buffer is zeroed out
bzero(buffer, BUFFER_SIZE);
//clean up any running backgroun processes
pid_t temp;
while((temp = waitpid(-1, NULL, WNOHANG)) > 0) {
printf("Done pid: %d\n", temp);
bg_process = 0;
}
//initial prompt and input from user
printf("tummillo> ");
fgets(buffer, 150, stdin);
//if loop which will run if user enters something other than exit
if((strcmp(buffer, "exit\n")) != 0 && buffer[0] != '\n'){
char* arg_list[50];
int arg_list_size = parseReverseArray(buffer, arg_list);
int spChPos = 0; //varible to store the location of the special character if one is encountered
/* This series of if statements will look through the array
of arguements and determine if any special operators exist
within the array. These operations include redirection of
stdout '<' and stdin '>', the pipe function '|', and
the background operator '&' */
if ((spChPos = redirectStdout(arg_list, arg_list_size)) >= 0) {
if(spChPos == (arg_list_size - 1)){
printf("No output destination specified\n");
} else {
int pid = fork();
if(pid == -1) {
//error occured
printf("Error creating child\n");
} else if (pid == 0) {
//child process
int fd; //file descriptor
char *filename = arg_list[spChPos + 1]; //destination file
char *arg_list2[spChPos+1]; //updated arg_list
for (int i = 0; i < spChPos; i++) {
arg_list2[i] = arg_list[i];
}
arg_list2[spChPos] = NULL;
if((fd = open(filename, O_CREAT | O_WRONLY, 0666)) < 0){
printf("Error opening specified destination\n");
}
if(dup2(fd, 1) < 0) {
printf("Error redirecting stdout\n" );
}
if(execvp(arg_list2[0], arg_list2) == -1){
printf("An error has occured\n");
close(fd);
exit(0);
}
close(fd);
} else {
wait(NULL);
}
}
} else if ((spChPos = redirectStdin(arg_list, arg_list_size)) >= 0) {
//printf("contains > found at position: %d\n", spChPos);
if(spChPos == (arg_list_size - 1)){
printf("No input destination specified\n");
} else {
int pid = fork();
if(pid == -1) {
//error occured
printf("Error creating child\n");
} else if (pid == 0) {
//child process
int fd; //file descriptor
char *filename = arg_list[spChPos + 1]; //destination file
char *arg_list2[spChPos+1]; //updated arg_list
for (int i = 0; i < spChPos; i++) {
arg_list2[i] = arg_list[i];
}
arg_list2[spChPos] = NULL;
if((fd = open(filename, O_RDONLY, 0666)) < 0){
printf("File does not exit\n");
}
if(dup2(fd, 0) < 0) {
printf("Error redirecting stdin\n" );
}
if(execvp(arg_list2[0], arg_list2) == -1){
printf("An error has occured");
close(fd);
exit(0);
}
close(fd);
} else {
wait(NULL);
}
}
} else if ((spChPos = pipeChecker(arg_list, arg_list_size)) >= 0) {
/* This section is responsible for splitting up the arguements before
and after the pipe so that they can be called in seperate processes */
int par_arg_size = arg_list_size - spChPos;
int chld_arg_size = spChPos + 1;
char *arg_list_parent[par_arg_size], *arg_list_child[chld_arg_size];
for(int i = 0; i < par_arg_size-1; i++){
arg_list_parent[i] = arg_list[spChPos+1];
}
arg_list_parent[par_arg_size - 1] = NULL;
for(int i = 0; i < chld_arg_size-1; i++){
arg_list_child[i] = arg_list[i];
}
arg_list_child[chld_arg_size-1] = NULL;
int pid = fork();
if(pid == -1) {
//error occured
printf("Error creating child");
} else if (pid == 0) {
int fd[2];
pipe(fd);
int pid = fork();
if(pid == -1) {
//error occured
printf("Error creating child");
} else if (pid == 0) {
close(fd[0]);
dup2(fd[1], 1);
if(execvp(arg_list_child[0], arg_list_child) == -1){
printf("An error has occured");
exit(0);
}
} else {
close(fd[1]);
dup2(fd[0], 0);
if(execvp(arg_list_parent[0], arg_list_parent) == -1){
printf("An error has occured");
exit(0);
}
}
} else {
wait(NULL);
}
} else if (arg_list[arg_list_size-1][0] == '&') { //if statement checks if process should be created in background
arg_list[arg_list_size-1] = NULL;
if(bg_process == 0) {
pid_t pid = fork();
if(pid == -1) {
//error occured
printf("Error creating child");
} else if (pid == 0) {
if(execvp(arg_list[0], arg_list) == -1){
printf("An error has occured");
exit(0);
}
//child process
} else {
bg_process = pid;
printf("Running (Pid: %d) &", pid);
for(int i = arg_list_size-2; i >= 0; i--) {
printf(" %s", arg_list[i]);
}
printf("\n");
}
} else {
printf("Background process already running.\n");
}
} else if (strcmp(arg_list[0], "fg") == 0) {
if(bg_process != 0){
waitpid(bg_process, NULL, 0);
bg_process = 0;
} else {
printf("No background processes exist\n");
}
} else {
int pid = fork();
if(pid == -1) {
//error occured
printf("Error creating child");
} else if (pid == 0) {
//child process
if(execvp(arg_list[0], arg_list) == -1){
printf("An error has occured");
exit(0);
}
} else {
wait(NULL);
}
}
}
}while(strcmp(buffer, "exit\n") != 0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct line {
char op, type;
unsigned addr;
unsigned size;
int unit;
} LINE;
typedef struct random_access_memory {
unsigned memory_size;
unsigned cache_size;
unsigned block_size;
unsigned block_count;
unsigned **cache;
} RAM;
int
main(int argc, char **argv)
{
RAM ram;
ram.memory_size = strtol(argv[1], NULL, 10);
ram.cache_size = strtol(argv[2], NULL, 10);
ram.block_size = strtol(argv[3], NULL, 10);
ram.block_count = ram.cache_size / ram.block_size;
ram.cache = calloc(ram.block_count, sizeof(*ram.cache));
for (int i = 0; i < ram.block_count; ++i) {
ram.cache[i] = calloc(2, sizeof(**ram.cache));
}
unsigned cache_block_num, memory_block_num;
unsigned long long misses = 0;
LINE cur;
memset(&cur, 0, sizeof(cur));
while (scanf("%c%c%x%u%d\n", &cur.op, &cur.type, &cur.addr, &cur.size, &cur.unit) > 4) {
if (cur.addr >= ram.memory_size) {
++misses;
continue;
}
memory_block_num = cur.addr / ram.block_size;
cache_block_num = memory_block_num % ram.block_count;
if (ram.cache[cache_block_num][0] == 0) {
++ram.cache[cache_block_num][0];
} else {
if (ram.cache[cache_block_num][1] != memory_block_num) {
++misses;
}
}
ram.cache[cache_block_num][1] = memory_block_num;
}
for (int i = 0; i < ram.block_count; ++i) {
free(ram.cache[i]);
}
free(ram.cache);
printf("%llu\n", misses);
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_3__ TYPE_1__ ;
/* Type definitions */
struct TYPE_3__ {int /*<<< orphan*/ path; int /*<<< orphan*/ fd; int /*<<< orphan*/ * inf; } ;
typedef TYPE_1__ FILEDESC ;
/* Variables and functions */
int /*<<< orphan*/ exit (int) ;
int /*<<< orphan*/ * fdopen (int /*<<< orphan*/ ,char*) ;
int /*<<< orphan*/ perror (int /*<<< orphan*/ ) ;
__attribute__((used)) static void
open_fp(FILEDESC *fp)
{
if (fp->inf == NULL && (fp->inf = fdopen(fp->fd, "r")) == NULL) {
perror(fp->path);
exit(1);
}
}
|
C
|
#include "command.h"
char peekchar() {
char c = getchar();
ungetc(c, stdin);
return c;
}
void consume_whitespace() {
while (1) {
char c = peekchar();
if (isalnum(c)) {
break;
} else {
getchar();
}
}
}
void read_command_name(struct command *command) {
char buffer[8] = {0};
int offset = 0;
while (1) {
char c = peekchar();
if (isalpha(c)) {
buffer[offset++] = c;
getchar();
} else {
break;
}
}
if (strcmp(buffer, "save") == 0) {
command->name = SAVE;
} else if (strcmp(buffer, "load") == 0) {
command->name = LOAD;
} else {
perror("unexpected command name\n");
}
}
int read_command_int() {
int result = 0;
while (1) {
char c = peekchar();
if (isnumber(c)) {
getchar();
result = 10 * result + c - '0';
} else {
break;
}
}
return result;
}
void read_command_index(struct command *command) {
command->index = read_command_int();
}
void read_command_value(struct command *command) {
command->value = read_command_int();
}
struct command read_command() {
struct command command;
read_command_name(&command);
consume_whitespace();
read_command_index(&command);
if (command.name == SAVE) {
consume_whitespace();
read_command_value(&command);
}
return command;
}
|
C
|
//average of the numbers
#include<stdio.h>
int main()
{
int num,a[100],avg=0,i,N;
printf("Enter the total numbers");
scanf("%d",&N);
printf("\nEnter the numbers");
for(i=1;i<=N;i++)
{
scanf("%d",&a[i]);
printf("\t%d",a[i]);
avg=avg+a[i];
}
printf("\nThe average value is %d",avg);
return 0;
}
|
C
|
// getchar_function.c
#include <stdio.h>
int main(void)
{
int c;
printf(" ϳ Է: _\b");
c = getchar();
printf("Է : %c\n", c);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "aula0804.h"
#define NUMERO_ARGUMENTOS COMPRIMENTO_PIS_PASEP + 1
#define ARGUMENTO_INVALIDO 1
#define NUMERO_ARGUMENTOS_INVALIDO 2
#define OK 0
int
main (int argc, char *argv[])
{
unsigned indice;
char pisPasep[COMPRIMENTO_PIS_PASEP];
if (argc != NUMERO_ARGUMENTOS)
{
printf("Uso: <nome_do_programa> <numeroPisPasep> \n");
exit(NUMERO_ARGUMENTOS_INVALIDO);
}
for (indice = 1; indice < COMPRIMENTO_PIS_PASEP + 1; indice++)
{
if ((strlen(argv[indice]) != 1) || ((argv[indice][0] < '0') || (argv[indice][0] > '9')))
{
printf("Argumento \"%s\" invalido, entrar com numeros entre \"0\" e \"9\"\n", argv[indice]);
exit(ARGUMENTO_INVALIDO);
}
}
strcpy(pisPasep, argv[1]);
for (indice = 1; indice < COMPRIMENTO_PIS_PASEP; indice++)
strcat(pisPasep, argv[indice + 1]);
printf("%c\n", GerarDigitoVerificadorPisPasep(pisPasep));
return OK;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 50
//Write a function that reverses the digits of a given floating-point
//number. The function should receive a double number and a pointer to
// an integer variable. In case of format error, it should set error to
// 1 and in case of success to 0. Declare a function prototype before
//defining the function.
double reverse(char* number, int *error);
int main()
{
char input[BUFFER_SIZE];
fgets(input, BUFFER_SIZE, stdin);
int error;
double reversed = reverse(input, &error);
if (error != 1)
{
printf("%.3lf", reversed);
}
else
{
printf("Invalid format");
}
return 0;
}
double reverse(char* number, int *error)
{
*error = 0;
int a, b, length = strlen(number);
char reversed[length];
for (a = 0, b = length - 2; a < length; a++, b--)
{
reversed[a] = number[b];
}
char* remainder;
double reversedNum = strtod(reversed, &remainder);
if (*remainder != '\0')
{
*error = 1;
return 0;
}
return reversedNum;
}
|
C
|
/*
Exercise 1-14. Write a program to print a histogram of the frequencies of different characters
in its input.
*/
#include "stdio.h"
#define MAX 1000
main(){
char c;
int counts[MAX];
int i, j;
i = j = 0;
//initialize counts
for (i=0; i < MAX; i++){
counts[i] = 0;
}
while((c = getchar()) != EOF){
if (c != '\t' && c != '\n' && c != '\r' && c != ' '){ // \r is needed for windows files
++counts[c];
}
}
for (i=0; i < MAX; i++){
if(counts[i] > 0){
printf("%2c |", i);
for (j=0; j < counts[i]; j++){
putchar('*');
}
putchar('\n');
}
}
}
|
C
|
/******************************************************************************
Напишите программу, которая запрашивает имя и фамилию, а затем выводит их в формате фамилия, имя.
*******************************************************************************/
#include <stdio.h>
int main()
{
char name[20];
char soname[20];
printf("Input name & so-name");
scanf("%s", name);
scanf("%s", soname);
printf("%s %s", soname, name);
return 0;
}
|
C
|
#pragma once
enum { QUEUE_SIZE = 5 };
typedef struct
{
char array[QUEUE_SIZE];
int front, rear;
}
QUEUE;
void initQueue(QUEUE* pq);
void enQueue(QUEUE* pq, char data);
char deQueue(QUEUE* pq);
int isEmpty(QUEUE* pq);
|
C
|
/*
Q5) Escreva uma função que receba, como entrada, uma cadeia de caracteres s e um inteiro n, e, em
seguida, retire o "sufixo" da cadeia s de tamanho n (isto é, retire os n últimos caracteres). Se a
cadeia não tiver pelo menos n caracteres, deve ser impressa a mensagem "erro". Por exemplo, se s
= "abcdefghi" e n = 3, então a cadeia "abcdef" deve ser impressa; com a mesma cadeia s e n = 17,
deve ser impresso "erro". O protótipo desta função é o seguinte: void retira_fim_n (char *str, int n).
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void retira_fim_n (char *str, int n);
int main(void){
char* cadeia;
int n;
printf("Informe a cadeia: ");
cadeia = (char*) malloc(sizeof(char) * 16);
scanf(" %15[^\n]", cadeia);
printf("Informe n: ");
scanf("%d", &n);
retira_fim_n(cadeia, n);
printf("\n");
}
void retira_fim_n(char *str, int n){
int i,j;
for(i = 0; str[i] != '\0'; i++);
if (i < n){
printf("erro");
}
else{
for(j = 0; j < i-n; j++){
printf("%c", str[j]);
}
}
}
|
C
|
#include <stdlib.h>
#include "two-sum.h"
int main(){
int nums[] = { 2, 7, 11, 15};
int target = 9;
int *result = twoSum(nums, 4, target);
if(result != NULL && (nums[result[0]]+nums[result[1]] == target)){
printf("WORKS!!\n");
} else {
printf(":(\n");
}
}
|
C
|
// Uses ptrace to overwrite the vdso of a running process.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/user.h>
#include <sys/ptrace.h>
#include "kernel/elf.h"
#include "tools/ptutil.h"
#include "misc.h"
static addr_t aux_addr(int pid, unsigned type) {
struct user_regs_struct regs;
trycall(ptrace(PTRACE_GETREGS, pid, NULL, ®s), "ptrace get sp for aux");
dword_t sp = (dword_t) regs.rsp;
// skip argc
sp += 4;
// skip argv
while (pt_read(pid, sp) != 0)
sp += 4;
sp += 4;
// skip envp
while (pt_read(pid, sp) != 0)
sp += 4;
sp += 4;
// dig through auxv
dword_t aux_type;
while ((aux_type = pt_read(pid, sp)) != 0) {
sp += 4;
if (aux_type == type) {
return sp;
}
sp += 4;
}
return 0;
}
static void aux_write(int pid, int type, dword_t value) {
return pt_write(pid, aux_addr(pid, type), value);
}
void transplant_vdso(int pid, const void *new_vdso, size_t new_vdso_size) {
// get the vdso address and size from /proc/pid/maps
char maps_file[32];
sprintf(maps_file, "/proc/%d/maps", pid);
FILE *maps = fopen(maps_file, "r");
char line[256];
dword_t start, end;
while (fgets(line, sizeof(line), maps) != NULL) {
char *map_type = NULL;
sscanf(line, "%8x-%8x %*s %*s %*s %*s %ms\n", &start, &end, &map_type);
if (map_type) {
if (strcmp(map_type, "[vdso]") == 0) {
free(map_type);
break;
}
free(map_type);
}
}
fclose(maps);
// copy the new vdso in
for (dword_t addr = start; addr < end; addr += sizeof(unsigned long)) {
unsigned long new_vdso_data = 0;
if (addr - start < new_vdso_size) {
new_vdso_data = *(unsigned long *) ((char *) new_vdso + addr - start);
}
if (ptrace(PTRACE_POKEDATA, pid, addr, new_vdso_data) < 0) {
perror("ptrace vdso poke"); exit(1);
}
}
// find the entry point
dword_t entry = *(dword_t *) ((char *) new_vdso + 24) + start;
aux_write(pid, AX_SYSINFO, entry);
aux_write(pid, AX_SYSINFO_EHDR, start);
}
|
C
|
/*
* TraceBuffer.c
*
*
* Created by Michael Weingert on 11-11-14.
* Copyright 2011 __MyCompanyName__. All rights reserved.
*
*/
#include "TraceBuffer.h"
#include "Constants.h"
#include "Structures.h"
#include <stdio.h>
#include <string.h>
void InitializeTraceBufferSEND()
{
int i;
TraceBuffer* temp;
TraceBuffer* tempPrev;
temp = (TraceBuffer *)malloc(sizeof(TraceBuffer));
headSEND = temp;
temp->previous = NULL;
tempPrev = temp;
for (i = 1; i < TRACE_BUFFER_NUM; i++)
{
temp->S_ID = -1; // for sanity checks
temp->next = (TraceBuffer *)malloc(sizeof(TraceBuffer));
tempPrev = temp;
temp = temp->next;
temp->previous = tempPrev;
}
tailSEND = tempPrev;
}
void InitializeTraceBufferRECEIVE()
{
int i;
TraceBuffer* temp;
TraceBuffer* tempPrev;
temp = (TraceBuffer *)malloc(sizeof(TraceBuffer));
headRECEIVE = temp;
temp->previous = NULL;
tempPrev = temp;
for (i = 1; i < TRACE_BUFFER_NUM; i++)
{
temp->S_ID = -1; // for sanity checks
temp->next = (TraceBuffer *)malloc(sizeof(TraceBuffer));
tempPrev = temp;
temp = temp->next;
temp->previous = tempPrev;
}
tailRECEIVE = tempPrev;
}
void DeallocateTraceBufferSEND()
{
TraceBuffer* temp = headSEND;
while (temp->next != NULL)
{
temp = temp->next;
free(temp->previous);
}
free(temp);
headSEND = NULL;
tailSEND = NULL;
}
void DeallocateTraceBufferRECEIVE()
{
TraceBuffer* temp = headRECEIVE;
while (temp->next != NULL)
{
temp = temp->next;
free(temp->previous);
}
free(temp);
headRECEIVE = NULL;
tailRECEIVE = NULL;
}
void Add_TraceBufferSEND(int S_ID, int R_ID, int TimeStampSec, int TimeStampMin, int TimeStampHr, int Message_Type)
{
tailSEND->S_ID = S_ID;
tailSEND->R_ID = R_ID;
tailSEND->TimeStampSec = TimeStampSec;
tailSEND->TimeStampMin = TimeStampMin;
tailSEND->TimeStampHr = TimeStampHr;
tailSEND->Message_Type = Message_Type;
tailSEND->next = headSEND;
headSEND->previous = tailSEND;
tailSEND->previous->next = NULL;
headSEND = tailSEND;
tailSEND = headSEND->previous;
headSEND->previous = NULL;
}
void Add_TraceBufferRECEIVE(int S_ID, int R_ID, int TimeStampSec, int TimeStampMin, int TimeStampHr, int Message_Type)
{
tailRECEIVE->S_ID = S_ID;
tailRECEIVE->R_ID = R_ID;
tailRECEIVE->TimeStampSec = TimeStampSec;
tailRECEIVE->TimeStampMin = TimeStampMin;
tailRECEIVE->TimeStampHr = TimeStampHr;
tailRECEIVE->Message_Type = Message_Type;
tailRECEIVE->next = headRECEIVE;
headRECEIVE->previous = tailRECEIVE;
tailRECEIVE->previous->next = NULL;
headRECEIVE = tailRECEIVE;
tailRECEIVE = headRECEIVE->previous;
headRECEIVE->previous = NULL;
}
void PrintTraceBufferSEND(MsgEnv* message)
{
int i;
char tempMessage[MAXCHAR];
// to do later
TraceBuffer * temp;
temp = headSEND;
snprintf(message->message, MAXCHAR, "%c[33mSEND TRACE BUFFER\n%c[0m", 0x1B, 0x1B);
//strcat(message->message, "SEND TRACE BUFFER\n");
if (temp->S_ID == -1 )
{
snprintf(message->message, MAXCHAR, "NULL SEND TRACE BUFFER");
return;
}
//message->message = ""; //NOTE NEED TO CHECK STRCAT OPERATION
for (i = 1; i < TRACE_BUFFER_NUM; i++)
{
if (temp->S_ID == -1)
break;
snprintf(tempMessage, MAXCHAR, "S_ID %i R_ID %i MessageType %i Time %i : %i : %i\n", temp->S_ID, temp->R_ID, temp->Message_Type, temp->TimeStampHr, temp->TimeStampMin, temp->TimeStampSec);
strcat(message->message, tempMessage);
//message->message += temp->S_ID + temp->R_ID + temp->Message_Type + temp->TimeStampHr + ":" + temp->TimeStampMin + ":" + temp->TimeStampSec;// etc etc
if (temp->next == NULL)
break;
temp = temp->next;
}
char command[40];
snprintf(command, 40, "%c[37mRECEIVE TRACE BUFFER\n%c[0m", 0x1B, 0x1B);
strcat(message->message, command);
temp = headRECEIVE;
if (temp->S_ID == -1 )
{
snprintf(message->message, MAXCHAR, "NULL RECEIVE TRACE BUFFER");
return;
}
//msg->message = ""
for (i = 1; i < TRACE_BUFFER_NUM; i++)
{
if (temp->S_ID == -1)
break;
snprintf(tempMessage, MAXCHAR, "S_ID %i R_ID %i MessageType %i Time %i : %i : %i\n", temp->S_ID, temp->R_ID, temp->Message_Type, temp->TimeStampHr, temp->TimeStampMin, temp->TimeStampSec);
strcat(message->message, tempMessage);
//msg->message += temp->S_ID + temp->R_ID + temp->Message_Type + temp->TimeStampHr + ":" + temp->TimeStampMin + ":" + temp->TimeStampSec;// etc etc
if (temp->next == NULL)
break;
temp = temp->next;
}
}
void PrintTraceBufferRECEIVE(MsgEnv* msg)
{
int i;
// to do later
char * tempMessage = (char *)malloc(MAXCHAR * sizeof(char));
TraceBuffer * temp;
temp = headRECEIVE;
if (temp->S_ID == -1 )
{
snprintf(msg->message, sizeof(msg->message), "NULL TRACE BUFFER");
return;
}
//msg->message = ""
for (i = 1; i < TRACE_BUFFER_NUM; i++)
{
if (temp->S_ID == -1)
break;
snprintf(tempMessage, MAXCHAR, "S_ID %i R_ID %i MessageType %i Time %i : %i : %i\n", temp->S_ID, temp->R_ID, temp->Message_Type, temp->TimeStampHr, temp->TimeStampMin, temp->TimeStampSec);
strcat(msg->message, tempMessage);
//msg->message += temp->S_ID + temp->R_ID + temp->Message_Type + temp->TimeStampHr + ":" + temp->TimeStampMin + ":" + temp->TimeStampSec;// etc etc
if (temp->next == NULL)
break;
temp = temp->next;
}
}
|
C
|
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include "util.h"
#include "cudd.h"
//Function wrappers around macros
DdNode *wrappedRegular(DdNode *f){
assert(f);
return Cudd_Regular(f);
}
void wrappedCuddRef(DdNode *f){
assert(f);
Cudd_Ref(f);
}
int wrappedCuddIsComplement(DdNode *f){
return Cudd_IsComplement(f);
}
//Garbage collection hooks
int preGCHook_sample(DdManager *dd, const char *str, void *data){
printf("Performing %s garbage collection...", str);
return 1;
}
int postGCHook_sample(DdManager *dd, const char *str, void *data){
printf("%s GC done\n", str);
return 1;
}
int **allSat(DdManager *m, DdNode *n, int *nterms, int *nvars){
CUDD_VALUE_TYPE value;
DdGen *gen;
int *cube;
int size = Cudd_ReadSize(m);
int num = ceil(Cudd_CountPathsToNonZero(n));
int i=0;
*nterms = num;
*nvars = size;
int **result = malloc(sizeof(int *)*num);
assert(result);
Cudd_ForeachCube(m, n, gen, cube, value){
result[i] = malloc(sizeof(int *)*size);
assert(result[i]);
int j;
for(j=0; j<size; j++){
result[i][j] = cube[j];
}
i++;
}
return result;
}
int *oneSat(DdManager *m, DdNode *n, int *nvars){
CUDD_VALUE_TYPE value;
DdGen *gen;
int *cube;
int size = Cudd_ReadSize(m);
int j;
*nvars = size;
gen = Cudd_FirstCube (m, n, &cube, &value);
if (Cudd_IsGenEmpty(gen)) {
Cudd_GenFree (gen);
return NULL;
}
int *result = malloc(sizeof(int) * size);
assert(result);
for(j=0; j<size; j++){
result[j] = cube[j];
}
Cudd_GenFree (gen);
return result;
}
int *onePrime(DdManager *m, DdNode *l, DdNode *u, int *nvars){
DdGen *gen;
int *cube;
int size = Cudd_ReadSize(m);
int j;
*nvars = size;
gen = Cudd_FirstPrime(m, l, u, &cube);
if (Cudd_IsGenEmpty(gen)) {
Cudd_GenFree (gen);
return NULL;
}
int *result = malloc(sizeof(int) * size);
assert(result);
for(j=0; j<size; j++){
result[j] = cube[j];
}
Cudd_GenFree (gen);
return result;
}
|
C
|
#define thisprog "xe-oversample1"
#define TITLE_STRING thisprog" v 1: 17.March.2019 [JRH]"
#define MAXLINELEN 1000
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
<TAGS> signal_processing filter </TAGS>
v 1: 17.March.2019 [JRH]
*/
/* external functions start */
char *xf_lineread1(char *line, long *maxlinelen, FILE *fpin);
long *xf_lineparse2(char *line,char *delimiters, long *nwords);
int xf_filter_bworth1_f(float *X, size_t nn, float sample_freq, float low_freq, float high_freq, float res, char *message);
long xf_interp3_f(float *data, long ndata);
float *xf_expand1_f(float *data , long nn, long setn, char *message);
/* external functions end */
int main (int argc, char *argv[]) {
/* general variables */
char *line=NULL,message[MAXLINELEN];
long ii,jj,kk,nn,nbad,maxlinelen=0;
int w,x,y,z;
float a,b,c,d,result_f[64];
double aa,bb,cc,dd,ee, result_d[64];
FILE *fpin,*fpout;
/* program-specific variables */
long sizeofd1,n2;
float *data1=NULL;
double sr2,divisor=2.0;
/* arguments */
char *infile;
int setverb=0;
long setcolx=1,setcoly=2;
double setsr=1000.0,setmul=4.0;
float setres=pow(2.0,0.5),setlow=0.0,sethigh=-1.0;
/********************************************************************************
PRINT INSTRUCTIONS IF THERE IS NO FILENAME SPECIFIED
********************************************************************************/
if(argc<2) {
fprintf(stderr,"\n");
fprintf(stderr,"----------------------------------------------------------------------\n");
fprintf(stderr,"%s\n",TITLE_STRING);
fprintf(stderr,"----------------------------------------------------------------------\n");
fprintf(stderr,"Resample an input, adding points and smoothing (Butterworth filter)\n");
fprintf(stderr,"- assumes one valid numeric value per input line\n");
fprintf(stderr,"- non-numeric values will be interpolated\n");
fprintf(stderr,"USAGE: %s [infile] [options]\n",thisprog);
fprintf(stderr," [input]: file name or \"stdin\"\n");
fprintf(stderr,"VALID OPTIONS: defaults in []\n");
fprintf(stderr," -sr: sample-rate (Hz) of input [%g]\n",setsr);
fprintf(stderr," -mul: multiplier for sample-rate [%g]\n",setmul);
fprintf(stderr," -low: low-cut filter (Hz, 0=NONE) [%g]\n",setlow);
fprintf(stderr," -high: high-cut filter (Hz, -1=AUTO, 0=NONE) [%g]\n",sethigh);
fprintf(stderr," AUTO= sr/%g\n",divisor);
fprintf(stderr," -verb: verbose output (0=NO 1=YES 999=DEBUG) [%d]\n",setverb);
fprintf(stderr,"EXAMPLES:\n");
fprintf(stderr," %s data.txt -sr 1000 -mul 4 -low 10 1\n",thisprog);
fprintf(stderr," cat temp.txt | %s stdin -sr 1000 -mul 2\n",thisprog);
fprintf(stderr,"OUTPUT:\n");
fprintf(stderr," higher-resolution, filtered values\n");
fprintf(stderr,"----------------------------------------------------------------------\n");
fprintf(stderr,"\n");
exit(0);
}
/********************************************************************************
READ THE FILENAME AND OPTIONAL ARGUMENTS - including comma-separated list item
********************************************************************************/
infile= argv[1];
for(ii=2;ii<argc;ii++) {
if( *(argv[ii]+0) == '-') {
if((ii+1)>=argc) {fprintf(stderr,"\n--- Error[%s]: missing value for argument \"%s\"\n\n",thisprog,argv[ii]); exit(1);}
else if(strcmp(argv[ii],"-sr")==0) setsr= atof(argv[++ii]);
else if(strcmp(argv[ii],"-mul")==0) setmul= atof(argv[++ii]);
else if(strcmp(argv[ii],"-low")==0) setlow= atof(argv[++ii]);
else if(strcmp(argv[ii],"-high")==0) sethigh= atof(argv[++ii]);
else if(strcmp(argv[ii],"-verb")==0) setverb= atoi(argv[++ii]);
else {fprintf(stderr,"\n--- Error [%s]: invalid command line argument [%s]\n\n",thisprog,argv[ii]); exit(1);}
}}
if(setverb!=0 && setverb!=1 && setverb != 999) { fprintf(stderr,"\n--- Error [%s]: invalid -verb [%d] must be 0,1, or 999\n\n",thisprog,setverb);exit(1);}
if(setmul<1.0) { fprintf(stderr,"\n--- Error [%s]: invalid -mul [%g] must be >=1\n\n",thisprog,setmul);exit(1);}
if(setmul==1) divisor=2.1;
/********************************************************************************
STORE DATA - ASSUME WE DON'T KNOW THE LENGTH OF EACH INPUT LINE
********************************************************************************/
sizeofd1= sizeof(*data1);
if(strcmp(infile,"stdin")==0) fpin=stdin;
else if((fpin=fopen(infile,"r"))==0) {fprintf(stderr,"\n--- Error[%s]: file \"%s\" not found\n\n",thisprog,infile);exit(1);}
nn= nbad= 0;
if(setverb==1) fprintf(stderr,"\tstoring data from %s\n",infile);
while((line=xf_lineread1(line,&maxlinelen,fpin))!=NULL) {
if(maxlinelen==-1) {fprintf(stderr,"\n--- Error[%s]: readline function encountered insufficient memory\n\n",thisprog);exit(1);}
if(sscanf(line,"%f",&a)!=1 || !isfinite(a)) {a=NAN; nbad++;}
data1= realloc(data1,((nn+1)*sizeofd1));
if(data1==NULL) {fprintf(stderr,"\n--- Error[%s]: insufficient memory\n\n",thisprog);exit(1);};
data1[nn]= a;
nn++;
}
if(strcmp(infile,"stdin")!=0) fclose(fpin);
if(setverb==1) fprintf(stderr,"\t%ld data points read - %ld invalid\n",nn,nbad);
//TEST: for(ii=0;ii<nn;ii++) printf("%g\n",data1[ii]); goto END;
/********************************************************************************/
/* INTERPOLATE IF THERE ARE INVALID DATAPOINTS */
/********************************************************************************/
if(nbad>0) {
if(setverb==1) fprintf(stderr,"\tinterpolating...\n");
kk= xf_interp3_f(data1,(off_t)nn);
if(kk<0) { fprintf(stderr,"\n\t --- Error [%s]: input \"%s\" contains no valid numbers\n\n",thisprog,infile);free(data1);exit(1);}
}
/********************************************************************************/
/* EXPAND THE DATA BY DUPLICATING POINTS */
/********************************************************************************/
n2= (long)nn*setmul;
sr2= setsr*setmul;
if(setverb==1) fprintf(stderr,"\texpanding to %ld points, samplerate= %g Hz...\n",n2,sr2);
if(setmul>1.0) {
data1= xf_expand1_f(data1,nn,n2,message);
if(data1==NULL) { fprintf(stderr,"\n\t--- %s/%s\n\n",thisprog,message); exit(1); }
}
/********************************************************************************/
/* APPLY THE BUTTERWORTH FILTER */
/********************************************************************************/
if(sethigh==-1) sethigh= (float)(setsr/divisor);
if(setverb==1) fprintf(stderr,"\tfiltering (%g-%g Hz) ...\n",setlow,sethigh);
z= xf_filter_bworth1_f(data1,n2,(float)sr2,setlow,sethigh,setres,message);
/********************************************************************************/
/* OUTPUT */
/********************************************************************************/
for(ii=0;ii<n2;ii++) printf("%g\n",data1[ii]);
goto END;
/********************************************************************************/
/* CLEANUP AND EXIT */
/********************************************************************************/
END:
if(data1!=NULL) free(data1);
exit(0);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "macro.h"
int main(int argc, char *argv[])
{
char recvbuf[BUF_LEN];
ssize_t recvbytes;
int serverfd;
int clientfd;
struct sockaddr_in serveraddr;
struct sockaddr_in clientaddr;
socklen_t clientlen;
/* 面向连接的字节流, 套接字描述符一般值为3 */
if ((serverfd = socket(AF_INET, SOCK_STREAM, 0)) == - 1)
{
perror("socket error");
return 1;
}
/* 初始化客户端套接字地址 */
memset(&clientaddr, 0, sizeof(struct sockaddr));
/* 初始化服务器套接字地址 */
memset(&serveraddr, 0, sizeof(struct sockaddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(SERVER_PORT); // 主机字节序转换为网络字节序
serveraddr.sin_addr.s_addr = INADDR_ANY; // 套接字端点可以被绑定到所有的系统网络接口上
printf("server: serveraddr = %u\n", serveraddr.sin_addr.s_addr);
/* 套接字绑定地址 */
if (bind(serverfd, (struct sockaddr *)&serveraddr, sizeof(struct sockaddr)) == - 1)
{
perror("bind error");
return 1;
}
/* 接收套接字连接请求 */
if (listen(serverfd, CONNECT_NUM) == - 1)
{
perror("listen error");
return 1;
}
while (1)
{
clientlen = sizeof(struct sockaddr_in);
/* 获得连接请求并建立连接, 阻塞模式 */
printf("server: ready to accept\n");
if ((clientfd = accept(serverfd, (struct sockaddr *)&clientaddr, &clientlen)) == - 1)
{
perror ("accept error");
continue;
}
printf("server: got connection from %s\n", inet_ntoa(clientaddr.sin_addr));
/* 接收 */
printf("server: ready to receive\n");
if ((recvbytes = recv(clientfd, recvbuf, BUF_LEN, 0) ) == -1)
{
perror ("recv error");
return 1;
}
printf("server: recvbytes = %zd\n", recvbytes);
if (recvbytes)
{
recvbuf[recvbytes] = '\0';
printf("server: receive: %s\n", recvbuf);
sleep(3);
}
/* 发送 */
printf("server: ready to send\n");
if (send(clientfd, "Hi, I am server", 16, 0) == -1)
{
perror("send error");
return 1;
}
close(clientfd);
}
return 0;
}
|
C
|
#include <stdio.h>
#include "mkl.h"
#include <math.h>
#include "functions.h"
int main(void) {
int i;
int size = 1000;
int s_e_point = 50;
int fl_par = 50;
double *x;
//Allocate memmory
x = (double *) malloc(sizeof (double) * size);
if (x == NULL) exit(99);
x[0] = 0;
for( i = 1; i < size; i++) {
x[i] = x[i-1] + 0.1;
}
sigmoid(x, size, s_e_point, fl_par);
return (0);
}
|
C
|
//
// Created by Linus Bein Fahlander on 2018-03-05.
//
#include <stdint.h> /* Declarations of uint_32 and the like */
#include <pic32mx.h> /* Declarations of system-specific addresses etc */
#include "flow_control.h"
#include "../drivers/display/display_functions.h"
#include "../controllers/fingerprint_sensor.h"
#include "../state.h"
uint8_t last_state = 0xFF;
void main_flow(){
switch (CURRENT_STATE){
case DEFAULT_STATE:
default_flow();
break;
case CONFIG_MODE:
config_flow();
break;
case ALARM_ARMED:
armed_flow();
break;
case ALARM_TRIGGERED:
triggered_flow();
break;
case SCAN_NEXT:
scan_next_flow();
break;
case ERROR_STATE:
error_flow();
break;
}
}
void default_flow(){
display_string(0, "Ready to");
display_string(1, "be armed!");
display_string(2, "");
display_string(3, "");
display_update();
}
void config_flow(){
display_string(0, "Configure");
display_string(1, "Mode");
display_string(2, "");
display_string(3, "");
display_update();
}
void armed_flow(){
display_string(0, "Alarm is");
display_string(1, "Active!");
display_string(2, "");
display_string(3, "");
display_update();
}
void triggered_flow(){
display_string(0, "ALARM ALARM");
display_string(1, "ALARM ALARM");
display_string(2, "ALARM ALARM");
display_string(3, "PRESS FINGER!");
display_update();
}
void scan_next_flow(){
display_string(0, "Please scan");
display_string(1, "Your finger");
display_string(2, "Again");
display_string(3, "");
display_update();
}
void error_flow(){
display_string(0, "AN ERROR");
display_string(1, "HAS OCCURRED");
display_string(2, "PLEASE");
display_string(3, "RESTART");
display_update();
}
|
C
|
/*
* Create a named stream pipe.
*/
#include <sys/types.h>
#include <sys/stat.h>
int /* return 0 if OK, -1 on error */
ns_pipe(name, fd)
char *name; /* user-specified name to assign to the stream pipe */
int fd[2]; /* two file descriptors returned through here */
{
int omask;
struct stat statbuff;
/*
* First create an unnamed stream pipe.
*/
if (s_pipe(fd) < 0)
return(-1);
/*
* Now assign the name to one end (the first descriptor, fd[0]).
* To do this we first find its major/minor device numbers using
* fstat(2), then use these in a call to mknod(2) to create the
* filesystem entry. Beware that mknod(2) is restricted to root
* (for everything other than FIFOs).
* Under System VR3.2, the major value for the unnamed stream pipe
* corresponds to the major for "/dev/spx" and the minor value is
* whatever the "/dev/spx" clone driver assigned to make the
* major/minor unique.
*/
if (fstat(fd[0], &statbuff) < 0) {
close(fd[0]);
close(fd[1]);
return(-1);
}
unlink(name); /* in case it already exists */
omask = umask(0); /* assure mode is 0666 */
if (mknod(name, S_IFCHR | 0666, statbuff.st_rdev) < 0) {
close(fd[0]);
close(fd[1]);
umask(omask);
return(-1);
}
umask(omask); /* restore old umask value */
return(0); /* all OK */
}
|
C
|
/* This code is public domain
Authors: Nicolas Gast, 2013
nicolas.gast@epfl.ch
Jean-Yves Le Boudec, 2019
jean-yves.leboudec@epfl.ch
*/
#include <stdio.h> /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket(), bind(), and connect() */
#include <arpa/inet.h> /* for sockaddr_in and inet_ntoa() */
#include <stdlib.h> /* for atoi() and exit() */
#include <string.h> /* for memset() */
#include <unistd.h> /* for close() */
#include <netdb.h>
#include <stdlib.h> // atoi, atof
#include <sys/time.h> // gettimeofday
#include<signal.h>
#include<errno.h>
#define TEN_TO_6 1000000
#define MAX_PACKET_SIZE 1000
#define KILO 1000.0
#define SMALL_PACKET 125
#define LARGE_PACKET 1000
#define DEFAULT_RATE 100.0
#define SMALL_RATE 50.0
int continue_sending = 1;
static void catch_function(int signal){
(void)signal; // to suppress the warning about unused variable
continue_sending = 0;
}
double get_time() {
struct timeval t;
gettimeofday(&t, 0);
return t.tv_sec + (double) t.tv_usec / TEN_TO_6;
}
int main(int argc, char **argv) {
signal(SIGINT, catch_function);
struct hostent *dst_ptr;
struct sockaddr_in dst_addr;
int sockfd, i, slen=sizeof(dst_addr);
char * dst_name; short port;
char data_buf[MAX_PACKET_SIZE]; for (i=0;i<MAX_PACKET_SIZE;i++) data_buf[i]=1;
// We will try to send packets of size "packet_size" every "waiting_time" milliseconds
double rate = DEFAULT_RATE; // default
int packet_size; // in Bytes
double waiting_time; // in milliseconds
if (argc < 3) {
fprintf(stderr, "Usage: %s <dst ip> <port> [rate kb/s]\n", argv[0]);
exit(1);
}
else {
dst_name = argv[1];
port = atoi(argv[2]);
if (argc >= 4){
rate = atof(argv[3]);
}
}
// We now set the packet_size and the waiting_time time as a function of the rate.
// if the rate<SMALL_RATE, we use packets of size SMALL_PACKET
// otherwise, packets of size LARGE_PACKET
if (rate < SMALL_RATE) {
packet_size = SMALL_PACKET;
}
else {
packet_size = LARGE_PACKET;
}
waiting_time = 8*packet_size/(KILO*rate);
/* create socket */
if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
perror ("socket");
exit(1);
}
if ((dst_ptr = gethostbyname(dst_name)) == 0) {
perror ("gethostbyname");
exit(1);
}
bcopy(dst_ptr->h_addr, (char *)&dst_addr.sin_addr, dst_ptr->h_length);
dst_addr.sin_family = AF_INET ;
dst_addr.sin_port = htons(port) ;
double start_time = get_time();
double last_print_time = start_time;
double next_time = start_time+waiting_time;
int nb_packets = 0, bytes_sent=0;
int sent_len, recv_len;
/* Now, we try to send one packet every "waiting_time" */
while(continue_sending)
{
// First, we send a packet
sprintf(data_buf,"%d\n",nb_packets+1); // we send the packet number in the data
if( (sent_len = sendto(sockfd,data_buf,packet_size,0,
(const struct sockaddr*) &dst_addr, slen)) == -1) {
perror("sendto");
exit(1);
}
bytes_sent += sent_len;
nb_packets ++;
// Every second, we print how many packets were sent
if (get_time() >= last_print_time+1){
printf("%5.1fs - sent:%6d pkts, %6.1f kb/s\n", get_time()-start_time, nb_packets, bytes_sent*8/ (get_time()-last_print_time) / KILO);
bytes_sent= 0;
last_print_time = get_time();
}
// Then, we add a wait to send a packet every x ms.
double time_to_wait = next_time-get_time();
if (time_to_wait > 0 ) usleep(TEN_TO_6 *time_to_wait);
next_time +=waiting_time;
}
/* When we receive ^C, we stop sending at full rate.
We send messages that start with 0 every 0.1s to notify the server.
until we receive an ack from the server (or another ^C) */
// First, we set the timeout to 0.1 second.
struct timeval tv; tv.tv_sec=0; tv.tv_usec = 0.1*TEN_TO_6;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(tv) );
// Now, we keep sending until we receive an ack or another ^C
continue_sending = 1;
while( continue_sending) {
data_buf[0]=0;
if( sendto(sockfd,data_buf,packet_size,0,(const struct sockaddr*) &dst_addr, slen) == -1) {
perror("sendto");
exit(1);
}
if ( (recv_len = continue_sending = recv(sockfd,data_buf,MAX_PACKET_SIZE,0)) < 0 ){
if (!(errno == EWOULDBLOCK) ) { // if error is not caused by TIMEOUT, we die.
perror("recv");
exit(1);
}
}
else { // if we received an ack, we stop sending
continue_sending = 0;
}
}
printf("packets sent = %d, avg rate=%6.1fkb/s\n", nb_packets, 8*packet_size*nb_packets/(get_time()-start_time)/KILO);
close (sockfd);
return 0;
}
|
C
|
//
// RingList.c
// Lab2
//
// Created by on 4/7/16.
// Copyright 2016 Sergey fedorenko. All rights reserved.
//
//
#include "RingList.h"
#include "Node.h"
#include <stdlib.h>
// Constants
const int kListError = -1;
//Create/delete a list
RingList *CreateList()
{
RingList *theList = (RingList *)malloc(sizeof(RingList));
theList->head = NULL;
theList->tail = theList->head;
theList->count = 0;
return theList;
}
RingList *doList()
{
printf("Start to create a Ring list \n");
IntNode *theNode0 = CreateNode(10);
IntNode *theNode1 = CreateNode(2);
IntNode *theNode2 = CreateNode(3);
IntNode *theNode4 = CreateNode(5);
IntNode *theNode5 = CreateNode(30);
IntNode *theNode6 = CreateNode(4);
RingList *theList = CreateList();
AddNode(theList, theNode0);
AddNode(theList, theNode1);
AddNode(theList, theNode2);
AddNode(theList, theNode4);
AddNode(theList, theNode5);
AddNode(theList, theNode6);
printf("number of elements: %d\n", CountList(theList));
return theList;
}
void FreeList(RingList *aList)
{
// Check the input parameter
if (NULL == aList)
{
return;
}
//1. Remove all elements
IntNode *theNode = aList->head;
while (NULL != theNode)
{
IntNode *theNodeFree = theNode;
theNode = theNode->nextNode;
free(theNodeFree);
}
//2. Free memory for the List structure
free(aList);
}
IntNode *AddNode(RingList *aList, IntNode *aNewNode)
{
// Check the input parameter
if (NULL == aList || NULL == aNewNode)
{
return NULL;
}
if (NULL == aList->head && NULL == aList->tail)
{
aList->head = aList->tail = aNewNode;
}
else
{
IntNode *theTail = aList->tail;
aList->tail = aNewNode;
if (NULL != theTail)
{
theTail->nextNode = aList->tail;
}
}
aList->count += 1;
return aNewNode;
}
int CountList(const RingList *aList)
{
int theResult = kListError;
if (NULL != aList)
{
theResult = aList->count;
}
return theResult;
}
IntNode *NodeAtIndex(const RingList *aList, int anIndex)
{
IntNode *theResult = NULL;
if (NULL != aList && anIndex < aList->count)
{
int i = 0;
IntNode *theNode = aList->head;
do
{
if (i == anIndex)
{
theResult = theNode;
break;
}
i++;
theNode = theNode->nextNode;
} while (NULL != theNode);
}
return theResult;
}
IntNode *InsertNodeAtIndex(RingList *aList, IntNode *aNewNode, int anIndex) {
if (NULL == aList || NULL == aNewNode || anIndex>aList->count + 1)
{
return NULL;
}
else
{
if (0 == anIndex) {
aNewNode->nextNode = aList->head;
aList->head = aNewNode;
aList->count++;
return(aNewNode);
}
else {
IntNode *theNode = NodeAtIndex(aList, anIndex);
IntNode *PreviosNode = NodeAtIndex(aList, anIndex - 1);
aNewNode->nextNode = PreviosNode->nextNode;
PreviosNode->nextNode = aNewNode;
aList->count++;
return aNewNode;
}
}
}
IntNode *RemovedNodeAtIndex(RingList *aList, int anIndex) {
if (anIndex < aList->count) {
if ((NULL == aList) || (anIndex>aList->count))
{
return NULL;
}
else
{
if (anIndex == 0) {
IntNode *theNode = NodeAtIndex(aList, anIndex);
aList->head = NodeAtIndex(aList, anIndex + 1);
aList->count -= 1;
return theNode;
}
else {
IntNode *theNode = NodeAtIndex(aList, anIndex);
IntNode *PreviosNode = NodeAtIndex(aList, anIndex - 1);
if (anIndex == aList->count) aList->tail = PreviosNode;
PreviosNode->nextNode = theNode->nextNode;
aList->count -= 1;
return theNode;
}
}
}
}
/*IntNode *findMinNode(const RingList *inputList) {
IntNode *currentNode = inputList->head;
IntNode *minNode = currentNode;
do {
if (currentNode->value <= minNode->value) {
minNode = currentNode;
}
currentNode = currentNode->nextNode;
} while (NULL != currentNode);
return minNode;
}
IntNode *findMaxNode(const RingList *aList) {
IntNode *currentNode = aList->head;
IntNode *maxNode = currentNode;
do {
if (currentNode->value >= maxNode->value) {
maxNode = currentNode;
}
currentNode = currentNode->nextNode;
} while (NULL != currentNode);
return maxNode;
}
RingList *swapNodeAtList(RingList *inputList) {
IntNode *minNode = findMinNode(inputList);
IntNode *maxNode = findMaxNode(inputList);
int minvalue = minNode->value;
minNode->value = maxNode->value;
maxNode->value = minvalue;
return inputList;
}
void doSortingValue(IntNode *theList) {
int a, min;
int j = 0;
int InMin = 0;
int InMax = 0;
int RemovedAtIndex = 0;
a = CountList(theList);
for (int j = 0; j < a; j++) {
IntNode *TheMinNode = NodeAtIndex(theList, InMin);
min = NodeAtIndex(theList, InMin)->value;
for (int k = InMin; k < a; k++)
{
if (min >= TheMinNode->value)
{
min = TheMinNode->value;
RemovedAtIndex = k;
}
TheMinNode = TheMinNode->nextNode;
}
InsertNodeAtIndex(theList, RemovedNodeAtIndex(theList, RemovedAtIndex), InMin);
InMin++;
}
}
*/
//Homework3
void theSelectionSorting(RingList*theList, int Count)
{
int j = 0;
int min;
int IndexMinimum = 0;
int IndexRemoved = 0;
for (int j = 0; j < Count; j++) {
IntNode *MinNode = NodeAtIndex(theList, IndexMinimum);
min = NodeAtIndex(theList, IndexMinimum)->value;
for (int k = IndexMinimum; k < Count; k++)
{
if (min >= MinNode->value)
{
min = MinNode->value;
IndexRemoved = k;
}
MinNode = MinNode->nextNode;
}
InsertNodeAtIndex(theList, RemovedNodeAtIndex(theList, IndexRemoved), IndexMinimum);
IndexMinimum++;
}
printf("\nselectionSort\n");
}
|
C
|
/* ************************************************************************
*
* This file implements the json parser.
*
* Working example and terminology
* ================================
* We use following json to depict
* how it works:
* [1, 2, {"key": 3.4}]
*
* We call [...] as *array*, and {...} as *hashtab*. Array and hashtab are
* *composite objects*, and number/string/boolean/null are *primitive objects*.
*
* This json snippet has two composite objects:
* - O2: is a hash-table having only one element with key being "key", and
* value being 3.4.
* - O1: is a array containing three elements, i.e. 1, 2 and O2.
*
* O2 is *nested* in O1, and O1 is O2's *immediate nesting* composite object.
*
* How it works
* =============
* The parser walks the input json from left to right, calling scaner to get a
* token at a time. The scaner recognizes following tokens in order:
*
* token type value
* ---------------------------
* char '['
* number 1
* char ','
* number 2
* char ','
* cahr '{'
* string "key"
* ....
*
* At the heart of the parser is a *parsing-stack*, which push a level when
* seeing the starting delimiter of a composite object (e.g. seeing '[' of
* an array), and pop until the closing delimiter of the same composite object
* is seen). So, the parse-stack is in essence mimicking the nesting
* relationship. Actually in our implementation, the stack element contains
* a data structure keeping track of the current composite object being
* processed.
*
* The result of the parser is organized in reverse-nesting order linked
* in a singly-linked list. See the comment to jp_parse() in ljson_parser.h
* for details.
*
* ************************************************************************
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <inttypes.h>
#include <ctype.h>
#include "util.h"
#include "mempool.h"
#include "scaner.h"
#include "parser.h"
#ifdef DEBUG
static int verfiy_reverse_nesting_order(obj_t* parse_result);
#endif
/* **************************************************************************
*
* About parse-stack.
*
* **************************************************************************
*/
static inline void
init_obj(obj_t* obj, obj_ty_t ty) {
obj->next = 0;
obj->obj_ty = ty;
obj->elmt_num = 0;
}
static inline void
init_composite_obj(obj_composite_t* obj, obj_ty_t ty, uint32_t id) {
init_obj(&obj->common, ty);
obj->subobjs = 0;
obj->id = id;
}
static inline composite_state_t*
alloc_composite_state(parser_t* parser) {
composite_state_t* cs;
cs = MEMPOOL_ALLOC_TYPE(parser->mempool, composite_state_t);
return cs;
}
static void
pstack_init(parser_t* parser) {
composite_state_t* cs = &parser->parse_stack;
init_composite_obj(&cs->obj, OT_ROOT, 0);
cs->next = 0;
cs->prev = cs; /* this is *top* */
}
int
pstack_push(parser_t* parser, obj_ty_t obj_ty, int init_state) {
/* Step 1: Allocate an stack element */
composite_state_t* cs = alloc_composite_state(parser);
if (unlikely(!cs))
return 0;
/* Step 2: Initialize the corresponding composite object. */
obj_composite_t* cobj = &cs->obj;
init_composite_obj(cobj, obj_ty, parser->next_cobj_id++);
/* link the composite objects in reverse-nesting order */
cobj->reverse_nesting_order = (obj_composite_t*)(void*)parser->result;
parser->result = &cobj->common;
/* Step 3: Push one level */
cs->parse_state = init_state;
cs->next = 0;
composite_state_t* root = &parser->parse_stack;
composite_state_t* top = root->prev;
cs->prev = top;
root->prev = cs; /* update the "top" */
return 1;
}
composite_state_t*
pstack_pop(parser_t* parser) {
composite_state_t* ps = &parser->parse_stack;
composite_state_t* top = ps->prev;
composite_state_t* new_top = top->prev;
new_top->next = 0;
ps->prev = new_top;
return new_top;
}
/***************************************************************************
*
* Emit Objects
*
***************************************************************************
*/
/* Convert the primitive token to primitive object */
static inline obj_t*
cvt_primitive_tk(mempool_t* mp, token_t* tk) {
ASSERT(tk_is_primitive(tk));
obj_primitive_t* obj = MEMPOOL_ALLOC_TYPE(mp, obj_primitive_t);
if (unlikely(!obj))
return 0;
ASSERT((((int)TT_INT64 == (int)OT_INT64) &&
((int)TT_FP == (int)OT_FP) &&
((int)TT_STR == (int)OT_STR) &&
((int)TT_BOOL == (int)OT_BOOL) &&
((int)TT_NULL == (int)OT_NULL)));
obj->common.obj_ty = tk->type;
obj->common.str_len = tk->str_len;
obj->int_val = tk->int_val;
return &obj->common;
}
void
insert_subobj(obj_composite_t* nesting, obj_t* nested) {
nested->next = nesting->subobjs;
nesting->subobjs = nested;
nesting->common.elmt_num ++;
}
int
emit_primitive_tk(mempool_t* mp, token_t* tk,
obj_composite_t* nesting_cobj) {
obj_t* obj = cvt_primitive_tk(mp, tk);
if (obj) {
insert_subobj(nesting_cobj, obj);
return 1;
}
return 0;
}
/***************************************************************************
*
* Parser driver
*
***************************************************************************
*/
obj_t*
parse(parser_t* parser, const char* json, uint32_t json_len) {
scaner_t* scaner = &parser->scaner;
const char* json_end = scaner->json_end;
pstack_init(parser);
token_t* tk = sc_get_token(scaner, json_end);
token_ty_t tk_ty = tk->type;
/* case 1: The input json starts with delimiter of composite objects
* (i.e. array/hashtab).
*/
if (tk_ty == TT_CHAR) {
int succ = 0;
char c = tk->char_val;
if (c == '{') {
succ = start_parsing_hashtab(parser);
} else if (c == '[') {
succ = start_parsing_array(parser);
} else {
set_parser_err_fmt(parser, "Unknow object starting with '%c'", c);
return 0;
}
while (succ) {
composite_state_t* top = pstack_top(parser);
obj_ty_t ot = top->obj.common.obj_ty;
if (ot == OT_HASHTAB) {
succ = parse_hashtab(parser);
} else if (ot == OT_ARRAY) {
succ = parse_array(parser);
} else {
ASSERT(ot == OT_ROOT);
break;
}
}
if (unlikely(!succ))
return 0;
token_t* end_tk = sc_get_token(scaner, json_end);
if (end_tk->type != TT_END) {
goto trailing_junk;
}
return parser->result;
}
/* case 2: The input jason is empty */
if (unlikely(tk_ty == TT_END)) {
parser->err_msg = "Input json is empty";
return 0;
}
/* case 3: The input starts with a primitive object. I don't know if it
* conforms to spec or not.
*/
if (tk_is_primitive(tk)) {
parser->result = cvt_primitive_tk(parser->mempool, tk);
if (sc_get_token(scaner, json_end)->type == TT_END) {
return parser->result;
}
}
trailing_junk:
parser->result = 0;
set_parser_err(parser, "Extraneous stuff");
return 0;
}
static void
reset_parser(parser_t* parser, const char* json, uint32_t json_len) {
mempool_t* mp = parser->mempool;
mp_free_all(mp);
pstack_init(parser);
sc_init_scaner(&parser->scaner, mp, json, json_len);
parser->result = 0;
parser->err_msg = 0;
parser->next_cobj_id = 1;
}
/****************************************************************************
*
* Implementation of the exported functions
*
***************************************************************************
*/
struct json_parser*
jp_create(void) {
parser_t* p = (parser_t*)malloc(sizeof(parser_t));
if (unlikely(!p))
return 0;
mempool_t* mp = mp_create();
if (unlikely(!mp))
return 0;
p->mempool = mp;
p->result = 0;
p->err_msg = "Out of Memory"; /* default error message :-)*/
pstack_init(p);
return (struct json_parser*)(void*)p;
}
obj_t*
jp_parse(struct json_parser* jp, const char* json, uint32_t len) {
parser_t* parser = (parser_t*)(void*)jp;
reset_parser(parser, json, len);
obj_t* obj = parse(parser, json, len);
ASSERT(verfiy_reverse_nesting_order(obj));
return obj;
}
void
jp_destroy(struct json_parser* p) {
parser_t* parser = (parser_t*)(void*)p;
mp_destroy(parser->mempool);
free((void*)p);
}
/* *****************************************************************************
*
* Debugging, error handling and other cold code
*
* *****************************************************************************
*/
void __attribute__((format(printf, 2, 3), cold))
set_parser_err_fmt(parser_t* parser, const char* fmt, ...) {
if (parser->err_msg)
return;
int buf_len = 250;
char* buf = MEMPOOL_ALLOC_TYPE_N(parser->mempool, char, buf_len);
if (!buf) {
parser->err_msg = "OOM";
return;
}
parser->err_msg = buf;
scaner_t* scaner = &parser->scaner;
/* In case error take place in scaner, we should go for scaner's
* error message.
*/
if (scaner->err_msg) {
snprintf(buf, buf_len, "%s", scaner->err_msg);
return;
}
int loc_info_len = snprintf(buf, buf_len, "(line:%d,col:%d) ",
scaner->line_num, scaner->col_num);
buf += loc_info_len;
buf_len -= loc_info_len;
va_list vl;
va_start(vl, fmt);
vsnprintf(buf, buf_len, fmt, vl);
va_end(vl);
}
void __attribute__((cold))
set_parser_err(parser_t* parser, const char* str) {
if (!parser->err_msg)
set_parser_err_fmt(parser, "%s", str);
}
static void __attribute__((cold))
dump_primitive_obj (FILE* f, obj_t* the_obj) {
obj_primitive_t* obj = (obj_primitive_t*)(void*)the_obj;
switch (the_obj->obj_ty) {
case OT_INT64:
fprintf(f, "%" PRIi64, obj->int_val);
break;
case OT_FP:
fprintf(f, "%.16f", obj->db_val);
break;
case OT_STR:
{
int idx = 0;
int len = the_obj->str_len;
fputc('"', f);
for (; idx < len; idx++) {
char c = obj->str_val[idx];
if (isprint(c)) {
fputc(c, f);
} else {
fprintf(f, "\\%#02x", c);
}
}
fputc('"', f);
}
break;
case OT_BOOL:
fputs(obj->int_val ? "true" : "false", f);
break;
case OT_NULL:
fputs("null", f);
break;
default:
ASSERT(0 && "NOT Primitive");
break;
}
}
void __attribute__((cold))
dump_composite_obj(FILE* f, obj_composite_t* cobj) {
obj_ty_t type = cobj->common.obj_ty;
if (type != OT_ARRAY && type != OT_HASHTAB) {
fprintf(f, "unknown composite type %d\n", (int)type);
return;
}
obj_t* elmt_slist = cobj->subobjs;
int elmt_num = cobj->common.elmt_num;
obj_t** elmt_vect = (obj_t**)malloc(sizeof(obj_t*) * elmt_num);
int i = elmt_num - 1;
while (elmt_slist) {
elmt_vect[i] = elmt_slist;
elmt_slist = elmt_slist->next;
i--;
}
if (i != -1) {
free(elmt_vect);
fprintf(f, "the numbers of elements disagree\n");
return;
}
if (type == OT_ARRAY) {
fprintf (f, "[ (id:%d) ", cobj->id);
int i;
for(i = 0; i < elmt_num; i++) {
obj_t* elmt = elmt_vect[i];
if (elmt->obj_ty <= OT_LAST_PRIMITIVE) {
dump_primitive_obj(f, elmt);
} else {
int id = ((obj_composite_t*)(void*)elmt)->id;
fprintf(f, "obj-%d", id);
}
if (i != elmt_num - 1)
fputs(", ", f);
}
fputs("]\n", f);
} else {
ASSERT(type == OT_HASHTAB);
ASSERT((elmt_num & 1) == 0);
fprintf(f, "{ (id:%d) ", cobj->id);
int i;
for(i = 0; i < elmt_num; i+=2) {
obj_t* key = elmt_vect[i];
obj_t* val = elmt_vect[i+1];
dump_primitive_obj(f, key);
fputc(':', f);
if (val->obj_ty <= OT_LAST_PRIMITIVE) {
dump_primitive_obj(f, val);
} else {
int id = ((obj_composite_t*)(void*)val)->id;
fprintf(f, "obj-%d", id);
}
if (i != elmt_num - 2)
fputs(", ", f);
}
fputs("}\n", f);
}
free(elmt_vect);
}
void __attribute__((cold))
dump_obj(FILE* f, obj_t* obj) {
if (!obj) {
fprintf(f, "null\n");
return;
}
obj_ty_t type = obj->obj_ty;
if (type <= OT_LAST_PRIMITIVE) {
dump_primitive_obj(f, obj);
fputc('\n', f);
} else {
obj_composite_t* cobj = (obj_composite_t*)(void*)obj;
for (; cobj; cobj = cobj->reverse_nesting_order) {
dump_composite_obj(f, cobj);
}
}
}
const char* __attribute__((cold))
jp_get_err(struct json_parser* p) {
parser_t* parser = (parser_t*)(void*)p;
return parser->err_msg;
}
#ifdef DEBUG
static int
verfiy_reverse_nesting_order(obj_t* parse_result) {
if (!parse_result)
return 1;
obj_ty_t type = parse_result->obj_ty;
if (type <= OT_LAST_PRIMITIVE)
return 0;
obj_composite_t* cobj = (obj_composite_t*)(void*)parse_result;
int obj_cnt = 1;
int first_id, last_id;
first_id = last_id = cobj->id;
/* loop over all composite-object in the the reverse-nesting order */
for (cobj = cobj->reverse_nesting_order;
cobj != 0;
cobj = cobj->reverse_nesting_order) {
if (cobj->id != last_id - 1)
return 0;
last_id = cobj->id;
obj_cnt++;
}
if (last_id != 1 || obj_cnt != first_id)
return 0;
return 1;
}
#endif
|
C
|
#ifndef ESTRUTURAS
#define ESTRUTURAS
typedef struct NoArvore
{
char temValor;
unsigned char letra;
unsigned int quantidade;
struct NoArvore *esq;
struct NoArvore *dir;
} NoArvore;
typedef struct NoFila
{
NoArvore *dado;
struct NoFila *prox;
} NoFila;
typedef struct
{
char *codigo;
char qtosBits;
}CodLetra;
/*a partir de dois nós, faz uma raiz com o primeiro na esquerda e o segundo na direita*/
NoArvore* juntarNos(NoArvore *noUm, NoArvore *noDois)
{
NoArvore *raiz = (NoArvore*)malloc(sizeof(NoArvore));
raiz->quantidade = (noUm->quantidade)+(noDois->quantidade);
raiz->temValor = 0;
raiz->esq = noUm;
raiz->dir = noDois;
return raiz;
}
/*tira o primeiro elemento da fila*/
NoFila* desenfileirar(NoFila *inicio)
{
NoFila *noAuxiliar = (NoFila*)malloc(sizeof(NoFila));
*noAuxiliar = *inicio;
noAuxiliar->prox = NULL;
*inicio = *(inicio->prox);
return noAuxiliar;
}
/*insere um elemento na fila sempre antes do que é maior que ele, e caso não houver, no fim*/
void inserirNaFila(NoArvore *novoNo, NoFila *inicio)
{
NoFila *novoNoFila;
novoNoFila = (NoFila*)malloc(sizeof(NoFila));
novoNoFila->dado = novoNo;
novoNoFila->prox = NULL;
if(inicio->dado == NULL)
{
inicio->dado = novoNo;
}
else
{
if((inicio->dado)->quantidade >= (novoNoFila->dado)->quantidade)
{
NoFila noAuxiliar = *inicio; /*um n� fila recebe o conte�do do ponteiro inicio*/
*inicio = *novoNoFila; /*o conteudo do inicio passa a ser o que � novoNoFila*/
inicio->prox = (NoFila*)malloc(sizeof(NoFila)); /*o prox de inicio recebe um malloc*/
*(inicio->prox) = noAuxiliar; /*o conteudo do prox de inicio recebe o noAuxiliar*/
}
else
{
NoFila *noAtual = inicio; /*Ponteiro que caminha pela fila*/
char achou = 0;
while(achou == 0)
{
if((noAtual->dado)->quantidade <= (novoNoFila->dado)->quantidade)
{
if(noAtual->prox == NULL)
{
achou = 1;
noAtual->prox = novoNoFila; /*Conte�do do ponteiro passa a ser o novo n� fila*/
}
else if(((noAtual->prox)->dado)->quantidade > (novoNoFila->dado)->quantidade)
{
achou = 1;
NoFila noAuxiliar = *(noAtual->prox); /*noAuxiliar recebe conteudo de prox de noAtual*/
*(noAtual->prox) = *novoNoFila; /*conteudo de prox passa a ser novoNoFila*/
noAtual->prox->prox = (NoFila*)malloc(sizeof(NoFila)); /*aloca prox de novoNoFila*/
*(noAtual->prox->prox) = noAuxiliar; /*guarda noAuxiliar no prox*/
}
}
noAtual = noAtual->prox;
}
}
}
}
/*vetor de códigos das letras*/
CodLetra codigosLetras[256];
/*percorre arvore recursivamente para formar os códigos das letras*/
void codificarLetras(NoArvore* atual, char cod, char indice, char codigo[])
{
codigo[indice] = cod;
if(atual->temValor == 0)
{
codificarLetras(atual->esq, 0, indice+1, codigo);
codificarLetras(atual->dir, 1, indice+1, codigo);
}
else
{
char i;
codigosLetras[atual->letra].codigo = (char*)malloc((indice+1)*sizeof(char));
for(i=0; i<=indice; i++)
codigosLetras[atual->letra].codigo[i] = codigo[i];
codigosLetras[atual->letra].qtosBits = indice+1;
}
}
/*converte a fila de prioridades numa arvore*/
void converterParaArvore(NoFila *inicio)
{
while(inicio->prox!= NULL)
{
if(inicio->prox->prox == NULL)
{
NoFila *dir = (NoFila*)malloc(sizeof(NoFila));
NoFila *esq = desenfileirar(inicio);
*dir = *inicio;
dir->dado = (NoArvore*)malloc(sizeof(NoArvore));
*(dir->dado) = *(inicio->dado);
inicio->dado->temValor = 0;
inicio->dado->quantidade = (dir->dado->quantidade) + (esq->dado->quantidade);
inicio->dado->esq = esq->dado;
inicio->dado->dir = dir->dado;
inicio->prox = NULL;
}
else
{
NoFila *esq = desenfileirar(inicio);
NoFila *dir = desenfileirar(inicio);
inserirNaFila(juntarNos(esq->dado, dir->dado), inicio);
}
}
}
/*desaloca todos os ponteiros da arvore*/
void limparArvore(NoArvore *atual)
{
if(atual != NULL)
{
NoArvore *esq = atual->esq;
NoArvore *dir = atual->dir;
free(atual);
limparArvore(esq);
limparArvore(dir);
}
}
#endif
|
C
|
#include <stdio.h>
int main(){
int a = 1;
int b = 2;
int c = 3;
unsigned int d = 3;
printf("---------------------------------------------\n");
printf("and or xor \n\n");
printf("0x%08x | 0x%08x = 0x%08x\n",a,b, a|b);
printf("0x%08x & 0x%08x = 0x%08x\n",a,b, a&b);
printf("0x%08x ^ 0x%08x = 0x%08x\n",a,b, a^b);
printf("~0x%08x = 0x%08x\n",a,~a);
printf("---------------------------------------------\n");
printf("signed Ʈ \n\n");
printf("signed int : 0x%08x >> 1 = 0x%08x\n",c,c >> 1);
printf("signed int : 0x%08x << 1 = 0x%08x\n",c,c << 1);
printf("signed int : 0x%08x >> 1 = 0x%08x\n",~c,~c >> 1);
printf("---------------------------------------------\n");
printf("unsigned Ʈ \n\n");
printf("unsigned int : 0x%08x >> 1 = 0x%08x\n",d,d >> 1);
printf("unsigned int : 0x%08x << 1 = 0x%08x\n",d,d << 1);
printf("unsigned int : 0x%08x >> 1 = 0x%08x\n",~d,~d >> 1);
return 0;
}
|
C
|
#include <stdlib.h>
#include "binary_heap_pro.h"
#define ROOT_IDX 0u
#define LEFT_CHILD(x) (2u * x) + 1u
#define RIGHT_CHILD(x) 2u * (x + 1u)
#define PARENT(x) (x - 1u) / 2u
/* I'm assuming a decent compiler will inline the next two functions; if not they can be made #define macros. */
void exch(unsigned int j, unsigned int k, Item arr[], unsigned int lookup[]) {
int priority = arr[j].priority;
int data = arr[j].data;
unsigned int key1 = arr[j].key;
unsigned int key2 = arr[k].key;
arr[j].priority = arr[k].priority;
arr[j].data = arr[k].data;
arr[j].key = key2;
lookup[key2] = j;
arr[k].priority = priority;
arr[k].data = data;
arr[k].key = key1;
lookup[key1] = k;
}
unsigned int pq_size(PQ *pq) {
return pq->first_available;
}
unsigned int capacity(PQ *pq) {
return pq->capacity;
}
int less(unsigned int j, unsigned int k, Item arr[]) {
return (arr[j].priority <= arr[k].priority);
}
void swim(unsigned int k, Item arr[], unsigned int lookup[]) {
while (k > ROOT_IDX && less (k, PARENT(k), arr)) {
exch(k, PARENT(k), arr, lookup);
k = PARENT(k);
}
}
void sink (unsigned int k, Item arr[], unsigned int first_available, unsigned int lookup[]) {
while (LEFT_CHILD(k) < first_available) { /* Requirement that capacity <= MAX_SIZE be of reasonable size */
unsigned j = LEFT_CHILD(k);
if (j+1 < first_available && less(j+1, j, arr)) j++; /* careful with j+1 overflow? */
if (less(k, j, arr)) break;
exch(k, j, arr, lookup);
k = j;
}
}
unsigned int pq_insert_nc(PQ *pq, int priority, int data) {
unsigned int fa = pq->first_available;
Item* cells = pq->heap_cells;
unsigned int key = cells[fa].key;
cells[fa].priority = priority;
cells[fa].data = data;
swim(fa, cells, pq->key_table);
pq->first_available = fa + 1;
return key;
}
void pq_edit_priority(PQ *pq, int key, int newpri) {
unsigned int* table = pq->key_table;
Item* cells = pq->heap_cells;
unsigned int target = table[key];
// if (target >= pq_size(pq)) return;
// I will now know that this key refers to a valid member of the heap
int oldpri = cells[target].priority;
cells[target].priority = newpri;
if (newpri <= oldpri) swim(target, cells, table);
// potentially unnecessary swimming in case of equality
else sink (target, cells, pq->first_available, table);
}
// post condition: either the key was in the heap and we did all this stuff,
// or we did nothing
void pq_remove_min_nc(PQ *pq, Item* item) {
/* unsigned int fa = pq->first_available - 1;
Item* cells = pq->heap_cells;
unsigned* lookup = pq->key_table;
exch(ROOT_IDX, fa, cells, lookup);
item->priority = cells[fa].priority;
item->data = cells[fa].data;
item->key = cells[fa].key;
sink(ROOT_IDX, cells, fa, lookup);
pq->first_available = fa; */
pq->first_available--;
exch(ROOT_IDX, pq->first_available, pq->heap_cells, pq->key_table);
item->priority = pq->heap_cells[pq->first_available].priority;
item->data = pq->heap_cells[pq->first_available].data;
item->key = pq->heap_cells[pq->first_available].key;
sink(ROOT_IDX, pq->heap_cells, pq->first_available, pq->key_table);
}
unsigned int pq_insert(PQ *pq, int priority, int data) {
if (pq->first_available == pq->capacity) return 0; /* Hrm, maybe should signal error or grow heap or whatever... */
return pq_insert_nc(pq, priority, data);
}
Item* pq_remove_min(PQ *pq) {
if (pq->first_available == ROOT_IDX) return 0;
Item* item = (Item*) malloc(sizeof(Item));
pq_remove_min_nc(pq, item);
return item;
}
PQ* pq_make(unsigned int size) { /* could take a size parameter I suppose... */
PQ *pq = (PQ*) mallocN(sizeof(PQ));
unsigned int* table = (unsigned int*) mallocN(sizeof(unsigned int) * size);
Item* arr = (Item*) mallocN(sizeof(Item) * size);
int i;
for (i = 0; i < size; i++) {
arr[i].key = i;
arr[i].priority = 0;
arr[i].data = 0;
table[i] = i;
}
pq->capacity = size;
pq->first_available = 0;
pq->heap_cells = arr;
pq->key_table = table;
return pq;
}
void pq_free (PQ *pq) {
freeN(pq->key_table);
freeN(pq->heap_cells);
freeN(pq);
}
/* could imagine adding some additonal functions:
heapify
?
*/
|
C
|
/*
* Say ip
* Written by Chun-Hsiang Chao
* Date:20191002
*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void say_char(char c){
FILE *in,*out;
char filename[100];
if(c=='.'){
sprintf(filename,"/home/pi/Music/voice/dot.pcm",c);
}
else{
sprintf(filename,"/home/pi/Music/voice/%c.pcm",c);
}
in=fopen(filename,"rb");
out=fopen("/dev/dsp","wb");
while(fscanf(in,"%c",&c)!=EOF){
fprintf(out,"%c",c);
}
fclose(in);
sleep(1);
fclose(out);
}
int main(int argc, char *argv[ ]){
FILE *read_fp;
char buffer[1000];
int chars_read;
char pattern[]="inet";
char *point;
char ip[20];
int i=5;
int j=0;
read_fp = popen("ifconfig wlan0", "r");
if (read_fp != NULL) {
chars_read = fread(buffer, sizeof(char), sizeof(buffer)-1, read_fp);
if (chars_read > 0) {
buffer[chars_read] = '\0';
//printf("Output was:-\n%s\n", buffer);
point=strstr(buffer,pattern);
if(point!=NULL){
//printf("%s\n",point);
while(1){
if(point[i]!=' '){
ip[j]=point[i];
i++;
j++;
}
else{
ip[j]='\0';
break;
}
}
}
}
pclose(read_fp);
for(i=0;i<strlen(ip);i++){
say_char(ip[i]);
}
printf("%s\n",ip);
}
exit(0);
}
|
C
|
#include "debug.h"
#include <stdio.h>
#include <string.h>
#include "array.h"
static const size_t string_buffer_size = 1 * 1024 * 1024; // 1 MB
// static char string_buffer[string_buffer_size];
static array g_string_buffer;
static const size_t error_message_count = 32;
static const char *error_messages[error_message_count]; // ring buffer
static int next_error_message_id = 0;
void debug_init() {
array_init(&g_string_buffer, 1, string_buffer_size);
char *p = g_string_buffer.ptr;
p[0] = '\0';
}
void debug_clear_all() {
next_error_message_id = 0;
g_string_buffer.size = 0;
}
void log_error(const char *msg) {
size_t len = strlen(msg);
if (g_string_buffer.size + len + 1 >= g_string_buffer.capacity) {
puts("[DEBUG] string buffer is full\n");
return;
}
char *p = g_string_buffer.ptr + g_string_buffer.size;
memcpy(p, msg, len);
p[len] = '\0';
g_string_buffer.size += len + 1;
error_messages[next_error_message_id] = p;
next_error_message_id++;
next_error_message_id %= error_message_count;
assert(strcmp(p, msg) == 0);
puts(msg);
}
bool debug_has_error() { return next_error_message_id != 0; }
int debug_get_error_message_count() { return next_error_message_id; }
const char *debug_get_error_message_at(int idx) { return error_messages[idx]; }
|
C
|
// Description----------------------------------------------------------------|
/*
* Initialises a struct with Name and Age data. Displays results on LEDs and
* LCD.
*/
// DEFINES AND INCLUDES-------------------------------------------------------|
#define STM32F051
//>>> Uncomment line 10 if using System Workbench (SW4STM32) or STM32CubeIDE
//#define SW4STM32
#ifndef SW4STM32
#define TRUESTUDIO
#endif
#include "stm32f0xx.h"
#include "lcd_stm32f0-1.h"
// GLOBAL VARIABLES ----------------------------------------------------------|
uint8_t = ADC_value; //adc value after conversation
unsigned char buffer[16];
// FUNCTION DECLARATIONS -----------------------------------------------------|
void main(void); //COMPULSORY
void init_ADC(void);
void display_on_LCD();
void init_LEDS(void);
void display_on_LEDs();
void init_external_interupts(void);
void init_buttons(void);
#ifdef TRUESTUDIO //COMPULSORY
void reset_clock_to_48Mhz(void); //COMPULSORY
#endif //COMPULSORY
// MAIN FUNCTION -------------------------------------------------------------|
void main(void)
{
#ifdef TRUESTUDIO //COMPULSORY
reset_clock_to_48Mhz(); //COMPULSORY
#endif //COMPULSORY
void init_ADC();
void display_on_LCD();
void init_LEDS();
void display_on_LEDs();
void display_on_LEDs();
void init_external_interupts();
void init_buttons();
while(1);
}
// OTHER FUNCTIONS -----------------------------------------------------------|
void init_ADC(void)
{
RCC -> APB2ENR |= RCC_APB2ENR_ADCEN; // enable clock for ADC
RCC -> AHBENR |= RCC_AHBENR_GPIOAEN; // enable clock PORT A
GPIOA -> MODER |= GPIO_MODER_MODER5; // set PA5, analogue mode
ADC1 -> CFGR1 |= ADC_CFGR1_RES_1; // 8 bit resolution
ADC1 -> CFGR1 &= ~ADC_CFGR1_CONT; //Cont = 0: single shot mode
ADC1->CR |= ADC_CR_ADEN; //set ADEN=1
while((ADC1->ISR & ADC_ISR_ADRDY)==0); //wait until ADRDY==1
ADC1->CR |= ADC_CR_ADSTART; //start the ADC
}
void display_on_LCD()
{
sprintf(buffer,"%f",ADC_value);
init_LCD();
lcd_command(CLEAR);
lcd_putstring(buffer);
}
void init_LEDS(void)
{
RCC->AHBENR |= RCC_AHBENR_GPIOBEN; // Enable GPIOB clock
GPIOB->MODER |= GPIO_MODER_MODER0_0;
GPIOB->MODER |= GPIO_MODER_MODER1_0;
GPIOB->MODER |= GPIO_MODER_MODER2_0;
GPIOB->MODER |= GPIO_MODER_MODER3_0;
GPIOB->MODER |= GPIO_MODER_MODER4_0;
GPIOB->MODER |= GPIO_MODER_MODER5_0;
GPIOB->MODER |= GPIO_MODER_MODER6_0;
GPIOB->MODER |= GPIO_MODER_MODER7_0;
}
void display_on_LEDs(void)
{
GPIOB -> ODR = ADC_value;
}
void init_buttons(void)
{
RCC -> AHBENR |= RCC_AHBENR_GPIOAEN; //enable clock for push buttons
GPIOA -> MODER &= ~GPIO_MODER_MODER3; // configure PA0 to input mode
GPIOA -> PUPDR |= GPIO_PUPDR_PUPDR3_0; // pull up '01'
}
#ifdef TRUESTUDIO //COMPULSORY
/* Description:
* This function resets the STM32 Clocks to 48 MHz
*/
void reset_clock_to_48Mhz(void) //COMPULSORY
{ //COMPULSORY
if ((RCC->CFGR & RCC_CFGR_SWS) == RCC_CFGR_SWS_PLL) //COMPULSORY
{ //COMPULSORY
RCC->CFGR &= (uint32_t) (~RCC_CFGR_SW); //COMPULSORY
while ((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_HSI); //COMPULSORY
} //COMPULSORY
RCC->CR &= (uint32_t)(~RCC_CR_PLLON); //COMPULSORY
while ((RCC->CR & RCC_CR_PLLRDY) != 0); //COMPULSORY
RCC->CFGR = ((RCC->CFGR & (~0x003C0000)) | 0x00280000); //COMPULSORY
RCC->CR |= RCC_CR_PLLON; //COMPULSORY
while ((RCC->CR & RCC_CR_PLLRDY) == 0); //COMPULSORY
RCC->CFGR |= (uint32_t) (RCC_CFGR_SW_PLL); //COMPULSORY
while ((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_PLL); //COMPULSORY
} //COMPULSORY
#endif //COMPULSORY
// INTERRUPT HANDLERS --------------------------------------------------------|
void init_external_interupts(void)
{
RCC->APB2ENR |= RCC_APB2ENR_SYSCFGOMPEN;
SYSCFG->EXTICR[0] |= SYSCFG_EXTICR1_EXTI0_PA;
SYSCFG->EXTICR[0] |= SYSCFG_EXTICR1_EXTI1_PA;
EXTI->IMR |= EXTI_IMR_MR3 | EXTI_IMR_MR1;
EXTI->FTSR |= EXTI_FTSR_TR3 | EXTI_FTSR_MR1;
NVIC_EnableIRQ(EXTI0_1_IRQn);
}
void EXTI0_1_IRQHandler(void)
{
if (EXTI-> PR &= EXTI_PR_PR3 )// IF BUTTON IS PUSHED WAS A3
{
GPIOB->ODR = ADC_values;
}
else
{
GPIOB -> ODR = 0x00;
}
EXTI->PR |= EXTI_PR_PR3;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int
char nama[30];
char alamat[40];
char nomer[20];
char jurusan[20];
char universitas[30];
printf("===================================\n");
printf("----Masukkan Data Diri Anda----\n");
printf("===================================\n");
printf("\n\n Masukkan nama anda \t\t: ");
gets(nama);
printf(" Masukkan alamat anda \t\t: ");
gets(alamat);
printf(" Masukkan nomor anda \t\t: ");
scanf("%s",&nomer);
printf(" Masukkan jurusan anda \t\t: ");
scanf("%s", &jurusan);
printf(" Masukkan Universitas anda \t: ");
scanf("%s", &universitas);
printf("\n ----Data Diri Anda---- \n");
printf(" Nama \t\t : %s\n",nama);
printf(" Alamat \t : %s\n",alamat);
printf(" Nomor Telp \t : %s\n",nomer);
printf(" Jurusan \t : %s\n",jurusan);
printf(" Universitas \t : %s\n",universitas);
return 0;
}
|
C
|
#include <stdio.h>
#define TAILLE 10
int main(){
int i;
int tab[TAILLE]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, tab_copy[TAILLE];
for (i=0; i<TAILLE; i++){
tab_copy[i]=tab[i];
printf("tab[%d]=%d\n", i, tab[i]);
printf("tab_copy[%d]=%d\n", i, tab_copy[i]);
}
return 0;
}
|
C
|
#include "monteCarlo.h"
#include "world.h"
#include "spgrid.h"
#include <string.h>
#define DIAMETER 1 /* Particles have diameter 1 */
static bool collidesHelper(Particle *p1, Particle *p2)
{
/* Returns TRUE if there is NO collision! */
return nearestImageDistance2(p1->pos, p2->pos) >= SQUARE(DIAMETER);
}
static bool collides(Particle *p)
{
return !forEveryNeighbourOf(p, &collidesHelper);
}
static void fillWorld(void)
{
double ws = world.worldSize;
for (int i = 0; i < world.numParticles; i++) {
Particle *p = &world.particles[i];
p->pos = (Vec3) {0, 0, 0};
addToGrid(p);
do {
p->pos.x = ws * (rand01() - 1/2.0);
p->pos.y = ws * (rand01() - 1/2.0);
if (!world.twoDimensional)
p->pos.z = ws * (rand01() - 1/2.0);
reboxParticle(p);
} while (collides(p));
}
}
typedef struct {
MonteCarloConfig conf;
long attempted; /* Attempted number of MC moves */
long accepted; /* Number of accepted MC moves */
} MonteCarloState;
static void *monteCarloTaskStart(void *initialData)
{
assert(initialData != NULL);
MonteCarloConfig *mcc = (MonteCarloConfig*) initialData;
int nb = floor(world.worldSize / mcc->boxSize);
if (nb < 0)
die("World so small (or boxSize so big) that I can't fit a "
"single box in there!\n");
/* adjust boxsize to get the correct world size! */
double trueBoxSize = world.worldSize / nb;
printf("Requested boxsize %f, actual box size %f\n",
mcc->boxSize, trueBoxSize);
if (world.twoDimensional) {
printf("Allocating grid for 2D world, %d boxes/dim.\n", nb);
allocGrid(nb, nb, 1, trueBoxSize);
} else {
printf("Allocating grid for 3D world, %d boxes/dim.\n", nb);
allocGrid(nb, nb, nb, trueBoxSize);
}
fillWorld();
MonteCarloState *state = malloc(sizeof(*state));
state->conf = *mcc;
state->attempted = 0;
state->accepted = 0;
free(mcc);
return state;
}
/* Perform a Monte Carlo sweep */
static TaskSignal monteCarloTaskTick(void *state)
{
assert(state != NULL);
MonteCarloState *mcs = (MonteCarloState*) state;
MonteCarloConfig *mcc = &mcs->conf;
assert(mcc->delta > 0);
for (int i = 0; i < world.numParticles; i++) {
Particle *p = &world.particles[randIndex(world.numParticles)];
Vec3 oldPos = p->pos;
p->pos.x += mcc->delta * (rand01() - 1/2.0);
p->pos.y += mcc->delta * (rand01() - 1/2.0);
if (!world.twoDimensional)
p->pos.z += mcc->delta * (rand01() - 1/2.0);
reboxParticle(p);
if (collides(p)) {
/* Back to old position! */
p->pos = oldPos;
reboxParticle(p);
} else {
mcs->accepted++;
}
}
mcs->attempted += world.numParticles;
return TASK_OK;
}
static void monteCarloTaskStop(void *state)
{
MonteCarloState *mcs = (MonteCarloState*) state;
printf("Acceptance ratio: %f\n",
((double) mcs->accepted) / mcs->attempted);
freeGrid();
free(mcs);
}
Task makeMonteCarloTask(MonteCarloConfig *mcc)
{
if (mcc->boxSize <= 0)
die("Box size is zero (or negative)!\n");
if (mcc->delta <= 0)
die("MC delta is zero (or negative)!\n");
MonteCarloConfig *mccCopy = malloc(sizeof(*mccCopy));
memcpy(mccCopy, mcc, sizeof(*mccCopy));
Task ret = {
.initialData = mccCopy,
.start = &monteCarloTaskStart,
.tick = &monteCarloTaskTick,
.stop = &monteCarloTaskStop,
};
return ret;
}
|
C
|
#include <stdio.h>
struct numbers {
int num1;
int num2;
};
int main()
{
//struct numbers s1 = {.num2 = 22, .num1 = 11};
struct numbers s1 = { 22, 11 };
// struct numbers s2 = {.num2 = 30};
struct numbers s2 = { 2 };
printf("num1: %d, num2: %d\n", s1.num1, s1.num2);
printf("s2.num1: %d s2.num2: %d", s2.num1, s2.num2);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int i, x, y, sum=0;
scanf("%d %d", &x, &y);
if(x<y)
{
for(i=x+1; i<y; i++)
if(i%2==1 || i%2==-1)
sum=sum+i;
}
else
{
for(i=y+1; i<x; i++)
if(i%2==1 || i%2==-1)
sum=sum+i;
}
printf("%d\n",sum);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int Val;
struct node* Prev;
struct node* Next;
}listNode;
listNode* receive(listNode* ptr,int n){
for (int i=0;i<n;i++){
listNode* node=(listNode*)malloc(sizeof(listNode));
scanf("%d", &node->Val);
node->Next = ptr;
node->Prev = NULL;
if (ptr!=NULL) ptr->Prev = node;
ptr = node;
}
return ptr;
}
int function(listNode* ptr,int n){
int flag = 0;
listNode* tail = ptr;
listNode* head = ptr;
while(tail->Next!=NULL) tail = tail->Next;
printf("%d",tail->Val);
for (;head!=tail&&head->Next!=tail;){
if (head->Val!=tail->Val){
flag = 1;
break;
}
head=head->Next;
tail=tail->Prev;
}
if (flag){
return 0;
}
return 1;
}
int main(){
int n = 0;
scanf("%d",&n);
listNode* ptr = NULL;
ptr = receive(ptr,n);
int adjust = function(ptr,n);
if (adjust){
printf("true");
} else {
printf("false");
}
return 0;
}
|
C
|
# include "util.h"
/*# include "efsManagement.h" */
# include "pManagement.h"
# include "hmac.h"
unsigned char * master_encdec_key ;
unsigned char * master_hmac_key ;
unsigned char * master_iv = "PURDUECS526CLASSFALL2015WLINUSA0";
unsigned char * password_file ;
unsigned char * master_filelist ="master.filelist";;
// FILL THE BODY OF THE FOLLOWING FUNCTIONS
int create_file(unsigned char *username, unsigned char* password, unsigned char * fileName){
printf("DEBUG: CALLED CREATE_FILE FUNCTION\n");
return OKAY ;
}
int delete_file(unsigned char *username, unsigned char* password, unsigned char * fileName){
printf("DEBUG: CALLED DELETE_FILE FUNCTION\n");
return OKAY ;
}
int encrypt_file(unsigned char *username, unsigned char* password, unsigned char * fileName){
printf("DEBUG: CALLED ENCRYPT_FILE FUNCTION\n");
return OKAY ;
}
int decrypt_file(unsigned char *username, unsigned char* password, unsigned char * fileName){
printf("DEBUG: CALLED DECRYPT_FILE FUNCTION\n");
return OKAY ;
}
char* read_from_file(unsigned char *username, unsigned char* password, unsigned char * fileName, int offset, int length){
printf("DEBUG: CALLED READ_FROM_FILE FUNCTION\n");
return NULL ;
}
int write_to_file(unsigned char *username, unsigned char* password, unsigned char * fileName, int offset, unsigned char * nContent){
printf("DEBUG: CALLED WRITE_TO_FILE FUNCTION\n");
return OKAY ;
}
int file_size(unsigned char *username, unsigned char* password, unsigned char * fileName){
printf("DEBUG: CALLED FILE_SIZE FUNCTION\n");
return ERROR ;
}
int file_integrity_check(unsigned char *username, unsigned char* password, unsigned char * fileName){
printf("DEBUG: CALLED FILE_INTEGRITY_CHECK FUNCTION\n");
return OKAY ;
}
int system_health_check(){
printf("DEBUG: CALLED SYSTEM_HEALTH_CHECK FUNCTION\n");
return OKAY ;
}
int main(int argc, char* argv[]){
if(argc != 4){
printf("ERROR: Missing command line arguments\nUsage: ./efsmanager master_password user_password_file date_and_time_of_last_change\n");
return 1 ;
}
printf("Found master password: %s\n",argv[1]);
printf("Found user password file: %s\n",argv[2]);
printf("Found date of last change: %s\n",argv[3]);
printf("Found master_iv: %s\n",master_iv);
//copy argv[2] to password_file
/*
use the master password and master IV to generate the master encryption
decryption key and master hmace key. Store the master encryption decryption
key in master_encdec_key and store the master hmac key in master_hmac_key
*/
unsigned char command[1024];
int operation_status ;
while(1){
printf("Available commands:\n(1) create_file\n(2) delete_file\n(3) encrypt_file\n(4) decrypt_file\n(5) read_from_file\n(6) write_to_file\n(7) file_size\n(8) file_integrity_check\n(9) system_health_check\n(10) quit\n\n\n");
printf("enter a command: ");
scanf("%s",command) ;
// printf("\n") ;
operation_status = OKAY ;
if(!strcmp(command,"create_file")){
printf("username: ");
unsigned char username[1024];
scanf("%s",username) ;
printf("password: ");
unsigned char password[1024] ;
scanf("%s",password) ;
printf("file name: ");
unsigned char pFile[1024] ;
scanf("%s",pFile);
operation_status = create_file(username,password,pFile) ;
}
else if(!strcmp(command,"delete_file")){
printf("username: ");
unsigned char username[1024];
scanf("%s",username) ;
printf("password: ");
unsigned char password[1024] ;
scanf("%s",password) ;
printf("file name: ");
unsigned char pFile[1024] ;
scanf("%s",pFile);
operation_status = delete_file(username,password,pFile) ;
}
else if(!strcmp(command,"encrypt_file")){
printf("username: ");
unsigned char username[1024];
scanf("%s",username) ;
printf("password: ");
unsigned char password[1024] ;
scanf("%s",password) ;
printf("file name to encrypt: ");
unsigned char pFile[1024] ;
scanf("%s",pFile);
operation_status = encrypt_file(username,password,pFile) ;
}
else if(!strcmp(command,"decrypt_file")){
printf("username: ");
unsigned char username[1024];
scanf("%s",username) ;
printf("password: ");
unsigned char password[1024] ;
scanf("%s",password) ;
printf("file name to decrypt: ");
unsigned char pFile[1024] ;
scanf("%s",pFile);
operation_status = decrypt_file(username,password,pFile) ;
}
else if(!strcmp(command,"file_size")){
printf("username: ");
unsigned char username[1024];
scanf("%s",username) ;
printf("password: ");
unsigned char password[1024] ;
scanf("%s",password) ;
printf("file name: ");
unsigned char pFile[1024] ;
scanf("%s",pFile);
operation_status = file_size(username,password,pFile) ;
}
else if(!strcmp(command,"file_integrity_check")){
printf("username: ");
unsigned char username[1024];
scanf("%s",username) ;
printf("password: ");
unsigned char password[1024] ;
scanf("%s",password) ;
printf("file name: ");
unsigned char pFile[1024] ;
scanf("%s",pFile);
operation_status = file_integrity_check(username,password,pFile) ;
}
else if(!strcmp(command,"system_health_check")){
operation_status = system_health_check();
}
else if(!strcmp(command,"read_from_file")){
printf("username: ");
unsigned char username[1024];
scanf("%s",username) ;
printf("password: ");
unsigned char password[1024] ;
scanf("%s",password) ;
printf("file name: ");
unsigned char pFile[1024] ;
scanf("%s",pFile);
printf("position to read from: ");
int offset ; scanf("%d",&offset);
printf("how many characters to read: ");
int len; scanf("%d",&len);
unsigned char *content = read_from_file(username,password,pFile,offset,len) ;
if(content == NULL){
printf("ERROR: Reading from file\n");
continue;
}
else{
printf("CONTENT:\n%s\n",content);
}
}
else if(!strcmp(command,"write_to_file")){
printf("username: ");
unsigned char username[1024];
scanf("%s",username) ;
printf("password: ");
unsigned char password[1024] ;
scanf("%s",password) ;
printf("file name: ");
unsigned char pFile[1024] ;
scanf("%s",pFile);
printf("position to write to: ");
int offset ; scanf("%d",&offset);
printf("Content to write:\n ");
char content[8192] ;
int i = 0 ;
while(1){
char ch = getchar();
if(ch == EOF) break ;
content[i] = ch ;
++i ;
}
operation_status = write_to_file(username,password,pFile,offset,content) ;
}
else if(!strcmp(command,"quit")){
printf("INFO: Got the quit command\n");
printf("Program terminating\n");
break;
}
else{
printf("ERROR: Unknown command %s\n",command);
printf("INFO: Ignoring command\n") ;
}
if(operation_status == ERROR)
printf("Operation %s failed\n",command) ;
}
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
union per
{
int a;
char buf[32];
char c;
};
int main(void)
{
//联合体大小
printf("sizeof(union) = %ld\n", sizeof(union per));
union per a;
a.a = 44;
strcpy(a.buf, "CHINA");
//a.c = 'Y';
printf("%d\n", a.a);
printf("%s\n", a.buf);
//printf("%c\n", a.c);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_options.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: luccasim <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/09/12 17:01:02 by luccasim #+# #+# */
/* Updated: 2016/09/12 17:01:05 by luccasim ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_unix.h"
#include "libft.h"
static char *handle_sglt(char c, uint32_t act)
{
static uint32_t flag = 0;
static uint32_t off = 0;
static char sglt[OPT_BUF_SIZE];
if (act == 0)
{
flag = 0;
off = 0;
ft_bzero(sglt, OPT_BUF_SIZE);
}
if (act == 1)
{
if (off == OPT_BUF_SIZE)
{
ft_error("Option SGLT", "Buffer_size is full");
return (sglt);
}
sglt[off++] = c;
flag = 1;
}
if (act == 3)
return ((flag) ? sglt : NULL);
return (sglt);
}
static int options_loop(char *str, char *option, char *buf, uint32_t *flag)
{
if (*str != '-' || !option)
return (SUCCESS);
while (*str)
{
if (*str == '-')
str++;
if (!*str || !ft_strchr(option, *str) || *flag)
return (ft_error(str, "illegal option"));
else
{
if (ft_strchr(buf, *str) == NULL)
handle_sglt(*str, 1);
}
++str;
}
return (-1);
}
static int number_arg(int32_t nbre_arg, int32_t size)
{
if (size == 0)
return (nbre_arg);
if (size < 0)
{
if (nbre_arg > ABS(size))
return (PERROR("Too much arguments"));
}
else
{
if (nbre_arg != size)
{
ft_fprintf(2, "You have [{r:%i}/{g:%i}] args\n", nbre_arg, size);
return (FAIL);
}
}
return (nbre_arg);
}
char *ft_options_sglt(void)
{
return (handle_sglt(0, 3));
}
int ft_options(char ***arg, char *opt, int32_t size)
{
char **av;
uint32_t nbre_arg;
int32_t res;
handle_sglt(0, 0);
av = *arg;
nbre_arg = 0;
av++;
while (*av)
{
res = options_loop(*av, opt, handle_sglt(0, 4), &nbre_arg);
if (res == FAIL)
return (FAIL);
else if (res < 0)
++av;
else
{
if (!nbre_arg)
*arg = av;
++nbre_arg;
++av;
}
}
return (number_arg(++nbre_arg, size));
}
|
C
|
#include <stdio.h>
#include <conio.h>
#define n 10
int main()
{
int i, j, b[n+1][n+1];
for(i=1;i<=n;i++)
{
b[1][i]=i;
}
for(i=2;i<=n;i++)
{
for(j=2;j<=n;j++)
{
b[i][j]=b[i-1][j-1];
}
b[i][1]=b[i-1][n];
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
gotoxy(j*3+15,i*2+3);
printf("%d", b[i][j]);
}
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.