language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdio.h>
#include <conio.h>
#include <string.h>
void converge(int line, char *message);
void main (void){
converge(10, "Isso é um teste de converge().");
}
void converge(int line, char *message){
int i,j;
for (i = 1, j = strlen(message); i < j; i++, j--){
gotoxy(i, line); printf("%c", message[i-1]);
gotoxy(j, line); printf("%c", message[j-1]);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
/*
Speed(knots) Description
Less than 1 Calm
1-3 Light air
4-27 Breeze
28-47 Gale
48-63 Storm
Above 63 Hurricane
*/
int main(int argc, char *argv[]) {
int knots, description;
printf("Enter the Speed(knots): ");
scanf("%d", &knots);
printf("Description: ");
if(knots < 1)
printf("Calm");
if(knots > 1 && knots <= 3)
printf("Light air");
if(knots > 4 && knots <= 27)
printf("Breeze");
if(knots > 28 && knots <= 47)
printf("Gale");
if(knots > 48 && knots <= 63)
printf("Storm");
if(knots > 63)
printf("Hurricane");
return 0;
}
|
C
|
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/syscall.h>
static int value = 0;
pthread_mutex_t mutex;
void func(void* args){
while(1){
pthread_mutex_lock(&mutex);
value ++;
printf("value = %d, tid = %d\n", value,syscall(SYS_gettid));
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main(){
pthread_t pid1, pid2;
pthread_mutex_init(&mutex, NULL);
if(pthread_create(&pid1, NULL, func, NULL)){
return -1;
}
if(pthread_create(&pid2, NULL, func, NULL)){
return -1;
}
printf("PID = %d\n",getpid());
while(1) sleep(0);
return 0;
}
|
C
|
/* ====================================================================
* Copyright (c) 1999-2006 Carnegie Mellon University. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* This work was supported in part by funding from the Defense Advanced
* Research Projects Agency and the National Science Foundation of the
* United States of America, and the CMU Sphinx Speech Consortium.
*
* THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND
* ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY
* NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ====================================================================
*
*/
/*
Largely derived just from the code obtained from text2wfreq.c -AC
*/
#include "ac_hash.h"
#include "pc_general.h"
#include "general.h"
/* create a new node, and sets the count to 1 */
struct node *new_node( char *key )
{
struct node *x;
x = (struct node *) rr_malloc( sizeof( struct node ) );
x->word = (char *) rr_malloc( (strlen( key ) + 1) * sizeof( char ) );
strcpy( x->word, key );
x->count = 1;
return x;
}
/* create hash table */
void new_hashtable( struct hash_table *table, int M )
{
int i;
table->size = M;
table->chain = (struct node **) rr_malloc( M * sizeof( struct node *) );
for( i = 0; i < M; i++ ) {
table->chain[i] = new_node( "HEAD_NODE" );
table->chain[i]->next = (struct node *) NULL;
}
}
/* update linked list */
int update_chain( struct node *t, char *key )
{
struct node *x;
int score;
while( t->next != NULL ) {
score = strcmp( key, t->next->word );
/* move to next node */
if ( score > 0 ) t = t->next;
/* update node */
else if ( score == 0 ) {
t->next->count++;
return 1;
}
/* add new node */
else {
x = new_node( key );
x->next = t->next;
t->next = x;
return 0;
}
}
/* add node at end */
x = new_node( key );
x->next = (struct node *) NULL;
t->next = x;
return 0;
}
/* generate a hash table address from a variable length character */
/* string - from R. Sedgewick, "Algorithms in C++". */
int hash( char *key, int M )
{
unsigned int h;
char *t = key;
for( h = 0; *t; t++ )
h = ( 64 * h + *t ) % M;
return h;
}
/* print contents of linked list */
static void print_chain(FILE* outfp, struct node *t )
{
t = t->next; /* don't print head node */
while ( t != NULL ) {
fprintf(outfp, "%s %d\n", t->word, t->count );
t = t->next;
}
}
/* print hash table contents */
void print(FILE* outfp, struct hash_table *table )
{
int i;
for( i = 0; i < table->size; i++ )
print_chain(outfp, table->chain[i] );
}
/* update hash table contents */
void update( struct hash_table *table, char *key, int verbosity )
{
int chain;
chain = hash( key, table->size );
if ( chain < 0 || chain >= table->size ) {
pc_message(verbosity,1,"WARNING : invalid hash address.\n");
pc_message(verbosity,1,"%s ignored\n", key );
return;
}
update_chain( table->chain[ chain ], key );
}
/* Hashing functions, by Gary Cook (gdc@eng.cam.ac.uk). Could use the
sih functions used in idngrma2lm, but these are much faster. */
/* return the nearest prime not smaller than 'num' */
int nearest_prime(int num)
{
int div;
int num_has_divisor = 1;
if ( num / 2 * 2 == num ) num++;
for (; num_has_divisor; num += 2 ) {
num_has_divisor=0;
for ( div = 3; div <= num / 3; div++ ) {
if ( ( num / div) * div == num ) {
num_has_divisor = 1;
break;
}
}
}
num -= 2;
return( num );
}
/**
ARCHAN 20060122 This is a customized implementation of hash table
for text2idngram and wngram2idngram.
*/
/* create a new node, and sets the index to ind */
struct idngram_node *idngram_new_node( char *key ,wordid_t ind)
{
struct idngram_node *x;
x = (struct idngram_node *) rr_malloc( sizeof( struct idngram_node ) );
x->word = (char *) rr_malloc( (strlen( key ) + 1) * sizeof( char ) );
strcpy( x->word, key );
x->ind = ind;
return x;
}
/* generate a hash table address from a variable length character */
/* string - from R. Sedgewick, "Algorithms in C++". */
int idngram_hash( char *key, int M )
{
unsigned int h;
char *t = key;
for( h = 0; *t; t++ )
h = ( 256 * h + *t ) % M;
return h;
}
/* create hash table */
void new_idngram_hashtable( struct idngram_hash_table *table, int M )
{
int i;
table->size = M;
table->chain = (struct idngram_node **) rr_malloc( M * sizeof( struct idngram_node *) );
for( i = 0; i < M; i++ ) {
table->chain[i] = idngram_new_node( "HEAD_NODE" , 0);
table->chain[i]->next = (struct idngram_node *) NULL;
}
/* for(i = 0; i< M ; i++){
fprintf(stderr, "%d %s ind %d, %d\n",i,table->chain[i]->word, table->chain[i]->ind, table->chain[i]->next);
fflush(stderr);
}*/
}
/* update linked list */
int idngram_update_chain( struct idngram_node *t, char *key ,wordid_t ind)
{
struct idngram_node *x;
/* Move to end of list */
while( t->next != NULL )
t = t->next;
/* add node at end */
x = idngram_new_node( key,ind );
x->next = (struct idngram_node *) NULL;
t->next = x;
return 0;
}
void add_to_idngram_hashtable( struct idngram_hash_table *table,
unsigned long position,
char *vocab_item,
wordid_t ind) {
idngram_update_chain( table->chain[position], vocab_item,ind );
}
wordid_t index2(struct idngram_hash_table *vocab,
char *word) {
unsigned long chain;
struct idngram_node *chain_pos;
chain = idngram_hash( word, vocab->size );
if ( chain >= vocab->size ) {
fprintf( stderr, "WARNING : invalid hash address\n" );
fprintf( stderr, "%s ignored\n", word );
return(0);
}
chain_pos = vocab->chain[chain];
while (chain_pos->next != NULL) {
if (strcmp(word,chain_pos->next->word) ) {
fflush(stderr);
chain_pos = chain_pos->next;
}else
return (chain_pos->next->ind);
}
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define MAXVALUE 10000 /*ȨֵΪ10000 */
#define MAXLEAF 30 /* 30Ҷӽ */
#define MAXNODE MAXLEAF*2-1
/* Ϊ1Ľ,ܽn=n0+n2 n0 =30ʱ,ݶ
n0=n2+1, n2 = n0C1=29Թ30+29 =59 */
#define MAXBIT 10
typedef struct
{int weight;
int parent;
int lchild;
int rchild;
}HNodeType;
typedef struct
{ int bit[MAXBIT]; /*ַĿռ*/
int start; /* ַĿʼλ */
}HCodeType;
void Create_HuffMTree(HNodeType HFMTree[ ],int n)
{
int m1,m2,x1,x2;
int i,j;
for(i=0;i<2*n-1;i++)
{
HFMTree[i].weight=0;
HFMTree[i].parent=-1;
HFMTree[i].lchild=-1;
HFMTree[i].rchild=-1;}
for (i=0;i<n;i++)
{printf("ҶӽڵȨֵ:");
scanf("%d",&HFMTree[i].weight);
}
for(i=0;i<n-1;i++) //gouzao haximanshu de n-1 ge jiedian
{
x1=x2=MAXVALUE;
m1=m2=0;
for (j=0;j<n+i;j++)
{
if(HFMTree[j].parent==-1&&HFMTree[j].weight<x1)
{
x2=x1;m2=m1;
x1=HFMTree[j].weight;
m1=j;
}
else if(HFMTree[j].parent==-1&& HFMTree[j].weight<x2)
{
x2=HFMTree[j].weight;
m2=j;}
}
HFMTree[m1].parent=n+i;
HFMTree[m2].parent=n+i;
HFMTree[n+i].weight=HFMTree[m1].weight+HFMTree[m2].weight; ;
HFMTree[n+i].lchild=m1;
HFMTree[n+i].rchild=m2;}
}
void HuffmanCode(HNodeType HFMTree[ ], HCodeType HuffCode[ ],int n)
{
HCodeType cd;
int i,j,c,p;
for(i=0;i<n;i++)
{cd.start=n-1;
c=i;
p=HFMTree[c].parent;
while(p!=-1)
{ if(HFMTree[p].lchild==c)
cd.bit[cd.start]=0;
else
cd.bit[cd.start]=1;
cd.start--;
c=p;
p=HFMTree[p].parent;
}
for(j=cd.start+1;j<MAXBIT;j++)
{
HuffCode[i].bit[j]=cd.bit[j];
}
HuffCode[i].start=cd.start;
}
}
void main()
{
HNodeType HFM[MAXNODE];
int num;
int i,j;
HCodeType HFMCode[MAXLEAF];
printf("Ҷӽڵ:");
scanf("%d",&num);
Create_HuffMTree(HFM,num);
HuffmanCode(HFM,HFMCode,num);
for(i=0;i<num;i++)
{
printf("%5d%8d ",i,HFM[i].weight);
for (j=HFMCode[i].start+1;j<MAXBIT;j++)
{
printf ("%d",HFMCode[i].bit[j]);
}
printf("\n");
}
}
|
C
|
int kek() {
int a = 1;
int b = 4;
int c = 8;
int d = 8;
return (a * b + c * d - 228 - 1488 * 322 - (228 - 322 - 1488)) < (8841 - (228 - 822));
}
int iseven(int x)
{
if (x % 2 == 0) {
return 1;
} else {
return 0;
}
}
int sgn(int x)
{
int res = 0;
if (x < 0) {
res = -1;
} else if (x > 0) {
res = 1;
}
return res;
}
int fib(int n)
{
int a = 1;
int b = 1;
int c = 1;
int i;
if (n <= 0) {
return -1;
}
if (n <= 2) {
return 1;
}
i = 3;
while (i <= n) {
c = a + b;
a = b;
b = c;
i = i + 1;
}
return b;
}
int area(int a, int b)
{
return a * b;
}
int inners(int n)
{
int i = 0;
int sum = 0;
int j = 0;
while (i <= n) {
j = 0;
while (j <= i) {
if (j % 2 == 0) {
sum = sum + j;
}
j = j + 1;
}
i = i + 1;
}
return sum;
}
int tobool(int x)
{
return !(!x);
}
int heh(int x)
{
if (1) {
x = 1;
} else {
x = 2;
}
return x;
}
|
C
|
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <avr/io.h>
#include "protocol.h"
#include "interrupt.h"
#define KBD_RESET_DEASSERT() (PORTB |= (1 << 0))
#define KBD_RESET_ASSERT() (PORTB &= ~(1 << 0))
#define KBD_CLK_ASSERT() (PORTB |= (1 << 1))
#define KBD_CLK_DEASSERT() (PORTB &= ~(1 << 1))
#define KBD_Q0 ((PINA >> 2) & 1)
#define KBD_Q1 ((PIND >> 4) & 1)
#define KBD_Q2 ((PIND >> 3) & 1)
#define KBD_Q3 ((PIND >> 1) & 1)
#define COLUMNS 17
typedef enum KeyboardState KeyboardState;
enum KeyboardState {
KEYBOARD_STATE_RESET,
KEYBOARD_STATE_CLK_LOW,
KEYBOARD_STATE_CLK_HIGH,
};
struct {
uint8_t keystate[9];
uint8_t column;
KeyboardState state;
uint8_t event[8];
uint8_t event_first;
uint8_t event_last;
} keyboard;
uint8_t keyboard_init() {
uint8_t row;
DDRB |= (1 << 0); //KBD_RESET output
DDRB |= (1 << 1); //KBD_CLK output
DDRA &= ~(1 << 2); //KBD_Q0 input
DDRD &= ~(1 << 4); //KBD_Q1 input
DDRD &= ~(1 << 3); //KBD_Q2 input
DDRD &= ~(1 << 1); //KBD_Q3 input
KBD_CLK_DEASSERT();
KBD_RESET_ASSERT();
memset(&keyboard, 0, sizeof(keyboard));
row = KBD_Q0 | (KBD_Q1 << 1) | (KBD_Q2 << 2) | (KBD_Q3 << 3);
return row;
}
void keyboard_deinit() {
DDRB &= ~(1 << 0); //KBD_RESET input
DDRB &= ~(1 << 1); //KBD_CLK input
DDRA &= ~(1 << 2); //KBD_Q0 input
DDRD &= ~(1 << 4); //KBD_Q1 input
DDRD &= ~(1 << 3); //KBD_Q2 input
DDRD &= ~(1 << 1); //KBD_Q3 input
}
void keyboard_event_push(uint8_t ev) {
uint8_t last;
reg_status.keyboard_if = true;
last = keyboard.event_last;
keyboard.event[keyboard.event_last++] = ev;
if(keyboard.event_last == 8)
keyboard.event_last = 0;
if(keyboard.event_last == keyboard.event_first)
keyboard.event_last = last;
}
int16_t keyboard_event_pop() {
uint8_t ret;
if(keyboard.event_first == keyboard.event_last) {
reg_status.keyboard_if = false;
return -1;
}
ret = keyboard.event[keyboard.event_first++];
if(keyboard.event_first == 8)
keyboard.event_first = 0;
if(keyboard.event_first == keyboard.event_last)
reg_status.keyboard_if = false;
return ret;
}
void keyboard_tick() {
uint8_t row;
uint8_t oldrow;
uint8_t i;
switch(keyboard.state) {
case KEYBOARD_STATE_RESET:
KBD_CLK_DEASSERT();
KBD_RESET_DEASSERT();
keyboard.state = KEYBOARD_STATE_CLK_LOW;
break;
case KEYBOARD_STATE_CLK_LOW:
row = KBD_Q0 | (KBD_Q1 << 1) | (KBD_Q2 << 2) | (KBD_Q3 << 3);
if(keyboard.column & 1) {
oldrow = keyboard.keystate[keyboard.column >> 1] >> 4;
keyboard.keystate[keyboard.column >> 1] &= 0x0F;
keyboard.keystate[keyboard.column >> 1] |= row << 4;
} else {
oldrow = keyboard.keystate[keyboard.column >> 1] & 0xF;
keyboard.keystate[keyboard.column >> 1] &= 0xF0;
keyboard.keystate[keyboard.column >> 1] |= row;
}
for(i = 0; oldrow != row; i++) {
if((oldrow & 1) ^ (row & 1)) {
keyboard_event_push(((oldrow & 1) << 7) | ((keyboard.column << 2) | i));
}
oldrow >>= 1;
row >>= 1;
}
KBD_CLK_ASSERT();
keyboard.state = KEYBOARD_STATE_CLK_HIGH;
break;
case KEYBOARD_STATE_CLK_HIGH:
if(++keyboard.column == COLUMNS)
keyboard.column = 0;
KBD_CLK_DEASSERT();
keyboard.state = KEYBOARD_STATE_CLK_LOW;
break;
}
}
|
C
|
#include <stdio.h>
#include <assert.h>
#define FOR(i,j) for(i=0; i<(j); ++i)
#define MAX(a,b) (a)>(b)? (a):(b)
#define MIN(a,b) (a)>(b)? (b):(a)
#defnie MAX_NODE_SIZE (1000)
#define debugf printf
#define NO (-1)
#define YES (1)
int preorder_node[MAX_NODE_SIZE];
int inorder_node[MAX_NODE_SIZE];
int postorder_node[MAX_NODE_SIZE];
void init(int node_size)
{
}
int get_answer(int node_size)
{
int i;
int j;
}
int main()
{
int test_case = 0;
int N;
int i,j,k;
scanf("%d", &test_case);
FOR(i, test_case)
{
scanf("%d", &N);
init(N);
FOR(j, N)
{
scanf("%d", &preorder_node[j]);
}
FOR(j, N)
{
scanf("%d", &inorder_node[j]);
}
get_answer(N);
FOR(j, N)
{
printf("%d ", postorder_node[j]);
}
printf("\n");
}
return 0;
}
|
C
|
//
// Created by pablo on 09.01.18.
//
#include <malloc.h>
#include "draw.h"
#include "types.h"
#include "player.h"
void draw_world(WINDOW *win, char **map) {
wclear(win);
box(win, 0, 0);
char *tempstr;
for (int y = 0; y < 20; ++y) {
for (int x = 0; x < 50; ++x) {
if (Player.x == x && Player.y == y) {
if (map[y][x] == 'S') {
Player.shield += 50;
map[y][x] = ' ';
} else if (map[y][x] == 'H') {
Player.health += 50;
if (Player.health > 100) {
Player.health = 100;
}
map[y][x] = ' ';
} else if (map[y][x] == 'M') {
Player.mana += 50;
if (Player.mana > 100) {
Player.mana = 100;
}
map[y][x] = ' ';
}
} else if (map[y][x] == '@') {
Player.x = x;
Player.y = y;
map[y][x] = ' ';
} else {
asprintf(&tempstr, "%c", map[y][x]);
mvwprintw(win, y + 2, x + 5, tempstr);
free(tempstr);
}
}
}
mvwaddch(win, Player.y + 2, Player.x + 5, Player.type | COLOR_PAIR(4));
}
void draw_stats(WINDOW *win) {
wclear(win);
char *hp;
asprintf(&hp, "Health: %d", Player.health);
mvwprintw(win, 2, 5, hp);
free(hp);
asprintf(&hp, "Mana: %d", Player.mana);
mvwprintw(win, 3, 5, hp);
free(hp);
asprintf(&hp, "Shield: %d", Player.shield);
mvwprintw(win, 4, 5, hp);
free(hp);
}
|
C
|
/************************************************************
**filename:get_syslog.c
**autor:Rocky
**date:2017/05/24
**description:get the message from file /proc/kmsg
************************************************************/
#include "../include/get_syslog.h"
#include "../include/get_time_str.h"
//#include "../pkg_log_msg/vc_log.h"
#include "../pkg_log_msg/vc_log_cfg.h"
void record_kmsg(const char *msg, int size);
void *start_monitor_kmsg(void *arg)
{
int iswatching = 1, startwatching = 1;
FILE *fp = NULL;
char msg_buf[BUFFER_SIZE + 1] = {0};
size_t ret_size = 0;
while (startwatching)
{
printf("begin to work\n");
iswatching = 1;
fp = fopen(ZTE_SYSLOG_DIR_FROM, "r");
if (NULL == fp)
{
perror("fopen fp error");
return NULL;
}
while (iswatching)
{
/* wait for system log */
ret_size = fread(msg_buf, 1, BUFFER_SIZE, fp);
if (ret_size > 0)
{
printf("begin to record\n");
record_kmsg(msg_buf, ret_size);
}
else
{
printf("read nothing\n");
iswatching = 0;
fclose(fp);
}
}
sleep(1);
}
}
void record_kmsg(const char *msg, int size)
{
int pos = 0;
FILE *local_fp = NULL;
char msg_arr[BUFFER_SIZE] = {0};
size_t time_size = 0, ret_size = 0;
local_fp = fopen(ZTE_SYSLOG_DIR_TO, "a+");
if (NULL == local_fp)
{
perror("fopen local_fp error");
return;
}
msg_arr[0] = '\n';
pos += 1;
time_size = make_current_time_str(msg_arr + pos);
pos += time_size;
strncat(msg_arr + pos, " : ", strlen(" : "));
pos += strlen(" : ");
if ((size + pos) > BUFFER_SIZE)
size = BUFFER_SIZE - pos;
strncat(msg_arr + pos, msg, size);
pos += size;
ret_size = fwrite(msg_arr, 1, pos, local_fp);
//printf("msg is %s, time_size = %d, ret_size = %d\n", msg_arr, time_size, ret_size);
if (pos != ret_size)
{
perror("fwrite error");
return;
}
fclose(local_fp);
}
|
C
|
#include<stdio.h>
int station(int a[],int n)
{
int i,k;
k=0;
for(i=1;i<=n;i++)
{
if(a[i]>a[k])
k=i;}
return(k+1);
}
main()
{
int a[100],n,i,t;
printf("enter n:\n");
scanf("%d",&n);
printf("\n");
printf("enter the array:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
t=station(a,n);
printf("the max_value position is:%d\n",t);
}
|
C
|
#include <stdio.h>
int main(void) {
float number;
float largest = 0;
while(1) {
printf("Enter a number: ");
scanf("%f", &number);
if (number > largest) {
largest = number;
}
if (number <= 0) {
break;
}
}
printf("\nThe largest number entered was %.2f\n", largest);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: teppei <teppei@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/08/11 13:31:18 by tkitagaw #+# #+# */
/* Updated: 2021/08/11 16:00:59 by teppei ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static int my_mkline(char **line, char **save, char *nl, int ret)
{
char *tmp;
*line = gnl_ft_strdup(*save);
if (!(*line))
{
free(*save);
return (1);
}
if (ret == 1)
{
tmp = gnl_ft_strdup(nl + 1);
if (!tmp)
{
free(*save);
return (1);
}
free(*save);
*save = tmp;
}
else
free(*save);
return (0);
}
static int my_chkline(char **line, char **save, int rc)
{
int ret;
char *nl;
ret = 0;
if (rc < 0)
{
free(*save);
return (-1);
}
if (!*save)
{
*line = gnl_ft_strdup("");
if (!(*line))
return (-1);
return (0);
}
nl = gnl_ft_strchr(*save, '\n');
if (nl)
{
*nl = '\0';
ret = 1;
}
if (my_mkline(line, save, nl, ret) == 0)
return (ret);
return (-1);
}
static int my_mksave(char **save, char **buf)
{
char *tmp;
if (!*save)
{
*save = gnl_ft_strdup(*buf);
if (!(*save))
{
free(*buf);
return (-1);
}
}
else
{
tmp = gnl_ft_strjoin(*save, *buf);
if (!tmp)
{
free(*save);
free(*buf);
return (-1);
}
free(*save);
*save = tmp;
}
return (1);
}
int get_next_line(int fd, char **line)
{
static char *save[256];
char *buf;
int rc;
if (fd < 0 || fd == 1 || fd == 2 || !line || BUFFER_SIZE < 1)
return (-1);
buf = (char *)malloc(sizeof(char) * (BUFFER_SIZE + 1));
if (!buf)
{
free(save[fd]);
return (-1);
}
rc = read(fd, buf, BUFFER_SIZE);
while (rc > 0)
{
buf[rc] = '\0';
if (my_mksave(&save[fd], &buf) == -1)
return (-1);
if (gnl_ft_strchr(save[fd], '\n'))
break ;
rc = read(fd, buf, BUFFER_SIZE);
}
free(buf);
return (my_chkline(line, &save[fd], rc));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct list{
int value;
struct list *next;
};
struct list *first; // a global variable created to access the first element of the list
void deletelist(struct list *p){
struct list *a;
while(p != NULL){
a = p->next;
free(p);
p = a;
}
}
void addfirst(struct list *p, int n){
struct list *a = (struct list*) malloc(sizeof(struct list));
if(a == NULL){
exit(0);
}
if(p->next == NULL){
p->value = n;
}else{
a->next = p;
a->value = n;
first = a;
}
}
void addlast(struct list *p, int n){
struct list *a = (struct list*) malloc(sizeof(struct list));
if(a == NULL){
exit(0);
}
while (p->next != NULL)
p = p->next;
p->next = a;
a->value = n;
a->next = NULL;
}
void remfirst(struct list *p){
first = p->next;
free(p);
}
void printl(struct list *p){
struct list *i;
for(i = p; i; i = p->next){
printf("%d",i->value);
}
}
int main(){
first = (struct list*) malloc(sizeof(struct list));
if(first == NULL){
exit(1);
}
first->next = NULL;
int n;
char oper;
int x = 0;
while(x == 0){
scanf("%c",&oper);
switch(oper){
case 'q':
++x;
deletelist(first);
break;
case 'p':
printl(first);
break;
case 'a':
scanf("%d",&n);
addlast(first,n);
break;
case 'b':
scanf("%d",&n);
addfirst(first, n);
break;
case 'r':
remfirst(first);
break;
}
}
return 0;
}
|
C
|
#include "table.h"
//RIGHT ROW BORDER
void count_mine_top_right(int nb_rows, int nb_columns, Case cases[nb_rows][nb_columns])
{
int i;
int j;
int count;
count = 0;
i = 0;
j = nb_columns - 1;
if(cases[i + 1][j].mine == - 1)
count++;
if(cases[i + 1][j - 1].mine == - 1)
count++;
if(cases[i][j - 1].mine == - 1)
count++;
cases[i][j].nb_mines = count;
}
|
C
|
/*
Seja A = {1, 2, 3, ..., n}. Faça um programa que leia n e exiba o produto cartesiano A x A.
Exemplo:
n = 3
A x A = { (1,1), (1,2), (1,3), (2,1), (2,2), (2,3), (3,1), (3,2), (3,3)}
*/
#include <stdio.h>
int main (int argc, char** argv){
int n, x, y, i, j;
printf ("Insira o numero n: ");
scanf("%d", &n);
n = n-1;
printf("\n\nAxA = { ");
for (i = 0; i<=n; i++){
for(j = 0;j<=n; j++){
printf("(%d,", (i+1));
printf("%d) ", (j+1));
}
}
printf(" };\n\n");
return 0;
}
|
C
|
/*
* Author: Evan Carlin
* Prompts the user for a menu option and returns their selection
*/
#include "menu.h"
#include <stdio.h>
int getMenuOpt(){
int userOption = -1;
//Keep prompting the user until a valid number is entered
while(1){
//Prompt the user for their choice
printf("\n\n *** Word Stat Menu ***\n");
printf("Please enter an option to continue.\n");
printf("Press 1 to get vowel and consonant frequency.\n");
printf("Press 2 to print out the word count.\n");
printf("Press 3 to print out a histogram of letter-use frequencyy.\n");
printf("Press 4 to continue entering more strings.\n");
printf("Press 5 to QUIT.\n");
//Read in the user choice
printf("Enter your choice: ");
scanf("%d", &userOption);
if(userOption == MENU_OPT_VC ||
userOption == MENU_OPT_WC ||
userOption == MENU_OPT_HISTO ||
userOption == MENU_OPT_RET ||
userOption == MENU_OPT_EXIT){
break;
}
else
printf("%d is not a vaild number!\n\n", userOption);
}
return userOption;
}
|
C
|
#include <stdio.h>
int power(int num1);
int main()
{
int num;
scanf("%d", &num);
printf("%d", power(num));
return 0;
}
int power(int num1)
{
if(num1==0)
return 1;
else if(num1==1)
return 2;
else
return 2 * power(num1-1);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
double raio, area, r= 3.14159;
scanf("%lf", &raio);
area=(raio*raio)*r;
printf("A=%.4f\n", area);
return 0;
}
|
C
|
//
// 12.c
// day06
//
// Created by student on 15-9-8.
// Copyright (c) 2015年 tarena. All rights reserved.
//
#include <stdio.h>
int main()
{for (int i=1;i<=4;i++)
{
for (int z=1;z<=4-i;z++)
{
printf(" ");
}
for (int y=0;y<2*i-1;y++)
{
if (i==2&&y==1)
{
printf(" ");
continue;
}
else if (i==3&&(y==1||y==2||y==3))
{
printf(" ");
continue;
}
printf("*");
}
printf("\n");
}
return 0;
}
|
C
|
#include "euler.h"
void eu023(char *ans) {
int N = 28123;
int abundant[N];
char issum[N];
int nabun = 0;
memset(abundant, 0, sizeof(abundant));
memset(issum, 0, sizeof(issum));
for (int i = 2; i < N; i++) {
if (sumdivisors(i) > i) {
abundant[nabun++] = i;
}
}
for (int i = 0; i < nabun; i++) {
for (int j = 0; j <= i; j++) {
int sum = abundant[i] + abundant[j];
if (sum < N) {
issum[sum] = 1;
}
}
}
int total = 0;
for (int i = 1; i < N; i++) {
if (!issum[i]) {
total += i;
}
}
sprintf(ans, "%d", total);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <sqlite3.h>
sqlite3 *db;
char *err_msg = 0;
int conexion;
struct becario{
char nombre[12];
int edad;
float promedio;
char procedencia[12];
int generacion;
unsigned int proyecto:1; //limite de bits
};
void createDB();
void print(struct becario bec);
void new_becario(struct becario bec);
int main(){
struct becario becarios[8];
char nombres[][20] = {"Angel", "Fernando", "Diana", "Gonzi", "Saine", "Cristian"};
char procedencia[][20] = {"Desconocido", "C.U.", "C.U.", "C.U.", "C.U.", "Acatlan"};
createDB();
for(int i=0; i<sizeof(nombres)/sizeof(nombres[0]); i++){
strcpy(becarios[i].nombre,nombres[i]);
strcpy(becarios[i].procedencia,procedencia[i]);
becarios[i].promedio = (rand() % 5)*2+1;
becarios[i].generacion = 11;
becarios[i].edad = (rand()%11)+15;
becarios[i].proyecto = i%2;
print(becarios[i]);
new_becario(becarios[i]);
}
sqlite3_close(db);
int conexion = 0;
}
void print(struct becario bec){
printf("\nNombre: %s\n",bec.nombre);
printf((bec.proyecto&1)?"Proyecto:Si\n":"Proyecto:No\n");
}
void createDB(){
// se crea una conexión a la DB
conexion = sqlite3_open("becarios.db",&db);
// valida si la conexión ha sido exitosa
if(conexion == SQLITE_OK){
char *sql = "DROP TABLE IF EXISTS Becarios;"
"CREATE TABLE Becarios"
"(Nombre TEXT, Edad INT, Promedio FLOAT,"
"Procedencia TEXT, Generacion INT, Proyecto TEXT);";
// ejecutamos el query
conexion = sqlite3_exec(db,sql,0,0,&err_msg);
// validamos si el query se ejecuto
if(conexion == SQLITE_OK) fprintf(stdout,"new table Becarios...!!OK\n");
else{ // ms de error en el query
fprintf(stderr, "SQL error: %s\n", err_msg);
sqlite3_free(err_msg);
}
} else{ // la conexión fallo
fprintf(stderr,"Cant open DB %s\n",sqlite3_errmsg(db));
sqlite3_close(db);
}
}
void new_becario(struct becario b){
char buf[1024];
snprintf(buf, sizeof buf,"INSERT INTO BECARIOS VALUES('%s',%d,%f,'%s',%d,%d);",
b.nombre,b.edad,b.promedio,b.procedencia,b.generacion,b.proyecto);
// ejecutamos el query
conexion = sqlite3_exec(db,buf,0,0,&err_msg);
if(conexion == SQLITE_OK) fprintf(stdout,"new becario...!!OK\n");
else{
fprintf(stderr, "SQL error: %s\n", err_msg);
sqlite3_free(err_msg);
}
}
|
C
|
#include <stdlib.h>
#include <unistd.h>
#include "convert_argv_to_maps.h"
#include "print_map.h"
#include "map_struct.h"
#include "map_struct.h"
#include "BBQ_string.h"
#include "BBQ_file.h"
#include "map_argument_is_valid.h"
#include "arg_to_map.h"
// TODO:
// ◦Should there be no passed arguments, your program must
// be able to read onthe standard input.
#define MAX_MAPS 128
int main(int argc, char **argv)
{
t_map_struct *maps;
int valid_map_count;
int i;
char ***char_maps;
int valid_map_found;
maps = (t_map_struct *)malloc(sizeof(t_map_struct) * (MAX_MAPS + 1));
char_maps = convert_argv_to_maps(argc, argv);
valid_map_count = 0;
i = -1;
while (i++ < argc)
{
if (argc == 1)
{
}
if (!argument_is_valid(argv[i]))
write(1, "Map Error!\n", 11);
else
{
maps[valid_map_count]
= arg_to_map(char_maps, valid_map_count, argv[i]);
valid_map_count++;
}
}
print_array_map(maps[0].char_array_map);
}
|
C
|
//TODO
/**
* 1. new socked
* 2. new listen
* 3. bind port
* 4. epoll wait
* 5. epoll_wait>0 then read
* 6. throw to php
* 7.
*/
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
//#include <cassert>
#include <sys/epoll.h>
//#include <sys/event.h>
//设置非阻塞描述符
int setnonblocking( int fd )
{
int old_option = fcntl( fd, F_GETFL );
int new_option = old_option | O_NONBLOCK;
fcntl( fd, F_SETFL, new_option );
return old_option;
}
#define MAXLINE 5000
#define MAXLENGTH 2465792
#define SERV_PORT 3989
#define LOCAL_ADDR "0.0.0.0"
//监听队列长度
#define LISTENQ 10
char response[MAXLENGTH];
int resLength;
struct epoll_event ev,events[20];//ev用于注册事件,数组用于回传要处理的事件
int i, maxi, listenfd, new_fd, sockfd,epfd,nfds;
int setOutPut(char * data,int fd,int length){
printf("setOutPut fd %d \n",fd);
printf("epfd fd %d \n",epfd);
resLength =length;
memcpy(response, data, resLength);
//strcpy(response, data); //data 中包含 \0(可能) 不能使用strcpy
ev.data.fd=fd;//设置用于写操作的文件描述符
ev.events=EPOLLOUT|EPOLLET;//设置用于注测的写操作事件
epoll_ctl(epfd,EPOLL_CTL_MOD,fd,&ev);//修改sockfd上要处理的事件为EPOLLOUT
}
//服务启动
int server(char* ip,int port)
{
//int i, maxi, listenfd, new_fd, sockfd,epfd,nfds;
ssize_t n;
char line[MAXLENGTH];
socklen_t clilen;
//struct epoll_event ev,events[20];//ev用于注册事件,数组用于回传要处理的事件
struct sockaddr_in clientaddr, serveraddr;
//生成socket文件描述符
listenfd = socket(AF_INET, SOCK_STREAM, 0);
//把socket设置为非阻塞方式
setnonblocking(listenfd);
//生成用于处理accept的epoll专用的文件描述符
epfd=epoll_create(256);
//设置与要处理的事件相关的文件描述符
ev.data.fd=listenfd;
//设置要处理的事件类型
ev.events=EPOLLIN|EPOLLET;
//注册epoll事件
epoll_ctl(epfd,EPOLL_CTL_ADD,listenfd,&ev);
printf("step 1 \n");
//设置服务器端地址信息
bzero(&serveraddr, sizeof(serveraddr));
printf("step 2 \n");
serveraddr.sin_family = AF_INET;
//监听的地址
char *local_addr= ip;
printf("step 3 \n");
inet_aton(local_addr,&(serveraddr.sin_addr));
printf("step 3.1 \n");
serveraddr.sin_port=htons(port);
printf("step 3.2 \n");
//绑定socket连接
bind(listenfd, ( struct sockaddr* )&serveraddr, sizeof(serveraddr));
printf("step 4 \n");
//监听
listen(listenfd, LISTENQ);
maxi = 0;
printf("listenfd %d \n",listenfd);
while(1)
{
/* epoll_wait:等待epoll事件的发生,并将发生的sokct fd和事件类型放入到events数组中;
* nfds:为发生的事件的个数。可用描述符数量
* 注:
*/
nfds=epoll_wait(epfd,events,20,500);
//处理可用描述符的事件
for(i=0;i<nfds;++i)
{
printf("nfds %d \n",nfds);
//当监听端口描述符可用时,接收链接的时候
if(events[i].data.fd==listenfd)
{
/* 获取发生事件端口信息,存于clientaddr中;
*new_fd:返回的新的socket描述符,用它来对该事件进行recv/send操作*/
new_fd = accept(listenfd,(struct sockaddr *)&clientaddr, &clilen);
printf("new_fd %d \n",new_fd);
if(new_fd<0)
{
perror("new_fd<0\n");
perror("test\n");
return 1;
}
perror("setnonblocking\n");
setnonblocking(new_fd);
char *str = inet_ntoa(clientaddr.sin_addr);
//设置用于读操作的文件描述符
ev.data.fd=new_fd;
//设置用于注测的读操作事件
ev.events=EPOLLIN|EPOLLET;
epoll_ctl( epfd, EPOLL_CTL_ADD, new_fd, &ev );
}
else if(events[i].events&EPOLLIN)//当数据进入触发下面的流程
{
sockfd = events[i].data.fd;
printf("read 0\n");
if ( (n = recv(sockfd, line, MAXLENGTH, 0)) < 0){
printf("read n \n");
if (errno == ECONNRESET)
{
close(sockfd);
events[i].data.fd = -1;
}else{
printf("readline error");
}
}else if (n == 0){
printf("read error \n");
close(sockfd);
events[i].data.fd = -1;
}
printf("line %s \n",line);
printf("line1 %c \n",line[20]);
printf("line2 %zu \n",sizeof(line));
printf("n %zu \n",n);
//设置用于写操作的文件描述符
ev.data.fd=sockfd;
ev.events=EPOLLOUT|EPOLLET;//设置用于注测的写操作事件
// epoll_ctl(epfd,ev.events,sockfd,&ev);//修改sockfd上要处理的事件为EPOLLOUT
//将接受到的请求抛给PHP
php_tinys_onReceive(sockfd,line,n);
}
else if(events[i].events&EPOLLOUT)//当数据发送触发下面的流程
{
sockfd = events[i].data.fd;
printf("response length %d \n",resLength);
int ret;
printf("wirte data fd %d \n",sockfd);
printf("response %s \n",response);
printf("res char %c \n",response[20]);
printf("res char %c \n",response[1]);
printf("res char %c \n",response[10]);
ret = write(sockfd, response, resLength);
printf("ret %d \n",ret);
if (ret<0)
{
printf("errno %d \n",errno);
}
ev.data.fd=sockfd;//设置用于读操作的文件描述符
ev.events=EPOLLET;//设置用于注测的读操作事件 EPOLLIN|
//EPOLL_CTL_DEL
epoll_ctl( epfd, EPOLL_CTL_DEL, sockfd, 0 );
close( sockfd );
//epoll_ctl(epfd,EPOLL_CTL_MOD,sockfd,&ev);//修改sockfd上要处理的事件为EPOLIN
}
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct Data {
char c1[20];
int *numberPointer;
};
int main() {
int num1 = 10;
//ü Ÿ
struct Data d;
//ü Ÿ
struct Data *dPointer = malloc(sizeof(struct Data));
d.numberPointer = &num1; //
dPointer -> numberPointer = &num1; //
printf("*d.numberPointer: %d\n", *d.numberPointer);
printf("*dPointer-> numberPointer: %d\n", *dPointer-> numberPointer);
printf("*d.numberPointer: %p\n", *d.numberPointer);
printf("*dPointer-> numberPointer: %p\n", dPointer-> numberPointer);
dPointer -> c1 = 'a';
printf("(*dPointer).c1: %c\n", (*dPointer).c1);
printf("(*dPointer).numberPointer: %d\n", (*dPointer).numberPointer);
printf("*(*dPointer).numberPointer: %p\n", *(*dPointer).numberPointer);
free(dPointer);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#pragma warning(disable:4996)
void submps(char *s1, char *s2, int len)
{
int i, j, m = 0;
int p, q;
int length = strlen(s2);
char a[100] = { 0 };
char b[100] = { 0 };
for (i = 0; i < len; i++)
{
for (j = 0; j < length; j++)
{
strcpy(a, "0");
p = i;
q = j;
while (s1[p] == s2[q] && s1[p] != 0)
{
a[m] = s2[q];
p++;
q++;
m++;
}
if (strlen(a) > strlen(b))
{
strcpy(b, a);
}
m = 0;
}
}
if (b[0]!= '0')
{
printf("%s\n", b);
}
else printf("ظ\n");
}
int main()
{
char str1[81] = { 0 };
char str2[81] = { 0 };
int len;
printf("ַ1");
scanf("%s", str1);
printf("ַ2");
scanf("%s", str2);
len = strlen(str1) <= strlen(str2) ? strlen(str1) : strlen(str2);
if (len == strlen(str1))
{
submps(str1, str2, len);
}
else if (len == strlen(str2))
{
submps(str2, str1, len);
}
return 0;
}
|
C
|
#include <stdlib.h>
#include "stack.h"
void stack_new(struct stack **stack, int elementSize, void (*freeFn)(void*))
{
if (stack == NULL) return;
if (*stack == NULL) {
(*stack) = (struct stack *)malloc(sizeof(struct stack));
(*stack)->list = NULL;
}
list_new(&((*stack)->list), elementSize, freeFn);
}
void stack_destroy(struct stack **stack)
{
list_destroy(&(*stack)->list);
free(*stack);
}
int stack_size(struct stack *stack)
{
return list_size(stack->list);
}
void stack_push(struct stack *stack, void *element)
{
list_prepend(stack->list, element);
}
void stack_pop(struct stack *stack, void *element)
{
if (stack_size(stack) <= 0) return;
list_head(stack->list, element, 1);
}
void stack_peek(struct stack *stack, void *element)
{
if (stack_size(stack) <= 0) return;
list_head(stack->list, element, 0);
}
|
C
|
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "../src/block/copy.h"
#include "../src/block/discovery.h"
#include "../src/utility.h"
void *read_binary(const char *path, size_t *size) {
FILE *f = fopen(path, "rb");
if (f == NULL) {
fprintf(stderr, "Could not open file '%s'\n", path);
*size = 0;
return NULL;
}
fseek(f, 0, SEEK_END);
*size = ftell(f);
fseek(f, 0, SEEK_SET);
void *code = malloc(*size);
if (code == NULL) {
fprintf(stderr, "Could not allocate %zu bytes for code\n", *size);
fclose(f);
return NULL;
}
fread((void *)code, *size, 1, f);
fclose(f);
return code;
}
void *copy_code(void *entry_point, size_t *target_size) {
void *entrypoints[] = {entry_point, NULL};
BlockList *blocks = discover_blocks(entrypoints);
if (blocks == NULL) {
fprintf(stderr, "Could not discover blocks\n");
return NULL;
}
*target_size = estimate_target_code_size(blocks);
assert(*target_size > 0);
PRINT_DEBUG("Target code size estimate = %.1fkB",
(float)*target_size / 1024.);
PRINT_DEBUG("Allocating target memory");
void *target_mem = malloc(*target_size);
assert(target_mem != NULL);
PRINT_DEBUG("Target base is %p", target_mem);
if (!copy_blocks(blocks, target_mem, *target_size)) {
fprintf(stderr, "Could not copy modified blocks\n");
return NULL;
}
void *target_entrypoint = get_target_address(entrypoints[0], blocks);
free_block_list(blocks);
PRINT_DEBUG("Target entry point is %p", target_entrypoint);
return target_mem;
}
|
C
|
#include <stdio.h>
void main()
{
int x[7]={200,300,400,500,600,848,545},val, i;
clrscr();
/*for(i=0;i<5;i++)
{
printf("\nval is :");
scanf("%d",&val);
if(val>=400)
x[i]=val*.20;
else
x[i]=val*.30;
} */
for(i=6;i>=0;i--)
printf("\nresult=%d",x[i]);
getch();
printf("\n%u\t%u\t%u",&x[1],x,&x);
getch();
}
|
C
|
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
void do_find(char*);
void process_entry(char *filename) {
struct stat info;
if(stat(filename, &info)==-1)
perror(filename);
else
if(S_ISDIR(info.st_mode)) {
printf("%s is a directory\n", filename);
//do_find(filename);
}
if(1){
/*strstr() should be used in the condition above*/
printf("Directory entry: %s\n", filename);
}
}
void do_find(char *dir_name) {
DIR *dir_ptr;
struct dirent *dirent_ptr;
dir_ptr=opendir(dir_name);
if(dir_ptr==0) {
perror("Cannot open directory");
}
else {
while((dirent_ptr=readdir(dir_ptr)) != 0)
process_entry(dirent_ptr->d_name);
closedir(dir_ptr);
}
}
int main(int ac, char *av[]) {
do_find(".");
return 0;
}
|
C
|
/*
* 3DAngle.h
*
* Created on: Aug 23, 2011
* Author: rmartz
*/
#ifndef ANGLE_3D_H_
#define ANGLE_3D_H_
struct Angle_3D {
double incline;
double turn;
};
typedef struct Angle_3D* Angle3D;
/** Creates a new 3DAngle object from a provided Vector object
* \param source The 3DVector object used to create the 3DAngle
* \return Pointer to a new 3DAngle object.
**/
Angle3D Angle3D_fromVector( Vector3D source );
/** Creates a new 3DAngle object from specified angles
* \param turn The direction along the X/Y axis for the angle
* \param incline The direction along the turn/Z axis for the angle
* \return Pointer to a new 3DAngle object.
**/
Angle3D Angle3D_fromAngle( double turn, double incline );
#endif /* ANGLE_3D_H_ */
|
C
|
#include "Cholesky.h"
/*
* typeof data is double *
*/
void Cholesky_updateStep(cncTag_t k, cncTag_t j, cncTag_t i, double *dataA1D, double *dataB1D, double *dataC1D, CholeskyCtx *ctx) {
int t = ctx->tileSize;
double (*dataA)[t] = (double(*)[t])dataA1D;
double (*dataB)[t] = (double(*)[t])dataB1D;
double (*dataC)[t] = (double(*)[t])dataC1D;
double temp;
int jB, kB, iB;
for (jB = 0; jB < t ; jB++ ) {
for (kB = 0; kB < t ; kB++) {
temp = 0 - dataC[ jB ][ kB ];
if (i != j)
for (iB = 0; iB < t ; iB++)
dataA[ iB ][ jB ] += temp * dataB[ iB ][ kB ];
else
for (iB = jB; iB < t; iB++)
dataA[ iB ][ jB ] += temp * dataC[ iB ][ kB ];
}
}
cncPut_data(dataA1D, j, i, k+1, ctx);
}
|
C
|
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#define MAX_CHAR 1000
#define MAX_SAME_VARS 10
#define MAX_WORD_SIZE 50
#define YES 1
#define NO 0
int COMMON_CHARS = 6;
char buffer[MAX_CHAR];
// Returns INT_MIN if s1 < s2 || INT_MAX if s1 > s2 || len if matched
int strsub(char *s1, char *s2, int common) {
//printf("\nSTRSUB: %s == %s", s1, s2);
int count = 0;
while(*s1++ == *s2++)
count++;
if(count == common)
return count;
else if(*(s1 - 1) < *(s2 - 1)) return INT_MIN;
return INT_MAX;
}
int curr_line_index = 0;
int getword(char *word, int limit, char *line) {
char *orig = word;
if(curr_line_index == strlen(line) - 1) return '\n';
while((isspace(line[curr_line_index]) || line[curr_line_index] == '(' || line[curr_line_index] == ')') && (line[curr_line_index] != '\n' && line[curr_line_index] != EOF))
{
curr_line_index++;
}
while(!isspace(line[curr_line_index]) && (line[curr_line_index] != '(') && (line[curr_line_index] != ')') && line[curr_line_index] != '\n' && line[curr_line_index] != EOF)
{
*(word++) = line[curr_line_index++];
}
*word = '\0';
word = orig;
//curr_line_index++;
return *word;
}
int istypedef(char *word) {
char *types[] = {
"int",
"float",
"long",
"double",
"short",
"char",
"unsigned"
};
for(int i = 0; i < sizeof(types)/sizeof(types[0]); i++) {
if(*word != types[i][0]) continue;
else if(!strcmp(word, types[i])) // Matching
return 1;
}
return 0;
}
struct tnode {
char *words[MAX_SAME_VARS];
int word_index;
struct tnode *left;
struct tnode *right;
} *tree;
struct tnode* talloc() {
return (struct tnode *) malloc(sizeof(struct tnode));
}
void taddnode(struct tnode **t, char *word, int len) {
//printf("\nDEBUG: Tree %x", *t);
if(*t == NULL) {
struct tnode *temp = talloc();
temp->left = NULL;
temp->right = NULL;
temp->word_index = 0;
temp->words[temp->word_index] = (char *) malloc(sizeof(*word));
strcpy(temp->words[temp->word_index], word);
temp->word_index++;
*t = temp;
}
else {
//printf("\nDEBUG: Trying to alloc mem in else");
//printf("\nDEBUG: Adding new word %s to tree to root word %s & word_index = %d", word, (*t)->words[(*t)->word_index - 1], (*t)->word_index);
//printf("\nRANJANDEBUG: %s",(*t)->words[0]);
if(strsub((*t)->words[0], word, COMMON_CHARS) == INT_MIN) {
//printf("\nDEBUG: %s < %s", (*t)->words[0], word);
taddnode(&((*t)->right), word, len);
}
else if(strsub((*t)->words[0], word, COMMON_CHARS) == INT_MAX) {
//printf("\nDEBUG: %s > %s", (*t)->words[0], word);
taddnode(&((*t)->left), word, len);
}
else {
//printf("\nDEBUG: s1 == s2");
if((*t)->word_index > MAX_SAME_VARS) printf("\nOverflow");
(*t)->words[(*t)->word_index++] = (char *) malloc(sizeof(word));
strcpy((*t)->words[(*t)->word_index - 1], word);
// Add to words list
}
}
}
void traverse(char *buff, int len) {
char wordbuff[MAX_WORD_SIZE];
int store_next = 0;
int result;
//printf("\nDEBUG: Entered traverse()");
while((result = getword(wordbuff, MAX_WORD_SIZE, buff)) != '\n') {
//printf("\nCurrent word: %s | Result: %d", wordbuff, result);
if(istypedef(wordbuff))
{
//printf("\nDEBUG: This is a declarator, so store next!");
store_next = YES;
continue;
}
if(store_next) {
store_next = !store_next;
//printf("\nDEBUG: Storing: %s", wordbuff);
taddnode(&tree, wordbuff, MAX_WORD_SIZE);
}
}
}
void tprint(struct tnode *t) {
if(t != NULL) {
tprint(t->left);
printf("\nGROUP: ");
for(int i = 0; i < t->word_index; i++)
printf(" %s ", t->words[i]);
tprint(t->right);
}
}
int main(int argc, char *argv[]) {
char c;
char *filename;
tree = NULL;
if(argc != 3) {
return printf("\nUSAGE: tree-count-vars [file-name] [commonchars]\n");
}
FILE *prog = fopen(filename = *(++argv), "r");
COMMON_CHARS = isdigit(c = *(++argv)[0]) ? c - '0': 6;
if(prog != NULL) {
printf("\nOpened file: %s\nCommon: %d\n", filename, COMMON_CHARS);
while(fgets(buffer, MAX_CHAR, prog) != NULL) {
//printf("\nTraversing: %s", buffer);
traverse(buffer, MAX_CHAR);
curr_line_index = 0;
}
//printf("\nDEBUG: Closed file");
tprint(tree);
}
return 0;
}
|
C
|
#define _XOPEN_SOURCE
#include <stdio.h>
#include <stdlib.h>
double a[4000][4000];
double b[4000][4000];
double c[4000][4000];
int main(int argc, char * argv[])
{
int N;
int i, j, k;
if (argc > 1) N = atoi(argv[1]);
else N = 100;
for (i=0 ;i<N; i++)
for (j=0 ;j<N; j++) {
c[i][j] = 0;
a[i][j] = drand48();
b[i][j] = drand48();
}
for (i=0; i<N; i++)
for (j=0; j<N; j++)
for (k=0; k<N; k++) c[i][j] = c[i][j] + a[i][k]*b[k][j];
#ifdef VERBOSE
for (i=0; i<N; i++)
for (j=0; j<N; j++)
printf("C[%d][%d] = %f\n", i, j, c[i][j]);
#endif
}
|
C
|
#include "bst.h"
BST *b_insert(int v, BST *t) {
BST *tmp;
if (t == NULL) {
return a_make_node(v);
}
if (v < t->value) {
tmp = b_insert(v, t->left);
t->left = tmp;
} else if (v > t->value) {
tmp = b_insert(v, t->right);
t->right = tmp;
}
return t;
}
int c_find(int v, BST *t) {
if (t == NULL) {
return FALSE;
} else if (v == t->value) {
return TRUE;
} else if (v < t->value) {
return c_find(v, t->left);
} else {
return c_find(v, t->right);
}
}
BST *e_remove(int v, BST *t) {
BST *ret_node;
if (t == NULL) {
return NULL;
} else if (v == t->value) {
if (t->left == NULL) {
ret_node = t->right;
free(t);
return ret_node;
} else if (t->right == NULL) {
ret_node = t->left;
free(t);
return ret_node;
} else {
int min = d_find_min(t->right);
t->right = e_remove(min, t->right);
t->value = min;
}
} else if (v < t->value) {
t->left = e_remove(v, t->left);
} else {
t->right = e_remove(v, t->right);
}
return t;
}
|
C
|
#include <stdio.h>
int main(void){
int num;
printf("\n Է: ");
scanf("%d", &num);
// if elseif ִ if() ̸ elseif Ȯ
// ʰ ü if elseif ´
// if elseif ߺ ʾƾ ϸ ߺ ʴ
// if elseif Ͽ single if ۼϴ ͺ
// ʿ üũϴ ɾ ִ.
if (num<0){
printf("Է 0 ۴. \n");
}else if (num>0){
printf("Է 0 ũ. \n");
}else if (num==0){
printf("Է 0̴. \n");
}
return 0;
}
|
C
|
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<pthread.h>
void* threadfun(void* arg)
{
pthread_detach(pthread_self());
int fd=*(int*)arg;
int lien;
char buf[100]="";
while(recv(fd,buf,99,0)>0)
{
printf("收到%s\n",buf);
bzero(buf,sizeof(buf));
}
}
void main()
{
int fd=socket(AF_INET,SOCK_DGRAM,0);
// setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,NULL,0);
struct sockaddr_in myaddr;
bzero(&myaddr,sizeof(myaddr));
myaddr.sin_family =AF_INET;
myaddr.sin_port =htons(7980);
myaddr.sin_addr.s_addr =INADDR_ANY;
bind(fd,(struct sockaddr*)&myaddr,sizeof(myaddr));
struct sockaddr_in saddr;
bzero(&saddr,sizeof(saddr));
saddr.sin_family =AF_INET;
saddr.sin_port =htons(7979);
saddr.sin_addr.s_addr =inet_addr("192.168.7.114");
pthread_t tid;
pthread_create(&tid,NULL,threadfun,&fd);
while(1)
{
char buf[100]="";
printf("请输入:");
scanf("%s",buf);
sendto(fd,buf,strlen(buf),0,(struct sockaddr*)&saddr,sizeof(saddr));
}
}
|
C
|
#include <sys/mman.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main()
{
int fd=open("file",O_RDWR|O_CREAT,0600);
if(fd==-1)
{
perror("open failed!\n");
return -1;
}
char a[10]="world";
char *b=mmap(NULL,5,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
if((int)b==-1)
{
perror("mmap failed!\n");
return -1;
}
memcpy(b,a,5);
if(munmap(b,5)==-1)
perror("munmap failed!\n");
return 0;
}
|
C
|
#include <stdio.h>
int main(void)
{
int i, n, start;
printf("Enter number of days in month: ");
scanf("%d", &n);
printf("Enter starting day of the week (1=Sun, 7=Sat): ");
scanf("%d", &start);
printf("\n Sun Mon Tue Wed Thu Fri Sat\n");
for (i = 1; i < start; i++) // prints empty space before 1st
printf(" ");
for (i = 1; i <= n; i++)
{
printf("%4d", i);
if ((i + start - 1) % 7 == 0) printf("\n");
}
printf("\n\n");
return 0;
}
|
C
|
#include <stdio.h>
#define MAXIMO 100 // maximo de vendedoras
float plantilla[MAXIMO + 1][5]; //(antiguedad, sueldobase, nroprodVendidos, totalVentas, comision)
float calculaSueldo(float sueldo,float i,float m,float s,float ant){
if(ant < 5)return sueldo + sueldo * i;
if(ant < 10)return sueldo + sueldo * m;
return sueldo + sueldo * s;
}
void leer(int n, float inf, float med, float sup, float comision){
printf("---Ingrese los datos de planilla para este mes:---\n");
int i;
float sueldo;
for(i = 1; i <= n; i++){
printf("---VENDEDORA %d---\n", i);
printf("Antiguedad: ");
scanf("%f", &plantilla[i][0]);
printf("sueldo(sin contar la antiguedad): ");
scanf("%f", &sueldo);
// sueldo segun la antiguedad
plantilla[i][1] = calculaSueldo(sueldo, inf, med, sup, plantilla[i][0]);
printf("Nro Ventas: ");
scanf("%f", &plantilla[i][2]);
printf("Total Recaudado por ventas: ");
scanf("%f", &plantilla[i][3]);
plantilla[i][4] = plantilla[i][3]*comision; // comisiones ganadas
}
}
void mostrarResultados(int n){
int i;
printf("---Sueldos y Comisiones por empleado:---\n");
for(i = 1; i <= n; i++){
printf("***VENDEDOR %d***\n", i);
printf("Total Sueldo: %.2f\n", plantilla[i][1]);
printf("Total Comision: %.2f\n", plantilla[i][4]);
}
}
int main(){
int n;
float porcentajeInf = 0.05; // 0 <= antiguedad < 5 => 5% por antiguedad
float porcentajeMed = 0.10; // 5 <= antiguedad < 10 => 10% por antiguedad
float porcentajeSup = 0.15; // 10 <= antiguedad => 15% por antiguedad
float comisionVentas = 0.10; // comision por el total de ventas realizadas
printf("Ingrese el numero de vendedoras: ");
scanf("%d", &n);
leer(n, porcentajeInf, porcentajeMed, porcentajeSup, comisionVentas);
mostrarResultados(n);
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char alp;
printf("\nEnter any alphabat...");
scanf("%c",&alp);
if( (alp>='a' && alp<='z') || (alp>='A' && alp<='Z'))
{
printf("%c is an alphabet.",alp);
else
printf("%c is not an alphabet.",alp)
}
switch(alp)
{
case 'a':printf("\nVowel");
break;
case 'e':printf("\nVowel");
break;
case 'i':printf("\nVowel");
break;
case 'o':printf("\nVowel");
break;
case 'u':printf("\nVowel");
break;
case 'A':printf("\nVowel");
break;
case 'E':printf("\nVowel");
break;
case 'I':printf("\nVowel");
break;
case 'O':printf("\nVowel");
break;
case 'U':printf("\nVowel");
break;
default:printf("\nIt is a consonant");
}
getch();
}
|
C
|
/*
* File: driver.c
* Authors: Christian Soto
*
* Purpose: The purpose of this file is to act as a main program for the
* makefile reader program.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "utils.h"
int main (int argc, char *argv[]){
//variables that will be needed
FILE *fp;
size_t n =0;
char *line=NULL;
char *filename=NULL;
char *tName=NULL;
char *targetName=NULL;
char *commandStr=NULL;
target *list=NULL;
//if too many arumenets are given then it is an error and exit the program
if(argc > 4){
fprintf(stderr, "Usage: example_makeThis [-f <file>] [target]\n");
exit(1);
}
//variables that will be need for error checking
int fileN = 0;
int targetN =1;
int i;
//loop thorugh the arguements starting at 1
for(i=1; i<argc; i++){
//if the -f flag is found, then incrmenet the fileN
//to indecate a filename is needed
if(strcmp(argv[i], "-f")==0){
fileN =1;
continue;
}//if statment
//if fileN is 1 then wee need to look and open file
if(fileN==1){
filename=strdup(argv[i]);
//error check for strdup
if(filename==NULL){
fprintf(stderr, "No memory left\n");
exit(1);
}
//once we get filename, fileN is set to 0
fileN=0;
continue;
}//if statement 2
if(targetN==1){
tName = strdup(argv[i]);
if(tName==NULL){
fprintf(stderr, "No memory left\n");
exit(1);
}
targetN=0;
}else{
fprintf(stderr,"Duplicate Targets\n");
exit(1);
}//if else
}
if(fileN==1){
fprintf(stderr,"No file given\n");
exit(1);
}
if(filename==NULL){
filename=strdup("makefileDefault");
if(filename==NULL){
fprintf(stderr,"out of Memory\n");
exit(1);
}
}
fp = fopen(filename, "r");
if(fp==NULL){
fprintf(stderr, "The file '%s' did not exist.\n", filename);
exit(1);
}//if statement
while(1){
line = NULL;
n = 0;
if(getline(&line, &n, fp)<0){
break;
}
line[strlen(line)-1]='\0';
if(line[0]== '\t'){
commandStr = trimwhitespace(line);
if(targetName==NULL){
fprintf(stderr,"Command with no target\n");
exit(1);
}else{
addCommand(list, targetName, commandStr);
}
}else{
line = trimwhitespace(line);
if(strlen(line)==0){
continue;
}
if (countTargets(line) != 1) {
fprintf(stderr,"Invalid Target line\n");
exit(1);
}
char * pch;
pch = strtok (line, ": \t");
if(pch == NULL){
fprintf(stderr,"Error, invalid target line\n");
exit(1);
}else{
targetName = trimwhitespace(pch);
list=addTarget(list,targetName, 1);
pch = strtok(NULL, ": \t");
while(pch !=NULL){
list = addTarget(list, pch, 0);
addDep(list, targetName, pch);
pch = strtok(NULL, ": \t");
}
}
}
}
//printList(list);
//no targets
if(tName==NULL){
if(list!=NULL){
tName = list->targetName;
}
}
postOrder(list, tName);
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{int a[10],sum=0,*p,i,n;
clrscr();
p=&a;
printf("Enter no. of Elements<=10:");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",p+i);
for(i=0;i<n;i++)
sum=sum+(*(p+i));
printf("Sum=%d",sum);
getch();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "arvore.h"
void inicArvore(struct Node **r)
{
(*r) = NULL;
}
void insere(struct Node **r, struct Node *novo)
{
if((*r) != NULL){
if(strcmp((*r)->contato.nome, novo->contato.nome) > 0){
if((*r)->esq == NULL)
(*r)->esq = novo;
else
insere(&(*r)->esq, novo);
}
else{
if((*r)->dir == NULL)
(*r)->dir = novo;
else
insere(&(*r)->dir, novo);
}
}
else
(*r) = novo;
(*r)->h = 1 + max(altura((*r)->esq), altura((*r)->dir)); //atualizar a altura
//testar se arvore está desbalanceada e chamar a rotação certa
if(FB(*r) > 1){
if(FB((*r)->dir) > 0)
*r = RE(*r);
else
*r = RDE(*r);
}
else if(FB(*r) < -1){
if(FB((*r)->esq) < 0)
*r = RD(*r);
else
*r = RED(*r);
}
}
void insereNode(struct Node **r, struct Contato temp)
{
struct Node *novo = malloc(sizeof(struct Node));
novo->contato = temp;
novo->esq = NULL;
novo->dir = NULL;
novo->h = 1; //um único nó tem altura 1
insere(r, novo);
}
void excluirNode(struct Node **r, char *nome)
{
struct Node *aux;
if((*r) != NULL){
if(strcmp(nome, (*r)->contato.nome) == 0){
aux = (*r);
if((*r)->esq == NULL)
(*r) = (*r)->dir;
else
if((*r)->dir == NULL)
(*r) = (*r)->esq;
else{
aux = encontrarMaiorEAjeitar(&((*r)->esq));
(*r)->contato = aux->contato;
}
excluirListaTelefones(&aux->contato.telefones);
free(aux);
}
else{
if(strcmp(nome, (*r)->contato.nome) < 0)
excluirNode(&((*r)->esq), nome);
else
excluirNode(&((*r)->dir), nome);
}
}
}
struct Node * encontrarMaiorEAjeitar(struct Node **r)
{
struct Node *aux = (*r);
if((*r)->dir == NULL){
(*r) = (*r)->esq;
return(aux);
}
else
return encontrarMaiorEAjeitar(&((*r)->dir));
}
struct Node *localizarNode(struct Node *r, char *nome)
{
if(!r)
return NULL;
else if(strcmp(r->contato.nome, nome) == 0)
return r;
else if(strcmp(r->contato.nome, nome) > 0)
return (localizarNode(r->esq, nome));
else
return (localizarNode(r->dir, nome));
}
void printEmOrdemCrescente(struct Node *r)
{
if(r != NULL){
printEmOrdemCrescente(r->esq);
printf("%s\n", r->contato.nome);
printTelefones(&r->contato.telefones);
printEmOrdemCrescente(r->dir);
}
}
void printEmOrdemDecrescente(struct Node *r)
{
if(r != NULL){
printEmOrdemDecrescente(r->dir);
printf("%s\n", r->contato.nome);
printTelefones(&r->contato.telefones);
printEmOrdemDecrescente(r->esq);
}
}
void printPreOrdem(struct Node *r)
{
if(r != NULL){
printf("%s\n", r->contato.nome);
printTelefones(&r->contato.telefones);
printPreOrdem(r->esq);
printPreOrdem(r->dir);
}
}
//retorna o maior entre 2 números
int max(int a, int b)
{
return (a > b)? a : b;
}
//retorna a altura do nó ou 0 se o ponteiro for NULL
int altura(struct Node *r)
{
if(!r)
return 0;
return r->h;
}
//retorna o fator de balanceamento(diferença das alturas da subárvore direita e esquerda) ou 0 se o ponteiro for NULL
int FB(struct Node *y)
{
if(!y)
return 0;
return (altura(y->dir) - altura(y->esq));
}
//rotação esquerda
struct Node *RE(struct Node *y)
{
struct Node *x = y->dir;
struct Node *aux = x->esq;
x->esq = y;
y->dir = aux;
y->h = 1 + max(altura(y->esq), altura(y->dir));
x->h = 1 + max(altura(x->esq), altura(x->dir));
return x;
}
//rotação direita
struct Node *RD(struct Node *y)
{
struct Node *x = y->esq;
struct Node *aux = x->dir;
x->dir = y;
y->esq = aux;
y->h = 1 + max(altura(y->esq), altura(y->dir));
x->h = 1 + max(altura(x->esq), altura(x->dir));
return x;
}
//rotação esquerda direita
struct Node *RED(struct Node *y)
{
y->esq = RE(y->esq);
return RD(y);
}
//rotação direita esquerda
struct Node *RDE(struct Node *y)
{
y->dir = RD(y->dir);
return RE(y);
}
|
C
|
#include <unistd.h>
#include <stdio.h>
int main()
{
//1 标准输出 常开
char str[20] = "1234567";
//close(1);
int ret = write(1,str,sizeof(str));
printf("ret = %d\n",ret);
}
|
C
|
#include <stdio.h>
#define BUFSIZE 1024
int main(int argc, char *argv[])
{
int byteCount;
FILE *in, *out;
char buf[BUFSIZE];
//실행시 파라메터의 입력이 정상인지 확인
if(argc != 3)
{
//write(2, "Usage : fcopy file1 file2\n", 27); // 밑과 같음
fprintf(stderr, "Usage : fcopy file1 file2\n");
return -1;
}
//원본파일을 읽기보드로 열기 if((in=fopen(argv[1], "r")) == NULL)
{
perror(argv[1]);
return -1;
}
//대상파일을 쓰기용으로 열기
if((out=fopen(argv[2], "w")) == NULL)
{
perror(argv[2]);
return -1;
}
while((byteCount = fread(buf, size(char), BUFSIZE, in)) > 0)
fwrite(buf, sizeof(char), byteCount, out);
fclose(in);
fclose(out);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yfu <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/04 21:43:43 by yfu #+# #+# */
/* Updated: 2021/05/04 23:45:19 by yfu ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "utils.h"
#include <fcntl.h>
static void sub(t_deque *stack[2], int *arr[3], int arr_size, int ct[2])
{
stack[0] = deque_init();
stack[1] = deque_init();
if (!stack[0] || !stack[1])
error_exit();
init_stack(stack[0], arr[0], arr_size);
arr[1] = ft_malloc(arr_size, sizeof(int));
if (!arr[1])
error_exit();
ct[0] = -1;
while (++ct[0] < arr_size)
arr[1][ct[0]] = arr[0][ct[0]];
arr[2] = ft_malloc(arr_size, sizeof(int));
if (!arr[2])
error_exit();
ct[0] = -1;
while (++ct[0] < arr_size)
arr[2][ct[0]] = arr[0][ct[0]];
ft_sort(arr[1], arr[1] + arr_size, ft_ascending);
descretize_stack(stack[0], arr[1], arr_size);
}
int main(int argc, char **argv)
{
int *arr[3];
int arr_size;
t_deque *stack[2];
int ct[2];
t_deque *instructions;
arr_size = get_nbr_in_line(arr, argc, argv);
if (arr_size < 2)
normal_exit();
sub(stack, arr, arr_size, ct);
instructions = push_swap(stack);
ct[1] = open("instructions", O_WRONLY | O_CREAT | O_TRUNC, 0777);
if (ct[1] < 0)
error_exit();
display_instructions(instructions, arr[2], arr_size, ct[1]);
close(ct[1]);
normal_exit();
}
|
C
|
//---------------------------------------------------------
// file: particle.c
// author: Dania Mohd
//
// contributors: Lee Jia Keat(death_particle), Bryan Koh Yan Wei(DeathP)
// email: nuruldania.b@digipen.edu, l.jiakeat@digipen.edu, yanweibryan.koh@digipen.edu
//
// brief: Simple particle system.
// Handles initialization, spawning, updating and destroying of particles.
//
// Copyright 2020 DigiPen, All rights reserved.
//---------------------------------------------------------
#include "particle.h"
#include "game.h"
#include "constants.h"
#include "player.h"
#include "utility.h"
#include <math.h>
CP_Vector pos;
//Particle pool
Particle particle[10000];
Particle smoke_particle[1];
Particle death_particles[10];
static float smoke_spawn_interval;
static Particle* smoke_ptr;
enum ParticleType {NONE, EXPLOSION, SMOKE, DEATH};
//Struct to hold data for Explosion particles
struct Explosion
{
Sprite explosion_sprite;
CP_Image image[8];
CP_Vector dimensions[8];
int image_count;
float delay;
}explosion;
struct Smoke
{
Sprite smoke_sprite;
CP_Image image[3];
CP_Vector dimensions[3];
int image_count;
float delay;
}smoke;
struct Death_Particle
{
Sprite death_sprite;
CP_Vector min_velocity;
CP_Vector max_velocity;
float min_size;
float max_size;
float current_lifespan;
}death_particle;
#define DVFXSize 200
typedef struct DeathP
{
CP_Image sprite[DVFXSize];
CP_Vector pos[DVFXSize];
CP_Vector aceeleration[DVFXSize];
CP_Vector dimension;
float current_lifespan, max_lifespan;
bool enabled;
}DeathP;
DeathP DP;
CP_Image DParticle;
/// <summary>
/// Initialize Particles
/// </summary>
/// <param name="void"></param>
void particle_init()
{
for (int i = 0; i < sizeof(particle) / sizeof(particle[0]); i++)
{
particle[i].posX = 0;
particle[i].posY = 0;
particle[i].velocity.x = 0;
particle[i].velocity.y = 0;
particle[i].enabled = 0;
particle[i].lifetime = 0;
particle[i].life = 0;
particle[i].id = 0;
particle[i].loop = false;
}
DParticle = CP_Image_Load("./Assets/reddot.png");
DP.enabled = false;
}
void explosion_init(void)
{
explosion.image[0] = CP_Image_Load("./Assets/Explosion/Image001.png");
explosion.image[1] = CP_Image_Load("./Assets/Explosion/Image002.png");
explosion.image[2] = CP_Image_Load("./Assets/Explosion/Image003.png");
explosion.image[3] = CP_Image_Load("./Assets/Explosion/Image004.png");
explosion.image[4] = CP_Image_Load("./Assets/Explosion/Image005.png");
explosion.image[5] = CP_Image_Load("./Assets/Explosion/Image006.png");
explosion.image[6] = CP_Image_Load("./Assets/Explosion/Image007.png");
explosion.image[7] = CP_Image_Load("./Assets/Explosion/Image008.png");
explosion.image_count = 8;
for (int i = 0; i < explosion.image_count; i++)
{
explosion.dimensions[i].x = (float)CP_Image_GetWidth(explosion.image[i]) * ASTEROIDS_SPRITE_EXPLOSION_DIMENSIONS_SCALE_FACTOR;
explosion.dimensions[i].y = (float)CP_Image_GetHeight(explosion.image[i]) * ASTEROIDS_SPRITE_EXPLOSION_DIMENSIONS_SCALE_FACTOR;
}
explosion.delay = 0.1f;
explosion.explosion_sprite = Asteroids_Sprite_Create_Animated(explosion.image, explosion.dimensions, explosion.image_count, explosion.delay * explosion.image_count, 0);
}
void smoke_init()
{
smoke.image[0] = CP_Image_Load("./Assets/SmokeTrail/smoke_0.png");
smoke.image[1] = CP_Image_Load("./Assets/SmokeTrail/smoke_1.png");
smoke.image[2] = CP_Image_Load("./Assets/SmokeTrail/smoke_2.png");
smoke.image_count = 3;
for (int i = 0; i < smoke.image_count; i++)
{
smoke.dimensions[i].x = (float)CP_Image_GetWidth(smoke.image[i]);
smoke.dimensions[i].y = (float)CP_Image_GetHeight(smoke.image[i]);
}
smoke.delay = 0.1f;
smoke.smoke_sprite = Asteroids_Sprite_Create_Animated(smoke.image, smoke.dimensions, smoke.image_count, smoke.delay * smoke.image_count, 0);
}
void Asteroids_Particles_Player_Death_Particle_Init()
{
CP_Image image = CP_Image_Load("./Assets/reddot.png");
float width = (float)CP_Image_GetWidth(image);
float height = (float)CP_Image_GetHeight(image);
death_particle.death_sprite = Asteroids_Sprite_Create_Static(image, CP_Vector_Set(width, height));
}
void Asteroids_Particle_Player_Death_Particle_Spawn(CP_Vector player_pos)
{
Spawn_Particle_Static(player_pos, 100, CP_Vector_Set(-100, -100), CP_Vector_Set(100, 100), 0.2f, death_particle.death_sprite, 10.0f);
}
void draw_particle()
{
for (int i = 0; i < sizeof(particle) / sizeof(particle[0]); i++)
{
if (particle[i].enabled)
{
if (particle[i].animated)
{
int keyframe = particle[i].sprite.keyframe;
CP_Vector dimensions = particle[i].sprite.dimensions[keyframe];
CP_Image_Draw(particle[i].sprite.images[keyframe], particle[i].posX, particle[i].posY, particle[i].size * dimensions.x, particle[i].size * dimensions.y, (int)(particle[i].lifetime / particle[i].life * 255.0f));
}
else
{
CP_Image_Draw(particle[i].sprite.image, particle[i].posX, particle[i].posY, particle[i].size * particle[i].sprite.width, particle[i].size * particle[i].sprite.height, (int)(particle[i].lifetime / particle[i].life * 255.0f));
}
}
}
}
//Generate particle velocity and set lifetime.
Particle* Spawn_Particle_Animated(CP_Vector position, int particles, float min_velocity,
float max_velocity, float size, Sprite sprite, int type, bool loop)
{
CP_Vector velocity;
for (int i = 0; i < sizeof(particle) / sizeof(particle[0]); i++)
{
if (particle[i].enabled == 0)
{
velocity.x = CP_Random_RangeFloat(min_velocity, max_velocity);
velocity.y = CP_Random_RangeFloat(min_velocity, max_velocity);
particle[i].sprite = sprite;
particle[i].enabled = 1;
particle[i].animated = true;
particle[i].posX = position.x;
particle[i].posY = position.y;
particle[i].velocity = velocity;
particle[i].life = particle[i].sprite.duration;
particle[i].lifetime = particle[i].life;
particle[i].size = size;
particle[i].loop = loop;
particle[i].id = type;
return &particle[i];
}
}
return NULL;
}
void Spawn_Particle_Static(CP_Vector position, int particle_count, CP_Vector min_velocity, CP_Vector max_velocity, float size, Sprite sprite, float life_span)
{
CP_Vector velocity;
for (int i = 0; i < sizeof(particle) / sizeof(particle[0]); i++)
{
if (particle[i].enabled == 0)
{
if ((particle_count) <= 0)
return;
velocity.x = CP_Random_RangeFloat(min_velocity.x, max_velocity.x);
velocity.y = CP_Random_RangeFloat(min_velocity.y, max_velocity.y);
particle[i].size = size;
particle[i].sprite = sprite;
particle[i].enabled = 1;
particle[i].animated = false;
particle[i].posX = position.x;
particle[i].posY = position.y;
particle[i].velocity = velocity;
particle[i].lifetime = life_span;
particle[i].life = life_span;
particle[i].id = DEATH;
particle_count--;
}
}
}
void spawn_explosion_anim(CP_Vector position, float size)
{
int particles = 1;
float min_velocity = 0;
float max_velocity = 0;
Spawn_Particle_Animated(position, particles, min_velocity, max_velocity, size, explosion.explosion_sprite, EXPLOSION, false);
}
void spawn_smoke_trail_anim(CP_Vector position, float size)
{
int particles = 1;
float min_velocity = 0;
float max_velocity = 0;
smoke_ptr = Spawn_Particle_Animated(position, particles, min_velocity, max_velocity, size, smoke.smoke_sprite, SMOKE, true);
}
void particle_update()
{
float dt = CP_System_GetDt();
for (int i = 0; i < sizeof(particle) / sizeof(particle[0]); i++)
{
if (particle[i].enabled)
{
particle[i].posX += particle[i].velocity.x * dt;
particle[i].posY += particle[i].velocity.y * dt;
if (particle[i].animated)
{
if (particle[i].loop == false)
{
particle[i].lifetime -= dt;
}
particle[i].sprite.time -= dt;
if (particle[i].sprite.time <= 0)
{
particle[i].sprite.time = particle[i].sprite.duration / particle[i].sprite.frame_count;
if (particle[i].sprite.keyframe >= (particle[i].sprite.frame_count - 1))
{
if (particle[i].loop)
particle[i].sprite.keyframe = 0;
}
else
particle[i].sprite.keyframe++;
}
}
else
{
particle[i].lifetime -= dt;
}
if (particle[i].lifetime <= 0)
{
particle[i].posX = 0;
particle[i].posY = 0;
particle[i].velocity.x = 0;
particle[i].velocity.y = 0;
particle[i].enabled = 0;
particle[i].lifetime = 0;
particle[i].sprite.time = 0;
particle[i].sprite.keyframe = 0;
}
}
}
draw_particle();
}
void smoke_update(CP_Vector rotation, CP_Vector playerPos)
{
rotation = CP_Vector_Scale(rotation, 40);
playerPos = CP_Vector_Subtract(playerPos, rotation);
smoke_ptr->posX = playerPos.x;
smoke_ptr->posY = playerPos.y;
}
void Asteroids_Player_Death_VFX_Spawn(Player* player)
{
if (!DP.enabled)
{
for (int i = 0; i < DVFXSize; i++)
{
DP.sprite[i] = DParticle;
DP.pos[i] = player->pos;
DP.aceeleration[i] = CP_Vector_Set(CP_Random_RangeFloat(-250, 250), CP_Random_RangeFloat(-250, 250));
DP.aceeleration[i] = CP_Vector_Normalize(DP.aceeleration[i]);
}
DP.current_lifespan = 5.0f;
DP.max_lifespan = 5.0f;
DP.dimension = CP_Vector_Set(25, 25);
DP.enabled = true;
}
}
void Asteroids_Player_Death_VFX_Update(Player* player)
{
if (DP.enabled)
{
DP.current_lifespan -= CP_System_GetDt();
if (DP.current_lifespan > 0)
{
for (int i = 0; i < DVFXSize; i++)
{
DP.pos[i] = CP_Vector_Add(DP.pos[i], CP_Vector_Scale(DP.aceeleration[i], CP_Random_RangeFloat(25, 250) * CP_System_GetDt()));
CP_Image_Draw(DP.sprite[i], DP.pos[i].x, DP.pos[i].y, DP.dimension.x, DP.dimension.y, (int)(DP.current_lifespan / DP.max_lifespan * 255));
}
}
}
if (DP.current_lifespan < 0)
{
Asteroids_Player_Death_VFX_Despawn(player);
}
}
void Asteroids_Player_Death_VFX_Despawn(Player* player)
{
DP.enabled = false;
player->active = 0;
}
|
C
|
#include<stdio.h>
/*program to extract digits of a number*/
int main() //main begins here
{
int num;
scanf("%d",&num); //taking input
printf("The digits are:");
while(num>0) //extracting digits
{
printf("%d\t",num%10);
num/=10;
}
return 0; //end of the program
}
|
C
|
#include "menu_fechas.h"
#include "menu_tp_1.h"
void menu_fechas()
{
int opcion;
system("cls");
printf("Trabajo practico 1 - Ejercicios con fechas\n");
printf("\n--------------------------\n");
printf("\n1. Validar fecha");
printf("\n2. Sumar un dia a una fecha");
printf("\n3. Sumarle n dias a un fecha");
printf("\n4. Restarle n dias a una fecha");
printf("\n5. Diferncia en dias entre dos fechas");
printf("\n6. Mostrar dia de la semana segun un fecha");
printf("\n7. Volver");
printf("\nIngrese una opcion: ");
scanf("%d", &opcion);
switch(opcion)
{
case 1:
validar_fecha();
break;
case 2:
dia_siguiente();
break;
case 3:
sumar_dias_a_una_fecha();
break;
case 4:
restarle_dias_a_una_fecha();
break;
case 5:
diferencia_entre_fechas();
break;
case 6:
dias_de_la_semana();
break;
case 7:
menu_tp_1();
break;
default:
printf("\nIngrese una opcion correcta: ");
scanf("%d", &opcion);
break;
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <winsock.h>
#define MAXLINE 1024
int main(int argc, char** argv) {
SOCKET sd;
struct sockaddr_in serv;
char str[1024];
char str_r[1024];
WSADATA wsadata;
int n;
WSAStartup(0x101,(LPWSADATA) &wsadata); // Is WSAStartup() U WinSock DLL ϥ
sd=socket(AF_INET, SOCK_STREAM, 0); //}Ҥ@ TCP socket.
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = inet_addr("127.0.0.1");
serv.sin_port = htons(5678);
connect(sd, (LPSOCKADDR) &serv, sizeof(serv)); // s echo server
printf("пJIP} : \n");
gets(str);
send(sd, str, strlen(str)+1, 0); //ǰe
//printf( "send: %s (%d bytes)\n" ,str,strlen(str)+1);
n=recv(sd, str_r, MAXLINE, 0); //
printf("IP}W٬ : \n%s \n",str_r);
printf("пJ} : \n");
gets(str);
send(sd, str, strlen(str)+1, 0); //ǰe
n=recv(sd, str_r, MAXLINE, 0); //
printf("ӥDW٬ : \n%s \n",str_r);
printf("пJSERVICE : \n");
gets(str);
send(sd, str, strlen(str)+1, 0); //ǰe
n=recv(sd, str_r, MAXLINE, 0); //
printf("SERVICE PORT : \n%s \n",str_r);
printf("пJPORT : \n");
gets(str);
send(sd, str, strlen(str)+1, 0); //ǰe
n=recv(sd, str_r, MAXLINE, 0); //
printf("PORT SERVICE : \n%s \n",str_r);
char proto[1024]="";
printf("пJPROTOCOL : \n");
gets(str);
send(sd, str, strlen(str)+1, 0); //ǰe
n=recv(sd, proto, MAXLINE, 0); //
printf("PROTOCOL s : \n%s \n",proto);
printf("пJPROTOCOL NUMBER : \n");
gets(str);
send(sd, str, strlen(str)+1, 0); //ǰe
n=recv(sd, str_r, MAXLINE, 0); //
printf("PROTOCOL : \n%s \n",str_r);
closesocket(sd); //TCP socket
WSACleanup(); // WinSock DLL ϥ
return 0;
}
|
C
|
#include "../inc/io.h"
int matrix_fill(matrix_t *matrix)
{
if (fscanf(stdin, "%d", &matrix->row) != 1)
return MATRIX_FILL_PARAMETR_ERROR;
if (matrix->row < 1)
return MATRIX_FILL_PARAMETR_ERROR;
if (fscanf(stdin, "%d", &matrix->column) != 1)
return MATRIX_FILL_PARAMETR_ERROR;
if (matrix->column < 1)
return MATRIX_FILL_PARAMETR_ERROR;
if (allocate_matrix(matrix) != OK)
return MEMORY_ALLOCATION_ERROR;
LOG_INFO("ROW=%d COLUMN=%d", matrix->row, matrix->column);
for (int i = 0; i < matrix->row; i++)
{
for (int j = 0; j < matrix->column; j++)
{
if (fscanf(stdin, "%d", &matrix->matrix[i][j]) != 1)
return MATRIX_FILL_ELEMENT_ERROR;
}
}
return OK;
}
void matrix_result_print(matrix_t *matrix)
{
for (int i = 0; i < matrix->row; i++)
{
for (int j = 0; j < matrix->column; j++)
{
printf("%20d ", matrix->matrix[i][j]);
}
printf("\n");
}
printf("\n");
}
|
C
|
/*
取模
*/
bool isUgly(int num) {
if (num == 1)
return true;
if (num <= 0)
return false;
while (num!=1)
{
if (num % 2 == 0)
{
num = num / 2;
continue;
}
if (num % 3 == 0)
{
num = num / 3;
continue;
}
if (num % 5 == 0)
{
num = num / 5;
continue;
}
return false;
}
return true;
}
|
C
|
#define _GNU_SOURCE
#include <assert.h>
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include "client_thread.h"
#include "buffer.h"
#include "../include/hash_table.h"
#define BUFFER_SIZE 8192
static int open_client_fd(char *hostname, int port, int *err) {
int client_fd = socket(AF_INET, SOCK_STREAM, 0);
if (client_fd < 0) {
return -1;
}
/* Fill in the server's IP address and port */
struct addrinfo *address;
char port_str[sizeof("65535")];
sprintf(port_str, "%d", port);
*err = getaddrinfo(hostname, port_str, NULL, &address);
if (*err != 0) {
return -2;
}
/* Establish a connection with the server */
bool success = connect(client_fd, address->ai_addr, address->ai_addrlen) >= 0;
freeaddrinfo(address);
return success ? client_fd : -1;
}
/* Writes a string to a file descriptor, returns whether successful */
static bool write_string(int fd, char *str) {
return write(fd, str, strlen(str)) >= 0;
}
/* Sends a status message to client with the status line specified by
* status with a message body described by msg.
* Returns whether successful */
static bool send_status_code(int client_fd, char *status, char *msg) {
char *format =
"HTTP/1.0 %s\r\n"
"Content-Type: text/html\r\n"
"Connection: close\r\n"
"\r\n"
"<html>"
"<head><title>%s</title></head>"
"<body>%s</body>"
"</html>";
/* Fill out the response template and send it to the client */
char response[strlen(format) + 2 * strlen(status) + strlen(msg)];
sprintf(response, format, status, status, msg);
return write_string(client_fd, response);
}
/* Opens connection to full_host and returns the file descriptor or
* returns -1 on error */
static int open_server_connection(int client_fd, char *full_host) {
int port;
char *port_str = strchr(full_host, ':');
if (port_str == NULL) {
port = 80;
}
else {
/* Host string was separated into hostname and port */
full_host[port_str - full_host] = '\0';
port = atoi(port_str + 1);
if (port <= 0 || port > 65535) {
verbose_printf("Malformed request string: Invalid port\n");
return -1;
}
}
/* Open connection to requested server */
int server_error;
int server_fd = open_client_fd(full_host, port, &server_error);
if (server_fd == -1) {
verbose_printf("open_client_fd error: %s\n", strerror(errno));
return -1;
}
if (server_fd == -2) {
switch (server_error) {
case EAI_FAIL:
case EAI_NONAME:
/* Don't bother checking exit code, since we are returning error
* afterwards anyway */
send_status_code(client_fd, "502 Bad Gateway",
"DNS could not resolve address.");
return -1;
case EAI_AGAIN:
/* Don't bother checking exit code, since we are returning error
* afterwards anyway */
send_status_code(client_fd, "502 Bad Gateway",
"DNS temporarily could not resolve address.");
return -1;
case EAI_NODATA:
/* Don't bother checking exit code, since we are returning error
* afterwards anyway */
send_status_code(client_fd, "502 Bad Gateway",
"DNS could has no network addresses for host.");
return -1;
}
verbose_printf("getaddrinfo error: %s\n", gai_strerror(server_error));
return -1;
}
return server_fd;
}
/* Send get request to server, returns whether successful */
static bool send_get_header(int server_fd, char *path) {
return write_string(server_fd, "GET ") &&
write_string(server_fd, path) &&
write_string(server_fd, " HTTP/1.0\r\n");
}
/* Reads a line from fd until a \r\n is reached. Returns an allocated
* buffer that must be freed by the user containing the line read in upon
* success. Returns NULL on error. */
static buffer_t *read_full_line(int fd) {
buffer_t *line = buffer_create(BUFFER_SIZE);
/* Read until we reach \r\n */
char c = '\0', last_c;
do {
last_c = c;
ssize_t chars_read = read(fd, &c, sizeof(c));
if (chars_read <= 0) {
if (chars_read < 0) {
/* Error occurred */
verbose_printf("Read error: %s\n", strerror(errno));
}
buffer_free(line);
return NULL;
}
buffer_append_char(line, c);
} while (!(last_c == '\r' && c == '\n'));
return line;
}
static bool starts_with(char *str, char *prefix) {
return strncmp(str, prefix, strlen(prefix)) == 0;
}
/* Produces a GET header from client's GET header
* Sets *full_host to the 'host:port' string specified in the GET
* Sets *path to the part of the GET request after the port, excluding
* the leading /
* *full_host and *path must be freed by the user if function returns 0.
* Returns whether successful. */
static bool make_get_header(int client_fd, char **full_host, char **path) {
*full_host = NULL;
*path = NULL;
/* Read the first line (with the GET request) separately */
buffer_t *buf = read_full_line(client_fd);
if (buf == NULL) {
verbose_printf("No request string\n");
goto MALFORMED_ERROR;
}
/* Parse first line. We are expecting one of a few cases:
* GET http://<HOST>/[<PATH>[/]] HTTP/..
* GET http://<HOST>:#..#/[<PATH>[/]] HTTP/..
*
* We reject any other request (and terminate the connection),
* because we believe it to be malformed.
*/
char* req;
char *data = buffer_string(buf);
char *prefix = strtok_r(data, " ", &req);
sleep(1);
char *url = strtok_r(NULL, " ", &req);
char *version = strtok_r(NULL, " ", &req);
if (prefix == NULL || url == NULL || version == NULL || strtok_r(NULL, " ", &req) != NULL) {
verbose_printf("Malformed request string: GET requests have"
" three parts\n");
goto MALFORMED_ERROR;
}
if (strcmp(prefix, "GET") != 0) {
verbose_printf("Unsupported request string: This proxy only"
" handles GET requests\n");
goto NOT_IMPLEMENTED_ERROR;
}
if (!starts_with(version, "HTTP/")) {
verbose_printf("Malformed request string: The third part of the"
" GET request should be an HTTP version\n");
goto MALFORMED_ERROR;
}
if (!starts_with(url, "http://")) {
verbose_printf("Malformed request string: The URL of the request"
" should start with 'http://'\n");
goto MALFORMED_ERROR;
}
char *host = url + strlen("http://");
/* Allocate path separately so we can free line buffer.
* The path starts at the first '/' in the URL.
* If there is no '/' (e.g. "http://ucla.edu"), the path is just "/". */
char *path_start = strchr(host, '/');
*path = strdup(path_start == NULL ? "/" : path_start);
assert(*path != NULL);
/* Copy host, so that we have a separate copy for later */
if (path_start != NULL) {
*path_start = '\0';
}
*full_host = strdup(host);
assert(*full_host != NULL);
printf("Handling Request: %s%s\n", *full_host, *path);
buffer_free(buf);
return true;
MALFORMED_ERROR:
/* Don't bother checking exit code, since we are returning error
* afterwards anyway */
send_status_code(client_fd, "400 Bad Request",
"Invalid request sent to proxy.");
goto ERROR;
NOT_IMPLEMENTED_ERROR:
/* Don't bother checking exit code, since we are returning error
* afterwards anyway */
send_status_code(client_fd, "501 Not Implemented",
"Invalid request sent to proxy.");
goto ERROR;
ERROR:
buffer_free(buf);
free(*path);
free(*full_host);
return false;
}
/* To be called after make_get_header. Reads the remaining headers from
* clientfd and sends them to serverfd after modification as follows:
*
* All Keep-Alive headers are dropped
* Connection headers have their value replaced with 'close'
* Proxy-Connection headers have their value replaced with 'close'
* If a Host header is not found, a Host header is added
*
* Returns whether successful
*/
static bool filter_rest_headers(int client_fd, int server_fd, char *host) {
bool sent_host_header = false, sent_connection_header = false;
while (true) {
buffer_t *buf = read_full_line(client_fd);
/* read_full_line() errored out */
if (buf == NULL) {
verbose_printf("Malformed header: Not terminated by new line\n");
return false;
}
char *line = buffer_string(buf);
/* Detect end of header (make sure we sent host line) */
if (strcmp(line, "\r\n") == 0) {
buffer_free(buf);
break;
}
/* Remove Keep-Alive line */
if (starts_with(line, "Keep-Alive:")) {
buffer_free(buf);
continue;
}
/* Deal with host line (if we recieve one */
if (starts_with(line, "Host:")) {
sent_host_header = true;
}
/* Connection: * -> Connection: close */
else if (starts_with(line, "Connection:")) {
line = "Connection: close\r\n";
sent_connection_header = 1;
}
/* Proxy-Connection: * -> Proxy-Connection: close */
else if (starts_with(line, "Proxy-Connection:")) {
line = "Proxy-Connection: close\r\n";
}
/* Send line to server */
bool success = write_string(server_fd, line);
buffer_free(buf);
if (!success) {
return false;
}
}
/* Done sending headers. Make sure the necessary headers were sent */
if (!sent_host_header) {
bool success = write_string(server_fd, "Host: ") &&
write_string(server_fd, host) &&
write_string(server_fd, "\r\n");
if (!success) {
return false;
}
}
if (!sent_connection_header) {
if (!write_string(server_fd, "Connection: close\r\n")) {
return false;
}
}
return write_string(server_fd, "\r\n");
}
/* Sends the server's response to the client.
* Returns whether successful */
static bool send_response(int client_fd, int server_fd, buffer_t *real_buffer) {
/* Loop until server sends an EOF */
//buffer_t *real_buffer = buffer_create(10);
while (true) {
uint8_t buf[BUFFER_SIZE];
ssize_t bytes_read = read(server_fd, buf, sizeof(buf));
if (bytes_read < 0) {
verbose_printf("read error: %s\n", strerror(errno));
return false;
}
buffer_append_bytes(real_buffer, buf, bytes_read);
/* Server sent EOF */
if (bytes_read == 0) {
//inserts into cache
//insert(host, real_buffer);
return true;
}
ssize_t bytes_written = write(client_fd, buf, bytes_read);
if (bytes_written < 0) {
return false;
}
}
}
//checks to see if the page is already cached
//if so, then the cache is written to the client_fd
//file descriptor, and true is returned
//otherwise, returns false
static bool already_cached(int client_fd, char *full_host) {
buffer_t *val = get(full_host);
//printf("\ni have gotten a cached item\n");
if (val != NULL){
///can't use strlen here
//TODO:
//put buffers in the cache instead of byte*
write(client_fd, buffer_data(val), buffer_length(val));
printf("\ni have printed a cached item\n");
return true;
}
//printf("\nnot already cached\n");
return false;
}
void *handle_request(void *cfd) {
pthread_detach(pthread_self());
int client_fd = *(int *) cfd;
free(cfd);
char *host = NULL, *path = NULL;
if (!make_get_header(client_fd, &host, &path)) {
goto CLIENT_ERROR;
}
// char *key = malloc(1 + strlen(host) + strlen(path));
// strcpy(key, host);
// strcat(key, path);
//check to see if the webpage is already cached
if (already_cached(client_fd, host)){
printf("\nalready cached\n");
//return get(key);
goto ALREADY_CACHED;
}
/* Establish connection with requested server */
int server_fd = open_server_connection(client_fd, host);
if (server_fd < 0) {
goto CLIENT_ERROR;
}
/* Send GET request to server */
if (!send_get_header(server_fd, path)) {
goto SERVER_ERROR;
}
/* Modify and send request headers to ensure no persistent connections and
* ensure the presence of a Host header */
if (!filter_rest_headers(client_fd, server_fd, host)) {
verbose_printf("filter_rest_headers error: %s\n", strerror(errno));
goto SERVER_ERROR;
}
buffer_t *real_buffer = buffer_create(10);
/* Forward response from server to client, and store the response in the
* cache if possible */
if (!send_response(client_fd, server_fd, real_buffer)) {
verbose_printf("send_reponse error: %s\n", strerror(errno));
/* Fall through, since we're done anyway */
}
insert(host, real_buffer);
//the webpage is already cached
close(server_fd);
ALREADY_CACHED:
/* Close the write end of the client socket and wait for it to send EOF. */
if (shutdown(client_fd, SHUT_WR) < 0) {
verbose_printf("shutdown error: %s\n", strerror(errno));
goto CLIENT_ERROR;
}
uint8_t discard_buffer[BUFFER_SIZE];
if (read(client_fd, discard_buffer, sizeof(discard_buffer)) < 0) {
verbose_printf("read error: %s\n", strerror(errno));
goto CLIENT_ERROR;
}
close(client_fd);
// free(host);
// free(path);
// free_hash_table();
return NULL;
SERVER_ERROR:
verbose_printf("Error in writing to server\n");
close(server_fd);
CLIENT_ERROR:
close(client_fd);
free(host);
free(path);
return NULL;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,j,c = 0;
//istenilen sayilar dondurulur
for (i = 10; i <= 200; i++)
{
//sadece 1 ve kendisine bolunebilen sayilar asal sayidir
for (j = 1; j <= i; j++)
{
if (i % j == 0)
{
c++;
}
}
if (c == 2)
{
printf("%d " , i);
}
c = 0;
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* math.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ecaceres <ecaceres@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/09/25 23:29:04 by ecaceres #+# #+# */
/* Updated: 2022/09/25 23:29:04 by ecaceres ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef MATH_H
# define MATH_H
# include <stdbool.h>
typedef struct
{
int x;
int y;
} t_vector2i;
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
#define CLAMP(x,lo,hi) MIN((hi), MAX((lo), (x)))
t_vector2i
vector2i(int x, int y);
t_vector2i
vector2i_zero(void);
bool
vector2i_equals(t_vector2i left, t_vector2i right);
t_vector2i
vector2i_substract(t_vector2i left, t_vector2i right);
t_vector2i
vector2i_add(t_vector2i left, t_vector2i right);
t_vector2i
vector2i_max(t_vector2i left, t_vector2i right);
#endif
|
C
|
/**********************************************************
*name : time.c
*detail : ʱغ
*version&time: v1.0 (2018-4-1)
*author&team : wang yuan
***********************************************************/
/* Includes ------------------------------------------------------------------*/
#include "time.h"
/* defines¯o ------------------------------------------------------------*/
/* typedef ------------------------------------------------------------------*/
/* variables&constants -----------------------------------------------------*/
time_t time;
/* functions ----------------------------------------------------------------*/
//
void Delayms(uint16_t ms)
{
// uint32_t tickstart = 0U;
// tickstart = HAL_GetTick();
// while((HAL_GetTick() - tickstart) < delay)
{
}
}
// עʱ
void RefreshTime(void)
{
}
//
void SetTime(date_t *d, clock_t *c)
{
time.date.year = d->year;
time.date.month = d->month;
time.date.day = d->day;
time.clock.hour = c->hour;
}
void TimeInit(void)
{
time.Delayms = Delayms;
time.RefreshTime = RefreshTime;
time.SetTime = SetTime;
}
/************************ (C) COPYRIGHT ucframe team ******* END OF FILE ******/
|
C
|
//Write a C program to print a pyramid of stars.
#include<stdio.h>
void pattern(int);
int main()
{
int size;
printf("Enter size of pyramid: ");
scanf("%d", &size);
pattern(size);
return 0;
}
void pattern(int size)
{
int i, j;
int sp = size/2;
int loop = sp+1;
for(i=0; i<size; i++) {
for(j=0; j<loop; j++) {
if(j<sp) {
printf(" ");
}
else {
printf("* ");
}
}
loop += 1;
printf("\n");
sp -= 1;
if(loop > size) {
break;
}
}
}
|
C
|
#ifndef __LIST__H__
#define __LIST__H__
#include <stdio.h>
#include <stdlib.h>
// BOOleans
typedef enum
{
false,
true
}Bool;
typedef struct ListElement
{
int value;
struct ListElement * next;
}ListElement , *List;
/*Prototypes **/
List new_list(void);
Bool is_empty_list(List li);
int list_length(List li);
void print_list(List li);
List insert_back_list(List li , int x);
List insert_front_list(List li , int x);
List delete_last_element(List li );
List delete_first_element(List li );
List clear_list(List li);
#endif
|
C
|
// functions to convert the 12-bit value into hexadecimal value for the 7-Segment display on DE0
#include "main3.h"
#include "i2c.h"
uint32_t convert_for_7_seg(uint8_t t1, uint8_t t2)
{
uint32_t data;
uint32_t temp1, temp2, temp3;
int tt;
tt = t1;
//(t1>>4) * 16 + t1&0x0F;
temp2 = t1 % 10;
temp1 = (t1 / 10) % 10;
temp3 = ((t2>>4) * 10 / 16);
temp1 =convertDigit(temp1);
temp2 =convertDigit(temp2);
temp3 =convertDigit(temp3);
temp1 = temp1<<16;
temp2 = temp2<<8;
data = temp1|temp2|temp3;
return data;
}
uint8_t convertDigit(uint8_t num) {
uint8_t data;
switch(num) {
case 0:
data = 0x3F;//0011 1111
break;
case 1:
data = 0x06;//0000 0110
break;
case 2:
data = 0x5B;//0101 1011
break;
case 3:
data = 0x4F;//0100 1111
break;
case 4:
data = 0x66;//0110 0110
break;
case 5:
data = 0x6D;//0110 1101
break;
case 6:
data = 0x7D;//0111 1101
break;
case 7:
data = 0x07;//0000 0111
break;
case 8:
data = 0x7F;//0111 1111
break;
case 9:
data = 0x6F;//0110 1111
break;
case 10:
data = 0x77;//0110 1101
break;
case 11:
data = 0x7C;//0111 1101
break;
case 12:
data = 0x39;//0000 0111
break;
case 13:
data = 0x5E;//0111 1111
break;
case 14:
data = 0x79;//0110 1111
break;
case 15:
data = 0x71;//0110 1111
break;
default:
data = 0x00;//clear
break;
}
return data;
}
|
C
|
//Soma de elementos impares de um vetor - pag 108
#include <stdio.h>
int main(){
int a[5];
int i, soma = 0;
puts("Somatorio de elementos impares\n");
//Entrada de dados
for(i = 0; i < 5; i++){
printf("Insira o %2d.0 elemento: ", i + 1);
scanf("%d", &a[i]);
}
//Processamento de elementos
for(i = 0; i < 5; i++){
if(a[i] % 2 != 0)
soma += a[i];
}
printf("\nO somatorio de elementos impares equivale a: %6d", soma);
return 0;
}
|
C
|
/*
Basler cameras provide "chunk features": The cameras can generate certain information about each image, e.g. frame counters, time stamps, and CRC checksums, which is appended to the image data as data "chunks".
This sample illustrates how to enable chunk features, how to grab
images, and how to process the appended data. When the camera is in chunk mode, it transfers data blocks
that are partitioned into chunks. The first chunk is always the image data. When chunk features are enabled,
the image data chunk is followed by chunks containing the information generated by the chunk features.
This sample also demonstrates how to use software triggers. Two buffers are used. Once a buffer is filled,
the acquisition of the next frame is triggered before processing the received buffer. This approach allows
performing image acquisition while the processing of the previous image proceeds.
*/
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <pylonc/PylonC.h>
#define CHECK( errc ) if ( GENAPI_E_OK != errc ) printErrorAndExit( errc )
/* This function can be used to wait for user input at the end of the sample program. */
void pressEnterToExit(void);
/* This method demonstrates how to retrieve the error message for the last failed function call. */
void printErrorAndExit( GENAPIC_RESULT errc );
/* Calculates the minimum and maximum gray value. */
void getMinMax( const unsigned char* pImg, int32_t width, int32_t height,
unsigned char* pMin, unsigned char* pMax);
#define NUM_GRABS 20 /* Number of images to grab. */
#define NUM_BUFFERS 2 /* Number of buffers used for grabbing. */
int main(void)
{
GENAPIC_RESULT res; /* Return value of pylon methods. */
size_t numDevices; /* Number of available devices. */
PYLON_DEVICE_HANDLE hDev; /* Handle for the pylon device. */
PYLON_STREAMGRABBER_HANDLE hGrabber; /* Handle for the pylon stream grabber. */
PYLON_CHUNKPARSER_HANDLE hChunkParser; /* Handle for the parser extracting the chunk data. */
PYLON_WAITOBJECT_HANDLE hWait; /* Handle used for waiting for a grab to be finished. */
int32_t payloadSize; /* Size of an image frame in bytes. */
unsigned char *buffers[NUM_BUFFERS]; /* Buffers used for grabbing. */
PYLON_STREAMBUFFER_HANDLE bufHandles[NUM_BUFFERS]; /* Handles for the buffers. */
PylonGrabResult_t grabResult; /* Stores the result of a grab operation. */
int nGrabs; /* Counts the number of buffers grabbed. */
size_t nStreams; /* The number of streams the device provides. */
_Bool isAvail; /* Used for checking feature availability. */
_Bool isReady; /* Used as an output parameter. */
size_t i; /* Counter. */
int ret=EXIT_FAILURE; /* The return value. */
const char* triggerSelectorValue = "FrameStart"; /* Preselect the trigger for image acquisition. */
_Bool isAvailFrameStart; /* Used for checking feature availability. */
_Bool isAvailAcquisitionStart; /* Used for checking feature availability. */
hDev = PYLONC_INVALID_HANDLE;
/* Before using any pylon methods, the pylon runtime must be initialized. */
PylonInitialize();
printf("Enumerating devices ...\n");
/* Enumerate all camera devices. You must call
PylonEnumerateDevices() before creating a device. */
res = PylonEnumerateDevices( &numDevices );
CHECK(res);
if ( 0 == numDevices )
{
fprintf( stderr, "No devices found.\n" );
/* Before exiting a program, PylonTerminate() should be called to release
all pylon related resources. */
PylonTerminate();
pressEnterToExit();
exit(EXIT_FAILURE);
}
printf("Opening first device ...\n");
/* Get a handle for the first device found. */
res = PylonCreateDeviceByIndex( 0, &hDev );
CHECK(res);
/* Before using the device, it must be opened. Open it for setting
parameters and for grabbing images. */
res = PylonDeviceOpen( hDev, PYLONC_ACCESS_MODE_CONTROL | PYLONC_ACCESS_MODE_STREAM );
CHECK(res);
/* Set the pixel format to Mono8 if available, where gray values will be output as 8 bit values for each pixel. */
isAvail = PylonDeviceFeatureIsAvailable(hDev, "EnumEntry_PixelFormat_Mono8");
if (isAvail)
{
res = PylonDeviceFeatureFromString( hDev, "PixelFormat", "Mono8" );
CHECK(res);
}
/* Check the available camera trigger mode(s) to select the appropriate one: acquisition start trigger mode (used by previous cameras;
do not confuse with acquisition start command) or frame start trigger mode (equivalent to previous acquisition start trigger mode). */
isAvailAcquisitionStart = PylonDeviceFeatureIsAvailable(hDev, "EnumEntry_TriggerSelector_AcquisitionStart");
isAvailFrameStart = PylonDeviceFeatureIsAvailable(hDev, "EnumEntry_TriggerSelector_FrameStart");
/* Check to see if the camera implements the acquisition start trigger mode only. */
if (isAvailAcquisitionStart && !isAvailFrameStart)
{
/* ... Select the software trigger as the trigger source. */
res = PylonDeviceFeatureFromString(hDev, "TriggerSelector", "AcquisitionStart");
CHECK(res);
res = PylonDeviceFeatureFromString(hDev, "TriggerMode", "On");
CHECK(res);
triggerSelectorValue = "AcquisitionStart";
}
else
{
/* Camera may have the acquisition start trigger mode and the frame start trigger mode implemented.
In this case, the acquisition trigger mode must be switched off. */
if (isAvailAcquisitionStart)
{
res = PylonDeviceFeatureFromString(hDev, "TriggerSelector", "AcquisitionStart");
CHECK(res);
res = PylonDeviceFeatureFromString(hDev, "TriggerMode", "Off");
CHECK(res);
}
/* Disable frame burst start trigger if available. */
isAvail = PylonDeviceFeatureIsAvailable( hDev, "EnumEntry_TriggerSelector_FrameBurstStart");
if (isAvail)
{
res = PylonDeviceFeatureFromString( hDev, "TriggerSelector", "FrameBurstStart");
CHECK(res);
res = PylonDeviceFeatureFromString( hDev, "TriggerMode", "Off");
CHECK(res);
}
/* To trigger each single frame by software or external hardware trigger: Enable the frame start trigger mode. */
res = PylonDeviceFeatureFromString(hDev, "TriggerSelector", "FrameStart");
CHECK(res);
res = PylonDeviceFeatureFromString(hDev, "TriggerMode", "On");
CHECK(res);
}
/* Note: the trigger selector must be set to the appropriate trigger mode
before setting the trigger source or issuing software triggers.
Frame start trigger mode for newer cameras, acquisition start trigger mode for previous cameras. */
PylonDeviceFeatureFromString(hDev, "TriggerSelector", triggerSelectorValue);
/* Enable software triggering. */
/* ... Select the software trigger as the trigger source. */
res = PylonDeviceFeatureFromString( hDev, "TriggerSource", "Software");
CHECK(res);
/* When using software triggering, the Continuous frame mode should be used. Once
acquisition is started, the camera sends one image each time a software trigger is
issued. */
res = PylonDeviceFeatureFromString( hDev, "AcquisitionMode", "Continuous" );
CHECK(res);
/* For GigE cameras, we recommend increasing the packet size for better
performance. When the network adapter supports jumbo frames, set the packet
size to a value > 1500, e.g., to 8192. In this sample, we only set the packet size
to 1500. */
/* ... Check first to see if the GigE camera packet size parameter is supported and if it is writable. */
isAvail = PylonDeviceFeatureIsWritable(hDev, "GevSCPSPacketSize");
if ( isAvail )
{
/* ... The device supports the packet size feature. Set a value. */
res = PylonDeviceSetIntegerFeature( hDev, "GevSCPSPacketSize", 1500 );
CHECK(res);
}
/* Before enabling individual chunks, the chunk mode in general must be activated. */
isAvail = PylonDeviceFeatureIsWritable(hDev, "ChunkModeActive") ;
if ( ! isAvail )
{
fprintf( stderr, "The device doesn't support the chunk mode.\n");
PylonTerminate();
pressEnterToExit();
exit(EXIT_FAILURE);
}
/* Activate the chunk mode. */
res = PylonDeviceSetBooleanFeature( hDev, "ChunkModeActive", 1);
CHECK(res);
/* Enable some individual chunks... */
/* ... The frame counter chunk feature. */
/* Is the chunk available? */
isAvail = PylonDeviceFeatureIsAvailable(hDev, "EnumEntry_ChunkSelector_Framecounter");
if ( isAvail )
{
/* Select the frame counter chunk feature. */
res = PylonDeviceFeatureFromString( hDev, "ChunkSelector", "Framecounter" );
CHECK(res);
/* Can the chunk feature be activated? */
isAvail = PylonDeviceFeatureIsWritable(hDev, "ChunkEnable");
if ( isAvail )
{
/* Activate the chunk feature. */
res = PylonDeviceSetBooleanFeature( hDev, "ChunkEnable", 1);
CHECK(res);
}
}
/* ... The CRC checksum chunk feature. */
/* Note: Enabling the CRC chunk feature is not a prerequisite for using
chunks. Chunks can also be handled when the CRC feature is disabled. */
isAvail = PylonDeviceFeatureIsAvailable(hDev, "EnumEntry_ChunkSelector_PayloadCRC16");
if ( isAvail )
{
/* Select the CRC chunk feature. */
res = PylonDeviceFeatureFromString( hDev, "ChunkSelector", "PayloadCRC16" );
CHECK(res);
/* Can the chunk feature be activated? */
isAvail = PylonDeviceFeatureIsWritable(hDev, "ChunkEnable");
if ( isAvail )
{
/* Activate the chunk feature. */
res = PylonDeviceSetBooleanFeature( hDev, "ChunkEnable", 1);
CHECK(res);
}
}
/* The data block containing the image chunk and the other chunks has a self-descriptive layout.
A chunk parser is used to extract the appended chunk data from the grabbed image frame.
Create a chunk parser. */
res = PylonDeviceCreateChunkParser( hDev, &hChunkParser );
CHECK(res);
if ( hChunkParser == PYLONC_INVALID_HANDLE )
{
/* The transport layer doesn't provide a chunk parser. */
fprintf(stderr, "No chunk parser available.\n");
goto exit;
}
/* Image grabbing is done using a stream grabber.
A device may be able to provide different streams. A separate stream grabber must
be used for each stream. In this sample, we create a stream grabber for the default
stream, i.e., the first stream ( index == 0 ).
*/
/* Get the number of streams supported by the device and the transport layer. */
res = PylonDeviceGetNumStreamGrabberChannels( hDev, &nStreams );
CHECK(res);
if ( nStreams < 1 )
{
fprintf( stderr, "The transport layer doesn't support image streams.\n");
PylonTerminate();
pressEnterToExit();
exit(EXIT_FAILURE);
}
/* Create and open a stream grabber for the first channel. */
res = PylonDeviceGetStreamGrabber( hDev, 0, &hGrabber );
CHECK(res);
res = PylonStreamGrabberOpen( hGrabber );
CHECK(res);
/* Get a handle for the stream grabber's wait object. The wait object
allows waiting for buffers to be filled with grabbed data. */
res = PylonStreamGrabberGetWaitObject( hGrabber, &hWait );
CHECK(res);
/* Determine the required size of the grab buffer. Since activating chunks will increase the
payload size and thus the required buffer size, do this after enabling the chunks. */
res = PylonDeviceGetIntegerFeatureInt32( hDev, "PayloadSize", &payloadSize );
CHECK(res);
/* Allocate memory for grabbing. */
for ( i = 0; i < NUM_BUFFERS; ++i )
{
buffers[i] = (unsigned char*) malloc ( payloadSize );
if ( NULL == buffers[i] )
{
fprintf( stderr, "Out of memory.\n" );
PylonTerminate();
pressEnterToExit();
exit(EXIT_FAILURE);
}
}
/* We must tell the stream grabber the number and size of the buffers
we are using. */
/* .. We will not use more than NUM_BUFFERS for grabbing. */
res = PylonStreamGrabberSetMaxNumBuffer( hGrabber, NUM_BUFFERS );
CHECK(res);
/* .. We will not use buffers bigger than payloadSize bytes. */
res = PylonStreamGrabberSetMaxBufferSize( hGrabber, payloadSize );
CHECK(res);
/* Allocate the resources required for grabbing. After this, critical parameters
that impact the payload size must not be changed until FinishGrab() is called. */
res = PylonStreamGrabberPrepareGrab( hGrabber );
CHECK(res);
/* Before using the buffers for grabbing, they must be registered at
the stream grabber. For each registered buffer, a buffer handle
is returned. After registering, these handles are used instead of the
raw pointers. */
for ( i = 0; i < NUM_BUFFERS; ++i )
{
res = PylonStreamGrabberRegisterBuffer( hGrabber, buffers[i], payloadSize, &bufHandles[i] );
CHECK(res);
}
/* Feed the buffers into the stream grabber's input queue. For each buffer, the API
allows passing in a pointer to additional context information. This pointer
will be returned unchanged when the grab is finished. In our example, we use the index of the
buffer as context information. */
for ( i = 0; i < NUM_BUFFERS; ++i )
{
res = PylonStreamGrabberQueueBuffer( hGrabber, bufHandles[i], (void*) i );
CHECK(res);
}
/* Issue an acquisition start command. Because the trigger mode is enabled, issuing the acquisition start command
itself will not trigger any image acquisitions. Issuing the start command simply prepares the camera to acquire images.
Once the camera is prepared it will acquire one image for every trigger it receives. */
res = PylonDeviceExecuteCommandFeature( hDev, "AcquisitionStart");
CHECK(res);
/* Trigger the first image. */
res = PylonDeviceExecuteCommandFeature( hDev, "TriggerSoftware");
CHECK(res);
/* Grab NUM_GRABS images */
nGrabs = 0; /* Counts the number of images grabbed. */
while ( nGrabs < NUM_GRABS )
{
size_t bufferIndex; /* Index of the buffer. */
unsigned char min, max;
int32_t chunkWidth = 0; /* Data retrieved from the chunk parser. */
int32_t chunkHeight = 0; /* Data retrieved from the chunk parser. */
/* Wait for the next buffer to be filled. Wait up to 1000 ms. */
res = PylonWaitObjectWait( hWait, 1000, &isReady );
CHECK(res);
if ( ! isReady )
{
/* Timeout occurred. */
fprintf(stderr, "Grab timeout occurred.\n");
break; /* Stop grabbing. */
}
/* Since the wait operation was successful, the result of at least one grab
operation is available. Retrieve it. */
res = PylonStreamGrabberRetrieveResult( hGrabber, &grabResult, &isReady );
CHECK(res);
if ( ! isReady )
{
/* Oops. No grab result available? We should never have reached this point.
Since the wait operation above returned without a timeout, a grab result
should be available. */
fprintf(stderr, "Failed to retrieve a grab result\n");
break;
}
nGrabs++;
/* Trigger the next image. Since we passed more than one buffer to the stream grabber,
the triggered image will be grabbed while the image processing is performed. */
res = PylonDeviceExecuteCommandFeature( hDev, "TriggerSoftware" );
CHECK(res);
/* Get the buffer index from the context information. */
bufferIndex = (size_t) grabResult.Context;
/* Check to see if the image was grabbed successfully. */
if ( grabResult.Status == Grabbed )
{
/* The grab is successfull. */
unsigned char* buffer; /* Pointer to the buffer attached to the grab result. */
/* Get the buffer pointer from the result structure. Since we also got the buffer index,
we could alternatively use buffers[bufferIndex]. */
buffer = (unsigned char*) grabResult.pBuffer;
printf("Grabbed frame #%2d into buffer %2d.\n", nGrabs, (int) bufferIndex );
/* Check to see if we really got image data plus chunk data. */
if ( grabResult.PayloadType != PayloadType_ChunkData )
{
fprintf(stderr, "Received a buffer not containing chunk data?\n");
}
else
{
/* Process the chunk data. This is done by passing the grabbed image buffer
to the chunk parser. When the chunk parser has processed the buffer, the chunk
data can be accessed in the same manner as "normal" camera parameters.
The only exception is the CRC feature. There are dedicated functions for
checking the CRC checksum. */
_Bool hasCRC;
/* Let the parser extract the data. */
res = PylonChunkParserAttachBuffer( hChunkParser, grabResult.pBuffer, (size_t) grabResult.PayloadSize );
CHECK(res);
/* Check the CRC. */
res = PylonChunkParserHasCRC( hChunkParser, &hasCRC );
CHECK(res);
if ( hasCRC )
{
_Bool isOk;
res = PylonChunkParserCheckCRC( hChunkParser, &isOk );
CHECK(res);
printf("Frame %d contains a CRC checksum. The checksum %s ok.\n", nGrabs, isOk ? "is" : "is not");
}
/* Retrieve the frame counter value. */
/* ... Check the availability. */
isAvail = PylonDeviceFeatureIsAvailable(hDev, "ChunkFramecounter");
printf("Frame %d %s a frame counter chunk.\n", nGrabs, isAvail ? "contains" : "doesn't contain" );
if ( isAvail )
{
/* ... Get the value. */
int64_t counter;
res = PylonDeviceGetIntegerFeature( hDev, "ChunkFramecounter", &counter );
CHECK(res);
#if __STDC_VERSION__ >= 199901L || defined(__GNUC__)
printf("Frame counter of frame %d: %lld.\n", nGrabs, (long long) counter );
#else
printf("Frame counter of frame %d: %I64d.\n", nGrabs, counter );
#endif
}
/* Retrieve the frame width value. */
/* ... Check the availability. */
isAvail = PylonDeviceFeatureIsAvailable(hDev, "ChunkWidth");
printf("Frame %d %s a width chunk.\n", nGrabs, isAvail ? "contains" : "doesn't contain" );
if ( isAvail )
{
/* ... Get the value. */
res = PylonDeviceGetIntegerFeatureInt32( hDev, "ChunkWidth", &chunkWidth );
CHECK(res);
printf("Width of frame %d: %d.\n", nGrabs, chunkWidth );
}
/* Retrieve the frame height value. */
/* ... Check the availability. */
isAvail = PylonDeviceFeatureIsAvailable(hDev, "ChunkHeight");
CHECK(res);
printf("Frame %d %s a height chunk.\n", nGrabs, isAvail ? "contains" : "doesn't contain" );
if ( isAvail )
{
/* ... Get the value. */
res = PylonDeviceGetIntegerFeatureInt32( hDev, "ChunkHeight", &chunkHeight );
CHECK(res);
printf("Height of frame %d: %d.\n", nGrabs, chunkHeight );
}
}
/* Perform the image processing. */
getMinMax( buffer, chunkWidth, chunkHeight, &min, &max );
printf("Min. gray value = %3u, Max. gray value = %3u\n", min, max);
/* Before requeueing the buffer, you should detach it from the chunk parser. */
res = PylonChunkParserDetachBuffer( hChunkParser ); /* The chunk data in the buffer is now no longer accessible. */
CHECK(res);
}
else if ( grabResult.Status == Failed )
{
fprintf( stderr, "Frame %d wasn't grabbed successfully. Error code = 0x%08X\n",
nGrabs, grabResult.ErrorCode );
}
/* Once finished with the processing, requeue the buffer to be filled again. */
res = PylonStreamGrabberQueueBuffer( hGrabber, grabResult.hBuffer, (void*) bufferIndex );
CHECK(res);
}
/* Clean up. */
/* ... Stop the camera. */
res = PylonDeviceExecuteCommandFeature( hDev, "AcquisitionStop");
CHECK(res);
/* ... We must issue a cancel call to ensure that all pending buffers are put into the
stream grabber's output queue. */
res = PylonStreamGrabberCancelGrab( hGrabber );
CHECK(res);
/* ... The buffers can now be retrieved from the stream grabber. */
do
{
res = PylonStreamGrabberRetrieveResult( hGrabber, &grabResult, &isReady );
CHECK(res);
} while ( isReady );
/* ... When all buffers are retrieved from the stream grabber, they can be deregistered.
After deregistering the buffers, it is safe to free the memory. */
for ( i = 0; i < NUM_BUFFERS; ++i )
{
res = PylonStreamGrabberDeregisterBuffer( hGrabber, bufHandles[i] );
CHECK(res);
free( buffers[i] );
}
/* ... Release grabbing related resources. */
res = PylonStreamGrabberFinishGrab( hGrabber );
CHECK(res);
/* After calling PylonStreamGrabberFinishGrab(), parameters that impact the payload size (e.g.,
the AOI width and height parameters) are unlocked and can be modified again. */
/* ... Close the stream grabber. */
res = PylonStreamGrabberClose( hGrabber );
CHECK(res);
/* ... Release the chunk parser. */
res = PylonDeviceDestroyChunkParser( hDev, hChunkParser );
CHECK(res);
ret = EXIT_SUCCESS;
exit:
/* Disable the software trigger and the chunk mode. */
if ( hDev != PYLONC_INVALID_HANDLE )
{
res = PylonDeviceSetBooleanFeature( hDev, "ChunkEnable", 0);
CHECK(res);
res = PylonDeviceSetBooleanFeature( hDev, "ChunkModeActive", 0);
CHECK(res);
res = PylonDeviceFeatureFromString( hDev, "TriggerMode", "Off" );
CHECK(res);
}
/* ... Close and release the pylon device. The stream grabber becomes invalid
after closing the pylon device. Don't call stream grabber related methods after
closing or releasing the device. */
res = PylonDeviceClose( hDev );
CHECK(res);
res = PylonDestroyDevice ( hDev );
CHECK(res);
/* ... Shut down the pylon runtime system. Don't call any pylon method after
calling PylonTerminate(). */
PylonTerminate();
pressEnterToExit();
return ret;
}
/* This function demonstrates how to retrieve the error message for the last failed
function call. */
void printErrorAndExit( GENAPIC_RESULT errc )
{
char *errMsg;
size_t length;
/* Retrieve the error message.
... First find out how big the buffer must be, */
GenApiGetLastErrorMessage( NULL, &length );
errMsg = (char*) malloc( length );
/* ... and retrieve the message. */
GenApiGetLastErrorMessage( errMsg, &length );
fprintf( stderr, "%s (%#08x).\n", errMsg, (unsigned int) errc);
free( errMsg);
/* Retrieve the more details about the error.
... First find out how big the buffer must be, */
GenApiGetLastErrorDetail( NULL, &length );
errMsg = (char*) malloc( length );
/* ... and retrieve the message. */
GenApiGetLastErrorDetail( errMsg, &length );
fprintf( stderr, "%s\n", errMsg);
free( errMsg);
PylonTerminate(); /* Releases all pylon resources. */
pressEnterToExit();
exit(EXIT_FAILURE);
}
/* Simple "image processing" function returning the minimum and maximum gray
value of an image with 8 bit gray values. */
void getMinMax( const unsigned char* pImg, int32_t width, int32_t height,
unsigned char* pMin, unsigned char* pMax)
{
unsigned char min = 255;
unsigned char max = 0;
unsigned char val;
const unsigned char *p;
for ( p = pImg; p < pImg + width * height; p++ )
{
val = *p;
if ( val > max )
max = val;
if ( val < min )
min = val;
}
*pMin = min;
*pMax = max;
}
/* This function can be used to wait for user input at the end of the sample program. */
void pressEnterToExit(void)
{
fprintf( stderr, "\nPress enter to exit.\n");
while( getchar() != '\n');
}
|
C
|
/*
* Illustrates fork, wait and exit return information
* Once run: Use
* echo $?
* to make the shell print-out the parent return value (15)
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main (
)
{
pid_t pid, cpid;
int status;
fprintf (stdout, "StartingProcess: PID=%d\n", getpid());
pid = fork();
if (pid != 0) {
// Father
fprintf (stdout, "Father: PID=%d; FatherPID=%d; ReturnPID=%d\n",
getpid(), getppid(), pid);
status = 0;
sleep (05);
cpid = wait (&status);
fprintf (stdout, "Father Wait: ChildPID=%d Status=%x ",
cpid, status);
fprintf (stdout, "WIFEXITED=%d WEXITSTATUS=%d\n",
WIFEXITED(status), WEXITSTATUS (status));
printf("Parent complete\n");
exit (25);
} else {
// Child
fprintf (stdout, "Child : PID=%d; FatherPID=%d; ReturnPID=%d\n",
getpid(), getppid(), pid);
sleep (10);
fprintf (stdout, "Child complete\n");
status = 123;
exit (6);
}
}
|
C
|
#include<stdio.h>
//#include<conio.h>
#include<stdlib.h>
void ins_sort(int a[], int n)
{
int i,j,k;
for(i=n-2;i>-1;i--)
{
k=a[i];
j=i+1;
while(k>a[j] && j<n)
{
a[j-1]=a[j];
j++;
}
a[j-1]=k;
}
}
main()
{
int i, a[100], n;
printf("\nHow many memebers in array ");
scanf("%d",&n);
printf("\nEnter the array");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
ins_sort(a,n);
printf("\nThe sorted array is \n\t");
for(i=0;i<n;i++)
printf(" %d ",a[i]);
//getch();
}
|
C
|
#include <stdio.h>
int main(void) {
int vetorA[5];
int vetorB[5];
int i, soma;
soma = 0;
printf("\n\nVetor A: \n");
for(i = 1; i <= 5; i++) {
printf("Digite o número: ");
scanf("%i", &vetorA[i]);
}
printf("\n\nVetor B: \n");
for(i = 1; i <= 5; i++) {
printf("Digite o número: ");
scanf("%i", &vetorB[i]);
}
for(i = 1; i <= 5; i++) {
soma = soma + (vetorA[i] - vetorB[6 - i]);
}
printf("\nO Resultado é: %i", soma);
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
double a,b,result;
char operator;
printf("\nChoose an operator (+,-,*,/,) : ");
scanf("%c",&operator);
printf("\nEnter the value of A : ");
scanf("%lf",&a);
printf("Enter the value of B : ");
scanf("%lf",&b);
result = 0;
if (operator == '+')
result = a+b;
else if (operator == '-')
result = a-b;
else if (operator == '*')
result = a*b;
else if (operator == '/')
result = a/b;
else
result = (int)a % (int)b;
printf("%.1lf %c %.1lf = %.1lf \n",a,operator,b,result);
return 1;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "utils.h" // Documentation is stored in here
#include <string.h>
static double g_ticks_persecond = 0.0;
void InitTSC(void)
{
#ifdef _WIN32
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
g_ticks_persecond = (double)frequency.QuadPart;
#else
uint64_t start_tick = ReadTSC();
usleep(1 * 1000000); // usleep takes sleep time in us (1 millionth of a second)
uint64_t end_tick = ReadTSC();
g_ticks_persecond = (double)(end_tick - start_tick);
#endif
//fprintf(stderr, "%e ticks per second.\n", g_ticks_persecond);
}
double ElapsedTime(uint64_t ticks)
{
if (g_ticks_persecond == 0.0) {
fprintf(stderr, "TSC timer has not been initialized.\n");
return 0.0;
}
else {
return (ticks / g_ticks_persecond);
}
}
uint64_t ReadTSC(void)
{
#ifdef _WIN32
LARGE_INTEGER time;
QueryPerformanceCounter(&time);
return (uint64_t)time.QuadPart * 1000000; // Convert to microsec
#elif defined(__i386__)
uint64_t x;
__asm__ __volatile__(".byte 0x0f, 0x31":"=A"(x));
return x;
#elif defined(__x86_64__)
uint32_t hi, lo;
__asm__ __volatile__("rdtsc":"=a"(lo), "=d"(hi));
return ((uint64_t)lo) | (((uint64_t)hi) << 32);
#elif defined(__powerpc__)
uint64_t result = 0;
uint64_t upper, lower, tmp;
__asm__ __volatile__("0: \n"
"\tmftbu %0 \n"
"\tmftb %1 \n"
"\tmftbu %2 \n"
"\tcmpw %2,%0 \n"
"\tbne 0b \n":"=r"(upper), "=r"(lower),
"=r"(tmp)
);
result = upper;
result = result << 32;
result = result | lower;
return result;
#endif // defined(__i386__)
}
void check_mm_ret(int ret)
{
switch (ret)
{
case MM_COULD_NOT_READ_FILE:
fprintf(stderr, "Error reading file.\n");
exit(EXIT_FAILURE);
break;
case MM_PREMATURE_EOF:
fprintf(stderr, "Premature EOF (not enough values in a line).\n");
exit(EXIT_FAILURE);
break;
case MM_NOT_MTX:
fprintf(stderr, "Not Matrix Market format.\n");
exit(EXIT_FAILURE);
break;
case MM_NO_HEADER:
fprintf(stderr, "No header information.\n");
exit(EXIT_FAILURE);
break;
case MM_UNSUPPORTED_TYPE:
fprintf(stderr, "Unsupported type (not a matrix).\n");
exit(EXIT_FAILURE);
break;
case MM_LINE_TOO_LONG:
fprintf(stderr, "Too many values in a line.\n");
exit(EXIT_FAILURE);
break;
case MM_COULD_NOT_WRITE_FILE:
fprintf(stderr, "Error writing to a file.\n");
exit(EXIT_FAILURE);
break;
case 0:
fprintf(stdout, "file loaded.\n");
break;
default:
fprintf(stdout, "Error - should not be here.\n");
exit(EXIT_FAILURE);
break;
}
}
void read_info(char* fileName)
{
FILE* fp;
MM_typecode matcode;
int m;
int n;
int nnz;
if ((fp = fopen(fileName, "r")) == NULL) {
fprintf(stderr, "Error opening file: %s\n", fileName);
exit(EXIT_FAILURE);
}
if (mm_read_banner(fp, &matcode) != 0)
{
fprintf(stderr, "Error processing Matrix Market banner.\n");
exit(EXIT_FAILURE);
}
if (mm_read_mtx_crd_size(fp, &m, &n, &nnz) != 0) {
fprintf(stderr, "Error reading size.\n");
exit(EXIT_FAILURE);
}
print_matrix_info(fileName, matcode, m, n, nnz);
fclose(fp);
}
void print_matrix_info(char* fileName, MM_typecode matcode,
int m, int n, int nnz)
{
fprintf(stdout, "-----------------------------------------------------\n");
fprintf(stdout, "Matrix name: %s\n", fileName);
fprintf(stdout, "Matrix size: %d x %d => %d\n", m, n, nnz);
fprintf(stdout, "-----------------------------------------------------\n");
fprintf(stdout, "Is matrix: %d\n", mm_is_matrix(matcode));
fprintf(stdout, "Is sparse: %d\n", mm_is_sparse(matcode));
fprintf(stdout, "-----------------------------------------------------\n");
fprintf(stdout, "Is complex: %d\n", mm_is_complex(matcode));
fprintf(stdout, "Is real: %d\n", mm_is_real(matcode));
fprintf(stdout, "Is integer: %d\n", mm_is_integer(matcode));
fprintf(stdout, "Is pattern only: %d\n", mm_is_pattern(matcode));
fprintf(stdout, "-----------------------------------------------------\n");
fprintf(stdout, "Is general: %d\n", mm_is_general(matcode));
fprintf(stdout, "Is symmetric: %d\n", mm_is_symmetric(matcode));
fprintf(stdout, "Is skewed: %d\n", mm_is_skew(matcode));
fprintf(stdout, "Is hermitian: %d\n", mm_is_hermitian(matcode));
fprintf(stdout, "-----------------------------------------------------\n");
}
void convert_coo_to_csr(int* row_ind, int* col_ind, double* val,
int m, int n, int nnz,
unsigned int** csr_row_ptr, unsigned int** csr_col_ind,
double** csr_vals)
{
// Temporary pointers
unsigned int* row_ptr_;
unsigned int* col_ind_;
double* vals_;
// We now how large the data structures should be
// csr_row_ptr -> m + 1
// csr_col_ind -> nnz
// csr_vals -> nnz
row_ptr_ = (unsigned int*)malloc(sizeof(unsigned int) * (m + 1));
assert(row_ptr_);
col_ind_ = (unsigned int*)malloc(sizeof(unsigned int) * nnz);
assert(col_ind_);
vals_ = (double*)malloc(sizeof(double) * nnz);
assert(vals_);
// Now determine how many non-zero elements are in each row
// Use a histogram to do this
unsigned int* buckets = (unsigned int*) malloc(sizeof(unsigned int) * m);
assert(buckets);
memset(buckets, 0, sizeof(unsigned int) * m);
for (unsigned int i = 0; i < nnz; i++) {
// row_ind[i] - 1 because index in mtx format starts from 1 (not 0)
buckets[row_ind[i] - 1]++;
}
// Now use a cumulative sum to determine the starting position of each
// row in csr_col_ind and csr_vals - this information is also what is
// stored in csr_row_ptr
for (unsigned int i = 1; i < m; i++) {
buckets[i] = buckets[i] + buckets[i - 1];
}
// Copy this to csr_row_ptr
row_ptr_[0] = 0;
for (unsigned int i = 0; i < m; i++) {
row_ptr_[i + 1] = buckets[i];
}
// We can use row_ptr_ to copy the column indices and vals to the
// correct positions in csr_col_ind and csr_vals
unsigned int* tmp_row_ptr = (unsigned int*)malloc(sizeof(unsigned int) *
m);
assert(tmp_row_ptr);
memcpy(tmp_row_ptr, row_ptr_, sizeof(unsigned int) * m);
// Now go through each non-zero and copy it to its appropriate position
for (unsigned int i = 0; i < nnz; i++) {
col_ind_[tmp_row_ptr[row_ind[i] - 1]] = col_ind[i] - 1;
vals_[tmp_row_ptr[row_ind[i] - 1]] = val[i];
tmp_row_ptr[row_ind[i] - 1]++;
}
// Copy the memory address to the input parameters
*csr_row_ptr = row_ptr_;
*csr_col_ind = col_ind_;
*csr_vals = vals_;
// Free memory
free(tmp_row_ptr);
free(buckets);
}
/* This function converts a matrix expressed in coordinate (COO)
format to ELLPACK (ELL) format.
input parameters
int* row_ind The row indices of a COO matrix
int* col_ind The column indices of a COO matrix
double* val The values associated with row_ind and col_ind
int m The number of rows in the COO matrix
int n The number of columns in the COO matrix
int nnz The number of non-zero entries in the COO
double** ell_data_ptr The array to store ELL data (column-major) in
unsigned int** ell_col_ind The array to store ELL column indices in
int* max_row_length The max number of non-zero entries in any row
return paramters:
none
*/
void convert_coo_to_ell(int* row_ind, int* col_ind, double* val,
int m, int n, int nnz,
double** ell_data_ptr, unsigned int** ell_col_ind, int* max_row_length) {
// Temporary pointers
double* data;
unsigned int* e_col_ind;
// Now determine how many non-zero elements are in each row
// Use a histogram to do this
unsigned int max_row = 0;
unsigned int* buckets = (unsigned int*)malloc(sizeof(unsigned int) * m);
assert(buckets);
memset(buckets, 0, sizeof(unsigned int) * m);
for (unsigned int i = 0; i < nnz; i++) {
// row_ind[i] - 1 because index in mtx format starts from 1 (not 0)
buckets[row_ind[i] - 1]++;
if (buckets[row_ind[i] - 1] > max_row) max_row = buckets[row_ind[i] - 1];
}
// We now know how big data and col_ind should be
data = (double*) malloc(sizeof(double) * m * max_row);
assert(data);
e_col_ind = (unsigned int*) malloc(sizeof(unsigned int) * m * max_row);
assert(e_col_ind);
// Zero out histogram again
memset(buckets, 0, sizeof(unsigned int) * m);
// Iterate through every non-zero value in array
unsigned int index;
for (unsigned int i = 0; i < nnz; i++) {
index = buckets[row_ind[i] - 1] * m + row_ind[i] - 1;
data[index] = val[i];
e_col_ind[index] = col_ind[i] - 1;
buckets[row_ind[i] - 1]++;
}
// Pad rest of arrays
for (unsigned int i = 0; i < m; i++) {
for (unsigned int j = buckets[i]; j < max_row; j++) {
index = j * m + i;
data[index] = 0.0;
e_col_ind[index] = 0;
}
}
// Copy the memory address to the input parameters
*ell_data_ptr = data;
*ell_col_ind = e_col_ind;
*max_row_length = max_row;
// Free memory
free(buckets);
}
void read_vector(char* fileName, double** vector, unsigned int* vecSize)
{
FILE* fp = fopen(fileName, "r");
assert(fp);
char line[MAX_NUM_LENGTH];
fgets(line, MAX_NUM_LENGTH, fp);
fclose(fp);
unsigned int vector_size = atoi(line);
double* vector_ = (double*)malloc(sizeof(double) * vector_size);
fp = fopen(fileName, "r");
assert(fp);
// first read the first line to get the # elements
fgets(line, MAX_NUM_LENGTH, fp);
unsigned int index = 0;
while (fgets(line, MAX_NUM_LENGTH, fp) != NULL) {
vector_[index] = atof(line);
index++;
}
fclose(fp);
assert(index == vector_size);
*vector = vector_;
*vecSize = vector_size;
}
void store_result(char* fileName, double* res, int m)
{
FILE* fp = fopen(fileName, "w");
assert(fp);
fprintf(fp, "%d\n", m);
for (int i = 0; i < m; i++) {
fprintf(fp, "%0.10f\n", res[i]);
}
fclose(fp);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* rush01.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hanskim <hanskim@student.42seoul.kr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/28 12:36:54 by hanskim #+# #+# */
/* Updated: 2021/02/28 18:43:18 by hanskim ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
extern int recursive(int r, int c);
extern int g_n;
extern int **g_condition;
extern int **g_fix;
extern int **g_box;
void init(void)
{
int i;
int j;
g_fix = (int **)malloc(sizeof(int *) * g_n);
g_box = (int **)malloc(sizeof(int *) * g_n);
i = -1;
while (++i < g_n)
{
g_fix[i] = (int *)malloc(sizeof(int) * g_n);
g_box[i] = (int *)malloc(sizeof(int) * g_n);
j = -1;
while (++j < g_n)
{
g_fix[i][j] = 0;
g_box[i][j] = 0;
}
}
return ;
}
int solve_n(void)
{
int i;
int j;
int k;
int r;
int c;
i = -1;
while ((j = -1) && (++i < g_n))
while (++j < g_n)
if ((k = -1) && (g_condition[i][j] == g_n))
while (++k < g_n)
{
r = i < 2 ? k : j;
c = i < 2 ? j : k;
if (g_fix[r][c] &&
(g_box[r][c] != (i % 2 ? g_n - k : k + 1)))
return (-1);
g_box[r][c] = i % 2 ? g_n - k : k + 1;
g_fix[r][c] = 1;
}
return (0);
}
int solve_one(void)
{
int i;
int j;
int row;
int col;
int val;
i = -1;
while (++i < g_n)
{
j = -1;
while (++j < g_n)
if (g_condition[i][j] == 1)
{
val = i % 2 ? g_n - 1 : 0;
row = i >= 2 ? j : val;
col = i < 2 ? j : val;
val = g_n;
if (g_fix[row][col] && g_box[row][col] != val)
return (-1);
g_box[row][col] = val;
g_fix[row][col] = 1;
}
}
return (0);
}
int solve_others(void)
{
return (recursive(0, 0));
}
int rush01(void)
{
init();
if (solve_n() < 0)
return (-1);
if (solve_one() < 0)
return (-1);
if (solve_others() < 0)
return (-1);
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct functions{
double* a, *b, *c,*d;
int size;
} Functions;
Functions* spline_cubic(double *x, double *y, int size){
Functions* output = (Functions*) malloc(sizeof(Functions));
output->a = (double*) malloc((sizeof(double))*(size+1));
output->b = (double*) malloc((sizeof(double))*(size+1));
output->c = (double*) malloc((sizeof(double))*(size+1));
output->d = (double*) malloc((sizeof(double))*(size+1));
output->size = size;
double h[size];
int i,j;
for(i=0 ; i< size - 1 ; i++){
h[i] = x[i+1] - x[i];
}
double alpha[size];
for(i=1 ; i < size - 1; i++){
alpha[i] = (3/(h[i]) * (y[i+1] - y[i])) - (3/(h[i-1]) * (y[i] - y[i-1]));
}
double aux1[size];
double aux2[size];
double aux3[size];
aux1[0] = 1;
aux2[0] = 0;
aux3[0] = 0;
for(i=1 ; i < size - 1; i++){
aux1[i] = 2*(x[i+1] - x[i-1]) - h[i-1]*aux2[i-1];
aux2[i] = h[i]/aux1[i];
aux3[i] = (alpha[i] - h[i-1]*aux3[i-1])/aux1[i];
}
aux1[size-1] = 1;
aux3[size-1] = 0;
output->c[size-1] = 0;
for(j=size-2 ; j >= 0 ; j-- ){
output->c[j] = aux3[j] - aux2[j]*output->c[j+1];
output->b[j] = (y[j+1] - y[j])/h[j] - h[j]*(output->c[j+1] + 2*output->c[j])/3;
output->d[j] = (output->c[j+1] - output->c[j])/(3*h[j]);
output->a[j] = y[j];
}
return output;
}
void print_function( Functions *graf){
int i;
for(i=0 ; i<graf->size-1; i++){
//puts("Certo ate aqui!");
printf("%.2lfx³ + %.2lfx² + %.2lfx + %.2lf\n", graf->d[i],graf->c[i],graf->b[i],graf->a[i]);
}
}
int main(){
double x[3] = {1., 2., 3.};
double y[3] = {2., 3., 5.};
int size = 3;
Functions *teste = spline_cubic(x, y, size);
print_function(teste);
return 0;
}
|
C
|
int main()
{
int b,c,i;
char a[100],z[100];
scanf("%s %s",&a,&z);
for(i=0;a[i]!='\0';i++);
b=i;
for(i=0;z[i]!='\0';i++);
c=i;
if(b>c)
printf("%s",a);
else if(b==c)
printf("%s",a);
else
printf("%s",z);
}
|
C
|
#include <stdio.h>
#include <SDL.h>
#include "engine.h"
int main(void){
printf("Initializing SDL video module.\n");
// Setting up SDL.
if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) != 0){
printf("Failed to initialize SDL: %s\n", SDL_GetError());
return 1;
}
SDL_SetVideoMode(700, 700, 24, SDL_SWSURFACE);//SDL_DOUBLEBUF);
SDL_Surface *main_surf = SDL_GetVideoSurface();
// Setting up the simulation configuration.
struct simulation_t simulation;
simulation = create_new_simulation(0.00005, 100, main_surf);
run_simulation(simulation);
// done, do some cleanup
// destroy_simulation(simulation);
SDL_Quit();
return 0;
}
|
C
|
#include "dominion.h"
#include "dominion_helpers.h"
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "rngs.h"
#include <math.h>
#define DEBUG 1
#define NOISY_TEST 1
// //discardCard(int handPos, int currentPlayer, struct gameState *state, int trashFlag)
int checkDiscardCard(int handPos, int currentPlayer, struct gameState *post, int trashFlag) {
struct gameState pre;
memcpy (&pre, post, sizeof(struct gameState));
int r;
r = discardCard(handPos, currentPlayer, post, trashFlag);
if (trashFlag < 1)
{
assert(post->playedCards[pre.playedCardCount] == pre.hand[currentPlayer][handPos]);
assert(pre.playedCardCount + 1 == post->playedCardCount);
}
assert(post->hand[currentPlayer][handPos] = -1);
//remove card from player's hand
if ( handPos == (pre.handCount[currentPlayer] - 1) ) //last card in hand array is played
{
assert(pre.handCount[currentPlayer] - 1 == post->handCount[currentPlayer] );
}
else if ( pre.handCount[currentPlayer] == 1 ) //only one card in hand
{
assert( pre.handCount[currentPlayer] - 1 == post->handCount[currentPlayer] );
}
else
{
assert( pre.hand[currentPlayer][ (pre.handCount[currentPlayer])] == post->hand[currentPlayer][ (post->handCount[currentPlayer] + 1) ] );
assert( post->hand[currentPlayer][post->handCount[currentPlayer]] == -1 );
assert( pre.handCount[currentPlayer] - 1 == post->handCount[currentPlayer] );
}
assert( r == 0 );
return 0;
}
int main () {
int i, n, r, p, deckCount, discardCount, handCount, toFlag, supplyPos, handPos, trash;
int k[10] = {adventurer, council_room, feast, gardens, mine,
remodel, smithy, village, baron, great_hall};
struct gameState G;
printf ("Testing DISCARDCARD.\n");
SelectStream(2);
PutSeed(3);
for (i = 0; i < sizeof(struct gameState); i++) {
((char*)&G)[i] = floor(Random() * 256);
}
int handCountConst = floor(Random() * MAX_HAND);
p = 0;
handPos = 5;
G.deckCount[p] = 40;
G.discardCount[p] = 10;
G.handCount[p] = 8;
G.discard[p][G.discardCount[p]] = 100;
G.playedCardCount = 3;
G.playedCards[ G.playedCardCount ] = G.hand[p][handPos-1];
trash = 0;
//discardCard(int handPos, int currentPlayer, struct gameState *state, int trashFlag)
checkDiscardCard(handPos, p , &G, trash); // checking trash = 0
trash = 1;
handPos = 6;
checkDiscardCard(handPos, p , &G, trash); // checking trash = 1
G.handCount[p] = 1;
checkDiscardCard(handPos, p , &G, trash); // checking trash = 1
// checkDiscardCard(supplyPos, &G, 1, p); // checking toFlag = 1
// checkDiscardCard(supplyPos, &G, 2, p); // checking toFlag = 2
// checkDiscardCard(-1, &G, -1, p); ////check if supply pile is empty (0) or card is not used in game (-1)
printf ("ALL TESTS OK FOR DISCARDCARD\n\n");
exit(0);
return 0;
}
|
C
|
#include <iostream>
using namespace std;
int add(int a[], int n, int k)
{
int count=0;
int p;
for(int i=0; i<n; i++)
{
a[i]=a[i]+1;
count++;
}
p=min(a, n);
if(p>=k)
{
return count;
}
else
{
add(a, n, k);
}
}
int min(int a[], int n)
{
int m=1000;
for(int i=0;i<n; i++)
{
if(a[i]<m)
{
m=a[i];
}
}
return m;
}
int main() {
int t;
cin>>t;
while(t--){
int n,k;
int ans;
cin>>n;
cin>>k;
int a[n];
for(int i=0; i<n; i++)
{
cin>>a[i];
}
ans= add(a, n, k);
cout<<ans<<"\n";
}
return 0;
}
|
C
|
#include <stdio.h>
#include <conio.h>
int main () {
float distancia, tempo, velocidade, Lusados;
printf ("\n\tCALCULE SUA VIAGEM!\n");
printf ("\nPRESSIONE ENTER...\n");
getch();
printf ("\n-------------------------------------\n");
printf ("\tPRECISAMOS DE ALGUNS DADOS!");
printf ("\n-------------------------------------\n");
printf ("\nQUANTO TEMPO LEVOU SUA VIAGEM?\n");
scanf ("%f", &tempo);
printf ("\nQUANTOS KM PERCORRIDOS?\n");
scanf ("%f", &velocidade);
distancia = tempo*velocidade;
printf ("\n SUA DISTANCIA PERCORRIDA:%.2f", distancia);
printf ("\nAGORA VAMOS PARA OS CALCULOS FINAIS\n");
printf ("\n PRESSIONE ENTER...\n");
getch();
Lusados = distancia/12;
printf ("\nA QUANTIDADE DE LITROS EM SUA VIAGEM FOI:\n\t%.2f", Lusados);
getch();
printf ("\nFIM\n");
system("PAUSE");
return (0);
}
|
C
|
#include<iostream>
#include <algorithm>
#include <vector>
using namespace std;
int r, c;
int cnt = 0;
void Z(int n,int x, int y);
int main()
{
int n;
cin >> n >> r >> c;
n = 2 << (n - 1);
Z(n, 0, 0);
return 0;
}
void Z(int n, int x, int y)
{
if (n == 2)
{
if (x == r&&y == c) {
cout << cnt;
return;
}
cnt++;
if (x == r && y+1 == c) {
cout << cnt;
return;
}
cnt++;
if (x+1 == r&&y == c) {
cout << cnt;
return;
}
cnt++;
if (x +1 == r && y +1 == c) {
cout << cnt;
return;
}
cnt++;
return;
}
Z(n / 2, x, y);
Z(n / 2,x,y+n/2);
Z(n / 2,x+n/2,y);
Z(n / 2,x+n/2,y+n/2);
}
|
C
|
// Encapsulates one color scheme
typedef struct colorizer_t {
int num_buckets;
float** rgbs;
} Colorizer;
Colorizer* colorizer_init(int num_buckets);
float* colorizer_color(float r, float g, float b);
void colorizer_calc_colors(const Colorizer colorizer, float greyscale, float* colors);
|
C
|
/*-
* descriptor.c - Descriptor
*
* Copyright 2015 Wenwen Chen
*/
/*!
* \addtogroup descriptor
* \{
*
* \file
* \brief Implementation the common descriptor functions
*
* \author Wenwen Chen
*/
#include "descriptor.h"
unsigned int getLeastActiveDescriptor(descriptor *p_descriptors, unsigned int descriptors_len){
unsigned int leastActiveDescriptorId=0; /*!<Store the id of the descriptor, which is the most inactive. That means, the descriptor value is the smallest*/
uint8_t leastActiveDescriptorValue = DESCRIPTOR_MAX_COUNTER;
for(int i=0; i< descriptors_len;i++){
if(DESCRIPTOR_INACTIVE == p_descriptors[i]){
return i;
}
if(p_descriptors[i] < leastActiveDescriptorValue){
leastActiveDescriptorId = i;
leastActiveDescriptorValue = p_descriptors[i];
}
}
return leastActiveDescriptorId;
}
unsigned int addNewDescriptor(descriptor *p_descriptors, unsigned int descriptors_len, unsigned int predefined_data_len, void * p_data, unsigned int len,
int (*checkFunc)(unsigned int, void *, unsigned int), int (*updateFunc)(unsigned int, void *, unsigned int)){
unsigned int leastActiveDescriptorId=0; /*!<Store the id of the descriptor, which is the most inactive. That means, the descriptor value is the smallest*/
uint8_t leastActiveDescriptorValue = p_descriptors[0];
int i = 0;
for(; i< descriptors_len;i++){
if(DESCRIPTOR_INACTIVE != p_descriptors[i]){
if(checkFunc(i, p_data, len)){
p_descriptors[i] = DESCRIPTOR_MAX_COUNTER;
return i;
}
p_descriptors[i]--;
}
if(p_descriptors[i] < leastActiveDescriptorValue){
leastActiveDescriptorId = i;
leastActiveDescriptorValue = p_descriptors[i];
}
}
for(i = 0; i< predefined_data_len; i++){
if(checkFunc(descriptors_len+i, p_data, len)){
return descriptors_len+i;
}
}
if(SUCC== updateFunc(leastActiveDescriptorId, p_data, len)){
return leastActiveDescriptorId;
}
return NO_DESCRIPTOR;
}
/*!
* \}
*/
|
C
|
#include <stdio.h>
int main()
{
int n=0;
for(int i=1;i<=7;i++)
{
for( int j=0;j<32-i;j+=(i+3))
{
printf("%d,",j);
}
printf("\n");
}
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <curses.h>
#include <math.h>
#include "CAM.h"
CAM_screen *my_screen;
unsigned int player1_y;
unsigned int player2_y;
int ball_x;
int ball_y;
double ball_dx = 1;
double ball_dy = 1;
unsigned int bat_height = 50;
unsigned char quit;
void game_tick(){
int pressed;
double r;
pressed = getch();
if(pressed == 'e' && player1_y){
player1_y -= 5;
} else if(pressed == 'c' && player1_y + bat_height < LINES*13 - 5){
player1_y += 5;
}
if(pressed == KEY_UP && player2_y){
player2_y -= 5;
} else if(pressed == KEY_DOWN && player2_y + bat_height < LINES*13 - 5){
player2_y += 5;
}
if(pressed == 'q'){
quit = 1;
}
if(ball_dx + ball_x < 0){
if(ball_y + 5 >= player1_y && ball_y - 5 <= player1_y + bat_height){
r = ((double) rand())/RAND_MAX;
ball_dx = -ball_dx + r*r;
} else {
ball_dx = -ball_dx;
quit = 1;
}
}
if(ball_dx + ball_x > COLS*8 - 19){
if(ball_y + 5 >= player2_y && ball_y - 5 <= player2_y + bat_height){
r = ((double) rand())/RAND_MAX;
ball_dx = -ball_dx - r*r;
} else {
ball_dx = -ball_dx;
quit = 1;
}
}
if(ball_dy + ball_y < 0 || ball_dy + ball_y > LINES*13 - 11){
ball_dy = -ball_dy;
}
ball_x += ball_dx;
ball_y += ball_dy;
CAM_fill(my_screen, COLOR_WHITE);
CAM_rect(my_screen, 0, player1_y, 8, player1_y + bat_height, COLOR_BLUE);
CAM_rect(my_screen, COLS*8 - 17, player2_y, COLS*8 - 9, player2_y + bat_height, COLOR_GREEN);
CAM_rect(my_screen, ball_x, ball_y, ball_x + 7, ball_y + 7, COLOR_RED);
CAM_update(my_screen);
refresh();
}
int main(int argc, char *argv[]){
initscr();
refresh();
start_color();
CAM_init(1);
struct timespec spec;
long last_frame;
srand(time(NULL));
cbreak();
noecho();
keypad(stdscr, TRUE);
nodelay(stdscr, TRUE);
my_screen = CAM_screen_create(stdscr, COLS - 1, LINES);
player1_y = 0;
player2_y = 0;
ball_x = 50;
ball_y = 50;
quit = 0;
clock_gettime(CLOCK_MONOTONIC, &spec);
last_frame = round(spec.tv_nsec/1.0e6) + 1000*spec.tv_sec;
while(!quit){
clock_gettime(CLOCK_MONOTONIC, &spec);
if(round(spec.tv_nsec/1.0e6) + 1000*spec.tv_sec - last_frame > 20){
last_frame = round(spec.tv_nsec/1.0e6) + 1000*spec.tv_sec;
game_tick();
}
}
endwin();
CAM_screen_free(my_screen);
}
|
C
|
/* splits a dollar amount into highest bills */
#include <stdio.h>
int main(void)
{
int dollars, twenties, tens, fives;
printf("Enter a dollar amount: ");
scanf("%d", &dollars);
twenties = dollars / 20;
dollars -= twenties * 20;
tens = dollars / 10;
dollars -= tens * 10;
fives = dollars / 5;
dollars -= fives * 5;
printf("$20 dollar bills: %d\n", twenties);
printf("$10 dollar bills: %d\n", tens);
printf(" $5 dollar bills: %d\n", fives);
printf(" $1 dollar bills: %d\n", dollars);
return 0;
}
|
C
|
// To check the structure of if-else statement:
#include<stdio.h>
void main() {
int x;
printf(“Enter a value”);
scanf(“%d”, &x);
if(x > 0)
printf(“%d”, x);
else
printf(“Number is zero”);
}
object Good7 {
def main(args: Array[String]) {
println("Enter a value")
val x=scala.io.StdIn.readInt();
if( x > 0 ){
println(x);
}
else {
println("Number is zero");
}
}
}
|
C
|
#include "stdio.h"
#include "../utils.h"
// Solicitar dois números inteiros "a" e "b" e imprimir na tela se o
// primeiro é perfeitamente divisível pelo segundo ("a"/"b"), sem gerar resto;
int main()
{
int a, b;
readInt("Informe o primeiro número", &a);
readInt("Informe o segundo número", &b);
printf("%i %s perfeitamente divisível por %i\n", a, a % b == 0 ? "é" : "não é", b);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct PersonNode {
char* name;
struct PersonNode* prev;
struct PersonNode* next;
};
typedef struct PersonNode* Favorites;
struct Person {
char* name;
Favorites favorites;
};
int main() {
struct PersonNode Node_A;
struct Person PersonA;
Node_A.name = "ABC";
Favorites favorite = malloc(sizeof(Favorites));
PersonA.favorites = malloc(sizeof(Favorites));
favorite->name = Node_A.name;
PersonA.favorites->name = Node_A.name;
printf("Node_A.name = %s\n", Node_A.name);
printf("favorite->name = %s\n", favorite->name);
printf("PersonA.favorites->name = %s\n", PersonA.favorites->name);
free(favorite);
free(PersonA.favorites);
return 0;
}
|
C
|
#include <xc.h>
#include "tmr1.h"
volatile uint16_t timer1ReloadVal;
void (*TMR1_InterruptHandler)(void);
void TMR1_Initialize(void)
{
T1CONbits.TMR1ON=0;
TMR1H=0x00;
TMR1L=0x00;
T1CON=0b00110100;
// Load the TMR value to reload variable
timer1ReloadVal=(uint16_t) ((TMR1H<<8)|TMR1L);
// Set Default Interrupt Handler
TMR1_SetInterruptHandler(TMR1_DefaultInterruptHandler);
// Clearing IF flag before enabling the interrupt.
PIR1bits.TMR1IF=0;
// Enabling TMR1 interrupt.
PIE1bits.TMR1IE=1;
T1CONbits.TMR1ON=1;
}
void TMR1_StartTimer(void)
{
// Start the Timer by writing to TMRxON bit
T1CONbits.TMR1ON=1;
}
void TMR1_StopTimer(void)
{
// Stop the Timer by writing to TMRxON bit
T1CONbits.TMR1ON=0;
}
uint16_t TMR1_ReadTimer(void) {
uint16_t readVal = TMR1H;
readVal <<= 8;
readVal |= TMR1L;
return readVal;
}
void TMR1_WriteTimer(uint16_t timerVal)
{
if(T1CONbits.nT1SYNC==1)
{
// Stop the Timer by writing to TMRxON bit
T1CONbits.TMR1ON=0;
// Write to the Timer1 register
TMR1H=(uint8_t) (timerVal>>8);
TMR1L=(uint8_t) timerVal;
// Start the Timer after writing to the register
T1CONbits.TMR1ON=1;
}
else
{
// Write to the Timer1 register
TMR1H=(uint8_t) (timerVal>>8);
TMR1L=(uint8_t) timerVal;
}
}
void TMR1_Reload(void)
{
TMR1_WriteTimer(timer1ReloadVal);
}
void TMR1_ISR(void)
{
// Clear the TMR1 interrupt flag
PIR1bits.TMR1IF=0;
TMR1_WriteTimer(timer1ReloadVal);
// ticker function call;
// ticker is 1 -> Callback function gets called everytime this ISR executes
TMR1_CallBack();
}
void TMR1_CallBack(void)
{
// Add your custom callback code here
if(TMR1_InterruptHandler)
{
TMR1_InterruptHandler();
}
}
void TMR1_SetInterruptHandler(void (* InterruptHandler)(void))
{
TMR1_InterruptHandler=InterruptHandler;
}
void TMR1_DefaultInterruptHandler(void)
{
// add your TMR1 interrupt custom code
// or set custom function using TMR1_SetInterruptHandler()
}
|
C
|
/*Binary search in 2D use diagoal as the base*/
bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) {
if(!matrix) return false;
int i = matrixRowSize-1;
int j = 0;
while(j<matrixColSize && i>=0){
if(matrix[i][j] == target){
return true;
}else if(matrix[i][j] < target){
j++;
}else {
i--;
}
}
return false;
}
|
C
|
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int main()
{
umask(0);
if(creat("example_681.test",0777)<0)
{
perror("creat");
exit(1);
}
umask(S_IRWXO);
if(creat("example_682.test",0777)<0)
{
perror("creat");
exit(1);
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <flickcurl.h>
#include "conf.h"
#define KEY "2e66493ec959256a79e4e5a3da7df729"
#define SECRET "c1b99d47790391c3"
static char conf_file_name[] = ".flickcurl.conf";
char *get_conf_path() {
char *conf_path;
char *home;
home = getenv("HOME");
if(!home)
return 0;
conf_path = (char *)malloc(strlen(home) + strlen(conf_file_name) + 2);
if(!conf_path)
return 0;
strcpy(conf_path, home);
strcat(conf_path, "/");
strcat(conf_path, conf_file_name);
return conf_path;
}
int create_conf(char *conf_path, flickcurl *fc) {
#define VERIFIER_SIZE 12
char verifier[VERIFIER_SIZE];
flickcurl_set_oauth_client_key(fc, KEY);
flickcurl_set_oauth_client_secret(fc, SECRET);
if(flickcurl_oauth_create_request_token(fc, NULL))
return FAIL;
const char *uri = flickcurl_oauth_get_authorize_uri(fc);
printf( "Go to: %s\n", uri );
printf( "Enter the 9-digit Verifier: " );
if(!fgets(verifier, VERIFIER_SIZE, stdin))
return FAIL;
if(flickcurl_oauth_create_access_token(fc, verifier))
return FAIL;
if(flickcurl_config_write_ini(fc, conf_path, "flickr"))
return FAIL;
return SUCCESS;
}
int check_conf_file(char *conf_path, flickcurl *fc) {
if(access(conf_path, F_OK) < 0) /* If conf file doesn't exist, create */
if(create_conf(conf_path, fc))
return FAIL;
return SUCCESS;
}
|
C
|
#include <stdio.h>
void print_array(char* s, int* a, int size);
void cum_sum(int* a, int* b, int size);
int main() {
int a[] = {31,28,31,30,31,30,31,31,30,31,30,31};
print_array("a", a, 12);
int b[12];
cum_sum(a, b, 12);
print_array("b", b, 12);
}
void print_array(char* s, int* a, int size) {
printf("%s :", s);
for(int i = 0; i < size; i++) {
printf("%d ", a[i]);
}
puts("");
}
void cum_sum(int* a, int* b, int size) {
int c = 0;
for(int i = 0; i < size; i++) {
c += a[i];
b[i] = c;
}
}
|
C
|
/*************************************************************************
*
* Copyright 1993 Mentor Graphics Corporation
* All Rights Reserved.
*
* THIS WORK CONTAINS TRADE SECRET AND PROPRIETARY INFORMATION WHICH IS
* THE PROPERTY OF MENTOR GRAPHICS CORPORATION OR ITS LICENSORS AND IS
* SUBJECT TO LICENSE TERMS.
*
*************************************************************************/
/*************************************************************************
*
* FILE NAME
*
* tcp_gda.c
*
* DESCRIPTION
*
* This file contains the routine to retrieve the value to delay TCP
* ACKs on a TCP socket at run-time.
*
* DATA STRUCTURES
*
* None.
*
* FUNCTIONS
*
* TCP_Getsockopt_TCP_DELAY_ACK
*
* DEPENDENCIES
*
* nu_net.h
*
************************************************************************/
#include "networking/nu_net.h"
/*************************************************************************
*
* FUNCTION
*
* TCP_Getsockopt_TCP_DELAY_ACK
*
* DESCRIPTION
*
* Retrieve the value to delay TCP ACKs on a TCP socket at run-time.
*
* INPUTS
*
* socketd Socket for which to retrieve the value.
* *delay Pointer to the memory in which to store
* the value in hardware ticks to delay
* transmitting ACKs for incoming data for
* the specified socket.
*
* OUTPUTS
*
* NU_SUCCESS Indicates successful completion of the
* service.
* NU_INVALID_SOCKET The socket passed in does not reference a
* valid TCP socket descriptor.
*
*************************************************************************/
STATUS TCP_Getsockopt_TCP_DELAY_ACK(INT socketd, UINT32 *delay)
{
INT pindex;
STATUS status;
/* Retrieve the port index. */
pindex = SCK_Sockets[socketd]->s_port_index;
/* If the TCP port is valid, return the value of the option. */
if ( (pindex != NU_IGNORE_VALUE) && (TCP_Ports[pindex] != NU_NULL) )
{
/* Store the value in the memory provided. */
*delay = TCP_Ports[pindex]->p_delay_ack;
status = NU_SUCCESS;
}
/* The socket is invalid. */
else
{
status = NU_INVALID_SOCKET;
}
return (status);
} /* TCP_Getsockopt_TCP_DELAY_ACK */
|
C
|
#define MAX_NAME 30 //ũ
#define N_KEYS 14
struct keytab{ //ü Ʋ
int nums; // īƮ
char name[MAX_NAME]; //Ű
};
struct keytab keywrds[N_KEYS] ={
{0, "int"},
{0, "float"},
{0, "return"},
{0, "if"},
{0, "for"},
{0, "while"},
{0, "goto"},
{0, "switch"},
{0, "case"},
{0, "void"},
{0, "default"},
{0, "char"},
{0, "do"},
{0, "scanf"}
};
void count_word(char *word){
int i;
//repeat each keywords
for (i=0;i<N_KEYS;i++)
{ //if word and i'th keyword is same
if(strncmp(word, keywrds[i].name, strlen(keywrds[i].name)/*keywrdsڿ */)==0/*n */){
//nums++;
keywrds[i].nums++;
}
}
}
void print_word()//Ű Ƚ Ʈ
{
int i;
//i Ű忡 ؼ
for(i=0;i<N_KEYS;i++)
{
//printf(Ű̸:);
printf("%s : %i\n", keywrds[i].name, keywrds[i].nums);
}
}
|
C
|
#include <stdio.h>
void main()
{
char letter;
printf("please input the first letter of someday\n");
while ((letter=getch())!='Y')/*ĸΪYʱŽ*/
{ switch (letter)
{case 'S':printf("please input second letter\n");
if((letter=getch())=='a')
printf("saturday\n");
else if ((letter=getch())=='u')
printf("sunday\n");
else printf("data error\n");
break;
case 'F':printf("friday\n");break;
case 'M':printf("monday\n");break;
case 'T':printf("please input second letter\n");
if((letter=getch())=='u')
printf("tuesday\n");
else if ((letter=getch())=='h')
printf("thursday\n");
else printf("data error\n");
break;
case 'W':printf("wednesday\n");break;
default: printf("data error\n");
}
}
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "ricette.h"
struct ricette
{
char *nome;
int tempo;
int num_ing_ric;
char **lista;
int *grammi;
ricetta next;
};
ricetta leggi_ricette()
{
FILE* fp;
int i, num, tempo, num_ing_ric;
char nome[31];
ricetta head;
fp= fopen("ricette.txt", "r"); //APERTURA + CONTROLLO FILE RICETTE
if(fp==NULL)
{
printf("Errore");
exit(-2);
}
head= malloc(sizeof(*head)); //ALLOCAZIONE TESTA DELLA LISTA RICETTE
head->next= NULL;
fscanf(fp, "%d", &num); //ACQUISIZIONE RICETTE
for(i=0; i<num; i++)
{
fscanf(fp, "%s%d%d", nome, &tempo, &num_ing_ric);
head= instail(head, nome, tempo, num_ing_ric, fp, 0);
}
return head;
}
ricetta newnode(char *nome, int tempo, int num_ing_ric, ricetta next, FILE* fp, int tipo)
{
int j;
char text[31];
ricetta x= malloc(sizeof(*x));
if(x==NULL)
return NULL;
else
{
x->nome= strdup(nome);
x->tempo= tempo;
x->num_ing_ric= num_ing_ric;
x->grammi= malloc(num_ing_ric*sizeof(int));
x->lista= malloc(num_ing_ric*sizeof(char*));
if(tipo==0) //INPUT INGREDIENTI RICETTA DA FILE
for(j=0; j<num_ing_ric; j++)
{
fscanf(fp, "%s%d", text, &x->grammi[j]);
x->lista[j]= strdup(text);
}
else //INPUT INGREDIENTI RICETTA DA TASTIERA
for(j=0; j<num_ing_ric; j++)
{
printf("%d: ", j+1);
scanf("%s%d", text, &x->grammi[j]);
x->lista[j]= strdup(text);
}
x->next= next;
}
return x;
}
ricetta instail(ricetta h, char *nome, int tempo, int num_ing_ric, FILE* fp, int tipo)
{
ricetta x;
if(h==NULL) //CONTROLLA CHE NON SIA LA TESTA
return newnode(nome, tempo, num_ing_ric, NULL, fp, tipo);
for(x=h; x->next!=NULL; x=x->next); //SCORRE LA LISTA FINO ALLA CODA
x->next = newnode(nome, tempo, num_ing_ric, NULL, fp, tipo); //AGGIUNGE IL NUOVO NODO
return h;
}
int info_ricetta(ricetta h, char *nome)
{
ricetta x;
for(x=h->next; x!=NULL; x=x->next)
if(strcmp(nome, x->nome)==0)
{
printf("Tempo di preparazione: %d\n", x->tempo);
printf("Numero ingredienti necessari: %d\n", x->num_ing_ric);
return 1;
}
return 0;
}
float calcolo_costo(ingredienti ing, ricetta h, char *nome)
{
int j, trovato= 0;
float calorie, costo, costo_tot= 0;
ricetta x;
for(x=h->next; x!=NULL; x=x->next) //SCORRE LA LISTA RICETTE ALLA RICERCA DELLA RICETTA DESIDERATA
if(strcmp(nome, x->nome)==0)
{
trovato= 1;
break;
}
if(trovato==0) //FALLIMENTO RICERCA
return -1;
for(j=0; j<x->num_ing_ric; j++) //SCORRIMENTO LISTA INGREDIENTI DELLA RICETTA
if(ricerca_calorie_costo(ing, x->lista[j], &calorie, &costo)==1)
{
calorie= calorie/1000;
if(calorie<1)
calorie= 1;
costo_tot= costo_tot + calorie*costo;
}
return costo_tot;
}
float calcolo_calorie(ingredienti ing, ricetta h, char *nome)
{
int j, trovato= 0;
float costo, calorie, calorie_tot= 0;
ricetta x;
for(x=h->next; x!=NULL; x=x->next) //SCORRE LA LISTA RICETTE ALLA RICERCA DELLA RICETTA DESIDERATA
if(strcmp(nome, x->nome)==0)
{
trovato= 1;
break;
}
if(trovato==0) //FALLIMENTO RICERCA
return -1;
for(j=0; j<x->num_ing_ric; j++) //SCORRIMENTO LISTA INGREDIENTI DELLA RICETTA
if(ricerca_calorie_costo(ing, x->lista[j], &calorie, &costo)==1)
calorie_tot= calorie_tot + calorie*x->grammi[j];
return calorie_tot;
}
int ricerca_ingrediente(ricetta h, char *nome)
{
int j, trovato= 0;
ricetta x;
for(x=h->next; x!=NULL; x=x->next)
for(j=0; j<x->num_ing_ric; j++)
if(strcmp(nome, x->lista[j])==0)
{
printf("%s\n", x->nome);
trovato= 1;
}
if(trovato==1)
return 1;
else
return 0;
}
void stampa_ricette(ricetta h)
{
ricetta x;
for(x=h->next; x!=NULL; x=x->next)
printf("%s\n", x->nome);
}
ricetta aggiunta_ricetta(ricetta h)
{
char nome[31];
int tempo, num_ing_ric;
printf("Inserire il nome della ricetta: ");
scanf("%s", nome);
printf("Inserire il tempo di preparazione: ");
scanf("%d", &tempo);
printf("Inserire il numero di ingredienti necessari: ");
scanf("%d", &num_ing_ric);
h= instail(h, nome, tempo, num_ing_ric, 0, 1);
return h;
}
|
C
|
#ifndef MAZE_SDL_MAZE_RENDERER_H
#define MAZE_SDL_MAZE_RENDERER_H
#include <SDL2/SDL.h>
#include "Maze.h"
void render_maze_to_sdl(SDL_Renderer *renderer, const Maze *maze, int cell_size);
int render_maze_with_refresh(
const Maze *maze,
int cell_size,
void (*maze_generator)(const Maze *)
) {
if (maze == NULL || cell_size < 1 || maze_generator == NULL) {
fprintf(stderr, "Invalid arguments for rendering");
return 1;
}
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
fprintf(stderr, "Failed to init video: %s\n", SDL_GetError());
return 1;
}
const int window_width = maze->width * cell_size;
const int window_height = maze->height * cell_size;
SDL_Window *window = SDL_CreateWindow(
"Maze",
0, 0,
window_width, window_height,
SDL_WINDOW_SHOWN
);
if (window == NULL) {
fprintf(stderr, "Unable to create window: %s\n", SDL_GetError());
return 1;
}
SDL_Renderer *renderer = SDL_CreateRenderer(
window,
-1,
SDL_RENDERER_SOFTWARE
);
if (renderer == NULL) {
fprintf(stderr, "Unable to create renderer: %s\n", SDL_GetError());
return 1;
}
maze_generator(maze);
render_maze_to_sdl(renderer, maze, cell_size);
bool done = false;
SDL_Event event;
while (!done && SDL_WaitEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
done = true;
break;
case SDL_WINDOWEVENT: {
switch (event.window.event) {
case SDL_WINDOWEVENT_MOVED:
case SDL_WINDOWEVENT_MAXIMIZED:
case SDL_WINDOWEVENT_RESIZED:
case SDL_WINDOWEVENT_RESTORED:
case SDL_WINDOWEVENT_SIZE_CHANGED:
render_maze_to_sdl(renderer, maze, cell_size);
break;
default:
break;
}
}
break;
case SDL_KEYUP: {
SDL_KeyCode code = event.key.keysym.sym;
if (code == SDLK_ESCAPE) {
done = true;
} else {
maze_generator(maze);
render_maze_to_sdl(renderer, maze, cell_size);
}
break;
}
}
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
return 0;
}
void render_maze_to_sdl(SDL_Renderer *renderer, const Maze *maze, int cell_size) {
if (renderer == NULL || maze == NULL) {
return;
}
const int width = maze->width;
const int height = maze->height;
SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE);
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
Cell *cell = cell_at(maze, x, y);
if (cell == NULL) continue;
Directions dirs = get_blocked_directions(cell);
if (dirs.north) {
SDL_RenderDrawLine(
renderer,
x * cell_size, y * cell_size,
(x * cell_size) + cell_size, y * cell_size
);
}
if (dirs.south) {
SDL_RenderDrawLine(
renderer,
x * cell_size, (y * cell_size) + cell_size,
(x * cell_size) + cell_size, (y * cell_size) + cell_size
);
}
if (dirs.west) {
SDL_RenderDrawLine(
renderer,
x * cell_size, y * cell_size,
x * cell_size, (y * cell_size) + cell_size
);
}
if (dirs.east) {
SDL_RenderDrawLine(
renderer,
(x * cell_size) + cell_size, y * cell_size,
(x * cell_size) + cell_size, (y * cell_size) + cell_size
);
}
}
}
SDL_RenderPresent(renderer);
}
#endif //MAZE_SDL_MAZE_RENDERER_H
|
C
|
#include "philo.h"
/*
* lock for num_phil + 1 -> die flag
* lock for num_phil + 2 -> count phils with num2eat 0
*/
int check2die(t_phil *ph)
{
pthread_mutex_lock(ph->lock[ph->num_phil]);
if (*ph->die == 1 || *ph->rf == ph->num_phil)
{
pthread_mutex_unlock(ph->lock[ph->num_phil]);
return (1);
}
pthread_mutex_unlock(ph->lock[ph->num_phil]);
return (0);
}
void set_death(t_phil *ph, uint64_t c_time)
{
pthread_mutex_lock(ph->lock[ph->num_phil]);
*ph->die = 1;
printf("\033[1;31m[%llu] %d died!\n",
(get_time() - c_time) / 1000, ph->uni_num);
printf("\033[0m");
pthread_mutex_unlock(ph->lock[ph->num_phil]);
return ;
}
void *run_sim(void *phil)
{
t_phil *ph;
uint64_t c_time;
int res;
ph = (t_phil *) phil;
c_time = get_time();
ph->tlm = c_time;
while (1)
{
if (check2die(ph))
return (NULL);
if (ph->t2e > ph->t2d || get_time() - ph->tlm > ph->t2d)
return (return_death(c_time, ph));
res = eat(ph, c_time);
if (res == 1)
return (return_death(c_time, ph));
else if (res == 0)
{
if (get_time() - ph->tlm + ph->t2s > ph->t2d)
return (return_death(c_time, ph));
ft_sleep(ph, c_time);
}
}
}
int start_loop(t_params *p)
{
int i;
i = 0;
while (i < p->num_phil)
{
ft_usleep(200);
p->phil[i] = create_phil(p, i + 1);
if (pthread_create(&(p->tid[i]), NULL, &run_sim, &p->phil[i]))
return (1);
i++;
}
i--;
while (i >= 0)
{
pthread_join(p->tid[i], NULL);
i--;
}
clean_up(p);
return (0);
}
int main(int argc, char **argv)
{
t_params params;
if (argc < 5 || argc > 6)
{
printf("Wrong number of arguments\n");
return (EXIT_FAILURE);
}
if (init_params(¶ms, argc, argv))
return (EXIT_FAILURE);
if (start_loop(¶ms))
return (EXIT_FAILURE);
return (EXIT_SUCCESS);
}
|
C
|
/*
* nghttp2 - HTTP/2 C Library
*
* Copyright (c) 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "nghttp2_map.h"
#include <string.h>
#define INITIAL_TABLE_LENGTH 256
int nghttp2_map_init(nghttp2_map *map, nghttp2_mem *mem) {
map->mem = mem;
map->tablelen = INITIAL_TABLE_LENGTH;
map->table =
nghttp2_mem_calloc(mem, map->tablelen, sizeof(nghttp2_map_entry *));
if (map->table == NULL) {
return NGHTTP2_ERR_NOMEM;
}
map->size = 0;
return 0;
}
void nghttp2_map_free(nghttp2_map *map) {
nghttp2_mem_free(map->mem, map->table);
}
void nghttp2_map_each_free(nghttp2_map *map,
int (*func)(nghttp2_map_entry *entry, void *ptr),
void *ptr) {
uint32_t i;
for (i = 0; i < map->tablelen; ++i) {
nghttp2_map_entry *entry;
for (entry = map->table[i]; entry;) {
nghttp2_map_entry *next = entry->next;
func(entry, ptr);
entry = next;
}
map->table[i] = NULL;
}
}
int nghttp2_map_each(nghttp2_map *map,
int (*func)(nghttp2_map_entry *entry, void *ptr),
void *ptr) {
int rv;
uint32_t i;
for (i = 0; i < map->tablelen; ++i) {
nghttp2_map_entry *entry;
for (entry = map->table[i]; entry; entry = entry->next) {
rv = func(entry, ptr);
if (rv != 0) {
return rv;
}
}
}
return 0;
}
void nghttp2_map_entry_init(nghttp2_map_entry *entry, key_type key) {
entry->key = key;
entry->next = NULL;
}
/* Same hash function in android HashMap source code. */
/* The |mod| must be power of 2 */
static uint32_t hash(int32_t key, uint32_t mod) {
uint32_t h = (uint32_t)key;
h ^= (h >> 20) ^ (h >> 12);
h ^= (h >> 7) ^ (h >> 4);
return h & (mod - 1);
}
static int insert(nghttp2_map_entry **table, uint32_t tablelen,
nghttp2_map_entry *entry) {
uint32_t h = hash(entry->key, tablelen);
if (table[h] == NULL) {
table[h] = entry;
} else {
nghttp2_map_entry *p;
/* We won't allow duplicated key, so check it out. */
for (p = table[h]; p; p = p->next) {
if (p->key == entry->key) {
return NGHTTP2_ERR_INVALID_ARGUMENT;
}
}
entry->next = table[h];
table[h] = entry;
}
return 0;
}
/* new_tablelen must be power of 2 */
static int resize(nghttp2_map *map, uint32_t new_tablelen) {
uint32_t i;
nghttp2_map_entry **new_table;
new_table =
nghttp2_mem_calloc(map->mem, new_tablelen, sizeof(nghttp2_map_entry *));
if (new_table == NULL) {
return NGHTTP2_ERR_NOMEM;
}
for (i = 0; i < map->tablelen; ++i) {
nghttp2_map_entry *entry;
for (entry = map->table[i]; entry;) {
nghttp2_map_entry *next = entry->next;
entry->next = NULL;
/* This function must succeed */
insert(new_table, new_tablelen, entry);
entry = next;
}
}
nghttp2_mem_free(map->mem, map->table);
map->tablelen = new_tablelen;
map->table = new_table;
return 0;
}
int nghttp2_map_insert(nghttp2_map *map, nghttp2_map_entry *new_entry) {
int rv;
/* Load factor is 0.75 */
if ((map->size + 1) * 4 > map->tablelen * 3) {
rv = resize(map, map->tablelen * 2);
if (rv != 0) {
return rv;
}
}
rv = insert(map->table, map->tablelen, new_entry);
if (rv != 0) {
return rv;
}
++map->size;
return 0;
}
nghttp2_map_entry *nghttp2_map_find(nghttp2_map *map, key_type key) {
uint32_t h;
nghttp2_map_entry *entry;
h = hash(key, map->tablelen);
for (entry = map->table[h]; entry; entry = entry->next) {
if (entry->key == key) {
return entry;
}
}
return NULL;
}
int nghttp2_map_remove(nghttp2_map *map, key_type key) {
uint32_t h;
nghttp2_map_entry **dst;
h = hash(key, map->tablelen);
for (dst = &map->table[h]; *dst; dst = &(*dst)->next) {
if ((*dst)->key != key) {
continue;
}
*dst = (*dst)->next;
--map->size;
return 0;
}
return NGHTTP2_ERR_INVALID_ARGUMENT;
}
size_t nghttp2_map_size(nghttp2_map *map) { return map->size; }
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <sys/fsys.h>
void main( int argc, char **argv ) {
int i;
for ( i = 1; i < argc; i++ ) {
char dev[_POSIX_NAME_MAX];
char mtpt[_POSIX_PATH_MAX];
if ( fsys_get_mount_dev( argv[i], dev ) == 0 &&
fsys_get_mount_pt( dev, mtpt ) == 0 ) {
printf( "%s\n", mtpt );
} else exit(1);
}
exit(0);
}
|
C
|
/*
* 2s_w07p01_laser.c
*
* Created: 2020-11-11 오전 9:11:05
* Author : Yunseo Hwang
*/
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
#include "adc.h"
#include "uart.h"
#define BV(n) (1 << n)
#define ON(n) PORTB |= BV(n);
#define OFF(n) PORTB &= ~BV(n);
#define LED_ON(n) {PORTB &= 0x01; ON(n);}
#define LED_OFF {PORTB &= 0x01;}
#define LASER 0
#define RED 1
#define GREEN 2
#define BLUE 3
void send_led(int color);
int main(void)
{
int cds = 0;
DDRB = 0xFF;
DDRA = 0x00;
PORTB = 0x00;
ADC_init();
uart_init(BAUDRATE(9600));
// 전원 인가 시 녹색 LED ON
LED_ON(GREEN);
send_led(GREEN);
_delay_ms(3000);
// LASER ON
ON(LASER);
LED_ON(BLUE);
send_led(BLUE);
_delay_ms(500);
while (1)
{
cds = ADC_read(0);
if (cds > 80) {
LED_ON(RED);
send_led(RED);
} else {
LED_ON(BLUE);
send_led(BLUE);
}
}
}
void send_led(int color)
{
uart_write(color);
}
|
C
|
#pragma once
/* dispatch()
*
* dispatch to the appropriate function based on the type of message
* (as determined by the first character in the pkt buffer).
*
* n = socket on which the message arrived
* pkt = packet buffer
*
*/
void dispatch(int n, char *pkt);
|
C
|
#include <stdbool.h>
#include <stdio.h>
#include <letmecreate/click/opto.h>
#include <letmecreate/core/common.h>
#include <letmecreate/core/gpio.h>
#include <letmecreate/core/gpio_monitor.h>
static const uint8_t channel_pins[MIKROBUS_COUNT][OPTO_CLICK_CHANNEL_COUNT] = {
{ MIKROBUS_1_INT, 0, MIKROBUS_1_RST, MIKROBUS_1_AN },
{ MIKROBUS_2_INT, 0, MIKROBUS_2_RST, MIKROBUS_2_AN }
};
static bool check_mikrobus_index(uint8_t mikrobus_index)
{
if (mikrobus_index != MIKROBUS_1 && mikrobus_index != MIKROBUS_2) {
fprintf(stderr, "opto: Invalid mikrobus index.\n");
return false;
}
return true;
}
static bool check_channel_index(uint8_t channel_index)
{
if (channel_index == OPTO_CLICK_CHANNEL_2) {
fprintf(stderr, "opto: Channel 2 is not supported on Ci40.\n");
return false;
}
if (channel_index >= OPTO_CLICK_CHANNEL_COUNT) {
fprintf(stderr, "opto: Invalid channel index.\n");
return false;
}
return true;
}
int opto_click_attach_callback(uint8_t mikrobus_index, uint8_t channel_index, void (*callback)(uint8_t))
{
uint8_t gpio_pin = 0;
if (check_mikrobus_index(mikrobus_index) == false
|| check_channel_index(channel_index) == false)
return -1;
if (callback == NULL) {
fprintf(stderr, "opto: Cannot attach null callback.\n");
return -1;
}
gpio_pin = channel_pins[mikrobus_index][channel_index];
if (gpio_init(gpio_pin) < 0
|| gpio_monitor_init() < 0
|| gpio_monitor_add_callback(gpio_pin, GPIO_EDGE, callback) < 0)
return -1;
return 0;
}
int LETMECREATE_CLICK_EXPORT opto_click_read_channel(uint8_t mikrobus_index, uint8_t channel_index, uint8_t *state)
{
uint8_t gpio_pin = 0;
if (check_mikrobus_index(mikrobus_index) == false
|| check_channel_index(channel_index) == false)
return -1;
if (state == NULL) {
fprintf(stderr, "opto: Cannot store state using null pointer.\n");
return -1;
}
gpio_pin = channel_pins[mikrobus_index][channel_index];
if (gpio_init(gpio_pin) < 0
|| gpio_get_value(gpio_pin, state) < 0)
return -1;
return 0;
}
|
C
|
/*
* Jonathan Sarba
* 13 de octubre de 2004
*
* El usuario debera tener seteas las sigueintes variables de entorno.
* ORACLE_HOME; ORACLE_SID
*
*/
#include <stdio.h>
#include <unistd.h>
#include <strings.h>
#include <stdlib.h>
#include <stdarg.h>
#include <sys/types.h>
#include <pwd.h>
#define MAX 512
extern char **environ;
#define CONNECT "connect internal\n"
#define STARTUP CONNECT"startup\nexit\n"
#define SHUTDOWN CONNECT"shutdown immediate\nexit\n"
#define SVRMGRL "/bin/svrmgrl"
gid_t getdbagrp(const char *db_owner)
{
struct passwd *dbainfo;
if ( (dbainfo = getpwnam(db_owner)) == NULL )
return -1;
else
return dbainfo->pw_gid;
}
char *svrmgrl()
{
char *path;
char *ret;
if ( (ret=(char *)calloc(MAX, sizeof(char))) == NULL )
exit(-2);
path = getenv("ORACLE_HOME");
if ( !path || (strlen(path)+strlen(SVRMGRL)) > MAX )
exit(-2);
memcpy(ret, path, strlen(path));
memcpy(ret+strlen(ret), SVRMGRL, strlen(SVRMGRL));
return ret;
}
int checksid(char *db)
{
char *sid;
sid = getenv("ORACLE_SID");
if ( !sid || strncmp(sid, db, strlen(db)) != 0 ) return 0;
else return 1;
}
int main(int argc, char **argv)
{
int fd[2];
int stop=0;
gid_t GrpId, OraId;
pid_t pid;
char *prg[2] = { NULL };
if ( argc < 4 )
{
printf("use: %s [database] [dba_owner] [stop|start]\n", argv[0]);
exit(0);
}
if ( strncmp(argv[3], "stop", 4) == 0 ) stop = 1;
GrpId = getegid();
if ( (OraId = getdbagrp(argv[2])) == -1 )
{
printf("User \"%s\" not found\n", argv[2]);
exit(-1);
}
if ( OraId != GrpId )
{
printf("File must be setgid for dba(%ld) group\n", OraId);
exit(-1);
}
if ( pipe(fd) == -1 )
{
printf("Pipe error\n");
exit(-2);
}
if ( checksid(argv[1]) == 0 )
{
printf("env ORACLE_SID != database\n");
exit(-2);
}
if ( (pid=fork()) == 0 )
{
dup2(fd[1], STDOUT_FILENO);
close(fd[0]);
close(fd[1]);
if ( stop == 1 )
fprintf(stdout, "%s", SHUTDOWN);
else
fprintf(stdout, "%s", STARTUP);
} else
{
dup2(fd[0], STDIN_FILENO);
close(fd[0]);
close(fd[1]);
setgid(OraId);
prg[0] = svrmgrl();
execve(prg[0], prg, environ);
}
exit(0);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.