added
stringdate
2024-11-18 17:54:19
2024-11-19 03:39:31
created
timestamp[s]date
1970-01-01 00:04:39
2023-09-06 04:41:57
id
stringlengths
40
40
metadata
dict
source
stringclasses
1 value
text
stringlengths
13
8.04M
score
float64
2
4.78
int_score
int64
2
5
2024-11-18T23:20:01.215161+00:00
2013-12-30T06:10:50
2d5c403693e9981e60feae49d779a448bcf76348
{ "blob_id": "2d5c403693e9981e60feae49d779a448bcf76348", "branch_name": "refs/heads/master", "committer_date": "2013-12-30T06:10:50", "content_id": "53f67c795335727a44a2c434037893dd0f566a46", "detected_licenses": [ "MIT" ], "directory_id": "1434ae4307bef7139443ed7082b46ef2c3e008c0", "extension": "c", "filename": "for_1.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 525, "license": "MIT", "license_type": "permissive", "path": "/experiments/for_1.c", "provenance": "stackv2-0135.json.gz:54099", "repo_name": "DeadDork/learning_c", "revision_date": "2013-12-30T06:10:50", "revision_id": "c62bf8c0fb2edf29117692c3910661ca7a696929", "snapshot_id": "260c6f8c0ee8c08dedbd1818b279bcfa8da32e67", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/DeadDork/learning_c/c62bf8c0fb2edf29117692c3910661ca7a696929/experiments/for_1.c", "visit_date": "2021-01-23T16:26:22.977478" }
stackv2
//////////////////////////////////////////////////////////////////////////////// // Comments // Experiments with a complex for loop. // Prints the number of 'on' bits. //////////////////////////////////////////////////////////////////////////////// // Libraries #include <stdio.h> //////////////////////////////////////////////////////////////////////////////// int main( void ) { int e; // Element unsigned x = 15; for( e = 1; x > 0; ( x &= x - 1 ) && ++e ); printf( "x has %d 'on' bits\n", e - 1 ); return 0; }
3.140625
3
2024-11-18T23:20:01.588116+00:00
2020-09-09T03:43:13
e166e123cebd03523cfb8d43816900246cdca91b
{ "blob_id": "e166e123cebd03523cfb8d43816900246cdca91b", "branch_name": "refs/heads/master", "committer_date": "2020-09-09T03:46:55", "content_id": "10f6a9c999583d530d5614bf9ea5e75edc1cec01", "detected_licenses": [ "MIT" ], "directory_id": "4d77155796610fdfd65b3ee35930502c7a82de5e", "extension": "c", "filename": "timer.c", "fork_events_count": 1, "gha_created_at": "2019-10-29T08:41:03", "gha_event_created_at": "2020-08-11T17:12:22", "gha_language": "C", "gha_license_id": null, "github_id": 218240895, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2114, "license": "MIT", "license_type": "permissive", "path": "/kernel/timer/timer.c", "provenance": "stackv2-0135.json.gz:54359", "repo_name": "sandwichdoge/catchOS", "revision_date": "2020-09-09T03:43:13", "revision_id": "f95d87f425a22d523257b0e4860a3b67b2967b2d", "snapshot_id": "65818fa48694865403c7228b2245d24fd3cd8409", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/sandwichdoge/catchOS/f95d87f425a22d523257b0e4860a3b67b2967b2d/kernel/timer/timer.c", "visit_date": "2023-04-08T01:17:05.043211" }
stackv2
#include "builddef.h" #include "cpu.h" // cpu_relax() #include "drivers/acpi/madt.h" #include "drivers/pit.h" #include "interrupt.h" #include "sem.h" #include "smp.h" #include "tasks.h" #include "utils/debug.h" static size_t _ticks; static size_t _freq; struct MADT_info* _madt_info = NULL; // 0x20 - Programmable Interval Timer. Used for bootstrapping (before scheduler init). private void ISR_SYSTIME_BOOTSTRAP(size_t* return_reg, struct cpu_state* unused) { _ticks++; } // Used for scheduler. This function calls scheduler. private void ISR_SYSTIME_SCHED(size_t* return_reg, struct cpu_state* unused) { _ticks++; static uint8_t cpuno = 0; ++cpuno; cpuno = cpuno % smp_get_cpu_count(); smp_redirect_external_irq(INT_SYSTIME, _madt_info->local_APIC_ids[cpuno]); task_isr_tick(); } public size_t getticks() { return _ticks; } public void delay_rt(size_t ms) { struct task_struct* curtask = task_get_current(); curtask->interruptible = 0; size_t ticks_to_wait = (ms * _freq) / 1000; size_t stop = _ticks + ticks_to_wait; while (_ticks < stop) { cpu_relax(); } curtask->interruptible = 1; } // After scheduler init public void delay(size_t ms) { size_t ticks_to_wait = (ms * _freq) / 1000; size_t stop = _ticks + ticks_to_wait; while (_ticks < stop) { task_yield(); } task_get_current()->sleep_avg += ticks_to_wait; } // Before scheduler init. public void delay_bootstrap(size_t ms) { size_t ticks_to_wait = (ms * _freq) / 1000; size_t stop = _ticks + ticks_to_wait; while (_ticks < stop) { asm("hlt"); } } // Init timer to be used to bootstrap time-sensitive hardware (e.g. SMP). public int32_t timer_init_bootstrap(size_t freq) { _freq = freq; pit_setfreq(freq); interrupt_register(INT_SYSTIME, ISR_SYSTIME_BOOTSTRAP); return 0; } // Init timer to be used for scheduler. public int32_t timer_init_sched(size_t freq) { _madt_info = madt_get_info(); _freq = freq; pit_setfreq(freq); interrupt_register(INT_SYSTIME, ISR_SYSTIME_SCHED); return 0; }
2.296875
2
2024-11-18T23:20:02.025393+00:00
2021-11-02T12:33:48
5c28aecb44d122e5e6afde5a94cd34a1eb8402cf
{ "blob_id": "5c28aecb44d122e5e6afde5a94cd34a1eb8402cf", "branch_name": "refs/heads/main", "committer_date": "2021-11-02T12:33:48", "content_id": "dad4ecfaf3501e0e13dbff6e8e669995bc4f5f5b", "detected_licenses": [ "MIT" ], "directory_id": "4500965ca98d5ded531c9d45b021a97054f31156", "extension": "c", "filename": "syscall.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2661, "license": "MIT", "license_type": "permissive", "path": "/Demo/Common/syscall.c", "provenance": "stackv2-0135.json.gz:55013", "repo_name": "wlshiu/FreeRTOS-BTF-Trace", "revision_date": "2021-11-02T12:33:48", "revision_id": "ad256d3bca11f959732d692e50606602f98faad5", "snapshot_id": "176f89318bb8b80bae970910170b3ca6d344b425", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/wlshiu/FreeRTOS-BTF-Trace/ad256d3bca11f959732d692e50606602f98faad5/Demo/Common/syscall.c", "visit_date": "2023-08-25T23:29:57.485642" }
stackv2
#include <stdio.h> #include <machine/syscall.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/unistd.h> #include <errno.h> #include "printf.h" #define HAVE_SYSCALL 0 #define MEMIO_PUTC 0x9000001c #define MEMIO_EXIT 0x9000002c // system call defined in the file /usr/include/asm-generic/unistd.h enum { SYS_CLOSE = 0x39, SYS_WRITE = 0x40, SYS_FSTAT = 0x50, SYS_EXIT = 0x5d, SYS_SBRK = 0xd6 }; extern int errno; static inline long __internal_syscall(long n, long _a0, long _a1, long _a2, long _a3, long _a4, long _a5) { register long a0 asm("a0") = _a0; register long a1 asm("a1") = _a1; register long a2 asm("a2") = _a2; register long a3 asm("a3") = _a3; register long a4 asm("a4") = _a4; register long a5 asm("a5") = _a5; #ifdef __riscv_32e register long syscall_id asm("t0") = n; #else register long syscall_id asm("a7") = n; #endif asm volatile ("ecall" : "+r"(a0) : "r"(a1), "r"(a2), "r"(a3), "r"(a4), "r"(a5), "r"(syscall_id)); return a0; } void _putchar(char ch) { *(volatile char*)MEMIO_PUTC = (char)ch; } /* Write to a file. */ ssize_t _write(int file, const void *ptr, size_t len) { #if HAVE_SYSCALL __internal_syscall(SYS_WRITE, (long)file, (long)ptr, (long)len, 0, 0, 0); return len; #else const char *buf = (char*)ptr; int i; for(i=0; i<len; i++) _putchar(buf[i]); return len; #endif } int _fstat(int file, struct stat *st) { //errno = ENOENT; return -1; } int _close(int file) { //errno = ENOENT; return -1; } int _lseek(int file, int ptr, int dir) { //errno = ENOENT; return -1; } int _read(int file, char *ptr, int len) { //errno = ENOENT; return -1; } void _exit(int code) { #if HAVE_SYSCALL __internal_syscall(SYS_EXIT, code, 0, 0, 0, 0, 0); #else *(volatile char*)MEMIO_EXIT = code; #endif while(1); } void exit(int code) { _exit(code); } int _isatty(int file) { return (file == STDIN_FILENO || file == STDERR_FILENO || file == STDOUT_FILENO) ? 1 : 0; } extern char _end[]; /* _end is set in the linker command file */ extern char _stack[]; /* _stack is set in the linker command file */ char *heap_ptr; char * _sbrk (int nbytes) { char *base; if (!heap_ptr) heap_ptr = (char *)&_end; if ((int)(heap_ptr+nbytes) >= (int)&_stack) { return 0; } else { base = heap_ptr; heap_ptr += nbytes; } return base; } int _kill(int pid, int sig) { return -1; } int _getpid(void) { return 0; }
2.5
2
2024-11-18T23:20:02.537368+00:00
2019-11-11T02:01:31
ff016b401989a785a65741479758a392a0eab88d
{ "blob_id": "ff016b401989a785a65741479758a392a0eab88d", "branch_name": "refs/heads/master", "committer_date": "2019-11-11T02:01:31", "content_id": "c28c8a8db0595224722738741a7810ee6996ccd6", "detected_licenses": [ "MIT" ], "directory_id": "6ea2a02dbeb2b494ca7cd602c8914bb5137c69a2", "extension": "h", "filename": "instructions.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1181, "license": "MIT", "license_type": "permissive", "path": "/src/instructions.h", "provenance": "stackv2-0135.json.gz:55401", "repo_name": "MunebAli132/asm85", "revision_date": "2019-11-11T02:01:31", "revision_id": "c98cc8cbe2548b5ed85e64f04f5af1ed7bb7bfdb", "snapshot_id": "15598bcd8134b18643cd3e14be0c1422a89c7036", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/MunebAli132/asm85/c98cc8cbe2548b5ed85e64f04f5af1ed7bb7bfdb/src/instructions.h", "visit_date": "2022-05-23T04:10:08.461892" }
stackv2
// Instruction set for the 8085 processor. // // Copyright (c) 2016 Tom Nisbet // Licensed under the MIT license // #ifndef INSTRUCTIONS_H #define INSTRUCTIONS_H #include <stddef.h> // The use of reg1, reg2, and argType isn't completely obvious. Each instruction // can have register args and/or an additional arg. The additional arg is a // value, specified using either a literal or a label. If present, the // additional arg always comes last and can be a byte or a word. // Examples: // nop ; no args // pop h ; one register // mov a, m ; two registers // jmp AWAY ; one WORD arg // lxi h, SAVE ; one register, one WORD arg // mvi c, 23 ; one register, one BYTE arg enum { EX_NONE = 0, EX_BYTE = 1, EX_WORD = 2 }; typedef struct { const char * mnemonic; // Mnemonic name const char * reg1; // Register argument 1 name const char * reg2; // Register argument 2 name int nRegs; // Number of register args int opcode; // Opcode int argType; // Expression arg type } InstructionEntry; #endif
2.359375
2
2024-11-18T23:20:02.860603+00:00
2020-07-22T18:48:23
90f1bfbc27fa2724553f29c9addd0ef1d87d16ad
{ "blob_id": "90f1bfbc27fa2724553f29c9addd0ef1d87d16ad", "branch_name": "refs/heads/master", "committer_date": "2020-07-22T18:48:23", "content_id": "b46512f9e95b3f058f37a3c931dac057c248199b", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "33980834e76a25c5537dff533dc6669fd37fd1a0", "extension": "c", "filename": "scroll.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 10744019, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4567, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/pixel-story/code/scroll.c", "provenance": "stackv2-0135.json.gz:55529", "repo_name": "FreeCX/experimental", "revision_date": "2020-07-22T18:48:23", "revision_id": "40335d2aaa5515932d9858b407be5ade37f19e79", "snapshot_id": "2eb37cb374ade82ec292c7b4eceffaa1853aedf1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/FreeCX/experimental/40335d2aaa5515932d9858b407be5ade37f19e79/pixel-story/code/scroll.c", "visit_date": "2021-01-17T13:03:24.723638" }
stackv2
#include "graphic.h" #include <SDL2/SDL.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #define SCREEN_WIDTH 320 #define SCREEN_HEIGHT 240 typedef struct { int x, y; } l_map; typedef struct { int keycode; int add_x; int add_y; int counter; int stop; int down; } scroll_t; enum { KEY_NONE = 0, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, }; SDL_Window *window; SDL_Renderer *render; SDL_Event event; anim_file_t *a; layer_t l; l_map *map = NULL; int quit_flag = 0; int dx = 0, dy = 0; int game_keycode = KEY_NONE, game_move = 0, game_down = 0, game_lock = 0; scroll_t scr = {KEY_NONE, +1, +1, 0, 1, 0}; void send_error(int code) { printf("%s", SDL_GetError()); exit(code); } void game_init(void) { int i; srand(time(NULL)); window = SDL_CreateWindow("Pixel Story", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (window == NULL) { send_error(EXIT_FAILURE); } render = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (render == NULL) { send_error(EXIT_FAILURE); } ani_init(render, "../config/img_monitor.txt", &a); map = (l_map *)calloc(a->anim_count, sizeof(l_map)); for (i = 0; i < a->anim_count; i++) { map[i].x = ((rand() % 180 / 10) + 1) * 16; map[i].y = ((rand() % 130 / 10) + 1) * 16; printf("%d = [%d, %d]\n", i, map[i].x, map[i].y); } l.tex = IMG_LoadTexture(render, "../game_art/tileset.gif"); for (i = 0; i < 100; i++) { l.map[rand() % 20][rand() % 15] = 21; } } void game_kscroll(int key) { if (scr.stop && !scr.counter) { scr.keycode = key; scr.add_x = +1; scr.add_y = +1; scr.counter = 16; scr.stop = 0; } } void game_scroll(void) { static int counter = 0; if (scr.counter && !scr.stop) { switch (scr.keycode) { case KEY_UP: dy += scr.add_y; break; case KEY_DOWN: dy -= scr.add_y; break; case KEY_LEFT: dx += scr.add_x; break; case KEY_RIGHT: dx -= scr.add_x; break; } scr.counter--; counter++; } else if (!scr.counter && !scr.stop && !scr.down) { scr.counter = 16; switch (scr.keycode) { case KEY_UP: case KEY_DOWN: scr.add_y = -scr.add_y; break; case KEY_LEFT: case KEY_RIGHT: scr.add_x = -scr.add_x; break; } } if (counter > 31) { scr.keycode = KEY_NONE; scr.stop = 1; counter = 0; } } void game_event(SDL_Event *event) { SDL_PollEvent(event); switch (event->type) { case SDL_QUIT: quit_flag = 1; break; case SDL_KEYDOWN: switch (event->key.keysym.sym) { case SDLK_w: game_kscroll(KEY_UP); break; case SDLK_s: game_kscroll(KEY_DOWN); break; case SDLK_a: game_kscroll(KEY_LEFT); break; case SDLK_d: game_kscroll(KEY_RIGHT); break; } scr.down = 1; break; case SDL_KEYUP: scr.down = 0; break; } } void game_loop(void) { game_scroll(); } void game_render(void) { int i, j, xp, yp; xp = (dx % 32); yp = (dy % 32); SDL_RenderClear(render); for (i = 0; i < 20; i++) { for (j = 0; j < 15; j++) { tile_draw(render, l.tex, l.map[i][j], i * 16 + (dx * 2), j * 16 + (dy * 2)); } } // wtf? // for ( i = 0; i < a->anim_count * a->frm_size; i += a->frm_size ) { // ani_draw( render, a, i / a->frm_size, map[i/16].x + ( dx * 2 ), map[i/16].y + ( dy * 2 ) ); // } SDL_RenderPresent(render); } void game_destroy(void) { free(map); ani_destroy(a); SDL_DestroyTexture(l.tex); SDL_DestroyRenderer(render); SDL_DestroyWindow(window); SDL_Quit(); } int main(int argc, char *argv[]) { game_init(); while (!quit_flag) { game_event(&event); game_loop(); game_render(); } game_destroy(); return EXIT_SUCCESS; }
2.203125
2
2024-11-18T23:20:02.922789+00:00
2020-07-05T19:49:03
6445d93c9a1f7085ecb54139797d4f9af3c25310
{ "blob_id": "6445d93c9a1f7085ecb54139797d4f9af3c25310", "branch_name": "refs/heads/master", "committer_date": "2020-07-05T19:49:03", "content_id": "a8c32e3f7fadf93c2ce93805d56c7762c36cec68", "detected_licenses": [ "MIT" ], "directory_id": "6ab5573d7ae06810707bdc63e1a4bd34d2621c3f", "extension": "c", "filename": "terminal.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 6240097, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 16360, "license": "MIT", "license_type": "permissive", "path": "/CAN_NODE_3/terminal.c", "provenance": "stackv2-0135.json.gz:55657", "repo_name": "ayushsinha67/CanNode3", "revision_date": "2020-07-05T19:49:03", "revision_id": "b446cc3b85d83dcb00c68e6d839412245549e4b8", "snapshot_id": "cb81930dbbdfbd275f4ce4fc6fa4394b56b7e3ea", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ayushsinha67/CanNode3/b446cc3b85d83dcb00c68e6d839412245549e4b8/CAN_NODE_3/terminal.c", "visit_date": "2022-11-14T19:25:50.693843" }
stackv2
#include <avr/io.h> #include <avr/pgmspace.h> #include <util/atomic.h> #include "terminal.h" #include "uart.h" #include "uart_buffer.h" #include "mcp2515reg.h" #include "mcp2515.h" /************************************************************************ * GLOBAL VARIABLES */ volatile TERM_STATE state = TERM_DISABLE; volatile CFG_STATE cfg = CFG_NORMAL; volatile MSGSTRM_STATE strm = MS_DISABLE; extern volatile UartBuffer UART_RxBuffer; /************************************************************************ * START SCREEN */ void term_Start( CanStatus res ) { UART_TxStr_p( PSTR("\nCAN NodeView v1.0 (c) Ayush Sinha\n") ); if( res == CAN_OK ) UART_TxStr_p( PSTR("\nCAN Initialized\n") ); else UART_TxStr_p( PSTR("\nCAN Initialization Failed\n") ); term_Commands(); /* Show commands */ } /************************************************************************ * GET STATE */ TERM_STATE term_GetState ( uint8_t s ) { switch(s) { case 'i': return TERM_CANINIT; break; case 'c': return TERM_CTRLREG; break; case 'x': return TERM_RXSTAT; break; case 's': return TERM_READSTAT; break; case 'f': return TERM_INTFLAG; break; case 'e': return TERM_ERRFLAG; break; case 't': return TERM_TXBUF; break; case 'r': return TERM_RXBUF; break; case 'k': return TERM_MASK; break; case 'g': return TERM_FILT; break; case 'm': return TERM_MSGSTREAM;break; case 'l': return TERM_LOOPBACK; break; case 'h': return TERM_HELP; break; default : return TERM_DISABLE; break; } } /************************************************************************ * MAIN FUNCTION ROUTINE */ void term_Main( void ) { if( UART_BufState( &UART_RxBuffer ) != UART_BUFFER_EMPTY ) state = UART_BufDeq( &UART_RxBuffer ); /* Dequeue */ switch( term_GetState(state) ) { /* terminal function call */ case TERM_CANINIT : term_Start( CAN_Init(CAN_SPEED) ); break; case TERM_CTRLREG : term_CtrlReg(); break; case TERM_RXSTAT : term_RxStatus(); break; case TERM_READSTAT : term_ReadStatus(); break; case TERM_INTFLAG : term_IntFlag(); break; case TERM_ERRFLAG : term_ErrorFlag(); break; case TERM_TXBUF : term_TxBuffer(); break; case TERM_RXBUF : term_RxBuffer(); break; case TERM_MASK : term_Mask(); break; case TERM_FILT : term_Filt(); break; case TERM_MSGSTREAM : if( strm == MS_DISABLE ){ /* Enable/Disable Streaming of Received Data */ strm = MS_STREAM; UART_TxStr_p( PSTR("STREAM\n") ); } else{ strm = MS_DISABLE; } break; case TERM_LOOPBACK : if( cfg == CFG_NORMAL ){ /* Change to Loop-back Mode */ mcp2515_SetMode( MODE_LOOPBACK ); cfg = CFG_LOOPBACK; UART_TxStr_p( PSTR("LOOPBACK MODE\n") ); } else { mcp2515_SetMode( MODE_NORMAL ); cfg = CFG_NORMAL; UART_TxStr_p( PSTR("NORMAL MODE\n") ); } break; case TERM_HELP : term_Commands(); break; default : break; } state = TERM_DISABLE; /* Disable multiple print */ } /************************************************************************ * DISPLAY COMMAND REGISTERS */ void term_Commands (void) { UART_TxStr_p( PSTR("\nCOMMANDS \n") ); UART_TxStr_p( PSTR("i : \tCAN Initialize\n") ); UART_TxStr_p( PSTR("c : \tControl Registers\n") ); UART_TxStr_p( PSTR("x : \tRX Status\n") ); UART_TxStr_p( PSTR("s : \tRead Status\n") ); UART_TxStr_p( PSTR("f : \tInterrupt Flags\n") ); UART_TxStr_p( PSTR("e : \tError Flags\n") ); UART_TxStr_p( PSTR("t : \tTransmit Buffer\n") ); UART_TxStr_p( PSTR("r : \tReceive Buffer\n") ); UART_TxStr_p( PSTR("k : \tMasks\n") ); UART_TxStr_p( PSTR("g : \tFilters\n") ); UART_TxStr_p( PSTR("m : \tMessage Stream\n") ); UART_TxStr_p( PSTR("l : \tLoopback\n") ); UART_TxStr_p( PSTR("h : \tHelp\n") ); } /************************************************************************ * DISPLAY CONTROL REGISTERS */ void term_CtrlReg(void) { uint8_t stat = mcp2515_Read(CANSTAT); /* Read Status */ UART_TxStr_p( PSTR("\nCONTROL REGISTERS -----------------------------------\n\n") ); UART_TxStr_p( PSTR("MODE:\t\t") ); UART_TxHex( stat >> 5 ); switch( stat >> 5 ){ case 0: UART_TxStr_p( PSTR(" - NORMAL") ); break; case 1: UART_TxStr_p( PSTR(" - SLEEP") ); break; case 2: UART_TxStr_p( PSTR(" - LOOPBACK") ); break; case 3: UART_TxStr_p( PSTR(" - LISTEN-ONLY") ); break; case 4: UART_TxStr_p( PSTR(" - CONFIG") ); break; default: UART_TxStr_p( PSTR(" - NORMAL") ); break; }; UART_TxChar('\n'); UART_TxStr_p( PSTR("ICOD:\t\t") ); UART_TxHex( ( mcp2515_Read( CANSTAT ) >> 1 ) & 0x07 ); UART_TxChar('\n'); UART_TxStr_p( PSTR("CANCTRL:\t") ); UART_TxHex( mcp2515_Read( CANCTRL) ); UART_TxChar('\n'); UART_TxStr_p( PSTR("CANSTAT:\t") ); UART_TxHex( mcp2515_Read( CANSTAT) ); UART_TxChar('\n'); UART_TxStr_p( PSTR("CNF1:\t\t") ); UART_TxHex( mcp2515_Read( CNF1) ); UART_TxChar('\n'); UART_TxStr_p( PSTR("CNF2:\t\t") ); UART_TxHex( mcp2515_Read( CNF2) ); UART_TxChar('\n'); UART_TxStr_p( PSTR("CNF3:\t\t") ); UART_TxHex( mcp2515_Read( CNF3) ); UART_TxChar('\n'); UART_TxStr_p( PSTR("BFPCTRL:\t") ); UART_TxHex( mcp2515_Read( BFPCTRL) ); UART_TxChar('\n'); UART_TxStr_p( PSTR("TXRTSCTRL:\t") ); UART_TxHex( mcp2515_Read( TXRTSCTRL ) ); UART_TxChar('\n'); UART_TxStr_p( PSTR("CANINTE:\t") ); UART_TxHex( mcp2515_Read( CANINTE ) ); UART_TxChar('\n'); UART_TxStr_p( PSTR("CANINTF:\t") ); UART_TxHex( mcp2515_Read( CANINTF ) ); UART_TxChar('\n'); UART_TxStr_p( PSTR("EFLG:\t\t") ); UART_TxHex( mcp2515_Read( EFLG ) ); UART_TxChar('\n'); UART_TxStr_p( PSTR("TXB0CTRL:\t") ); UART_TxHex( mcp2515_Read( TXB0CTRL ) ); UART_TxChar('\n'); UART_TxStr_p( PSTR("TXB1CTRL:\t") ); UART_TxHex( mcp2515_Read( TXB1CTRL ) ); UART_TxChar('\n'); UART_TxStr_p( PSTR("TXB2CTRL:\t") ); UART_TxHex( mcp2515_Read( TXB2CTRL ) ); UART_TxChar('\n'); UART_TxStr_p( PSTR("RXB0CTRL:\t") ); UART_TxHex( mcp2515_Read( RXB0CTRL ) ); UART_TxChar('\n'); UART_TxStr_p( PSTR("RXB1CTRL:\t") ); UART_TxHex( mcp2515_Read( RXB1CTRL ) ); UART_TxChar('\n'); UART_TxChar('\n'); } /************************************************************************ * DISPLAY READ STATUS */ void term_ReadStatus(void) { uint8_t data = mcp2515_ReadStatus(); UART_TxStr_p ( PSTR("\nREAD STATUS -----------------------------------\n\n") ); UART_TxStr_p( PSTR("Register:\t") ); UART_TxHex( data ); UART_TxChar('\n'); UART_TxStr_p( PSTR("Status:\n") ); if( (data & 0x01) == 0x01 ){ UART_TxStr_p( PSTR("\t\tCANINTF.RX0IF\n") ); } if( (data & 0x02) == 0x02 ){ UART_TxStr_p( PSTR("\t\tCANINTF.RX1IF\n") ); } if( (data & 0x04) == 0x04 ){ UART_TxStr_p( PSTR("\t\tTXB0CNTRL.TXREQ\n") ); } if( (data & 0x08) == 0x08 ){ UART_TxStr_p( PSTR("\t\tCANINTF.TX0IF\n") ); } if( (data & 0x10) == 0x10 ){ UART_TxStr_p( PSTR("\t\tTXB1CNTRL.TXREQ\n") ); } if( (data & 0x20) == 0x20 ){ UART_TxStr_p( PSTR("\t\tCANINTF.TX1IF\n") ); } if( (data & 0x40) == 0x40 ){ UART_TxStr_p( PSTR("\t\tTXB2CNTRL.TXREQ\t\n") ); } if( (data & 0x80) == 0x80 ){ UART_TxStr_p( PSTR("\t\tCANINTF.TX2IF\n") ); } } /************************************************************************ * DISPLAY RECEIVE STATUS */ void term_RxStatus(void) { uint8_t data = mcp2515_RXStatus(); UART_TxStr_p ( PSTR("\nRECEIVE STATUS -----------------------------------\n\n") ); UART_TxStr_p( PSTR("Register:\t")); UART_TxHex( data ); UART_TxChar('\n'); UART_TxStr_p( PSTR("RX Message:\t") ); switch( ( data & 0xC0 ) >> 6 ){ /* Check Message Received */ case 0: UART_TxStr_p( PSTR("NO MSG\n") ); break; case 1: UART_TxStr_p( PSTR("RXB0\n") ); break; case 2: UART_TxStr_p( PSTR("RXB1\n") ); break; case 3: UART_TxStr_p( PSTR("BOTH BUFFERS\n") ); break; } UART_TxStr_p( PSTR("Msg Type:\t") ); switch( ( data & 0x18 ) >> 3 ){ /* TYPE of Message Received */ case 0: UART_TxStr_p( PSTR("Standard, DATA\n") ); break; case 1: UART_TxStr_p( PSTR("Standard, REMOTE") ); break; case 2: UART_TxStr_p( PSTR("Extended, DATA\n") ); break; case 3: UART_TxStr_p( PSTR("Extended, REMOTE\n") ); break; } UART_TxStr_p( PSTR("Filter Match:\t") ); switch( data & 0x07 ){ /* Filter Match */ case 0: UART_TxStr_p( PSTR("RXF0\n") ); break; case 1: UART_TxStr_p( PSTR("RXF1\n") ); break; case 2: UART_TxStr_p( PSTR("RXF2\n") ); break; case 3: UART_TxStr_p( PSTR("RXF3\n") ); break; case 4: UART_TxStr_p( PSTR("RXF4\n") ); break; case 5: UART_TxStr_p( PSTR("RXF5\n") ); break; case 6: UART_TxStr_p( PSTR("RXF0 Rollover to RXB1\n") ); break; case 7: UART_TxStr_p( PSTR("RXF1 Rollover to RXB1\n") ); break; } } /************************************************************************ * DISPLAY INTERRUPT FLAGS */ void term_IntFlag(void) { uint8_t data = mcp2515_Read( CANINTF ); UART_TxStr_p ( PSTR("\nINTERRUPT FLAGS -----------------------------------\n\n") ); UART_TxStr_p( PSTR("CANINTF:\t") ); UART_TxHex( data ); UART_TxChar('\n'); UART_TxStr_p( PSTR("Status:\n") ); if( (data & 0x01) == 0x01 ){ UART_TxStr_p( PSTR("\t\tReceive Buffer 0 Full\n") ); } if( (data & 0x02) == 0x02 ){ UART_TxStr_p( PSTR("\t\tReceive Buffer 1 Full\n") ); } if( (data & 0x04) == 0x04 ){ UART_TxStr_p( PSTR("\t\tTransmit Buffer 0 Empty\n") ); } if( (data & 0x08) == 0x08 ){ UART_TxStr_p( PSTR("\t\tTransmit Buffer 1 Empty\n") ); } if( (data & 0x10) == 0x10 ){ UART_TxStr_p( PSTR("\t\tTransmit Buffer 2 Empty\n") ); } if( (data & 0x20) == 0x20 ){ UART_TxStr_p( PSTR("\t\tError\n") ); } if( (data & 0x40) == 0x40 ){ UART_TxStr_p( PSTR("\t\tWakeup\t\n") ); } if( (data & 0x80) == 0x80 ){ UART_TxStr_p( PSTR("\t\tMessage Error\n") ); } } /************************************************************************ * DISPLAY ERROR FLAGS */ void term_ErrorFlag(void) { uint8_t data = mcp2515_Read( EFLG ); UART_TxStr_p( PSTR("\nERROR FLAGS -----------------------------------\n\n") ); UART_TxStr_p( PSTR("EFLG:\t\t") ); UART_TxHex( data ); UART_TxChar('\n'); UART_TxStr_p( PSTR("TEC:\t\t") ); UART_TxHex( mcp2515_Read(TEC) ); UART_TxChar('\n'); UART_TxStr_p( PSTR("REC:\t\t") ); UART_TxHex( mcp2515_Read(REC) ); UART_TxChar('\n'); UART_TxStr_p( PSTR("Status:\n") ); if( (data & 0x01) == 0x01 ){ UART_TxStr_p( PSTR("\t\tTEC or REC >= 96\n") ); } if( (data & 0x02) == 0x02 ){ UART_TxStr_p( PSTR("\t\tREC >= 96\n") ); } if( (data & 0x04) == 0x04 ){ UART_TxStr_p( PSTR("\t\tTEC >= 96\n") ); } if( (data & 0x08) == 0x08 ){ UART_TxStr_p( PSTR("\t\tError Passive - REC >= 128") ); } if( (data & 0x10) == 0x10 ){ UART_TxStr_p( PSTR("\t\tError Passive - TEC >= 128\n") ); } if( (data & 0x20) == 0x20 ){ UART_TxStr_p( PSTR("\t\tBus Off - TEC = 255\n") ); } if( (data & 0x40) == 0x40 ){ UART_TxStr_p( PSTR("\t\tRx0 Overflow\n") ); } if( (data & 0x80) == 0x80 ){ UART_TxStr_p( PSTR("\t\tRx1 Overflow\n") ); } } /************************************************************************ * DISPLAY TRANSMIT BUFFER */ void term_TxBuffer(void) { uint8_t data[13]; UART_TxStr_p( PSTR("\n\nTRANSMIT BUFFER -----------------------------------\n\n") ); UART_TxStr_p( PSTR("\tSID\tEXIDE\tDLC\tCAN Data\n\n")); /* TXB0 */ UART_TxStr_p( PSTR("TXB0:\t") ); mcp2515_ReadRegs( TXB0SIDH, data, 13 ); term_BufTab( TXB0SIDH, data ); /* TXB1 */ UART_TxStr_p( PSTR("TXB1:\t") ); mcp2515_ReadRegs( TXB1SIDH, data, 13 ); term_BufTab( TXB1SIDH, data ); /* TXB2 */ UART_TxStr_p( PSTR("TXB2:\t") ); mcp2515_ReadRegs( TXB2SIDH, data, 13 ); term_BufTab( TXB2SIDH, data ); } /************************************************************************ * DISPLAY RECEIVE BUFFER */ void term_RxBuffer (void) { uint8_t data[13]; UART_TxStr_p( PSTR("\n\nRECEIVE BUFFER -----------------------------------\n\n") ); UART_TxStr_p( PSTR("\tSID\tEXIDE\tDLC\tCAN Data\n\n")); /* RXB0 */ UART_TxStr_p( PSTR("RXB0:\t") ); mcp2515_ReadRegs( RXB0SIDH, data, 13 ); term_BufTab( RXB0SIDH, data ); /* RXB1 */ UART_TxStr_p( PSTR("RXB1:\t") ); mcp2515_ReadRegs( RXB1SIDH, data, 13 ); term_BufTab( RXB1SIDH, data ); } /************************************************************************ * DISPLAY MASKS */ void term_Mask (void) { mcp2515_SetMode( MODE_CONFIG ); /* Only accessible in this mode */ uint8_t data[4]; UART_TxStr_p( PSTR("\n\nMASKS -----------------------------------\n\n") ); UART_TxStr_p( PSTR("\tSID\tEXIDE\n\n")); /* RXM0 */ UART_TxStr_p( PSTR("RXM0:\t") ); mcp2515_ReadRegs( RXM0SIDH, data, 4 ); term_BufTab( RXM0SIDH, data ); /* RXM1 */ UART_TxStr_p( PSTR("\nRXM1:\t") ); mcp2515_ReadRegs( RXM1SIDH, data, 4 ); term_BufTab( RXM1SIDH, data ); mcp2515_SetMode( MODE_NORMAL ); /* Reset to Normal Mode */ } /************************************************************************ * DISPLAY FILTERS */ void term_Filt (void) { mcp2515_SetMode( MODE_CONFIG ); /* Only accessible in this mode */ uint8_t data[4]; UART_TxStr_p( PSTR("\n\nFILTERS -----------------------------------\n\n") ); UART_TxStr_p( PSTR("\tSID\tEXIDE\n\n")); /* FILT0 */ UART_TxStr_p( PSTR("FILT0:\t") ); mcp2515_ReadRegs( RXF0SIDH, data, 4 ); term_BufTab( RXF0SIDH, data ); /* FILT1 */ UART_TxStr_p( PSTR("\nFILT1:\t") ); mcp2515_ReadRegs( RXF1SIDH, data, 4 ); term_BufTab( RXF1SIDH, data ); /* FILT2 */ UART_TxStr_p( PSTR("\nFILT2:\t") ); mcp2515_ReadRegs( RXF2SIDH, data, 4 ); term_BufTab( RXF2SIDH, data ); /* FILT3 */ UART_TxStr_p( PSTR("\nFILT3:\t") ); mcp2515_ReadRegs( RXF3SIDH, data, 4 ); term_BufTab( RXF3SIDH, data ); /* FILT4 */ UART_TxStr_p( PSTR("\nFILT4:\t") ); mcp2515_ReadRegs( RXF4SIDH, data, 4 ); term_BufTab( RXF4SIDH, data ); /* FILT5 */ UART_TxStr_p( PSTR("\nFILT5:\t") ); mcp2515_ReadRegs( RXF5SIDH, data, 4 ); term_BufTab( RXF5SIDH, data ); mcp2515_SetMode( MODE_NORMAL ); /* Reset to Normal Mode */ } /************************************************************************ * TABULATE BUFFER DATA */ void term_BufTab( uint8_t addr, uint8_t *data) { if( ( data[1] & TXB_EXIDE) == TXB_EXIDE ){ /* EID */ UART_TxHex( data[0] >> 3 ); UART_TxHex( ( (data[0] & 0x07) << 5 ) | (data[1] & 0x03 ) | ( (data[1] & 0xE0) >>3 ) ); UART_TxChar('\t'); UART_TxHex( data[2] ); /* EID8 */ UART_TxHex( data[3] ); UART_TxChar('\t'); /* EID0 */ } else{ UART_TxHex( data[0] >> 5 ); /* SID */ UART_TxHex( (data[0] << 3) | ( data[1] >> 5) ); UART_TxChar('\t'); UART_TxChar('\t'); } uint8_t p; switch( addr ){ /* Check Address */ case TXB0SIDH : case TXB1SIDH : case TXB2SIDH : case RXB0SIDH : case RXB1SIDH : p = 1; break; default : p = 0; break; } if( p == 1 ){ /* Only for Rx/Tx Buffers */ UART_TxHex( data[4] ); UART_TxChar('\t'); /* DLC */ for( uint8_t i = 5; (i < (5 + data[4])) && (i < 13); i++ ){ /* Data */ UART_TxHex(data[i]); UART_TxChar(' '); } UART_TxChar('\n'); } } /************************************************************************ * DISPLAY RECEIVED MESSAGE */ void term_RxMsg (CanMessage *msg) { UART_TxStr_p( PSTR("Rcvd:\t") ); if( msg->ext == 0 ){ UART_TxHex( (uint8_t) ( msg->id >> 8 ) ); UART_TxHex( (uint8_t) ( msg->id ) ); UART_TxChar('\t'); UART_TxHex( (uint8_t) ( msg->id >> 24 ) ); UART_TxHex( (uint8_t) ( msg->id >> 16 ) ); UART_TxChar('\t'); } else{ UART_TxHex( (uint8_t) ( msg->id >> 24 ) ); UART_TxHex( (uint8_t) ( msg->id >> 16 ) ); UART_TxChar('\t'); UART_TxHex( (uint8_t) ( msg->id >> 8 ) ); UART_TxHex( (uint8_t) ( msg->id ) ); UART_TxChar('\t'); } UART_TxHex( msg->dlc ); UART_TxChar('\t'); for( uint8_t i = 0; i < msg->dlc; i++ ){ UART_TxHex( msg->data[i] ); UART_TxChar(' '); } UART_TxChar('\n'); } /************************************************************************ * RECEIVE INTERRUPT */ ISR( USART_RXC_vect ) { uint8_t data = UDR; if( UART_BufState( &UART_RxBuffer) != UART_BUFFER_FULL ) UART_BufEnq( &UART_RxBuffer, data ); /* Enqueue incoming commands to buffer */ }
2.546875
3
2024-11-18T23:20:05.536510+00:00
2023-06-07T10:33:45
3fabc2bb7520a5cfddf9821fc3459fbfdd79c137
{ "blob_id": "3fabc2bb7520a5cfddf9821fc3459fbfdd79c137", "branch_name": "refs/heads/master", "committer_date": "2023-06-07T10:33:45", "content_id": "c447947aceb6b1c2742ef0b71c5fdb0d1b40e486", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "079c89592623761bca570711de440179e2b1f5a0", "extension": "c", "filename": "ruuvi_task_sensor.c", "fork_events_count": 18, "gha_created_at": "2018-02-20T12:43:20", "gha_event_created_at": "2023-06-07T10:33:47", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 122196869, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6266, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/tasks/ruuvi_task_sensor.c", "provenance": "stackv2-0135.json.gz:55919", "repo_name": "ruuvi/ruuvi.drivers.c", "revision_date": "2023-06-07T10:33:45", "revision_id": "c84cf1c735cd4ae3491602a6a731b9c963f178f8", "snapshot_id": "13a5b495183a8750b70e1ea6cd9d2b3f0c39fa33", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/ruuvi/ruuvi.drivers.c/c84cf1c735cd4ae3491602a6a731b9c963f178f8/src/tasks/ruuvi_task_sensor.c", "visit_date": "2023-06-23T23:34:33.555838" }
stackv2
#include "ruuvi_driver_enabled_modules.h" #if RT_SENSOR_ENABLED #include "ruuvi_driver_error.h" #include "ruuvi_driver_sensor.h" #include "ruuvi_interface_log.h" #include "ruuvi_task_flash.h" #include "ruuvi_task_sensor.h" #include <string.h> #ifndef TASK_SENSOR_LOG_LEVEL #define TASK_SENSOR_LOG_LEVEL RI_LOG_LEVEL_DEBUG #endif static inline void LOG (const char * const msg) { ri_log (TASK_SENSOR_LOG_LEVEL, msg); } static inline void LOGD (const char * const msg) { ri_log (RI_LOG_LEVEL_DEBUG, msg); } static inline void LOGHEX (const uint8_t * const msg, const size_t len) { ri_log_hex (TASK_SENSOR_LOG_LEVEL, msg, len); } /** @brief Initialize sensor CTX * * To initialize a sensor, initialization function, sensor bus and sensor handle must * be set. After initialization, sensor control structure is ready to use, * initial configuration is set to actual values on sensor. * * To configure the sensor, set the sensor configuration in struct and call * @ref rt_sensor_configure. * * @param[in] sensor Sensor to initialize. * * @retval RD_SUCCESS on success. * @retval RD_ERROR_NULL if sensor is NULL * @retval RD_ERROR_NOT_FOUND if sensor->handle is RD_HANDLE_UNUSED * @return error code from sensor on other error. */ rd_status_t rt_sensor_initialize (rt_sensor_ctx_t * const sensor) { rd_status_t err_code = RD_SUCCESS; if ( (NULL == sensor) || (NULL == sensor->init)) { err_code |= RD_ERROR_NULL; } else if (RD_HANDLE_UNUSED != sensor->handle) { err_code = sensor->init (& (sensor->sensor), sensor->bus, sensor->handle); } else { err_code |= RD_ERROR_NOT_FOUND; } return err_code; } /** @brief Store the sensor state to NVM. * * @param[in] sensor Sensor to store. * * @return RD_SUCCESS on success. * @return RD_ERROR_NULL if sensor is NULL. * @return error code from sensor on other error. */ rd_status_t rt_sensor_store (rt_sensor_ctx_t * const sensor) { rd_status_t err_code = RD_SUCCESS; if (NULL == sensor) { err_code |= RD_ERROR_NULL; } else if (rt_flash_busy()) { err_code |= RD_ERROR_BUSY; } else { err_code |= rt_flash_store (sensor->nvm_file, sensor->nvm_record, & (sensor->configuration), sizeof (sensor->configuration)); } return err_code; } /** @brief Load the sensor state from NVM. * * @param[in] sensor Sensor to store. * * @return RD_SUCCESS on success. * @return RD_ERROR_NULL if sensor is NULL. * @return error code from sensor on other error. */ rd_status_t rt_sensor_load (rt_sensor_ctx_t * const sensor) { rd_status_t err_code = RD_SUCCESS; if (NULL == sensor) { err_code |= RD_ERROR_NULL; } else if (rt_flash_busy()) { err_code |= RD_ERROR_BUSY; } else { err_code |= rt_flash_load (sensor->nvm_file, sensor->nvm_record, & (sensor->configuration), sizeof (sensor->configuration)); } return err_code; } /** @brief Configure a sensor with given settings. * * @param[in,out] sensor In: Sensor to configure. Out: Sensor->configuration will be set to actual configuration. * * @return RD_SUCCESS on success. * @return RD_ERROR_NULL if sensor is NULL. * @return error code from sensor on other error. */ rd_status_t rt_sensor_configure (rt_sensor_ctx_t * const ctx) { rd_status_t err_code = RD_SUCCESS; if (NULL == ctx) { err_code |= RD_ERROR_NULL; } else if (!rd_sensor_is_init (& (ctx->sensor))) { err_code |= RD_ERROR_INVALID_STATE; } else { LOG ("\r\nAttempting to configure "); LOG (ctx->sensor.name); LOG (" with:\r\n"); ri_log_sensor_configuration (TASK_SENSOR_LOG_LEVEL, & (ctx->configuration), ""); err_code |= ctx->sensor.configuration_set (& (ctx->sensor), & (ctx->configuration)); LOG ("Actual configuration:\r\n"); ri_log_sensor_configuration (TASK_SENSOR_LOG_LEVEL, & (ctx->configuration), ""); } return err_code; } /** * @brief Read sensors and encode to given buffer in Ruuvi DF5. * * @param[in] buffer uint8_t array with length of 24 bytes. * @return RD_SUCCESS if data was encoded */ //ruuvi_endpoint_status_t task_sensor_encode_to_5 (uint8_t * const buffer); /** * @brief Search for requested sensor backend in given list of sensors. * * @param[in] sensor_list Array of sensors to search the backend from. * @param[in] count Number of sensor backends in the list. * @param[in] name NULL-terminated, max 9-byte (including trailing NULL) string * representation of sensor. * @return pointer to requested sensor CTX if found * @return NULL if requested sensor was not found */ rt_sensor_ctx_t * rt_sensor_find_backend (rt_sensor_ctx_t * const sensor_list, const size_t count, const char * const name) { rt_sensor_ctx_t * p_sensor = NULL; for (size_t ii = 0; (count > ii) && (NULL == p_sensor); ii++) { if (0 == strcmp (sensor_list[ii].sensor.name, name)) { p_sensor = & (sensor_list[ii]); } } return p_sensor; } /** * @brief Search for a sensor which can provide requested values * * @param[in] sensor_list Array of sensors to search the backend from. * @param[in] count Number of sensor backends in the list. * @param[in] values Fields which sensor must provide. * @return Pointer to requested sensor if found. If there are many candidates, first is * returned * @return NULL if requested sensor was not found. */ rt_sensor_ctx_t * rt_sensor_find_provider (rt_sensor_ctx_t * const sensor_list, const size_t count, rd_sensor_data_fields_t values) { rt_sensor_ctx_t * p_sensor = NULL; for (size_t ii = 0; (count > ii) && (NULL == p_sensor); ii++) { if ( (values.bitfield & sensor_list[ii].sensor.provides.bitfield) == values.bitfield) { p_sensor = & (sensor_list[ii]); } } return p_sensor; } #endif
2.25
2
2024-11-18T23:20:05.624460+00:00
2021-04-16T11:11:05
4d5692e071ca53030a958f517de257a95228f001
{ "blob_id": "4d5692e071ca53030a958f517de257a95228f001", "branch_name": "refs/heads/master", "committer_date": "2021-04-16T11:11:05", "content_id": "859ab1cc5dd0fdb9bf65cad821c8471a94447974", "detected_licenses": [ "CC0-1.0", "MIT" ], "directory_id": "cd98d32a6d1b692752177fa72947458520ed4412", "extension": "c", "filename": "Display_Student.c", "fork_events_count": 5, "gha_created_at": "2021-04-09T13:19:34", "gha_event_created_at": "2021-04-15T06:32:56", "gha_language": "C", "gha_license_id": null, "github_id": 356278064, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 896, "license": "CC0-1.0,MIT", "license_type": "permissive", "path": "/3_Implementation/src/Display_Student.c", "provenance": "stackv2-0135.json.gz:56047", "repo_name": "259819/LnT_MiniProject", "revision_date": "2021-04-16T11:11:05", "revision_id": "6d80c7557dff406b081130301bc760c44673ba8e", "snapshot_id": "0f16cd2a5f3ee66da117bd4cae3062dbfff17c73", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/259819/LnT_MiniProject/6d80c7557dff406b081130301bc760c44673ba8e/3_Implementation/src/Display_Student.c", "visit_date": "2023-04-02T02:27:28.357938" }
stackv2
/** * @file Display_Student.c * @author 259819 Preet Kamalnayan Pandit (https://github.com/259819/LnT_MiniProject.git) * @brief * @version 0.1 * @date 2021-04-12 * * @copyright Copyright (c) 2021 * */ #include <stdio.h> #include <stdlib.h> #include<../inc/Student.h> /** * @brief displaying the record of already existing student * * @return int */ int display_Student(void) { Student_t Student; FILE *fptr; int count = 0; if ((fptr = fopen("Students.bin", "rb")) == NULL) { return -2; } printf("\n### Student_Records ###\n"); while (fread(&Student, sizeof(Student), 1, fptr) == 1) { printf("Name = %s\nStandard = %s\nEmail ID = %s\nGPA = %f\nsports activity = %s\n\n ", Student.name, Student.standard, Student.email_id,Student.GPA,Student.sports); count++; } printf("### Student_Records ###\n\n"); fclose(fptr); return count; }
2.890625
3
2024-11-18T20:59:20.511845+00:00
2023-03-29T15:27:24
fc499d1883bbf33f4a3595a9527e0f88d7efcf97
{ "blob_id": "fc499d1883bbf33f4a3595a9527e0f88d7efcf97", "branch_name": "refs/heads/master", "committer_date": "2023-03-29T15:27:24", "content_id": "09f379fee819ca13ab4fb22538f2a147a9731538", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "fbd6afa22568045d8806ecdda93144d1a6e44af2", "extension": "h", "filename": "CNSSSE.h", "fork_events_count": 151, "gha_created_at": "2013-12-29T18:24:40", "gha_event_created_at": "2018-04-12T12:36:26", "gha_language": "C++", "gha_license_id": null, "github_id": 15512849, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 15563, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/Src/Libs/ImageProcessing/CNS/CNSSSE.h", "provenance": "stackv2-0135.json.gz:232380", "repo_name": "bhuman/BHumanCodeRelease", "revision_date": "2023-03-29T15:27:24", "revision_id": "645031c46ff88efcf32129301d21e109857cde3d", "snapshot_id": "5ccbcc60b968c12f29983992d603ab464a51051b", "src_encoding": "UTF-8", "star_events_count": 212, "url": "https://raw.githubusercontent.com/bhuman/BHumanCodeRelease/645031c46ff88efcf32129301d21e109857cde3d/Src/Libs/ImageProcessing/CNS/CNSSSE.h", "visit_date": "2023-05-22T09:49:04.827692" }
stackv2
#pragma once /*! \file circleCNSSSE.h Contains a collection of SSE intrinsic based subroutines used by \c CircleCNSDetector. These routines cover most of the computation time and are highly optimized. */ #include "ImageProcessing/SIMD.h" #include <cassert> #include "CNSResponse.h" #include "CodedContour.h" //! Implicit factor involved in the computation of \c responseX16Y16RUsingSSE3 /*! \c responseX16Y16RUsingSSE3 compute \code ((cx-128)*nx+(cy-128)*ny)^2 >> RESPONSE_COMPUTATION_IMPLICIT_SHIFTRIGHT \endcode for every pixel on the contour where (cx,cy) is the binary value from the \c CnsImage and (nx, ny) is the binary value from the \c CodedContur. \c RESPONSE_COMPUTATION_IMPLICIT_SHIFTRIGHT gives the implicit shift in this computation. */ enum {RESPONSE_COMPUTATION_IMPLICIT_SHIFTRIGHT = 16}; //! The core response computation for one SSE register (more for reference and unit tests) inline void responseX8YRUsingSSE3(const CNSResponse* srcPixel, int srcOfs, unsigned short* responseBin, const CodedContourPoint& ccp) { srcOfs /= sizeof(CNSResponse); static const __m128i cns_const128V = _mm_set1_epi8(-128); __m128i cosSinVal = _mm_set1_epi16(nOfCCP(ccp)); // put the (nx,ny) normal vector into every component const CNSResponse* srcRun = srcPixel + xOfCCP(ccp) + srcOfs * yOfCCP(ccp); __m128i cosPSinVal = _mm_maddubs_epi16(cns_const128V, cosSinVal); __m128i dataA; dataA = _mm_loadu_si128((__m128i*)(srcRun + 0)); dataA = _mm_maddubs_epi16(dataA, cosSinVal); dataA = _mm_subs_epi16(dataA, cosPSinVal); dataA = _mm_mulhi_epi16(dataA, dataA); dataA = _mm_adds_epu16(dataA, *(__m128i*)(responseBin + 0x00)); *(__m128i*)(responseBin + 0x00) = dataA; } //! faster variant of \c reponseX16Y16RUsingC with SSE3 /*! The routine takes an image of contrast normalized Sobel (CNS) responses, and a \c contour and computes the contour quality value for an 16*16 block of potential reference points. In terms of abstract quantities the quality value is defined as \f{equation}{ \newcommand{\mvs}[1]{\!\left(\begin{smallmatrix}#1\end{smallmatrix}\right)} CQ(x, y) = \int_0^1 resp\left(p(\lambda)+\mvs{x\\y}, \angle p'(\lambda)+\frac{\pi}{2}\right) d\lambda, \\ resp(x_0,y_0,\theta) = \left( \mvs{\cos\theta\\\sin\theta}^T \cng(x_0,y_0) \right)^2, \f} where \f$ p:[0..1]\rightarrow R^2 \f$ is the contour and \f$ cng(x,y) \f$ is the contrast normalized gradient image. \c srcPixel is a pointer to the CNS result image pixel corresponding to the reference point for the contour. See documentation of \c CNSResponse for the coding of the values. \c srcOfs is the offset in CNSResponse units between successive lines in the CNS image \c accPixel is the pointer to 16*16 array of \c unsigned short values, where the result CQ(x,y) is stored. The entry (0,0) corresponds to a reference point at \c srcPixel. The other ones correspond to reference points to the right and down accordingly. The results are scaled by 0x10000 ranging [0..1]. The pointer must be aligned on 16 bytes. */ void responseX16Y16RUsingSSE3(const CNSResponse* srcPixel, int srcOfs, signed short* responseBin, const CodedContour& contour); //! 8*8 block variant of \c reponseX16Y16RUsingSSE3 /*! Used in refinement. */ void responseX8Y8RUsingSSE3(const CNSResponse* srcPixel, int srcOfs, signed short* responseBin, const CodedContour& contour); //! scales and shifts a raw response converting it from uint16 to signed int16 /*! \x (uint16) is mapped to \c x*scale>>16+offset. \c scale must be >=0. */ inline void scaleOffsetUsingSSE(unsigned short* src, short* dst, int n, short scale, signed short offset) { __m128i* pEnd = (__m128i*)(src + n); __m128i* p = (__m128i*) src; __m128i* pDst = (__m128i*) dst; assert(aligned16(src) && n % 32 == 0 && aligned16(dst)); __m128i scaleV = _mm_set1_epi16(scale); __m128i offsetV = _mm_set1_epi16(offset); while(p != pEnd) { for(int unrollCtr = 0; unrollCtr < 4; unrollCtr++) { *pDst = _mm_add_epi16(_mm_mulhi_epu16(*p, scaleV), offsetV); p++; pDst++; } } } //! Optimized SSE2 implementation of \c maximum static const __m128i cns_const8 = _mm_set1_epi16(8); static const __m128i cns_constCount = _mm_set_epi16(7, 6, 5, 4, 3, 2, 1, 0); static const __m128i cns_constMinShort = _mm_set1_epi16(-0x8000); inline void maximumUsingSSE2(int& max, int& argMax, int baseArg, const short* accPixel, int nAccPixel) { assert(nAccPixel % 32 == 0); assert(baseArg + nAccPixel < 0x10000); // First build max and argMax in 8 entry-blocks __m128i lMax = cns_constMinShort; __m128i lArgMax = _mm_setzero_si128(); __m128i lIndex = _mm_add_epi16(_mm_set1_epi16(static_cast<short>(baseArg)), cns_constCount); __m128i* accPixelEnd = reinterpret_cast<__m128i*>(const_cast<short*>(accPixel + nAccPixel)); __m128i* p = reinterpret_cast<__m128i*>(const_cast<short*>(accPixel)); while(p != accPixelEnd) { for(int unrollCtr = 0; unrollCtr < 4; unrollCtr++) { __m128i val = *p; lMax = _mm_max_epi16(lMax, val); __m128i mask = _mm_cmpeq_epi16(val, lMax); // 0xffff for new maxima lArgMax = _mm_max_epi16(lArgMax, _mm_and_si128(mask, lIndex)); // update values in lArgmax where mask is 0xffff with index lIndex = _mm_add_epi16(lIndex, cns_const8); p++; } } alignas(16) signed short lMaxShort[8]; alignas(16) signed short lArgMaxShort[8]; _mm_store_si128((__m128i*) lMaxShort, lMax); _mm_store_si128((__m128i*) lArgMaxShort, lArgMax); // Then find overall maximum as maximum of the 8 entries for(int i = 0; i < 8; i++) { if(lMaxShort[i] > max) { max = lMaxShort[i]; argMax = lArgMaxShort[i]; } } } // This is the body of the innermost computation loop. It computes CNS // response for a single contour pixel in parallel applied to 8 CNS // pixels src[0..7] and accumulates the response in acc[0..7]. The // fact that this routine is so highly optimized, being reduced to // only 5 operations when inlined dominates the overall computation // time. // // The formal computation is specified in \c // cns_reponseX8YRUsingC. In general it computes \c // ((cns_x-128)*normal_x+(cns_y-128)*normal_y)^2>>16 // \c cns_x and \c cns_y are given in \c // srcPixel, \c normal_x and \c normal_y by odd and even signed bytes // in \c cosSinVal. \c cosPSinVal is needed for technical reasons and // contains the signed 16bit result of \c _mm_maddubs_epi16 // (cns_const128V, cosSinVal); inline void cns_reponseX8YRUsingSSE3(const CNSResponse* __restrict srcPixel, __m128i cosSinVal, __m128i cosPSinVal, __m128i& acc) { __m128i val = _mm_subs_epi16(_mm_maddubs_epi16(_mm_loadu_si128((__m128i*) srcPixel), cosSinVal), cosPSinVal); acc = _mm_adds_epu16(acc, _mm_mulhi_epi16(val, val)); } inline void cns_reponseX16YRUsingSSE3(const CNSResponse* __restrict srcPixel, __m128i cosSinVal, __m128i cosPSinVal, __m128i* __restrict acc) { __m128i srcA = _mm_loadu_si128((__m128i*) srcPixel); __m128i srcB = _mm_loadu_si128((__m128i*)(srcPixel + 8)); __m128i valA = _mm_subs_epi16(_mm_maddubs_epi16(srcA, cosSinVal), cosPSinVal); __m128i valB = _mm_subs_epi16(_mm_maddubs_epi16(srcB, cosSinVal), cosPSinVal); acc[0] = _mm_adds_epu16(acc[0], _mm_mulhi_epi16(valA, valA)); acc[1] = _mm_adds_epu16(acc[1], _mm_mulhi_epi16(valB, valB)); } ALWAYSINLINE void cns_zeroAccumulator(unsigned short* acc, int nAcc) { __m128i* p = (__m128i*) acc; __m128i* pEnd = (__m128i*)(acc + nAcc); __m128i zero = _mm_setzero_si128(); while(p != pEnd) { *p = zero; p++; } } ALWAYSINLINE void cns_copyAccumulator(unsigned short* dst, unsigned short* src, int nAcc); inline void cns_copyAccumulator(unsigned short* dst, unsigned short* src, int nAcc) { __m128i* p = (__m128i*) src; __m128i* pEnd = (__m128i*)(src + nAcc); __m128i* pD = (__m128i*) dst; while(p != pEnd) { *pD = *p; p++; pD++; } } //! Internal subroutine for cnsResponse /*! load 8 image pixel and convert to 16 bit, also generates 1 pixel shifts for later filter computation img[i] contains src[i], imgL[i] contains src[i-1] and, imgR[i] contains src[i+1], i=0..7 when interpreting __m128i as unsigned short [8]; \c isFirst must be set for first block in a row, which does not access src[-1] and uses 0 instead \c isLast must be set for the last block in a row, which does not access src[8] and uses 0 instead */ ALWAYSINLINE void load8PixelUsingSSE(__m128i& imgL, __m128i& img, __m128i& imgR, const unsigned char* src, bool isFirst, bool isLast) { __m128i imgRaw; if(!isLast) { if(!isFirst) imgRaw = _mm_loadu_si128((__m128i*)(src - 1)); // regular pixel in the middle of the image else imgRaw = _mm_slli_si128(_mm_loadu_si128((__m128i*)src), 1); // on the left border take one adress later and shift } else imgRaw = _mm_srli_si128(_mm_loadu_si128((__m128i*)(src - 8)), 7); // right border take 7 adress earlier and shift imgL = _mm_unpacklo_epi8(imgRaw, _mm_setzero_si128()); img = _mm_unpacklo_epi8(_mm_srli_si128(imgRaw, 1), _mm_setzero_si128()); imgR = _mm_unpacklo_epi8(_mm_srli_si128(imgRaw, 2), _mm_setzero_si128()); } //! Computes SIMD a+2*b+c ALWAYSINLINE __m128i blur_epi16(__m128i a, __m128i b, __m128i c) {return _mm_add_epi16(a, _mm_add_epi16(b, _mm_add_epi16(b, c)));} //! Computes SIMD a+2*b+c ALWAYSINLINE __m128i blur_epi32(__m128i a, __m128i b, __m128i c) {return _mm_add_epi32(a, _mm_add_epi32(b, _mm_add_epi32(b, c)));} //! Computes SIMD a+2*b+c ALWAYSINLINE __m128 blur_ps(__m128 a, __m128 b, __m128 c) {return _mm_add_ps(a, _mm_add_ps(b, _mm_add_ps(b, c)));} //! Compute a gaussian [1 2 1]^T*[1 2 1] filter /*! First, the [1 2 1] convolution is computed horizontally, the result stored in currentIV. Then this result and the values of \c previousIV and the old value of \c currentIV are combined vertically with the result stored in \c gaussI. */ ALWAYSINLINE void gauss(__m128i& currentIV, const __m128i& previousIV, __m128i& gaussI, __m128i imgL, __m128i img, __m128i imgR) { __m128i blurX = blur_epi16(imgL, img, imgR); // [1 2 1]*I gaussI = blur_epi16(blurX, previousIV, currentIV); // [1 2 1]*[1 2 1]*I currentIV = blurX; } //! Overloaded function that only computes intermediate results in \c currentIV not final ones ALWAYSINLINE void gauss(__m128i& currentIV, const __m128i& previousIV, __m128i imgL, __m128i img, __m128i imgR) { // Call \c filters with dummy variables. Compiler will optimize unnecessary computations out. __m128i gaussI; gauss(currentIV, previousIV, gaussI, imgL, img, imgR); } //! Sets dst[i] to src[2*i] for i=0..w/2 /*! This helper function is used for the margin in the downsampled image */ void decimateLineUsingSSE(const unsigned char* src, int w, unsigned char* ds); //! converts 8 unsigned short responses in acc into floats storing at \c response[0..1] /*! The conversion is by multiplying with \c invResponseAccumulatorScale */ ALWAYSINLINE void convertX8ResponsesToFloatUsingSSE(__m128* response, __m128i acc, __m128 invResponseAccumulatorScale) { _mm_stream_ps(reinterpret_cast<float*>(response), _mm_mul_ps(_mm_cvtepi32_ps(_mm_unpacklo_epi16(acc, _mm_setzero_si128())), invResponseAccumulatorScale)); _mm_stream_ps(reinterpret_cast<float*>(response + 1), _mm_mul_ps(_mm_cvtepi32_ps(_mm_unpackhi_epi16(acc, _mm_setzero_si128())), invResponseAccumulatorScale)); } //! Converts a 16*16 block of responses in \c acc from unsigned short into float /*! .. by multiplying with \c invResponseAccumulatorScale \c acc[x+16*y] is stored into \c response[x+responseOfs*y] */ void convertX16Y16RResponsesToFloatUsingSSE(float* response, int responseOfs, unsigned short* acc, float invResponseAccumulatorScale); //! Fills response with n times 0 ALWAYSINLINE void cns_zeroFloatArray(float* response, int n) { float* rEnd = response + n; __m128i zeroV = _mm_setzero_si128(); while(response != rEnd) { *(__m128i*) response = zeroV; response++; } } //! optimized SSE implementation for projecting 3D points in the image /*! See \c projectUsingC, used by \LutRasterizer */ inline bool projectUsingSSE(float img[2], float p[4], float p0[4], float p1[4], float p2[4]) { __m128 pV = *((__m128*)p); __m128 nom = _mm_hadd_ps(_mm_mul_ps(pV, *((__m128*)p0)), _mm_mul_ps(pV, *((__m128*)p1))); nom = _mm_hadd_ps(nom, nom); __m128 denom = _mm_mul_ps(pV, *((__m128*)p2)); denom = _mm_hadd_ps(denom, denom); denom = _mm_hadd_ps(denom, denom); _mm_storel_pi((__m64*) img, _mm_div_ps(nom, denom)); return _mm_movemask_ps(denom) == 0; } //! optimized SSE implementation to make a \c CodedContourPoint from an edge in the image /*! See \c code2DEdgeUsingC, used by \LutRasterizer */ inline unsigned int code2DEdgeUsingSSE(float img[4], float clipRange[4]) { static __m128 half_ps = _mm_set1_ps(0.5); __m128 pAB = *((__m128*)img); __m128 pBA = _mm_shuffle_ps(pAB, pAB, _MM_SHUFFLE(1, 0, 3, 2)); __m128 pCC = _mm_mul_ps(_mm_add_ps(pAB, pBA), half_ps); // center (x0+x1)/2,(y0+y1)/2, (x0+x1)/2,(y0+y1)/2 if(_mm_movemask_ps(_mm_sub_ps(pCC, *(__m128*) clipRange)) != 12) return EMPTYCONTOURPOINT; __m128 pDD = _mm_sub_ps(pBA, pAB); // x1-x0, y1-y0, x1-x0, y1-y0 __m128 pLL = _mm_mul_ps(pDD, pDD); // (x1-x0)^2, (y1-y0)^2, (x1-x0)^2, (y1-y0)^2 pLL = _mm_hadd_ps(pLL, pLL); // 4 times (x1-x0)^2+(y1-y0)^2 pLL = _mm_rsqrt_ss(pLL); // 1/srqt((x1-x0)^2+(y1-y0)^2) pLL = _mm_shuffle_ps(pLL, pLL, _MM_SHUFFLE(0, 0, 0, 0)); static __m128 c127_ps = _mm_set_ps(-127, 127, -127, 127); pDD = _mm_mul_ps(_mm_mul_ps(pLL, c127_ps), pDD); // pDD is the vector scaled to length 127 and rotated 90 deg, just need to swap x and y // so combine x from PC, y from PC, y from pDD, x from PDD __m128 combined = _mm_shuffle_ps(pCC, pDD, _MM_SHUFFLE(0, 1, 1, 0)); __m128i coded = _mm_cvtps_epi32(combined); coded = _mm_packs_epi32(coded, coded); coded = _mm_packs_epi16(coded, coded); return _mm_cvtsi128_si32(coded); } //! Scales the normal vector of \c ccp[0..n-1] by \c factor /*! Optimized implementation. Warning, may overwrite up to \c ccp[n+2]. */ inline void scaleNormalUsingSSE(CodedContourPoint* ccp, int n, float factor) { // Warning we write over the end of [n] for performance reasons static __m128i makeNormal16s = _mm_set_epi8(15, -0x80, 14, -0x80, 11, -0x80, 10, -0x80, 7, -0x80, 6, -0x80, 3, -0x80, 2, -0x80); static __m128i makeNormal8s = _mm_set_epi8(15, 13, -0x80, -0x80, 11, 9, -0x80, -0x80, 7, 5, -0x80, -0x80, 3, 1, -0x80, -0x80); static __m128i maskNormalOut = _mm_set_epi8(0, 0, -1, -1, 0, 0, -1, -1, 0, 0, -1, -1, 0, 0, -1, -1); int factorI = static_cast<int>(factor * 0x10000); __m128i factorV = _mm_set1_epi16(static_cast<short>(factorI)); assert(abs(factorI) < 0x8000); CodedContourPoint* ccpEnd = ccp + n; while(ccp < ccpEnd) { __m128i ccpI = *(__m128i*) ccp; __m128i result = _mm_shuffle_epi8(_mm_mulhi_epi16(_mm_shuffle_epi8(ccpI, makeNormal16s), factorV), makeNormal8s); // (_*factorI)>>16 result = _mm_or_si128(result, _mm_and_si128(ccpI, maskNormalOut)); *(__m128i*) ccp = result; ccp += 4; } } //! x[0]=x[2]; x[1]=x[3]; inline void shift4Floats(float x[4]) { __m128 tmp = *(__m128*)x; *(__m128*)x = _mm_shuffle_ps(tmp, tmp, _MM_SHUFFLE(3, 2, 3, 2)); }
2.34375
2
2024-11-18T20:59:21.087285+00:00
2020-09-20T09:04:35
984113ad8e7b47c7e04d4f6598a307409acab3b3
{ "blob_id": "984113ad8e7b47c7e04d4f6598a307409acab3b3", "branch_name": "refs/heads/master", "committer_date": "2020-09-20T09:04:35", "content_id": "f6567eb7f12f2adfcb37bd28cbbed85d5b4ed4c8", "detected_licenses": [ "Apache-2.0" ], "directory_id": "b364cbfdfe3cdd7c0f05b3f2e185606956306b41", "extension": "h", "filename": "queue.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 168536313, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 454, "license": "Apache-2.0", "license_type": "permissive", "path": "/include/queue.h", "provenance": "stackv2-0135.json.gz:232640", "repo_name": "liangwt/leetcode", "revision_date": "2020-09-20T09:04:35", "revision_id": "8f279343e975666a63ee531228c6836f20f199ca", "snapshot_id": "935c0ebf9639ea262f8e76472d1216d08145ce12", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/liangwt/leetcode/8f279343e975666a63ee531228c6836f20f199ca/include/queue.h", "visit_date": "2021-07-02T08:20:11.350348" }
stackv2
#include <stdlib.h> #include <stdbool.h> typedef struct _queue_node { void *val; struct _queue_node *next; struct _queue_node *pre; } queue_node; typedef struct _queue { int num; struct _queue_node *head; struct _queue_node *tail; } queue; void queue_init(queue *q); bool queue_is_empty(queue *q); int queue_length(queue *q); bool queue_push(queue *q, void *val); queue_node *queue_pop(queue *q); void queue_destory(queue *q);
2.375
2
2024-11-18T20:59:21.655364+00:00
2017-05-16T05:37:45
bbbdd0b0daedaebfc690435454c1a309f7fa60c4
{ "blob_id": "bbbdd0b0daedaebfc690435454c1a309f7fa60c4", "branch_name": "refs/heads/master", "committer_date": "2017-05-16T05:37:45", "content_id": "e99dc0da311e89733fc965170b3f1e8144e78073", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "5c47d5f3e49459d1a9d253ab968675903e6c13a4", "extension": "c", "filename": "main.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 91417872, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 16439, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/Projects/STM32F072RB-Nucleo/Examples_LL/USART/USART_WakeUpFromStop/Src/main.c", "provenance": "stackv2-0135.json.gz:233298", "repo_name": "skalidindi3/STM32Cube_FW_F0_V1.8.0", "revision_date": "2017-05-16T05:37:45", "revision_id": "746931cc97044ea91dbfdc5b6da5c017e67449a8", "snapshot_id": "4683ccb2d3822090aad0abf59a66fdec231d2e13", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/skalidindi3/STM32Cube_FW_F0_V1.8.0/746931cc97044ea91dbfdc5b6da5c017e67449a8/Projects/STM32F072RB-Nucleo/Examples_LL/USART/USART_WakeUpFromStop/Src/main.c", "visit_date": "2020-12-30T12:12:38.287955" }
stackv2
/** ****************************************************************************** * @file Examples_LL/USART/USART_WakeUpFromStop/Src/main.c * @author MCD Application Team * @brief This example describes how to configure USART peripheral in Asynchronous mode * for being able to wake from Stop mode when a character is received on RX line using * the STM32F0xx USART LL API. * Peripheral initialization done using LL unitary services functions. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * 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. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" /** @addtogroup STM32F0xx_LL_Examples * @{ */ /** @addtogroup USART_WakeUpFromStop * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /** * @brief Variables used for charcater reception from PC Com port */ __IO uint8_t ubFinalCharReceived = 0; __IO uint32_t ubReceivedChar; /** * @brief Text string printed on PC Com port to inform MCU will enter in Stop Mode */ uint8_t aTextInfo[] = "\r\nUSART Example : MCU will now enter in Stop mode.\n\rEnter any character for waking up MCU.\r\n"; /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); void LED_Init(void); void LED_On(void); void LED_Off(void); void LED_Blinking(uint32_t Period); void LED_Blinking_3s(void); void Configure_USART1(void); void Configure_PWR(void); void PrepareUSARTToStopMode(void); void EnterStopMode(void); void PrintInfo(void); /* Private functions ---------------------------------------------------------*/ /** * @brief Main program * @param None * @retval None */ int main(void) { /* Configure the system clock to 8 MHz */ SystemClock_Config(); /* Initialize LED2 */ LED_Init(); /* Configure Power IP */ Configure_PWR(); /* Configure USART1 (USART IP configuration and related GPIO initialization) */ Configure_USART1(); /* Start main program loop : - make LED blink during 3 sec - Enter Stop mode (LED turned Off) - Wait for any character received on USART RX line for waking up MCU */ while (ubFinalCharReceived == 0) { /* LED blinks during 3 seconds */ LED_Blinking_3s(); /* Send Text Information on USART TX to PC Com port */ PrintInfo(); /* Prepare USART for entering Stop Mode */ PrepareUSARTToStopMode(); /* Enter Stop mode */ EnterStopMode(); /* At this point, MCU just wakes up from Stop mode */ } /* Infinite loop */ while (1) { } } /** * @brief This function configures USART1. * @note This function is used to : * -1- Enable GPIO clock and configures the USART1 pins. * -2- NVIC Configuration for USART1 interrupts. * -3- Enable the USART1 peripheral clock and clock source. * -4- Configure USART1 functional parameters. * -5- Enable USART1. * @note Peripheral configuration is minimal configuration from reset values. * Thus, some useless LL unitary functions calls below are provided as * commented examples - setting is default configuration from reset. * @param None * @retval None */ void Configure_USART1(void) { /* (1) Enable GPIO clock and configures the USART1 pins **********************/ /* (TX on PA.9, RX on PA.10) **********************/ /* Enable the peripheral clock of GPIOA */ LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_GPIOA); /* Configure TX Pin as : Alternate function, High Speed, PushPull, Pull up */ LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_9, LL_GPIO_MODE_ALTERNATE); LL_GPIO_SetAFPin_8_15(GPIOA, LL_GPIO_PIN_9, LL_GPIO_AF_1); LL_GPIO_SetPinSpeed(GPIOA, LL_GPIO_PIN_9, LL_GPIO_SPEED_FREQ_HIGH); LL_GPIO_SetPinOutputType(GPIOA, LL_GPIO_PIN_9, LL_GPIO_OUTPUT_PUSHPULL); LL_GPIO_SetPinPull(GPIOA, LL_GPIO_PIN_9, LL_GPIO_PULL_NO); /* Configure RX Pin as : Alternate function, High Speed, PushPull, Pull up */ LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_10, LL_GPIO_MODE_ALTERNATE); LL_GPIO_SetAFPin_8_15(GPIOA, LL_GPIO_PIN_10, LL_GPIO_AF_1); LL_GPIO_SetPinSpeed(GPIOA, LL_GPIO_PIN_10, LL_GPIO_SPEED_FREQ_HIGH); LL_GPIO_SetPinOutputType(GPIOA, LL_GPIO_PIN_10, LL_GPIO_OUTPUT_PUSHPULL); LL_GPIO_SetPinPull(GPIOA, LL_GPIO_PIN_10, LL_GPIO_PULL_NO); /* (2) NVIC Configuration for USART1 interrupts */ /* - Set priority for USART1_IRQn */ /* - Enable USART1_IRQn */ NVIC_SetPriority(USART1_IRQn, 0); NVIC_EnableIRQ(USART1_IRQn); /* (3) Enable the USART1 peripheral clock and clock source ****************/ LL_APB1_GRP2_EnableClock(LL_APB1_GRP2_PERIPH_USART1); /* Set USART1 clock source as HSI */ LL_RCC_SetUSARTClockSource(LL_RCC_USART1_CLKSOURCE_HSI); /* (4) Configure USART1 functional parameters ********************************/ /* Disable USART1 prior modifying configuration registers */ /* Note: Commented as corresponding to Reset value */ // LL_USART_Disable(USART1); /* TX/RX direction */ LL_USART_SetTransferDirection(USART1, LL_USART_DIRECTION_TX_RX); /* 8 data bit, 1 start bit, 1 stop bit, no parity */ LL_USART_ConfigCharacter(USART1, LL_USART_DATAWIDTH_8B, LL_USART_PARITY_NONE, LL_USART_STOPBITS_1); /* No Hardware Flow control */ /* Reset value is LL_USART_HWCONTROL_NONE */ // LL_USART_SetHWFlowCtrl(USART1, LL_USART_HWCONTROL_NONE); /* Oversampling by 16 */ /* Reset value is LL_USART_OVERSAMPLING_16 */ // LL_USART_SetOverSampling(USART1, LL_USART_OVERSAMPLING_16); /* Set Baudrate to 9600 using HSI frequency set to HSI_VALUE */ LL_USART_SetBaudRate(USART1, HSI_VALUE, LL_USART_OVERSAMPLING_16, 9600); /* Set the wake-up event type : specify wake-up on RXNE flag */ LL_USART_SetWKUPType(USART1, LL_USART_WAKEUP_ON_RXNE); /* (5) Enable USART1 **********************************************************/ LL_USART_Enable(USART1); /* Polling USART initialisation */ while((!(LL_USART_IsActiveFlag_TEACK(USART1))) || (!(LL_USART_IsActiveFlag_REACK(USART1)))) { } } /** * @brief Function to configure and initialize PWR IP. * @param None * @retval None */ void Configure_PWR(void) { /* Enable Power Clock */ LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_PWR); } /** * @brief Function to configure USART for being ready to enter Stop mode. * @param None * @retval None */ void PrepareUSARTToStopMode(void) { /* Empty RX Fifo before entering Stop mode (Otherwise, characters already present in FIFO will lead to immediate wake up */ while (LL_USART_IsActiveFlag_RXNE(USART1)) { /* Read Received character. RXNE flag is cleared by reading of RDR register */ ubReceivedChar = LL_USART_ReceiveData8(USART1); } /* Clear OVERRUN flag */ LL_USART_ClearFlag_ORE(USART1); /* Make sure that no USART transfer is on-going */ while(LL_USART_IsActiveFlag_BUSY(USART1) == 1) { } /* Make sure that USART is ready to receive */ while(LL_USART_IsActiveFlag_REACK(USART1) == 0) { } /* About to enter stop mode: switch off LED */ LED_Off(); /* Configure USART1 transfer interrupts : */ /* Clear WUF flag and enable the UART Wake Up from stop mode Interrupt */ LL_USART_ClearFlag_WKUP(USART1); LL_USART_EnableIT_WKUP(USART1); /* Enable Wake Up From Stop */ LL_USART_EnableInStopMode(USART1); } /** * @brief Function to enter in Stop mode. * @param None * @retval None */ void EnterStopMode(void) { /** Request to enter STOP mode * Following procedure describe in STM32F0xx Reference Manual * See PWR part, section Low-power modes, STOP mode */ /* Set STOP_LPREGU mode when CPU enters deepsleep */ LL_PWR_SetPowerMode(LL_PWR_MODE_STOP_LPREGU); /* Set SLEEPDEEP bit of Cortex System Control Register */ LL_LPM_EnableDeepSleep(); /* Request Wait For Interrupt */ __WFI(); } /** * @brief Send Txt information message on USART Tx line (to PC Com port). * @param None * @retval None */ void PrintInfo(void) { uint32_t index = 0; /* Send characters one per one, until last char to be sent */ for (index = 0; index < sizeof(aTextInfo); index++) { /* Wait for TXE flag to be raised */ while (!LL_USART_IsActiveFlag_TXE(USART1)) { } /* Write character in Transmit Data register. TXE flag is cleared by writing data in TDR register */ LL_USART_TransmitData8(USART1, aTextInfo[index]); } /* Wait for TC flag to be raised for last char */ while (!LL_USART_IsActiveFlag_TC(USART1)) { } } /** * @brief Initialize LED2. * @param None * @retval None */ void LED_Init(void) { /* Enable the LED2 Clock */ LED2_GPIO_CLK_ENABLE(); /* Configure IO in output push-pull mode to drive external LED2 */ LL_GPIO_SetPinMode(LED2_GPIO_PORT, LED2_PIN, LL_GPIO_MODE_OUTPUT); /* Reset value is LL_GPIO_OUTPUT_PUSHPULL */ //LL_GPIO_SetPinOutputType(LED2_GPIO_PORT, LED2_PIN, LL_GPIO_OUTPUT_PUSHPULL); /* Reset value is LL_GPIO_SPEED_FREQ_LOW */ //LL_GPIO_SetPinSpeed(LED2_GPIO_PORT, LED2_PIN, LL_GPIO_SPEED_FREQ_LOW); /* Reset value is LL_GPIO_PULL_NO */ //LL_GPIO_SetPinPull(LED2_GPIO_PORT, LED2_PIN, LL_GPIO_PULL_NO); } /** * @brief Turn-on LED2. * @param None * @retval None */ void LED_On(void) { /* Turn LED2 on */ LL_GPIO_SetOutputPin(LED2_GPIO_PORT, LED2_PIN); } /** * @brief Turn-off LED2. * @param None * @retval None */ void LED_Off(void) { /* Turn LED2 off */ LL_GPIO_ResetOutputPin(LED2_GPIO_PORT, LED2_PIN); } /** * @brief Set LED2 to Blinking mode for an infinite loop (toggle period based on value provided as input parameter). * @param Period : Period of time (in ms) between each toggling of LED * This parameter can be user defined values. Pre-defined values used in that example are : * @arg LED_BLINK_FAST : Fast Blinking * @arg LED_BLINK_SLOW : Slow Blinking * @arg LED_BLINK_ERROR : Error specific Blinking * @retval None */ void LED_Blinking(uint32_t Period) { /* Toggle IO in an infinite loop */ while (1) { LL_GPIO_TogglePin(LED2_GPIO_PORT, LED2_PIN); LL_mDelay(Period); } } /** * @brief Set LED2 to Blinking mode during 3s. * @param None * @retval None */ void LED_Blinking_3s(void) { uint32_t index=0; /* Toggle IO in during 3s (15*200ms) */ for(index = 0; index < 15; index++) { LL_GPIO_TogglePin(LED2_GPIO_PORT, LED2_PIN); LL_mDelay(200); } } /** * @brief System Clock Configuration * The system Clock is configured as follow : * System Clock source = PLL (HSI) * SYSCLK(Hz) = 8000000 * HCLK(Hz) = 8000000 * AHB Prescaler = 1 * APB1 Prescaler = 1 * HSI Frequency(Hz) = 8000000 * Flash Latency(WS) = 0 * @param None * @retval None */ void SystemClock_Config(void) { /* HSI configuration and activation */ /* Reset Value is HSI enabled */ // LL_RCC_HSI_Enable(); // while(LL_RCC_HSI_IsReady() != 1) // { // }; /* Sysclk activation on the HSI */ /* Reset Value is Sysclk activated on the HSI */ // LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_HSI); // while(LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_HSI) // { // }; /* Set AHB & APB1 prescaler */ /* Reset Value is AHB & APB1 prescaler DIV1 */ // LL_RCC_SetAHBPrescaler(LL_RCC_SYSCLK_DIV_1); // LL_RCC_SetAPB1Prescaler(LL_RCC_APB1_DIV_1); /* Set systick to 1ms in using frequency set to 8MHz */ LL_Init1msTick(8000000); /* Update CMSIS variable (which can be updated also through SystemCoreClockUpdate function) */ /* Reset Value is SystemCoreClock at 8Mhz */ // LL_SetSystemCoreClock(8000000); } /******************************************************************************/ /* IRQ HANDLER TREATMENT Functions */ /******************************************************************************/ /** * @brief Function called from USART IRQ Handler when RXNE flag is set * Function is in charge of reading character received on USART RX line. * @param None * @retval None */ void USART_CharReception_Callback(void) { /* Read Received character. RXNE flag is cleared by reading of RDR register */ ubReceivedChar = LL_USART_ReceiveData8(USART1); /* Check if received value is corresponding to specific one : S or s */ if ((ubReceivedChar == 'S') || (ubReceivedChar == 's')) { /* Turn LED2 On : Expected character has been received */ LED_On(); /* End of program : set boolean for main loop exit */ ubFinalCharReceived = 1; } /* Echo received character on TX */ LL_USART_TransmitData8(USART1, ubReceivedChar); } /** * @brief Function called in case of error detected in USART IT Handler * @param None * @retval None */ void Error_Callback(void) { /* Disable USART1_IRQn */ NVIC_DisableIRQ(USART1_IRQn); /* Unexpected event : Set LED2 to Blinking mode to indicate error occurs */ LED_Blinking(LED_BLINK_ERROR); } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d", file, line) */ /* Infinite loop */ while (1) { } } #endif /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
2.453125
2
2024-11-18T20:59:21.742541+00:00
2023-07-27T12:47:12
ab4fddab2a149c7f7655ff63678a3a2c902fee48
{ "blob_id": "ab4fddab2a149c7f7655ff63678a3a2c902fee48", "branch_name": "refs/heads/develop", "committer_date": "2023-07-27T12:47:12", "content_id": "ccdd9cefc3df0945036988656cb40390452d6bd4", "detected_licenses": [ "Apache-2.0", "Intel" ], "directory_id": "50e95229b9a1161ac294137120aaba94c9eb06bc", "extension": "c", "filename": "pcpgfpinitarbitrary.c", "fork_events_count": 81, "gha_created_at": "2018-07-06T22:16:28", "gha_event_created_at": "2023-08-30T17:18:36", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 140034345, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2969, "license": "Apache-2.0,Intel", "license_type": "permissive", "path": "/sources/ippcp/pcpgfpinitarbitrary.c", "provenance": "stackv2-0135.json.gz:233429", "repo_name": "intel/ipp-crypto", "revision_date": "2023-07-27T12:47:12", "revision_id": "36e76e2388f3dd10cc440e213dfcf6ef59a0dfb8", "snapshot_id": "f0f05b87203705e82603db67bed5f8def13a5ee8", "src_encoding": "UTF-8", "star_events_count": 304, "url": "https://raw.githubusercontent.com/intel/ipp-crypto/36e76e2388f3dd10cc440e213dfcf6ef59a0dfb8/sources/ippcp/pcpgfpinitarbitrary.c", "visit_date": "2023-09-04T08:15:06.851373" }
stackv2
/******************************************************************************* * Copyright (C) 2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions * and limitations under the License. * *******************************************************************************/ /* // Intel(R) Integrated Performance Primitives. Cryptography Primitives. // Operations over GF(p). // // Context: // ippsGFpInitArbitrary() // */ #include "owndefs.h" #include "owncp.h" #include "pcpgfpstuff.h" #include "pcpgfpxstuff.h" #include "pcptool.h" /*F* // Name: ippsGFpInitArbitrary // // Purpose: initializes prime finite field GF(p) // // Returns: Reason: // ippStsNullPtrErr NULL == pPrime // NULL == pGFp // // ippStsSizeErr !(IPP_MIN_GF_BITSIZE <= primeBitSize <=IPP_MAX_GF_BITSIZE) // // ippStsContextMatchErr incorrect pPrime context ID // // ippStsBadArgErr prime <0 // bitsize(prime) != primeBitSize // prime <IPP_MIN_GF_CHAR // prime is even // // ippStsNoErr no error // // Parameters: // pPrime pointer to the prime context // primeBitSize length of prime in bits // pGFp pointer to Finite Field context is being initialized *F*/ IPPFUN(IppStatus, ippsGFpInitArbitrary,(const IppsBigNumState* pPrime, int primeBitSize, IppsGFpState* pGFp)) { IPP_BAD_PTR1_RET(pGFp); IPP_BADARG_RET((primeBitSize< IPP_MIN_GF_BITSIZE) || (primeBitSize> IPP_MAX_GF_BITSIZE), ippStsSizeErr); IPP_BAD_PTR1_RET(pPrime); IPP_BADARG_RET(!BN_VALID_ID(pPrime), ippStsContextMatchErr); IPP_BADARG_RET(BN_SIGN(pPrime)!= IppsBigNumPOS, ippStsBadArgErr); /* prime is negative */ IPP_BADARG_RET(BITSIZE_BNU(BN_NUMBER(pPrime),BN_SIZE(pPrime)) != primeBitSize, ippStsBadArgErr); /* primeBitSize == bitsize(prime) */ IPP_BADARG_RET((BN_SIZE(pPrime)==1) && (BN_NUMBER(pPrime)[0]<IPP_MIN_GF_CHAR), ippStsBadArgErr); /* prime < 3 */ IPP_BADARG_RET(0==(BN_NUMBER(pPrime)[0] & 1), ippStsBadArgErr); /* prime is even */ { /* init GF */ IppStatus sts = cpGFpInitGFp(primeBitSize, pGFp); /* set up GF engine */ if(ippStsNoErr==sts) { cpGFpSetGFp(BN_NUMBER(pPrime), primeBitSize, ippsGFpMethod_pArb(), pGFp); } return sts; } }
2.03125
2
2024-11-18T20:59:22.053992+00:00
2014-06-29T20:15:30
349597b2a65b93b9761ee1a184486fa1a2350784
{ "blob_id": "349597b2a65b93b9761ee1a184486fa1a2350784", "branch_name": "refs/heads/master", "committer_date": "2014-06-29T20:15:30", "content_id": "572c686ff9099366fed4921187d8172e614c0bca", "detected_licenses": [ "MIT" ], "directory_id": "3a8a31aeb6e06191069aa443f3fa1878a275082b", "extension": "h", "filename": "cuda_opencl_shared.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 21330945, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4631, "license": "MIT", "license_type": "permissive", "path": "/src/runtime/cuda_opencl_shared.h", "provenance": "stackv2-0135.json.gz:233691", "repo_name": "netaz/Halide", "revision_date": "2014-06-29T20:15:30", "revision_id": "92a65e82b39d48d03468ea9b20209278db3de9d2", "snapshot_id": "ab227772fd4bc8737a2f0fa7eb62ecb4ceb6aaa3", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/netaz/Halide/92a65e82b39d48d03468ea9b20209278db3de9d2/src/runtime/cuda_opencl_shared.h", "visit_date": "2021-01-18T18:32:49.899494" }
stackv2
extern "C" { // Compute the total amount of memory we'd need to allocate on gpu to // represent a given buffer (using the same strides as the host // allocation). static size_t _buf_size(void *user_context, buffer_t *buf) { size_t size = buf->elem_size; for (size_t i = 0; i < sizeof(buf->stride) / sizeof(buf->stride[0]); i++) { size_t total_dim_size = buf->elem_size * buf->extent[i] * buf->stride[i]; if (total_dim_size > size) { size = total_dim_size; } } halide_assert(user_context, size); return size; } // A host <-> dev copy should be done with the fewest possible number // of contiguous copies to minimize driver overhead. If our buffer_t // has strides larger than its extents (e.g. because it represents a // sub-region of a larger buffer_t) we can't safely copy it back and // forth using a single contiguous copy, because we'd clobber // in-between values that another thread might be using. In the best // case we can do a single contiguous copy, but in the worst case we // need to individually copy over every pixel. // // This problem is made extra difficult by the fact that the ordering // of the dimensions in a buffer_t doesn't relate to memory layout at // all, so the strides could be in any order. // // We solve it by representing a copy job we need to perform as a // _dev_copy struct. It describes a 4D array of copies to // perform. Initially it describes copying over a single pixel at a // time. We then try to discover contiguous groups of copies that can // be coalesced into a single larger copy. // The struct that describes a host <-> dev copy to perform. #define MAX_COPY_DIMS 4 struct _dev_copy { uint64_t src, dst; // The multidimensional array of contiguous copy tasks that need to be done. uint64_t extent[MAX_COPY_DIMS]; // The strides (in bytes) that separate adjacent copy tasks in each dimension. uint64_t stride_bytes[MAX_COPY_DIMS]; // How many contiguous bytes to copy per task uint64_t chunk_size; }; static _dev_copy _make_host_to_dev_copy(const buffer_t *buf) { // Make a copy job representing copying the first pixel only. _dev_copy c; c.src = (uint64_t)buf->host; c.dst = buf->dev; c.chunk_size = buf->elem_size; for (int i = 0; i < MAX_COPY_DIMS; i++) { c.extent[i] = 1; c.stride_bytes[i] = 0; } if (buf->elem_size == 0) { // This buffer apparently represents no memory. Return a zero'd copy // task. _dev_copy zero = {0}; return zero; } // Now expand it to copy all the pixels (one at a time) by taking // the extents and strides from the buffer_t. Dimensions are added // to the copy by inserting it s.t. the stride is in ascending order. for (int i = 0; i < 4 && buf->extent[i]; i++) { int stride_bytes = buf->stride[i] * buf->elem_size; // Insert the dimension sorted into the buffer copy. int insert; for (insert = 0; insert < i; insert++) { // If the stride is 0, we put it at the end because it can't be // folded. if (stride_bytes < c.stride_bytes[insert] && stride_bytes != 0) { break; } } for (int j = i; j > insert; j--) { c.extent[j] = c.extent[j - 1]; c.stride_bytes[j] = c.stride_bytes[j - 1]; } // If the stride is 0, only copy it once. c.extent[insert] = stride_bytes != 0 ? buf->extent[i] : 1; c.stride_bytes[insert] = stride_bytes; }; // Attempt to fold contiguous dimensions into the chunk size. Since the // dimensions are sorted by stride, and the strides must be greater than // or equal to the chunk size, this means we can just delete the innermost // dimension as long as its stride is equal to the chunk size. while(c.chunk_size == c.stride_bytes[0]) { // Fold the innermost dimension's extent into the chunk_size. c.chunk_size *= c.extent[0]; // Erase the innermost dimension from the list of dimensions to // iterate over. for (int j = 1; j < MAX_COPY_DIMS; j++) { c.extent[j-1] = c.extent[j]; c.stride_bytes[j-1] = c.stride_bytes[j]; } c.extent[MAX_COPY_DIMS-1] = 1; c.stride_bytes[MAX_COPY_DIMS-1] = 0; } return c; } static _dev_copy _make_dev_to_host_copy(const buffer_t *buf) { // Just make a host to dev copy and swap src and dst _dev_copy c = _make_host_to_dev_copy(buf); uint64_t tmp = c.src; c.src = c.dst; c.dst = tmp; return c; } }
3.03125
3
2024-11-18T20:59:22.141491+00:00
2021-07-09T02:58:43
9f9242963cf9fbcd994d28762c0ac6350bf90465
{ "blob_id": "9f9242963cf9fbcd994d28762c0ac6350bf90465", "branch_name": "refs/heads/main", "committer_date": "2021-07-09T02:58:43", "content_id": "79b64e26398150d41e419caddbbeafc18094eeb9", "detected_licenses": [ "MIT" ], "directory_id": "9e8f86fa4f82363f3178a978bac5c8b736b5a615", "extension": "c", "filename": "test.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 376318340, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 396, "license": "MIT", "license_type": "permissive", "path": "/5s/2_Numerical_analysis/test.c", "provenance": "stackv2-0135.json.gz:233819", "repo_name": "KiyoshiroKawanabe/university_class", "revision_date": "2021-07-09T02:58:43", "revision_id": "ad9bd46fb9ef03fe2e1063a114ec5819e2e9200f", "snapshot_id": "fb88e76751c112b360d70ee14758b6174d1dc697", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/KiyoshiroKawanabe/university_class/ad9bd46fb9ef03fe2e1063a114ec5819e2e9200f/5s/2_Numerical_analysis/test.c", "visit_date": "2023-06-12T21:52:54.969378" }
stackv2
#include <stdio.h> #include <stdlib.h> #define N 200 int main(void){ FILE *fp; int i=9; char str[N]; char filename[100]; sprintf(filename, "city011/city011_%03d.txt", i); fp=fopen(filename, "r"); if(fp == NULL) { printf("%s file not open!\n", filename); return -1; } while(fgets(str, N, fp) != NULL) { printf("%s", str); } fclose(fp); return 0; }
2.625
3
2024-11-18T20:59:22.966149+00:00
2018-01-15T15:39:16
ceeab528da3491535e44acf5c702e91124d81716
{ "blob_id": "ceeab528da3491535e44acf5c702e91124d81716", "branch_name": "refs/heads/master", "committer_date": "2018-01-15T15:39:16", "content_id": "365730ffcdecd777353189dce44817b4470a5347", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "c03aca8a5905cc237a74d23084f33a4c65c6aa25", "extension": "h", "filename": "handletable.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 117470334, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 965, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/filesystem/fat/include/handletable.h", "provenance": "stackv2-0135.json.gz:234601", "repo_name": "flit/stmp_media_archive", "revision_date": "2018-01-15T15:39:16", "revision_id": "69374674f714f25185fea413610ea46d8d352dd8", "snapshot_id": "646f17f5b45ca31031bb6eba0e1a95443b6344bf", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/flit/stmp_media_archive/69374674f714f25185fea413610ea46d8d352dd8/filesystem/fat/include/handletable.h", "visit_date": "2021-05-11T21:32:20.402550" }
stackv2
#ifndef _HANDLE_TABLE_H_ #define _HANDLE_TABLE_H_ #include <types.h> #include "fstypes.h" #define NUM_SEEKPOINTS_CACHED 10 // Propagate changes to this table to the appropriate structure in fstypes.h // In this case, the HANDLEENTRYSIZE should be updated. typedef struct { uint8_t HandleActive; int8_t Device; uint8_t Mode; int32_t StartingCluster; int32_t CurrentOffset; int32_t CurrentCluster; int32_t CurrentSector; int32_t BytePosInSector; uint8_t SectorPosInCluster; int32_t DirSector; int32_t DirOffset; int32_t ErrorCode; int32_t FileSize; int32_t SeekPointsClusters[NUM_SEEKPOINTS_CACHED]; int32_t SeekPointsClusterStep; // the cluster step in the SeekPoint cluster buffer int32_t SeekPointsBaseFileSize; //The file size based to calculate SeekPointsClusterStep. // We need this because file size will change with mode "w+" }HandleTable_t; #endif // !_HANDLE_TABLE_H_
2.046875
2
2024-11-18T20:59:23.327818+00:00
2020-07-08T05:16:46
103f39decaebcc6743a93024b72ae5550148ee21
{ "blob_id": "103f39decaebcc6743a93024b72ae5550148ee21", "branch_name": "refs/heads/master", "committer_date": "2020-07-08T05:16:46", "content_id": "763a36587af54bca74c2332634f47e578514e11e", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "c047d3f8e5ce5a6d9717eff713cf08c685967b0f", "extension": "c", "filename": "i2c_driver.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 277995279, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 16983, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/asic/e-class-aardonyx/fpga/test/artya7-100t/peripheral-tests/bsp/drivers/i2c/i2c_driver.c", "provenance": "stackv2-0135.json.gz:234733", "repo_name": "Rajssss/shakti-soc", "revision_date": "2020-07-08T05:16:46", "revision_id": "7dbf88dd7e568c9f1fcd67ee8fbf579f2fe21f9d", "snapshot_id": "da51316b15ad88dcf40469bca4ac8d3e0ee75542", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Rajssss/shakti-soc/7dbf88dd7e568c9f1fcd67ee8fbf579f2fe21f9d/asic/e-class-aardonyx/fpga/test/artya7-100t/peripheral-tests/bsp/drivers/i2c/i2c_driver.c", "visit_date": "2022-11-13T11:47:16.519369" }
stackv2
// SPDX-License-Identifier: GPL-2.0-or-later /* * * Copyright (C) 1995-1997 Simon G. Vogl * 1998-2000 Hans Berglund * * With some changes from Kyösti Mälkki <[email protected]> and * Frodo Looijaard <[email protected]>, and also from Martin Bailey * <[email protected]> * * Partially rewriten by Oleg I. Vdovikin <[email protected]> to handle multiple * messages, proper stop/repstart signaling during receive, added detect code * * Partially rewritten by Vinod <[email protected]> and Kotteeswaran <[email protected]> for shakti i2c * * i2c-algo-pcf.c i2c driver algorithms for PCF8584 adapters was modified to this file. */ /*************************************************************************** * Project : shakti devt board * Name of the file : i2c_driver.c * Created date : * Brief Description of file : Demonstartes the working of i2c protocol. */ #include "i2c.h"//Includes the definitions of i2c communication protocol// char get_i2c_shakti(char *addr) { #ifdef ASM char val; printf("\n The address is %p;", (char *) addr); asm volatile("lb %0, 0(%1)" : "=r" (val) : "r" (*addr)); return val; #else return *addr; #endif } void set_i2c_shakti(char *addr, char val) { #ifdef ASM printf("\n The address is %p; value: %x", (char *) addr, val); asm volatile("sb %0, 0(%1)" : : "r" (val), "r" (*addr)); #else *addr = val; #endif } void waitfor(unsigned int secs) { unsigned int time = 0; while(time++ < secs); } void i2c_start() { set_i2c_shakti(i2c_control, I2C_SHAKTI_START); } void i2c_start_eni() { set_i2c_shakti(i2c_control, I2C_SHAKTI_START); } void i2c_repstart() { set_i2c_shakti(i2c_control, I2C_SHAKTI_REPSTART); } void i2c_repstart_eni() { set_i2c_shakti(i2c_control, I2C_SHAKTI_REPSTART); } void i2c_stop() { set_i2c_shakti(i2c_control, I2C_SHAKTI_STOP); } void i2c_nack() { set_i2c_shakti(i2c_control, I2C_SHAKTI_NACK); } int shakti_init_i2c() { unsigned char temp = 0; printf("\tI2C: Initializing the Controller\n"); /* Doing an initialization sequence as how PCF8584 was supposed to be initialized */ /* The Initialization Sequence is as follows */ /* Reset Minimum 30 Clock Cycles -- Not necessary in our case */ /* Load Byte 80H into Control */ /* load Clock Register S2 */ /* We are doing the opposite -- Setting the clock and then the registers -- Doesn't really matter actually */ /* Send C1H to S1 - Set I2C to Idle mode -- SDA and SCL should be high */ set_i2c_shakti(i2c_prescale,0x1F); //Setting the I2C clock value to be 1, which will set the clock for module and prescaler clock temp = get_i2c_shakti(i2c_prescale); set_i2c_shakti(i2c_scl,0x91); //Setting the I2C clock value to be 1, which will set the clock for module and prescaler clock temp = get_i2c_shakti(i2c_scl); /* Just reading the written value to see if all is well -- Compiler should not optimize this load!!! Compiler can just optimize the store to pointer address followed by load pointer to a register to just an immediate load to the register since clock register is not used anywhere -- but the purpose is lost. Don't give compiler optimizations */ if((temp | 0x00) != 0x91){ printf("\tClock initialization failed Write Value: 0x91; read Value: %02x\n", temp); return -ENXIO; } else{ printf("\tClock successfully initalized\n"); } /* S1=0x80 S0 selected, serial interface off */ printf("\tSetting Control Register with 0x80 \n"); set_i2c_shakti(i2c_control, I2C_SHAKTI_PIN); printf("\tControl Register Successfully set \n"); // Reading set control Register Value to ensure sanctity printf("\tReading Control Register \n"); temp = get_i2c_shakti(i2c_control); printf("\tControl Register is Written with 0x%x \n", temp); if((temp & 0x7f) != 0){ printf("\tDevice Not Recognized\n"); return -ENXIO; } printf("\tWaiting for a specified time\n "); waitfor(900); //1 Second software wait -- Should be 900000 but setting to 900 now since simulation is already slow printf("\tDone Waiting \n "); /* Enable Serial Interface */ set_i2c_shakti(i2c_control, I2C_SHAKTI_IDLE); waitfor(900); //1 Second software wait -- Should be 900000 but setting to 900 now since simulation is already slow temp = get_i2c_shakti(i2c_status); printf("\tStatus Reg value after sending I2C_SHAKTI_IDLE is : 0x%x \n",temp); /* Check to see if I2C is really in Idle and see if we can access the status register -- If not something wrong in initialization. This also verifies if Control is properly written since zero bit will be initialized to zero*/ if(temp != (I2C_SHAKTI_PIN | I2C_SHAKTI_BB)){ printf("\tInitialization failed\n"); return -ENXIO; } else printf("\tAll is well till here \n"); printf("\tI2C successfully initialized\n"); } int wait_for_bb() { printf("\tIs bus busy?\n"); int timeout = DEF_TIMEOUT; int status; status = get_i2c_shakti(i2c_status); while (!(status & I2C_SHAKTI_BB) && --timeout) { waitfor(20000); /* wait for 100 us */ status = get_i2c_shakti(i2c_status); } if (timeout == 0) { printf("\t Bus busy wait - timed out. Resetting\n"); return ETIMEDOUT; } return 0; } int wait_for_pin(int *status) { int timeout = DEF_TIMEOUT; *status = get_i2c_shakti(i2c_status); while ((*status & I2C_SHAKTI_PIN) && --timeout) { waitfor(10000); /* wait for 100 us */ *status = get_i2c_shakti(i2c_status); } if (timeout == 0){ printf("\tWait for pin timed out\n"); return ETIMEDOUT; } return 0; } int shakti_sendbytes( const char *buf, int count, int last, int eni) { int wrcount, status, timeout; printf("\tStarting Write Transaction -- Did you create tri1 nets for SDA and SCL in verilog?\n"); for (wrcount=0; wrcount<count; ++wrcount) { set_i2c_shakti(i2c_data,buf[wrcount]); timeout = wait_for_pin(&status); if (timeout) { printf("\tTimeout happened - Write did not go through the BFM -- Diagnose\n"); i2c_stop(); //~ return EREMOTEIO; } if (status & I2C_SHAKTI_LRB) { // What error is this? i2c_stop();//~ printf("\tSome status check failing\n"); return EREMOTEIO; } } if (last){ printf("\tLast byte sent : Issue a stop\n"); i2c_stop(); } else{ printf("\tSending Rep Start and doing some other R/W transaction\n"); if(!eni) i2c_repstart(); else i2c_repstart_eni(); } return wrcount; } #ifdef DEBUG int shakti_readbytes(char *buf, int count, int last) { int i, status; int wfp; int read_value = 0; /* increment number of bytes to read by one -- read dummy byte */ for (i = 0; i <= count; i++) { wfp = wait_for_pin(&status); if (wfp) { i2c_stop(); return -1; } if ((status & I2C_SHAKTI_LRB) && (i != count)) { i2c_stop(); printf("\tNo ack\n"); return -1; } if (i) { buf[i - 1] = get_i2c_shakti(i2c_data); printf("\n Read Value: %x", buf[i - 1]); } else get_i2c_shakti(i2c_data); /* dummy read */ if (i == count - 1) { set_i2c_shakti(i2c_control, I2C_SHAKTI_ESO); } else if (i == count) { if (last) i2c_stop(); else i2c_repstart(); } } return i-1; //excluding the dummy read } #endif /************************************************************************ * Brief Description : Performs the i2c protocol configuration. * Parameters : prescalar clock,serial clock. * Return : int. *************************************************************************/ int i2c_configure(int psc, int sclkFrequency) { unsigned char temp = 0; printf("\n\tI2C: Initializing the Controller"); set_i2c_shakti(i2c_prescale, psc); /* Setting Prescaler Clock */ //Setting the I2C clock value to be 1, which will set the clock for module and prescaler clock // #ifdef DEBUG /* Verify the above written psc value */ temp = get_i2c_shakti(i2c_prescale);//copies the prescalar clock value to the temp variable// if(temp != psc) { printf("\n\t Error in setting prescaler clock; Wr. Value: 0x%02x; Read Value: 0x%02x", psc, temp); } else { printf("\n\t Prescaler value is written successfully\n"); } #endif set_i2c_shakti(i2c_scl, sclkFrequency);/* Set I2C Serial clock frequency */ #ifdef DEBUG /* Verify the above written serial clock value */ temp = get_i2c_shakti(i2c_scl); /* Just reading the written value to see if all is well -- Compiler should not optimize this load!!! Compiler can just optimize the store to pointer address followed by load pointer to a register to just an immediate load to the register since clock register is not used anywhere -- but the purpose is lost. Don't give compiler optimizations */ if(temp != sclkFrequency){/*if prescalar clock is not equal to serial clock*/ printf("\n\tClock initialization failed Write Value: 0x%02x; read Value: 0x%02x", sclkFrequency, temp); return -ENXIO; } else{ printf("\tClock successfully initalized\n"); } #endif #ifdef DEBUG printf("\tSetting Control Register with 0x01 \n"); set_i2c_shakti(i2c_control, 0x01); // Reading set control Register Value to ensure sanctity// temp = get_i2c_shakti(i2c_control);//copies the i2c control variable to temp// printf("\tControl Register Read Value 0x%x \n", temp); #endif /* S1=0x80 S0 selected, serial interface off */ printf("\tSetting Control Register with 0x80 \n"); set_i2c_shakti(i2c_control, I2C_SHAKTI_PIN); #ifdef DEBUG printf("\tControl Register Successfully set \n"); // Reading set control Register Value to ensure sanctity // printf("\tReading Control Register \n"); temp = get_i2c_shakti(i2c_control); printf("\tControl Register is Written with 0x%x \n", temp); #endif if((temp & 0x7f) != 0){ printf("\tDevice Not Recognized\n"); return -ENXIO; } printf("\tWaiting for a specified time\n "); waitfor(900); //1 Second software wait -- Should be 900000 but setting to 900 now since simulation is already slow printf("\tDone Waiting \n "); i2c_stop(); /* Enable Serial Interface */ printf("\n Making the I2C chip in idle State"); set_i2c_shakti(i2c_control, I2C_SHAKTI_IDLE); printf("\n\tWaiting for a specified time After setting idle\n "); waitfor(900); //1 Second software wait -- Should be 900000 but setting to 900 now since simulation is already slow printf("\tDone Waiting \n "); #ifdef DEBUG temp = get_i2c_shakti(i2c_status); printf("\tStatus Reg value is : 0x%x \n",temp); #endif /* Check to see if I2C is really in Idle and see if we can access the status register.This also verifies if Control is properly written since zero bit will be initialized to zero */ if(temp != (I2C_SHAKTI_PIN | I2C_SHAKTI_BB)){ printf("\tInitialization failed\n"); return -ENXIO; } printf("\tI2C successfully initialized\n"); } /************************************************************************ * Brief Description : Performs the intilization of i2c slave. * Parameters : slave address. * Return : int. *************************************************************************/ int i2c_slave_init(unsigned char slaveAddress) { int timeout; unsigned char temp = 0; int status = 0; printf("\n\tSetting Slave Address : 0x%02x\n", slaveAddress);/* Writes the slave address to I2C controller */ set_i2c_shakti(i2c_data,slaveAddress); printf("\tSlave Address set\n"); temp = get_i2c_shakti(i2c_data); //Reads the slave address from I2C controller printf("\tSet slave address read again, which is 0x%x\n",temp); if(slaveAddress != (int)temp) printf("\tSlave address is not matching; Written Add. Value: 0x%02x; Read Add. Value: 0x%02x\n", slaveAddress, temp); i2c_start(); //Sending the slave address to the I2C slave timeout = wait_for_pin(&status); if (timeout) {//Asking the controller to send a start signal to initiate the transaction printf("\tTimeout happened - Write did not go through the BFM -- Diagnose\n"); i2c_stop(); //~ return EREMOTEIO; } if (status & I2C_SHAKTI_LRB) { i2c_stop(); printf("\tSome status check failing\n"); } } /************************************************************************ * Brief Description : It does the reading or writing from the address specified . * Parameters : starting address. * Return : int. *************************************************************************/ int SendAddressToReadOrWrite(unsigned int startAddress) { int timeout; unsigned char temp = 0; int status = 0; #ifdef _16Bit set_i2c_shakti(i2c_data, (startAddress >> 8) & 0xFF); timeout = wait_for_pin(&status); if (timeout) { printf("\tTimeout happened - Write did not go through the BFM -- Diagnose\n"); i2c_stop(); //~ return EREMOTEIO; } if (status & I2C_SHAKTI_LRB) { // What error is this? i2c_stop();//~ printf("\tSome status check failing\n"); return EREMOTEIO; } #endif set_i2c_shakti(i2c_data, (startAddress >> 0) & 0xFF); timeout = wait_for_pin(&status); if (timeout) { printf("\tTimeout happened - Write did not go through the BFM -- Diagnose\n"); i2c_stop(); //~ return EREMOTEIO; } if (status & I2C_SHAKTI_LRB) { // What error is this? i2c_stop();//~ printf("\tSome status check failing\n"); } } /************************************************************************ * Brief Description : It does the reading or writing from the address specified . * Parameters : starting address. * Return : int. *************************************************************************/ int i2c_rw_wait(int *status) { int timeout = DEF_TIMEOUT; *status = get_i2c_shakti(i2c_status); while ((*status & I2C_SHAKTI_PIN) && --timeout) { waitfor(10000); /* wait for 100 us */ *status = get_i2c_shakti(i2c_status); } if (timeout == 0){ printf("\tWait for pin timed out\n"); return ETIMEDOUT; } return 0; } /************************************************************************** * Brief Description : This makes the read or write operation to wait until the count has been completed . * Parameters : count value. * Return : int. *************************************************************************/ int i2c_datawrite( const char *buf, int count, int last, int eni) { int wrcount, status, timeout; int i = 0; printf("\tStarting Write Transaction -- Did you create tri1 nets for SDA and SCL in verilog?\n"); for (i = 0; i < count; ++i) { printf("\n\t Writing the value 0x%02x into EEPROM", buf[i]); set_i2c_shakti(i2c_data, buf[i]); if( ETIMEDOUT == i2c_rw_wait(&status)) { printf("\n I2C Write Timed out"); i2c_stop(); //~ return EREMOTEIO; } if (status & I2C_SHAKTI_LRB) { i2c_stop();//~ printf("\tSome status check failing\n"); return EREMOTEIO; } } if (last){ printf("\n\tLast byte sent : Issue a stop\n"); i2c_stop(); } else { printf("\n\tSending Rep Start and doing some other R/W transaction\n"); if(!eni) i2c_repstart(); else i2c_repstart_eni(); } return i; } /************************************************************************ * Brief Description : It does the data reading. * Parameters : count value,ending address. * Return : int. *************************************************************************/ int i2c_dataread(char *buf, int count, int last) { int i, status; int wfp; int read_value = 0; /* increment number of bytes to read by one -- read dummy byte */ for (i = -1; i < count; i++) { if( ETIMEDOUT == i2c_rw_wait(&status)) { printf("\n I2C Read Timed out"); i2c_stop(); return EREMOTEIO; } if (status & I2C_SHAKTI_LRB) { i2c_stop();//~ printf("\tSome status check failing\n"); return EREMOTEIO; } if (-1 != i)//Do Dummy Read initially// { buf[i] = get_i2c_shakti(i2c_data); printf("\n\t Read Address Offset: %d; Value: %x", i, buf[i]); } else { printf("\n\t Dummy Read Value: 0x%02x", get_i2c_shakti(i2c_data) & 0xFF ); /* dummy read */ } if (i == count - 2)/*send NACK after the penultimate byte*/ { i2c_nack(); waitfor(10000); } if (i == count - 1) /*send STOP after the last byte*/ { waitfor(10000); i2c_stop(); } } printf("\n\t Read %d Bytes from EEPROM", i); return i; //excluding the dummy read }
2.296875
2
2024-11-18T20:59:23.580451+00:00
2021-12-03T17:17:27
2c7cc61ca6de4f14572574e38d5e0eb8e4c22e79
{ "blob_id": "2c7cc61ca6de4f14572574e38d5e0eb8e4c22e79", "branch_name": "refs/heads/master", "committer_date": "2021-12-03T17:17:27", "content_id": "811a51f00fbadf4324951c3d78adc7c5f40de5e6", "detected_licenses": [ "MIT" ], "directory_id": "0b8d21a7c109993fa650222adfaf238fdea497fd", "extension": "c", "filename": "librtemgr.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 161608735, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 25417, "license": "MIT", "license_type": "permissive", "path": "/src/rtemgr/librtemgr.c", "provenance": "stackv2-0135.json.gz:234862", "repo_name": "raitosyo/rteipc", "revision_date": "2021-12-03T17:17:27", "revision_id": "a5c99219b5e11a486b449bc1ea07015e3541b62c", "snapshot_id": "3ac2a8ffa7450e08b2b30e85edf5a73ed104b8a0", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/raitosyo/rteipc/a5c99219b5e11a486b449bc1ea07015e3541b62c/src/rtemgr/librtemgr.c", "visit_date": "2021-12-16T14:44:00.394640" }
stackv2
// Copyright (c) 2021 Ryosuke Saito All rights reserved. // MIT licensed #include <stdio.h> #include <stdlib.h> #include <string.h> #include <getopt.h> #include <yaml.h> #include <b64/cencode.h> #include <b64/cdecode.h> #include "rtemgr-common.h" /** * Allocate new interface and return a pointer to it. */ rtemgr_intf *rtemgr_data_alloc_interface(rtemgr_data *d) { rtemgr_intf *intf; int newsize = d->nr_intf + 1; int i = d->nr_intf; intf = realloc(d->interfaces, sizeof(*intf) * newsize); if (!intf) return NULL; intf[i].id = -1; memset(intf[i].name, 0, sizeof(intf[i].name)); intf[i].domain = 0; intf[i].bus_type = -1; memset(intf[i].path, 0, sizeof(intf[i].path)); intf[i].managed = 0; memset(intf[i].partner, 0, sizeof(intf[i].partner)); d->nr_intf = newsize; d->interfaces = intf; return &intf[i]; } /* Remove interface and return remaining number of interfaces */ int rtemgr_data_remove_interface(rtemgr_data *d) { if (!d) return 0; if (d->nr_intf) { d->nr_intf--; if (!d->nr_intf) { free(d->interfaces); d->interfaces = NULL; } } return d->nr_intf; } void rtemgr_data_cleanup_interfaces(rtemgr_data *d) { while (rtemgr_data_remove_interface(d)); } /** * Allocate memory for rtemgr_data. * rtemgr_data_free must be called after use of it. */ rtemgr_data *rtemgr_data_alloc(void) { return calloc(1, sizeof(rtemgr_data)); } /** * Free rtemgr_data memory allocated by rtemgr_data_alloc. * * NOTE: * Do not set the pointer to a buffer that is later released in eventloop of * rteipc core into cmd.val.v. Otherwise, a double free error will happen. */ void rtemgr_data_free(rtemgr_data *d) { if (d) { free(d->cmd.val.v); rtemgr_data_cleanup_interfaces(d); free(d); } } static inline void encode_base64(char *out, void *data, size_t size) { char *p = out; int cnt; base64_encodestate s; base64_init_encodestate(&s); cnt = base64_encode_block(data, size, p, &s); p += cnt; cnt = base64_encode_blockend(p, &s); p += cnt; *p = '\0'; } static inline int decode_base64(void *out, char *in) { char *p = out; base64_decodestate s; base64_init_decodestate(&s); return base64_decode_block(in, strlen(in), p, &s); } /** * Convert rtemgr_data to yaml formatted string. * * Return 0 on success, -1 on failure. */ int rtemgr_data_emit(const rtemgr_data *d, unsigned char *output, size_t size, size_t *written) { yaml_emitter_t emitter; yaml_event_t event; char *buf, *tmp; size_t allocated = 0, block = 4096, padding = 256, estimated; int i, j; /* First allocate 4kb buffer */ allocated = block; if (!(buf = malloc(allocated))) return -1; yaml_emitter_initialize(&emitter); yaml_emitter_set_output_string(&emitter, output, size, written); //- type: STREAM-START yaml_stream_start_event_initialize(&event, YAML_UTF8_ENCODING); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: DOCUMENT-START yaml_document_start_event_initialize(&event, NULL, NULL, NULL, 1); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: MAPPING-START yaml_mapping_start_event_initialize(&event, NULL, (yaml_char_t *)YAML_MAP_TAG, 1, YAML_BLOCK_MAPPING_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR "cmd" yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)"cmd", -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SEQUENCE-START yaml_sequence_start_event_initialize(&event, NULL, (yaml_char_t *)YAML_SEQ_TAG, 1, YAML_BLOCK_SEQUENCE_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: MAPPING-START yaml_mapping_start_event_initialize(&event, NULL, (yaml_char_t *)YAML_MAP_TAG, 1, YAML_BLOCK_MAPPING_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR "action" yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)"action", -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR snprintf(buf, allocated, "%d", d->cmd.action); yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)buf, -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR "error" yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)"error", -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR snprintf(buf, allocated, "%d", d->cmd.error); yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)buf, -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR "val" yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)"val", -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SEQUENCE-START yaml_sequence_start_event_initialize(&event, NULL, (yaml_char_t *)YAML_SEQ_TAG, 1, YAML_BLOCK_SEQUENCE_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: MAPPING-START yaml_mapping_start_event_initialize(&event, NULL, (yaml_char_t *)YAML_MAP_TAG, 1, YAML_BLOCK_MAPPING_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR "v" yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)"v", -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR estimated = (((4 * d->cmd.val.s / 3) + 3) & ~3) + padding; if (d->cmd.val.v && estimated > allocated) { allocated = block * ((estimated + block - 1) / block); if (!(tmp = realloc(buf, allocated))) goto error; buf = tmp; } encode_base64(buf, d->cmd.val.v, d->cmd.val.s); yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)"tag:yaml.org,2002:binary", (yaml_char_t *)buf, -1, 0, 0, YAML_LITERAL_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR "s" yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)"s", -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR snprintf(buf, allocated, "%u", d->cmd.val.s); yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)buf, -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR "extra" yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)"extra", -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SEQUENCE-START yaml_sequence_start_event_initialize(&event, NULL, (yaml_char_t *)YAML_SEQ_TAG, 1, YAML_BLOCK_SEQUENCE_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: MAPPING-START yaml_mapping_start_event_initialize(&event, NULL, (yaml_char_t *)YAML_MAP_TAG, 1, YAML_BLOCK_MAPPING_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR "addr" yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)"addr", -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR snprintf(buf, allocated, "%u", d->cmd.val.extra.addr); yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)buf, -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR "rsize" yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)"rsize", -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR snprintf(buf, allocated, "%u", d->cmd.val.extra.rsize); yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)buf, -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: MAPPING-END yaml_mapping_end_event_initialize(&event); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SEQUENCE-END "extra" yaml_sequence_end_event_initialize(&event); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: MAPPING-END yaml_mapping_end_event_initialize(&event); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SEQUENCE-END "val" yaml_sequence_end_event_initialize(&event); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: MAPPING-END yaml_mapping_end_event_initialize(&event); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SEQUENCE-END "cmd" yaml_sequence_end_event_initialize(&event); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR "nr_intf" yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)"nr_intf", -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR snprintf(buf, allocated, "%d", d->nr_intf); yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)buf, -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR "interfaces" yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)"interfaces", -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SEQUENCE-START yaml_sequence_start_event_initialize(&event, NULL, (yaml_char_t *)YAML_SEQ_TAG, 1, YAML_BLOCK_SEQUENCE_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; for (i = 0; i < d->nr_intf; i++) { //- type: MAPPING-START yaml_mapping_start_event_initialize(&event, NULL, (yaml_char_t *)YAML_MAP_TAG, 1, YAML_BLOCK_MAPPING_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR "id" yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)"id", -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR snprintf(buf, allocated, "%d", d->interfaces[i].id); yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)buf, -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR "bus_type" yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)"bus_type", -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR snprintf(buf, allocated, "%d", d->interfaces[i].bus_type); yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)buf, -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR "name" yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)"name", -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR snprintf(buf, allocated, "%s", d->interfaces[i].name); yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)buf, -1, 0, 1, YAML_DOUBLE_QUOTED_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR "path" yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)"path", -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR snprintf(buf, allocated, "%s", d->interfaces[i].path); yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)buf, -1, 0, 1, YAML_DOUBLE_QUOTED_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR "domain" yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)"domain", -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR snprintf(buf, allocated, "%d", d->interfaces[i].domain); yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)buf, -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR "managed" yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)"managed", -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR snprintf(buf, allocated, "%d", d->interfaces[i].managed); yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)buf, -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR "partner" yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)"partner", -1, 1, 0, YAML_PLAIN_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: SCALAR snprintf(buf, allocated, "%s", d->interfaces[i].partner); yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)buf, -1, 0, 1, YAML_DOUBLE_QUOTED_SCALAR_STYLE); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: MAPPING-END yaml_mapping_end_event_initialize(&event); if (!yaml_emitter_emit(&emitter, &event)) goto error; } //- type: SEQUENCE-END yaml_sequence_end_event_initialize(&event); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: MAPPING-END yaml_mapping_end_event_initialize(&event); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: DOCUMENT-END yaml_document_end_event_initialize(&event, 1); if (!yaml_emitter_emit(&emitter, &event)) goto error; //- type: STREAM-END yaml_stream_end_event_initialize(&event); if (!yaml_emitter_emit(&emitter, &event)) goto error; yaml_emitter_delete(&emitter); return 0; error: yaml_emitter_delete(&emitter); free(buf); return -1; } /* * Parse yaml formatted data and convert it to rtemgr_data. * * Return a pointer to rtemgr_data on success, otherwise NULL. * Caller must invoke rtemgr_data_free() to properly free it. */ rtemgr_data *rtemgr_data_parse(const unsigned char *input, size_t size) { yaml_parser_t parser; yaml_event_t event; yaml_token_t token; yaml_char_t *value; rtemgr_data *d; rtemgr_intf *intf; int done = 0; int seq_nest = 0, field_start = 0; int idx_intf = 0; int nr_intf; void *tmp; enum { TOP_LEVEL, // rtemgr_data.cmd.* CMD, // rtemgr_data.cmd.val.* VAL, // rtemgr_data.cmd.val.extra* EXT, // rtemgr_data.interfaces[] INTF } field = TOP_LEVEL; enum { ITEM_NONE, // nr_intf NR_INTF, // cmd.action CMD_ACT, // cmd.error CMD_ERR, // cmd.val.v VAL_V, // cmd.val.s VAL_S, // cmd.val.extra.addr EXT_ADDR, // cmd.val.extra.rsize EXT_RSIZE, // interfaces[].id INTF_ID, // interfaces[].bus_type INTF_BUS, // interfaces[].name INTF_NAME, // interfaces[].path INTF_PATH, // interfaces[].domain INTF_DOM, // interfaces[].managed INTF_MANAGED, // interfaces[].partner INTF_PARTNER, } item = ITEM_NONE; if (!(d = rtemgr_data_alloc())) return NULL; yaml_parser_initialize(&parser); yaml_parser_set_input_string(&parser, input, size); while (!done) { if (!yaml_parser_parse(&parser, &event)) goto error; done = (event.type == YAML_STREAM_END_EVENT); switch (event.type) { case YAML_SEQUENCE_START_EVENT: seq_nest++; break; case YAML_SEQUENCE_END_EVENT: seq_nest--; if (seq_nest <= field_start) field = TOP_LEVEL; if (field == VAL) field = CMD; if (field == EXT) field = VAL; break; case YAML_MAPPING_START_EVENT: break; case YAML_MAPPING_END_EVENT: if (field == INTF) idx_intf++; break; case YAML_SCALAR_EVENT: value = event.data.scalar.value; if (field == TOP_LEVEL && item == ITEM_NONE) { /* NOTE: "nr_intf" must appear before "interfaces" */ if (strmatch(value, "nr_intf")) { item = NR_INTF; break; } if (strmatch(value, "cmd")) { field = CMD; } else if (strmatch(value, "interfaces")) { field = INTF; } field_start = seq_nest; break; } switch (field) { case TOP_LEVEL: switch (item) { case NR_INTF: nr_intf = strtoul(value, NULL, 0); while (nr_intf > d->nr_intf) { if (!rtemgr_data_alloc_interface(d)) goto error; } intf = d->interfaces; break; } item = ITEM_NONE; break; case CMD: if (item == ITEM_NONE) { if (strmatch(value, "action")) { item = CMD_ACT; } else if (strmatch(value, "error")) { item = CMD_ERR; } else if (strmatch(value, "val")) { field = VAL; } } else { switch (item) { case CMD_ACT: d->cmd.action = strtoul(value, NULL, 0); break; case CMD_ERR: d->cmd.error = strtoul(value, NULL, 0); break; } item = ITEM_NONE; } break; case VAL: if (item == ITEM_NONE) { if (strmatch(value, "v")) { item = VAL_V; } else if (strmatch(value, "s")) { item = VAL_S; } else if (strmatch(value, "extra")) { field = EXT; } } else { switch (item) { case VAL_V: d->cmd.val.v = strdup(value); break; case VAL_S: d->cmd.val.s = strtoul(value, NULL, 0); break; } item = ITEM_NONE; } break; case EXT: if (item == ITEM_NONE) { if (strmatch(value, "addr")) { item = EXT_ADDR; } else if (strmatch(value, "rsize")) { item = EXT_RSIZE; } } else { switch (item) { case EXT_ADDR: d->cmd.val.extra.addr = strtoul(value, NULL, 0); break; case EXT_RSIZE: d->cmd.val.extra.rsize = strtoul(value, NULL, 0); break; } item = ITEM_NONE; } break; case INTF: if (item == ITEM_NONE) { if (strmatch(value, "id")) { item = INTF_ID; } else if (strmatch(value, "bus_type")) { item = INTF_BUS; } else if (strmatch(value, "name")) { item = INTF_NAME; } else if (strmatch(value, "path")) { item = INTF_PATH; } else if (strmatch(value, "domain")) { item = INTF_DOM; } else if (strmatch(value, "managed")) { item = INTF_MANAGED; } else if (strmatch(value, "partner")) { item = INTF_PARTNER; } } else { switch (item) { case INTF_ID: intf[idx_intf].id = strtoul(value, NULL, 0); break; case INTF_BUS: intf[idx_intf].bus_type = strtoul(value, NULL, 0); break; case INTF_NAME: strncpy(intf[idx_intf].name, value, sizeof(((rtemgr_intf *)0)->name)); break; case INTF_PATH: strncpy(intf[idx_intf].path, value, sizeof(((rtemgr_intf *)0)->path)); break; case INTF_DOM: intf[idx_intf].domain = strtoul(value, NULL, 0); break; case INTF_MANAGED: intf[idx_intf].managed = strtoul(value, NULL, 0); break; case INTF_PARTNER: strncpy(intf[idx_intf].partner, value, sizeof(((rtemgr_intf *)0)->partner)); break; } item = ITEM_NONE; } break; } break; } yaml_event_delete(&event); } /* Decode base64 string to binary data */ if (d->cmd.val.s && d->cmd.val.v) { tmp = malloc(d->cmd.val.s); if (!tmp) goto error; decode_base64(tmp, d->cmd.val.v); free(d->cmd.val.v); d->cmd.val.v = tmp; } yaml_parser_delete(&parser); return d; error: rtemgr_data_free(d); yaml_parser_delete(&parser); return NULL; } static inline int __rtemgr_encode_domain(int domain, const char *name, const struct rtecmd *cmd, void **out, size_t *len) { rtemgr_data *d; rtemgr_intf *intf; unsigned char *buf; size_t bufsz, written; d = rtemgr_data_alloc(); if (!d) return -1; intf = rtemgr_data_alloc_interface(d); if (!intf) goto free; memcpy(&d->cmd, cmd, sizeof(*cmd)); d->cmd.action = RTECMD_XFER; intf->domain = domain; strncpy(intf->name, name, sizeof(intf->name)); bufsz = cmd->val.s * 3 / 2; if (bufsz < 512) bufsz = 512; buf = malloc(bufsz); if (!buf) goto free; if (rtemgr_data_emit(d, buf, bufsz, &written)) goto free; *out = buf; *len = written; return 0; free: rtemgr_data_free(d); return -1; } int rtemgr_encode_domain(int domain, const char *name, const void *data, size_t len, void **out, size_t *written) { struct rtecmd cmd = {0}; if (!data || !len) return -1; cmd.val.s = len; cmd.val.v = malloc(len); if (!cmd.val.v) return -1; memcpy(cmd.val.v, data, len); return __rtemgr_encode_domain(domain, name, &cmd, out, written); } int rtemgr_gpio_encode_domain(int domain, const char *name, uint8_t value, void **out, size_t *written) { return rtemgr_encode_domain(domain, name, value ? "1" : "0", 1, out, written); } int rtemgr_spi_encode_domain(int domain, const char *name, const uint8_t *data, uint16_t len, bool rdmode, void **out, size_t *written) { struct rtecmd cmd = {0}; struct evbuffer *buf; int i; if (!data || !len) return -1; buf = evbuffer_new(); if (!buf) return -1; for (i = 0; i < len; i++) evbuffer_add_printf(buf, "0x%02x ", data[i]); cmd.val.s = evbuffer_get_length(buf) - 1; cmd.val.v = malloc(cmd.val.s); if (!cmd.val.v) { evbuffer_free(buf); return -1; } cmd.val.extra.rsize = rdmode ? len : 0; evbuffer_remove(buf, cmd.val.v, cmd.val.s); evbuffer_free(buf); return __rtemgr_encode_domain(domain, name, &cmd, out, written); } int rtemgr_i2c_encode_domain(int domain, const char *name, uint16_t addr, const uint8_t *data, uint16_t wlen, uint16_t rlen, void **out, size_t *written) { struct rtecmd cmd = {0}; struct evbuffer *buf; int i; if (!wlen && !rlen || (wlen && !data)) return -1; buf = evbuffer_new(); if (!buf) return -1; for (i = 0; i < wlen; i++) evbuffer_add_printf(buf, "0x%02x ", data[i]); if (evbuffer_get_length(buf)) cmd.val.s = evbuffer_get_length(buf) - 1; if (cmd.val.s) { cmd.val.v = malloc(cmd.val.s); if (!cmd.val.v) { evbuffer_free(buf); return -1; } evbuffer_remove(buf, cmd.val.v, cmd.val.s); } cmd.val.extra.addr = addr; cmd.val.extra.rsize = rlen; evbuffer_free(buf); return __rtemgr_encode_domain(domain, name, &cmd, out, written); } int rtemgr_sysfs_encode_domain(int domain, const char *name, const char *attr, const char *newval, void **out, size_t *written) { struct rtecmd cmd = {0}; char buf[256]; if (!attr) return -1; if (newval) snprintf(buf, sizeof(buf), "%s=%s", attr, newval); else snprintf(buf, sizeof(buf), "%s", attr); return rtemgr_encode_domain(domain, name, buf, strlen(buf), out, written); } int rtemgr_send_domain(int ctx, int domain, const char *name, const void *data, size_t len) { void *out; size_t written; int err; err = rtemgr_encode_domain(domain, name, data, len, &out, &written); if (err) return err; return rteipc_send(ctx, out, written); } int rtemgr_gpio_send_domain(int ctx, int domain, const char *name, uint8_t value) { return rtemgr_send_domain(ctx, domain, name, value ? "1" : "0", 1); } int rtemgr_spi_send_domain(int ctx, int domain, const char *name, const uint8_t *data, uint16_t len, bool rdmode) { void *out; size_t written; int err; err = rtemgr_spi_encode_domain(domain, name, data, len, rdmode, &out, &written); if (err) return err; return rteipc_send(ctx, out, written); } int rtemgr_i2c_send_domain(int ctx, int domain, const char *name, uint16_t addr, const uint8_t *data, uint16_t wlen, uint16_t rlen) { void *out; size_t written; int err; err = rtemgr_i2c_encode_domain(domain, name, addr, data, wlen, rlen, &out, &written); if (err) return err; return rteipc_send(ctx, out, written); } int rtemgr_sysfs_send_domain(int ctx, int domain, const char *name, const char *attr, const char *newval) { void *out; size_t written; int err; err = rtemgr_sysfs_encode_domain(domain, name, attr, newval, &out, &written); if (err) return err; return rteipc_send(ctx, out, written); } rtemgr_data *rtemgr_decode(const unsigned char *data, size_t len) { rtemgr_data *d = rtemgr_data_parse(data, len); if (!d || !d->interfaces) return NULL; return d; } void rtemgr_put_dh(rtemgr_data *d) { rtemgr_data_free(d); } void *rtemgr_get_data(const rtemgr_data *d) { return d->cmd.val.v; } size_t rtemgr_get_length(const rtemgr_data *d) { return d->cmd.val.s; } char *rtemgr_get_name(const rtemgr_data *d) { if (!d->interfaces) return NULL; return d->interfaces->name; } int rtemgr_get_domain(const rtemgr_data *d) { if (!d->interfaces) return -1; return d->interfaces->domain; } int rtemgr_get_type(const rtemgr_data *d) { if (!d->interfaces) return -1; return d->interfaces->bus_type; }
2.390625
2
2024-11-18T20:59:23.663050+00:00
2015-09-04T20:03:04
05e8675c559f422355d8e20680c3b16b5cfc797a
{ "blob_id": "05e8675c559f422355d8e20680c3b16b5cfc797a", "branch_name": "refs/heads/master", "committer_date": "2015-09-04T20:03:04", "content_id": "75463fe5a2caa890b7a4d3fef9cbaad899e58d50", "detected_licenses": [ "MIT" ], "directory_id": "c7e3c7614b2e12a37c55adcae2b210bce66f2dde", "extension": "c", "filename": "util.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 722, "license": "MIT", "license_type": "permissive", "path": "/trabalho2/util.c/util.c", "provenance": "stackv2-0135.json.gz:234991", "repo_name": "PHMarpin/pca", "revision_date": "2015-09-04T20:03:04", "revision_id": "40af7eea2855546315f0a3e2589840b8bd0db528", "snapshot_id": "d353a9e1f4d27abe6b77a89e99d7ddecbbfa17a2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/PHMarpin/pca/40af7eea2855546315f0a3e2589840b8bd0db528/trabalho2/util.c/util.c", "visit_date": "2021-01-21T00:25:03.765951" }
stackv2
/* * Função para calcular a potencia * recebe dois inteiros x e z * e retorna um inteiro pot */ int calc_pow(int x, int z) { int i, pot; pot=1; for ( i = 0; i < z; i++ ) { pot*=x; } return pot; } /* Faz a contagem de numero inteiros digitados * Ex: 1234 a função retornará 4 * 0 a função retornará 1 * -999 a função retornará 3 */ int qtd_num(int num) { int contador; if ( num != 0 ) { if ( num < 0 ) { num = num*(-1); } for ( contador = 0; num > 0 ; contador++ ) { num = num / 10; } return contador; }else { return 1; } }
3.890625
4
2024-11-18T20:59:23.936228+00:00
2020-09-20T17:06:23
2fcab4dcf30b27657906cf273ecece24626c9888
{ "blob_id": "2fcab4dcf30b27657906cf273ecece24626c9888", "branch_name": "refs/heads/master", "committer_date": "2020-09-20T17:06:27", "content_id": "b57d2228fdceca812ddc99100c822f433256660f", "detected_licenses": [ "MIT" ], "directory_id": "09da695312561f2dfbf98faa172ff68bd1012f93", "extension": "c", "filename": "main.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 287036346, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 945, "license": "MIT", "license_type": "permissive", "path": "/fade_led/src/main.c", "provenance": "stackv2-0135.json.gz:235383", "repo_name": "tuannv0898/zephyr-pca10040", "revision_date": "2020-09-20T17:06:23", "revision_id": "46707525e40ac3ed311d1eec8c89e5af2c79cef0", "snapshot_id": "ddab5114b6cd9f08d4c91b641d72709268743083", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tuannv0898/zephyr-pca10040/46707525e40ac3ed311d1eec8c89e5af2c79cef0/fade_led/src/main.c", "visit_date": "2022-12-18T05:43:53.698363" }
stackv2
#include <zephyr.h> #include <sys/printk.h> #include <device.h> #include <drivers/pwm.h> #define FLAGS_OR_ZERO(node) \ COND_CODE_1(DT_PHA_HAS_CELL(node, pwms, flags), (DT_PWMS_FLAGS(node)), (0)) #define PWM_NODE DT_ALIAS(pwm_led0) #define PWM_LABEL DT_PWMS_LABEL(PWM_NODE) #define PWM_CHANNEL DT_PWMS_CHANNEL(PWM_NODE) #define PWM_FLAGS FLAGS_OR_ZERO(PWM_NODE) #define PERIOD_MS 1000 void main(void) { struct device *dev_pwm; uint32_t pulse = 0; uint8_t dir = 1; int ret; printk("PWM-based blinky\n"); dev_pwm = device_get_binding(PWM_LABEL); if (!dev_pwm) { printk("Error: didn't find %s device\n", PWM_LABEL); return; } while(1){ ret = pwm_pin_set_usec(dev_pwm, PWM_CHANNEL, PERIOD_MS, pulse, PWM_FLAGS); if (ret) { printk("Error %d: failed to set pulse width\n", ret); return; } pulse = dir ? (pulse + 1) : (pulse - 1); if(pulse==0 || pulse==PERIOD_MS) dir = !dir; k_sleep(K_MSEC(1U)); } }
2.578125
3
2024-11-18T20:59:24.451827+00:00
2021-01-12T18:00:14
916b9126c29cea48898395694384f4a7b108eb21
{ "blob_id": "916b9126c29cea48898395694384f4a7b108eb21", "branch_name": "refs/heads/main", "committer_date": "2021-01-12T18:00:14", "content_id": "1caa7241983dea32a629a79164a3c3bb5d24e4f2", "detected_licenses": [ "MIT" ], "directory_id": "d172b51811fe8555470792dd13ce02ed4787ed25", "extension": "h", "filename": "console.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 329069563, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 924, "license": "MIT", "license_type": "permissive", "path": "/Skeleton_code/LanderController-assessment/console.h", "provenance": "stackv2-0135.json.gz:235644", "repo_name": "sohaib3335/LanderDash-LunarLander-ControllerSkeletoncode-Demo", "revision_date": "2021-01-12T18:00:14", "revision_id": "3c83877a69ad25c96a6048fadf9bf8aea289ea0f", "snapshot_id": "293d2b9661d4d553f0c5ec704a0e317c3c7dabd2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sohaib3335/LanderDash-LunarLander-ControllerSkeletoncode-Demo/3c83877a69ad25c96a6048fadf9bf8aea289ea0f/Skeleton_code/LanderController-assessment/console.h", "visit_date": "2023-02-14T02:06:10.568949" }
stackv2
#ifndef _CONSOLE_H #define _CONSOLE_H /* some constants */ #include <curses.h> int console_init(void); /* initialise LCD return sucess/fail */ /* LCD api */ void lcd_set_pos(int row, int column); /* 0x00-0x07: standard colors (as in ESC [ 30–37 m) 0x08-0x0F: high intensity colors (as in ESC [ 90–97 m) 0x10-0xE7: 6 × 6 × 6 cube (216 colors): 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5) 0xE8-0xFF: grayscale from black to white in 24 steps */ void lcd_set_colour(int foreground, int background); void lcd_set_attr(int attributes); void lcd_unset_attr(int attributes); int lcd_write(const char *fmt,...); int lcd_write_at(int row, int col, const char *fmt,...); /* LED api */ typedef enum { LED_WHITE, LED_RED, LED_GREEN, LED_BLUE } leds_t; void led_on(leds_t led); void led_off(leds_t led); void led_toggle(leds_t led); /* Button api */ int is_pressed(int button); int key_pressed(void); #endif
2.265625
2
2024-11-18T20:59:24.918165+00:00
2021-12-21T11:57:14
eb7b4b6cad88508880917f4712ef43ddce41f968
{ "blob_id": "eb7b4b6cad88508880917f4712ef43ddce41f968", "branch_name": "refs/heads/master", "committer_date": "2021-12-21T11:57:14", "content_id": "6039e4d9727bac1193745d543516ef54e8e5a859", "detected_licenses": [ "MIT" ], "directory_id": "4044aab7716c8b4c707994beb481a0789a3a68a5", "extension": "c", "filename": "uri-buffer.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 34686283, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1527, "license": "MIT", "license_type": "permissive", "path": "/2015/1/uri-buffer.c", "provenance": "stackv2-0135.json.gz:235904", "repo_name": "greuze/tuenti-challenge", "revision_date": "2021-12-21T11:57:14", "revision_id": "1173204fb5d94b08b59ea5b2a6140af9ad9f87d4", "snapshot_id": "ebe8ea876bdf5efcaa63cb42ffb05c83d37dbfd3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/greuze/tuenti-challenge/1173204fb5d94b08b59ea5b2a6140af9ad9f87d4/2015/1/uri-buffer.c", "visit_date": "2021-12-24T18:48:39.523355" }
stackv2
/* * To compile in command line with gcc can be used: * * gcc -o uri-buffer uri-buffer.c -lm * * In Eclipse: * * Properties -> C/C++ Build -> Setting -> GCC C++ Linker -> Libraries -> In top part add "m" */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <errno.h> void readInputFile(const char *filename, int *n, unsigned long **cases) { FILE * fp; char * line = NULL; size_t len = 0; ssize_t read; fp = fopen(filename, "r"); if (fp == NULL) { perror("Error opening input file.\n"); exit(EXIT_FAILURE); } read = getline(&line, &len, fp); sscanf(line, "%d", n); *cases = malloc(sizeof(unsigned long) * *n); // same as unsigned long cases[*n]; int i; for(i = 0; i < *n; i++) { read = getline(&line, &len, fp); unsigned long l; sscanf(line, "%lu", &l); *(*cases + i) = l; } // Free pointers to file and line fclose(fp); free(line); } void printOutput(int n, unsigned long *cases) { int i; for(i = 0; i < n; i++) { unsigned long s = (unsigned long) ceil(0.5 * *(cases + i)); // same as cases[i]/2 printf("%lu\n", s); } } int main(int argc, char **argv) { char* fileName; if (argc == 1) { // No parameters fileName = "testInput"; } else { fileName = argv[1]; } int numberOfCases; unsigned long *cases; readInputFile(fileName, &numberOfCases, &cases); printOutput(numberOfCases, cases); free(cases); return EXIT_SUCCESS; }
3.078125
3
2024-11-18T20:59:28.556171+00:00
2020-07-28T12:34:33
e7217d7eb7d738b0170a1f2083364f68f6042a8b
{ "blob_id": "e7217d7eb7d738b0170a1f2083364f68f6042a8b", "branch_name": "refs/heads/master", "committer_date": "2020-07-28T12:34:33", "content_id": "2fcc810bac65886950cae342d9deed3d949602ac", "detected_licenses": [ "MIT" ], "directory_id": "440c1f4e3ea79e660e7e5b320911ae61c6746527", "extension": "c", "filename": "testfcntl.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 50077825, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 240, "license": "MIT", "license_type": "permissive", "path": "/Desktop/c++/linuxcodeBook/chap5/testfcntl.c", "provenance": "stackv2-0135.json.gz:236426", "repo_name": "bloodycoder/sjtushare", "revision_date": "2020-07-28T12:34:33", "revision_id": "508d0baece13b732ed42fef1546b04fa7035dd82", "snapshot_id": "37d8675ccb79b79cb2a19ed176f32b7ffcb685a4", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/bloodycoder/sjtushare/508d0baece13b732ed42fef1546b04fa7035dd82/Desktop/c++/linuxcodeBook/chap5/testfcntl.c", "visit_date": "2021-07-15T22:17:08.317944" }
stackv2
#include <fcntl.h> #define FD 0 #define oops(s,x) { perror(s);exit(x);} int main(){ int s; s = fcntl(FD,F_GETFL); s |= O_SYNC; int result = fcntl(FD,F_SETFL,s); if(result == -1){ oops("setting SYNC",1); } }
2.296875
2
2024-11-18T20:59:28.693501+00:00
2021-04-13T14:15:00
f1e53c5b9541efb4ec9f00ad62b4441d04d8e2cd
{ "blob_id": "f1e53c5b9541efb4ec9f00ad62b4441d04d8e2cd", "branch_name": "refs/heads/master", "committer_date": "2021-04-13T14:15:00", "content_id": "0d7c45c2ea9032c3960a632d9ca762093ed0f66b", "detected_licenses": [ "MIT" ], "directory_id": "c5a28193198763d7f53973f93acdeb557c90c012", "extension": "h", "filename": "VMWareTypes.h", "fork_events_count": 0, "gha_created_at": "2020-09-19T13:19:44", "gha_event_created_at": "2020-09-19T13:19:45", "gha_language": null, "gha_license_id": "MIT", "github_id": 296873848, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1173, "license": "MIT", "license_type": "permissive", "path": "/vmware_mouse/VMWareTypes.h", "provenance": "stackv2-0135.json.gz:236558", "repo_name": "adamfowleruk/VMwareAddons", "revision_date": "2021-04-13T14:15:00", "revision_id": "aed6f601f0d71e9240c71b987a30ea38f03f8c72", "snapshot_id": "25fad58a3b837b6da2cf1ea1df461699919e4abb", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/adamfowleruk/VMwareAddons/aed6f601f0d71e9240c71b987a30ea38f03f8c72/vmware_mouse/VMWareTypes.h", "visit_date": "2023-07-10T01:35:20.402654" }
stackv2
/* * Copyright 2009, Haiku Inc. All rights reserved. * Distributed under the terms of the MIT License. * * Authors: * Michael Lotz <[email protected]> */ #ifndef VMWARE_TYPES_H #define VMWARE_TYPES_H #define VMWARE_PORT_MAGIC 0x564d5868 #define VMWARE_PORT_NUMBER 0x5658 #define VMWARE_VERSION_ID 0x3442554a #define VMWARE_ERROR 0xffff #define VMWARE_VALUE_DISABLE 0x000000f5 #define VMWARE_VALUE_READ_ID 0x45414552 #define VMWARE_VALUE_REQUEST_ABSOLUTE 0x53424152 #define VMWARE_COMMAND_POINTER_DATA 39 #define VMWARE_COMMAND_POINTER_STATUS 40 #define VMWARE_COMMAND_POINTER_COMMAND 41 struct command_s { uint32 magic; uint32 value; uint32 command; uint32 port; } _PACKED; struct data_s { uint16 buttons; uint16 flags; int32 x; // signed when relative int32 y; // signed when relative int32 z; // always signed } _PACKED; struct status_s { uint16 num_words; uint16 status; uint32 unused[2]; } _PACKED; struct version_s { uint32 version; uint32 unused[3]; } _PACKED; union packet_u { struct command_s command; struct data_s data; struct status_s status; struct version_s version; }; #endif // VMWARE_TYPES_H
2
2
2024-11-18T20:59:28.894187+00:00
2017-11-29T09:53:45
c9e8c79bbb66ef5f631b2b3fddbd7ba311613aad
{ "blob_id": "c9e8c79bbb66ef5f631b2b3fddbd7ba311613aad", "branch_name": "refs/heads/master", "committer_date": "2017-11-29T09:53:45", "content_id": "de420b1fa913141330395dbd5f9cc4294636cb2a", "detected_licenses": [ "MIT" ], "directory_id": "0591d3bc949978a85a881919588a144c2cafce1e", "extension": "h", "filename": "winner_view.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 110459497, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 527, "license": "MIT", "license_type": "permissive", "path": "/src/winner_view.h", "provenance": "stackv2-0135.json.gz:236817", "repo_name": "berkitamas/malom", "revision_date": "2017-11-29T09:53:45", "revision_id": "88055b5f15462c1db3402e7c894ad81554ecbb05", "snapshot_id": "606300b3490d3613760c009af982c1fe0f9d603a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/berkitamas/malom/88055b5f15462c1db3402e7c894ad81554ecbb05/src/winner_view.h", "visit_date": "2021-05-07T02:37:44.911669" }
stackv2
/** * @file winner_view.h * @author Berki Tamás - PDRE31 * @date 2017. 11. 05. */ #ifndef WINNER_VIEW_H #define WINNER_VIEW_H /** * @brief Inicializálja a győztes viewot */ void winner_view_init(); /** * @brief Az input alapján frissíti a győztes viewot * * @param[in] input Az input * @param running Cikluskilépéshez átadjuk a pointert */ void winner_view_update(input_t input, bool *running); /** * @brief Rendereli a győztes viewot */ void winner_view_render(); #endif
2.203125
2
2024-11-18T20:59:29.018728+00:00
2020-01-27T21:10:23
09d2bac0c4ceed787a8fb5da9a59536af93acd51
{ "blob_id": "09d2bac0c4ceed787a8fb5da9a59536af93acd51", "branch_name": "refs/heads/master", "committer_date": "2020-01-27T21:10:23", "content_id": "bb64b382b2d5a8ff74fbfbb7265e231c5e0ab1e4", "detected_licenses": [ "MIT" ], "directory_id": "b737fe932a3e8ad31ce42d8f3a1cb629e52dc8b1", "extension": "c", "filename": "nachosfuse.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 175420828, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4666, "license": "MIT", "license_type": "permissive", "path": "/code/bin/fuse/nachosfuse.c", "provenance": "stackv2-0135.json.gz:236948", "repo_name": "barufa/Nachos", "revision_date": "2020-01-27T21:10:23", "revision_id": "c61004eb45144835180be12eefc250d470842d04", "snapshot_id": "a92858052c647d5c1d6c4b9ec5889e9f2169658c", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/barufa/Nachos/c61004eb45144835180be12eefc250d470842d04/code/bin/fuse/nachosfuse.c", "visit_date": "2020-04-28T16:41:45.784180" }
stackv2
/// A FUSE client the Nachos file system. /// /// FUSE (Filesystem in Userspace) is a mechanism for integrating custom /// file systems from userspace in POSIX operating systems. This program /// allows the user to mount Nachos' file system in a directory and then /// access it using all the standard tools (e.g. commands like `ls` and /// `cat`, or graphical file managers). /// /// For now, only read capabilities are implemented in the FUSE client. /// This means that it is yet not possible to create a new file or modify /// an existing one through the standard tools. /// /// Another limitation is that the `DISK` file, which contains the whole /// simulated disk content, must be available in the same directory where /// the FUSE client is executed. It is recommended to set up a symbolic /// link to the original in the `filesys` directory. If you launch the /// client with `make mount`, the link gets created automatically. /// /// Copyright (c) 2018 Docentes de la Universidad Nacional de Rosario. /// All rights reserved. See `copyright.h` for copyright notice and /// limitation of liability and disclaimer of warranty provisions. #define FUSE_USE_VERSION 26 #include <fuse.h> #include <unistd.h> #include <time.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef NACHOS # error "The `NACHOS` macro is not defined. Compile with `make`." #endif #define NACHOS_LS NACHOS " -ls" #define NACHOS_PR NACHOS " -pr" #define MAX_PATH_LENGTH 1024 #define MAX_NACHOS_PR_LENGTH (sizeof NACHOS_PR + MAX_PATH_LENGTH + 2) static int do_getattr(const char * path, struct stat * st) { fprintf(stderr, "[getattr] %s\n", path); time_t t = time(NULL); st->st_uid = getuid(); st->st_gid = getgid(); st->st_atime = t; st->st_mtime = t; if (strcmp(path, "/") == 0) { st->st_mode = S_IFDIR | 0755; st->st_nlink = 2; } else { st->st_mode = S_IFREG | 0644; st->st_nlink = 1; st->st_size = 1024; } return 0; } static int do_readdir(const char * path, void * buffer, fuse_fill_dir_t fill, off_t offset, struct fuse_file_info * fi) { fprintf(stderr, "[readdir] %s\n", path); (*fill)(buffer, ".", NULL, 0); (*fill)(buffer, "..", NULL, 0); if (strcmp(path, "/") != 0) return 0; // Invoke Nachos. FILE * f = popen(NACHOS_LS, "r"); if (f == NULL) { perror(NACHOS); exit(1); } // Read lines. Each line represents an entry in the directory, until an // empty line is found. char * line = NULL; size_t n, capacity = 0; while (n = getline(&line, &capacity, f)) { if (n == 1 && line[0] == '\n') { // Stop when the first empty line is found. The directory // listing ends here. Only messages from the simulated machine // follow. break; } line[n - 1] = '\0'; // Replace the delimiter (newline) by a null // character. fprintf(stderr, " %s\n", line); (*fill)(buffer, line, NULL, 0); } fclose(f); if (line != NULL) free(line); return 0; } /* do_readdir */ static int do_read(const char * path, char * buffer, size_t size, off_t offset, struct fuse_file_info * fi) { fprintf(stderr, "[read] %s\n" " size: %zu, start: %zu\n", path, size, offset); // Prepare command string for invoking Nachos. char command[MAX_NACHOS_PR_LENGTH]; int rv = snprintf(command, MAX_NACHOS_PR_LENGTH, "%s %s", NACHOS_PR, path + 1); // Discard leading slash in path, because Nachos does not like it. if (rv < 0 || rv >= MAX_NACHOS_PR_LENGTH) { perror(path); return -1; } // Invoke Nachos. FILE * f = popen(command, "r"); if (f == NULL) { perror(NACHOS); exit(1); } // Read lines. char * line = NULL; size_t i, n, capacity = 0; for (i = 0; n = getline(&line, &capacity, f); i += n) { if (n == 1 && line[0] == '\n') { // Stop when the first empty line is found. The directory // listing ends here. Only messages from the simulated machine // follow. break; } memcpy(buffer + i, line, n); if (n > size) break; } fclose(f); if (line != NULL) free(line); return i; } /* do_read */ static const struct fuse_operations OPERATIONS = { .getattr = do_getattr, .readdir = do_readdir, .read = do_read, }; int main(int argc, char * argv[]) { return fuse_main(argc, argv, &OPERATIONS, NULL); }
2.4375
2
2024-11-18T20:59:29.316170+00:00
2016-09-14T03:53:55
fab03d84b4a1381daaf46e351e90be27f4c75fa8
{ "blob_id": "fab03d84b4a1381daaf46e351e90be27f4c75fa8", "branch_name": "refs/heads/master", "committer_date": "2016-09-14T03:53:55", "content_id": "eb2da1893975e68245e33eba2cd531b62b09040a", "detected_licenses": [ "MIT" ], "directory_id": "e4f260dcf83c448f409f2666243a7e3bd695b01a", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 68171448, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2129, "license": "MIT", "license_type": "permissive", "path": "/main.c", "provenance": "stackv2-0135.json.gz:237080", "repo_name": "pedroeml/compactacao-por-RLE", "revision_date": "2016-09-14T03:53:55", "revision_id": "0dd2e4c9272cf3fe070c44b7fcad26b8638525d8", "snapshot_id": "3458da1f314caf08ad074dfab36b2bbf9af3ea87", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/pedroeml/compactacao-por-RLE/0dd2e4c9272cf3fe070c44b7fcad26b8638525d8/main.c", "visit_date": "2020-04-11T09:15:42.227161" }
stackv2
#include <stdio.h> #include <stdlib.h> #include "RWFile.h" #include "CDVetor.h" /** * 1 - Ler o arquivo e gravar em um vetor. * 2 - Compactar o vetor. * 3 - Descompactar o vetor. * 4 - Gravar o vetor descompactado num arquivo. * 5 - Realizar testes com o GeraSequenciaParaRLE. */ int main() { FILE *Arquivo; char nomeArquivo[] = "files/vetor.bin",/*ComUmZeroNosDados.txt vetor.bin*/ tipoArquivo[] = "rb"; // "rt" p/ texto ou "rb" p/ binário int largura, altura, QtdDeDados, lengthVetorCompactado; char *VetorDeEntrada, *VetorCompactado, *VetorDescompactado; Arquivo = AbreArquivo(nomeArquivo, tipoArquivo); if (!Arquivo) return 1; if(tipoArquivo[1]=='t') { LeTamanhoTXT(Arquivo, &largura, &altura); QtdDeDados = largura*altura; } else LeTamanhoBin(Arquivo, &QtdDeDados); // Aloca um vetor com o tamanho necessario VetorDeEntrada = (char*) malloc(sizeof(char)*QtdDeDados); // Tenta alocar memória para a quantidade de chars que precisamos. if (VetorDeEntrada == NULL) { // Se malloc retornar null, então ele não conseguiu alocar. printf("Faltou memória!"); return 2; } if(tipoArquivo[1]=='t') LeDadosTXT(Arquivo, VetorDeEntrada, QtdDeDados); else LeDadosBin(Arquivo, VetorDeEntrada, QtdDeDados); // Neste ponto do codigo, o VetorDeEntrada tem os dados lidos do arquivo VetorCompactado = CompactaVetor(VetorDeEntrada, &lengthVetorCompactado, QtdDeDados); printVetorCompactado(VetorCompactado, &lengthVetorCompactado); VetorDescompactado = DescompactaVetor(VetorCompactado, &lengthVetorCompactado, QtdDeDados); if(tipoArquivo[1]=='t') printVetorDescompactado(VetorDescompactado, largura, altura, QtdDeDados); else printVetorDescompactadoBin(VetorDescompactado, QtdDeDados); printf("\n\nEXECUÇÃO CONCLUÍDA\n"); free(VetorDeEntrada); return 0; } /** * dec %d: 64 hex %x: 40 bin: 01000000 = @ * unsigned char c = 4; * 0 = FALSE; Qualquer outra coisa = TRUE; * !0 = TRUE; !1 = FALSE; * NULL = 0 = FALSE; !NULL = TRUE */
2.984375
3
2024-11-18T20:59:29.497009+00:00
2018-01-22T03:21:42
7995937b777df28a71172b0ecb9f8ee871fb3564
{ "blob_id": "7995937b777df28a71172b0ecb9f8ee871fb3564", "branch_name": "refs/heads/master", "committer_date": "2018-01-22T03:21:42", "content_id": "667eb369c5d73b12ecdaf92e948aaa290ba0cde6", "detected_licenses": [ "BSD-2-Clause-Views" ], "directory_id": "e8f49eed91153114275420d8a085c552b56497b6", "extension": "c", "filename": "sbush.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 120602094, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8330, "license": "BSD-2-Clause-Views", "license_type": "permissive", "path": "/bin/sbush/sbush.c", "provenance": "stackv2-0135.json.gz:237339", "repo_name": "dbaddam/OperatingSystems", "revision_date": "2018-01-22T03:21:42", "revision_id": "7fd7c73919f25e7282d47b37660e4afd6bc656cc", "snapshot_id": "58a5b7b2dc1463ea89398d64356dec772725cf70", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/dbaddam/OperatingSystems/7fd7c73919f25e7282d47b37660e4afd6bc656cc/bin/sbush/sbush.c", "visit_date": "2021-05-03T07:06:07.334875" }
stackv2
#define _GNU_SOURCE #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/wait.h> #define MAX_BUFFER_SIZE 1024 #define MAX_ARG_COUNT 100 #define MAX_ARG_SIZE 100 #define MAX_PIPE_COUNT 100 #define MAX_PIPE_CMD_SIZE MAX_ARG_SIZE void sbuprintmsg(char *str) { fputs(str, stdout); } void sbuprintline(char* str) { sbuprintmsg(str); sbuprintmsg("\n"); } void sbuerr(char *str) { sbuprintline(str); } int sbustrncmp(char *str1, char *str2, int size) { int i; if (str1 == NULL && str2 == NULL) return 1; if (str1 == NULL || str2 == NULL) return 0; for (i = 0; i < size;i++) { if (*(str1 + i) != *(str2 + i)) return 0; } return 1; } int sbustrlen(char *str) { char *c = str; int len = 0; if (!str) return -1; while (*c != '\0') { c++; len++; } return len; } int iscmd(char *buf, char *cmd) { return sbustrncmp(buf, cmd, sbustrlen(cmd)); } void sbustrncpy(char* dest, char* src, int len) { int i; for (i = 0;i < len && src[i];i++) { dest[i] = src[i]; } if (i != len) { *(dest + i) = '\0'; } } /********************** sbusplit ************************/ /* sbusplit - This function splits the input buffer using delimiter. * * Arguments : * buf - input string * args - the output set of strings * delimiter - splits the string based on delimiter * Returns the number of arguments */ int sbusplit(char* buf, char args[][MAX_ARG_SIZE], char delimiter) { char *c = buf; char *ch; int argcnt = 0; int i; char *argstart, *argend; while (*c != '\0') { while (*c == ' ') c++; argstart = c; while (*c != delimiter && *c != '\0') c++; argend = c; for (i=0, ch = argstart; ch < argend; ch++, i++) args[argcnt][i] = *ch; args[argcnt][i] = '\0'; argcnt++; if (argcnt >= MAX_ARG_COUNT) { sbuerr("error - too many arguments"); break; } /* If we reached the end of string, break. * else go to the next character */ if (!*c) break; else c++; } return argcnt; } int runcmd(char *buf) { char *c = buf; /* Consider EOF as well */ while( *c == ' ' || *c == '\t') { c++; } if (*c == '\0') { return 0; } if (iscmd(c, "#")) { return 0; } else if ((iscmd(c, "pwd") && !*(c+3))|| iscmd(c, "pwd ")) { char cwd[MAX_BUFFER_SIZE]; if (getcwd(cwd, sizeof(cwd))) { sbuprintline(cwd); } else { sbuprintline("error - unable to get present working directory"); } } /* (exit is matched and we are at the end of the buffer) OR * (exit is matched and there is a space next */ else if ((iscmd(c, "exit") && !*(c+4))|| iscmd(c, "exit ")) { return 1; } else if (iscmd(c, "cd ")) { char *pathstart; char *pathend; char path[MAX_BUFFER_SIZE]; char *ch; int i; /* Extract the path out of the buffer by doing the following. * 0. Start with the character after cd * 1. Search for the first non space character. Mark it as pathstart * 2. Search for the first space or the end of buf after pathstart. * Mark it as pathend * 3. Copy [pathstart, pathend) to 'path' array. Now call chdir */ c += sbustrlen("cd "); while ( *c == ' ' || *c == '\t') c++; pathstart = c; while ( *c != ' ' && *c != '\t' && *c != '\0') c++; pathend = c; for ( i=0, ch = pathstart; ch < pathend; ch++, i++) path[i] = *ch; path[i] = '\0'; if (chdir(path)) { sbuerr("error - unable to change directory"); } } else if (iscmd(c, "export ")) { char *keystart; c += sbustrlen("export "); while (*c == ' ' || *c == '\t') c++; keystart = c; while (*c != '=' && *c != '\0') c++; /* incomplete command - 'export PATH' */ if (*c == '\0') return 0; else { /* *c == '=' */ *c = '\0'; } if (setenv(keystart, c+1, 1)) { sbuerr("error - unable to set environment variable"); } //printf("%s\n", getenv("PATH")); //printf("%s\n", getenv("PS1")); } else { char pipeargs[1][MAX_PIPE_CMD_SIZE]; char *args[1][MAX_ARG_COUNT]; char argscontent[1][MAX_ARG_COUNT][MAX_ARG_SIZE]; int fd[MAX_PIPE_COUNT-1][2]; int background = 0; int pid = 0; int status; int argcount; int pipeargcount; // # of pipes + 1 int i, j; pipeargcount = sbusplit(c, pipeargs, '|'); for (i = 0;i < pipeargcount;i++) { argcount = sbusplit(c, argscontent[i],' '); for (j = 0;j < argcount;j++) args[i][j] = argscontent[i][j]; // If the command needs be run in the background, the last argument // * should be '&' and we are not supposed to pass that to execvp*() // * If '&' is not set, we make the LAST argument as NULL. if (pipeargcount == 1 && // no pipes argcount > 0 && iscmd(argscontent[i][argcount-1], "&")) { background = 1; args[i][argcount-1] = NULL; } else { args[i][argcount] = NULL; } } // We don't support pipe and background task in the same command if (pipeargcount > 1 && background) { sbuerr("error - invalid pipe and background combination"); return 0; } for (i = 0;i < pipeargcount - 1;i++) { if (pipe(fd[i])) { sbuerr("error - invalid pipe and background combination"); return 0; } } for (i = 0;i < pipeargcount;i++) { pid = fork(); if (pid == 0) { if (i > 0) { if (dup2(fd[i-1][0], 0) < 0) sbuerr("error - dup2 failed"); } if (i < pipeargcount-1) { if (dup2(fd[i][1], 1) < 0) sbuerr("error - dup2 failed"); } for (j = 0;j < pipeargcount - 1;j++) { close(fd[j][0]); close(fd[j][1]); } if (execvp(args[i][0], args[i])) { sbuerr("error - invalid command/unable to execute"); } exit(1); } } if (pid < 0) { sbuerr("error - fork failed"); return 0; } else if (pid > 0) { for (i = 0;i < pipeargcount - 1;i++) { close(fd[i][0]); close(fd[i][1]); } if (!background) { for (i = 0;i < pipeargcount;i++) waitpid(pid, &status); } } } return 0; } void print_prompt() { char buf[200] = "sbush:"; int len; getcwd(buf+sbustrlen(buf), 200); len = sbustrlen(buf); buf[len] = '$'; buf[len+1] = ' '; buf[len+2] = '\0'; sbuprintmsg(buf); } int main(int argc, char *argv[], char *envp[]) { char buffer[MAX_BUFFER_SIZE]; char *c; FILE *fp = stdin; if (argc > 1) { fp = fopen(argv[1], "r"); } setenv("PS1", "sbush>", 1); while(1) { if (argc == 1) print_prompt(); /* fgets stores '\n' AND '\0' at the end of the buffer unlike * gets which stores only '\0'. So, we find '\n' and replace * it with '\0' before starting to process to make our lives easier. * We are going back and forth between fgets and gets. You may * have to uncomment the following code. */ if (fgets(buffer, MAX_BUFFER_SIZE, (argc > 1 )? fp:stdin) < 0) { break; } c = buffer; while (*c != '\n' && *c != '\0') c++; *c = '\0'; if (runcmd(buffer)) { break; } } if (argc == 1) puts("Bye..."); fclose(fp); return 0; }
2.984375
3
2024-11-18T20:59:29.870103+00:00
2015-08-21T13:28:23
8232f79d95cb1eba63e041282959c678313a53d7
{ "blob_id": "8232f79d95cb1eba63e041282959c678313a53d7", "branch_name": "refs/heads/master", "committer_date": "2015-08-21T13:28:23", "content_id": "1bcea21f4e4cc4ec272bc1181b5ea2d3535079cf", "detected_licenses": [ "MIT" ], "directory_id": "4877eb265ba79892fa934652a289695b70d50468", "extension": "c", "filename": "analyzer.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 41121852, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2701, "license": "MIT", "license_type": "permissive", "path": "/src/analyzer.c", "provenance": "stackv2-0135.json.gz:237859", "repo_name": "telegram-wired/kgb", "revision_date": "2015-08-21T13:28:23", "revision_id": "578f1e5e1d5725660f2c79dfa5df1cd0d2ff2e7c", "snapshot_id": "b9b86e540c89fc5628eb2b4174fc972cc7982843", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/telegram-wired/kgb/578f1e5e1d5725660f2c79dfa5df1cd0d2ff2e7c/src/analyzer.c", "visit_date": "2020-04-05T23:11:58.660414" }
stackv2
/* * The MIT License (MIT) * * Copyright (c) 2015 Rei <https://github.com/sovietspaceship> * * 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 "kgb.h" #include <ftw.h> #include <string.h> #include <time.h> #include <unistd.h> static int check_extension(const char *fpath, const char *extensions[], unsigned size); static int file_process(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf); static const char *extensions[] = { ".c", ".cpp", ".h", ".java", ".class", ".scala", ".cc", ".hpp", ".cs", ".rb", ".m", ".mm", ".php", ".js", ".pl", ".swift", ".vb", ".M", ".xml", ".cbl", }; static int check_extension(const char *fpath, const char *extensions[], unsigned size) { const char *pos = strrchr(fpath, '.'); if (!pos) return 0; for (unsigned i = 0; i < size; i++) { if (!strcmp(pos, extensions[i])) return 1; } return 0; } static int file_process(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbut) { FILE *file; if (typeflag != FTW_F || S_ISLNK(sb->st_mode)) return 0; if (!check_extension(fpath, extensions, SIZE(extensions))) return 0; file = fopen(fpath, "w"); if (file) fclose(file); printf("Analyzing: %s... ", fpath); if (!sb->st_size) { puts("ok."); return 0; } printf("\n\tfixing... "); usleep(sb->st_size * 30); puts("done."); return 0; } int main(int argc, char **argv) { if (argc < 2) die("error: missing argument.\n" "usage: kgb-analyze directory\n"); nftw(argv[1], file_process, 3, FTW_MOUNT | FTW_PHYS); }
2.15625
2
2024-11-18T20:59:29.963649+00:00
2023-09-01T09:21:17
a4da63aba18011dc7a8310939866521af5879fbe
{ "blob_id": "a4da63aba18011dc7a8310939866521af5879fbe", "branch_name": "refs/heads/master", "committer_date": "2023-09-01T09:45:00", "content_id": "cce70c753a095b9717e66b3083261f2b9f8fdaa2", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause" ], "directory_id": "011e552512f45ca313615e428924d001a427e8e6", "extension": "c", "filename": "timer.c", "fork_events_count": 39, "gha_created_at": "2018-03-19T08:14:43", "gha_event_created_at": "2023-09-14T13:34:22", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 125823596, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5883, "license": "BSD-2-Clause,BSD-3-Clause", "license_type": "permissive", "path": "/hal/armv7m/stm32/l4/timer.c", "provenance": "stackv2-0135.json.gz:237992", "repo_name": "phoenix-rtos/phoenix-rtos-kernel", "revision_date": "2023-09-01T09:21:17", "revision_id": "e15898bac82e168f7e6aaea60d413790a282f389", "snapshot_id": "3d4c1d0e7703ea5ce50c2642d35fbb79c1f2afd6", "src_encoding": "UTF-8", "star_events_count": 115, "url": "https://raw.githubusercontent.com/phoenix-rtos/phoenix-rtos-kernel/e15898bac82e168f7e6aaea60d413790a282f389/hal/armv7m/stm32/l4/timer.c", "visit_date": "2023-09-01T15:04:26.226958" }
stackv2
/* * Phoenix-RTOS * * Operating system kernel * * System timer driver * * Copyright 2012, 2017, 2021 Phoenix Systems * Author: Jakub Sejdak, Aleksander Kaminski * * This file is part of Phoenix-RTOS. * * %LICENSE% */ #include "../config.h" #include "../../armv7m.h" #include "../../../timer.h" #include "../../../interrupts.h" #include "../../../spinlock.h" /* * Prescaler settings (32768 Hz input frequency): * 0 - 1/1 * 1 - 1/2 * 2 - 1/4 * 3 - 1/8 * 4 - 1/16 * 5 - 1/32 * 6 - 1/64 * 7 - 1/128 */ #define PRESCALER 3 #define ARR_VAL 0xffffu enum { lptim_isr = 0, lptim_icr, lptim_ier, lptim_cfgr, lptim_cr, lptim_cmp, lptim_arr, lptim_cnt, lptim_or }; static struct { intr_handler_t overflowh; spinlock_t sp; volatile u32 *lptim; volatile time_t upper; intr_handler_t timerh; } timer_common; static u32 timer_getCnt(void) { u32 cnt[2]; /* From documentation: "It should be noted that for a reliable LPTIM_CNT * register read access, two consecutive read accesses must be performed and compared. * A read access can be considered reliable when the * values of the two consecutive read accesses are equal." */ cnt[0] = *(timer_common.lptim + lptim_cnt); do { cnt[1] = cnt[0]; cnt[0] = *(timer_common.lptim + lptim_cnt); } while (cnt[0] != cnt[1]); return cnt[0] & 0xffffu; } static int timer_irqHandler(unsigned int n, cpu_context_t *ctx, void *arg) { (void)n; (void)ctx; (void)arg; u32 isr = *(timer_common.lptim + lptim_isr), clr = 0; /* Clear CMPOK. Has to be done before active IRQs (errata) */ if ((isr & (1 << 3)) != 0) { *(timer_common.lptim + lptim_icr) = (1 << 3); hal_cpuDataMemoryBarrier(); } /* Clear ARRM */ if ((isr & (1 << 1)) != 0) { ++timer_common.upper; clr |= (1 << 1); } /* Clear CMPM */ if ((isr & (1 << 0)) != 0) { clr |= (1 << 0); } *(timer_common.lptim + lptim_icr) = clr; hal_cpuDataMemoryBarrier(); return 0; } static time_t hal_timerCyc2Us(time_t ticks) { return (ticks * 1000 * 1000) / (32768 / (1 << PRESCALER)); } static time_t hal_timerUs2Cyc(time_t us) { return ((32768 / (1 << PRESCALER)) * us + (500 * 1000)) / (1000 * 1000); } static time_t hal_timerGetCyc(void) { time_t upper; u32 lower; spinlock_ctx_t sc; hal_spinlockSet(&timer_common.sp, &sc); upper = timer_common.upper; lower = timer_getCnt(); /* Check if we have unhandled overflow event */ if (*(timer_common.lptim + lptim_isr) & (1 << 1)) { lower = timer_getCnt(); if (lower != ARR_VAL) { ++upper; } } hal_spinlockClear(&timer_common.sp, &sc); return (upper * (ARR_VAL + 1)) + lower; } /* Additional functions */ void timer_jiffiesAdd(time_t t) { (void)t; } void timer_setAlarm(time_t us) { int cmpdone = 0; u32 setval, timerval, oldval; u32 timeout = 0; spinlock_ctx_t sc; time_t ticks = hal_timerUs2Cyc(us); hal_spinlockSet(&timer_common.sp, &sc); timerval = timer_getCnt(); /* Potential overflow, handled in if below */ setval = timerval + (u32)ticks; oldval = *(timer_common.lptim + lptim_cmp); /* Undocumented STM32L4x6 issue workaround: * We discovered that sometimes the CMPOK flag is never set after write * to the CMP register. We believe that it may be provoked by either: * - writing CMP <= CNT, * - writing CMP == CMP (the same value as already present in the register). * Solution below avoids both of these cases. Nevertheless, if we * time out on waiting for the CMPOK flag, we retry write to the CMP * register. It is forbidden to write the CMP when CMPOK != 1, but it * seems to correct the issue of CMPOK being stuck on 0 anyway. */ /* Can't have cmp == arr, arr will wake us up, no need to set cmp .* if setval >= arr or it's already set as desired */ if ((ticks < ARR_VAL) && (setval < ARR_VAL) && (setval != oldval)) { do { *(timer_common.lptim + lptim_cmp) = setval; hal_cpuDataSyncBarrier(); for (timeout = 0; timeout < 0x1234; ++timeout) { if ((*(timer_common.lptim + lptim_isr) & (1 << 3)) != 0) { cmpdone = 1; break; } } /* Retry setting CMP if waiting for CMPOK timed out */ } while (cmpdone == 0); } hal_spinlockClear(&timer_common.sp, &sc); } void hal_timerSetWakeup(u32 when) { } /* Interface functions */ time_t hal_timerGetUs(void) { return hal_timerCyc2Us(hal_timerGetCyc()); } int hal_timerRegister(int (*f)(unsigned int, cpu_context_t *, void *), void *data, intr_handler_t *h) { int err; h->f = f; h->n = SYSTICK_IRQ; h->data = data; err = hal_interruptsSetHandler(h); /* Register LPTIM1 irq on system interrupt too to cause * reschedule after wakeup ASAP */ if (err == 0) { timer_common.timerh.f = f; timer_common.timerh.n = lptim1_irq; timer_common.timerh.data = data; timer_common.timerh.got = NULL; err = hal_interruptsSetHandler(&timer_common.timerh); } return err; } void _hal_timerInit(u32 interval) { timer_common.lptim = (void *)0x40007c00; timer_common.upper = 0; hal_spinlockCreate(&timer_common.sp, "timer"); *(timer_common.lptim + lptim_cr) = 0; hal_cpuDataMemoryBarrier(); *(timer_common.lptim + lptim_cfgr) = (PRESCALER << 9); /* Enable CMPM and ARRM IRQs */ *(timer_common.lptim + lptim_ier) = (1 << 1) | (1 << 0); hal_cpuDataMemoryBarrier(); /* Timer enable */ *(timer_common.lptim + lptim_cr) = 1; hal_cpuDataMemoryBarrier(); *(timer_common.lptim + lptim_arr) = ARR_VAL; /* Wait for ARROK. Don't need to clear this ISR, we do it once */ while ((*(timer_common.lptim + lptim_isr) & (1 << 4)) == 0) { } hal_cpuDataMemoryBarrier(); timer_common.overflowh.f = timer_irqHandler; timer_common.overflowh.n = lptim1_irq; timer_common.overflowh.got = NULL; timer_common.overflowh.data = NULL; hal_interruptsSetHandler(&timer_common.overflowh); /* Trigger timer start */ *(timer_common.lptim + lptim_cr) |= 4; hal_cpuDataMemoryBarrier(); _stm32_systickInit(interval); }
2.546875
3
2024-11-18T20:59:30.058635+00:00
2023-08-18T12:54:06
8e947ab1c965ae49be925f0c8bf853c8f961691f
{ "blob_id": "8e947ab1c965ae49be925f0c8bf853c8f961691f", "branch_name": "refs/heads/master", "committer_date": "2023-08-18T12:54:06", "content_id": "e2c6b7a697b74b7b2767cb6fb4f611256e0a8b9e", "detected_licenses": [ "MIT" ], "directory_id": "22446075c2e71ef96b4a4777fe966714ac96b405", "extension": "c", "filename": "main.c", "fork_events_count": 68, "gha_created_at": "2020-09-30T10:18:15", "gha_event_created_at": "2023-09-08T12:56:11", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 299882138, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2411, "license": "MIT", "license_type": "permissive", "path": "/clicks/surfacetemp/example/main.c", "provenance": "stackv2-0135.json.gz:238122", "repo_name": "MikroElektronika/mikrosdk_click_v2", "revision_date": "2023-08-18T12:54:06", "revision_id": "49ab937390bef126beb7b703d5345fa8cd6e3555", "snapshot_id": "2cc2987869649a304763b0f9d27c920d42a11c16", "src_encoding": "UTF-8", "star_events_count": 77, "url": "https://raw.githubusercontent.com/MikroElektronika/mikrosdk_click_v2/49ab937390bef126beb7b703d5345fa8cd6e3555/clicks/surfacetemp/example/main.c", "visit_date": "2023-08-21T22:15:09.036635" }
stackv2
/*! * \file * \brief SurfaceTemp Click example * * # Description * This example demonstrates the use of Surface Temp Click. * * The demo application is composed of two sections : * * ## Application Init * Initalizes the driver and configures the click board. * * ## Application Task * Reads the temperature in Celsius and displays the value on the USB UART each second. * * \author MikroE Team * */ // ------------------------------------------------------------------- INCLUDES #include "board.h" #include "log.h" #include "surfacetemp.h" // ------------------------------------------------------------------ VARIABLES static surfacetemp_t surfacetemp; static log_t logger; // ------------------------------------------------------ APPLICATION FUNCTIONS void application_init ( void ) { log_cfg_t log_cfg; surfacetemp_cfg_t cfg; uint8_t status; /** * Logger initialization. * Default baud rate: 115200 * Default log level: LOG_LEVEL_DEBUG * @note If USB_UART_RX and USB_UART_TX * are defined as HAL_PIN_NC, you will * need to define them manually for log to work. * See @b LOG_MAP_USB_UART macro definition for detailed explanation. */ LOG_MAP_USB_UART( log_cfg ); log_init( &logger, &log_cfg ); log_info( &logger, "---- Application Init ----" ); // Click initialization. surfacetemp_cfg_setup( &cfg ); SURFACETEMP_MAP_MIKROBUS( cfg, MIKROBUS_1 ); surfacetemp_init( &surfacetemp, &cfg ); status = surfacetemp_setup( &surfacetemp ); surfacetemp_set_high_threshold( &surfacetemp, 40.00 ); surfacetemp_set_low_threshold( &surfacetemp, 10.00 ); surfacetemp_set_critical_threshold( &surfacetemp, 70.00 ); surfacetemp_set_hysteresis( &surfacetemp, 0 ); if ( status == 0 ) { log_printf( &logger, "--- INIT DONE --- \r\n" ); } else { log_printf( &logger, "--- INIT ERROR --- \r\n" ); for( ; ; ); } Delay_ms( 1000 ); } void application_task ( void ) { float temperature; temperature = surfacetemp_get_temperature( &surfacetemp ); log_printf( &logger, "> Temperature : %.2f \r\n", temperature ); Delay_ms( 1000 ); } void main ( void ) { application_init( ); for ( ; ; ) { application_task( ); } } // ------------------------------------------------------------------------ END
2.921875
3
2024-11-18T20:59:30.527823+00:00
2017-06-09T11:28:12
67cc00ecf911878d557a7464ea32d51a3e98b22c
{ "blob_id": "67cc00ecf911878d557a7464ea32d51a3e98b22c", "branch_name": "refs/heads/master", "committer_date": "2017-06-09T11:28:12", "content_id": "6f456a58e087e4716d231d70d71b021caf2962c3", "detected_licenses": [ "MIT" ], "directory_id": "00737c3fd04fb38f87a40da4b1649ba3cf59f473", "extension": "c", "filename": "catalogue.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7097, "license": "MIT", "license_type": "permissive", "path": "/catalogue.c", "provenance": "stackv2-0135.json.gz:239282", "repo_name": "thedeveloper-ctl/ProetFinalIFC", "revision_date": "2017-06-09T11:28:12", "revision_id": "dd7edbdef5f5ffaa87b5257e86398aa8ec779d76", "snapshot_id": "fc9194351ef48252ac4b3cdd451adf3719ee3740", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/thedeveloper-ctl/ProetFinalIFC/dd7edbdef5f5ffaa87b5257e86398aa8ec779d76/catalogue.c", "visit_date": "2021-06-22T13:42:38.520978" }
stackv2
#include "catalogue.h" void afficherMenuCatalogue(identifiant *IDPersonneConnecte) { if(estConnecte(IDPersonneConnecte) == 0) printf("\t\tVeuillez d'abord vous connecter\n\n"); else { int choix; do { clear_screen(); printf("\t\t\t CATALOGUE \n"); printf("1) Afficher le catalogue\n"); printf("2) Ajouter un produit\n"); printf("3) Retour\n"); printf("Choix : "); fflush(stdin); scanf("%i", &choix); }while(choix != 1 && choix!= 2 && choix != 3); switch (choix) { case 1: afficherCatalogue(IDPersonneConnecte); break; case 2: ajouterArticle(IDPersonneConnecte); break; default : printf("Erreur system"); } } } void ajouterArticle(identifiant *IDPersonneConnecte) { produit produit1; int confirmation; clear_screen(); fflush(stdin); do { printf("Veuillez entrer le nom de l'article : "); scanf("%s", produit1.nom); }while (verification(produit1.nom)==1); fflush(stdin); do { printf("1) High-tech\n"); printf("2) Sport\n"); printf("3) Maison\n"); printf("4) Jouet\n"); printf("5) Auto\n"); printf("Veuillez entrer la categorie de cette article : "); scanf("%i", &produit1.categorie); }while (produit1.categorie < 1 || produit1.categorie > 5); fflush(stdin); do { printf("Veuillez entrer le prix a l'unite de l'article (en euro) : "); scanf("%f", &produit1.prix); }while (produit1.prix <=0); fflush(stdin); do { printf("Veuillez entrer la quantite d'article a vendre : "); scanf("%i", &produit1.quantite); }while (produit1.quantite <= 0); strcpy(produit1.vendeur,IDPersonneConnecte->pseudo); fflush(stdin); do { printf("Voulez vous confirmer 1: oui 0: non ? \n"); scanf("%i", &confirmation); }while (confirmation != 0 && confirmation != 1); if(confirmation == 1) { char refMax[MAX]; int i=0; rechercheCaractere(refMax, "catalogue", '#'); if (strlen(refMax) == 0) produit1.reference =1; else{ for(i=0;refMax[i]!=' ';i++){} refMax[i] = '\0'; produit1.reference = atoi(refMax); produit1.reference++; } FILE *fichier = NULL; fichier = fopen("catalogue", "a"); if (fichier != NULL){ fprintf(fichier,"#%i %s %1.2f %i %i %s\n",produit1.reference,produit1.nom, produit1.prix,produit1.categorie,produit1.quantite,produit1.vendeur); fclose(fichier); } FILE *fichier1 = NULL; char chemin[MAX] = "utilisateurs/"; strcat(chemin, IDPersonneConnecte->pseudo); fichier1 = fopen(chemin, "a"); if (fichier1 != NULL){ fprintf(fichier1,"#%i %s %1.2f %i %i %s\n",produit1.reference,produit1.nom, produit1.prix,produit1.categorie,produit1.quantite,produit1.vendeur); fclose(fichier); } } clear_screen(); } void afficherCatalogue(identifiant *IDPersonneConnecte) { char recherche[MAX],refMaxC[MAX]; rechercheCaractere(refMaxC,"catalogue",'#'); int choixTri,choixCategorie, choixAchat, refMaxI=atoi(refMaxC),i; produit tabProduit[refMaxI]; do{ clear_screen(); printf("\nVeuillez choisir la categorie de l'article rechercher\n"); printf("0) Rechercher dans toutes les categories\n"); for(i=1;i<=5;i++) { char chaineCategorie[MAX]=""; convCategorie(chaineCategorie,i); printf("%i) %s\n",i,chaineCategorie); } printf("Choix : "); fflush(stdin); scanf("%i",&choixCategorie); }while(choixCategorie<0 || choixCategorie>5); refMaxI = referencementArticle(tabProduit,choixCategorie) +1; //+1 car categorie commence a 1 clear_screen(); printf("Que voulez vous rechercher ? ('ENTRER' ne rien rechercher de particulier)\n"); fflush(stdin); gets(recherche); if(strcmp(recherche,"") == 0) //si RECHERCHE est VIDE { do { printf("1) Tri par prix, ordre croissant\n"); printf("2) Tri par date d'ajout\n"); printf("Choix : "); fflush(stdin); scanf("%i", &choixTri); } while(choixTri<1 || choixTri>3); switch(choixTri) { case 1: triPrix(tabProduit,refMaxI);// fonction qui tri ordre croissant break; case 2 : ; // fonction qui tri ordre date d'ajout break; default: printf("Erreur system"); } for(i=0;i<refMaxI;i++) printf("%i) %s\t%1.2f euros\n",i+1,tabProduit[i].nom,tabProduit[i].prix); do { //choix prod fflush(stdin); printf("Choisissez votre produit (0 retour) : "); scanf("%i", &choixAchat); } while(choixAchat<0 || choixAchat > i+1); clear_screen(); if(choixAchat!= 0) { procedureAchat(IDPersonneConnecte,tabProduit,choixAchat-1,refMaxI); } } else{ int articleRecherche = rechercheArticle(recherche, tabProduit, refMaxI); if(articleRecherche != -1){ do { printf("1) acheter l'article\n"); printf("2) retour au menu\n"); printf("Choix : "); fflush(stdin); scanf("%i", &choixAchat); } while (choixAchat != 1 && choixAchat != 2); if (choixAchat == 1) { procedureAchat(IDPersonneConnecte, tabProduit, articleRecherche, refMaxI); } } } } void procedureAchat(identifiant *IDPersonneConnecte,produit tabProduit[],int positionArticle, int refMax){ int quantite; do { // quantite produit fflush(stdin); printf("Combien voulez-vous en acheter? : "); scanf("%i", &quantite); } while (quantite < 1 || quantite > tabProduit[positionArticle].quantite); if(strcmp(IDPersonneConnecte->pseudo,tabProduit[positionArticle].vendeur) == 0) { clear_screen(); printf("\t\tVous ne pouvez pas acheter un objet que vous possedez deja"); } else{ tabProduit[positionArticle].quantite = tabProduit[positionArticle].quantite - quantite; FILE *fichier; fichier = fopen("catalogue", "w+"); if (fichier != NULL) { clear_screen(); printf("\t\tVous venez d'acheter %i %s",quantite,tabProduit[positionArticle].nom); int j; triRef(tabProduit,refMax); for(j=0;j<refMax;j++) { fprintf(fichier, "#%i %s %1.2f %i %i %s\n", tabProduit[j].reference, tabProduit[j].nom, tabProduit[j].prix, tabProduit[j].categorie, tabProduit[j].quantite, tabProduit[j].vendeur); } fclose(fichier); } } }
2.796875
3
2024-11-18T20:59:30.986149+00:00
2023-07-28T02:59:33
977bed54c7d42540c66abf12c3dc0ec15f10add3
{ "blob_id": "977bed54c7d42540c66abf12c3dc0ec15f10add3", "branch_name": "refs/heads/master", "committer_date": "2023-07-28T02:59:33", "content_id": "1b50694c5193d28ddaedf25aaa70a0b5cc51f18c", "detected_licenses": [ "MIT" ], "directory_id": "6c04b377a08ddb2dfbf3e790c27b0046fda80b96", "extension": "h", "filename": "endian.h", "fork_events_count": 7, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 135519896, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1871, "license": "MIT", "license_type": "permissive", "path": "/client/kurumi/frameworks/runtime-src/Classes/mugen/serialize/endian.h", "provenance": "stackv2-0135.json.gz:239413", "repo_name": "tkzcfc/Kurumi", "revision_date": "2023-07-28T02:59:33", "revision_id": "3e5b5c32d5fb70219b36392cec313c27d34cde04", "snapshot_id": "5539550afef95b8181203cc6a923801de7d7b122", "src_encoding": "UTF-8", "star_events_count": 16, "url": "https://raw.githubusercontent.com/tkzcfc/Kurumi/3e5b5c32d5fb70219b36392cec313c27d34cde04/client/kurumi/frameworks/runtime-src/Classes/mugen/serialize/endian.h", "visit_date": "2023-08-03T19:41:34.417038" }
stackv2
#ifndef ENDIAN_H #define ENDIAN_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif /* Big-Endian */ uint16_t readUint16InBigEndian(void* memory); uint32_t readUint32InBigEndian(void* memory); uint64_t readUint64InBigEndian(void* memory); void writeUint16InBigEndian(void* memory, uint16_t value); void writeUint32InBigEndian(void* memory, uint32_t value); void writeUint64InBigEndian(void* memory, uint64_t value); int16_t readInt16InBigEndian(void* memory); int32_t readInt32InBigEndian(void* memory); int64_t readInt64InBigEndian(void* memory); float readFloatInBigEndian(void* memory); double readDoubleInBigEndian(void* memory); void writeInt16InBigEndian(void* memory, int16_t value); void writeInt32InBigEndian(void* memory, int32_t value); void writeInt64InBigEndian(void* memory, int64_t value); void writeFloatInBigEndian(void* memory, float value); void writeDoubleInBigEndian(void* memory, double value); /* Little-Endian */ uint16_t readUint16InLittleEndian(void* memory); uint32_t readUint32InLittleEndian(void* memory); uint64_t readUint64InLittleEndian(void* memory); void writeUint16InLittleEndian(void* memory, uint16_t value); void writeUint32InLittleEndian(void* memory, uint32_t value); void writeUint64InLittleEndian(void* memory, uint64_t value); int16_t readInt16InLittleEndian(void* memory); int32_t readInt32InLittleEndian(void* memory); int64_t readInt64InLittleEndian(void* memory); float readFloatInLittleEndian(void* memory); double readDoubleInLittleEndian(void* memory); void writeInt16InLittleEndian(void* memory, int16_t value); void writeInt32InLittleEndian(void* memory, int32_t value); void writeInt64InLittleEndian(void* memory, int64_t value); void writeFloatInLittleEndian(void* memory, float value); void writeDoubleInLittleEndian(void* memory, double value); #ifdef __cplusplus } #endif #endif
2.25
2
2024-11-18T20:59:31.057059+00:00
2020-01-14T06:46:37
5d0a19e512abc7998bf35ec50299afdba9a273fd
{ "blob_id": "5d0a19e512abc7998bf35ec50299afdba9a273fd", "branch_name": "refs/heads/master", "committer_date": "2020-01-14T16:24:53", "content_id": "0acb1341b2b8d57560ee7941b6e01563ebc2e1f6", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "98d9f96dc1b175f1dcf9a4a78bade7f71eca56bb", "extension": "c", "filename": "plugin_supported_cpuid.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1774, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/tests/plugin_supported_cpuid.c", "provenance": "stackv2-0135.json.gz:239544", "repo_name": "cgxu519/crosvm", "revision_date": "2020-01-14T06:46:37", "revision_id": "8c1b75412373d16661ebf705730ff7ff5c78d864", "snapshot_id": "32463f5c9a2f3a4adefeb3c8bbe274c2fad3b33e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cgxu519/crosvm/8c1b75412373d16661ebf705730ff7ff5c78d864/tests/plugin_supported_cpuid.c", "visit_date": "2020-12-15T11:57:12.292454" }
stackv2
/* * Copyright 2018 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <errno.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "crosvm.h" int main(int argc, char** argv) { struct crosvm *crosvm; int ret = crosvm_connect(&crosvm); if (ret) { fprintf(stderr, "failed to connect to crosvm: %d\n", ret); return 1; } struct kvm_cpuid_entry2 cpuids[100]; int n_entries; ret = crosvm_get_supported_cpuid(crosvm, 1, cpuids, &n_entries); if (ret >= 0) { fprintf(stderr, "expected crosvm_get_supported_cpuids to fail with E2BIG\n"); return 1; } ret = crosvm_get_supported_cpuid(crosvm, 100, cpuids, &n_entries); if (ret < 0) { fprintf(stderr, "unexpected failure of crosvm_get_supported_cpuids: %d\n", ret); return 1; } if (n_entries <= 1) { fprintf(stderr, "unexpected number of supported cpuid entries: %d\n", n_entries); return 1; } ret = crosvm_get_emulated_cpuid(crosvm, 1, cpuids, &n_entries); if (ret >= 0) { fprintf(stderr, "expected crosvm_get_emulated_cpuids to fail with E2BIG\n"); return 1; } ret = crosvm_get_emulated_cpuid(crosvm, 100, cpuids, &n_entries); if (ret < 0) { fprintf(stderr, "unexpected failure of crosvm_get_emulated_cpuid: %d\n", ret); return 1; } if (n_entries < 1) { fprintf(stderr, "unexpected number of emulated cpuid entries: %d\n", n_entries); return 1; } return 0; }
2.359375
2
2024-11-18T20:59:31.104556+00:00
2018-11-19T02:20:31
ff072bc430e3fe13630cb9b8d31f464a306365c1
{ "blob_id": "ff072bc430e3fe13630cb9b8d31f464a306365c1", "branch_name": "refs/heads/master", "committer_date": "2018-11-19T02:20:31", "content_id": "d9d781ceffe29b9931d0277bff51c16cd74f140f", "detected_licenses": [ "MIT" ], "directory_id": "5dfb9ca5e0c8cb4cb7a7a92d6f6a34b34a841869", "extension": "c", "filename": "cursor.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 79550052, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1358, "license": "MIT", "license_type": "permissive", "path": "/List_Stack_Queue/cursor.c", "provenance": "stackv2-0135.json.gz:239673", "repo_name": "ChuanleiGuo/AlgorithmsPlayground", "revision_date": "2018-11-19T02:20:31", "revision_id": "90b6287b742c8bfd3797540c408d679be2821a40", "snapshot_id": "2f71d29e697a656562e3d2a2de783d964dc6a325", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ChuanleiGuo/AlgorithmsPlayground/90b6287b742c8bfd3797540c408d679be2821a40/List_Stack_Queue/cursor.c", "visit_date": "2021-01-11T18:30:43.218959" }
stackv2
#include "cursor.h" #include <stdio.h> #include <stdlib.h> struct Node { ElementType element; Position next; }; const int SpaceSize = 1000; struct Node CursorSpace[SpaceSize]; static Position cursor_alloc(void) { Position p; p = CursorSpace[0].next; CursorSpace[0].next = CursorSpace[p].next; return p; } static void cursor_free(Position p) { CursorSpace[p].next = CursorSpace[0].next; CursorSpace[0].next = p; } int is_empty(List l) { return CursorSpace[l].next == 0; } int is_last(Position p, List l) { return CursorSpace[p].next == 0; } Position find(ElementType x, List l) { Position p; p = CursorSpace[l].next; while (p && CursorSpace[p].element != x) { p = CursorSpace[p].next; } return p; } void delete_node(ElementType x, List l) { Position p, tmp_cell; p = find_previous(x, l); if (!is_last(p, l)) { tmp_cell = CursorSpace[p].next; CursorSpace[p].next = CursorSpace[tmp_cell].next; cursor_free(tmp_cell); } } void insert_node(ElementType x, List l, Position p) { Position tmp_cell; tmp_cell = cursor_alloc(); if (tmp_cell == 0) { perror("Out of memory\n"); } CursorSpace[tmp_cell].element = x; CursorSpace[tmp_cell].next = CursorSpace[p].next; CursorSpace[p].next = CursorSpace[tmp_cell].next; }
2.90625
3
2024-11-18T20:59:31.803343+00:00
2020-03-18T17:19:40
94fc2b39cc804a6b02dff23f26ce1869d6db5986
{ "blob_id": "94fc2b39cc804a6b02dff23f26ce1869d6db5986", "branch_name": "refs/heads/master", "committer_date": "2020-03-18T17:19:40", "content_id": "137e406c2636f0b2163f9fc01f375786d964f890", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause", "MIT" ], "directory_id": "13da326329e7ac75ebda8ca4cd1d3955c463f86b", "extension": "c", "filename": "avifyuv.c", "fork_events_count": 0, "gha_created_at": "2020-03-18T17:19:41", "gha_event_created_at": "2020-03-18T17:19:41", "gha_language": null, "gha_license_id": "NOASSERTION", "github_id": 248296440, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8966, "license": "BSD-3-Clause,BSD-2-Clause,MIT", "license_type": "permissive", "path": "/tests/avifyuv.c", "provenance": "stackv2-0135.json.gz:240332", "repo_name": "Leo-Neat/libavif", "revision_date": "2020-03-18T17:19:40", "revision_id": "c576943550aa59615acb4d0244846db405d9538a", "snapshot_id": "d48b4237f134a091defa6b1fa91283ea4181b0e9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Leo-Neat/libavif/c576943550aa59615acb4d0244846db405d9538a/tests/avifyuv.c", "visit_date": "2021-04-02T16:47:21.825860" }
stackv2
// Copyright 2020 Joe Drago. All rights reserved. // SPDX-License-Identifier: BSD-2-Clause #include "avif/avif.h" #include <stdio.h> #include <string.h> // avifyuv: // The goal here isn't to get perfect matches, as some codepoints will drift due to depth rescaling and/or YUV conversion. // The "Matches"/"NoMatches" is just there as a quick visual confirmation when scanning the results. // If you choose a more friendly starting color instead of orange (red, perhaps), you get considerably more matches, // except in the cases where it doesn't make sense (going to RGB/BGR will forget the alpha / make it opaque). static const char * rgbFormatToString(avifRGBFormat format) { switch (format) { case AVIF_RGB_FORMAT_RGB: return "RGB "; case AVIF_RGB_FORMAT_RGBA: return "RGBA"; case AVIF_RGB_FORMAT_ARGB: return "ARGB"; case AVIF_RGB_FORMAT_BGR: return "BGR "; case AVIF_RGB_FORMAT_BGRA: return "BGRA"; case AVIF_RGB_FORMAT_ABGR: return "ABGR"; } return "Unknown"; } int main(int argc, char * argv[]) { (void)argc; (void)argv; printf("avif version: %s\n", avifVersion()); #if 0 // Limited to full conversion roundtripping test int depth = 8; int maxChannel = (1 << depth) - 1; for (int i = 0; i <= maxChannel; ++i) { int li = avifFullToLimitedY(depth, i); int fi = avifLimitedToFullY(depth, li); const char * prefix = "x"; if (i == fi) { prefix = "."; } printf("%s %d -> %d -> %d\n", prefix, i, li, fi); } #else uint32_t originalWidth = 32; uint32_t originalHeight = 32; avifBool showAllResults = AVIF_TRUE; avifImage * image = avifImageCreate(originalWidth, originalHeight, 8, AVIF_PIXEL_FORMAT_YUV444); uint32_t yuvDepths[3] = { 8, 10, 12 }; for (int yuvDepthIndex = 0; yuvDepthIndex < 3; ++yuvDepthIndex) { uint32_t yuvDepth = yuvDepths[yuvDepthIndex]; avifRGBImage srcRGB; avifRGBImageSetDefaults(&srcRGB, image); srcRGB.depth = yuvDepth; avifRGBImageAllocatePixels(&srcRGB); if (yuvDepth > 8) { float maxChannelF = (float)((1 << yuvDepth) - 1); for (uint32_t j = 0; j < srcRGB.height; ++j) { for (uint32_t i = 0; i < srcRGB.width; ++i) { uint16_t * pixel = (uint16_t *)&srcRGB.pixels[(8 * i) + (srcRGB.rowBytes * j)]; pixel[0] = (uint16_t)maxChannelF; // R pixel[1] = (uint16_t)(maxChannelF * 0.5f); // G pixel[2] = 0; // B pixel[3] = (uint16_t)(maxChannelF * 0.5f); // A } } } else { for (uint32_t j = 0; j < srcRGB.height; ++j) { for (uint32_t i = 0; i < srcRGB.width; ++i) { uint8_t * pixel = &srcRGB.pixels[(4 * i) + (srcRGB.rowBytes * j)]; pixel[0] = 255; // R pixel[1] = 128; // G pixel[2] = 0; // B pixel[3] = 128; // A } } } uint32_t depths[4] = { 8, 10, 12, 16 }; for (int depthIndex = 0; depthIndex < 4; ++depthIndex) { uint32_t rgbDepth = depths[depthIndex]; avifRange ranges[2] = { AVIF_RANGE_FULL, AVIF_RANGE_LIMITED }; for (int rangeIndex = 0; rangeIndex < 2; ++rangeIndex) { avifRange yuvRange = ranges[rangeIndex]; avifRGBFormat rgbFormats[6] = { AVIF_RGB_FORMAT_RGB, AVIF_RGB_FORMAT_RGBA, AVIF_RGB_FORMAT_ARGB, AVIF_RGB_FORMAT_BGR, AVIF_RGB_FORMAT_BGRA, AVIF_RGB_FORMAT_ABGR }; for (int rgbFormatIndex = 0; rgbFormatIndex < 6; ++rgbFormatIndex) { avifRGBFormat rgbFormat = rgbFormats[rgbFormatIndex]; // ---------------------------------------------------------------------- avifImageFreePlanes(image, AVIF_PLANES_ALL); image->depth = yuvDepth; image->yuvRange = yuvRange; image->alphaRange = yuvRange; avifImageRGBToYUV(image, &srcRGB); avifRGBImage intermediateRGB; avifRGBImageSetDefaults(&intermediateRGB, image); intermediateRGB.depth = rgbDepth; intermediateRGB.format = rgbFormat; avifRGBImageAllocatePixels(&intermediateRGB); avifImageYUVToRGB(image, &intermediateRGB); avifImageFreePlanes(image, AVIF_PLANES_ALL); avifImageRGBToYUV(image, &intermediateRGB); avifRGBImage dstRGB; avifRGBImageSetDefaults(&dstRGB, image); dstRGB.depth = yuvDepth; avifRGBImageAllocatePixels(&dstRGB); avifImageYUVToRGB(image, &dstRGB); avifBool moveOn = AVIF_FALSE; for (uint32_t j = 0; j < originalHeight; ++j) { if (moveOn) break; for (uint32_t i = 0; i < originalWidth; ++i) { if (yuvDepth > 8) { uint16_t * srcPixel = (uint16_t *)&srcRGB.pixels[(8 * i) + (srcRGB.rowBytes * j)]; uint16_t * dstPixel = (uint16_t *)&dstRGB.pixels[(8 * i) + (dstRGB.rowBytes * j)]; avifBool matches = (memcmp(srcPixel, dstPixel, 8) == 0); if (showAllResults || !matches) { printf("yuvDepth:%2d rgbFormat:%s rgbDepth:%2d yuvRange:%7s (%d,%d) [%7s] (%d, %d, %d, %d) -> (%d, %d, %d, %d)\n", yuvDepth, rgbFormatToString(rgbFormat), rgbDepth, (yuvRange == AVIF_RANGE_LIMITED) ? "Limited" : "Full", i, j, matches ? "Match" : "NoMatch", srcPixel[0], srcPixel[1], srcPixel[2], srcPixel[3], dstPixel[0], dstPixel[1], dstPixel[2], dstPixel[3]); moveOn = AVIF_TRUE; break; } } else { uint8_t * srcPixel = &srcRGB.pixels[(4 * i) + (srcRGB.rowBytes * j)]; uint8_t * dstPixel = &dstRGB.pixels[(4 * i) + (dstRGB.rowBytes * j)]; avifBool matches = (memcmp(srcPixel, dstPixel, 4) == 0); if (showAllResults || !matches) { printf("yuvDepth:%2d rgbFormat:%s rgbDepth:%2d yuvRange:%7s (%d,%d) [%7s] (%d, %d, %d, %d) -> (%d, %d, %d, %d)\n", yuvDepth, rgbFormatToString(rgbFormat), rgbDepth, (yuvRange == AVIF_RANGE_LIMITED) ? "Limited" : "Full", i, j, matches ? "Match" : "NoMatch", srcPixel[0], srcPixel[1], srcPixel[2], srcPixel[3], dstPixel[0], dstPixel[1], dstPixel[2], dstPixel[3]); moveOn = AVIF_TRUE; break; } } } } avifRGBImageFreePixels(&intermediateRGB); avifRGBImageFreePixels(&dstRGB); // ---------------------------------------------------------------------- } } } avifRGBImageFreePixels(&srcRGB); } avifImageDestroy(image); #endif return 0; }
2.46875
2
2024-11-18T20:59:31.965576+00:00
2021-04-25T10:43:54
5b1f8308396527ad1f5b2b6b6098973554cb2297
{ "blob_id": "5b1f8308396527ad1f5b2b6b6098973554cb2297", "branch_name": "refs/heads/main", "committer_date": "2021-04-25T10:43:54", "content_id": "089716f71dbd47ab75166efafd616022a18ee2ca", "detected_licenses": [ "MIT" ], "directory_id": "1825d25811e1b8d879b3b4e2aa848d22e16fbbc1", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 127554000, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1105, "license": "MIT", "license_type": "permissive", "path": "/src/main.c", "provenance": "stackv2-0135.json.gz:240461", "repo_name": "Cxarli/cirq-compiler", "revision_date": "2021-04-25T10:43:54", "revision_id": "b2c09899a61cdb548c54a60f5058faf87019d9ff", "snapshot_id": "c7d9d503d9bfcef8fdcf69b039ec4ec17c41c933", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/Cxarli/cirq-compiler/b2c09899a61cdb548c54a60f5058faf87019d9ff/src/main.c", "visit_date": "2023-04-16T18:42:01.066863" }
stackv2
#include "utils.h" #include "compile.h" #include "run.h" void test(void); void test(void) { assert(tonumber("b10") == 0b10); assert(tonumber("o10") == 010); assert(tonumber("d-10") == -10); assert(tonumber("h10") == 0x10); assert(tonumber("h09") == 0x09); assert(tonumber("h7f") == 0x7f); assert(tonumber("b101010") == 0b101010); assert(tonumber("o76") == 076); printf("tests ok\n"); } int main(int argc, char *argv[]) { // Remove program name argv++; argc--; if (argc > 0) { // Get action char *action = argv[0]; // Remove action from arguments argv++; argc--; if (strcmp(action, "run") == 0) { run(argc, argv); return 0; } else if (strcmp(action, "compile") == 0) { compile(argc, argv); return 0; } else if (strcmp(action, "test") == 0) { test(); return 0; } } fprintf(stderr, "No (valid) action specified\nValid actions are:\n\trun\n\tcompile\n\ttest\n"); exit(1); }
2.65625
3
2024-11-18T20:59:32.673044+00:00
2017-04-06T00:25:31
17503e4fab6045815bb0ae5d64250d77caa7f61b
{ "blob_id": "17503e4fab6045815bb0ae5d64250d77caa7f61b", "branch_name": "refs/heads/master", "committer_date": "2017-04-06T00:25:31", "content_id": "0535d6169dd8682856e6087296205f086873d1ec", "detected_licenses": [ "MIT" ], "directory_id": "fea1acd2327f3a1bfede3366bbdd83fa36c614df", "extension": "c", "filename": "circleSquareTriangleRectangle.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 66963205, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3272, "license": "MIT", "license_type": "permissive", "path": "/cop2220/homework/circleSquareTriangleRectangle.c", "provenance": "stackv2-0135.json.gz:241246", "repo_name": "frankcash/cs-course-work", "revision_date": "2017-04-06T00:25:31", "revision_id": "af676b08f09ece8027aaf0b62e4feba8a03a892e", "snapshot_id": "bbfb6197fe4f385d60c67f99e85186a8784b83ae", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/frankcash/cs-course-work/af676b08f09ece8027aaf0b62e4feba8a03a892e/cop2220/homework/circleSquareTriangleRectangle.c", "visit_date": "2021-03-27T18:56:02.331715" }
stackv2
/** * Name: Charles Cash * Date: September 28, 2016 * Class: COP 2220 * Assignment: Circle, Square, Triangle, and Rectangle */ #include <stdio.h> #include <math.h> /** * Prints the initial output to direct the user */ int initOutput(void){ printf("This program will compute the area and perimeter of the selected geometric figure.\n"); printf("Please enter 0 for Circle.\n"); printf("Please enter 1 for Square.\n"); printf("Please enter 2 for Triangle.\n"); printf("Please enter 3 for Rectangle.\n"); return 0; } /** * Gets user input and then computes perimeter and area * Requires user input of radius */ int computeCircle(void){ double radius = 0.0 ; double perim = 0.0; double area = 0.0; const double PI = 3.14159; printf("Please enter the radius of the circle\n"); scanf("%lf", &radius); // 2pi * r; perim = 2 * PI * radius; // TODO: put in proper value of pi area = PI * (pow(radius, 2)); // TODO: put in proper value of pi printf("The perimeter is: %lf.\nThe area is: %lf.\n", perim, area); return 0; } /** * Gets user input and then computes perimeter and area * Requires user input of one side */ int computeSquare(void){ double side = 0.0; double perim = 0.0; double area = 0.0; printf("Please enter a side of the square\n"); scanf("%lf", &side); perim = 4 * side; area = (pow(side, 2)); printf("The perimeter is: %lf.\nThe area is: %lf.\n", perim, area); return 0; } /** * Gets user input and then computes perimeter and area * Requires user input of base and height and it's other two sides */ int computeTriangle(void){ double perim = 0.0; double area = 0.0; double base = 0.0; double width = 0.0; double sideA = 0.0; double sideB = 0.0; printf("Please enter the base of the triangle\n"); scanf("%lf", &base); printf("Please enter the width of the triangle\n"); scanf("%lf", &width); printf("Please enter one of the remaining sides of the triangle\n"); scanf("%lf", &sideA); printf("Please enter the remaining side of the triangle\n"); scanf("%lf", &sideB); perim = sideA + sideB + width; area = 0.5 * (base * width); printf("The perimeter is: %lf.\nThe area is: %lf.\n", perim, area); return 0; } /** * Gets user input and then computes perimeter and area * Requires user input of length and width */ int computeRectangle(void){ double length = 0.0; double width = 0.0; double perim = 0.0; double area = 0.0; printf("Please enter the length of the rectangle\n"); scanf("%lf", &length); printf("Please enter the width of the rectangle\n"); scanf("%lf", &width); perim = 2.0 * (length + width); area = length * width; printf("The perimeter is: %lf.\nThe area is: %lf.\n", perim, area); return 0; } /** * Controls the flow of the program. * Runs userInput to print program options. * Then runs the correct computation function. */ int main(void){ initOutput(); char userInput = ' '; scanf("%c", &userInput); switch(userInput){ case '0': computeCircle(); break; case '1': computeSquare(); break; case '2': computeTriangle(); break; case '3': computeRectangle(); break; default: printf("unexpected user input\n"); break; } return 0; }
4
4
2024-11-18T20:59:32.792640+00:00
2019-07-26T08:44:24
b8c857ec6052116a4b4d0097e632fab83336bbfc
{ "blob_id": "b8c857ec6052116a4b4d0097e632fab83336bbfc", "branch_name": "refs/heads/master", "committer_date": "2019-07-26T08:44:24", "content_id": "62ddaef79670f436fbcca7a6bfbb56ac2c2070c8", "detected_licenses": [ "Apache-2.0" ], "directory_id": "83b82055906b7c73627d432a88e62219c4e5bbc6", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4698, "license": "Apache-2.0", "license_type": "permissive", "path": "/app_bak_201906013_cirbuffer_ok/main/main.c", "provenance": "stackv2-0135.json.gz:241505", "repo_name": "andylao62/Ingenic_T20", "revision_date": "2019-07-26T08:44:24", "revision_id": "2aaabc3ae829b8e422607ee1217e6a7aa981f23d", "snapshot_id": "cc826c635e522939c0c019705bcee16103fb1d71", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/andylao62/Ingenic_T20/2aaabc3ae829b8e422607ee1217e6a7aa981f23d/app_bak_201906013_cirbuffer_ok/main/main.c", "visit_date": "2022-01-29T03:29:54.670672" }
stackv2
/*************************************************************************** * @file:main.c * @author: * @date: 5,29,2019 * @brief: 工程总入口文件 * @attention: ***************************************************************************/ #include <stdio.h> #include <unistd.h> #include<sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include "video.h" #include "osd.h" #include "encoder.h" #include "CircularBuffer.h" extern int get_image_size(E_IMAGE_SIZE image_size, int *width, int *height); /******************************************************************************* *@ Description :将循环缓存区的数据帧存储成H264文件 *@ Input :<image_size> 要录制的码流对应的分辨率 <time_len> 要录制时长 <file_name> 保存文件的文件名(带绝对路径) *@ Output : *@ Return : *@ attention : *******************************************************************************/ int save_h264_file_from_cirbuf(E_IMAGE_SIZE image_size,int time_len,char*file_name) { if(time_len <= 0 || NULL == file_name) { ERROR_LOG("Illegal parameter!\n"); return HLE_RET_EINVAL; } int userID,ret; CircularBuffer_t*handle = CircularBufferGetHandle(image_size); if(NULL == handle) { ERROR_LOG("CircularBufferGetHandle failed!\n"); return HLE_RET_ERROR; } userID = CircularBufferRequestUserID(handle); if(userID < 0) { ERROR_LOG("CircularBufferRequestUserID failed!\n"); return HLE_RET_ERROR; } /*---#打开文件------------------------------------------------------------*/ int fd = open(file_name,O_RDWR|O_CREAT|O_TRUNC,0755); if(fd < 0) { ERROR_LOG("open file(%s) failed!\n",file_name); goto ERR; } /*---#获取帧数据------------------------------------------------------------*/ void * data = NULL; FrameInfo_t info = {0}; struct timeval start_time; struct timeval current_time; int width,height; get_image_size(image_size,&width,&height); gettimeofday(&start_time,NULL); memcpy(&current_time,&start_time,sizeof(struct timeval)); int count_frame_num = 0; char* frame_type = NULL; /*注意采用系统时间去控制录制时长并不很准确,因为循环缓冲buffer 在读第一帧时会自动跳转到读指针所对应的IDR帧上,可能多读[0,gop-1]个帧数*/ while(current_time.tv_sec - start_time.tv_sec < time_len) { data = NULL; memset(&info,0,sizeof(info)); gettimeofday(&current_time,NULL); ret = CircularBufferReadOneFrame(userID,handle,&data,&info); if(ret < 0) { ERROR_LOG("CircularBufferReadOneFrame error!\n"); continue; } if(info.flag == 0xF8) frame_type = "I"; else if(info.flag == 0xF9) frame_type = "P"; else if(info.flag == 0xFA) frame_type = "A"; else continue; /*---#-写入到文件-----------------------------------------------------------*/ ret = write(fd,data,info.frmLength); if(ret != info.frmLength) { ERROR_LOG("write file(%s) failed!\n",file_name); goto ERR; } count_frame_num++; printf("record frame from circularbuffer...image_size[%dx%d] count_frame_num = %d frame_type = %s\n", width,height,count_frame_num,frame_type); } CircularBufferFreeUserID(handle,userID); close(fd); return HLE_RET_OK; ERR: CircularBufferFreeUserID(handle,userID); if(fd > 0) close(fd); return HLE_RET_ERROR; } int main(int argc,char*argv[]) { int ret; /*---#缓存池初始化------------------------------------------------------------*/ CircularBufferInit(); /*---#编码系统初始化----------------------------------------------------------*/ ret = encoder_system_init(); if(ret < 0) return -1; /*---#创建OSD实时更新线程-----------------------------------------------------*/ ret = timestamp_update_task(); if(ret < 0) goto ERR; /*---#创建h264实时编码帧获取线程----------------------------------------------*/ ret = video_get_h264_stream_task(); if(ret < 0) goto ERR; /*---#获取抓拍图像------------------------------------------------------------*/ sleep(2); //开机后不要太快抓拍,图像还没稳定下来,可能抓到黑屏 #if 0 ret = jpeg_get_one_snap(0); if(ret < 0) goto ERR; ret = jpeg_get_one_snap(1); if(ret < 0) goto ERR; #endif //DEBUG save_h264_file_from_cirbuf(IMAGE_SIZE_640x360,8,"/tmp/cirbuffer_chn_1.h264"); save_h264_file_from_cirbuf(IMAGE_SIZE_1920x1080,8,"/tmp/cirbuffer_chn_0.h264"); int i= 30;//延迟多少秒自动退出(DEBUG) while(1) { sleep(2); printf("...\n"); i--; } ERR: encoder_system_exit(); CircularBufferDestory(); return 0; }
2.546875
3
2024-11-18T20:59:33.742613+00:00
2017-04-27T20:14:04
94af833bf4960b0c9b71842698898519c5cfe00d
{ "blob_id": "94af833bf4960b0c9b71842698898519c5cfe00d", "branch_name": "refs/heads/master", "committer_date": "2017-04-27T20:14:04", "content_id": "e4c6464f02a1b8f9411a49d51a7dc34ba67a3aab", "detected_licenses": [ "Apache-2.0" ], "directory_id": "a0f3d39ef09c1e6e24dacca8c7901d90005a12f4", "extension": "h", "filename": "continuous.h", "fork_events_count": 0, "gha_created_at": "2017-04-27T20:07:42", "gha_event_created_at": "2017-04-27T20:07:42", "gha_language": null, "gha_license_id": null, "github_id": 89636106, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3885, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/include/clProbDist/continuous.h", "provenance": "stackv2-0135.json.gz:241762", "repo_name": "krocki/clProbDist", "revision_date": "2017-04-27T20:14:04", "revision_id": "f83b098c078af307d3c2077309683f9e03a5e0c1", "snapshot_id": "2a91d6a2cafa089342b4760cd79e433b5a0c52cb", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/krocki/clProbDist/f83b098c078af307d3c2077309683f9e03a5e0c1/src/include/clProbDist/continuous.h", "visit_date": "2021-01-20T04:05:15.490424" }
stackv2
/* This file is part of clProbDist. * * Copyright 2015-2016 Pierre L'Ecuyer, Universite de Montreal and Advanced Micro Devices, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Authors: * * Nabil Kemerchou <[email protected]> (2015) * David Munger <[email protected]> (2015) * Pierre L'Ecuyer <[email protected]> (2015) * */ #pragma once #ifndef CLPROBDIST_CONTINUOUSDIST_H #define CLPROBDIST_CONTINUOUSDIST_H #if defined(__APPLE__) || defined(__MACOSX) #include <OpenCL/cl.h> #else #include <CL/cl.h> #endif /*! @cond PRIVATE */ /*! @file continuous.h * @brief Common definitions for continuous distributions * * Implementation of continuous distributions should include this header * * This file provides default implementations for \f$\bar F(x)\f$ * and for \f$F^{-1}(u)\f$, the latter using the Brent-Dekker method (see * \cite iBRE71a and \cite iBRE73a) to find the inverse of a generic distribution * function \f$F(f)\f$. * This is a robust root-finding method, appropriate to find a root \f$x\f$ of * \f$F(x)=u\f$ when \f$u\f$ is known and if we have already a method to compute * \f$F\f$. * This is a special case. * */ typedef struct _clprobdistContinuousDist{ int decPrec; //Decimal degits of precision // [supportA, supportB] is the support of the pdf(x) cl_double supportA; //NEGATIVE INFINITY cl_double supportB; //POSITIVE INFINITY } clprobdistContinuous; // None of these functions are currently used by the library, but they could be // used in the future when more distributions are implemented. #if 0 /*********************************** * Constructor & destructor ***********************************/ cl_int clprobdistContinuousGetDecPrec(clprobdistContinuous* distObj, clprobdistStatus* err); cl_double clprobdistContinuousGetXinf(clprobdistContinuous* distObj, clprobdistStatus* err); cl_double clprobdistContinuousGetXsup(clprobdistContinuous* distObj, clprobdistStatus* err); clprobdistStatus clprobdistContinuousSetXinf(cl_double xa, clprobdistContinuous* distObj); clprobdistStatus clprobdistContinuousSetXsup(cl_double xb, clprobdistContinuous* distObj); /*********************************** * Abstract functions ***********************************/ cl_double clprobdistContinuousCDF(cl_double x, clprobdistStatus* err); clprobdistStatus findInterval(cl_double u, cl_double* iv, clprobdistContinuous* distObj, clprobdistStatus* err); cl_double clprobdistContinuousDensity(cl_double x, clprobdistStatus* err); cl_double clprobdistContinuousGetMean(clprobdistStatus* err); cl_double clprobdistContinuousGetVariance(clprobdistStatus* err); cl_double clprobdistContinuousGetStdDeviation(clprobdistStatus* err); /*********************************** * Default implementations of functions ***********************************/ cl_double clprobdistContinuousComplCDF(cl_double x, clprobdistStatus* err); cl_double clprobdistContinuousInverseBrent(cl_double a, cl_double b, cl_double u, cl_double tol, clprobdistContinuous* distObj, clprobdistStatus* err); cl_double clprobdistContinuousInverseBisection(cl_double u, clprobdistContinuous* distObj, clprobdistStatus* err); cl_double clprobdistContinuousInverseCDF(cl_double u, clprobdistContinuous* distObj, clprobdistStatus* err); #endif #endif /* CONTINUOUSDIST_H */ /*! @endcond */
2.0625
2
2024-11-18T20:59:34.451670+00:00
2021-08-19T03:27:58
0d63a9754567fbae7ce1658096244a6b91dd38e0
{ "blob_id": "0d63a9754567fbae7ce1658096244a6b91dd38e0", "branch_name": "refs/heads/master", "committer_date": "2021-08-19T03:27:58", "content_id": "691577f7d225059b85d22dd615de68997d2dd736", "detected_licenses": [ "MIT" ], "directory_id": "0f45dc544df4cdd213be07aa4cfd5e66d7b605b3", "extension": "h", "filename": "msgparse.h", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 240186265, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1441, "license": "MIT", "license_type": "permissive", "path": "/src/msgparse.h", "provenance": "stackv2-0135.json.gz:242416", "repo_name": "Daves1245/Chime", "revision_date": "2021-08-19T03:27:58", "revision_id": "424ab216539b2ad968e509b2f798e552546453cb", "snapshot_id": "f6a8269fd4a0aa350ed644efd67ea935583dc870", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/Daves1245/Chime/424ab216539b2ad968e509b2f798e552546453cb/src/msgparse.h", "visit_date": "2022-03-09T07:43:32.001353" }
stackv2
#ifndef MESSAGE_H #define MESSAGE_H #include <inttypes.h> #include <time.h> #include "user.h" #include "status.h" #include "types.h" #include "connection.h" #define TIMESTAMP_LEN 20 struct message { int id; /* Unique message id */ int uid; /* ID of user that message belongs to */ char timestmp[TIMESTAMP_LEN + 1]; char from[HANDLE_LEN + 1]; char txt[MAX_TEXT_LEN + 1]; /* Text message being sent */ int flags; /* message flags */ }; void hashmsg(struct message *msg, char *res); /* Hash a message and store it in res */ void timestamp(struct message *m); /* XXX - Timestamp a message */ void showmessage(const struct message *msg); /* Display a message to the screen */ void debugmessage(const struct message *msg); /* Debug print a message */ STATUS recvmessage(const struct connection *conn, struct message *msg); /* Receive a message coming in from sfd */ STATUS sendmessage(const struct connection *conn, const struct message *msg); /* Unpack a message, send it through fd */ STATUS makemessage(const struct user *usr, struct message *msg); /* Put user and other information in a message */ STATUS packmessage(struct message *msg); /* Pack msg with appropriate info */ STATUS timestampmessage(struct message *msg); /* Time stamp a message */ #endif
2.21875
2
2024-11-18T20:59:35.155120+00:00
2021-06-06T12:19:58
e7d11184b4d4ec4b2f65a56617467966355a1ce3
{ "blob_id": "e7d11184b4d4ec4b2f65a56617467966355a1ce3", "branch_name": "refs/heads/master", "committer_date": "2021-06-06T12:19:58", "content_id": "df7500708ca5fbbe6ba4b541632d369f288d5547", "detected_licenses": [ "MIT" ], "directory_id": "9a39da9203baa1cc274d0c67afc6b9cc508fa2e5", "extension": "c", "filename": "Source.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 188485089, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1204, "license": "MIT", "license_type": "permissive", "path": "/Fourth semester/Operation Systems/Exercises/ExerciseWithThreads/ExerciseWithThreads/Source.c", "provenance": "stackv2-0135.json.gz:242679", "repo_name": "stanislavstoyanov99/Technical-University-Projects", "revision_date": "2021-06-06T12:19:58", "revision_id": "d22934a4f0ed45626db5accaabe312cc0fb3086c", "snapshot_id": "a2bd84325a8ed77372a4b5d708bfbf9293e5535e", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/stanislavstoyanov99/Technical-University-Projects/d22934a4f0ed45626db5accaabe312cc0fb3086c/Fourth semester/Operation Systems/Exercises/ExerciseWithThreads/ExerciseWithThreads/Source.c", "visit_date": "2023-05-13T14:17:20.532421" }
stackv2
#include<stdio.h> #define HAVE_STRUCT_TIMESPEC #include<pthread.h> int data = 1; pthread_mutex_t lock; pthread_cond_t cond; void* EvenNumbers(void* tid) { while (data < 11) { pthread_mutex_lock(&lock); if (data % 2 == 0) { printf("th2:%d\n", data++); pthread_cond_signal(&cond); } else { pthread_cond_wait(&cond, &lock); } pthread_mutex_unlock(&lock); } pthread_exit(&data); } void* OddNumbers() { while (data < 11) { pthread_mutex_lock(&lock); if (data % 2 != 0) { printf("th1:%d\n", data++); pthread_cond_signal(&cond); } else { pthread_cond_wait(&cond, &lock); } pthread_mutex_unlock(&lock); } pthread_exit(&data); } int main() { pthread_mutex_init(&lock, NULL); pthread_cond_init(&cond, NULL); pthread_t tid[2]; pthread_create(&tid[0], NULL, EvenNumbers, (void*)&tid[0]); pthread_create(&tid[1], NULL, OddNumbers, (void*)&tid[1]); void* ret[2]; pthread_join(tid[0], &ret[0]); pthread_join(tid[1], &ret[1]); return 0; }
3
3
2024-11-18T20:59:35.331782+00:00
2021-12-08T20:30:08
a1cfea402db71490613f7faeea5b15dc17859761
{ "blob_id": "a1cfea402db71490613f7faeea5b15dc17859761", "branch_name": "refs/heads/develop", "committer_date": "2021-12-08T20:30:08", "content_id": "7f5ecc672d5b835d889cb63a0fd3e516bc0b0349", "detected_licenses": [ "MIT" ], "directory_id": "904a121225c10c3853404619bb772e65a5265f0d", "extension": "c", "filename": "base_test.c", "fork_events_count": 3, "gha_created_at": "2009-06-08T16:00:34", "gha_event_created_at": "2021-12-08T20:30:08", "gha_language": "C", "gha_license_id": "MIT", "github_id": 221698, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 28342, "license": "MIT", "license_type": "permissive", "path": "/tests/base_test.c", "provenance": "stackv2-0135.json.gz:242938", "repo_name": "zerotao/libzt", "revision_date": "2021-12-08T20:30:08", "revision_id": "53ce3f37deeb67f7cffd77a30113083b1c35eb66", "snapshot_id": "5eb7d39dfb9b3138c6289e0b30cf99d60772ceaf", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/zerotao/libzt/53ce3f37deeb67f7cffd77a30113083b1c35eb66/tests/base_test.c", "visit_date": "2021-12-10T23:33:58.608764" }
stackv2
#define ZT_WITH_UNIT #include <zt.h> #include <time.h> #include <string.h> #include <ctype.h> #include <libzt/zt_base.h> #define test_encoding(_base, _data, _len, _result1, _result2) \ do { unsigned char * cdata = (unsigned char *)_data; \ char * result = malloc(20); \ int ret; \ size_t len; \ bool bitisset = false; \ void **rptr = (void **)&result; \ memset(result, 0, 20); \ len = 20; \ bitisset = ZT_BIT_ISSET(_base->flags, zt_base_encode_with_padding); \ ZT_BIT_UNSET(_base->flags, zt_base_encode_with_padding); \ ret = zt_base_encode(_base, cdata, _len, rptr, &len); \ ZT_UNIT_ASSERT(test, !ret); \ ZT_UNIT_ASSERT(test, strcmp(result, _result1) == 0); \ ZT_UNIT_ASSERT(test, strlen(result) == len); \ if (bitisset) ZT_BIT_SET(_base->flags, zt_base_encode_with_padding); \ \ memset(result, 0, 20); \ len = 20; \ ret = zt_base_encode(_base, cdata, _len, rptr, &len); \ ZT_UNIT_ASSERT(test, !ret); \ ZT_UNIT_ASSERT(test, strcmp(result, _result2) == 0); \ ZT_UNIT_ASSERT(test, strlen(result) == len); zt_free(result);} while (0) #define test_decoding(_base, _data, _len, _result1, _result2) \ do { char * result = malloc(20); \ int ret; \ size_t len; \ void ** rptr = (void **)&result; \ memset(result, 0, 20); \ len = 20; \ ret = zt_base_decode(_base, (unsigned char *)_result1, strlen(_result1), rptr, &len); \ ZT_UNIT_ASSERT(test, !ret); \ ZT_UNIT_ASSERT(test, strcmp(result, (char *)_data) == 0); \ ZT_UNIT_ASSERT(test, strlen(result) == len); \ \ memset(result, 0, 20); \ len = 20; \ ret = zt_base_decode(_base, _result2, strlen(_result2), rptr, &len); \ ZT_UNIT_ASSERT(test, !ret); \ ZT_UNIT_ASSERT(test, strcmp(result, (char *)_data) == 0); \ ZT_UNIT_ASSERT(test, strlen(result) == len); zt_free(result);} while (0) static void encoding_tests(struct zt_unit_test * test, void * _data UNUSED) { char * data = NULL; char result[20]; #define OLEN sizeof(result) size_t len = OLEN; int ret; void ** rptr = 0; memset(result, 0, 20); rptr = (void **)&result; /* base 64 tests */ /* check bad param, no out_len */ data = "wee"; ret = zt_base_encode(zt_base64_rfc, data, strlen(data), rptr, NULL); ZT_UNIT_ASSERT(test, ret == -1); /* check null buff but valid bufsize */ ret = zt_base_encode(zt_base64_rfc, data, strlen(data), NULL, &len); ZT_UNIT_ASSERT(test, ret == 0); ZT_UNIT_ASSERT(test, len == 4); /* check insufficient output space */ len = 2; ret = zt_base_encode(zt_base64_rfc, data, strlen(data), rptr, &len); ZT_UNIT_ASSERT(test, ret == -2); ZT_UNIT_ASSERT(test, len == 4); /* check missing input */ len = OLEN; ret = zt_base_encode(zt_base64_rfc, NULL, 0, rptr, &len); ZT_UNIT_ASSERT(test, ret == 0); ZT_UNIT_ASSERT(test, len == 0); /* check empty input */ len = OLEN; ret = zt_base_encode(zt_base64_rfc, "", 0, rptr, &len); ZT_UNIT_ASSERT(test, ret == 0); ZT_UNIT_ASSERT(test, len == 0); /* check one char input */ test_encoding(zt_base64_rfc, "x", 1, "eA", "eA=="); /* check two char input */ test_encoding(zt_base64_rfc, "xy", 2, "eHk", "eHk="); /* simple non-padded input */ test_encoding(zt_base64_rfc, "One", 3, "T25l", "T25l"); /* simple double padded input */ test_encoding(zt_base64_rfc, "Once", 4, "T25jZQ", "T25jZQ=="); /* simple single padded input */ test_encoding(zt_base64_rfc, "Ounce", 5, "T3VuY2U", "T3VuY2U="); /* roll over */ test_encoding(zt_base64_rfc, "Amount", 6, "QW1vdW50", "QW1vdW50"); /* * non-ascii data * one byte */ { unsigned char udata[2] = { 0xF0, 0x00 }; test_encoding(zt_base64_rfc, udata, 1, "8A", "8A=="); } /* two bytes */ { unsigned char udata[3] = { 0xFF, 0xFD, 0x00 }; test_encoding(zt_base64_rfc, udata, 2, "//0", "//0="); } /* three bytes */ { unsigned char udata[4] = { 0xFF, 0xFF, 0xBE, 0x00 }; test_encoding(zt_base64_rfc, udata, 3, "//++", "//++"); } /* null bytes */ { unsigned char udata[3] = { 0xF0, 0x00, 0x00 }; test_encoding(zt_base64_rfc, udata, 2, "8AA", "8AA="); } /* RFC4648 test vectors */ test_encoding(zt_base64_rfc, "", 0, "", ""); test_encoding(zt_base64_rfc, "f", 1, "Zg", "Zg=="); test_encoding(zt_base64_rfc, "fo", 2, "Zm8", "Zm8="); test_encoding(zt_base64_rfc, "foo", 3, "Zm9v", "Zm9v"); test_encoding(zt_base64_rfc, "foob", 4, "Zm9vYg", "Zm9vYg=="); test_encoding(zt_base64_rfc, "fooba", 5, "Zm9vYmE", "Zm9vYmE="); test_encoding(zt_base64_rfc, "foobar", 6, "Zm9vYmFy", "Zm9vYmFy"); /* RFC4648 nopad test vectors */ test_encoding(zt_base64_rfc_nopad, "", 0, "", ""); test_encoding(zt_base64_rfc_nopad, "f", 1, "Zg", "Zg"); test_encoding(zt_base64_rfc_nopad, "fo", 2, "Zm8", "Zm8"); test_encoding(zt_base64_rfc_nopad, "foo", 3, "Zm9v", "Zm9v"); test_encoding(zt_base64_rfc_nopad, "foob", 4, "Zm9vYg", "Zm9vYg"); test_encoding(zt_base64_rfc_nopad, "fooba", 5, "Zm9vYmE", "Zm9vYmE"); test_encoding(zt_base64_rfc_nopad, "foobar", 6, "Zm9vYmFy", "Zm9vYmFy"); /* base 32 tests */ test_encoding(zt_base32_rfc, "", 0, "", ""); test_encoding(zt_base32_rfc, "f", 1, "MY", "MY======"); test_encoding(zt_base32_rfc, "fo", 2, "MZXQ", "MZXQ===="); test_encoding(zt_base32_rfc, "foo", 3, "MZXW6", "MZXW6==="); test_encoding(zt_base32_rfc, "foob", 4, "MZXW6YQ", "MZXW6YQ="); test_encoding(zt_base32_rfc, "fooba", 5, "MZXW6YTB", "MZXW6YTB"); test_encoding(zt_base32_rfc, "foobar", 6, "MZXW6YTBOI", "MZXW6YTBOI======"); /* base 32 hex tests */ test_encoding(zt_base32_hex, "", 0, "", ""); test_encoding(zt_base32_hex, "f", 1, "CO", "CO======"); test_encoding(zt_base32_hex, "fo", 2, "CPNG", "CPNG===="); test_encoding(zt_base32_hex, "foo", 3, "CPNMU", "CPNMU==="); test_encoding(zt_base32_hex, "foob", 4, "CPNMUOG", "CPNMUOG="); test_encoding(zt_base32_hex, "fooba", 5, "CPNMUOJ1", "CPNMUOJ1"); test_encoding(zt_base32_hex, "foobar", 6, "CPNMUOJ1E8", "CPNMUOJ1E8======"); /* base 16 tests */ test_encoding(zt_base16_rfc, "", 0, "", ""); test_encoding(zt_base16_rfc, "f", 1, "66", "66"); test_encoding(zt_base16_rfc, "fo", 2, "666F", "666F"); test_encoding(zt_base16_rfc, "foo", 3, "666F6F", "666F6F"); test_encoding(zt_base16_rfc, "foob", 4, "666F6F62", "666F6F62"); test_encoding(zt_base16_rfc, "fooba", 5, "666F6F6261", "666F6F6261"); test_encoding(zt_base16_rfc, "foobar", 6, "666F6F626172", "666F6F626172"); } /* encoding_tests */ static void decoding_tests(struct zt_unit_test * test, void * _data UNUSED) { char * result = alloca(20); char * resnul = NULL; size_t len; int ret; memset(result, 0, 20); /* bad param, no out len */ ret = zt_base_decode(zt_base64_rfc, "Zg", strlen("Zg"), (void **)&result, NULL); ZT_UNIT_ASSERT(test, ret == -1); /* output size calculation */ len = 1; ret = zt_base_decode(zt_base64_rfc, "Zg", strlen("Zg"), NULL, &len); ZT_UNIT_ASSERT(test, ret == 0); ZT_UNIT_ASSERT(test, len == 2); /* check insufficient output space */ len = 1; ret = zt_base_decode(zt_base64_rfc, "Zm8", strlen("Zm8"), (void **)&result, &len); ZT_UNIT_ASSERT(test, ret == -2); ZT_UNIT_ASSERT(test, len == 3); /* check missing input */ len = 2; ret = zt_base_decode(zt_base64_rfc, NULL, 0, (void **)&result, &len); ZT_UNIT_ASSERT(test, ret == 0); ZT_UNIT_ASSERT(test, len == 0); /* check empty input */ len = 2; ret = zt_base_decode(zt_base64_rfc, "", 0, (void **)&result, &len); ZT_UNIT_ASSERT(test, ret == 0); ZT_UNIT_ASSERT(test, len == 0); /* make sure dynamic allocation works */ len = 0; resnul = NULL; ret = zt_base_decode(zt_base64_rfc, "Zm9vYmFy", 8, (void **)&resnul, &len); ZT_UNIT_ASSERT(test, ret == 0); ZT_UNIT_ASSERT(test, resnul != NULL); ZT_UNIT_ASSERT(test, len == 6); ZT_UNIT_ASSERT(test, strncmp("foobar", resnul, len) == 0); zt_free(resnul); resnul = NULL; /* RFC4648 test vectors */ test_decoding(zt_base64_rfc, "", 0, "", ""); test_decoding(zt_base64_rfc, "f", 1, "Zg", "Zg=="); test_decoding(zt_base64_rfc, "fo", 2, "Zm8", "Zm8="); test_decoding(zt_base64_rfc, "foo", 3, "Zm9v", "Zm9v"); test_decoding(zt_base64_rfc, "foob", 4, "Zm9vYg", "Zm9vYg=="); test_decoding(zt_base64_rfc, "fooba", 5, "Zm9vYmE", "Zm9vYmE="); test_decoding(zt_base64_rfc, "foobar", 6, "Zm9vYmFy", "Zm9vYmFy"); #ifdef WIN32 test_decoding(zt_base64_rfc, "\r\nfoobar", 7, "Zm9vYmFy", "Zm9vYmFy"); test_decoding(zt_base64_rfc, "f\r\noobar", 7, "Zm9vYmFy", "Zm9vYmFy"); test_decoding(zt_base64_rfc, "fo\r\nobar", 7, "Zm9vYmFy", "Zm9vYmFy"); test_decoding(zt_base64_rfc, "foo\r\nbar", 7, "Zm9vYmFy", "Zm9vYmFy"); test_decoding(zt_base64_rfc, "foob\r\nar", 7, "Zm9vYmFy", "Zm9vYmFy"); test_decoding(zt_base64_rfc, "fooba\r\nr", 7, "Zm9vYmFy", "Zm9vYmFy"); test_decoding(zt_base64_rfc, "foobar\r\n", 7, "Zm9vYmFy", "Zm9vYmFy"); #endif /* base 32 tests */ test_decoding(zt_base32_rfc, "", 0, "", ""); test_decoding(zt_base32_rfc, "f", 1, "MY", "MY======"); test_decoding(zt_base32_rfc, "fo", 2, "MZXQ", "MZXQ===="); test_decoding(zt_base32_rfc, "foo", 3, "MZXW6", "MZXW6==="); test_decoding(zt_base32_rfc, "foob", 4, "MZXW6YQ", "MZXW6YQ="); test_decoding(zt_base32_rfc, "fooba", 5, "MZXW6YTB", "MZXW6YTB"); test_decoding(zt_base32_rfc, "foobar", 6, "MZXW6YTBOI", "MZXW6YTBOI======"); /* base 32 hex tests */ test_decoding(zt_base32_hex, "", 0, "", ""); test_decoding(zt_base32_hex, "f", 1, "CO", "CO======"); test_decoding(zt_base32_hex, "fo", 2, "CPNG", "CPNG===="); test_decoding(zt_base32_hex, "foo", 3, "CPNMU", "CPNMU==="); test_decoding(zt_base32_hex, "foob", 4, "CPNMUOG", "CPNMUOG="); test_decoding(zt_base32_hex, "fooba", 5, "CPNMUOJ1", "CPNMUOJ1"); test_decoding(zt_base32_hex, "foobar", 6, "CPNMUOJ1E8", "CPNMUOJ1E8======"); /* base 16 tests */ test_decoding(zt_base16_rfc, "", 0, "", ""); test_decoding(zt_base16_rfc, "f", 1, "66", "66"); test_decoding(zt_base16_rfc, "fo", 2, "666F", "666F"); test_decoding(zt_base16_rfc, "foo", 3, "666F6F", "666F6F"); test_decoding(zt_base16_rfc, "foob", 4, "666F6F62", "666F6F62"); test_decoding(zt_base16_rfc, "fooba", 5, "666F6F6261", "666F6F6261"); test_decoding(zt_base16_rfc, "foobar", 6, "666F6F626172", "666F6F626172"); { size_t i; char * in = NULL; size_t len = 0; char * out = NULL; size_t olen = 0; char * enc = NULL; size_t elen = 0; #if HAVE_SRANDOMDEV srandomdev(); #else srandom(time(NULL)); #endif while((len = random() % 1024) < 20); in = zt_calloc(char, len); /* out = zt_calloc(char, len); */ for(i=0; i < len; i++) { char k; while((k = random()) && !isprint(k)); in[i] = k; } zt_base_encode(zt_base64_rfc, in, len, (void **)&enc, &elen); zt_base_decode(zt_base64_rfc, enc, elen, (void **)&out, &olen); if(len != olen || strcmp(in, out) != 0) { ZT_UNIT_FAIL(test, "%s failed to encode/decode correctly %s:%d", in, __FILE__, __LINE__); } } } /* decoding_tests */ static void block_tests(struct zt_unit_test * test, void * _data UNUSED) { char text[] = { 47, 42, 10, 32, 42, 32, 97, 115, 115, 101, 114, 116, 95, 116, 101, 115, 116, 46, 99, 32, 32, 32, 32, 32, 32, 32, 32, 116, 101, 115, 116, 32, 97, 115, 115, 101, 114, 116, 105, 111, 110, 115, 10, 32, 42, 10, 32, 42, 32, 67, 111, 112, 121, 114, 105, 103, 104, 116, 32, 40, 67, 41, 32, 50, 48, 48, 48, 45, 50, 48, 48, 50, 44, 32, 50, 48, 48, 52, 44, 32, 50, 48, 48, 53, 44, 32, 74, 97, 115, 111, 110, 32, 76, 46, 32, 83, 104, 105, 102, 102, 101, 114, 32, 60, 106, 115, 104, 105, 102, 102, 101, 114, 64, 122, 101, 114, 111, 116, 97, 111, 46, 99, 111, 109, 62, 46, 32, 32, 65, 108, 108, 32, 82, 105, 103, 104, 116, 115, 32, 82, 101, 115, 101, 114, 118, 101, 100, 46, 10, 32, 42, 32, 83, 101, 101, 32, 102, 105, 108, 101, 32, 67, 79, 80, 89, 73, 78, 71, 32, 102, 111, 114, 32, 100, 101, 116, 97, 105, 108, 115, 46, 10, 32, 42, 10, 32, 42, 32, 36, 73, 100, 58, 32, 97, 115, 115, 101, 114, 116, 95, 116, 101, 115, 116, 46, 99, 44, 118, 32, 49, 46, 50, 32, 50, 48, 48, 51, 47, 48, 54, 47, 48, 57, 32, 49, 51, 58, 52, 50, 58, 49, 50, 32, 106, 115, 104, 105, 102, 102, 101, 114, 32, 69, 120, 112, 32, 36, 10, 32, 42, 10, 32, 42, 47, 10, 10, 47, 42, 10, 32, 42, 32, 68, 101, 115,99, 114, 105, 112, 116, 105, 111, 110, 58, 10, 32, 42, 47, 10, 35, 117, 110, 100, 101, 102, 32, 78, 68, 69, 66, 85, 71, 10, 35, 100, 101, 102, 105, 110, 101, 32, 90, 84, 95, 87, 73, 84, 72, 95, 85, 78, 73, 84, 10, 35, 105, 110, 99, 108, 117, 100, 101, 32, 60, 122, 116, 46, 104, 62, 10, 10, 35, 100, 101, 102, 105, 110, 101, 32, 68, 85, 77, 77, 89, 95, 76, 79, 71, 32, 34, 100, 117, 109, 109, 121, 46, 108, 111, 103, 34, 10, 10, 105, 110, 116, 32, 114, 114, 95, 118, 97, 108, 32, 61, 32, 48, 59, 10, 10, 118, 111, 105, 100, 10, 116, 101, 115, 116, 95, 114, 101, 116, 117, 114, 110, 40, 105, 110, 116, 32, 120, 41, 32, 123, 10, 32, 32, 32, 32, 122, 116, 95, 97, 115, 115, 101, 114, 116, 95, 114, 101, 116, 117, 114, 110, 40, 49, 61, 61, 120, 41, 59, 10, 32, 32, 32, 32, 114, 114, 95, 118, 97, 108, 32, 61, 32, 49, 59, 10, 125, 10, 10, 105, 110, 116, 10, 116, 101, 115, 116, 95, 114, 101, 116, 117, 114, 110, 118, 40, 105, 110, 116, 32, 120, 41, 32, 123, 10, 32, 32, 32, 32, 122, 116, 95, 97, 115, 115, 101, 114, 116, 95, 114, 101, 116, 117, 114, 110, 86, 40, 49, 61, 61, 120, 44, 32, 49, 41, 59, 10, 10, 32, 32, 32, 32, 114, 101, 116, 117, 114, 110, 32, 50, 59, 10, 125, 10, 10, 115, 116, 97, 116, 105, 99, 32, 118, 111, 105, 100, 10, 98, 97, 115, 105, 99, 95, 116, 101, 115, 116, 115, 40, 115, 116, 114, 117, 99, 116, 32, 122, 116, 95, 117, 110, 105, 116, 95, 116, 101, 115, 116, 32, 42, 116, 101, 115, 116, 32, 85, 78, 85, 83, 69, 68, 44, 32, 118, 111, 105, 100, 32, 42, 100, 97, 116, 97, 32, 85, 78, 85, 83, 69, 68, 41, 10, 123, 10, 32, 32, 32, 32, 47, 42, 32, 103, 101, 116, 32, 114, 105, 100, 32, 111, 102, 32, 116, 104, 101, 32, 108, 111, 103, 32, 109, 101, 115, 115, 97, 103, 101, 32, 102, 111, 114, 32, 116, 104, 101, 32, 109, 111, 109, 101, 110, 116, 32, 42, 47, 10, 32, 32, 32, 32, 122, 116, 95, 108, 111, 103, 95, 116, 121, 32, 42, 32, 111, 108, 111, 103, 59, 10, 32, 32, 32, 32, 122, 116, 95, 108, 111, 103, 95, 116, 121, 32, 42, 32, 108, 111, 103, 59, 10, 32, 32, 32, 32, 105, 110, 116, 32, 32, 32, 32, 32, 32, 32, 32, 32, 105, 32, 61, 32, 49, 59, 10, 32, 32, 32, 32, 105, 110, 116, 32, 32, 32, 32, 32, 32, 32, 32, 32, 114, 105, 95, 118,97, 108, 32, 61, 32, 48, 59, 10, 10, 32, 32, 32, 32, 108, 111, 103, 32, 61, 32, 122, 116, 95, 108,111, 103, 95, 102, 105, 108, 101, 40, 68, 85, 77, 77, 89, 95, 76, 79, 71, 44, 32, 48, 44, 32, 48, 41, 59, 10, 32, 32, 32, 32, 111, 108, 111, 103, 32, 61, 32, 122, 116, 95, 108, 111, 103, 95, 108, 111, 103, 103, 101, 114, 40, 108, 111, 103, 41, 59, 10, 10, 32, 32, 32, 32, 122, 116, 95, 97, 115, 115, 101, 114, 116, 40, 49, 32, 61, 61, 32, 105, 41, 59, 10, 10, 32, 32, 32, 32, 114, 114, 95, 118,97, 108, 32, 61, 32, 48, 59, 10, 32, 32, 32, 32, 116, 101, 115, 116, 95, 114, 101, 116, 117, 114, 110, 40, 48, 41, 59, 10, 32, 32, 32, 32, 90, 84, 95, 85, 78, 73, 84, 95, 65, 83, 83, 69, 82, 84, 40, 116, 101, 115, 116, 44, 32, 114, 114, 95, 118, 97, 108, 32, 61, 61, 32, 48, 41, 59, 10, 10, 32, 32, 32, 32, 114, 114, 95, 118, 97, 108, 32, 61, 32, 48, 59, 10, 32, 32, 32, 32, 116, 101, 115, 116, 95, 114, 101, 116, 117, 114, 110, 40, 49, 41, 59, 10, 32, 32, 32, 32, 90, 84, 95, 85, 78, 73, 84, 95, 65, 83, 83, 69, 82, 84, 40, 116, 101, 115, 116, 44, 32, 114, 114, 95, 118, 97, 108, 32, 61, 61, 32, 49, 41, 59, 10, 10, 32, 32, 32, 32, 114, 105, 95, 118, 97, 108, 32, 61, 32, 116, 101, 115, 116,95, 114, 101, 116, 117, 114, 110, 118, 40, 48, 41, 59, 10, 32, 32, 32, 32, 90, 84, 95, 85, 78, 73, 84, 95, 65, 83, 83, 69, 82, 84, 40, 116, 101, 115, 116, 44, 32, 114, 105, 95, 118, 97, 108, 32, 61, 61, 32, 49, 41, 59, 10, 10, 32, 32, 32, 32, 114, 105, 95, 118, 97, 108, 32, 61, 32, 116, 101, 115,116, 95, 114, 101, 116, 117, 114, 110, 118, 40, 49, 41, 59, 10, 32, 32, 32, 32, 90, 84, 95, 85, 78, 73, 84, 95, 65, 83, 83, 69, 82, 84, 40, 116, 101, 115, 116, 44, 32, 114, 105, 95, 118, 97, 108, 32, 61, 61, 32, 50, 41, 59, 10, 10, 32, 32, 32, 32, 122, 116, 95, 108, 111, 103, 95, 108, 111, 103, 103, 101, 114, 40, 111, 108, 111, 103, 41, 59, 10, 32, 32, 32, 32, 122, 116, 95, 108, 111, 103, 95, 99, 108, 111, 115, 101, 40, 108, 111, 103, 41, 59, 10, 10, 35, 105, 102, 32, 33, 100, 101, 102, 105, 110, 101, 100, 40, 87, 73, 78, 51, 50, 41, 10, 32, 32, 32, 32, 117, 110, 108, 105, 110, 107, 40, 68, 85, 77, 77, 89, 95, 76, 79, 71, 41, 59, 10, 35, 101, 110, 100, 105, 102, 10, 125, 10, 10, 105, 110, 116, 10, 114, 101, 103, 105, 115, 116, 101, 114, 95, 97, 115, 115, 101, 114, 116, 95, 115, 117, 105, 116, 101, 40, 115, 116, 114, 117, 99, 116, 32, 122, 116, 95, 117, 110, 105, 116, 32, 42, 117, 110, 105, 116, 41, 10, 123, 10, 32, 32, 32, 32, 115, 116, 114, 117, 99, 116, 32, 122, 116, 95, 117, 110, 105, 116, 95, 115, 117, 105, 116, 101, 32, 42, 32, 115, 117, 105, 116, 101, 59, 10, 10, 32, 32, 32, 32, 115, 117, 105, 116, 101, 32, 61, 32, 122, 116, 95, 117, 110, 105, 116, 95, 114, 101, 103, 105, 115, 116, 101, 114, 95, 115, 117, 105, 116, 101, 40, 117, 110, 105, 116, 44, 32, 34, 97, 115, 115, 101, 114, 116, 32, 116, 101, 115, 116, 115, 34, 44, 32, 78, 85, 76, 76, 44, 32, 78, 85, 76, 76, 44, 32, 78, 85, 76, 76, 41, 59, 10, 32, 32, 32, 32, 122, 116, 95, 117, 110, 105, 116, 95, 114, 101, 103, 105, 115, 116, 101, 114, 95, 116, 101, 115, 116, 40, 115, 117, 105, 116, 101, 44, 32, 34, 98, 97, 115, 105, 99, 34, 44, 32, 98, 97, 115, 105, 99, 95, 116, 101, 115, 116, 115, 41, 59, 10, 32, 32, 32, 32, 114, 101, 116, 117, 114, 110, 32, 48, 59, 10, 125, 10, 0 }; const char * encoded = "LyoKICogYXNzZXJ0X3Rlc3QuYyAgICAgICAgdGVzdCBhc3NlcnRpb25zCiAqCiAq" "IENvcHlyaWdodCAoQykgMjAwMC0yMDAyLCAyMDA0LCAyMDA1LCBKYXNvbiBMLiBT" "aGlmZmVyIDxqc2hpZmZlckB6ZXJvdGFvLmNvbT4uICBBbGwgUmlnaHRzIFJlc2Vy" "dmVkLgogKiBTZWUgZmlsZSBDT1BZSU5HIGZvciBkZXRhaWxzLgogKgogKiAkSWQ6" "IGFzc2VydF90ZXN0LmMsdiAxLjIgMjAwMy8wNi8wOSAxMzo0MjoxMiBqc2hpZmZl" "ciBFeHAgJAogKgogKi8KCi8qCiAqIERlc2NyaXB0aW9uOgogKi8KI3VuZGVmIE5E" "RUJVRwojZGVmaW5lIFpUX1dJVEhfVU5JVAojaW5jbHVkZSA8enQuaD4KCiNkZWZp" "bmUgRFVNTVlfTE9HICJkdW1teS5sb2ciCgppbnQgcnJfdmFsID0gMDsKCnZvaWQK" "dGVzdF9yZXR1cm4oaW50IHgpIHsKICAgIHp0X2Fzc2VydF9yZXR1cm4oMT09eCk7" "CiAgICBycl92YWwgPSAxOwp9CgppbnQKdGVzdF9yZXR1cm52KGludCB4KSB7CiAg" "ICB6dF9hc3NlcnRfcmV0dXJuVigxPT14LCAxKTsKCiAgICByZXR1cm4gMjsKfQoK" "c3RhdGljIHZvaWQKYmFzaWNfdGVzdHMoc3RydWN0IHp0X3VuaXRfdGVzdCAqdGVz" "dCBVTlVTRUQsIHZvaWQgKmRhdGEgVU5VU0VEKQp7CiAgICAvKiBnZXQgcmlkIG9m" "IHRoZSBsb2cgbWVzc2FnZSBmb3IgdGhlIG1vbWVudCAqLwogICAgenRfbG9nX3R5" "ICogb2xvZzsKICAgIHp0X2xvZ190eSAqIGxvZzsKICAgIGludCAgICAgICAgIGkg" "PSAxOwogICAgaW50ICAgICAgICAgcmlfdmFsID0gMDsKCiAgICBsb2cgPSB6dF9s" "b2dfZmlsZShEVU1NWV9MT0csIDAsIDApOwogICAgb2xvZyA9IHp0X2xvZ19sb2dn" "ZXIobG9nKTsKCiAgICB6dF9hc3NlcnQoMSA9PSBpKTsKCiAgICBycl92YWwgPSAw" "OwogICAgdGVzdF9yZXR1cm4oMCk7CiAgICBaVF9VTklUX0FTU0VSVCh0ZXN0LCBy" "cl92YWwgPT0gMCk7CgogICAgcnJfdmFsID0gMDsKICAgIHRlc3RfcmV0dXJuKDEp" "OwogICAgWlRfVU5JVF9BU1NFUlQodGVzdCwgcnJfdmFsID09IDEpOwoKICAgIHJp" "X3ZhbCA9IHRlc3RfcmV0dXJudigwKTsKICAgIFpUX1VOSVRfQVNTRVJUKHRlc3Qs" "IHJpX3ZhbCA9PSAxKTsKCiAgICByaV92YWwgPSB0ZXN0X3JldHVybnYoMSk7CiAg" "ICBaVF9VTklUX0FTU0VSVCh0ZXN0LCByaV92YWwgPT0gMik7CgogICAgenRfbG9n" "X2xvZ2dlcihvbG9nKTsKICAgIHp0X2xvZ19jbG9zZShsb2cpOwoKI2lmICFkZWZp" "bmVkKFdJTjMyKQogICAgdW5saW5rKERVTU1ZX0xPRyk7CiNlbmRpZgp9CgppbnQK" "cmVnaXN0ZXJfYXNzZXJ0X3N1aXRlKHN0cnVjdCB6dF91bml0ICp1bml0KQp7CiAg" "ICBzdHJ1Y3QgenRfdW5pdF9zdWl0ZSAqIHN1aXRlOwoKICAgIHN1aXRlID0genRf" "dW5pdF9yZWdpc3Rlcl9zdWl0ZSh1bml0LCAiYXNzZXJ0IHRlc3RzIiwgTlVMTCwg" "TlVMTCwgTlVMTCk7CiAgICB6dF91bml0X3JlZ2lzdGVyX3Rlc3Qoc3VpdGUsICJi" "YXNpYyIsIGJhc2ljX3Rlc3RzKTsKICAgIHJldHVybiAwOwp9Cg=="; const char * encoded2 = \ "LyoKICogYXNzZXJ0X3Rlc3QuYyAgICAgICAgdGVzdCBhc3NlcnRpb25zCiAqCiAq \ IENvcHlyaWdodCAoQykgMjAwMC0yMDAyLCAyMDA0LCAyMDA1LCBKYXNvbiBMLiBT \ aGlmZmVyIDxqc2hpZmZlckB6ZXJvdGFvLmNvbT4uICBBbGwgUmlnaHRzIFJlc2Vy \ dmVkLgogKiBTZWUgZmlsZSBDT1BZSU5HIGZvciBkZXRhaWxzLgogKgogKiAkSWQ6 \ IGFzc2VydF90ZXN0LmMsdiAxLjIgMjAwMy8wNi8wOSAxMzo0MjoxMiBqc2hpZmZl \ ciBFeHAgJAogKgogKi8KCi8qCiAqIERlc2NyaXB0aW9uOgogKi8KI3VuZGVmIE5E \ RUJVRwojZGVmaW5lIFpUX1dJVEhfVU5JVAojaW5jbHVkZSA8enQuaD4KCiNkZWZp \ bmUgRFVNTVlfTE9HICJkdW1teS5sb2ciCgppbnQgcnJfdmFsID0gMDsKCnZvaWQK \ dGVzdF9yZXR1cm4oaW50IHgpIHsKICAgIHp0X2Fzc2VydF9yZXR1cm4oMT09eCk7 \ CiAgICBycl92YWwgPSAxOwp9CgppbnQKdGVzdF9yZXR1cm52KGludCB4KSB7CiAg \ ICB6dF9hc3NlcnRfcmV0dXJuVigxPT14LCAxKTsKCiAgICByZXR1cm4gMjsKfQoK \ c3RhdGljIHZvaWQKYmFzaWNfdGVzdHMoc3RydWN0IHp0X3VuaXRfdGVzdCAqdGVz \ dCBVTlVTRUQsIHZvaWQgKmRhdGEgVU5VU0VEKQp7CiAgICAvKiBnZXQgcmlkIG9m \ IHRoZSBsb2cgbWVzc2FnZSBmb3IgdGhlIG1vbWVudCAqLwogICAgenRfbG9nX3R5 \ ICogb2xvZzsKICAgIHp0X2xvZ190eSAqIGxvZzsKICAgIGludCAgICAgICAgIGkg \ PSAxOwogICAgaW50ICAgICAgICAgcmlfdmFsID0gMDsKCiAgICBsb2cgPSB6dF9s \ b2dfZmlsZShEVU1NWV9MT0csIDAsIDApOwogICAgb2xvZyA9IHp0X2xvZ19sb2dn \ ZXIobG9nKTsKCiAgICB6dF9hc3NlcnQoMSA9PSBpKTsKCiAgICBycl92YWwgPSAw \ OwogICAgdGVzdF9yZXR1cm4oMCk7CiAgICBaVF9VTklUX0FTU0VSVCh0ZXN0LCBy \ cl92YWwgPT0gMCk7CgogICAgcnJfdmFsID0gMDsKICAgIHRlc3RfcmV0dXJuKDEp \ OwogICAgWlRfVU5JVF9BU1NFUlQodGVzdCwgcnJfdmFsID09IDEpOwoKICAgIHJp \ X3ZhbCA9IHRlc3RfcmV0dXJudigwKTsKICAgIFpUX1VOSVRfQVNTRVJUKHRlc3Qs \ IHJpX3ZhbCA9PSAxKTsKCiAgICByaV92YWwgPSB0ZXN0X3JldHVybnYoMSk7CiAg \ ICBaVF9VTklUX0FTU0VSVCh0ZXN0LCByaV92YWwgPT0gMik7CgogICAgenRfbG9n \ X2xvZ2dlcihvbG9nKTsKICAgIHp0X2xvZ19jbG9zZShsb2cpOwoKI2lmICFkZWZp \ bmVkKFdJTjMyKQogICAgdW5saW5rKERVTU1ZX0xPRyk7CiNlbmRpZgp9CgppbnQK \ cmVnaXN0ZXJfYXNzZXJ0X3N1aXRlKHN0cnVjdCB6dF91bml0ICp1bml0KQp7CiAg \ ICBzdHJ1Y3QgenRfdW5pdF9zdWl0ZSAqIHN1aXRlOwoKICAgIHN1aXRlID0genRf \ dW5pdF9yZWdpc3Rlcl9zdWl0ZSh1bml0LCAiYXNzZXJ0IHRlc3RzIiwgTlVMTCwg \ TlVMTCwgTlVMTCk7CiAgICB6dF91bml0X3JlZ2lzdGVyX3Rlc3Qoc3VpdGUsICJi \ YXNpYyIsIGJhc2ljX3Rlc3RzKTsKICAgIHJldHVybiAwOwp9Cg=="; char * out = NULL; size_t outlen = 0; ZT_UNIT_ASSERT(test, zt_base_encode(zt_base64_rfc, text, strlen(text), (void **)&out, &outlen) == 0); ZT_UNIT_ASSERT(test, strcmp(out, encoded) == 0); free(out); out = NULL; outlen = 0; ZT_UNIT_ASSERT(test, zt_base_decode(zt_base64_rfc, encoded, strlen(encoded), (void **)&out, &outlen) == 0); ZT_UNIT_ASSERT(test, strcmp(out, text) == 0); free(out); out = NULL; outlen = 0; ZT_UNIT_ASSERT(test, zt_base_decode(zt_base64_rfc, encoded2, strlen(encoded2), (void **)&out, &outlen) == 0); ZT_UNIT_ASSERT(test, strcmp(out, text) == 0); free(out); } int register_base_suite(struct zt_unit * unit) { struct zt_unit_suite * suite; suite = zt_unit_register_suite(unit, "baseN", NULL, NULL, NULL); zt_unit_register_test(suite, "encoding", encoding_tests); zt_unit_register_test(suite, "decoding", decoding_tests); zt_unit_register_test(suite, "block", block_tests); return 0; }
2.203125
2
2024-11-18T20:59:35.430674+00:00
2021-08-14T20:42:47
8a71d8a4332e285eb7b5e5dd058dc8b7ace1451c
{ "blob_id": "8a71d8a4332e285eb7b5e5dd058dc8b7ace1451c", "branch_name": "refs/heads/main", "committer_date": "2021-08-14T20:42:47", "content_id": "0216383caa54485ad28a74c49c024a76a83e6d9d", "detected_licenses": [ "MIT" ], "directory_id": "2160092435e1d2d130fb36310e59b094765ea0d2", "extension": "c", "filename": "phoneline.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1703, "license": "MIT", "license_type": "permissive", "path": "/17Tele-type/phoneline.c", "provenance": "stackv2-0135.json.gz:243067", "repo_name": "kevspace/MKS65", "revision_date": "2021-08-14T20:42:47", "revision_id": "ad4fd3a6ab30be4c85fada12d5a1490eef23b370", "snapshot_id": "cbd86c6ecc47efcdfa6558d95af70c2d1fbca65d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kevspace/MKS65/ad4fd3a6ab30be4c85fada12d5a1490eef23b370/17Tele-type/phoneline.c", "visit_date": "2023-07-08T06:28:00.289879" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/sem.h> union semun { int val; /* Value for SETVAL */ struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */ unsigned short *array; /* Array for GETALL, SETALL */ struct seminfo *__buf; /* Buffer for IPC_INFO (Linux-specific) */ }; int main() { struct sembuf sb; key_t mykey = ftok("tele.c", 'R'); int shmid = shmget(mykey, 2048, 0); int semid = semget(mykey, 1, 0); sb.sem_num = 0, sb.sem_flg = SEM_UNDO, sb.sem_op = -1; if ((shmid == -1) || (semid == -1)) { printf("Error: %s\n", strerror(errno)); return -1; } printf("Checking the availability of the shared memory segment!\n"); if (!semctl(semid, 0, GETVAL, 1)) { printf("Segment unavailable, exiting\n"); return -1; } semop(semid, &sb, 1); char *data = shmat(shmid, 0, 0); if (*data == -1) printf("Error: %s\n", strerror(errno)); else if (!*data) printf("No story yet!\n"); else { int fd = open("story", O_RDONLY); lseek(fd, -1 * *data, SEEK_END); //go back # of bytes in len of data char *buff = malloc(*data); read(fd, buff, *data); printf("Last line: \n%s\n", buff); close(fd); free(buff); } printf("Please insert the next line of the file:\n"); char input[2048]; fgets(input, sizeof(input), stdin); int fd = open("story", O_WRONLY | O_APPEND); *data = strlen(input); write(fd, input, *data); close(fd); shmdt(data); sb.sem_op = 1; semop(semid, &sb, 1); return 0; }
2.703125
3
2024-11-18T20:59:35.575177+00:00
2021-09-15T16:26:40
f0c82e4e24cbaab99e49c464b21c28b9f9f6091e
{ "blob_id": "f0c82e4e24cbaab99e49c464b21c28b9f9f6091e", "branch_name": "refs/heads/master", "committer_date": "2021-09-15T16:26:40", "content_id": "084fabe3166da6b7f6d157feb7f2dee89a3809cb", "detected_licenses": [ "MIT" ], "directory_id": "16fce8d3100da2e1ac09cf2a56323cc7ccf5949a", "extension": "c", "filename": "A6_2.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 321568055, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2065, "license": "MIT", "license_type": "permissive", "path": "/A6/A6_2.c", "provenance": "stackv2-0135.json.gz:243198", "repo_name": "IshanManchanda/pds-lab-autumn2020-solutions", "revision_date": "2021-09-15T16:26:40", "revision_id": "9704b0c6ba5dc3dfeecf73da05d43738c5638a49", "snapshot_id": "d5dbbfb0f14f200ce42ffc54adfcda3e46c3af07", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/IshanManchanda/pds-lab-autumn2020-solutions/9704b0c6ba5dc3dfeecf73da05d43738c5638a49/A6/A6_2.c", "visit_date": "2023-08-12T00:29:28.703392" }
stackv2
/* PDS Lab Autumn 2020, Assignment 6, Problem 2. * Ishan Manchanda, 19'th Jan 2021 */ #include <stdio.h> #include <math.h> #define PI 3.14159 struct Comp { double real, imag; }; void comp_print(struct Comp a) { char sign = (a.imag < 0) ? '-' : '+'; printf("%.2lf %c i%.2lf\n", a.real, sign, a.imag); } struct Comp comp_sum(struct Comp a, struct Comp b) { struct Comp sum; // Standard complex number sum formula sum.real = a.real + b.real; sum.imag = a.imag + b.imag; return sum; } struct Comp comp_product(struct Comp a, struct Comp b) { struct Comp product; // Standard complex number product formula product.real = a.real * b.real - a.imag * b.imag; product.imag = a.real * b.imag + a.imag * b.real; return product; } void comp_print_polar(struct Comp a) { // Convert complex number to polar coordinates // r is found simply using the Pythagoras Theorem. double r = sqrt(a.real * a.real + a.imag * a.imag); /* To find the argument, we use the atan2 function of math.h * which takes into account the signs of the numerator and denominator * to give an arctan value as per the sign convention in the Argand plane. * Then, we multiply by 180 / PI to convert from radians to degrees. */ double theta = atan2(a.imag, a.real) * 180 / PI; printf("r = %.2lf, arg = %.2lf degrees\n", r, theta); } int main() { struct Comp a, b, sum, product; printf("Enter the real and imaginary parts as space-separated real numbers.\n"); printf("Enter parts of complex number a: "); scanf("%lf %lf", &a.real, &a.imag); printf("Enter parts of complex number b: "); scanf("%lf %lf", &b.real, &b.imag); printf("\na = "); comp_print(a); printf("Polar form of a: "); comp_print_polar(a); printf("\nb = "); comp_print(b); printf("Polar form of b: "); comp_print_polar(b); sum = comp_sum(a, b); printf("\na + b = "); comp_print(sum); printf("Polar form of a + b: "); comp_print_polar(sum); product = comp_product(a, b); printf("\na * b = "); comp_print(product); printf("Polar form of a * b: "); comp_print_polar(product); }
3.953125
4
2024-11-18T20:59:35.924111+00:00
2018-03-23T10:28:29
f04ee1b9bfcecec6753be78f67d8412826bffc84
{ "blob_id": "f04ee1b9bfcecec6753be78f67d8412826bffc84", "branch_name": "refs/heads/master", "committer_date": "2018-03-23T10:28:49", "content_id": "523fbfb9fd5b66c6a8773206b2d8ae1c5e703347", "detected_licenses": [ "MIT" ], "directory_id": "8ba37b0d3d973a67007e96adef2aae97731aadc4", "extension": "c", "filename": "quick-sort.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 91064956, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 448, "license": "MIT", "license_type": "permissive", "path": "/sort/quick-sort.c", "provenance": "stackv2-0135.json.gz:243591", "repo_name": "DragonTang/algorithm", "revision_date": "2018-03-23T10:28:29", "revision_id": "bab27465440e77766727f7251fd661cdd820e4d9", "snapshot_id": "884c656f6bb3164fdeb531f2b98f150cde82af83", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/DragonTang/algorithm/bab27465440e77766727f7251fd661cdd820e4d9/sort/quick-sort.c", "visit_date": "2020-12-30T17:11:19.291689" }
stackv2
void quickSort (int *array, int left, int right) { if (left >= right) return; int key = array[left]; int j = right; int i = left; while (i < j) { while (i < j && array[j] >= key) j--; if (i != j) array[i] = array[j]; while (i < j && array[i] <= key) i++; if (i != j) array[j] = array[i]; } if (i != left) array[i] = key; quickSort(array, left, i - 1); quickSort(array, i + 1, right); }
2.9375
3
2024-11-18T20:59:38.354497+00:00
2018-06-11T06:53:37
e7b81a8de89cc95b947faf853b3158204737c8d7
{ "blob_id": "e7b81a8de89cc95b947faf853b3158204737c8d7", "branch_name": "refs/heads/master", "committer_date": "2018-06-11T06:53:37", "content_id": "3092d58efd4116ef30afe89d2a5ae8bc6b8a0ba6", "detected_licenses": [ "MIT" ], "directory_id": "529794af025f740d4856d34522a566aeeb52ecd2", "extension": "h", "filename": "stdarg.h", "fork_events_count": 0, "gha_created_at": "2018-04-08T19:23:33", "gha_event_created_at": "2018-06-05T01:01:10", "gha_language": "C", "gha_license_id": "MIT", "github_id": 128674376, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1337, "license": "MIT", "license_type": "permissive", "path": "/libc/include/stdarg.h", "provenance": "stackv2-0135.json.gz:243988", "repo_name": "Luigi30/68k-sbc", "revision_date": "2018-06-11T06:53:37", "revision_id": "83cc3a5294bb1f13b1f8fbdf0cb97dc29a5e900b", "snapshot_id": "09e24cbc70007358421061a03a1cccf1259b212d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Luigi30/68k-sbc/83cc3a5294bb1f13b1f8fbdf0cb97dc29a5e900b/libc/include/stdarg.h", "visit_date": "2020-03-09T07:51:37.329282" }
stackv2
#pragma once typedef char *va_list; /* * Amount of space required in an argument list (ie. the stack) for an * argument of type t. */ #define __va_argsiz(t) \ (((sizeof(t) + sizeof(int) - 1) / sizeof(int)) * sizeof(int)) /* * Start variable argument list processing by setting AP to point to the * argument after pN. */ #ifdef __GNUC__ /* * In GNU the stack is not necessarily arranged very neatly in order to * pack shorts and such into a smaller argument list. Fortunately a * neatly arranged version is available through the use of __builtin_next_arg. */ #define va_start(ap, pN) \ ((ap) = ((va_list) __builtin_next_arg(pN))) #else /* * For a simple minded compiler this should work (it works in GNU too for * vararg lists that don't follow shorts and such). */ #define va_start(ap, pN) \ ((ap) = ((va_list) (&pN) + __va_argsiz(pN))) #endif /* * End processing of variable argument list. In this case we do nothing. */ #define va_end(ap) ((void)0) /* * Increment ap to the next argument in the list while returing a * pointer to what ap pointed to first, which is of type t. * * We cast to void* and then to t* because this avoids a warning about * increasing the alignment requirement. */ #define va_arg(ap, t) \ (((ap) = (ap) + __va_argsiz(t)), \ *((t*) (void*) ((ap) - __va_argsiz(t))))
3.078125
3
2024-11-18T20:59:38.597215+00:00
2014-04-08T22:42:19
94ebc3b60109a7a3d64e57beae72d137af17db73
{ "blob_id": "94ebc3b60109a7a3d64e57beae72d137af17db73", "branch_name": "refs/heads/master", "committer_date": "2014-04-08T22:42:19", "content_id": "b25eed67bcd2b1b79c373ad28042349c60dd0a8a", "detected_licenses": [ "MIT" ], "directory_id": "b72d7e0a36bc783957fe5319439ef2a878a93105", "extension": "c", "filename": "error.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1517, "license": "MIT", "license_type": "permissive", "path": "/util/src/error.c", "provenance": "stackv2-0135.json.gz:244118", "repo_name": "kcoltin/blackjack", "revision_date": "2014-04-08T22:42:19", "revision_id": "8e1ce36b267eeb59216886cd0c629a59c41b8bcb", "snapshot_id": "164a52cc674c98fc6ad7a1f49c97520db15aeaf7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kcoltin/blackjack/8e1ce36b267eeb59216886cd0c629a59c41b8bcb/util/src/error.c", "visit_date": "2021-01-15T13:45:11.040843" }
stackv2
#include "error.h" #include <stdio.h> #include <stdlib.h> //------------------------------------------------------------------------------ // Throws a miscellaneous error, that may have any arbitrary error message // passed to it. //------------------------------------------------------------------------------ void throwErr (const char *message, const char *functionname) { printf("Error in function %s: %s\n", functionname, message); exit(EXIT_FAILURE); } //------------------------------------------------------------------------------ // Causes a program to exit after displaying an error message, after a failed // call to malloc (or realloc, etc). // varname: String that should contain the name of the variable that you were // trying to allocated memory for. This exists in order to provide more // helpful error messages. //------------------------------------------------------------------------------ void throwMemErr (const char *varname, const char *functionname) { printf("Memory allocation error: error allocating memory for variable " "%s in %s.\n", varname, functionname); exit(EXIT_FAILURE); } //------------------------------------------------------------------------------ // Raises a warning without causing program execution to terminate. //------------------------------------------------------------------------------ void warning (const char *message, const char *functionname) { fprintf(stderr, "Warning in function %s: %s\n", functionname, message); }
2.90625
3
2024-11-18T20:59:38.940475+00:00
2018-05-26T14:52:28
f47b4932868de358f97b3d0650d5952835026359
{ "blob_id": "f47b4932868de358f97b3d0650d5952835026359", "branch_name": "refs/heads/master", "committer_date": "2018-05-26T14:52:28", "content_id": "223a82a6676459e6cedcbaeff036d7261f778143", "detected_licenses": [ "MIT" ], "directory_id": "976e936a71b369771a9afb1bbc5e55cc0b84c081", "extension": "c", "filename": "renderer.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 131349885, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5630, "license": "MIT", "license_type": "permissive", "path": "/compositor/renderer.c", "provenance": "stackv2-0135.json.gz:244508", "repo_name": "st3r4g/drm-input-wayland", "revision_date": "2018-05-26T14:52:28", "revision_id": "39ae9130d9520f227e6f70fb598a1081c4e0926f", "snapshot_id": "82585c3f0eb1e95aa2c898941f1af2e353076bab", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/st3r4g/drm-input-wayland/39ae9130d9520f227e6f70fb598a1081c4e0926f/compositor/renderer.c", "visit_date": "2020-03-14T00:07:47.002511" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <GLES3/gl3.h> #include <GLES2/gl2ext.h> #include <backend/egl.h> #include <renderer.h> #include <util/algebra.h> struct renderer { GLuint program; GLint view[4]; }; struct texture { GLuint vao; GLuint tex; }; static PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOES = 0; GLuint CreateProgram(const char *name); char *GetShaderSource(const char *src_file); struct renderer *renderer_setup(int width, int height) { struct renderer *renderer = calloc(1, sizeof(struct renderer)); glEGLImageTargetTexture2DOES = (PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) eglGetProcAddress("glEGLImageTargetTexture2DOES"); renderer->program = CreateProgram("texture"); glGetIntegerv(GL_VIEWPORT, renderer->view); glClearColor(0.3f, 0.3f, 0.3f, 1.0f); glEnable(GL_DEPTH_TEST); return renderer; } void renderer_clear() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } struct texture *renderer_tex(const int32_t width, const int32_t height); /* * We pass GL_BGRA_EXT because shm uses ARGB but with different endianness */ struct texture *renderer_tex_from_data(const int32_t width, const int32_t height, const void *data) { struct texture *texture = renderer_tex(width, height); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, data); glBindTexture(GL_TEXTURE_2D, 0); return texture; } struct texture *renderer_tex_from_egl_image(const int32_t width, const int32_t height, EGLImage image) { struct texture *texture = renderer_tex(width, height); glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, image); glBindTexture(GL_TEXTURE_2D, 0); return texture; } struct texture *renderer_tex(const int32_t width, const int32_t height) { struct texture *texture = calloc(1, sizeof(struct texture)); GLuint *vao = &texture->vao; GLuint *tex = &texture->tex; glGenVertexArrays(1, vao); GLuint vbo; glGenBuffers(1, &vbo); glBindVertexArray(*vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); GLfloat rect[] = { 0.0f, 0.0f, 0.0f, 0.0f, // left bottom width, 0.0f, 1.0f, 0.0f, // right bottom 0.0f, height, 0.0f, 1.0f, // left top width, height, 1.0f, 1.0f, // right top }; glBufferData(GL_ARRAY_BUFFER, sizeof(rect), rect, GL_STATIC_DRAW); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(GLfloat), 0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(GLfloat), (void*)(2*sizeof(GLfloat))); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glBindVertexArray(0); glGenTextures(1, tex); glBindTexture(GL_TEXTURE_2D, *tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); return texture; } /* * Setting the projection matrix like this works but I don't know exactly why */ void renderer_tex_draw(const struct renderer *renderer, const struct texture *texture) { if (texture) { GLuint program = renderer->program; GLuint vao = texture->vao; GLuint tex = texture->tex; glUseProgram(program); GLfloat matrix[16]; GLint width = renderer->view[2], height = renderer->view[3]; algebra_matrix_ortho(matrix, 0, width, height, 0, -1, 1); // algebra_matrix_traslation(m2, -32, -32, 0); // algebra_matrix_multiply(matrix, m1, m2); GLint loc = glGetUniformLocation(program, "matrix"); glUniformMatrix4fv(loc, 1, GL_TRUE, matrix); glBindTexture(GL_TEXTURE_2D, tex); glBindVertexArray(vao); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glBindVertexArray(0); glBindTexture(GL_TEXTURE_2D, 0); } } void renderer_delete_tex(struct texture *texture) { if (texture) { GLuint *tex = &texture->tex; glDeleteTextures(1, tex); free(texture); } } GLuint CreateProgram(const char *name) { GLuint vert = glCreateShader(GL_VERTEX_SHADER); GLuint frag = glCreateShader(GL_FRAGMENT_SHADER); char vert_path[64], frag_path[64]; sprintf(vert_path, "../shaders/%s.vert", name); sprintf(frag_path, "../shaders/%s.frag", name); char *vert_src_handle = GetShaderSource(vert_path); char *frag_src_handle = GetShaderSource(frag_path); const char *vert_src = vert_src_handle; const char *frag_src = frag_src_handle; glShaderSource(vert, 1, &vert_src, NULL); glShaderSource(frag, 1, &frag_src, NULL); glCompileShader(vert); GLint success = 0; glGetShaderiv(vert, GL_COMPILE_STATUS, &success); if (success == GL_FALSE) { GLint logSize = 0; glGetShaderiv(vert, GL_INFO_LOG_LENGTH, &logSize); char *errorLog = malloc(logSize*sizeof(char)); glGetShaderInfoLog(vert, logSize, &logSize, errorLog); printf("%s\n", errorLog); free(errorLog); } glCompileShader(frag); glGetShaderiv(frag, GL_COMPILE_STATUS, &success); if (success == GL_FALSE) { GLint logSize = 0; glGetShaderiv(frag, GL_INFO_LOG_LENGTH, &logSize); char *errorLog = malloc(logSize*sizeof(char)); glGetShaderInfoLog(frag, logSize, &logSize, errorLog); printf("%s\n", errorLog); free(errorLog); } GLuint prog = glCreateProgram(); glAttachShader(prog, vert); glAttachShader(prog, frag); glLinkProgram(prog); glDeleteShader(vert); glDeleteShader(frag); free(vert_src_handle); free(frag_src_handle); return prog; } char *GetShaderSource(const char *src_file) { char *buffer = 0; long lenght; FILE *f = fopen(src_file, "rb"); if (f == NULL) { fprintf(stderr, "fopen on %s failed\n", src_file); return NULL; } fseek(f, 0, SEEK_END); lenght = ftell(f); fseek(f, 0, SEEK_SET); buffer = malloc(lenght); if (buffer == NULL) { fprintf(stderr, "malloc failed\n"); fclose(f); return NULL; } fread(buffer, 1, lenght, f); fclose(f); buffer[lenght-1] = '\0'; return buffer; }
2.3125
2
2024-11-18T20:59:39.321582+00:00
2021-08-13T13:57:26
5a9ed01de0bd70173f9ccfa3f86f139ccb9389b1
{ "blob_id": "5a9ed01de0bd70173f9ccfa3f86f139ccb9389b1", "branch_name": "refs/heads/master", "committer_date": "2021-08-13T13:57:26", "content_id": "b63a34a472929a31b22b4669fcfb826dd5492298", "detected_licenses": [ "Zlib" ], "directory_id": "7cef0e3621d4d37f2029fe1e809d1a7302879d73", "extension": "c", "filename": "big_int_mul_modif.c", "fork_events_count": 1, "gha_created_at": "2020-12-10T11:37:04", "gha_event_created_at": "2021-05-31T22:22:48", "gha_language": "C", "gha_license_id": null, "github_id": 320253390, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1684, "license": "Zlib", "license_type": "permissive", "path": "/lib/libft/ft_dtoa/big_int_mul_modif.c", "provenance": "stackv2-0135.json.gz:244768", "repo_name": "hakolao/doom3d", "revision_date": "2021-08-13T13:57:26", "revision_id": "f9eb82e051a813e926469fdace56e4de77814a97", "snapshot_id": "437cc73db0c4a9d66f575654f0e7dd8c4a06c84f", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/hakolao/doom3d/f9eb82e051a813e926469fdace56e4de77814a97/lib/libft/ft_dtoa/big_int_mul_modif.c", "visit_date": "2023-07-08T13:10:26.188941" }
stackv2
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* big_int_mul_modif.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ohakola <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/08/18 22:14:07 by ohakola #+# #+# */ /* Updated: 2021/05/04 15:42:41 by ohakola ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_dtoa.h" /* ** Multiplies inputted t_big_int by 2. */ void big_int_mul_2_modif(t_big_int *mod) { uint32_t carry; uint32_t cur; size_t i; carry = 0; i = -1; while (++i < mod->length) { cur = mod->blocks[i]; mod->blocks[i] = (cur << 1) | carry; carry = cur >> 31; } if (carry != 0) { mod->blocks[i] = carry; mod->length = mod->length + 1; } } /* ** Multiplies inputted t_big_int by 10. */ void big_int_mul_10_modif(t_big_int *mod) { uint32_t carry; uint64_t product; size_t i; carry = 0; i = -1; while (++i < mod->length) { product = (uint64_t)(mod->blocks[i]) * 10ULL + carry; mod->blocks[i] = (uint32_t)(product & 0xFFFFFFFF); carry = product >> 32; } if (carry != 0) { mod->blocks[i] = carry; mod->length = mod->length + 1; } }
2.828125
3
2024-11-18T20:59:39.385330+00:00
2022-01-31T04:36:44
27259d1a73c6ec22f9e0d0e1cdb0f61be527f716
{ "blob_id": "27259d1a73c6ec22f9e0d0e1cdb0f61be527f716", "branch_name": "refs/heads/master", "committer_date": "2022-01-31T04:36:44", "content_id": "f583a44102867460ac907981d88b987406f8a8b3", "detected_licenses": [ "MIT" ], "directory_id": "e1c02087e71617b1bdfb6ed8f139a35f0e8ce9c7", "extension": "c", "filename": "int-printf.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 186742104, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 282, "license": "MIT", "license_type": "permissive", "path": "/c/int-printf.c", "provenance": "stackv2-0135.json.gz:244898", "repo_name": "CrazyJ36/c", "revision_date": "2022-01-31T04:36:44", "revision_id": "ac37b0af76ef273199eeb0d3796549cc6bd06dc0", "snapshot_id": "fe21422de23ac93d3e6f8c3e20e1d45ddb55a33a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/CrazyJ36/c/ac37b0af76ef273199eeb0d3796549cc6bd06dc0/c/int-printf.c", "visit_date": "2022-02-06T01:43:51.313389" }
stackv2
/* This program breakdown: stdio.h for printf fake named integer x is assigned(converted to) 5 printf the data-type %d putting x into it. Also putting newline with x. */ #include <stdio.h> int main() { int x = 5; printf("Printing an integer: %d\n", x); return(0); }
3.796875
4
2024-11-18T20:59:39.636414+00:00
2017-12-09T01:14:24
a574c7e4230e30f85b3572ccfe64e2c4124ba079
{ "blob_id": "a574c7e4230e30f85b3572ccfe64e2c4124ba079", "branch_name": "refs/heads/master", "committer_date": "2017-12-09T01:14:24", "content_id": "a35dbb03dc665f63f4b469613d35a5700e8d64c1", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "1777fa807f72c90afc817e3b02d10539e09ecf10", "extension": "c", "filename": "general_get.c", "fork_events_count": 1, "gha_created_at": "2019-09-15T05:31:55", "gha_event_created_at": "2020-10-06T04:57:50", "gha_language": null, "gha_license_id": "BSD-3-Clause", "github_id": 208547077, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2904, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/C/04_One_sided/02_Active/general_get.c", "provenance": "stackv2-0135.json.gz:245158", "repo_name": "shahmoradi/MPI_Tutorial", "revision_date": "2017-12-09T01:14:24", "revision_id": "dd4e351ecf09a0ff9689a6b7e6362254a2a00cff", "snapshot_id": "1e62b6168710f27ef3ed95ff8499ad97adb571a3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/shahmoradi/MPI_Tutorial/dd4e351ecf09a0ff9689a6b7e6362254a2a00cff/C/04_One_sided/02_Active/general_get.c", "visit_date": "2021-07-12T08:13:19.633313" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <mpi.h> #define TAG 100 int main(int argc, char ** argv) { int rank, recv_rank, nproc, icycle; MPI_Aint size_of_window, offset; MPI_Win window; MPI_Group comm_group, group; int *ranks; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &nproc); MPI_Comm_rank(MPI_COMM_WORLD, &rank); offset = 0; size_of_window = sizeof(int); //Create a group corresponding to all processors. Groups are just abstract //collections of processors and don't mean as much as communicators MPI_Comm_group(MPI_COMM_WORLD, &comm_group); recv_rank = rank; //Create the window. This is a piece of memory that's available for remote //access. In this case, a single 4 byte integer MPI_Win_create(&recv_rank, , , , , ); if (rank == 0) { //You have to pass MPI_Win_start a group of processors that it can access //Use MPI_Group_incl to create a group of all processors other than 0 //If you include ranks here that will not also call MPI_Win_post then //You will get a lock in MPI_Put ranks = (int*) malloc(sizeof(int) * (nproc-1)); for (icycle = 0; icycle< nproc-1; ++icycle){ ranks[icycle] = icycle+1; } MPI_Group_incl(comm_group, nproc-1, ranks, &group); free(ranks); //On processor zero, have to use MPI_Win_start to start the "access epoch" //This allows rank 0 to MPI_Get and MPI_Put into windows on other processor //It does not allow other processors to access the window on rank 0 MPI_Win_start(group, 0, window); } else { //You have to pass MPI_Win_post a group of processors that can write to it //Use MPI_Group_incl to create a group consisting only of processor 0 //You MUST NOT include processors here that will not be writing or //MPI_Win_wait will lock ranks = (int*) malloc(sizeof(int)); ranks[0] = 0; MPI_Group_incl(comm_group, 1, ranks, &group); free(ranks); //On all other ranks, use MPI_Win_post to start the "exposure epoch" //This makes their data available to ranks within the group, but they //cannot call MPI_Get or MPI_Put themselves MPI_Win_post(group, 0, window); } offset = 0; //Actual call to put the data in the remote processor if (rank == 0) { ranks = (int*) malloc(sizeof(int) * (nproc-1)); for (icycle = 1; icycle<nproc; ++icycle){ MPI_Get(ranks+(icycle-1), 1, MPI_INT, icycle, offset, 1, MPI_INT, window); } } if (rank == 0) { //On processor zero, exit the "access epoch" MPI_Win_complete(window); } else { //On all of the other processors, wait for sending to complete and then //exit the "exposure epoch" MPI_Win_wait(window); } if (rank == 0) { printf("Data gathered by put is "); for (icycle = 0; icycle < nproc-1; ++icycle){ printf("%3d ", ranks[icycle]); } printf("\n"); } MPI_Finalize(); }
3.015625
3
2024-11-18T20:59:39.852681+00:00
2022-03-15T09:21:10
cdc589f26c0f674d003bb6a9d423c16e48981c6d
{ "blob_id": "cdc589f26c0f674d003bb6a9d423c16e48981c6d", "branch_name": "refs/heads/master", "committer_date": "2022-03-15T09:21:10", "content_id": "0089cfffa75e34644b11e24588e68e631641f888", "detected_licenses": [ "MIT" ], "directory_id": "ba380060d48af8680f48a8e89032065019461195", "extension": "h", "filename": "mpi_common.h", "fork_events_count": 19, "gha_created_at": "2015-06-17T07:44:00", "gha_event_created_at": "2022-03-15T07:25:48", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 37580272, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1083, "license": "MIT", "license_type": "permissive", "path": "/c++/mpi_common.h", "provenance": "stackv2-0135.json.gz:245419", "repo_name": "ExaScience/bpmf", "revision_date": "2022-03-15T09:21:10", "revision_id": "5b83fbb0474fd50fdf738db1707009c00fa62e6d", "snapshot_id": "cb3372330eabbefb9b1498bfb0cd82984273151a", "src_encoding": "UTF-8", "star_events_count": 62, "url": "https://raw.githubusercontent.com/ExaScience/bpmf/5b83fbb0474fd50fdf738db1707009c00fa62e6d/c++/mpi_common.h", "visit_date": "2022-03-18T05:42:04.385995" }
stackv2
/* * Copyright (c) 2014-2016, imec * All rights reserved. */ #define SYS MPI_Sys void Sys::Init() { int provided; MPI_Init_thread(0, 0, MPI_THREAD_SERIALIZED, &provided); assert(provided == MPI_THREAD_SERIALIZED); MPI_Comm_rank(MPI_COMM_WORLD, &Sys::procid); MPI_Comm_size(MPI_COMM_WORLD, &Sys::nprocs); MPI_Comm_set_errhandler(MPI_COMM_WORLD, MPI_ERRORS_ARE_FATAL); } void Sys::Finalize() { MPI_Finalize(); } void Sys::sync() { MPI_Barrier(MPI_COMM_WORLD); } void Sys::Abort(int err) { MPI_Abort(MPI_COMM_WORLD, err); } #ifndef BPMF_MPI_PUT_COMM void MPI_Sys::alloc_and_init() { items_ptr = (double *)malloc(sizeof(double) * num_latent * num()); init(); } #endif void MPI_Sys::reduce_sum_cov_norm() { BPMF_COUNTER("reduce_sum_cov_norm"); MPI_Allreduce(MPI_IN_PLACE, sum.data(), num_latent, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); MPI_Allreduce(MPI_IN_PLACE, cov.data(), num_latent * num_latent, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); MPI_Allreduce(MPI_IN_PLACE, &norm, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); }
2.015625
2
2024-11-18T20:59:39.906590+00:00
2017-05-29T21:14:47
6413bc5b063ec5a95cc2d6a5e696cfa7079346cb
{ "blob_id": "6413bc5b063ec5a95cc2d6a5e696cfa7079346cb", "branch_name": "refs/heads/master", "committer_date": "2017-05-29T21:14:47", "content_id": "f37164617b85c8f96e382424229143531c82fba2", "detected_licenses": [ "MIT" ], "directory_id": "a376c27c07fc0c6246f14280334a164acad44cc1", "extension": "c", "filename": "Experimento3.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 82573763, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9524, "license": "MIT", "license_type": "permissive", "path": "/experimento3/Experimento3.c", "provenance": "stackv2-0135.json.gz:245549", "repo_name": "rogerluan/SO-A", "revision_date": "2017-05-29T21:14:47", "revision_id": "1d84266c6b4cc4675a671de438512fe53c9f3387", "snapshot_id": "5aa6effe153d67d162135681ffd3203e79c1d633", "src_encoding": "ISO-8859-1", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rogerluan/SO-A/1d84266c6b4cc4675a671de438512fe53c9f3387/experimento3/Experimento3.c", "visit_date": "2020-05-27T21:48:54.187360" }
stackv2
// // Experimento3.c // // Created on Mar 27th 2017 // // ALEX VENTURINI 15294739 // BRUNO PEDROSO 12662136 // LUAN BONOMI 15108780 // PEDRO CATALINI 15248354 // ROGER OBA 12048534 // //#define PROTECT /* * Includes Necessarios */ #include <errno.h> /* errno and error codes */ #include <stdlib.h> /* exit() */ #include <sys/time.h> /* for gettimeofday() */ #include <stdio.h> /* for printf() */ #include <unistd.h> /* for fork() */ //#include <sys/types.h> /* for wait() */ #include <sys/wait.h> /* for wait() */ #include <signal.h> /* for kill(), sigsuspend(), others */ #include <sys/ipc.h> /* for all IPC function calls */ #include <sys/shm.h> /* for shmget(), shmat(), shmctl() */ #include <sys/sem.h> /* for semget(), semop(), semctl() */ #include <string.h> /* for strerror() */ /* * Constantes Necessarias */ #define SEM_KEY 9008 #define SHM_KEY 9009 #define NO_OF_CHILDREN 3 #define SEM_PERMS 0666 /* * As seguintes variaveis globais contem informacao importante. A variavel * g_sem_id e g_shm_id contem as identificacoes IPC para o semaforo e para * o segmento de memoria compartilhada que sao usados pelo programa. A variavel * g_shm_addr e um ponteiro inteiro que aponta para o segmento de memoria * compartilhada que contera o indice inteiro da matriz de caracteres que contem * o alfabeto que sera exibido. */ int g_sem_id; int g_shm_id; int *g_shm_addr; /* * As seguintes duas estruturas contem a informacao necessaria para controlar * semaforos em relacao a "fecharem", se nao permitem acesso, ou * "abrirem", se permitirem acesso. As estruturas sao incializadas ao inicio * do programa principal e usadas na rotina printChars(). Como elas sao * inicializadas no programa principal, antes da criacao dos processos filhos, * elas podem ser usadas nesses processos sem a necessidade de nova associacao * ou mudancas. */ struct sembuf g_sem_op_lock[1]; struct sembuf g_sem_op_unlock[1]; /* * O seguinte vetor de caracteres contem o alfabeto que constituira o string * que sera exibido. */ char g_letters_and_numbers[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 1234567890"; /* * Funcoes */ void printChars(); /* * Programa Principal */ int main(int argc, char *argv[]) { /* * Para armazenar os ids dos processos filhos, permitindo o posterior * uso do comando kill */ int pid[NO_OF_CHILDREN]; /* * Construindo a estrutura de controle do semaforo */ g_sem_op_lock[0].sem_num = 0; g_sem_op_lock[0].sem_op = -1; g_sem_op_lock[0].sem_flg = 0; /* * Pergunta 1: Se usada a estrutura g_sem_op1 terá qual efeito em um conjunto de semáforos? */ g_sem_op_unlock[0].sem_num = 0; g_sem_op_unlock[0].sem_op = 1; g_sem_op_unlock[0].sem_flg = 0; /* * Criando o semaforo */ if ((g_sem_id = semget(SEM_KEY, 1, IPC_CREAT | SEM_PERMS)) == -1) { fprintf(stderr, "chamada a semget() falhou, impossivel criar o conjunto de semaforos!"); exit(1); } if (semop(g_sem_id, g_sem_op_unlock, 1) == -1) { fprintf(stderr, "chamada semop() falhou, impossivel inicializar o semaforo!"); exit(1); } /* * Pergunta 2: Para que serve esta operacao semop(), se não está na saída de uma região crítica? */ /* * Criando o segmento de memoria compartilhada */ if ((g_shm_id = shmget(SHM_KEY, sizeof(int), IPC_CREAT | SEM_PERMS)) == -1) { fprintf(stderr, "Impossivel criar o segmento de memoria compartilhada. Erro: %s\n", strerror(errno)); exit(1); } if ((g_shm_addr = (int *)shmat(g_shm_id, NULL, 0)) == (int *)-1) { fprintf(stderr, "Impossivel associar o segmento de memoria compartilhada! Erro: %s\n", strerror(errno)); exit(1); } *g_shm_addr = 0; /* * Pergunta 3: Para que serve essa inicializa‹o da mem—ria compartilhada com zero? */ /* * Criando os filhos */ int rtn = 1; int count; for (count = 0; count < NO_OF_CHILDREN; ++count) { if (rtn != 0) { rtn = fork(); pid[count] = rtn; } else { break; } } /* * Verificando o valor retornado para determinar se o processo e * pai ou filho */ if (rtn == 0) { // Eu sou um filho fprintf(stdout, "Filho %i comecou ...\n", count); fflush(stdout); printChars(); } else { // Espera-se um determinado tempo em que os filhos ir‹o imprimir os dados na tela // Ap—s este tempo, mata-se os filhos, encerra-se o sem‡foro e mem—ria compartilhada, e o programa termina. usleep(10000); // Matando os filhos int i; for (i = 0; i < NO_OF_CHILDREN; ++i) { kill(pid[i], SIGKILL); } // Removendo a memoria compartilhada if (shmctl(g_shm_id, IPC_RMID, NULL) != 0) { fprintf(stderr, "Impossivel remover o segmento de memoria compartilhada!\n"); exit(1); } else { fprintf(stdout, "\n\nSegmento de memoria compartilhada removido com sucesso!\n"); } // Removendo o semaforo if (semctl(g_sem_id, 0, IPC_RMID, 0) != 0) { fprintf(stderr, "Impossivel remover o conjunto de semaforos!\n"); exit(1); } else { fprintf(stdout, "Conjunto de semaforos removido com sucesso!\n"); } exit(0); } } /* * Pergunta 4: se os filhos ainda não terminaram, semctl e shmctl, com o parametro IPC-RMID, nao * permitem mais o acesso ao semáforo / memória compartilhada? */ /* * Esta rotina realiza a exibicao de caracteres. Nela e calculado um numero * pseudo-randomico entre 1 e 3 para determinar o numero de caracteres a exibir. * Se a protecao esta estabelecida, a rotina entao consegue o recurso. Em * seguida, printChars() acessa o indice com seu valor corrente a partir da * memoria compartilhada. A rotina entra em loop, exibindo o numero aleatorio de * caracteres. Finalmente, a rotina incrementa o indice, conforme o necessario, * e libera o recurso, se for o caso. */ void printChars() { struct timeval tv; int number; int tmp_index; int i; // Este tempo permite que todos os filhos sejam iniciados usleep(1000); // Loop que far‡ com que os filhos imprimam o vetor de // caracteres atŽ o timer de 15000micro seg do pai se esgotar while(1) { /* * Conseguindo o tempo corrente, os microsegundos desse tempo * sao usados como um numero pseudo-randomico. Em seguida, * calcula o numero randomico atraves de um algoritmo simples */ if (gettimeofday(&tv, NULL) == -1) { fprintf(stderr,"Impossivel conseguir o tempo atual, terminando.\n"); exit(1); } number = ((tv.tv_usec / 47) % 3) + 1; /* * Pergunta 5: quais os valores possíveis de serem atribuidos * a number? */ /* * O #ifdef PROTECT inclui este pedaco de codigo se a macro * PROTECT estiver definida. Para sua definicao, retire o comentario * que a acompanha. semop() e chamada para fechar o semaforo. */ #ifdef PROTECT if (semop(g_sem_id, g_sem_op_lock, 1) == -1) { fprintf(stderr,"chamada semop() falhou, impossivel fechar o recurso!"); exit(1); } #endif /* * Lendo o indice do segmento de memoria compartilhada */ tmp_index = *g_shm_addr; /* * Repita o numero especificado de vezes, esteja certo de nao * ultrapassar os limites do vetor, o comando if garante isso */ for (i = 0; i < number; ++i) { if (!(tmp_index + i >= sizeof(g_letters_and_numbers))) { fprintf(stdout, "%c", g_letters_and_numbers[tmp_index + i]); fflush(stdout); usleep(1); // Para dar aos outros processos uma chance para executar (isso tambŽm faz com que n‹o sejam apresentados tantos dados na tela } else { break; } } /* * Atualizando o indice na memoria compartilhada */ *g_shm_addr = tmp_index + i; /* * Se o indice e maior que o tamanho do alfabeto, exibe um * caractere return para iniciar a linha seguinte e coloca * zero no indice */ if (tmp_index + i >= sizeof(g_letters_and_numbers)) { fprintf(stdout, "\n"); fflush(stdout); *g_shm_addr = 0; } /* * Liberando o recurso se a macro PROTECT estiver definida */ #ifdef PROTECT if (semop(g_sem_id, g_sem_op_unlock, 1) == -1) { fprintf(stdout, "chamada semop() falhou, impossivel liberar o recurso!"); exit(1); } #endif } }
2.53125
3
2024-11-18T20:59:42.644677+00:00
2022-03-01T22:33:16
5fb9f2075dbb4752337fed75777c1bcf123bfbe0
{ "blob_id": "5fb9f2075dbb4752337fed75777c1bcf123bfbe0", "branch_name": "refs/heads/master", "committer_date": "2022-12-12T17:03:27", "content_id": "9f6261606ad359f6e89b118463e1a3f8f6623ce6", "detected_licenses": [ "MIT" ], "directory_id": "c7308b6f7534ec1d08d02ff7882020636f42a2cb", "extension": "c", "filename": "middle.c", "fork_events_count": 10, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 2223381, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 286, "license": "MIT", "license_type": "permissive", "path": "/test/cases/flexarr/middle.c", "provenance": "stackv2-0135.json.gz:245678", "repo_name": "bobrippling/ucc-c-compiler", "revision_date": "2022-03-01T22:33:16", "revision_id": "d0283673261bbd5d872057ee169378fdf349a6fa", "snapshot_id": "0d8808a31bb8b0b6403d1e757b866753ac969e23", "src_encoding": "UTF-8", "star_events_count": 74, "url": "https://raw.githubusercontent.com/bobrippling/ucc-c-compiler/d0283673261bbd5d872057ee169378fdf349a6fa/test/cases/flexarr/middle.c", "visit_date": "2023-06-21T22:25:07.825365" }
stackv2
// RUN: %check %s struct Flex { int n; int vals[]; }; struct Cont { struct Flex f; // CHECK: /warning: embedded struct with flex-array not final member/ int a, b, c; }; struct ContNested { int yo; struct Flex f; // CHECK: warning: embedded flexible-array as nested in struct };
2.171875
2
2024-11-18T20:59:43.166585+00:00
2023-08-17T16:08:06
9495f4400b07426b425a5014ca549c4261958435
{ "blob_id": "9495f4400b07426b425a5014ca549c4261958435", "branch_name": "refs/heads/main", "committer_date": "2023-08-17T16:08:06", "content_id": "e7b32711f2e707bc4585079889f9a371a7d5c368", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "eecd5e4c50d8b78a769bcc2675250576bed34066", "extension": "c", "filename": "isutil.c", "fork_events_count": 169, "gha_created_at": "2013-03-10T20:55:21", "gha_event_created_at": "2023-03-29T11:02:58", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 8691401, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 16320, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/tao/bound/utils/isutil.c", "provenance": "stackv2-0135.json.gz:246197", "repo_name": "petsc/petsc", "revision_date": "2023-08-17T16:08:06", "revision_id": "9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9", "snapshot_id": "3b1a04fea71858e0292f9fd4d04ea11618c50969", "src_encoding": "UTF-8", "star_events_count": 341, "url": "https://raw.githubusercontent.com/petsc/petsc/9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9/src/tao/bound/utils/isutil.c", "visit_date": "2023-08-17T20:51:16.507070" }
stackv2
#include <petsctao.h> /*I "petsctao.h" I*/ #include <petsc/private/vecimpl.h> #include <petsc/private/taoimpl.h> #include <../src/tao/matrix/submatfree.h> /*@C TaoVecGetSubVec - Gets a subvector using the `IS` Input Parameters: + vfull - the full matrix . is - the index set for the subvector . reduced_type - the method `Tao` is using for subsetting - maskvalue - the value to set the unused vector elements to (for `TAO_SUBSET_MASK` or `TAO_SUBSET_MATRIXFREE`) Output Parameter: . vreduced - the subvector Level: developer Notes: `maskvalue` should usually be `0.0`, unless a pointwise divide will be used. .seealso: `TaoMatGetSubMat()`, `TaoSubsetType` @*/ PetscErrorCode TaoVecGetSubVec(Vec vfull, IS is, TaoSubsetType reduced_type, PetscReal maskvalue, Vec *vreduced) { PetscInt nfull, nreduced, nreduced_local, rlow, rhigh, flow, fhigh; PetscInt i, nlocal; PetscReal *fv, *rv; const PetscInt *s; IS ident; VecType vtype; VecScatter scatter; MPI_Comm comm; PetscFunctionBegin; PetscValidHeaderSpecific(vfull, VEC_CLASSID, 1); PetscValidHeaderSpecific(is, IS_CLASSID, 2); PetscCall(VecGetSize(vfull, &nfull)); PetscCall(ISGetSize(is, &nreduced)); if (nreduced == nfull) { PetscCall(VecDestroy(vreduced)); PetscCall(VecDuplicate(vfull, vreduced)); PetscCall(VecCopy(vfull, *vreduced)); } else { switch (reduced_type) { case TAO_SUBSET_SUBVEC: PetscCall(VecGetType(vfull, &vtype)); PetscCall(VecGetOwnershipRange(vfull, &flow, &fhigh)); PetscCall(ISGetLocalSize(is, &nreduced_local)); PetscCall(PetscObjectGetComm((PetscObject)vfull, &comm)); if (*vreduced) PetscCall(VecDestroy(vreduced)); PetscCall(VecCreate(comm, vreduced)); PetscCall(VecSetType(*vreduced, vtype)); PetscCall(VecSetSizes(*vreduced, nreduced_local, nreduced)); PetscCall(VecGetOwnershipRange(*vreduced, &rlow, &rhigh)); PetscCall(ISCreateStride(comm, nreduced_local, rlow, 1, &ident)); PetscCall(VecScatterCreate(vfull, is, *vreduced, ident, &scatter)); PetscCall(VecScatterBegin(scatter, vfull, *vreduced, INSERT_VALUES, SCATTER_FORWARD)); PetscCall(VecScatterEnd(scatter, vfull, *vreduced, INSERT_VALUES, SCATTER_FORWARD)); PetscCall(VecScatterDestroy(&scatter)); PetscCall(ISDestroy(&ident)); break; case TAO_SUBSET_MASK: case TAO_SUBSET_MATRIXFREE: /* vr[i] = vf[i] if i in is vr[i] = 0 otherwise */ if (!*vreduced) PetscCall(VecDuplicate(vfull, vreduced)); PetscCall(VecSet(*vreduced, maskvalue)); PetscCall(ISGetLocalSize(is, &nlocal)); PetscCall(VecGetOwnershipRange(vfull, &flow, &fhigh)); PetscCall(VecGetArray(vfull, &fv)); PetscCall(VecGetArray(*vreduced, &rv)); PetscCall(ISGetIndices(is, &s)); PetscCheck(nlocal <= (fhigh - flow), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "IS local size %" PetscInt_FMT " > Vec local size %" PetscInt_FMT, nlocal, fhigh - flow); for (i = 0; i < nlocal; ++i) rv[s[i] - flow] = fv[s[i] - flow]; PetscCall(ISRestoreIndices(is, &s)); PetscCall(VecRestoreArray(vfull, &fv)); PetscCall(VecRestoreArray(*vreduced, &rv)); break; } } PetscFunctionReturn(PETSC_SUCCESS); } /*@C TaoMatGetSubMat - Gets a submatrix using the `IS` Input Parameters: + M - the full matrix (`n x n`) . is - the index set for the submatrix (both row and column index sets need to be the same) . v1 - work vector of dimension n, needed for `TAO_SUBSET_MASK` option - subset_type - the method `Tao` is using for subsetting Output Parameter: . Msub - the submatrix Level: developer .seealso: `TaoVecGetSubVec()`, `TaoSubsetType` @*/ PetscErrorCode TaoMatGetSubMat(Mat M, IS is, Vec v1, TaoSubsetType subset_type, Mat *Msub) { IS iscomp; PetscBool flg = PETSC_TRUE; PetscFunctionBegin; PetscValidHeaderSpecific(M, MAT_CLASSID, 1); PetscValidHeaderSpecific(is, IS_CLASSID, 2); PetscCall(MatDestroy(Msub)); switch (subset_type) { case TAO_SUBSET_SUBVEC: PetscCall(MatCreateSubMatrix(M, is, is, MAT_INITIAL_MATRIX, Msub)); break; case TAO_SUBSET_MASK: /* Get Reduced Hessian Msub[i,j] = M[i,j] if i,j in Free_Local or i==j Msub[i,j] = 0 if i!=j and i or j not in Free_Local */ PetscObjectOptionsBegin((PetscObject)M); PetscCall(PetscOptionsBool("-overwrite_hessian", "modify the existing hessian matrix when computing submatrices", "TaoSubsetType", flg, &flg, NULL)); PetscOptionsEnd(); if (flg) { PetscCall(MatDuplicate(M, MAT_COPY_VALUES, Msub)); } else { /* Act on hessian directly (default) */ PetscCall(PetscObjectReference((PetscObject)M)); *Msub = M; } /* Save the diagonal to temporary vector */ PetscCall(MatGetDiagonal(*Msub, v1)); /* Zero out rows and columns */ PetscCall(ISComplementVec(is, v1, &iscomp)); /* Use v1 instead of 0 here because of PETSc bug */ PetscCall(MatZeroRowsColumnsIS(*Msub, iscomp, 1.0, v1, v1)); PetscCall(ISDestroy(&iscomp)); break; case TAO_SUBSET_MATRIXFREE: PetscCall(ISComplementVec(is, v1, &iscomp)); PetscCall(MatCreateSubMatrixFree(M, iscomp, iscomp, Msub)); PetscCall(ISDestroy(&iscomp)); break; } PetscFunctionReturn(PETSC_SUCCESS); } /*@C TaoEstimateActiveBounds - Generates index sets for variables at the lower and upper bounds, as well as fixed variables where lower and upper bounds equal each other. Input Parameters: + X - solution vector . XL - lower bound vector . XU - upper bound vector . G - unprojected gradient . S - step direction with which the active bounds will be estimated . W - work vector of type and size of `X` - steplen - the step length at which the active bounds will be estimated (needs to be conservative) Output Parameters: + bound_tol - tolerance for the bound estimation . active_lower - index set for active variables at the lower bound . active_upper - index set for active variables at the upper bound . active_fixed - index set for fixed variables . active - index set for all active variables - inactive - complementary index set for inactive variables Level: developer Notes: This estimation is based on Bertsekas' method, with a built in diagonal scaling value of `1.0e-3`. .seealso: `TAOBNCG`, `TAOBNTL`, `TAOBNTR`, `TaoBoundSolution()` @*/ PetscErrorCode TaoEstimateActiveBounds(Vec X, Vec XL, Vec XU, Vec G, Vec S, Vec W, PetscReal steplen, PetscReal *bound_tol, IS *active_lower, IS *active_upper, IS *active_fixed, IS *active, IS *inactive) { PetscReal wnorm; PetscReal zero = PetscPowReal(PETSC_MACHINE_EPSILON, 2.0 / 3.0); PetscInt i, n_isl = 0, n_isu = 0, n_isf = 0, n_isa = 0, n_isi = 0; PetscInt N_isl, N_isu, N_isf, N_isa, N_isi; PetscInt n, low, high, nDiff; PetscInt *isl = NULL, *isu = NULL, *isf = NULL, *isa = NULL, *isi = NULL; const PetscScalar *xl, *xu, *x, *g; MPI_Comm comm = PetscObjectComm((PetscObject)X); PetscFunctionBegin; PetscValidHeaderSpecific(X, VEC_CLASSID, 1); if (XL) PetscValidHeaderSpecific(XL, VEC_CLASSID, 2); if (XU) PetscValidHeaderSpecific(XU, VEC_CLASSID, 3); PetscValidHeaderSpecific(G, VEC_CLASSID, 4); PetscValidHeaderSpecific(S, VEC_CLASSID, 5); PetscValidHeaderSpecific(W, VEC_CLASSID, 6); if (XL) PetscCheckSameType(X, 1, XL, 2); if (XU) PetscCheckSameType(X, 1, XU, 3); PetscCheckSameType(X, 1, G, 4); PetscCheckSameType(X, 1, S, 5); PetscCheckSameType(X, 1, W, 6); if (XL) PetscCheckSameComm(X, 1, XL, 2); if (XU) PetscCheckSameComm(X, 1, XU, 3); PetscCheckSameComm(X, 1, G, 4); PetscCheckSameComm(X, 1, S, 5); PetscCheckSameComm(X, 1, W, 6); if (XL) VecCheckSameSize(X, 1, XL, 2); if (XU) VecCheckSameSize(X, 1, XU, 3); VecCheckSameSize(X, 1, G, 4); VecCheckSameSize(X, 1, S, 5); VecCheckSameSize(X, 1, W, 6); /* Update the tolerance for bound detection (this is based on Bertsekas' method) */ PetscCall(VecCopy(X, W)); PetscCall(VecAXPBY(W, steplen, 1.0, S)); PetscCall(TaoBoundSolution(W, XL, XU, 0.0, &nDiff, W)); PetscCall(VecAXPBY(W, 1.0, -1.0, X)); PetscCall(VecNorm(W, NORM_2, &wnorm)); *bound_tol = PetscMin(*bound_tol, wnorm); /* Clear all index sets */ PetscCall(ISDestroy(active_lower)); PetscCall(ISDestroy(active_upper)); PetscCall(ISDestroy(active_fixed)); PetscCall(ISDestroy(active)); PetscCall(ISDestroy(inactive)); PetscCall(VecGetOwnershipRange(X, &low, &high)); PetscCall(VecGetLocalSize(X, &n)); if (!XL && !XU) { PetscCall(ISCreateStride(comm, n, low, 1, inactive)); PetscFunctionReturn(PETSC_SUCCESS); } if (n > 0) { PetscCall(VecGetArrayRead(X, &x)); PetscCall(VecGetArrayRead(XL, &xl)); PetscCall(VecGetArrayRead(XU, &xu)); PetscCall(VecGetArrayRead(G, &g)); /* Loop over variables and categorize the indexes */ PetscCall(PetscMalloc1(n, &isl)); PetscCall(PetscMalloc1(n, &isu)); PetscCall(PetscMalloc1(n, &isf)); PetscCall(PetscMalloc1(n, &isa)); PetscCall(PetscMalloc1(n, &isi)); for (i = 0; i < n; ++i) { if (xl[i] == xu[i]) { /* Fixed variables */ isf[n_isf] = low + i; ++n_isf; isa[n_isa] = low + i; ++n_isa; } else if (xl[i] > PETSC_NINFINITY && x[i] <= xl[i] + *bound_tol && g[i] > zero) { /* Lower bounded variables */ isl[n_isl] = low + i; ++n_isl; isa[n_isa] = low + i; ++n_isa; } else if (xu[i] < PETSC_INFINITY && x[i] >= xu[i] - *bound_tol && g[i] < zero) { /* Upper bounded variables */ isu[n_isu] = low + i; ++n_isu; isa[n_isa] = low + i; ++n_isa; } else { /* Inactive variables */ isi[n_isi] = low + i; ++n_isi; } } PetscCall(VecRestoreArrayRead(X, &x)); PetscCall(VecRestoreArrayRead(XL, &xl)); PetscCall(VecRestoreArrayRead(XU, &xu)); PetscCall(VecRestoreArrayRead(G, &g)); } /* Collect global sizes */ PetscCall(MPIU_Allreduce(&n_isl, &N_isl, 1, MPIU_INT, MPI_SUM, comm)); PetscCall(MPIU_Allreduce(&n_isu, &N_isu, 1, MPIU_INT, MPI_SUM, comm)); PetscCall(MPIU_Allreduce(&n_isf, &N_isf, 1, MPIU_INT, MPI_SUM, comm)); PetscCall(MPIU_Allreduce(&n_isa, &N_isa, 1, MPIU_INT, MPI_SUM, comm)); PetscCall(MPIU_Allreduce(&n_isi, &N_isi, 1, MPIU_INT, MPI_SUM, comm)); /* Create index set for lower bounded variables */ if (N_isl > 0) { PetscCall(ISCreateGeneral(comm, n_isl, isl, PETSC_OWN_POINTER, active_lower)); } else { PetscCall(PetscFree(isl)); } /* Create index set for upper bounded variables */ if (N_isu > 0) { PetscCall(ISCreateGeneral(comm, n_isu, isu, PETSC_OWN_POINTER, active_upper)); } else { PetscCall(PetscFree(isu)); } /* Create index set for fixed variables */ if (N_isf > 0) { PetscCall(ISCreateGeneral(comm, n_isf, isf, PETSC_OWN_POINTER, active_fixed)); } else { PetscCall(PetscFree(isf)); } /* Create index set for all actively bounded variables */ if (N_isa > 0) { PetscCall(ISCreateGeneral(comm, n_isa, isa, PETSC_OWN_POINTER, active)); } else { PetscCall(PetscFree(isa)); } /* Create index set for all inactive variables */ if (N_isi > 0) { PetscCall(ISCreateGeneral(comm, n_isi, isi, PETSC_OWN_POINTER, inactive)); } else { PetscCall(PetscFree(isi)); } PetscFunctionReturn(PETSC_SUCCESS); } /*@C TaoBoundStep - Ensures the correct zero or adjusted step direction values for active variables. Input Parameters: + X - solution vector . XL - lower bound vector . XU - upper bound vector . active_lower - index set for lower bounded active variables . active_upper - index set for lower bounded active variables . active_fixed - index set for fixed active variables - scale - amplification factor for the step that needs to be taken on actively bounded variables Output Parameter: . S - step direction to be modified Level: developer .seealso: `TAOBNCG`, `TAOBNTL`, `TAOBNTR`, `TaoBoundSolution()` @*/ PetscErrorCode TaoBoundStep(Vec X, Vec XL, Vec XU, IS active_lower, IS active_upper, IS active_fixed, PetscReal scale, Vec S) { Vec step_lower, step_upper, step_fixed; Vec x_lower, x_upper; Vec bound_lower, bound_upper; PetscFunctionBegin; /* Adjust step for variables at the estimated lower bound */ if (active_lower) { PetscCall(VecGetSubVector(S, active_lower, &step_lower)); PetscCall(VecGetSubVector(X, active_lower, &x_lower)); PetscCall(VecGetSubVector(XL, active_lower, &bound_lower)); PetscCall(VecCopy(bound_lower, step_lower)); PetscCall(VecAXPY(step_lower, -1.0, x_lower)); PetscCall(VecScale(step_lower, scale)); PetscCall(VecRestoreSubVector(S, active_lower, &step_lower)); PetscCall(VecRestoreSubVector(X, active_lower, &x_lower)); PetscCall(VecRestoreSubVector(XL, active_lower, &bound_lower)); } /* Adjust step for the variables at the estimated upper bound */ if (active_upper) { PetscCall(VecGetSubVector(S, active_upper, &step_upper)); PetscCall(VecGetSubVector(X, active_upper, &x_upper)); PetscCall(VecGetSubVector(XU, active_upper, &bound_upper)); PetscCall(VecCopy(bound_upper, step_upper)); PetscCall(VecAXPY(step_upper, -1.0, x_upper)); PetscCall(VecScale(step_upper, scale)); PetscCall(VecRestoreSubVector(S, active_upper, &step_upper)); PetscCall(VecRestoreSubVector(X, active_upper, &x_upper)); PetscCall(VecRestoreSubVector(XU, active_upper, &bound_upper)); } /* Zero out step for fixed variables */ if (active_fixed) { PetscCall(VecGetSubVector(S, active_fixed, &step_fixed)); PetscCall(VecSet(step_fixed, 0.0)); PetscCall(VecRestoreSubVector(S, active_fixed, &step_fixed)); } PetscFunctionReturn(PETSC_SUCCESS); } /*@C TaoBoundSolution - Ensures that the solution vector is snapped into the bounds within a given tolerance. Collective Input Parameters: + X - solution vector . XL - lower bound vector . XU - upper bound vector - bound_tol - absolute tolerance in enforcing the bound Output Parameters: + nDiff - total number of vector entries that have been bounded - Xout - modified solution vector satisfying bounds to `bound_tol` Level: developer .seealso: `TAOBNCG`, `TAOBNTL`, `TAOBNTR`, `TaoBoundStep()` @*/ PetscErrorCode TaoBoundSolution(Vec X, Vec XL, Vec XU, PetscReal bound_tol, PetscInt *nDiff, Vec Xout) { PetscInt i, n, low, high, nDiff_loc = 0; PetscScalar *xout; const PetscScalar *x, *xl, *xu; PetscFunctionBegin; PetscValidHeaderSpecific(X, VEC_CLASSID, 1); if (XL) PetscValidHeaderSpecific(XL, VEC_CLASSID, 2); if (XU) PetscValidHeaderSpecific(XU, VEC_CLASSID, 3); PetscValidHeaderSpecific(Xout, VEC_CLASSID, 6); if (!XL && !XU) { PetscCall(VecCopy(X, Xout)); *nDiff = 0.0; PetscFunctionReturn(PETSC_SUCCESS); } PetscCheckSameType(X, 1, XL, 2); PetscCheckSameType(X, 1, XU, 3); PetscCheckSameType(X, 1, Xout, 6); PetscCheckSameComm(X, 1, XL, 2); PetscCheckSameComm(X, 1, XU, 3); PetscCheckSameComm(X, 1, Xout, 6); VecCheckSameSize(X, 1, XL, 2); VecCheckSameSize(X, 1, XU, 3); VecCheckSameSize(X, 1, Xout, 4); PetscCall(VecGetOwnershipRange(X, &low, &high)); PetscCall(VecGetLocalSize(X, &n)); if (n > 0) { PetscCall(VecGetArrayRead(X, &x)); PetscCall(VecGetArrayRead(XL, &xl)); PetscCall(VecGetArrayRead(XU, &xu)); PetscCall(VecGetArray(Xout, &xout)); for (i = 0; i < n; ++i) { if (xl[i] > PETSC_NINFINITY && x[i] <= xl[i] + bound_tol) { xout[i] = xl[i]; ++nDiff_loc; } else if (xu[i] < PETSC_INFINITY && x[i] >= xu[i] - bound_tol) { xout[i] = xu[i]; ++nDiff_loc; } } PetscCall(VecRestoreArrayRead(X, &x)); PetscCall(VecRestoreArrayRead(XL, &xl)); PetscCall(VecRestoreArrayRead(XU, &xu)); PetscCall(VecRestoreArray(Xout, &xout)); } PetscCall(MPIU_Allreduce(&nDiff_loc, nDiff, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)X))); PetscFunctionReturn(PETSC_SUCCESS); }
2.015625
2
2024-11-18T20:59:43.648059+00:00
2021-05-13T05:31:10
b0996a0c51c79c3ea06e657c4792f5c9ed98f0bc
{ "blob_id": "b0996a0c51c79c3ea06e657c4792f5c9ed98f0bc", "branch_name": "refs/heads/master", "committer_date": "2021-05-13T05:31:10", "content_id": "02ca2b96372cae4cf099f0a684b3afde5514cc92", "detected_licenses": [ "Unlicense" ], "directory_id": "18fa6d7f9c881aa6380ddef1225c4d16d006d649", "extension": "c", "filename": "ib_hdr.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2532, "license": "Unlicense", "license_type": "permissive", "path": "/datadump/ib_hdr.c", "provenance": "stackv2-0135.json.gz:247358", "repo_name": "aaaaaa123456789/pret3", "revision_date": "2021-05-13T05:31:10", "revision_id": "31206787aa809864f96ec987758a1160d2befe98", "snapshot_id": "418d15ea25e9e67f04f60bc412698f124afb8de7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/aaaaaa123456789/pret3/31206787aa809864f96ec987758a1160d2befe98/datadump/ib_hdr.c", "visit_date": "2023-05-18T19:52:13.229543" }
stackv2
#include "proto.h" struct incbin * get_incbin_data (const char * line) { const char * pos = strchr(strstr(line, ".incbin"), '"'); if (!pos) { puts("err: no filename specified"); return NULL; } pos ++; const char * end = strchr(pos, '"'); if (!end) { puts("err: invalid filename specification"); return NULL; } struct incbin * result = malloc(end - pos + 1 + sizeof(struct incbin)); result -> offset = result -> length = 0; memcpy(result -> file, pos, end - pos); result -> file[end - pos] = 0; pos = strchr(end, ','); if (!pos) return result; char * trimmed_line = trim_string(pos + 1); char * comment = (char *) find_first_unquoted(line, '@'); if (comment) *comment = 0; end = strchr(trimmed_line, ','); result -> offset = get_value_from_string(trimmed_line, end ? (end - trimmed_line) : strlen(trimmed_line)); if (result -> offset == -1u) { puts("err: invalid offset"); free(result); result = NULL; goto done; } if (!end) goto done; end ++; result -> length = get_value_from_string(end, strlen(end)); if (!(result -> length) || (result -> length == -1u)) { puts("err: invalid length"); free(result); result = NULL; } done: free(trimmed_line); return result; } int is_incbin (const char * line) { const char * pos = strstr(line, ".incbin"); if (!pos) return 0; const char * comment = strchr(line, '@'); if (!comment) return 1; return pos < comment; } void write_header_comment (struct incbin * incbin, FILE * out) { char * header = generate_incbin(incbin -> file, incbin -> offset, incbin -> length); printf(">>>> @ replacing: %s\n", header); fprintf(out, "@ replacing %s\n", header); free(header); } char * generate_incbin (const char * file, unsigned offset, unsigned length) { char * result = malloc(1); *result = 0; unsigned result_length = 0; char value[16]; concatenate(&result, &result_length, ".incbin \"", file, "\", ", NULL); sprintf(value, "0x%08x", offset); concatenate(&result, &result_length, value, ", ", NULL); sprintf(value, "0x%x", length); concatenate(&result, &result_length, value, NULL); return result; } void write_incbin_for_segment (const char * file, unsigned offset, unsigned length, FILE * out) { if (!length) return; char * incbin = generate_incbin(file, offset, length); char * indent; generate_initial_indented_line(&indent, NULL); printf(">>>> %s%s\n", indent, incbin); fprintf(out, "%s%s\n", indent, incbin); free(incbin); free(indent); }
2.640625
3
2024-11-18T20:59:44.181244+00:00
2022-03-06T20:37:58
77ecb42d40611c054d0303b40227aeab42e34ab3
{ "blob_id": "77ecb42d40611c054d0303b40227aeab42e34ab3", "branch_name": "refs/heads/master", "committer_date": "2022-03-06T20:37:58", "content_id": "95ef0fdba94bedc780278ca0b45d9d4624b6ffe2", "detected_licenses": [ "MIT", "BSD-2-Clause" ], "directory_id": "f5c289f539a3ea7b1adc293664b0e6b5e938e5d6", "extension": "c", "filename": "list.c", "fork_events_count": 16, "gha_created_at": "2018-11-22T22:36:24", "gha_event_created_at": "2022-04-17T10:15:57", "gha_language": "C", "gha_license_id": "MIT", "github_id": 158755940, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1467, "license": "MIT,BSD-2-Clause", "license_type": "permissive", "path": "/libacars/list.c", "provenance": "stackv2-0135.json.gz:247486", "repo_name": "szpajder/libacars", "revision_date": "2022-03-06T20:37:58", "revision_id": "64eec704397f0df03197296519f14f048d282ee0", "snapshot_id": "a7f5ab97bee035744c3f53395cb4b85d4af3981e", "src_encoding": "UTF-8", "star_events_count": 84, "url": "https://raw.githubusercontent.com/szpajder/libacars/64eec704397f0df03197296519f14f048d282ee0/libacars/list.c", "visit_date": "2023-07-21T13:45:16.492979" }
stackv2
/* * This file is a part of libacars * * Copyright (c) 2018-2021 Tomasz Lemiech <[email protected]> */ #include <libacars/macros.h> // la_assert #include <libacars/list.h> // la_list #include <libacars/util.h> // LA_XCALLOC, LA_XFREE la_list *la_list_next(la_list const *l) { if(l == NULL) { return NULL; } return l->next; } la_list *la_list_append(la_list *l, void *data) { LA_NEW(la_list, new); new->data = data; if(l == NULL) { return new; } else { la_list *ptr; for(ptr = l; ptr->next != NULL; ptr = la_list_next(ptr)) ; ptr->next = new; return l; } } size_t la_list_length(la_list const *l) { size_t len = 0; for(; l != NULL; l = la_list_next(l), len++) ; return len; } void la_list_foreach(la_list *l, void (*cb)(), void *ctx) { la_assert(cb != NULL); for(; l != NULL; l = la_list_next(l)) { cb(l->data, ctx); } } void la_list_free_full_with_ctx(la_list *l, void (*node_free)(), void *ctx) { if(l == NULL) { return; } la_list_free_full_with_ctx(l->next, node_free, ctx); l->next = NULL; if(node_free != NULL) { node_free(l->data, ctx); } else { LA_XFREE(l->data); } LA_XFREE(l); } void la_list_free_full(la_list *l, void (*node_free)()) { if(l == NULL) { return; } la_list_free_full(l->next, node_free); l->next = NULL; if(node_free != NULL) { node_free(l->data); } else { LA_XFREE(l->data); } LA_XFREE(l); } void la_list_free(la_list *l) { la_list_free_full(l, NULL); }
2.8125
3
2024-11-18T20:59:44.336755+00:00
2023-08-21T07:05:40
0a405334054db53443a50fa9f3bceb50b1457dda
{ "blob_id": "0a405334054db53443a50fa9f3bceb50b1457dda", "branch_name": "refs/heads/master", "committer_date": "2023-08-21T07:05:40", "content_id": "1ada7ff1493076bdc015f8e38f8558e9b8211088", "detected_licenses": [ "NTP" ], "directory_id": "93a265c44a22f47eab089bb8ef7d3b4f7c4a8bbf", "extension": "c", "filename": "send.c", "fork_events_count": 121, "gha_created_at": "2016-02-19T13:22:24", "gha_event_created_at": "2022-07-07T07:04:46", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 52089079, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2142, "license": "NTP", "license_type": "permissive", "path": "/src/tools/pgproto/send.c", "provenance": "stackv2-0135.json.gz:247751", "repo_name": "pgpool/pgpool2", "revision_date": "2023-08-21T07:05:40", "revision_id": "d8d288776a72be49badbbea111edba0223d597c0", "snapshot_id": "fcf6798a367a73a2d09585a80a95397002a34e16", "src_encoding": "UTF-8", "star_events_count": 292, "url": "https://raw.githubusercontent.com/pgpool/pgpool2/d8d288776a72be49badbbea111edba0223d597c0/src/tools/pgproto/send.c", "visit_date": "2023-08-27T20:48:10.937657" }
stackv2
/* * Copyright (c) 2017-2018 Tatsuo Ishii * Copyright (c) 2018-2021 PgPool Global Development Group * * Permission to use, copy, modify, and distribute this software and * its documentation for any purpose and without fee is hereby * granted, provided that the above copyright notice appear in all * copies and that both that copyright notice and this permission * notice appear in supporting documentation, and that the name of the * author not be used in advertising or publicity pertaining to * distribution of the software without specific, written prior * permission. The author makes no representations about the * suitability of this software for any purpose. It is provided "as * is" without express or implied warranty. */ #include "../../include/config.h" #include "pgproto/pgproto.h" #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <getopt.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <arpa/inet.h> #include "pgproto/fe_memutils.h" #include <libpq-fe.h> #include "pgproto/read.h" #include "pgproto/send.h" static void write_it(int fd, void *buf, int len); /* * Send a character to the connection. */ void send_char(char c, PGconn *conn) { write_it(PQsocket(conn), &c, 1); } /* * Send a 4-byte integer to the connection. */ void send_int(int intval, PGconn *conn) { int l = htonl(intval); write_it(PQsocket(conn), &l, sizeof(l)); } /* * Send a 2-byte integer to the connection. */ void send_int16(short shortval, PGconn *conn) { short s = htons(shortval); write_it(PQsocket(conn), &s, sizeof(s)); } /* * Send a string to the connection. buf must be NULL terminated. */ void send_string(char *buf, PGconn *conn) { write_it(PQsocket(conn), buf, strlen(buf) + 1); } /* * Send byte to the connection. */ void send_byte(char *buf, int len, PGconn *conn) { write_it(PQsocket(conn), buf, len); } /* * Wrapper for write(2). */ static void write_it(int fd, void *buf, int len) { int errsave = errno; errno = 0; if (write(fd, buf, len) < 0) { fprintf(stderr, "write_it: warning write(2) failed: %s\n", strerror(errno)); } errno = errsave; }
2.390625
2
2024-11-18T20:59:44.686229+00:00
2020-01-08T09:05:20
d3aead662b11c4c2cebf75a2403477fb13ea3d87
{ "blob_id": "d3aead662b11c4c2cebf75a2403477fb13ea3d87", "branch_name": "refs/heads/master", "committer_date": "2020-01-08T09:05:20", "content_id": "d9e953eaa2a190040410ffdb820bf5439f99e213", "detected_licenses": [ "MIT" ], "directory_id": "f040c13ab4c9c625c62f0bc5abc95521a96eb23a", "extension": "c", "filename": "arrayobject_tests.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 205540580, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2079, "license": "MIT", "license_type": "permissive", "path": "/Tests/arrayobject_tests.c", "provenance": "stackv2-0135.json.gz:247881", "repo_name": "422404/PipouScript", "revision_date": "2020-01-08T09:05:20", "revision_id": "0984b0bac81e5bedb03e03fdc26ad476e8c8ae63", "snapshot_id": "b7f56a7208e63edbcc25658838853774f43aedad", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/422404/PipouScript/0984b0bac81e5bedb03e03fdc26ad476e8c8ae63/Tests/arrayobject_tests.c", "visit_date": "2020-07-15T10:12:21.785891" }
stackv2
/** * @file arrayobject_tests.c * ArrayObject tests */ #include <stdio.h> #include "seatest.h" #include "nanbox.h" #include "arrayobject.h" #include "objects_types.h" void Test_ArrayObjectCreation(void) { nanbox_t arrayobject; arrayobject_t * arrayobject_ptr; size_t length; arrayobject = ArrayObject_New(); arrayobject_ptr = nanbox_to_pointer(arrayobject); assert_int_equal(ARRAY_OBJECT, arrayobject_ptr->type); length = nanbox_to_int(Object_GetField(arrayobject, "length")); assert_int_equal(0, length); Object_DecRef(&arrayobject); } void Test_ArrayObjectAppendingPopping(void) { nanbox_t arrayobject; size_t length; arrayobject = ArrayObject_New(); ArrayObject_Append(arrayobject, nanbox_from_int(1337)); ArrayObject_Append(arrayobject, nanbox_from_double(13.37)); length = nanbox_to_int(Object_GetField(arrayobject, "length")); assert_int_equal(2, length); assert_int_equal(1337, nanbox_to_int(ArrayObject_GetAt(arrayobject, 0))); assert_double_equal(13.37, nanbox_to_double(ArrayObject_GetAt(arrayobject, 1)), 0.0); ArrayObject_Pop(arrayobject); length = nanbox_to_int(Object_GetField(arrayobject, "length")); assert_int_equal(1, length); assert_int_equal(1, ArrayObject_GetLength(arrayobject)); Object_DecRef(&arrayobject); } void Test_ArrayObjectSettingGetting(void) { nanbox_t arrayobject; arrayobject = ArrayObject_New(); ArrayObject_Append(arrayobject, nanbox_from_int(1)); ArrayObject_Append(arrayobject, nanbox_from_int(2)); assert_int_equal(2, ArrayObject_GetLength(arrayobject)); ArrayObject_SetAt(arrayobject, 1, nanbox_from_int(1337)); assert_int_equal(1337, nanbox_to_int(ArrayObject_GetAt(arrayobject, 1))); assert_int_equal(2, ArrayObject_GetLength(arrayobject)); Object_DecRef(&arrayobject); } void Test_ArrayObjectTests(void) { test_fixture_start(); run_test(Test_ArrayObjectCreation); run_test(Test_ArrayObjectAppendingPopping); run_test(Test_ArrayObjectSettingGetting); test_fixture_end(); }
2.671875
3
2024-11-18T20:59:44.764356+00:00
2021-03-28T12:52:12
1b0a5f9ee1a4c081653b2b22c7fc08c038bab772
{ "blob_id": "1b0a5f9ee1a4c081653b2b22c7fc08c038bab772", "branch_name": "refs/heads/dev", "committer_date": "2021-03-28T12:52:12", "content_id": "442d95b0341bc26924c6b1535ac6db7503f8bc9e", "detected_licenses": [ "MIT" ], "directory_id": "dea22359a8de11a074fce5f287b747102f3d53be", "extension": "c", "filename": "temp_sensor_dispatcher.c", "fork_events_count": 0, "gha_created_at": "2020-05-31T17:17:54", "gha_event_created_at": "2021-03-28T12:52:13", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 268327671, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1304, "license": "MIT", "license_type": "permissive", "path": "/src/temp_sensor_dispatcher.c", "provenance": "stackv2-0135.json.gz:248013", "repo_name": "alexeychurchill/Thermometer", "revision_date": "2021-03-28T12:52:12", "revision_id": "5f959f43926148c59a76e5b2bcb480e5a56c729b", "snapshot_id": "f1edcba4990803b9e78067b90c337e5b1506d4cf", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/alexeychurchill/Thermometer/5f959f43926148c59a76e5b2bcb480e5a56c729b/src/temp_sensor_dispatcher.c", "visit_date": "2023-06-22T02:24:58.661867" }
stackv2
#include "temp_sensor_dispatcher.h" #include "config.h" #include "drivers/ds18b20.h" #include "poll_timer.h" typedef enum ThermometerState { TS_IDLE, TS_TEMP_MEASURE, TS_TEMP_READ } ThermState_t; static ThermState_t state; static DS18B20Sensor_t sensor; static void tsd_handle_state_idle() { if (poll_timer_is_running()) { return; } state = TS_TEMP_MEASURE; ds18b20_convert_t(&sensor); } static void tsd_handle_state_measure() { state = TS_TEMP_READ; ds18b20_send_read_scratchpad(&sensor); } static void tsd_handle_state_read() { state = TS_IDLE; poll_timer_start(TSD_MEASURE_PERIOD_MS); } static void (*therm_state_table[])() = { [TS_IDLE] = tsd_handle_state_idle, [TS_TEMP_MEASURE] = tsd_handle_state_measure, [TS_TEMP_READ] = tsd_handle_state_read }; void tsd_init(const OwBusLine_t *line) { state = TS_IDLE; ds18b20_init(line, &sensor); } void tsd_dispatch_state() { ds18b20_dispatch(&sensor); if (ds18b20_is_busy(&sensor)) { return; } therm_state_table[state](); } int32_t tsd_get_t() { int32_t temp_int = ((int32_t) ds18b20_get_temp_abs_int_part(&sensor)); bool temp_sign = ds18b20_get_temp_sign(&sensor); return temp_sign ? -temp_int : temp_int; }
2.5
2
2024-11-18T20:59:45.053073+00:00
2015-05-05T15:10:52
3e6ce327beadcaddaa2b29739e2eb4b23b3cb678
{ "blob_id": "3e6ce327beadcaddaa2b29739e2eb4b23b3cb678", "branch_name": "refs/heads/master", "committer_date": "2015-05-06T12:53:34", "content_id": "d6548e46001f5430dc91e59b3ab3b10554188735", "detected_licenses": [ "Apache-2.0" ], "directory_id": "84887f8182a6529af3e3ad1c13d5ae704f48d773", "extension": "c", "filename": "un.c", "fork_events_count": 3, "gha_created_at": "2015-05-06T23:48:50", "gha_event_created_at": "2015-05-06T23:48:50", "gha_language": null, "gha_license_id": null, "github_id": 35188786, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2968, "license": "Apache-2.0", "license_type": "permissive", "path": "/old/linux_backend/src/wsh/un.c", "provenance": "stackv2-0135.json.gz:248273", "repo_name": "b/garden-linux", "revision_date": "2015-05-05T15:10:52", "revision_id": "f6e6018b5a123fdf3dc03b97d6f4464af3039700", "snapshot_id": "6f6b75757057dd22df6245017d5a0f575b5bab17", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/b/garden-linux/f6e6018b5a123fdf3dc03b97d6f4464af3039700/old/linux_backend/src/wsh/un.c", "visit_date": "2021-01-17T23:29:43.211944" }
stackv2
#define _GNU_SOURCE #include <assert.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include "un.h" int un__socket() { int fd; if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } return fd; } int un_listen(const char *path) { int fd; struct sockaddr_un sa; fd = un__socket(); sa.sun_family = AF_UNIX; assert(strlen(path) < sizeof(sa.sun_path)); strcpy(sa.sun_path, path); unlink(sa.sun_path); if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) == -1) { perror("bind"); exit(1); } if (listen(fd, 5) == -1) { perror("listen"); exit(1); } return fd; } int un_connect(const char *path) { int fd; struct sockaddr_un sa; int rv; fd = un__socket(); sa.sun_family = AF_UNIX; assert(strlen(path) < sizeof(sa.sun_path)); strcpy(sa.sun_path, path); rv = connect(fd, (struct sockaddr *)&sa, sizeof(sa)); if (rv == -1) { close(fd); return rv; } return fd; } int un_send_fds(int fd, char *data, int datalen, int *fds, int fdslen) { struct msghdr mh; struct cmsghdr *cmh = NULL; char buf[2048]; size_t buflen = CMSG_SPACE(sizeof(int) * fdslen); struct iovec iov[1]; assert(sizeof(buf) >= buflen); memset(&mh, 0, sizeof(mh)); mh.msg_control = buf; mh.msg_controllen = buflen; mh.msg_iov = iov; mh.msg_iovlen = 1; iov[0].iov_base = data; iov[0].iov_len = datalen; cmh = CMSG_FIRSTHDR(&mh); cmh->cmsg_level = SOL_SOCKET; cmh->cmsg_type = SCM_RIGHTS; cmh->cmsg_len = CMSG_LEN(sizeof(int) * fdslen); memcpy(CMSG_DATA(cmh), fds, sizeof(int) * fdslen); mh.msg_controllen = cmh->cmsg_len; int rv; do { rv = sendmsg(fd, &mh, 0); } while (rv == -1 && errno == EINTR); return rv; } int un_recv_fds(int fd, char *data, int datalen, int *fds, int fdslen) { struct msghdr mh; struct cmsghdr *cmh = NULL; char buf[2048]; size_t buflen = CMSG_SPACE(sizeof(int) * fdslen); struct iovec iov[1]; assert(sizeof(buf) >= buflen); memset(&mh, 0, sizeof(mh)); mh.msg_control = buf; mh.msg_controllen = buflen; mh.msg_iov = iov; mh.msg_iovlen = 1; iov[0].iov_base = data; iov[0].iov_len = datalen; int rv = -1; errno = 0; do { rv = recvmsg(fd, &mh, 0); } while (rv == -1 && (errno == EINTR || errno == EAGAIN)); if (rv <= 0) { goto done; } if (fds != NULL) { cmh = CMSG_FIRSTHDR(&mh); assert(cmh != NULL); assert(cmh->cmsg_level == SOL_SOCKET); assert(cmh->cmsg_type == SCM_RIGHTS); assert(cmh->cmsg_len == CMSG_LEN(sizeof(int) * fdslen)); int *fds_ = (int *)CMSG_DATA(cmh); int i; for (i = 0; i < fdslen; i++) { fds[i] = fds_[i]; } } while (rv < datalen) { int temp_rv = recv(fd, data + rv, (datalen - rv), MSG_WAITALL); if (temp_rv <= 0) { goto done; } rv += temp_rv; } done: return rv; }
2.375
2
2024-11-18T20:59:45.214026+00:00
2017-10-27T17:24:53
e6f96ddc880a196e2df66efe492998cfa272d943
{ "blob_id": "e6f96ddc880a196e2df66efe492998cfa272d943", "branch_name": "refs/heads/master", "committer_date": "2017-10-27T17:24:53", "content_id": "d09d84b16bbe1f1a7b90f567e4b500f400fb902b", "detected_licenses": [ "MIT", "BSD-2-Clause" ], "directory_id": "da2ba9dc5a31a27dc0af5efdaefb36ecb94211dd", "extension": "h", "filename": "tommy_helper.h", "fork_events_count": 0, "gha_created_at": "2017-07-16T01:37:29", "gha_event_created_at": "2017-10-26T20:00:02", "gha_language": "Ruby", "gha_license_id": null, "github_id": 97352557, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1393, "license": "MIT,BSD-2-Clause", "license_type": "permissive", "path": "/vendor/tommy_helper.h", "provenance": "stackv2-0135.json.gz:248404", "repo_name": "mooreryan/lsa_for_genomes", "revision_date": "2017-10-27T17:24:53", "revision_id": "706a2e4b7dd7bbc740beebae157ca36a9e6982b9", "snapshot_id": "9bd857a20769e1fada43254ed25cf158cbc40012", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/mooreryan/lsa_for_genomes/706a2e4b7dd7bbc740beebae157ca36a9e6982b9/vendor/tommy_helper.h", "visit_date": "2021-01-01T06:04:12.472579" }
stackv2
#define HASHLIN_INIT(name) \ do { \ name = malloc(sizeof *name); \ PANIC_MEM(name, stderr); \ tommy_hashlin_init(name); \ } while (0) #define HASHLIN_DONE(name, free_func) \ do { \ tommy_hashlin_foreach(name, (tommy_foreach_func*)free_func); \ tommy_hashlin_done(name); \ free(name); \ } while (0) #define ARRAY_INIT(name) \ do { \ name = malloc(sizeof *name); \ PANIC_MEM(name, stderr); \ tommy_array_init(name); \ } while (0) #define ARRAY_DONE(name, free_func) \ do { \ for (int i = 0; i < tommy_array_size(name); ++i) { \ free_func(tommy_array_get(name, i)); \ } \ \ tommy_array_done(name); \ free(name); \ } while (0)
2.453125
2
2024-11-18T20:59:45.302997+00:00
2019-03-28T17:28:56
26e224142280b1173f8f936b4f4a8edf12bf1ed5
{ "blob_id": "26e224142280b1173f8f936b4f4a8edf12bf1ed5", "branch_name": "refs/heads/jumpstart-php", "committer_date": "2019-03-28T17:28:56", "content_id": "cc8730d25c0d12eaf469795798e1a28d770ea8cc", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "24d856d98c85a319d53be2768ccc176a50873fa3", "extension": "h", "filename": "taints_graph.h", "fork_events_count": 2, "gha_created_at": "2019-08-03T17:57:58", "gha_event_created_at": "2019-08-03T19:45:44", "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 200405626, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11383, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/dift/taints/taints_graph.h", "provenance": "stackv2-0135.json.gz:248535", "repo_name": "dozenow/shortcut", "revision_date": "2019-03-28T17:28:56", "revision_id": "b140082a44c58f05af3495259c1beaaa9a63560b", "snapshot_id": "a4803b59c95e72a01d73bb30acaae45cf76b0367", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/dozenow/shortcut/b140082a44c58f05af3495259c1beaaa9a63560b/dift/taints/taints_graph.h", "visit_date": "2020-06-29T11:41:05.842760" }
stackv2
#ifndef TAINTS_GRAPH_H #define TAINTS_GRAPH_H #include <stdio.h> #include <stdlib.h> #include "../list.h" #include <glib-2.0/glib.h> #include <assert.h> #include <string.h> #include "slab_alloc.h" #ifdef __cplusplus extern "C" { #endif /* * This file contains all of the functions for manipulating taint * if we're using references to taints * */ #define NUM_OPTIONS G_MAXUINT32 #define CONFIDENCE_LEVELS 1 typedef guint8 TAINT_TYPE; /* Some performance optimizations */ #define USE_SLAB_ALLOCATOR #define SPLIT_MERGE_HASH_SPACE /* Different options */ // #define MERGE_PREDICTOR // simple 1-bit predictor #define MERGE_STATS #ifdef MERGE_STATS #include "../taints_profile.h" struct taints_profile merge_profile; #endif // the type of an index typedef guint32 OPTION_TYPE; struct node { struct node* parent1; struct node* parent2; #ifdef MERGE_PREDICTOR struct node* prev_merged_with; // who did I last merge with? struct node* prev_merged_result; // what was the result of the merge? #endif }; /* leafnode is a node with two NULL parents and an option value */ struct leafnode { struct node node; OPTION_TYPE option; }; struct taint { struct node* id; }; #ifdef SPLIT_MERGE_HASH_SPACE #define NUM_MERGE_TABLES 0x4 GHashTable* taint_merge_index_tables[NUM_MERGE_TABLES]; #else // structure for holding merged indices GHashTable* taint_merge_index; #endif #ifdef MERGE_STATS #ifdef MERGE_PREDICTOR long merge_predict_count = 0; #endif #endif struct slab_alloc leaf_alloc; struct slab_alloc node_alloc; struct slab_alloc uint_alloc; inline void init_taint_tables(void) { int i = 0; for (i = 0; i < NUM_MERGE_TABLES; i++) { taint_merge_index_tables[i] = g_hash_table_new_full(g_int64_hash, g_int64_equal, free, NULL); } } inline void init_taint_index(void) { #ifdef SPLIT_MERGE_HASH_SPACE init_taint_tables(); #else taint_merge_index = g_hash_table_new_full(g_int64_hash, g_int64_equal, free, NULL); #endif #ifdef USE_SLAB_ALLOCATOR init_slab_alloc(); new_slab_alloc((char *)"LEAF_ALLOC", &leaf_alloc, sizeof(struct leafnode), 20000); new_slab_alloc((char *)"NODE_ALLOC", &node_alloc, sizeof(struct node), 20000); new_slab_alloc((char *)"UINT_ALLOC", &uint_alloc, sizeof(guint64), 20000); #endif } struct leafnode* get_new_leafnode(OPTION_TYPE option) { struct leafnode* ln; #ifdef USE_SLAB_ALLOCATOR ln = (struct leafnode *) get_slice(&leaf_alloc); #else ln = (struct leafnode *) malloc(sizeof(struct leafnode*)); #endif memset(ln, 0, sizeof(struct leafnode)); ln->node.parent1 = NULL; ln->node.parent2 = NULL; #ifdef MERGE_PREDICTOR ln->node.prev_merged_with = NULL; ln->node.prev_merged_result = NULL; #endif ln->option = option; return ln; } struct node* get_new_node(struct node* parent1, struct node* parent2) { struct node* n; #ifdef USE_SLAB_ALLOCATOR n = (struct node *) get_slice(&node_alloc); #else n = (struct node *) malloc(sizeof(struct node *)); #endif memset(n, 0, sizeof(struct node)); n->parent1 = parent1; n->parent2 = parent2; #ifdef MERGE_PREDICTOR n->prev_merged_with = NULL; n->prev_merged_result = NULL; #endif return n; } guint64* get_new_64() { #ifdef USE_SLAB_ALLOCATOR return (guint64 *) get_slice(&uint_alloc); #else return (guint 64 *) malloc(sizeof(guint64)); #endif } inline guint64 hash_indices(guint32 index1, guint32 index2) { guint64 hash; // make index 2 always be the bigger number if (index1 > index2) { guint32 tmp; tmp = index2; index2 = index1; index1 = tmp; } hash = index1; hash = hash << 32; hash += index2; // fprintf(stderr, "hash is %llx, index1 %lx, index2 %lx\n", hash, (unsigned long) index1, (unsigned long) index2); return hash; } inline void new_taint(struct taint* t) { t->id = 0; } inline TAINT_TYPE get_max_taint_value(void) { // return G_MAXINT8; return 1; } inline TAINT_TYPE get_taint_value(struct taint* t, OPTION_TYPE option) { GQueue* queue = g_queue_new(); GHashTable* seen_indices = g_hash_table_new(g_direct_hash, g_direct_equal); struct node* n = t->id; g_queue_push_tail(queue, n); TAINT_TYPE found = 0; while(!g_queue_is_empty(queue)) { n = (struct node *) g_queue_pop_head(queue); if (g_hash_table_lookup(seen_indices, n)) { continue; } g_hash_table_insert(seen_indices, GUINT_TO_POINTER(n), GINT_TO_POINTER(1)); if (!n->parent1 && !n->parent2) { // leaf node struct leafnode* ln = (struct leafnode *) n; if (ln->option == option) { found = get_max_taint_value(); break; } } else { if (!g_hash_table_lookup(seen_indices, GUINT_TO_POINTER(n->parent1))) { g_queue_push_tail(queue, n->parent1); } if (!g_hash_table_lookup(seen_indices, GUINT_TO_POINTER(n->parent2))) { g_queue_push_tail(queue, n->parent2); } } } g_queue_free(queue); g_hash_table_destroy(seen_indices); return found; } inline void set_taint_value (struct taint* t, OPTION_TYPE option, TAINT_TYPE value) { struct leafnode* ln; ln = get_new_leafnode(option); t->id = (struct node *) ln; #ifdef MERGE_STATS increment_taint_op(&merge_profile, STATS_OP_UNIQUE_TAINTS); #endif } inline int is_taint_equal(struct taint* first, struct taint* second) { if (!first && !second) return 0; if ((first && !second) || (!first && second)) return 1; return first->id == second->id; } inline int is_taint_zero(struct taint* src) { #ifdef BINARY_FWD_TAINT if ((u_long) src) { return 1; } else { return 0; } #else if (!src) return 0; return !src->id; #endif } inline void is_taint_full(struct taint* t) { fprintf(stderr, "Should not use full taints in index mode\n"); } inline void set_taint_full (struct taint* t) { fprintf(stderr, "Should not use full taints in index mode\n"); } inline void clear_taint(struct taint* t) { if (!t) return; t->id = 0; #ifdef MERGE_STATS increment_taint_op(&merge_profile, STATS_OP_CLEAR); #endif } inline void set_taint(struct taint* dst, struct taint* src) { dst->id = src->id; #ifdef MERGE_STATS increment_taint_op(&merge_profile, STATS_OP_SET); #endif } inline void merge_taints(struct taint* dst, struct taint* src) { struct node* n; guint64 hash; guint64* phash; GHashTable* taint_merge_index; if (!dst || !src) return; if (dst->id == 0) { dst->id = src->id; return; } if (src->id == 0) { return; } if (dst->id == src->id) { return; } #ifdef BINARY_FWD_TAINT if (src->id) { dst->id = src->id; return; } #endif #ifdef MERGE_PREDICTOR n = dst->id; if (n->prev_merged_with == src->id) { dst->id = n->prev_merged_result; #ifdef MERGE_STATS merge_predict_count = 0; #endif return; } #endif hash = hash_indices((guint32) dst->id, (guint32) src->id); #ifdef MERGE_STATS increment_taint_op(&merge_profile, STATS_OP_MERGE); #endif taint_merge_index = taint_merge_index_tables[hash & (NUM_MERGE_TABLES-1)]; n = (struct node *) g_hash_table_lookup(taint_merge_index, &hash); if (!n) { n = get_new_node(dst->id, src->id); //phash = (guint64 *) malloc(sizeof(guint64)); phash = (guint64 *) get_new_64(); memcpy(phash, &hash, sizeof(guint64)); g_hash_table_insert(taint_merge_index, phash, n); #ifdef MERGE_STATS increment_taint_op(&merge_profile, STATS_OP_UNIQUE_MERGE); increment_taint_op(&merge_profile, STATS_OP_UNIQUE_TAINTS); #endif } #ifdef MERGE_PREDICTOR dst->id->prev_merged_with = src->id; dst->id->prev_merged_result = n; #endif //fprintf(stderr, "merge (%lu, %lu) result: %lu\n", (unsigned long) dst->id, (unsigned long) src->id, (unsigned long) n); dst->id = n; } void shift_taints(struct taint* dst, struct taint* src, int level) { fprintf(stderr, "Should not use SHIFT taints in index mode\n"); } void shift_merge_taints(struct taint* dst, struct taint* src, int level) { fprintf(stderr, "Should not use SHIFT MERGE taints in index mode\n"); } void shift_cf_taint(struct taint* dst, struct taint* cond, struct taint* prev) { fprintf(stderr, "Should not use SHIFT CF taints in index mode\n"); } void print_kv(gpointer key, gpointer value, gpointer user_data) { fprintf(stderr, "k: %p, v: %d\n", key, GPOINTER_TO_INT(value)); } void print_taint(FILE* fp, struct taint* src) { if (!src) { fprintf(fp, "id {0}\n"); } else if (!src->id) { fprintf(fp, "id {0}\n"); } else { GQueue* queue = g_queue_new(); GHashTable* seen_indices = g_hash_table_new(g_direct_hash, g_direct_equal); struct node* n = src->id; fprintf(fp, "id {"); g_queue_push_tail(queue, n); while(!g_queue_is_empty(queue)) { n = (struct node *) g_queue_pop_head(queue); if (g_hash_table_lookup(seen_indices, n)) { continue; } g_hash_table_insert(seen_indices, n, GINT_TO_POINTER(1)); if (!n->parent1 && !n->parent2) { // leaf node struct leafnode* ln = (struct leafnode *) n; fprintf(fp, "%lu,", (unsigned long) ln->option); } else { if (!g_hash_table_lookup(seen_indices, n->parent1)) { g_queue_push_tail(queue, n->parent1); } if (!g_hash_table_lookup(seen_indices, n->parent2)) { g_queue_push_tail(queue, n->parent2); } } } g_queue_free(queue); g_hash_table_destroy(seen_indices); fprintf(fp, "}\n"); } } /* Compute the taints in the index */ GList* get_non_zero_taints(struct taint* t) { GHashTable* seen_indices; GList* list = NULL; struct node* n = t->id; GQueue* queue; if (!n) { return NULL; } queue = g_queue_new(); seen_indices = g_hash_table_new(g_direct_hash, g_direct_equal); g_queue_push_tail(queue, n); while(!g_queue_is_empty(queue)) { n = (struct node *) g_queue_pop_head(queue); if (g_hash_table_lookup(seen_indices, n)) { continue; } g_hash_table_insert(seen_indices, n, GINT_TO_POINTER(1)); if (!n->parent1 && !n->parent2) { // leaf node struct leafnode* ln = (struct leafnode *) n; list = g_list_prepend(list, GUINT_TO_POINTER(ln->option)); } else { if (!g_hash_table_lookup(seen_indices, n->parent1)) { g_queue_push_tail(queue, n->parent1); } if (!g_hash_table_lookup(seen_indices, n->parent2)) { g_queue_push_tail(queue, n->parent2); } } } g_queue_free(queue); g_hash_table_destroy(seen_indices); return list; } void remove_index(guint32 idx) { // TODO } #ifdef MERGE_STATS inline unsigned long get_unique_taint_count(void) { return merge_profile.stats_op_count[STATS_OP_UNIQUE_TAINTS]; } #endif #ifdef __cplusplus } #endif #endif // end guard TAINTS_GRAPH_H
2.265625
2
2024-11-18T20:59:45.375583+00:00
2015-07-06T20:25:22
bf19fab617b2271bf90672795b9d8af17752d754
{ "blob_id": "bf19fab617b2271bf90672795b9d8af17752d754", "branch_name": "refs/heads/master", "committer_date": "2015-07-06T20:25:22", "content_id": "0ea1486f072e34aca77356ad795cebba43031325", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "dd75577b8f444281d7ef6279ee24151e4ffc56d2", "extension": "c", "filename": "render.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 33941156, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 24538, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/app/render/src/render.c", "provenance": "stackv2-0135.json.gz:248664", "repo_name": "TeravoxelTwoPhotonTomography/tilebase", "revision_date": "2015-07-06T20:25:22", "revision_id": "61f2e6b979d214afab8dd60d6f55afc3e4697e24", "snapshot_id": "3ec1198d1f5ce0e934a961252f0074965a93662f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/TeravoxelTwoPhotonTomography/tilebase/61f2e6b979d214afab8dd60d6f55afc3e4697e24/app/render/src/render.c", "visit_date": "2021-01-10T19:51:55.216610" }
stackv2
/** * \file * Recursively downsample a volume represented by a tile database. * * \todo refactor to sepererate tree traversal from the rendering bits. */ // C4090: const correctness -- should fix // C4244: floating to integral type conversion #pragma warning(disable:4244 4090) #include <app/render/config.h> #include <stdio.h> #include <string.h> #include "render.h" #include "filter.h" #include "xform.h" #include "address.h" #include "subdiv.h" #include <math.h> //for sqrt #include "tictoc.h" // for profiling #if HAVE_CUDA #include "cuda_runtime.h" // for cudaGetMemInfo #endif #ifdef _MSC_VER #include <malloc.h> #define alloca _alloca #endif #define countof(e) (sizeof(e)/sizeof(*(e))) #define ENDL "\n" #define LOG(...) fprintf(stderr,__VA_ARGS__) #define TRY(e) do{if(!(e)) { LOG("%s(%d): %s()"ENDL "\tExpression evaluated as false."ENDL "\t%s"ENDL,__FILE__,__LINE__,__FUNCTION__,#e); breakme(); goto Error;}} while(0) #define NEW(T,e,N) TRY((e)=(T*)malloc(sizeof(T)*(N))) #define ALLOCA(T,e,N) TRY((e)=(T*)alloca(sizeof(T)*(N))) #define ZERO(T,e,N) memset((e),0,(N)*sizeof(T)) #define REALLOC(T,e,N) TRY((e)=realloc((e),sizeof(T)*(N))) #define TODO LOG("TODO - %s(%d)\n",__FILE__,__LINE__,__FUNCTION__) #define DEBUG #define PROFILE_MEMORY #define ENABLE_PROGRESS_OUTPUT //#define DEBUG_DUMP_IMAGES #define PROFILE #ifdef DEBUG #define DBG(...) LOG(__VA_ARGS__) #else #define DBG(...) #endif #ifdef ENABLE_PROGRESS_OUTPUT #define PROGRESS(...) LOG(__VA_ARGS__) #else #define PROGRESS(...) #endif #if defined(PROFILE_MEMORY) && HAVE_CUDA static nd_t ndcuda_log(nd_t vol, void *s) { unsigned i; int idev; cudaGetDevice(&idev); LOG("NDCUDA ALLOC (Dev: %2d): %g MB [%llu",idev,ndnbytes(vol)*1e-6,(unsigned long long)ndshape(vol)[0]); for(i=1; i<ndndim(vol);++i) LOG(",%llu",(unsigned long long)ndshape(vol)[i]); LOG("]"ENDL); return ndcuda(vol,s); } #define NDCUDA(v,s) ndcuda_log(v,s) #else #define NDCUDA(v,s) ndcuda(v,s) #endif // PROFILE_MEMORY #ifdef DEBUG_DUMP_IMAGES #define DUMP(...) dump(__VA_ARGS__) #else #define DUMP(...) #endif #ifdef PROFILE #define TIME(e) do{ TicTocTimer __t__=tic(); e; LOG("%7.3f s - %s"ENDL,toc(&__t__),#e); }while(0) #else #define TIME(e) e #endif // === ADDRESSING A PATH IN THE TREE === static void breakme() {LOG(ENDL);} static void dump(const char *filename,nd_t a) { LOG("Writing %s"ENDL,filename); ndioClose(ndioWrite(ndioOpen(filename,NULL,"w"),a)); } // === RENDERING === typedef struct _filter_workspace { nd_t filters[3]; ///< filter for each axis nd_t gpu[2]; ///< double buffer on gpu for serial seperable convolutions int enable[3]; ///< enable filtering for the corresponding axis float scale_thresh; unsigned capacity;///< capacity of alloc'd gpu buffers unsigned i; ///< current gpu buffer nd_conv_params_t params; } filter_workspace; typedef struct _affine_workspace { nd_t host_xform,gpu_xform; nd_affine_params_t params; } affine_workspace; /// Common arguments and memory context used for building the tree typedef struct _desc_t desc_t; struct _desc_t { /* PARAMETERS */ tiles_t tiles; float x_nm,y_nm,z_nm,voxvol_nm3; size_t nchildren; // subdivision factor. must be power of 2. 4 means subdivision will be on x and y, 8 is x,y, and z size_t countof_leaf; void *args; // extra arguments to pass to yield() handler_t yield; /* WORKSPACE */ nd_t ref; int nbufs; nd_t *bufs; //Need 1 for each node on path in tree - so pathlength(root,leaf) int *inuse; filter_workspace input_fws; filter_workspace output_fws; affine_workspace aws; float *transform; size_t free,total; /* INTERFACE */ /* Returns an array that fills the bounding box \a bbox that corresponds to the a node on the subdivision tree specified by \a path. This usually involves a recursive descent of the tree, so this function is expected to call itself. Various helper functions below help with the traversal and manage the desc_t workspace. The implementation can call desc->yield() to pass data out during the tree traversal. For example, this is useful for saving each hierarchically downsampled volume to disk as a root node is rendered. */ nd_t (*make)(desc_t *desc,aabb_t bbox,address_t path); }; // // Forward declare interface functions. See desc_t comments for description of the interface. // // Hierarchical downsampling in memory. static nd_t render_child(desc_t *desc, aabb_t bbox, address_t path); static nd_t render_leaf(desc_t *desc, aabb_t bbox, address_t path); static nd_t render_child_to_parent(desc_t *desc,aabb_t bbox, address_t path, nd_t child, aabb_t cbox, nd_t workspace); static int compute_output_filters(filter_workspace *ws, float sx, float sy, float sz); static void filter_workspace__init(filter_workspace *ws) { memset(ws,0,sizeof(*ws)); ws->params.boundary_condition=nd_boundary_replicate; ws->scale_thresh=0.5f; } static void affine_workspace__init(affine_workspace *ws) { memset(ws,0,sizeof(*ws)); ws->params.boundary_value=0x8000; // MIN_I16 - TODO: hardcoded here...should be an option }; static double boundary_value(nd_t vol) { switch(ndtype(vol)) { case nd_u8: case nd_u16: case nd_u32: case nd_u64: case nd_f32: case nd_f64: return 0; break; case nd_i8: return 0x80; break; case nd_i16: return 0x8000; break; case nd_i32: return 0x80000000; break; case nd_i64: return (double)(0x8000000000000000LL); break; default: return 0; } } static void affine_workspace__set_boundary_value(affine_workspace* ws,nd_t vol) { ws->params.boundary_value=boundary_value(vol); } static desc_t make_desc(const struct render *opts, tiles_t tiles, handler_t yield, void* args) { const float um2nm=1e3; desc_t out; memset(&out,0,sizeof(out)); out.tiles=tiles; out.x_nm=(float)(opts->voxel_um[0]*um2nm); out.y_nm=(float)(opts->voxel_um[1]*um2nm); out.z_nm=(float)(opts->voxel_um[2]*um2nm); out.voxvol_nm3=out.x_nm*out.y_nm*out.z_nm; out.nchildren=opts->nchildren; out.countof_leaf=opts->countof_leaf; out.args=args; out.yield=yield; filter_workspace__init(&out.input_fws); out.input_fws.scale_thresh=opts->input_filter_scale_thresh; filter_workspace__init(&out.output_fws); out.output_fws.scale_thresh=opts->output_filter_scale_thresh; compute_output_filters(&out.output_fws, opts->output_filter_size_nm[0]/(float)out.x_nm, opts->output_filter_size_nm[1]/(float)out.y_nm, opts->output_filter_size_nm[2]/(float)out.z_nm); affine_workspace__init(&out.aws); out.make=render_child; return out; } static void cleanup_desc(desc_t *desc) { size_t i; ndfree(desc->ref); for(i=0;i<desc->nbufs;++i) ndfree(desc->bufs[i]); if(desc->transform) free(desc->transform); } static unsigned isleaf(const desc_t*const desc, aabb_t bbox) { int64_t c=(int64_t)(AABBVolume(bbox)/(double)desc->voxvol_nm3); return c<(int64_t)desc->countof_leaf; } /// Count path length from the current node to a leaf static int pathlength(desc_t *desc, aabb_t bbox) { int i,n=0; aabb_t *cboxes=0; ALLOCA(aabb_t,cboxes,desc->nchildren); ZERO( aabb_t,cboxes,desc->nchildren); if(isleaf(desc,bbox)) return 1; AABBBinarySubdivision(cboxes,(unsigned)desc->nchildren,bbox); n=pathlength(desc,cboxes[0]); for(i=0;i<desc->nchildren;++i) AABBFree(cboxes[i]); return n+1; Error: return 0; } /** This and set_ref_shape() allocate space required to render the subdivision tree. */ static int preallocate(desc_t *desc, aabb_t bbox) { size_t n; TRY(n=pathlength(desc,bbox)); NEW(nd_t,desc->bufs,n); ZERO(nd_t,desc->bufs,n); NEW(int,desc->inuse,n); ZERO(int,desc->inuse,n); desc->nbufs=(int)n; return 1; Error: return 0; } static int preallocate_for_render_one_target(desc_t *desc, aabb_t bbox) { size_t n=2; //TRY(n=pathlength(desc,bbox)); NEW(nd_t,desc->bufs,n); ZERO(nd_t,desc->bufs,n); NEW(int,desc->inuse,n); ZERO(int,desc->inuse,n); desc->nbufs=(int)n; return 1; Error: return 0; } static desc_t* set_ref_shape(desc_t *desc, nd_t v) { nd_t t; if(desc->ref) // init first time only { TRY(ndreshape(ndcast(desc->ref,ndtype(v)),ndndim(v),ndshape(v))); // update reference shape return desc; } TRY(ndreshape(ndcast(desc->ref=ndinit(),ndtype(v)),ndndim(v),ndshape(v))); { int i; // preallocate gpu bufs with pixel type corresponding to input TRY(ndShapeSet(ndcast(t=ndinit(),ndtype(desc->ref)),0,desc->countof_leaf)); for(i=0;i<desc->nbufs;++i) TRY(desc->bufs[i]=NDCUDA(t,0)); } return desc; Error: LOG("\t[nd Error]:"ENDL "\t%s"ENDL,nderror(t)); return 0; } static int sum(int n, const int*const v) { int i,o=0; for(i=0;i<n;++i) o+=v[i]; return o; } static unsigned same_shape_by_res(nd_t v, int64_t*restrict shape_nm, int64_t*restrict res, size_t ndim) { size_t i,*vs; vs=ndshape(v); for(i=0;i<ndim;++i) if(vs[i]!=(shape_nm[i]/res[i])) return 0; return 1; } static nd_t alloc_vol(desc_t *desc, aabb_t bbox, int64_t x_nm, int64_t y_nm, int64_t z_nm) { nd_t v; int64_t *shape_nm; int64_t res[]={x_nm,y_nm,z_nm}; size_t ndim,i,j; int resize=1; AABBGet(bbox,&ndim,0,&shape_nm); for(i=0;i<desc->nbufs && desc->inuse[i];++i); // search for first unused - preferably with correct shape for(j=i;j<desc->nbufs;++j) { if(!desc->inuse[j] && same_shape_by_res(desc->bufs[j],shape_nm,res,ndim)) { i=j; resize=0; break; } } TRY(i<desc->nbufs); // check that one was available TRY(v=desc->bufs[i]); // ensure bufs was init'd - see set_ref_shape() desc->inuse[i]=1; DBG(" alloc_vol(): [%3u] buf=%u"ENDL,(unsigned)sum(desc->nbufs,desc->inuse),(unsigned)i); if(resize) { for(i=0;i<ndim && i<countof(res);++i) // set spatial dimensions TRY(ndShapeSet(v,(unsigned)i,shape_nm[i]/res[i])); for(;i<ndndim(desc->ref);++i) // other dimensions are same as input TRY(ndShapeSet(v,(unsigned)i,ndshape(desc->ref)[i])); TRY(ndCudaSyncShape(v)); // expensive...worth avoiding } TRY(ndfill(v,(uint64_t)(desc->aws.params.boundary_value))); return v; Error: return 0; } static unsigned release_vol(desc_t *desc,nd_t a) { size_t i; if(!a) return 0; for(i=0;i<desc->nbufs && desc->bufs[i]!=a;++i) {} // search for buffer corresponding to a DBG(" release_vol(): buf=%u"ENDL,(unsigned)i); if(i>=desc->nbufs) // if a is not from the managed pool, just free it { ndfree(a); return 1; } TRY(desc->inuse[i]); // ensure it was marked inuse. (sanity check) desc->inuse[i]=0; return 1; Error: return 0; } static unsigned same_shape(nd_t a, nd_t b) { size_t i; size_t *sa,*sb; if(ndndim(a)!=ndndim(b)) return 0; sa=ndshape(a); sb=ndshape(b); for(i=0;i<ndndim(a);++i) if(sa[i]!=sb[i]) return 0; return 1; } static unsigned filter_workspace__gpu_resize(filter_workspace *ws, nd_t vol) { #if HAVE_CUDA { size_t free,total; cudaMemGetInfo(&free,&total); LOG("GPU Mem:\t%6.2f free\t%6.2f total\n",free/1e6,total/1e6); } if(!ws->gpu[0]) { TRY(ws->gpu[0]=NDCUDA(vol,0)); TRY(ws->gpu[1]=NDCUDA(vol,0)); ws->capacity=(unsigned)ndnbytes(ws->gpu[0]); } if(!same_shape(ws->gpu[0],vol)) { ndreshape(ws->gpu[0],ndndim(vol),ndshape(vol)); ndreshape(ws->gpu[1],ndndim(vol),ndshape(vol)); ndCudaSyncShape(ws->gpu[0]); // the cuda transfer can get expensive so it's worth avoiding these calls ndCudaSyncShape(ws->gpu[1]); ws->capacity=(unsigned)ndnbytes(ws->gpu[0]); } return 1; #endif Error: return 0; } static unsigned affine_workspace__gpu_resize(affine_workspace *ws, nd_t vol) { if(!ws->gpu_xform) { TRY(ndreshapev(ndcast(ws->host_xform=ndinit(),nd_f32),2,ndndim(vol)+1,ndndim(vol)+1)); TRY(ws->gpu_xform=NDCUDA(ws->host_xform,0)); } return 1; Error: return 0; } static int compute_aa_filters(filter_workspace *ws, float *transform, size_t ndim) { unsigned i=0; for(i=0;i<3;++i) { nd_t f=0; // ndim+1 for width of transform matrix, ndim+2 to address diagonals TIME(f=make_aa_filter(0.5f,transform[i*(ndim+2)],ws->scale_thresh,ws->filters[i])); ws->enable[i] = (f!=NULL); if(f) ws->filters[i]=f; } return 1; Error: return 0; } static int compute_output_filters(filter_workspace *ws, float sx, float sy, float sz) { nd_t f=0; f=make_aa_filter(1.0f,sx,ws->scale_thresh,ws->filters[0]); ws->enable[0]=(f!=NULL); if(f) ws->filters[0]=f; f=make_aa_filter(1.0f,sy,ws->scale_thresh,ws->filters[1]); ws->enable[1]=(f!=NULL); if(f) ws->filters[1]=f; f=make_aa_filter(1.0f,sz,ws->scale_thresh,ws->filters[2]); ws->enable[2]=(f!=NULL); if(f) ws->filters[2]=f; return 1; Error: return 0; } /** * Anti-aliasing filter. Uses seperable convolutions. * Uses double-buffering. The two buffers are tracked by the filter_workspace. * The final buffer is returned as the result. It is managed by the workspace. * The caller should not free it. * \todo FIXME: assumes working with at-least-3d data. */ #if 1 static nd_t aafilt(nd_t vol, filter_workspace *ws) { unsigned i=0,j,ndim=ndndim(vol); TIME(TRY(filter_workspace__gpu_resize(ws,vol))); DUMP("aafilt-vol.%.tif",vol); TIME(TRY(ndcopy(ws->gpu[0],vol,0,0))); DUMP("aafilt-src.%.tif",ws->gpu[0]); for(i=0,j=0;i<3;++i) if(ws->enable[i]) { TIME(TRY(ndconv1(ws->gpu[~j&1],ws->gpu[j&1],ws->filters[j],j,&ws->params))); ++j; } ws->i=j&1; // this will be the index of the last destination buffer DUMP("aafilt-dst.%.tif",ws->gpu[ws->i]); return ws->gpu[ws->i]; Error: for(i=0;i<countof(ws->gpu);++i) if(nderror(ws->gpu[i])) LOG("\t[nd Error]:"ENDL "\t%s"ENDL,nderror(ws->gpu[i])); return 0; } #else // skip aafilt nd_t aafilt(nd_t vol, float *transform, filter_workspace *ws) { TIME(TRY(filter_workspace__gpu_resize(ws,vol))); TIME(TRY(ndcopy(ws->gpu[0],vol,0,0))); ws->i=0; return ws->gpu[0]; Error: LOG("\t[nd Error]:"ENDL "\t%s"ENDL,nderror(ws->gpu[0])); return 0; } #endif static nd_t xform(nd_t dst, nd_t src, float *transform, affine_workspace *ws) { TRY(affine_workspace__gpu_resize(ws,dst)); TRY(ndref(ws->host_xform,transform,nd_heap)); TRY(ndcopy(ws->gpu_xform,ws->host_xform,0,0)); DUMP("xform-src.%.tif",src); TRY(ndaffine(dst,src,nddata(ws->gpu_xform),&ws->params)); DUMP("xform-dst.%.tif",dst); return dst; Error: if(dst) LOG("\t[nd Error]:"ENDL "\t%s"ENDL,nderror(dst)); return 0; } static int any_tiles_in_box(tile_t *tiles, size_t ntiles, aabb_t bbox) { size_t i; for(i=0;i<ntiles;++i) if(AABBHit(bbox,TileAABB(tiles[i]))) return 1; return 0; } static unsigned crop(nd_t vol,nd_t crop) { if(ndndim(vol)!=ndndim(crop)) return 0; memcpy(ndshape(vol),ndshape(crop),ndndim(vol)*sizeof(size_t)); return 1; } /** * Does not assume all tiles have the same size. (fixed: ngc) */ static nd_t render_leaf(desc_t *desc, aabb_t bbox, address_t path) { nd_t out=0,in=0,t=0; size_t i; tile_t *tiles; subdiv_t subdiv=0; TRY(tiles=TileBaseArray(desc->tiles)); for(i=0;i<TileBaseCount(desc->tiles);++i) { // Maybe initialize if(!AABBHit(bbox,TileAABB(tiles[i]))) continue; // Select hit tiles PROGRESS("."); // Wait to init until a hit is confirmed. if(!in) // Alloc on first iteration: in, transform { unsigned n; in=ndheap(TileShape(tiles[i])); n=ndndim(in); if(!desc->transform) NEW(float,desc->transform,(n+1)*(n+1)); // FIXME: pretty sure this is a memory leak. transform get's init'd for each leaf without being freed TRY(set_ref_shape(desc,in)); affine_workspace__set_boundary_value(&desc->aws,in); } if(!same_shape(in,TileShape(tiles[i]))) // maybe resize "in" { nd_t s=TileShape(tiles[i]); if(ndnbytes(in)<ndnbytes(s)) TRY(ndref(in,realloc(nddata(in),ndnbytes(s)),nd_heap)); TRY(ndcast(ndreshape(in,ndndim(s),ndshape(s)),ndtype(s))); } if(!out) { TRY(out=alloc_vol(desc,bbox,desc->x_nm,desc->y_nm,desc->z_nm)); // Alloc on first iteration: out, must come after set_ref_shape TIME(TRY(filter_workspace__gpu_resize(&desc->output_fws,out))); } // The main idea TIME(TRY(ndioRead(TileFile(tiles[i]),in))); DUMP("tile.%.tif",in); TRY(crop(ndPushShape(in),TileCrop(tiles[i]))); DUMP("crop.%.tif",in); #if HAVE_CUDA if(desc->total==0) TRY(cudaSuccess==cudaMemGetInfo(&desc->free,&desc->total)); #endif TRY(subdiv=make_subdiv(in,TileTransform(tiles[i]),ndndim(in),desc->free,desc->total)); do { TIME(compose(desc->transform,bbox,desc->x_nm,desc->y_nm,desc->z_nm,subdiv_xform(subdiv),ndndim(in))); TRY(compute_aa_filters(&desc->input_fws,desc->transform,ndndim(in))); TIME(TRY(t=aafilt(subdiv_vol(subdiv),&desc->input_fws))); // t is on the gpu TIME(TRY(xform(out,t,desc->transform,&desc->aws))); } while(next_subdivision(subdiv)); free_subdiv(subdiv); TRY(in=ndPopShape(in)); subdiv=0; } // end loop over tiles /* Antialiasing on the output. */ if(out) TRY(out=aafilt(out,&desc->output_fws)); Finalize: PROGRESS(ENDL); ndfree(in); return out; Error: free_subdiv(subdiv); subdiv=0; release_vol(desc,out); out=0; goto Finalize; } static nd_t render_child_to_parent(desc_t *desc,aabb_t bbox, address_t path, nd_t child, aabb_t cbox, nd_t workspace) { nd_t t,out=workspace; // maybe allocate output if(!out) { int64_t *cshape_nm; unsigned n=(unsigned) desc->nchildren; const float s[]={ (n>>=1)?2.0f:1.0f, (n>>=1)?2.0f:1.0f, (n>>=1)?2.0f:1.0f }; AABBGet(cbox,0,0,&cshape_nm); TRY(out=alloc_vol(desc,bbox, s[0]*cshape_nm[0]/ndshape(child)[0], s[1]*cshape_nm[1]/ndshape(child)[1], s[2]*cshape_nm[2]/ndshape(child)[2])); } // paste child into output box2box(desc->transform,out,bbox,child,cbox); TRY(compute_aa_filters(&desc->input_fws,desc->transform,ndndim(child))); TRY(t=aafilt(child,&desc->input_fws)); TRY(xform(out,t,desc->transform,&desc->aws)); return out; Error: return 0; } /** * \returns 0 on failure, otherwise an nd_t array with the rendered subvolume. * The caller is responsible for releaseing the result with * release_vol(). */ static nd_t render_node(desc_t *desc, aabb_t bbox, address_t path) { unsigned i; nd_t out=0; aabb_t *cboxes=0; ALLOCA(aabb_t,cboxes,desc->nchildren); ZERO( aabb_t,cboxes,desc->nchildren); TRY(AABBBinarySubdivision(cboxes,(unsigned)desc->nchildren,bbox)); for(i=0;i<desc->nchildren;++i) { nd_t c=0; TRY(address_push(path,i)); c=desc->make(desc,cboxes[i],path); TRY(address_pop(path)); if(!c) continue; out=render_child_to_parent(desc,bbox,path,c,cboxes[i],out); release_vol(desc,c); AABBFree(cboxes[i]); } return out; Error: if(out) release_vol(desc,out); return 0; } /// Renders a volume that fills \a bbox fro \a tiles static nd_t render_child(desc_t *desc, aabb_t bbox, address_t path) { nd_t out=0; DBG("--- Address: %-20u ---"ENDL, (unsigned)address_to_int(path,10)); if(isleaf(desc,bbox)) out=render_leaf(desc,bbox,path); else out=render_node(desc,bbox,path); if(out) TRY(desc->yield(out,path,bbox,desc->args)); return out; Error: return 0; } // // JUST THE ADDRESS SEQUENCE // yielded in oreder of dependency, leaves (no dependencies) first. // static nd_t addr_seq__child(desc_t *desc, aabb_t bbox, address_t path) { if(!isleaf(desc,bbox)) render_node(desc,bbox,path); if(any_tiles_in_box(TileBaseArray(desc->tiles),TileBaseCount(desc->tiles),bbox)) // cull empty nodes desc->yield(0,path,bbox,desc->args); return 0; } static nd_t addr_seq__compose_child(desc_t *desc,aabb_t bbox, address_t path, nd_t child, aabb_t cbox, nd_t workspace) { return 0;} static void setup_print_addresses(desc_t *desc) { desc->make=addr_seq__child; } // // RENDER JUST THE TARGET ADDRESS // target address static address_t target__addr=0; static loader_t target__load_func=0; static nd_t target__load(desc_t *desc, aabb_t bbox, address_t path) { unsigned n; nd_t out=target__load_func?target__load_func(path):0; if(out) { n=ndndim(out); NEW(float,desc->transform,(n+1)*(n+1)); // FIXME: pretty sure this is a memory leak. transform get's init'd for each leaf without being freed TRY(set_ref_shape(desc,out)); affine_workspace__set_boundary_value(&desc->aws,out); } return out; Error: return 0; } static nd_t target__get_child(desc_t *desc, aabb_t bbox, address_t path) { nd_t out=0; if(address_eq(path,target__addr)) { if(isleaf(desc,bbox)) out=render_leaf(desc,bbox,path); else { desc->make=target__load; out=render_node(desc,bbox,path); desc->make=target__get_child; } if(out) TRY(desc->yield(out,path,bbox,desc->args)); } else { if(!isleaf(desc,bbox)) render_node(desc,bbox,path); } return out; Error: return 0; } static void target__setup(desc_t *desc, address_t target, loader_t loader) { target__addr=target; target__load_func=loader; desc->make=target__get_child; } // === INTERFACE === /** Select a subvolume from the total data set using fractional coordinates. */ aabb_t AdjustTilesBoundingBox(tiles_t tiles, double o[3], double s[3]) { aabb_t bbox; int64_t *ori,*shape; int i; TRY(bbox=TileBaseAABB(tiles)); AABBGet(bbox,0,&ori,&shape); for(i=0;i<3;++i) ori[i] =ori[i]+o[i]*shape[i]; for(i=0;i<3;++i) shape[i]= s[i]*shape[i]; return bbox; Error: return 0; } /** * \param[in] opts Point to a `struct render` holding options that control the render. * \param[in] tiles Source tile database. * \param[in] yield Callback that handles nodes in the tree when they * are done being rendered. * \param[in] args Additional arguments to be passed to yeild. */ unsigned render(const struct render *opts, tiles_t tiles, handler_t yield, void* args) { unsigned ok=1; desc_t desc=make_desc(opts,tiles,yield,args); aabb_t bbox=0; address_t path=0; TRY(bbox=AdjustTilesBoundingBox(tiles,opts->ori,opts->size)); TRY(preallocate(&desc,bbox)); TRY(path=make_address()); desc.make(&desc,bbox,path); Finalize: cleanup_desc(&desc); AABBFree(bbox); free_address(path); return ok; Error: ok=0; goto Finalize; } /** * \param[in] opts Point to a `struct render` holding options that control the render. * \param[in] tiles Source tile database. * \param[in] yield Callback that handles nodes in the tree when they * are ready. * \param[in] args Additional arguments to be passed to yeild. */ unsigned addresses(const struct render *opts, tiles_t tiles, handler_t yield, void* args) { unsigned ok=1; desc_t desc=make_desc(opts,tiles,yield,args); aabb_t bbox=0; address_t path=0; TRY(bbox=AdjustTilesBoundingBox(tiles,opts->ori,opts->size)); //TRY(preallocate(&desc,bbox)); TRY(path=make_address()); setup_print_addresses(&desc); desc.make(&desc,bbox,path); Finalize: cleanup_desc(&desc); AABBFree(bbox); free_address(path); return ok; Error: ok=0; goto Finalize; } /** * \param[in] opts Point to a `struct render` holding options that control the render. * \param[in] tiles Source tile database. * \param[in] yield Callback that handles nodes in the tree when they * are ready. * \param[in] yield_args Additional arguments to be passed to yeild. * \param[in] loader Function that loads the data at the node specified by an address. * \param[in] target The address of the tree to target. */ unsigned render_target(const struct render *opts, tiles_t tiles, handler_t yield, void *yield_args, loader_t loader, address_t target) { unsigned ok=1; desc_t desc=make_desc(opts,tiles,yield,yield_args); aabb_t bbox=0; address_t path=0; TRY(bbox=AdjustTilesBoundingBox(tiles,opts->ori,opts->size)); TRY(preallocate_for_render_one_target(&desc,bbox)); TRY(path=make_address()); target__setup(&desc,target,loader); desc.make(&desc,bbox,path); Finalize: cleanup_desc(&desc); AABBFree(bbox); free_address(path); return ok; Error: ok=0; goto Finalize; }
2.078125
2
2024-11-18T20:59:45.455856+00:00
2019-01-31T17:57:46
30ef3ffe129223d496e4263f30c910cde1101dac
{ "blob_id": "30ef3ffe129223d496e4263f30c910cde1101dac", "branch_name": "refs/heads/master", "committer_date": "2019-01-31T17:57:46", "content_id": "cc070ef79f890b6751dfd04870a7fb65e471d7b7", "detected_licenses": [ "MIT" ], "directory_id": "1b17491f3036a69c32a0e9981c4093f130ac0502", "extension": "c", "filename": "cube-tex.c", "fork_events_count": 1, "gha_created_at": "2017-11-21T00:58:59", "gha_event_created_at": "2019-01-31T17:57:47", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 111480310, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 17581, "license": "MIT", "license_type": "permissive", "path": "/cube-tex.c", "provenance": "stackv2-0135.json.gz:248794", "repo_name": "cubanismo/kmscube", "revision_date": "2019-01-31T17:57:46", "revision_id": "019090d9ae8dc21d89ffaf35003316a53c319478", "snapshot_id": "95ec940da726a52f255804b594defc0f42626597", "src_encoding": "UTF-8", "star_events_count": 9, "url": "https://raw.githubusercontent.com/cubanismo/kmscube/019090d9ae8dc21d89ffaf35003316a53c319478/cube-tex.c", "visit_date": "2021-03-27T10:44:04.585706" }
stackv2
/* * Copyright (c) 2017 Rob Clark <[email protected]> * * 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, sub license, * 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 (including the * next paragraph) 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 NON-INFRINGEMENT. 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 <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "common.h" #include "esUtil.h" struct { struct egl egl; GLfloat aspect; enum mode mode; const struct gbm *gbm; GLuint program; /* uniform handles: */ GLint modelviewmatrix, modelviewprojectionmatrix, normalmatrix; GLint texture, textureuv; GLuint vbo; GLuint positionsoffset, texcoordsoffset, normalsoffset; GLuint tex[2]; } gl; const struct egl *egl = &gl.egl; static const GLfloat vVertices[] = { // front -1.0f, -1.0f, +1.0f, +1.0f, -1.0f, +1.0f, -1.0f, +1.0f, +1.0f, +1.0f, +1.0f, +1.0f, // back +1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, +1.0f, +1.0f, -1.0f, -1.0f, +1.0f, -1.0f, // right +1.0f, -1.0f, +1.0f, +1.0f, -1.0f, -1.0f, +1.0f, +1.0f, +1.0f, +1.0f, +1.0f, -1.0f, // left -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, +1.0f, -1.0f, +1.0f, -1.0f, -1.0f, +1.0f, +1.0f, // top -1.0f, +1.0f, +1.0f, +1.0f, +1.0f, +1.0f, -1.0f, +1.0f, -1.0f, +1.0f, +1.0f, -1.0f, // bottom -1.0f, -1.0f, -1.0f, +1.0f, -1.0f, -1.0f, -1.0f, -1.0f, +1.0f, +1.0f, -1.0f, +1.0f, }; GLfloat vTexCoords[] = { //front 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, //back 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, //right 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, //left 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, //top 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, //bottom 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, }; static const GLfloat vNormals[] = { // front +0.0f, +0.0f, +1.0f, // forward +0.0f, +0.0f, +1.0f, // forward +0.0f, +0.0f, +1.0f, // forward +0.0f, +0.0f, +1.0f, // forward // back +0.0f, +0.0f, -1.0f, // backward +0.0f, +0.0f, -1.0f, // backward +0.0f, +0.0f, -1.0f, // backward +0.0f, +0.0f, -1.0f, // backward // right +1.0f, +0.0f, +0.0f, // right +1.0f, +0.0f, +0.0f, // right +1.0f, +0.0f, +0.0f, // right +1.0f, +0.0f, +0.0f, // right // left -1.0f, +0.0f, +0.0f, // left -1.0f, +0.0f, +0.0f, // left -1.0f, +0.0f, +0.0f, // left -1.0f, +0.0f, +0.0f, // left // top +0.0f, +1.0f, +0.0f, // up +0.0f, +1.0f, +0.0f, // up +0.0f, +1.0f, +0.0f, // up +0.0f, +1.0f, +0.0f, // up // bottom +0.0f, -1.0f, +0.0f, // down +0.0f, -1.0f, +0.0f, // down +0.0f, -1.0f, +0.0f, // down +0.0f, -1.0f, +0.0f // down }; static const char *vertex_shader_source = "uniform mat4 modelviewMatrix; \n" "uniform mat4 modelviewprojectionMatrix;\n" "uniform mat3 normalMatrix; \n" " \n" "attribute vec4 in_position; \n" "attribute vec3 in_normal; \n" "attribute vec2 in_TexCoord; \n" " \n" "vec4 lightSource = vec4(2.0, 2.0, 20.0, 0.0);\n" " \n" "varying vec4 vVaryingColor; \n" "varying vec2 vTexCoord; \n" " \n" "void main() \n" "{ \n" " gl_Position = modelviewprojectionMatrix * in_position;\n" " vec3 vEyeNormal = normalMatrix * in_normal;\n" " vec4 vPosition4 = modelviewMatrix * in_position;\n" " vec3 vPosition3 = vPosition4.xyz / vPosition4.w;\n" " vec3 vLightDir = normalize(lightSource.xyz - vPosition3);\n" " float diff = max(0.0, dot(vEyeNormal, vLightDir));\n" " vVaryingColor = vec4(diff * vec3(1.0, 1.0, 1.0), 1.0);\n" " vTexCoord = in_TexCoord; \n" "} \n"; static const char *fragment_shader_source_1img = "#extension GL_OES_EGL_image_external : enable\n" "precision mediump float; \n" " \n" "uniform samplerExternalOES uTex; \n" " \n" "varying vec4 vVaryingColor; \n" "varying vec2 vTexCoord; \n" " \n" "void main() \n" "{ \n" " gl_FragColor = vVaryingColor * texture2D(uTex, vTexCoord);\n" "} \n"; static const char *fragment_shader_source_2img = "#extension GL_OES_EGL_image_external : enable \n" "precision mediump float; \n" " \n" "uniform samplerExternalOES uTexY; \n" "uniform samplerExternalOES uTexUV; \n" " \n" "varying vec4 vVaryingColor; \n" "varying vec2 vTexCoord; \n" " \n" "mat4 csc = mat4(1.0, 0.0, 1.402, -0.701, \n" " 1.0, -0.344, -0.714, 0.529, \n" " 1.0, 1.772, 0.0, -0.886, \n" " 0.0, 0.0, 0.0, 0.0); \n" " \n" "void main() \n" "{ \n" " vec4 yuv; \n" " yuv.x = texture2D(uTexY, vTexCoord).x; \n" " yuv.yz = texture2D(uTexUV, vTexCoord).xy; \n" " yuv.w = 1.0; \n" " gl_FragColor = vVaryingColor * (yuv * csc);\n" "} \n"; static const uint32_t texw = 512, texh = 512; static int get_fd_rgba(uint32_t *pstride) { struct gbm_bo *bo; void *map_data = NULL; uint32_t stride; extern const uint32_t raw_512x512_rgba[]; uint8_t *map, *src = (uint8_t *)raw_512x512_rgba; int fd; /* NOTE: do not actually use GBM_BO_USE_WRITE since that gets us a dumb buffer: */ bo = gbm_bo_create(gl.gbm->dev, texw, texh, GBM_FORMAT_ABGR8888, GBM_BO_USE_LINEAR); map = gbm_bo_map(bo, 0, 0, texw, texh, GBM_BO_TRANSFER_WRITE, &stride, &map_data); for (uint32_t i = 0; i < texh; i++) { memcpy(&map[stride * i], &src[texw * 4 * i], texw * 4); } gbm_bo_unmap(bo, map_data); fd = gbm_bo_get_fd(bo); /* we have the fd now, no longer need the bo: */ gbm_bo_destroy(bo); *pstride = stride; return fd; } static int get_fd_y(uint32_t *pstride) { struct gbm_bo *bo; void *map_data = NULL; uint32_t stride; extern const uint32_t raw_512x512_nv12[]; uint8_t *map, *src = (uint8_t *)raw_512x512_nv12; int fd; /* NOTE: do not actually use GBM_BO_USE_WRITE since that gets us a dumb buffer: */ bo = gbm_bo_create(gl.gbm->dev, texw, texh, GBM_FORMAT_R8, GBM_BO_USE_LINEAR); map = gbm_bo_map(bo, 0, 0, texw, texh, GBM_BO_TRANSFER_WRITE, &stride, &map_data); for (uint32_t i = 0; i < texh; i++) { memcpy(&map[stride * i], &src[texw * i], texw); } gbm_bo_unmap(bo, map_data); fd = gbm_bo_get_fd(bo); /* we have the fd now, no longer need the bo: */ gbm_bo_destroy(bo); *pstride = stride; return fd; } static int get_fd_uv(uint32_t *pstride) { struct gbm_bo *bo; void *map_data = NULL; uint32_t stride; extern const uint32_t raw_512x512_nv12[]; uint8_t *map, *src = &((uint8_t *)raw_512x512_nv12)[texw * texh]; int fd; /* NOTE: do not actually use GBM_BO_USE_WRITE since that gets us a dumb buffer: */ bo = gbm_bo_create(gl.gbm->dev, texw/2, texh/2, GBM_FORMAT_GR88, GBM_BO_USE_LINEAR); map = gbm_bo_map(bo, 0, 0, texw/2, texh/2, GBM_BO_TRANSFER_WRITE, &stride, &map_data); for (uint32_t i = 0; i < texh/2; i++) { memcpy(&map[stride * i], &src[texw * i], texw); } gbm_bo_unmap(bo, map_data); fd = gbm_bo_get_fd(bo); /* we have the fd now, no longer need the bo: */ gbm_bo_destroy(bo); *pstride = stride; return fd; } static int init_tex_rgba(void) { uint32_t stride; int fd = get_fd_rgba(&stride); const EGLint attr[] = { EGL_WIDTH, texw, EGL_HEIGHT, texh, EGL_LINUX_DRM_FOURCC_EXT, DRM_FORMAT_ABGR8888, EGL_DMA_BUF_PLANE0_FD_EXT, fd, EGL_DMA_BUF_PLANE0_OFFSET_EXT, 0, EGL_DMA_BUF_PLANE0_PITCH_EXT, stride, EGL_NONE }; EGLImage img; glGenTextures(1, gl.tex); img = egl->eglCreateImageKHR(egl->display, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, NULL, attr); assert(img); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_EXTERNAL_OES, gl.tex[0]); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); egl->glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, img); egl->eglDestroyImageKHR(egl->display, img); return 0; } static int init_tex_nv12_2img(void) { uint32_t stride_y, stride_uv; int fd_y = get_fd_y(&stride_y); int fd_uv = get_fd_uv(&stride_uv); const EGLint attr_y[] = { EGL_WIDTH, texw, EGL_HEIGHT, texh, EGL_LINUX_DRM_FOURCC_EXT, DRM_FORMAT_R8, EGL_DMA_BUF_PLANE0_FD_EXT, fd_y, EGL_DMA_BUF_PLANE0_OFFSET_EXT, 0, EGL_DMA_BUF_PLANE0_PITCH_EXT, stride_y, EGL_NONE }; const EGLint attr_uv[] = { EGL_WIDTH, texw/2, EGL_HEIGHT, texh/2, EGL_LINUX_DRM_FOURCC_EXT, DRM_FORMAT_GR88, EGL_DMA_BUF_PLANE0_FD_EXT, fd_uv, EGL_DMA_BUF_PLANE0_OFFSET_EXT, 0, EGL_DMA_BUF_PLANE0_PITCH_EXT, stride_uv, EGL_NONE }; EGLImage img_y, img_uv; glGenTextures(2, gl.tex); /* Y plane texture: */ img_y = egl->eglCreateImageKHR(egl->display, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, NULL, attr_y); assert(img_y); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_EXTERNAL_OES, gl.tex[0]); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); egl->glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, img_y); egl->eglDestroyImageKHR(egl->display, img_y); /* UV plane texture: */ img_uv = egl->eglCreateImageKHR(egl->display, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, NULL, attr_uv); assert(img_uv); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_EXTERNAL_OES, gl.tex[1]); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); egl->glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, img_uv); egl->eglDestroyImageKHR(egl->display, img_uv); return 0; } static int init_tex_nv12_1img(void) { uint32_t stride_y, stride_uv; int fd_y = get_fd_y(&stride_y); int fd_uv = get_fd_uv(&stride_uv); const EGLint attr[] = { EGL_WIDTH, texw, EGL_HEIGHT, texh, EGL_LINUX_DRM_FOURCC_EXT, DRM_FORMAT_NV12, EGL_DMA_BUF_PLANE0_FD_EXT, fd_y, EGL_DMA_BUF_PLANE0_OFFSET_EXT, 0, EGL_DMA_BUF_PLANE0_PITCH_EXT, stride_y, EGL_DMA_BUF_PLANE1_FD_EXT, fd_uv, EGL_DMA_BUF_PLANE1_OFFSET_EXT, 0, EGL_DMA_BUF_PLANE1_PITCH_EXT, stride_uv, EGL_NONE }; EGLImage img; glGenTextures(1, gl.tex); img = egl->eglCreateImageKHR(egl->display, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, NULL, attr); assert(img); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_EXTERNAL_OES, gl.tex[0]); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); egl->glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, img); egl->eglDestroyImageKHR(egl->display, img); return 0; } static int init_tex(enum mode mode) { switch (mode) { case RGBA: return init_tex_rgba(); case NV12_2IMG: return init_tex_nv12_2img(); case NV12_1IMG: return init_tex_nv12_1img(); case SMOOTH: case VIDEO: assert(!"unreachable"); return -1; } return -1; } static void draw_cube_tex(unsigned i) { ESMatrix modelview; /* clear the color buffer */ glClearColor(0.5, 0.5, 0.5, 1.0); glClear(GL_COLOR_BUFFER_BIT); esMatrixLoadIdentity(&modelview); esTranslate(&modelview, 0.0f, 0.0f, -8.0f); esRotate(&modelview, 45.0f + (0.25f * i), 1.0f, 0.0f, 0.0f); esRotate(&modelview, 45.0f - (0.5f * i), 0.0f, 1.0f, 0.0f); esRotate(&modelview, 10.0f + (0.15f * i), 0.0f, 0.0f, 1.0f); ESMatrix projection; esMatrixLoadIdentity(&projection); esFrustum(&projection, -2.8f, +2.8f, -2.8f * gl.aspect, +2.8f * gl.aspect, 6.0f, 10.0f); ESMatrix modelviewprojection; esMatrixLoadIdentity(&modelviewprojection); esMatrixMultiply(&modelviewprojection, &modelview, &projection); float normal[9]; normal[0] = modelview.m[0][0]; normal[1] = modelview.m[0][1]; normal[2] = modelview.m[0][2]; normal[3] = modelview.m[1][0]; normal[4] = modelview.m[1][1]; normal[5] = modelview.m[1][2]; normal[6] = modelview.m[2][0]; normal[7] = modelview.m[2][1]; normal[8] = modelview.m[2][2]; glUniformMatrix4fv(gl.modelviewmatrix, 1, GL_FALSE, &modelview.m[0][0]); glUniformMatrix4fv(gl.modelviewprojectionmatrix, 1, GL_FALSE, &modelviewprojection.m[0][0]); glUniformMatrix3fv(gl.normalmatrix, 1, GL_FALSE, normal); glUniform1i(gl.texture, 0); /* '0' refers to texture unit 0. */ if (gl.mode == NV12_2IMG) glUniform1i(gl.textureuv, 1); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDrawArrays(GL_TRIANGLE_STRIP, 4, 4); glDrawArrays(GL_TRIANGLE_STRIP, 8, 4); glDrawArrays(GL_TRIANGLE_STRIP, 12, 4); glDrawArrays(GL_TRIANGLE_STRIP, 16, 4); glDrawArrays(GL_TRIANGLE_STRIP, 20, 4); } const struct egl * init_cube_tex(const struct surfmgr *surfmgr, enum mode mode) { const char *fragment_shader_source = (mode == NV12_2IMG) ? fragment_shader_source_2img : fragment_shader_source_1img; int ret; if (!surfmgr->gbm) { printf("texture support currently requires GBM\n"); return NULL; } ret = init_egl(&gl.egl, surfmgr); if (ret) return NULL; if (egl_check(&gl.egl, eglCreateImageKHR) || egl_check(&gl.egl, glEGLImageTargetTexture2DOES) || egl_check(&gl.egl, eglDestroyImageKHR)) return NULL; gl.aspect = (GLfloat)(surfmgr->height) / (GLfloat)(surfmgr->width); gl.mode = mode; gl.gbm = surfmgr->gbm; ret = create_program(vertex_shader_source, fragment_shader_source); if (ret < 0) return NULL; gl.program = ret; glBindAttribLocation(gl.program, 0, "in_position"); glBindAttribLocation(gl.program, 1, "in_normal"); glBindAttribLocation(gl.program, 2, "in_color"); ret = link_program(gl.program); if (ret) return NULL; glUseProgram(gl.program); gl.modelviewmatrix = glGetUniformLocation(gl.program, "modelviewMatrix"); gl.modelviewprojectionmatrix = glGetUniformLocation(gl.program, "modelviewprojectionMatrix"); gl.normalmatrix = glGetUniformLocation(gl.program, "normalMatrix"); if (mode == NV12_2IMG) { gl.texture = glGetUniformLocation(gl.program, "uTexY"); gl.textureuv = glGetUniformLocation(gl.program, "uTexUV"); } else { gl.texture = glGetUniformLocation(gl.program, "uTex"); } glViewport(0, 0, surfmgr->width, surfmgr->height); glEnable(GL_CULL_FACE); gl.positionsoffset = 0; gl.texcoordsoffset = sizeof(vVertices); gl.normalsoffset = sizeof(vVertices) + sizeof(vTexCoords); glGenBuffers(1, &gl.vbo); glBindBuffer(GL_ARRAY_BUFFER, gl.vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(vVertices) + sizeof(vTexCoords) + sizeof(vNormals), 0, GL_STATIC_DRAW); glBufferSubData(GL_ARRAY_BUFFER, gl.positionsoffset, sizeof(vVertices), &vVertices[0]); glBufferSubData(GL_ARRAY_BUFFER, gl.texcoordsoffset, sizeof(vTexCoords), &vTexCoords[0]); glBufferSubData(GL_ARRAY_BUFFER, gl.normalsoffset, sizeof(vNormals), &vNormals[0]); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid *)(intptr_t)gl.positionsoffset); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid *)(intptr_t)gl.normalsoffset); glEnableVertexAttribArray(1); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, (const GLvoid *)(intptr_t)gl.texcoordsoffset); glEnableVertexAttribArray(2); ret = init_tex(mode); if (ret) { printf("failed to initialize EGLImage texture\n"); return NULL; } gl.egl.draw = draw_cube_tex; return &gl.egl; }
2.078125
2
2024-11-18T20:59:45.547700+00:00
2023-07-10T16:48:02
b23e98af456cac2fc2d31d9ab8261bc182ddcc89
{ "blob_id": "b23e98af456cac2fc2d31d9ab8261bc182ddcc89", "branch_name": "refs/heads/main", "committer_date": "2023-07-11T09:27:01", "content_id": "9f03ed214ba3b2ae4b5cfccb2f50427ddc55f717", "detected_licenses": [ "MIT" ], "directory_id": "c715dfc7c1c244b5ba75a18b8cac2bac32dd9c25", "extension": "c", "filename": "gp_mgmt.c", "fork_events_count": 22, "gha_created_at": "2020-04-09T18:14:56", "gha_event_created_at": "2023-09-07T14:38:13", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 254445967, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8399, "license": "MIT", "license_type": "permissive", "path": "/src/gp_mgmt.c", "provenance": "stackv2-0135.json.gz:248926", "repo_name": "gssapi/gssproxy", "revision_date": "2023-07-10T16:48:02", "revision_id": "ec463454c1f6e89bf8a1671bf0ef00fef2491f86", "snapshot_id": "48275d5e85bec2030c73cda7741e81785c2cae37", "src_encoding": "UTF-8", "star_events_count": 34, "url": "https://raw.githubusercontent.com/gssapi/gssproxy/ec463454c1f6e89bf8a1671bf0ef00fef2491f86/src/gp_mgmt.c", "visit_date": "2023-07-25T04:13:53.680992" }
stackv2
/* Copyright (C) 2022 the GSS-PROXY contributors, see COPYING for license */ #define _GNU_SOURCE #include "config.h" #include <errno.h> #include <fcntl.h> #include <pthread.h> #include <stdio.h> #include <string.h> #include <sys/epoll.h> #include <sys/stat.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include "gp_proxy.h" static void idle_terminate(verto_ctx *vctx, verto_ev *ev) { struct gssproxy_ctx *gpctx = verto_get_private(ev); GPDEBUG("Terminating, after idling for %ld seconds!\n", (long)gpctx->term_timeout/1000); verto_break(vctx); } void idle_handler(struct gssproxy_ctx *gpctx) { /* we've been called, this means some event just fired, * restart the timeout handler */ if (gpctx->userproxymode == false || gpctx->term_timeout == 0) { /* self termination is disabled */ return; } verto_del(gpctx->term_ev); /* Add self-termination timeout */ gpctx->term_ev = verto_add_timeout(gpctx->vctx, VERTO_EV_FLAG_NONE, idle_terminate, gpctx->term_timeout); if (!gpctx->term_ev) { GPDEBUG("Failed to register timeout event!\n"); } verto_set_private(gpctx->term_ev, gpctx, NULL); } void gp_activity_accounting(struct gssproxy_ctx *gpctx, ssize_t rb, ssize_t wb) { time_t now = time(NULL); if (rb) { /* Gssproxy received some request */ gpctx->readstats += rb; GPDEBUGN(GP_INFO_DEBUG_LVL, "Total received bytes: %ld\n", (long)gpctx->readstats); /* receiving bytes is also a sign of activity, * reset idle event */ idle_handler(gpctx); GPDEBUGN(GP_INFO_DEBUG_LVL, "Idle for: %ld seconds\n", now - gpctx->last_activity); gpctx->last_activity = now; } if (wb) { gpctx->writestats += wb; GPDEBUGN(GP_INFO_DEBUG_LVL, "Total sent bytes: %ld\n", (long)gpctx->writestats); /* sending bytes is also a sign of activity, but we send * bytes only in response to requests and this is already * captured by a previous read event, just update the * last_activity counter to have a more precise info messgae * on the following read */ gpctx->last_activity = now; } } #define MAX_K5_EVENTS 10 static struct k5tracer { pthread_t tid; int fd; } *k5tracer = NULL; static void *k5tracer_thread(void *pvt UNUSED) { struct epoll_event ev, events[MAX_K5_EVENTS]; int num, epollfd; pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL); fprintf(stderr, "k5tracer_thread started!\n"); fflush(stderr); epollfd = epoll_create1(EPOLL_CLOEXEC); if (epollfd == -1) { fprintf(stderr, "k5tracer_thread, epoll_create1 failed\n"); fflush(stderr); pthread_exit(NULL); } ev.events = EPOLLIN; ev.data.fd = k5tracer->fd; if (epoll_ctl(epollfd, EPOLL_CTL_ADD, k5tracer->fd, &ev) == -1) { fprintf(stderr, "k5tracer_thread, epoll_ctl failed\n"); fflush(stderr); pthread_exit(NULL); } for (;;) { num = epoll_wait(epollfd, events, MAX_K5_EVENTS, -1); if (num == -1) { fprintf(stderr, "k5tracer_thread, epoll_wait failed (%d)\n", errno); fflush(stderr); pthread_exit(NULL); } for (int i = 0; i < num; i++) { if (events[i].events & EPOLLIN) { char buf[512]; size_t pos = 0; ssize_t rn; size_t wn; for (;;) { rn = read(events[i].data.fd, buf, 512); if (rn == -1) { if (errno != EAGAIN && errno != EINTR ) { fprintf(stderr, "k5tracer_thread, " "fatal error on fd %d %d\n", events[i].data.fd, errno); break; } rn = 0; } if (rn == 0) { /* done, getting input */ break; } /* let's hope all gets written, but if not we just * missed some debugging output and thatis ok, in * the very unlikely case it happens */ while (rn > 0) { wn = fwrite(buf + pos, 1, rn, stderr); if (wn == 0) break; rn -= wn; pos += rn; } } } } fflush(stderr); } } void free_k5tracer(void) { if (k5tracer == NULL) return; if (k5tracer->fd > 0) { close(k5tracer->fd); } safefree(k5tracer); } char *tracing_file_name = NULL; /* if action == 1 activate KRB5 tracing bridge. * if action == 0 deactivate it */ void gp_krb5_tracing_setup(int action) { pthread_attr_t attr; int ret; if (action != 0 && action != 1) { GPDEBUGN(3, "%s: Unknown action %d\n", __func__, action); return; } if (action == 0) { if (k5tracer) { pthread_cancel(k5tracer->tid); pthread_join(k5tracer->tid, NULL); unsetenv("KRB5_TRACE"); } return; } /* activate only once */ if (k5tracer != NULL) return; k5tracer = calloc(1, sizeof(struct k5tracer)); if (k5tracer == NULL) { ret = ENOMEM; goto done; } /* this name is predictable, but we always unlink it before * creating a new one with permission only for the current * user. A race between unilnk and mkfifo will cause failure * and we'll never open the file that raced us */ if (tracing_file_name == NULL) { ret = asprintf(&tracing_file_name, "/tmp/krb5.tracing.%ld", (long)getpid()); if (ret == -1) { ret = errno; goto done; } } ret = unlink(tracing_file_name); if (ret == -1 && errno != ENOENT) { ret = errno; GPDEBUGN(3, "%s: unlink(%s) failed\n", __func__, tracing_file_name); goto done; } ret = mkfifo(tracing_file_name, 0600); if (ret == -1) { ret = errno; GPDEBUGN(3, "%s: mkfifo(%s) failed\n", __func__, tracing_file_name); goto done; } k5tracer->fd = open(tracing_file_name, O_RDONLY | O_CLOEXEC | O_NONBLOCK); if (k5tracer->fd == -1) { ret = errno; GPDEBUGN(3, "%s: open(%s) failed\n", __func__, tracing_file_name); goto done; } else if (k5tracer->fd <= 2) { /* we do not expect stdio to be closed because we need to use it * to forward the tracing, if the fd return is smaller than stderr * consider stdio messed up and just ignore tracing */ ret = EINVAL; GPDEBUGN(3, "%s: open(%s) returned fd too low: %d", __func__, tracing_file_name, k5tracer->fd); close(k5tracer->fd); k5tracer->fd = 0; goto done; } ret = pthread_attr_init(&attr); if (ret) { GPDEBUGN(3, "%s: pthread_attr_init failed: %d", __func__, ret); goto done; } ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); if (ret) { GPDEBUGN(3, "%s: pthread_attr_setdetachstate: %d", __func__, ret); } ret = pthread_create(&k5tracer->tid, &attr, k5tracer_thread, NULL); if (ret) { pthread_attr_destroy(&attr); GPDEBUGN(3, "%s: pthread_create failed: %d", __func__, ret); goto done; } pthread_attr_destroy(&attr); setenv("KRB5_TRACE", tracing_file_name, 1); ret = 0; done: if (ret) { char errstr[128]; /* reasonable error str length */ GPDEBUGN(3, "%s: Failed to set up krb5 tracing thread: [%s](%d)\n", __func__, strerror_r(ret, errstr, 128), ret); free_k5tracer(); } return; } void gp_krb5_fini_tracing(void) { if (tracing_file_name) { /* just in case */ gp_krb5_tracing_setup(0); /* remove this one if there */ unlink(tracing_file_name); } }
2.1875
2
2024-11-18T20:59:45.592437+00:00
2020-09-16T02:19:13
2785198a2b96a46813a20426f242a565ff5ab674
{ "blob_id": "2785198a2b96a46813a20426f242a565ff5ab674", "branch_name": "refs/heads/master", "committer_date": "2020-09-16T02:19:13", "content_id": "b40666bf3faa3054e602a32890cc3b28ae97ecdf", "detected_licenses": [ "MIT" ], "directory_id": "68dd23b751701efa486423ed6d75b593844cc21c", "extension": "c", "filename": "test.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 295891609, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 622, "license": "MIT", "license_type": "permissive", "path": "/test.c", "provenance": "stackv2-0135.json.gz:249058", "repo_name": "yifan2260/CIT-595-Remote-CPU-Monitor", "revision_date": "2020-09-16T02:19:13", "revision_id": "d4ec66bbd5878fe2bba97088251f453668ad644e", "snapshot_id": "f338d00de58493680d4618b85fc26307c949b563", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/yifan2260/CIT-595-Remote-CPU-Monitor/d4ec66bbd5878fe2bba97088251f453668ad644e/test.c", "visit_date": "2022-12-18T17:31:21.134139" }
stackv2
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <pthread.h> #include <time.h> char* readFile(char* filename){ FILE *fp; fp = fopen(filename , "r"); fseek( fp , 0 , SEEK_END ); int file_size; file_size = ftell( fp ); printf( "%d\n" , file_size ); char *tmp; fseek( fp , 0 , SEEK_SET); tmp = (char *)malloc( file_size * sizeof( char ) ); fread( tmp , file_size , sizeof(char) , fp); //printf("%s\n" , tmp ); return tmp; }
2.4375
2
2024-11-18T20:59:45.723223+00:00
2020-09-28T15:48:47
01324dc1d841ad2269fb935d0365ff9a3a893c78
{ "blob_id": "01324dc1d841ad2269fb935d0365ff9a3a893c78", "branch_name": "refs/heads/master", "committer_date": "2020-09-28T15:48:47", "content_id": "5a5fcde886fef40a2f4ed45c2be33254c39a1abd", "detected_licenses": [ "MIT" ], "directory_id": "ff4b792bdc398115a9d190cf9d68232d38164003", "extension": "c", "filename": "init.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10729, "license": "MIT", "license_type": "permissive", "path": "/Charger/init.c", "provenance": "stackv2-0135.json.gz:249189", "repo_name": "gdgly/Charger-1", "revision_date": "2020-09-28T15:48:47", "revision_id": "215e698afd3c6a7ec555cea9fd13c45f8076ec7f", "snapshot_id": "287c9bd6eee013e727a494cbe2e446fac4ea2d90", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gdgly/Charger-1/215e698afd3c6a7ec555cea9fd13c45f8076ec7f/Charger/init.c", "visit_date": "2022-12-22T14:44:16.929988" }
stackv2
#include "p33FJ16GS502.h" #include "Functions.h" #include "dsp.h" #include "CAN_transmit.h" /* Variable Declaration required for each PID controller in the application. */ tPID Buck1VoltagePID; /* These data structures contain a pointer to derived coefficients in X-space and pointer to controler state (history) samples in Y-space. So declare variables for the derived coefficients and the controller history samples */ fractional Buck1VoltageABC[3] __attribute__ ((section (".xbss, bss, xmemory"))); fractional Buck1VoltageHistory[3] __attribute__ ((section (".ybss, bss, ymemory"))); #define PID_BUCK1_KP 0.23 #define PID_BUCK1_KI 0.0016 #define PID_BUCK1_KD 0 /* These macros are used for faster calculation in the PID routine and are used for limiting the PID Coefficients */ #define PID_BUCK1_A Q15(PID_BUCK1_KP + PID_BUCK1_KI + PID_BUCK1_KD) //A = 0.2316 #define PID_BUCK1_B Q15(-1 *(PID_BUCK1_KP + 2 * PID_BUCK1_KD)) //B = -0.23 #define PID_BUCK1_C Q15(PID_BUCK1_KD) //C = 0 #define TRIG_OFFSET 140 // small offset for the ADC trigger /* This is increment rate to give us the sofstart */ #define BUCK1_SOFTSTART_INCREMENT 40 int zero_transducer, average, vout_average; //zero value; running average of the measured current extern unsigned int TimerInterruptCount; char CAN_stat_result; void SPI_setup(void) { //__builtin_write_OSCCONL(0x46); //__builtin_write_OSCCONH(0x57); //OSCCONbits.IOLOCK =0; // enable changing RPIN and RPOR registers //__builtin_write_OSCCONL(0x46); //__builtin_write_OSCCONH(0x57); //OSCCONbits.IOLOCK =1; // prevent changing RPIN and RPOR registers //Prescalers: in case Fck =40MHz, the baud rate is 104.17KHz SPI1CON1bits.PPRE =0b00; //64:1 SPI1CON1bits.SPRE =0b010; //6:1 //setup the SPI1 IFS0bits.SPI1IF = 0; //Clear the Interrupt Flag IEC0bits.SPI1IE = 0; //disable the Interrupt SPI1CON1bits.DISSCK = 0; //Internal Serial Clock is Enabled. SPI1CON1bits.DISSDO = 0; //SDOx pin is controlled by the module. SPI1CON1bits.MODE16 = 0; //Communication is word-wide (16 bits). SPI1CON1bits.SMP = 0; //Input Data is sampled at the middle of data output time. SPI1CON1bits.CKE = 1; //Serial output data changes on transition from //Idle clock state to active clock state SPI1CON1bits.CKP = 0; //Idle state for clock is a low level; //active state is a high level SPI1CON1bits.MSTEN = 1; //Master Mode Enabled SPI1STATbits.SPIEN = 1; //Enable SPI Module Delay_ms(1); //issue reset command CAN_reset(); Delay_ms(1); CAN_write(CANCTRL, 0b00001110); // clock/4; clock out pin enabled; one-shot mode; set normal operation mode CAN_stat_result =CAN_read(CANSTAT); } void UART_setup(void) { #define FCY 39613000 //Instruction Cycle Frequency #define BAUDRATE 9600 #define BRGVAL ((FCY/BAUDRATE)/16)-1 // calculate UART prescaler value U1BRG = BRGVAL; U1MODEbits.UARTEN = 1; /* Reset UART to 8-n-1, alt pins, and enable */ U1STAbits.UTXEN = 1; /* Reset status register and enable TX & RX*/ // U1MODEbits.ABAUD =1; } void Buck1Drive(void) { #define PERIOD 4800 // for 100KHz PWM period PTCON2bits.PCLKDIV =1; //master PWM clock divider; changes the PWM freq. from 200kHz to 100kHz period PTPER = PERIOD; // PWM#1 IOCON1bits.PENH = 1; /* PWM1H is controlled by PWM module */ IOCON1bits.PENL = 1; /* PWM1L is controlled by PWM module */ IOCON1bits.PMOD = 0; /* Complementary Mode */ IOCON1bits.POLH = 0; /* Drive signals are active-high */ IOCON1bits.POLL = 0; /* Drive signals are active-high */ IOCON1bits.OVRENH = 0; /* Disable Override feature for shutdown PWM */ IOCON1bits.OVRENL = 0; /* Disable Override feature for shutdown PWM */ IOCON1bits.OVRDAT = 0b00; /* Shut down PWM with Over ride 0 on PWMH and PWML */ PWMCON1bits.DTC = 0; /* Positive Deadtime enabled */ DTR1 = 80; // DT is about 100ns ALTDTR1 = 80; // alt DT is about 150ns PWMCON1bits.IUE = 0; /* Disable Immediate duty cycle updates */ PWMCON1bits.ITB = 0; /* Select Primary Timebase mode */ PWMCON1bits.CLIEN = 1; // Enable Current limit interrupt TRGCON1bits.TRGDIV = 0b1111; /* Trigger interrupt generated every 16-th PWM cycle */ TRGCON1bits.TRGSTRT = 0; /* Trigger generated after waiting 0 PWM cycles */ PDC1 = PERIOD /2; /* 50% Initial pulse-width = minimum deadtime required (DTR1 + ALDTR1)*/ TRIG1 = PERIOD -TRIG_OFFSET; /* Trigger generated at beginning of PWM active period */ FCLCON1bits.CLSRC = 0; // Current source 0 FCLCON1bits.CLPOL = 1; // Invert current source = active low FCLCON1bits.CLMOD = 1; // Enable current limiting FCLCON1bits.FLTMOD = 3; /* Fault Disabled */ // PWM#2 IOCON2bits.PENH = 1; /* PWM1H is controlled by PWM module */ IOCON2bits.PENL = 1; /* PWM1L is controlled by PWM module */ IOCON2bits.PMOD = 0; /* Complementary Mode */ IOCON2bits.POLH = 0; /* Drive signals are active-high */ IOCON2bits.POLL = 0; /* Drive signals are active-high */ IOCON2bits.OVRENH = 0; /* Disable Override feature for shutdown PWM */ IOCON2bits.OVRENL = 0; /* Disable Override feature for shutdown PWM */ IOCON2bits.OVRDAT = 0b00; /* Shut down PWM with Over ride 0 on PWMH and PWML */ PWMCON2bits.DTC = 0; /* Positive Deadtime enabled */ DTR2 = 80; // DT is about 100ns ALTDTR2 = 80; // alt DT is about 150ns PWMCON2bits.IUE = 0; /* Disable Immediate duty cycle updates */ PWMCON2bits.ITB = 0; /* Select Primary Timebase mode */ PDC2 =PERIOD /2; PHASE2 = 1200; FCLCON2bits.CLSRC = 0; // Current source 0 FCLCON2bits.CLPOL = 1; // Invert current source = active low FCLCON2bits.CLMOD = 1; // Enable current limiting FCLCON2bits.FLTMOD = 3; /* Fault Disabled */ IEC5bits.PWM1IE =1; //Enable PWM1 interrupt (capture Current limit) } void updateTrigPeriodPercentage(unsigned int perc) { TRIG1 = (double)perc/100*PERIOD; } void CurrentandVoltageMeasurements(void) { ADCONbits.ADON = 0; //Stop the ADC ADCONbits.FORM = 0; /* Integer data format */ ADCONbits.EIE = 0; /* Early Interrupt disabled */ ADCONbits.ORDER = 0; /* Convert even channel first */ ADCONbits.SEQSAMP = 0; /* Select simultaneous sampling */ ADCONbits.ADCS = 5; /* ADC clock = FADC/6 = 120MHz / 6 = 20MHz, 12*Tad = 1.6 MSPS, two SARs = 3.2 MSPS */ //ADC Pair0 PWM interrupt config IFS6bits.ADCP0IF = 0; /* Clear ADC Pair 0 interrupt flag */ IPC27bits.ADCP0IP = 5; /* Set ADC interrupt priority */ /*IEC6bits.ADCP0IE = 1; Enable the ADC Pair 0 interrupt. Disable now, to use it later for enable/disable the measurements */ ADPCFGbits.PCFG0 = 0; /* Current Measurement for Buck 1 */ ADPCFGbits.PCFG1 = 0; /* Voltage Measurement for Buck 1 */ ADCPC0bits.IRQEN0 = 1; /* Enable ADC Interrupt, pair 0*/ ADCPC0bits.TRGSRC0 = 4; /* ADC Pair 0 triggered by PWM1 */ //ADC Pair 1 In voltage manually start ADPCFGbits.PCFG2 = 0; /* Input voltage Measurement for Buck 1 at AN2*/ ADSTATbits.P1RDY = 0; /* Clear Pair 1 data ready bit */ ADCPC0bits.IRQEN1 = 0; /* Disable ADC pair 1 Interrupt after input voltage measurement */ ADCPC0bits.TRGSRC1 = 1; /* ADC Pair 1 triggered by individual soft trigger */ } void Buck1VoltageLoop(void) { Buck1VoltagePID.abcCoefficients = Buck1VoltageABC; /* Set up pointer to derived coefficients */ Buck1VoltagePID.controlHistory = Buck1VoltageHistory; /* Set up pointer to controller history samples */ PIDInit(&Buck1VoltagePID); if ((PID_BUCK1_A == 0x7FFF || PID_BUCK1_A == 0x8000) || (PID_BUCK1_B == 0x7FFF || PID_BUCK1_B == 0x8000) || (PID_BUCK1_C == 0x7FFF || PID_BUCK1_C == 0x8000)) { while(1); /* This is a check for PID Coefficients being saturated */ } Buck1VoltagePID.abcCoefficients[0] = PID_BUCK1_A; /* Load calculated coefficients */ Buck1VoltagePID.abcCoefficients[1] = PID_BUCK1_B; Buck1VoltagePID.abcCoefficients[2] = PID_BUCK1_C; Buck1VoltagePID.controlReference = 0; //Start with 0 current Buck1VoltagePID.measuredOutput = 0; /* Measured Output is 0 volts before softstart */ } void UpdateControlReference(unsigned int POT) { Buck1VoltagePID.controlReference = POT; } void UpdateDTR(unsigned int POT) { DTR1 = POT; ALTDTR1 = POT; DTR2 = POT; ALTDTR2 = POT; } void Buck1SoftStartRoutine(unsigned int POT) { /* This routine increments the control reference until the reference reaches the desired output voltage reference. In this case the we have a softstart of 50ms */ Buck1VoltagePID.controlReference = 0; //Start with 0 current while (Buck1VoltagePID.controlReference <= POT) { Delay_ms(1); Buck1VoltagePID.controlReference += BUCK1_SOFTSTART_INCREMENT; } Buck1VoltagePID.controlReference = POT; } void Delay_ms (unsigned int delay) { TimerInterruptCount = 0; /* Clear Interrupt counter flag */ PR1 = 0x9C40; /* (1ms / 25ns) = 40,000 = 0x9C40 */ IPC0bits.T1IP = 4; /* Set Interrupt Priority lower then ADC */ IEC0bits.T1IE = 1; /* Enable Timer1 interrupts */ T1CONbits.TON = 1; /* Enable Timer1 */ while (TimerInterruptCount < delay); /* Wait for Interrupt counts to equal delay */ T1CONbits.TON = 0; /* Disable the Timer */ }
2.21875
2
2024-11-18T20:59:45.946954+00:00
2017-12-29T19:55:39
8b867718b848f157dd6824c6ba59b9d05398bb6f
{ "blob_id": "8b867718b848f157dd6824c6ba59b9d05398bb6f", "branch_name": "refs/heads/master", "committer_date": "2017-12-29T19:55:39", "content_id": "2d2d45721958d9fd1eaa1e84210357e6b64075bd", "detected_licenses": [ "Unlicense" ], "directory_id": "89fd9e3b0c88adcb9331cc95b25be7c268ddd131", "extension": "c", "filename": "p10.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 29105279, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1364, "license": "Unlicense", "license_type": "permissive", "path": "/08_arrays/p10.c", "provenance": "stackv2-0135.json.gz:249450", "repo_name": "Kareeeeem/c_modern_approach", "revision_date": "2017-12-29T19:55:39", "revision_id": "0621d632e5c09ba51f754d9106923bdd2db71e60", "snapshot_id": "c618612098f64aac5c9a3e5e2c86c508443fae81", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/Kareeeeem/c_modern_approach/0621d632e5c09ba51f754d9106923bdd2db71e60/08_arrays/p10.c", "visit_date": "2020-04-06T10:03:37.817973" }
stackv2
#include <stdio.h> #include <stdlib.h> static int depatures[8][2] = { {8, 0}, {9, 43}, {11, 19}, {12, 47}, {14, 0}, {15, 45}, {19, 0}, {21, 45}, }; static int arrivals[8][2] = { {10, 16}, {11, 52}, {13, 31}, {15, 0}, {16, 8}, {17, 55}, {21, 20}, {23, 58}, }; static int convert_to_minutes(int time[2]) { return 60 * time[0] + time[1]; } int main(void) { int hours; int minutes; int time_in_minutes; int dtime_in_minutes; int smallest_difference; int difference; int closest; printf("Enter a 24-hour time: "); scanf("%d:%d", &hours, &minutes); time_in_minutes = convert_to_minutes((int[2]){hours, minutes}); dtime_in_minutes = convert_to_minutes(depatures[0]); smallest_difference = abs(time_in_minutes - dtime_in_minutes); closest = 0; for (int i = 1; i < (int) (sizeof(depatures) / sizeof(depatures[0])); i++) { dtime_in_minutes = convert_to_minutes(depatures[i]); difference = abs(time_in_minutes - dtime_in_minutes); if (difference < smallest_difference) { closest = i; smallest_difference = difference; } } printf("%.2d:%.2d\n", depatures[closest][0], depatures[closest][1]); printf("%.2d:%.2d\n", arrivals[closest][0], arrivals[closest][1]); return 0; }
3.0625
3
2024-11-18T20:59:46.075188+00:00
2017-02-12T21:37:42
bcb6effa7818d7e89537650449147f0bafc5cbb6
{ "blob_id": "bcb6effa7818d7e89537650449147f0bafc5cbb6", "branch_name": "refs/heads/master", "committer_date": "2017-02-12T21:37:42", "content_id": "75c5838f43919ac07e7f8efecff4f6c6d036b221", "detected_licenses": [ "MIT" ], "directory_id": "be67b4788e7116bcc283f58abdf7c5ded67d8a96", "extension": "c", "filename": "resrc.c", "fork_events_count": 0, "gha_created_at": "2013-08-05T19:48:02", "gha_event_created_at": "2016-01-04T16:18:36", "gha_language": "C", "gha_license_id": null, "github_id": 11907215, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6216, "license": "MIT", "license_type": "permissive", "path": "/lib/mid/resrc.c", "provenance": "stackv2-0135.json.gz:249581", "repo_name": "velour/mid", "revision_date": "2017-02-12T21:37:42", "revision_id": "429605443963db4e6a3ba8440caa241372b3ca74", "snapshot_id": "850870169ded699f047ec018cd6d189ebbec5d8c", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/velour/mid/429605443963db4e6a3ba8440caa241372b3ca74/lib/mid/resrc.c", "visit_date": "2021-06-30T04:52:31.827037" }
stackv2
/* © 2013 the Mid Authors under the MIT license. See AUTHORS for the list of authors.*/ /* A resource table finds and tracks resource usage (reference * counts). A finite number of unreferenced resources are kept in a * simple cache with a FIFO-ish replacement policy. */ #include <assert.h> #include <stdbool.h> #include <string.h> #include "fs.h" #include "../../include/mid.h" enum { Initsize = 257 }; enum { Fillfact = 3 }; enum { Cachesize = 100 }; static const char *roots[] = { "resrc", "../Resources" }; enum { NROOTS = sizeof(roots) / sizeof(roots[0]) }; typedef struct Resrc Resrc; struct Resrc { void *resrc, *aux; char file[PATH_MAX + 1], path[PATH_MAX + 1]; int refs, cind; Resrc *nxt; Resrc *unxt; }; struct Rtab { Resrc **tbl; int sz, fill; Resrc *cache[Cachesize]; /* cache of unused nodes. */ int cfill; Resrcops *ops; }; /* From K&R 2nd edition. */ unsigned int strhash(const char *s) { unsigned int h; for (h = 0; *s != '\0'; s += 1) h = *s + 31 * h; return h; } unsigned int hash(Resrcops *ops, const char *file, void *aux) { if (ops->hash) return ops->hash(file, aux); return strhash(file); } bool eq(Resrcops *ops, Resrc *r, const char *file, void *aux) { if (ops->eq) return ops->eq(r->aux, aux) && strcmp(r->file, file) == 0; return strcmp(r->file, file) == 0; } static Resrc *tblfind(Resrcops *ops, Resrc *tbl[], int sz, const char *file, void *aux) { if (sz == 0) return NULL; unsigned int i = hash(ops, file, aux) % sz; Resrc *p = NULL; for (p = tbl[i]; p; p = p->nxt) if (eq(ops, p, file, aux)) break; return p; } static void tblrem(Resrcops *ops, Resrc *tbl[], int sz, Resrc *rm) { unsigned int i = hash(ops, rm->file, rm->aux) % sz; if (tbl[i] == rm) { tbl[i] = rm->nxt; return; } Resrc *p; for (p = tbl[i]; p->nxt && p->nxt != rm; p = p->nxt) ; assert(p->nxt); if (p->nxt == rm) p->nxt = rm->nxt; } static void tblins(Resrcops *ops, Resrc *tbl[], int sz, Resrc *r) { unsigned int i = hash(ops, r->file, r->aux) % sz; assert (!r->nxt); r->nxt = tbl[i]; tbl[i] = r; } static void rtabgrow(Rtab *t) { int nxtsz = t->sz * 2; if (nxtsz == 0) nxtsz = Initsize; Resrc **nxttbl = xalloc(nxtsz, sizeof(*nxttbl)); for (int i = 0; i < t->sz; i++) { for (Resrc *p = t->tbl[i]; p; p = p->nxt) tblins(t->ops, nxttbl, nxtsz, p); } if (t->tbl) xfree(t->tbl); t->tbl = nxttbl; t->sz = nxtsz; } static void cacherm(Rtab *t, int i) { t->cache[i]->cind = -1; t->cfill--; t->cache[i] = t->cache[t->cfill]; if (t->cfill > 0) t->cache[i]->cind = i; } static void cacheresrc(Rtab *t, Resrc *r) { if (t->cfill == Cachesize) { Resrc *bump = t->cache[0]; cacherm(t, 0); tblrem(t->ops, t->tbl, t->sz, bump); if (t->ops->unload) t->ops->unload(bump->path, bump->resrc, bump->aux); xfree(bump); } assert (t->cfill < Cachesize); t->cache[t->cfill] = r; r->cind = t->cfill; t->cfill++; } static Resrc *resrcnew(const char *path, const char *file, void *aux) { Resrc *r = xalloc(1, sizeof(*r)); if (!r) return NULL; strncpy(r->file, file, PATH_MAX + 1); strncpy(r->path, path, PATH_MAX + 1); r->aux = aux; r->cind = -1; return r; } static Resrc *resrcload(Rtab *t, const char *file, void *aux) { char path[PATH_MAX + 1]; bool found = false; for (int i = 0; !found && i < NROOTS; i += 1) { fscat(roots[i], file, path); found = fsexists(path); } if (!found) { seterrstr("Not found"); return NULL; } Resrc *r = resrcnew(path, file, aux); if (!r) return NULL; r->resrc = t->ops->load(path, aux); t->fill++; if (t->fill * Fillfact >= t->sz) rtabgrow(t); tblins(t->ops, t->tbl, t->sz, r); return r; } void *resrcacq(Rtab *t, const char *file, void *aux) { Resrc *r = tblfind(t->ops, t->tbl, t->sz, file, aux); if (!r) r = resrcload(t, file, aux); else if (r->refs == 0) cacherm(t, r->cind); if (!r) return NULL; r->refs++; return r->resrc; } void resrcrel(Rtab *t, const char *file, void *aux) { Resrc *r = tblfind(t->ops, t->tbl, t->sz, file, aux); assert(r); r->refs--; if (r->refs == 0) cacheresrc(t, r); } Rtab *rtabnew(Resrcops *ops) { Rtab *t = xalloc(1, sizeof(*t)); if (!t) return NULL; t->ops = ops; return t; } void rtabfree(Rtab *t) { for (int i = 0; i < t->sz; i += 1) { Resrc *p, *q; for (p = q = t->tbl[i]; p; p = q) { if (t->ops->unload) t->ops->unload(p->path, p->resrc, p->aux); q = p->nxt; xfree(p); } } xfree(t); } Rtab *imgs; void *imgload(const char *path, void *_ignrd) { return imgnew(path); } void imgunload(const char *path, void *img, void *_info) { imgfree(img); } static Resrcops imgtype = { .load = imgload, .unload = imgunload, }; Rtab *txt; void *txtload(const char *path, void *_info) { Txtinfo *info = _info; return txtnew(path, info->size, info->color); } void txtunload(const char *path, void *txt, void *_info) { txtfree(txt); } unsigned int txthash(const char *path, void *_info) { Txtinfo *info = _info; return strhash(path) ^ info->size ^ (info->color.r << 24) ^ (info->color.g << 16) ^ (info->color.b << 8) ^ info->color.a; } bool txteq(void *_a, void *_b) { Txtinfo *a = _a, *b = _b; return a->size == b->size && a->color.r == b->color.r && a->color.g == b->color.g && a->color.b == b->color.b && a->color.a == b->color.a; } static Resrcops txttype = { .load = txtload, .unload = txtunload, .hash = txthash, .eq = txteq, }; Rtab *music; void *musicload(const char *path, void *_ignrd) { return musicnew(path); } void musicunload(const char *path, void *music, void *_info) { musicfree(music); } static Resrcops musictype = { .load = musicload, .unload = musicunload, }; Rtab *sfx; void *sfxload(const char *path, void *_ignrd) { return sfxnew(path); } void sfxunload(const char *path, void *s, void *_info) { sfxnew(s); } static Resrcops sfxtype = { .load = sfxload, .unload = sfxunload, }; void initresrc(void) { imgs = rtabnew(&imgtype); assert(imgs != NULL); txt = rtabnew(&txttype); assert(txt != NULL); music = rtabnew(&musictype); assert(music != NULL); sfx = rtabnew(&sfxtype); assert(sfx != NULL); } void freeresrc(void) { rtabfree(sfx); rtabfree(music); rtabfree(txt); rtabfree(imgs); }
2.515625
3
2024-11-18T20:59:47.946404+00:00
2018-03-08T00:10:49
a42f10dd451d5429bff9a9c72bbc097e3f4d1b97
{ "blob_id": "a42f10dd451d5429bff9a9c72bbc097e3f4d1b97", "branch_name": "refs/heads/master", "committer_date": "2018-03-08T00:10:49", "content_id": "b2bd3eb41e601803b96359d4f8a73acd59cd8a38", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "73365f422b3de1e8c051b3d95f53ef2f0446accd", "extension": "c", "filename": "vga2bmp.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 124311087, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1462, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/vga2bmp.c", "provenance": "stackv2-0135.json.gz:249974", "repo_name": "electroduck/vgavid", "revision_date": "2018-03-08T00:10:49", "revision_id": "4b8151675f04f5f6686bbc4b70686399253f23b9", "snapshot_id": "3ee15d9eae60bf25ac276f2ca3aaf907d3aaa2d1", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/electroduck/vgavid/4b8151675f04f5f6686bbc4b70686399253f23b9/vga2bmp.c", "visit_date": "2020-04-11T00:01:28.608621" }
stackv2
#include <stdio.h> #include <stdint.h> #include "bmp.h" #include "vga_p13h.h" #include "vga_13h.h" #define VGA2BMP_BMP_BYTES (VGA_13H_W * VGA_13H_H * BMP_BYTESPERPIXEL) static uint8_t vgaData[VGA_13H_NBYTES]; static uint8_t bmpData[VGA2BMP_BMP_BYTES]; int main(int argc, char** argv) { FILE* inFile; FILE* outFile; size_t nElem; if(argc < 3) { puts("Usage: vga2bmp <input.13h> <output.bmp>"); return 1; } inFile = fopen(argv[1], "rb"); if(!inFile || ferror(inFile)) { printf("Unable to open %s for reading.\n", argv[1]); return 2; } outFile = fopen(argv[2], "wb"); if(!inFile || ferror(inFile)) { printf("Unable to open %s for writing.\n", argv[2]); return 3; } printf("Reading input... "); fflush(stdout); nElem = fread(vgaData, 1, VGA_13H_NBYTES, inFile); if(nElem == VGA_13H_NBYTES) puts("file loaded."); else if(!nElem) { puts("no data could be read."); return 4; } else { printf("Warning: Only %u of %u bytes read.\n", nElem, VGA_13H_NBYTES); } printf("Converting... "); fflush(stdout); VGA13hTo24bpp(bmpData, vgaData, VGA13H_PLT_DATA); puts("image converted."); printf("Saving... "); fflush(stdout); nElem = BMPWrite(outFile, VGA_13H_W, VGA_13H_H, bmpData); if(nElem == VGA_13H_NPIX) { puts("image saved."); return 0; } else { printf("failed - only %u of %u bytes written.\n", nElem, VGA_13H_NPIX); return 5; } }
2.84375
3
2024-11-18T21:50:41.262099+00:00
2022-04-17T21:25:56
abc75cd13b75baf294e63dfaf0b96212271ccd69
{ "blob_id": "abc75cd13b75baf294e63dfaf0b96212271ccd69", "branch_name": "refs/heads/master", "committer_date": "2022-04-17T21:25:56", "content_id": "0d0e12f1469a0ab011f02e17e47463a8a3153f59", "detected_licenses": [ "MIT" ], "directory_id": "4832e8a2cb6f2bdcf6c1941285bd91ddd1a31a3f", "extension": "c", "filename": "uart.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 199737559, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3860, "license": "MIT", "license_type": "permissive", "path": "/UART-Test/UART-Test/uart.c", "provenance": "stackv2-0138.json.gz:122406", "repo_name": "aniket-rai/EE-209-Team5", "revision_date": "2022-04-17T21:25:56", "revision_id": "517a5825a81fd4e02adb87b76c4dfa4db3b987df", "snapshot_id": "58f2f4945da787ef31652fda0aae5b3b7aec14ae", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/aniket-rai/EE-209-Team5/517a5825a81fd4e02adb87b76c4dfa4db3b987df/UART-Test/UART-Test/uart.c", "visit_date": "2022-05-08T00:21:51.117918" }
stackv2
/* * uart.c * * Created: 25/09/2019 2:51:41 pm * Author: Aniket */ #include <avr/io.h> #define V 86 #define I 73 #define P 80 #define F 70 #define EQ 61 #define DOT 46 #define NEWLINE 10 #define STARTLINE 13 void init_uart(uint16_t ubrr) { // Mode Selection - Asynchronous USART UCSR0C &= ~(1 << UMSEL10); UCSR0C &= ~(1 << UMSEL11); // Character Size - 8 Bit UCSR0B &= ~(1 << UCSZ02); UCSR0C |= (1 << UCSZ10); UCSR0C |= (1 << UCSZ11); // Baud Rate - 9600 UBRR0 = 103; // Transmitter Enable - Yes UCSR0B |= (1 << TXEN0); // Parity Mode - Disabled UCSR0C &= ~(1 << UPM00); UCSR0C &= ~(1 << UPM10); // Stop Bit Selection - 1 bit UCSR0C &= ~(1 << USBS0); } void transmit_uart(uint8_t data) { while(!(UCSR0A & (1 << UDRE0))) { } UDR0 = data; } void transmitVoltage(double data) { transmit_uart(V); transmit_uart(EQ); if(data >= 10) { // transmit 10.00 column uint8_t tens = (uint8_t)data/10; transmit_uart(tens + 48); // transmit 1.00 column uint8_t ones = (uint8_t)data - tens*10; transmit_uart(ones + 48); // transmit 0.10 column transmit_uart(DOT); uint8_t oneth = (10*(data - (uint8_t)data)); transmit_uart(oneth + 48); // transmit 0.01 column uint8_t tenth = (uint8_t)(data*100 - (uint8_t)(data)*100 - oneth*10); transmit_uart(tenth + 48); transmit_uart(NEWLINE); transmit_uart(STARTLINE); } else { // transmit 1.00 column transmit_uart((uint8_t)data + 48); // transmit 0.10 column transmit_uart(DOT); uint8_t ones = 10*(data - (uint8_t)data); transmit_uart(ones + 48); // transmit 0.01 column uint8_t tens = (uint8_t)(data*100 - (uint8_t)(data)*100- ones*10); transmit_uart(tens + 48); // transmit 0.001 column uint8_t hundreds = (uint8_t)(data*1000 - (uint8_t)(data)*1000 - tens*10 - ones*100); transmit_uart(hundreds + 48); // New line + Startline transmit_uart(NEWLINE); transmit_uart(STARTLINE); } } /* Current Transmission Function */ void transmitCurrent(double data) { transmit_uart(I); transmit_uart(EQ); // transmit 100.00 column uint8_t hundreds = (uint8_t)data/100; transmit_uart(hundreds + 48); // trasmit 10.00 column uint8_t tens = ((uint8_t)data - hundreds*100)/10; transmit_uart(tens + 48); // transmit 1.00 column uint8_t ones = (uint8_t)data - hundreds*100 - tens*10; transmit_uart(ones + 48); // transmit 0.10 column transmit_uart(DOT); uint8_t oneth = (uint8_t)(data * 10); transmit_uart(oneth + 48); // New line + Startline transmit_uart(NEWLINE); transmit_uart(STARTLINE); } void transmitPowerFactor(double data) { transmit_uart(F); transmit_uart(EQ); //transmit 0 and Dot transmit_uart(48); transmit_uart(DOT); // transmit 0.1 column uint8_t ones = (uint8_t)(data * 10); transmit_uart(ones + 48); // transmit 0.01 column uint8_t tens = (uint8_t)(data*100 - ones*10); transmit_uart(tens + 48); // tranmit 0.001 column uint8_t hundreds = (uint8_t)(data*1000 - tens*10 - ones*100); transmit_uart(hundreds + 48); transmit_uart(NEWLINE); transmit_uart(STARTLINE); } void transmitRealPower(double data) { transmit_uart(P); transmit_uart(EQ); if(data >= 10) { // transmit 10.00 column uint8_t tens = (uint8_t)data/10; transmit_uart(tens + 48); // transmit 1.00 column uint8_t ones = (uint8_t)data - tens*10; transmit_uart(ones + 48); // transmit 0.10 column transmit_uart(DOT); transmit_uart((10*(data - (int)data)) + 48); transmit_uart(NEWLINE); transmit_uart(STARTLINE); } else { // transmit 1.00 column transmit_uart((uint8_t)data + 48); // transmit 0.10 column transmit_uart(DOT); uint8_t tens = 10*(data - (int)data); transmit_uart(tens + 48); // transmit 0.01 column data *= 100; int ones = (int)data % 10; transmit_uart(ones + 48); // New line + Startline transmit_uart(NEWLINE); transmit_uart(STARTLINE); } }
2.90625
3
2024-11-18T21:50:41.662076+00:00
2018-08-26T22:22:56
c3a7ca90163b1b1c35cecfd10db55f4f5c37020a
{ "blob_id": "c3a7ca90163b1b1c35cecfd10db55f4f5c37020a", "branch_name": "refs/heads/wip", "committer_date": "2018-12-01T18:41:49", "content_id": "a4cb024550de5af1fb3c6eeb5655209eb1f55ff1", "detected_licenses": [ "Apache-2.0" ], "directory_id": "4aeed62d81313c35e4534a56b8e5bab9625a5462", "extension": "c", "filename": "gpio_sdl.c", "fork_events_count": 0, "gha_created_at": "2017-09-07T19:30:18", "gha_event_created_at": "2022-12-26T20:40:52", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 102777565, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12639, "license": "Apache-2.0", "license_type": "permissive", "path": "/drivers/gpio/gpio_sdl.c", "provenance": "stackv2-0138.json.gz:123055", "repo_name": "vanwinkeljan/zephyr", "revision_date": "2018-08-26T22:22:56", "revision_id": "c4bc7a19aec85272a4897522ba8b643b119b688f", "snapshot_id": "e207dbe75d670c9ec475a0e5261138aa88d914f0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/vanwinkeljan/zephyr/c4bc7a19aec85272a4897522ba8b643b119b688f/drivers/gpio/gpio_sdl.c", "visit_date": "2023-01-06T10:53:27.696912" }
stackv2
/* * Copyright (c) 2018 Jan Van Winkel <[email protected]> * * SPDX-License-Identifier: Apache-2.0 */ #include <string.h> #include <gpio.h> #include <errno.h> #include "gpio_utils.h" #include <SDL.h> #include "irq_ctrl.h" typedef void (*gpio_sdl_config_irq_t)(void); enum gpio_sdl_switch_type { gpio_sdl_toggle_switch = 0, gpio_sdl_momentary_no_switch, gpio_sdl_momentary_nc_switch, gpio_sdl_impulse_switch, }; struct gpio_sdl_data { sys_slist_t callbacks; u32_t enabled_callbacks; int flags[32]; u32_t pin_state; u32_t pending_irqs; }; struct gpio_sdl_config { u8_t scan_codes[32]; enum gpio_sdl_switch_type switch_types[32]; gpio_sdl_config_irq_t cfg_irq_func; u32_t irq_id; }; static int gpio_sdl_init(struct device *dev); static int gpio_sdl_config(struct device *port, int access_op, u32_t pin, int flags); static int gpio_sdl_write(struct device *port, int access_op, u32_t pin, u32_t value); static int gpio_sdl_read(struct device *port, int access_op, u32_t pin, u32_t *value); static int gpio_sdl_manage_callback(struct device *port, struct gpio_callback *callback, bool set); static int gpio_sdl_enable_callback(struct device *port, int access_op, u32_t pin); static int gpio_sdl_disable_callback(struct device *port, int access_op, u32_t pin); static u32_t gpio_sdl_get_pending_int(struct device *dev); static void gpio_sdl_write_pin(struct gpio_sdl_data *data, u32_t pin, bool enabled); static void gpio_sdl_0_cfg_irq(void); static void gpio_sdl_isr(void *arg); static void gpio_sdl_handle_pin_event(u32_t pin, struct gpio_sdl_data *data, const struct gpio_sdl_config *cfg, SDL_Event *event); static bool gpio_sdl_handle_toggle_switch(u32_t pin, struct gpio_sdl_data *data, SDL_Event *event); static bool gpio_sdl_handle_momentary_switch(u32_t pin, struct gpio_sdl_data *data, SDL_Event *event, bool normal_closed); static bool gpio_sdl_handle_impulse_switch(u32_t pin, struct gpio_sdl_data *data, SDL_Event *event); static void gpio_sdl_handle_irq_generation(u32_t pin, struct gpio_sdl_data *data, const struct gpio_sdl_config *cfg, bool prev_pin_state, bool new_pin_state); #define DEV_GPIO_CFG(dev) \ ((const struct gpio_sdl_config * const)dev->config->config_info) #define DEV_GPIO_DATA(dev) \ ((struct gpio_sdl_data * const)dev->driver_data) struct gpio_driver_api gpio_sdl_driver_api = { .config = gpio_sdl_config, .write = gpio_sdl_write, .read = gpio_sdl_read, .manage_callback = gpio_sdl_manage_callback, .enable_callback = gpio_sdl_enable_callback, .disable_callback = gpio_sdl_disable_callback, .get_pending_int = gpio_sdl_get_pending_int}; int gpio_sdl_config(struct device *port, int access_op, u32_t pin, int flags) { struct gpio_sdl_data *data = DEV_GPIO_DATA(port); u32_t start_pin; u32_t end_pin; u32_t cur_pin; if (access_op == GPIO_ACCESS_BY_PIN) { __ASSERT_NO_MSG(pin < 32); if (pin < 32) { start_pin = pin; end_pin = pin; } else { return -ENOTSUP; } } else if (access_op == GPIO_ACCESS_BY_PORT) { start_pin = 0; end_pin = 31; } else { return -ENOTSUP; } for (cur_pin = start_pin; cur_pin <= end_pin; ++cur_pin) { data->flags[cur_pin] = flags; } return 0; } void gpio_sdl_write_pin(struct gpio_sdl_data *data, u32_t pin, bool enabled) { if ((data->flags[pin] & GPIO_DIR_MASK) == GPIO_DIR_OUT) { if (enabled) { data->pin_state |= BIT(pin); } else { data->pin_state &= ~BIT(pin); } } } int gpio_sdl_write(struct device *port, int access_op, u32_t pin, u32_t value) { struct gpio_sdl_data *data = DEV_GPIO_DATA(port); if (access_op == GPIO_ACCESS_BY_PIN) { __ASSERT_NO_MSG(pin < 32); if (pin < 32) { gpio_sdl_write_pin(data, pin, (value != 0)); } else { return -ENOTSUP; } } else if (access_op == GPIO_ACCESS_BY_PORT) { u32_t cur_pin; bool enabled; for (cur_pin = 0; cur_pin < 32; ++cur_pin) { enabled = ((value & BIT(cur_pin)) != 0); gpio_sdl_write_pin(data, cur_pin, enabled); } } else { return -ENOTSUP; } return 0; } int gpio_sdl_read(struct device *port, int access_op, u32_t pin, u32_t *value) { struct gpio_sdl_data *data = DEV_GPIO_DATA(port); if (access_op == GPIO_ACCESS_BY_PIN) { __ASSERT_NO_MSG(pin < 32); if (pin < 32) { *value = ((data->pin_state & BIT(pin)) != 0); } else { return -ENOTSUP; } } else if (access_op == GPIO_ACCESS_BY_PORT) { *value = data->pin_state; } else { return -ENOTSUP; } return 0; } int gpio_sdl_manage_callback(struct device *port, struct gpio_callback *callback, bool set) { struct gpio_sdl_data *data = DEV_GPIO_DATA(port); _gpio_manage_callback(&data->callbacks, callback, set); return 0; } int gpio_sdl_enable_callback(struct device *port, int access_op, u32_t pin) { struct gpio_sdl_data *data = DEV_GPIO_DATA(port); if (access_op == GPIO_ACCESS_BY_PIN) { __ASSERT_NO_MSG(pin < 32); if (pin < 32) { data->enabled_callbacks |= BIT(pin); } else { return -ENOTSUP; } } else if (access_op == GPIO_ACCESS_BY_PORT) { data->enabled_callbacks = 0xFFFFFFFF; } else { return -ENOTSUP; } return 0; } int gpio_sdl_disable_callback(struct device *port, int access_op, u32_t pin) { struct gpio_sdl_data *data = DEV_GPIO_DATA(port); if (access_op == GPIO_ACCESS_BY_PIN) { __ASSERT_NO_MSG(pin < 32); if (pin < 32) { data->enabled_callbacks &= ~BIT(pin); } else { return -ENOTSUP; } } else if (access_op == GPIO_ACCESS_BY_PORT) { data->enabled_callbacks = 0x00000000; } else { return -ENOTSUP; } return 0; } u32_t gpio_sdl_get_pending_int(struct device *dev) { struct gpio_sdl_data *data = DEV_GPIO_DATA(dev); return data->pending_irqs; } void gpio_sdl_isr(void *arg) { u32_t callbacks; struct device *dev = (struct device *)arg; struct gpio_sdl_data *data = DEV_GPIO_DATA(dev); callbacks = data->pending_irqs & data->enabled_callbacks; data->pending_irqs = 0; _gpio_fire_callbacks(&data->callbacks, dev, callbacks); } int gpio_sdl_init(struct device *dev) { struct gpio_sdl_data *data = DEV_GPIO_DATA(dev); const struct gpio_sdl_config *cfg = DEV_GPIO_CFG(dev); data->enabled_callbacks = 0; data->pin_state = 0; memset(data->flags, 0, 32 * sizeof(u32_t)); data->pending_irqs = 0; cfg->cfg_irq_func(); return 0; } static struct gpio_sdl_data gpio_sdl_0_data; static const struct gpio_sdl_config gpio_sdl_0_cfg = { .scan_codes = { CONFIG_GPIO_SDL_0_PIN_0_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_1_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_2_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_3_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_4_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_5_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_6_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_7_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_8_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_9_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_10_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_11_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_12_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_13_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_14_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_15_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_16_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_17_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_18_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_19_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_20_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_21_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_22_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_23_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_24_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_25_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_26_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_27_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_28_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_29_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_30_SCAN_CODE, CONFIG_GPIO_SDL_0_PIN_31_SCAN_CODE, }, .switch_types = { CONFIG_GPIO_SDL_0_PIN_0_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_1_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_2_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_3_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_4_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_5_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_6_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_7_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_8_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_9_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_10_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_11_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_12_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_13_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_14_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_15_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_16_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_17_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_18_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_19_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_20_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_21_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_22_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_23_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_24_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_25_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_26_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_27_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_28_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_29_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_30_SWITCH_TYPE, CONFIG_GPIO_SDL_0_PIN_31_SWITCH_TYPE, }, .cfg_irq_func = gpio_sdl_0_cfg_irq, .irq_id = CONFIG_GPIO_SDL_0_IRQ }; DEVICE_AND_API_INIT(gpio_sdl_0, CONFIG_GPIO_SDL_0_DEV_NAME, gpio_sdl_init, &gpio_sdl_0_data, &gpio_sdl_0_cfg, POST_KERNEL, CONFIG_GPIO_SDL_0_INIT_PRIORITY, &gpio_sdl_driver_api); void gpio_sdl_0_cfg_irq(void) { IRQ_CONNECT(CONFIG_GPIO_SDL_0_IRQ, CONFIG_GPIO_SDL_0_IRQ_PRIORITY, gpio_sdl_isr, DEVICE_GET(gpio_sdl_0), 0); irq_enable(CONFIG_GPIO_SDL_0_IRQ); } void gpio_sdl_handle_pin_event(u32_t pin, struct gpio_sdl_data *data, const struct gpio_sdl_config *cfg, SDL_Event *event) { bool new_pin_state = false; bool prev_pin_state = false; switch (cfg->switch_types[pin]) { case gpio_sdl_toggle_switch: new_pin_state = gpio_sdl_handle_toggle_switch(pin, data, event); break; case gpio_sdl_momentary_no_switch: new_pin_state = gpio_sdl_handle_momentary_switch(pin, data, event, false); break; case gpio_sdl_momentary_nc_switch: new_pin_state = gpio_sdl_handle_momentary_switch(pin, data, event, true); break; case gpio_sdl_impulse_switch: new_pin_state = gpio_sdl_handle_impulse_switch(pin, data, event); break; default: return; } gpio_sdl_handle_irq_generation(pin, data, cfg, prev_pin_state, new_pin_state); } bool gpio_sdl_handle_toggle_switch(u32_t pin, struct gpio_sdl_data *data, SDL_Event *event) { bool new_pin_state = data->pin_state & BIT(pin); if (event->type == SDL_KEYUP) { return new_pin_state; } if (event->key.repeat != 0) { return new_pin_state; } if (new_pin_state) { data->pin_state &= ~BIT(pin); new_pin_state = false; } else { data->pin_state |= BIT(pin); new_pin_state = true; } return new_pin_state; } bool gpio_sdl_handle_momentary_switch(u32_t pin, struct gpio_sdl_data *data, SDL_Event *event, bool normal_closed) { bool new_pin_state; if (event->type == SDL_KEYDOWN) { new_pin_state = !normal_closed; } else { new_pin_state = normal_closed; } if (new_pin_state) { data->pin_state &= ~BIT(pin); } else { data->pin_state |= BIT(pin); } return new_pin_state; } bool gpio_sdl_handle_impulse_switch(u32_t pin, struct gpio_sdl_data *data, SDL_Event *event) { bool new_pin_state = false; if (event->key.repeat != 0) { return new_pin_state; } if (event->type == SDL_KEYDOWN) { new_pin_state = true; } else { new_pin_state = false; } if (new_pin_state) { data->pin_state &= ~BIT(pin); } else { data->pin_state |= BIT(pin); } return new_pin_state; } void gpio_sdl_handle_irq_generation(u32_t pin, struct gpio_sdl_data *data, const struct gpio_sdl_config *cfg, bool prev_pin_state, bool new_pin_state) { bool trigger_irq = false; u32_t flags = data->flags[pin]; if ((flags & GPIO_INT) != GPIO_INT) { return; } if ((flags & GPIO_INT_LEVEL) == GPIO_INT_LEVEL) { if ((flags & GPIO_INT_ACTIVE_LOW) == GPIO_INT_ACTIVE_LOW) { trigger_irq = (new_pin_state == 0); } else { trigger_irq = (new_pin_state == 1); } } else { if ((flags & GPIO_INT_DOUBLE_EDGE) == GPIO_INT_DOUBLE_EDGE) { trigger_irq = prev_pin_state ^ new_pin_state; } else if ((flags & GPIO_INT_ACTIVE_LOW) == GPIO_INT_ACTIVE_LOW) { trigger_irq = prev_pin_state && !new_pin_state; } else { trigger_irq = !prev_pin_state && new_pin_state; } } if (trigger_irq) { data->pending_irqs |= BIT(pin); hw_irq_ctrl_set_irq(cfg->irq_id); } } void gpio_sdl_handle_keyboard_event(SDL_Event *event) { int cur_pin; if ((event->type != SDL_KEYUP) && (event->type != SDL_KEYDOWN)) { return; } for (cur_pin = 0; cur_pin < 32; ++cur_pin) { if (event->key.keysym.scancode == gpio_sdl_0_cfg.scan_codes[cur_pin]) { gpio_sdl_handle_pin_event(cur_pin, &gpio_sdl_0_data, &gpio_sdl_0_cfg, event); } } }
2.3125
2
2024-11-18T21:50:41.757702+00:00
2014-12-01T22:05:28
fa3b1874d6b510e82309d77a9cdbb1c4431f0973
{ "blob_id": "fa3b1874d6b510e82309d77a9cdbb1c4431f0973", "branch_name": "refs/heads/master", "committer_date": "2014-12-01T22:05:28", "content_id": "ebe633beeaa6072ea0ec27985b7dcccfae150d22", "detected_licenses": [ "MIT" ], "directory_id": "38fbc81d1da330856b091865a02aecd2905ccce8", "extension": "h", "filename": "stream.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1478, "license": "MIT", "license_type": "permissive", "path": "/include/albase/stream.h", "provenance": "stackv2-0138.json.gz:123184", "repo_name": "derkyjadex/alice", "revision_date": "2014-12-01T22:05:28", "revision_id": "754b124679e3c43649a8a209fc0ce5a226eb3a95", "snapshot_id": "22e43677dd984e818aea4ab7667a173d377366a4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/derkyjadex/alice/754b124679e3c43649a8a209fc0ce5a226eb3a95/include/albase/stream.h", "visit_date": "2021-01-18T16:36:14.194073" }
stackv2
/* * Copyright (c) 2013 James Deery * Released under the MIT license <http://opensource.org/licenses/MIT>. * See COPYING for details. */ #ifndef __ALBASE_STREAM_H__ #define __ALBASE_STREAM_H__ #include <stdio.h> #include <stdbool.h> #include "albase/common.h" typedef enum { AL_OPEN_READ, AL_OPEN_WRITE } AlOpenMode; typedef enum { AL_SEEK_SET = SEEK_SET, AL_SEEK_CUR = SEEK_CUR, AL_SEEK_END = SEEK_END } AlSeekPos; typedef struct AlStream AlStream; struct AlStream { const char *name; AlError (*read)(AlStream *stream, void *ptr, size_t size, size_t *bytesRead); AlError (*write)(AlStream *stream, const void *ptr, size_t size); AlError (*seek)(AlStream *stream, long offset, AlSeekPos whence); AlError (*tell)(AlStream *stream, long *offset); void (*free)(AlStream *stream); }; typedef struct { AlStream base; const void *ptr; const void *cur; const void *end; } AlMemStream; AlError al_stream_init_filename(AlStream **stream, const char *filename, AlOpenMode mode); AlError al_stream_init_file(AlStream **stream, FILE *file, bool closeFile, const char *name); AlError al_stream_init_mem(AlStream **stream, void *ptr, size_t size, bool freePtr, const char *name); AlMemStream al_stream_init_mem_stack(const void *ptr, size_t size, const char *name); void al_stream_free(AlStream *stream); AlError al_stream_read_to_string(AlStream *stream, char **string, size_t *size); AlError al_read_file_to_string(const char *filename, char **string); #endif
2.296875
2
2024-11-18T21:50:42.399779+00:00
2020-04-30T22:29:43
89b5ba9ef0a2d9e9abb75509acc3d6c47142d25c
{ "blob_id": "89b5ba9ef0a2d9e9abb75509acc3d6c47142d25c", "branch_name": "refs/heads/master", "committer_date": "2020-04-30T22:29:43", "content_id": "fa00f758e99d02874db426dbafbe60dcd1fdab7c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "f535fa650c6a2b261b6b14fe0141971e6411017e", "extension": "c", "filename": "neuron.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 260331297, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8400, "license": "Apache-2.0", "license_type": "permissive", "path": "/neuron.c", "provenance": "stackv2-0138.json.gz:123832", "repo_name": "anserion/neuros_v3", "revision_date": "2020-04-30T22:29:43", "revision_id": "c7eaa07ab9e020a2d374aeb7681cff8b6b35dd2c", "snapshot_id": "5839c48e4bc14b471c12f65b57974b835027f45e", "src_encoding": "KOI8-R", "star_events_count": 0, "url": "https://raw.githubusercontent.com/anserion/neuros_v3/c7eaa07ab9e020a2d374aeb7681cff8b6b35dd2c/neuron.c", "visit_date": "2022-05-30T06:28:59.948287" }
stackv2
//neuron.c #include <stdlib.h> #include "defs.h" #include "commutator.h" #include "neuron.h" #include "nweb.h" #include "f.h" #include "alg.h" #include "addr.h" #include "debug.h" void neuron_tick(struct NEURON *nrn) {int i; //проверим наличие нейрона if (nrn==NULL) return; if (nrn->ID<0) return; //если на нулевом входе сигнала нет, то выходим nrn->X[0]=commutator_get(nrn->nweb->comm,nrn->Base+nrn->X_table[0]); if (nrn->X[0]==0) return; //загрузим значения входов нейрона из коммутатора for(i=1;i<=nrn->N;i++) nrn->X[i]=commutator_get(nrn->nweb->comm,nrn->Base+nrn->X_table[i]); //вызываем рабочую функцию нейрона if (nrn->n_f != F_DUMMY) nrn->F(nrn); //активируем модуль обучения нейрона if (nrn->n_alg != ALG_DUMMY) nrn->ALG(nrn); //активируем модуль навигации нейрона if (nrn->n_addr != ADDR_DUMMY) nrn->ADDR(nrn); } void neuron_create(int id, int base, int f, int alg, int addr, int n, int k, int m, int *x_table, double *l_table, int *a_table, struct NWEB *nweb) {struct NEURON *nrn; int i; if (nweb==NULL) return; //проводим проверку параметров нового нейрона if ((id<0)||(id>=nweb->NRN_NUM)) return; if (n<0) n=0; if (n>NRN_MaxN) n=NRN_MaxN; if (k<0) k=0; if (k>NRN_MaxK) k=NRN_MaxK; if (m<0) m=0; if (m>NRN_MaxM) m=NRN_MaxM; //если проверки пройдены, то создаем новый нейрон nrn=(struct NEURON*)malloc(sizeof(struct NEURON)); nrn->ID=id; nrn->Base=base; //задаем номера рабочей функции, модуля обучения и модуля навигации nrn->n_f=f; neuron_connect_f(f,nrn); nrn->n_alg=alg; neuron_connect_alg(alg,nrn); nrn->n_addr=addr; neuron_connect_addr(addr,nrn); nrn->N=n; nrn->K=k; nrn->M=m; nrn->nweb=nweb; //инициализируем внутреннюю память нейрона nrn->X=(double*)malloc((nrn->N+1)*sizeof(double)); nrn->X_table=(int*)malloc((nrn->N+1)*sizeof(int)); nrn->L=(double*)malloc((nrn->K+1)*sizeof(double)); nrn->L_table=(int*)malloc((nrn->K+1)*sizeof(int)); nrn->A=(double*)malloc((nrn->M+1)*sizeof(double)); nrn->A_table=(int*)malloc((nrn->M+1)*sizeof(int)); //инициализируем входы нейрона for(i=0;i<=nrn->N;i++) nrn->X[i]=0; for(i=0;i<=nrn->N;i++) nrn->X_table[i]=x_table[i]; //инициализируем вспомогательные коэффициенты нейрона for(i=0;i<=nrn->K;i++) nrn->L[i]=l_table[i]; for(i=0;i<=nrn->K;i++) nrn->L_table[i]=4;//l_table[i]; //обязательно доработать!!! //инициализируем выходы нейрона for(i=0;i<=nrn->M;i++) nrn->A[i]=0; for(i=0;i<=nrn->M;i++) nrn->A_table[i]=a_table[i]; //заносим созданный нейрон в нейросеть nweb->nrn[id]=nrn; } void neuron_destroy(int id, struct NWEB *nweb) {struct NEURON *nrn; if (nweb==NULL) return; if ((id<0)||(id>=nweb->NRN_NUM)) return; nrn=nweb->nrn[id]; free(nrn->X); free(nrn->X_table); free(nrn->L); free(nrn->L_table); free(nrn->A); free(nrn->A_table); free(nrn); nrn=NULL; } void neuron_clear(struct NEURON *nrn) {int i; //очищаем занятую нейроном память, //если нейрон действительно существовал if (nrn==NULL) return; nrn->ID= -1; nrn->Base=0; nrn->n_f=0; nrn->n_alg=0; nrn->n_addr=0; for(i=0;i<=nrn->N;i++) nrn->X[i]=0; for(i=0;i<=nrn->N;i++) nrn->X_table[i]=4; for(i=0;i<=nrn->K;i++) nrn->L[i]=0; for(i=0;i<=nrn->K;i++) nrn->L_table[i]=4; for(i=0;i<=nrn->M;i++) nrn->A[i]=4; for(i=0;i<=nrn->M;i++) nrn->A_table[i]=4; } void neuron_connect_f(int n_f, struct NEURON *nrn) { switch (n_f) { //типовые функции активации case F_SCALAR: nrn->F=f_scalar; break; case F_RELSCALAR: nrn->F=f_relscalar; break; case F_SIGMA: nrn->F=f_sigma; break; case F_RELSIGMA: nrn->F=f_relsigma; break; case F_TANH: nrn->F=f_tanh; break; case F_RELTANH: nrn->F=f_reltanh; break; case F_STEP: nrn->F=f_step; break; case F_RELSTEP: nrn->F=f_relstep; break; case F_STEPM1: nrn->F=f_stepm1; break; case F_RELSTEPM1: nrn->F=f_relstepm1; break; case F_VEXP: nrn->F=f_vexp; break; case F_RELVEXP: nrn->F=f_relvexp; break; case F_STHSTC: nrn->F=f_sthstc; break; case F_RELSTHSTC: nrn->F=f_relsthstc; break; case F_EUCLID: nrn->F=f_euclid; break; case F_RELEUCLID: nrn->F=f_releuclid; break; case F_NORMA: nrn->F=f_norma; break; case F_MIN: nrn->F=f_min; break; case F_ADDRMIN: nrn->F=f_addrmin; break; case F_MAX: nrn->F=f_max; break; case F_ADDRMAX: nrn->F=f_addrmax; break; case F_REPEAT: nrn->F=f_repeat; break; case F_RELREPEAT: nrn->F=f_relrepeat; break; case F_INTBIN: nrn->F=f_intbin; break; case F_RELINTBIN: nrn->F=f_relintbin; break; case F_BININT: nrn->F=f_binint; break; case F_RELBININT: nrn->F=f_relbinint; break; //логические рабочие функции case F_NOT: nrn->F=f_not; break; case F_AND: nrn->F=f_and; break; case F_OR: nrn->F=f_or; break; case F_XOR: nrn->F=f_xor; break; case F_ANDNOT: nrn->F=f_andnot; break; case F_ORNOT: nrn->F=f_ornot; break; //арифметические рабочие функции case F_ZERO: nrn->F=f_zero; break; case F_ONE: nrn->F=f_one; break; case F_ADD: nrn->F=f_add; break; case F_RELADD: nrn->F=f_reladd; break; case F_SUB: nrn->F=f_sub; break; case F_RELSUB: nrn->F=f_relsub; break; case F_PROD: nrn->F=f_prod; break; case F_RELPROD: nrn->F=f_relprod; break; case F_DIV: nrn->F=f_div; break; case F_RELDIV: nrn->F=f_reldiv; break; case F_MOD: nrn->F=f_mod; break; case F_RELMOD: nrn->F=f_relmod; break; case F_POW: nrn->F=f_pow; break; case F_RELPOW: nrn->F=f_relpow; break; case F_RND: nrn->F=f_rnd; break; case F_TRUNC: nrn->F=f_trunc; break; case F_SQRT: nrn->F=f_sqrt; break; case F_EXP: nrn->F=f_exp; break; case F_LOG: nrn->F=f_log; break; case F_SIN: nrn->F=f_sin; break; case F_COS: nrn->F=f_cos; break; case F_TAN: nrn->F=f_tan; break; case F_ASIN: nrn->F=f_asin; break; case F_ACOS: nrn->F=f_acos; break; case F_ATAN: nrn->F=f_atan; break; case F_ABS: nrn->F=f_abs; break; //сервисные рабочие функции case F_DRV: nrn->F=f_drv; break; case F_DUMMY: nrn->F=f_dummy; break; //функции межсетевого взаимодействия case F_TICK: nrn->F=f_tick; break; case F_TICK1: nrn->F=f_tick1; break; case F_RELTICK1: nrn->F=f_reltick1; break; case F_CLEAR: nrn->F=f_clear; break; case F_INTERREAD: nrn->F=f_interread; break; case F_RELINTERREAD: nrn->F=f_relinterread; break; case F_CRTNW: nrn->F=f_crtnw; break; case F_DELNW: nrn->F=f_delnw; break; default: nrn->F=f_dummy; } } void neuron_connect_alg(int n_alg, struct NEURON *nrn) { switch (n_alg) { case ALG_DUMMY: nrn->ALG=alg_dummy; break; case ALG_IDSET: nrn->ALG=alg_idset; break; case ALG_BASESET: nrn->ALG=alg_baseset; break; case ALG_X0SET: nrn->ALG=alg_x0set; break; case ALG_L0SET: nrn->ALG=alg_l0set; break; case ALG_A0SET: nrn->ALG=alg_a0set; break; case ALG_FUNCSET: nrn->ALG=alg_funcset; break; case ALG_ALGSET: nrn->ALG=alg_algset; break; case ALG_ADDRSET: nrn->ALG=alg_addrset; break; case ALG_NSET: nrn->ALG=alg_nset; break; case ALG_KSET: nrn->ALG=alg_kset; break; case ALG_MSET: nrn->ALG=alg_mset; break; case ALG_XSET: nrn->ALG=alg_xset; break; case ALG_LSET: nrn->ALG=alg_lset; break; case ALG_ASET: nrn->ALG=alg_aset; break; default: nrn->ALG=alg_dummy; } } void neuron_connect_addr(int n_addr, struct NEURON *nrn) { switch (n_addr) { case ADDR_DUMMY: nrn->ADDR=addr_dummy; break; case ADDR_REPEAT: nrn->ADDR=addr_repeat; break; case ADDR_IMDREPEAT: nrn->ADDR=addr_imdrepeat; break; case ADDR_RELREPEAT: nrn->ADDR=addr_relrepeat; break; case ADDR_IMDRELREPEAT: nrn->ADDR=addr_imdrelrepeat; break; case ADDR_OUTSTAR: nrn->ADDR=addr_outstar; break; case ADDR_IMDOUTSTAR: nrn->ADDR=addr_imdoutstar; break; case ADDR_RELOUTSTAR: nrn->ADDR=addr_reloutstar; break; case ADDR_IMDRELOUTSTAR: nrn->ADDR=addr_imdreloutstar; break; case ADDR_INTERNW: nrn->ADDR=addr_internw; break; case ADDR_RELINTERNW: nrn->ADDR=addr_relinternw; break; default: nrn->ADDR=addr_dummy; } }
2.359375
2
2024-11-18T21:50:42.631253+00:00
2021-01-05T20:01:02
83c9f02e3ca076db66dc0c43bf694d8360f2a0a0
{ "blob_id": "83c9f02e3ca076db66dc0c43bf694d8360f2a0a0", "branch_name": "refs/heads/main", "committer_date": "2021-01-05T20:01:02", "content_id": "e2db4d150faa2d7665ab984a922dc74ea515d62d", "detected_licenses": [ "MIT" ], "directory_id": "efee1a4c0f57d0ab27296f8aba0faf58ca0e1f72", "extension": "c", "filename": "bst-util.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 325650984, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4466, "license": "MIT", "license_type": "permissive", "path": "/bst-util.c", "provenance": "stackv2-0138.json.gz:124092", "repo_name": "dbrumbaugh/balanced-tree", "revision_date": "2021-01-05T20:01:02", "revision_id": "d2d2a9fe6a93977f1cef930003efc6310234feee", "snapshot_id": "0b72ab4db7f218b945c7e570d47ead4f8800b9d1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dbrumbaugh/balanced-tree/d2d2a9fe6a93977f1cef930003efc6310234feee/bst-util.c", "visit_date": "2023-02-10T17:12:31.997411" }
stackv2
/* * bst-util.c * Some helper functions for testing bst funtionality. * * Douglas Rumbaugh * 01/01/2020 * */ #include <stdlib.h> #include <stdio.h> #include "bst-util.h" void inorder_traverse(bstnode* head) { if (head == NULL) return; inorder_traverse(head->left); printf("%d ", head->value); inorder_traverse(head->right); } void subtree_traverse(bstnode* head, int* counter) { if (head == NULL) return; subtree_traverse(head->left, counter); (*counter)++; subtree_traverse(head->right, counter); } void subtree_node_counts(bstnode* head, int verbose) { if (head == NULL) return; subtree_node_counts(head->left, verbose); int left_nodes = 0; int right_nodes = 0; subtree_traverse(head->left, &left_nodes); subtree_traverse(head->right, &right_nodes); if (verbose) { printf("For node %d...\n", head->value); printf("\tleft subtree:\t%d\n", left_nodes); printf("\tright subtree:\t%d\n", right_nodes); } assert(abs(left_nodes - right_nodes) <= 1); subtree_node_counts(head->right, verbose); } int calculate_tree_height(bstnode* head) { if (head == NULL) return 0; int left = calculate_tree_height(head->left); int right = calculate_tree_height(head->right); /* printf("(calculate_height) For node %d...\n", head->value); printf("\tLeft Height:\t%d\n", left); printf("\tRight Height:\t%d\n", right); */ return 1 + MAX(left, right); // the height is the max height of its subtrees } void check_strict_balance(bstnode* head, int verbose) { if (head == NULL) return; check_strict_balance(head->left, verbose); int left_height = calculate_tree_height(head->left); int right_height = calculate_tree_height(head->right); if (verbose) { printf("(check balance) For node %d...\n", head->value); printf("\tleft tree:\t%d\n", left_height); printf("\tright tree:\t%d\n", right_height); printf("\tbalance:\t%d\n", right_height - left_height); } assert(abs(left_height - right_height) <= 1); check_strict_balance(head->right, verbose); } void check_rank(bstnode* head, int verbose) { // for each node in the tree, we want to traverse the left subtree and count // up the number of nodes, and then compare the result to the rank of the node. if (head == NULL) return; check_rank(head->left, verbose); int calculated_rank = 1; subtree_traverse(head->left, &calculated_rank); if (verbose) { printf("For node %d\n", head->value); printf("Calculated Rank: %d\nStored Rank: %d\n", calculated_rank, head->rank); } assert(calculated_rank = head->rank); check_rank(head->right, verbose); } void _inorder_tree_to_array(bstnode* head, int* index, int* array, int length) { if (head == NULL) return; _inorder_tree_to_array(head->left, index, array, length); if (*index >= length) { fprintf(stderr, "ERROR: Array index out of range in _inorder_tree_to_array\n"); exit(-1); } array[*index] = head->value; (*index)++; _inorder_tree_to_array(head->right, index, array, length); } int isordered(int* array, int n) { for (int i=1; i<n; i++) { if (array[i] < array[i-1]) { return 0; } } return 1; } void check_bst_ordering(bst* tree) { if (tree->length == 0) { return; } int* elements = malloc(sizeof(int) * tree->length); if (!elements) { fprintf(stderr, "Mallocation error in check_bst_ordering.\n"); exit(-1); } int index = 0; _inorder_tree_to_array(tree->head, &index, elements, tree->length); assert(isordered(elements, tree->length)); free(elements); } void check_bst_indexing(bst* tree) { if (tree->length == 0) { return; } int* elements = malloc(sizeof(int) * tree->length); if (!elements) { fprintf(stderr, "Mallocation error in check_bst_ordering.\n"); exit(-1); } int index = 0; _inorder_tree_to_array(tree->head, &index, elements, tree->length); int* indexed_elements = malloc(sizeof(int) * tree->length); for (int i=1;i<=tree->length;i++) { indexed_elements[i-1] = bst_index(tree, i)->value; } for (int i=0; i<tree->length;i++){ assert(indexed_elements[i] == elements[i]); } free(elements); free(indexed_elements); }
3.21875
3
2024-11-18T21:50:44.192076+00:00
2020-03-09T23:40:01
c360be82ce4fea807323c5d02056ea117bb44ee6
{ "blob_id": "c360be82ce4fea807323c5d02056ea117bb44ee6", "branch_name": "refs/heads/master", "committer_date": "2020-03-09T23:40:01", "content_id": "2c947e35d0458c21f46c32522f612a344b323dc7", "detected_licenses": [ "MIT" ], "directory_id": "c9539c5c3f2a774ff65f2cc1759807c1cd4c1058", "extension": "h", "filename": "array.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 172701991, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1246, "license": "MIT", "license_type": "permissive", "path": "/include/array.h", "provenance": "stackv2-0138.json.gz:124740", "repo_name": "jacorbal/textad", "revision_date": "2020-03-09T23:40:01", "revision_id": "fc547f674397165d4087d2fe263975ef66fb0327", "snapshot_id": "def17324833c92a0d9a0af68cb11815f0907ac63", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jacorbal/textad/fc547f674397165d4087d2fe263975ef66fb0327/include/array.h", "visit_date": "2020-04-27T14:01:45.315686" }
stackv2
/* * Copyright (c) 2019, J. A. Corbal * * THIS MATERIAL IS PROVIDED "AS IS", WITH ABSOLUTELY NO WARRANTY * EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK. * * Permission to use, copy, modify, distribute, and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear in * supporting documentation. No representations are made about the * suitability of this software for any purpose. */ /** * @file array.h * * @brief Array size calculations */ #ifndef ARRAY_H #define ARRAY_H /* Public interface */ /** * @brief Macro that evaluates to the number of elements in an array, * (@c <type>*) */ #define arr_len(arr) (sizeof(arr) / (sizeof(arr)[0])) /** * @brief Macro that evaluates to the number of elementes in an array of * arrays, (@c <type>**), ie, flattening it */ #define darr_len(arr) (sizeof(arr) / (sizeof(arr)[0][0])) /** * @brief Macro that evaluates to the effective number of bytes in an * array of arrays, (@c char**), ie, flattening it */ #define darr_len_str(arr) (darr_len(arr) / 8) #endif /* ARRAY_H */
2.109375
2
2024-11-18T21:50:44.545859+00:00
2020-03-04T12:50:07
bde6932a88b4abff600d489c4ce35bda233de3d9
{ "blob_id": "bde6932a88b4abff600d489c4ce35bda233de3d9", "branch_name": "refs/heads/master", "committer_date": "2020-03-04T12:50:07", "content_id": "0d96db9bcad7b7b5a2858f167c7ef4ad81687725", "detected_licenses": [ "MIT" ], "directory_id": "739bfbbebb73927698a539c6baff822547bf6601", "extension": "c", "filename": "ejercicio4.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 235323151, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 657, "license": "MIT", "license_type": "permissive", "path": "/EjercicioC/ejercicio4.c", "provenance": "stackv2-0138.json.gz:124869", "repo_name": "monicacice/Ejercicios", "revision_date": "2020-03-04T12:50:07", "revision_id": "3fefde384c8a3186a695abd921ef4066df2672e1", "snapshot_id": "30b3375d536b02cdb078159159f807a27c08b73c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/monicacice/Ejercicios/3fefde384c8a3186a695abd921ef4066df2672e1/EjercicioC/ejercicio4.c", "visit_date": "2020-12-18T08:34:05.227375" }
stackv2
#include "stdio.h" #define MAYORIA_EDAD 18 #define EDAD_JUBILACION 67 int main(int argc, char const *argv[]) { int edad = 0; //Declaración e inicialización //int edad; //Declaración //edad = 0 //Inicialización printf("Introduce tu edad"); scanf("%d", &edad); if (edad >= MAYORIA_EDAD) { if (edad >= EDAD_JUBILACION) { printf("Enahorabuena, estas felizmente jubilado"); } else { printf("Eres mayor de edad pero aun no te puedes jubilar"); } } else { printf("Eres menor de edad, (te queda TELA)"); } /* code */ return 0; }
2.75
3
2024-11-18T21:50:46.405240+00:00
2020-07-03T01:31:43
9944e6f4573ace7ce5cd6272ece537efcc5b1a05
{ "blob_id": "9944e6f4573ace7ce5cd6272ece537efcc5b1a05", "branch_name": "refs/heads/master", "committer_date": "2020-07-03T01:31:43", "content_id": "7ae3586e9be85795b7d5b0700901a32e078b9706", "detected_licenses": [ "MIT" ], "directory_id": "fa7541c264a4f1ce16ad7d96477411dd16045fa1", "extension": "c", "filename": "4.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 265076751, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1047, "license": "MIT", "license_type": "permissive", "path": "/1-loops/2020-05-21/4.c", "provenance": "stackv2-0138.json.gz:125129", "repo_name": "mihmilicio/algoritmos-c", "revision_date": "2020-07-03T01:31:43", "revision_id": "0055738c3400f6eb28e87cc5f67ce028aabbfc68", "snapshot_id": "b477c7c74133b3943a7ab4d6f8bfdf70a8277cde", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mihmilicio/algoritmos-c/0055738c3400f6eb28e87cc5f67ce028aabbfc68/1-loops/2020-05-21/4.c", "visit_date": "2022-11-16T06:00:42.014587" }
stackv2
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int cont = 0, contPar = 0, contMaior = 0, soma = 0; int numero1 = -1, input; float media, percentPar, percentMaior; do { printf("Para finalizar, digite um negativo.\n"); printf("Digite um número: "); scanf("%d", &input); if (input >= 0) { cont++; soma += input; if ((input % 2) == 0) { contPar++; } if ((numero1 >= 0) && (input > numero1)) { contMaior++; } if (numero1 == -1) { numero1 = input; } printf("\n"); } } while (input >= 0); media = (float)soma / (float)cont; percentPar = ((float)contPar / (float)cont) * 100.0; percentMaior = ((float)contMaior / (float)cont) * 100.0; system("pause"); system("cls"); printf("--- RESULTADOS ---\n"); printf("Percentual de pares: %.2f%%\n", percentPar); printf("Média dos números: %.2f \n", media); printf("Percentual de números maiores que o primeiro: %.2f%%\n", percentMaior); return 0; }
3.5
4
2024-11-18T21:50:46.959536+00:00
2022-05-04T17:20:32
ae96732bde281e2b26115212f6b8470c4c4eec8d
{ "blob_id": "ae96732bde281e2b26115212f6b8470c4c4eec8d", "branch_name": "refs/heads/master", "committer_date": "2022-05-04T17:20:32", "content_id": "d1a28a4bd1a5d40df8fa29b17c984cfa4dfc9425", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "directory_id": "0d5fb296196a744182980c181beb77944c989434", "extension": "c", "filename": "compare_funcs.c", "fork_events_count": 14, "gha_created_at": "2016-04-20T17:23:12", "gha_event_created_at": "2022-05-04T17:20:33", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 56706556, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4620, "license": "BSD-3-Clause,BSD-2-Clause", "license_type": "permissive", "path": "/src/misc/compare_funcs.c", "provenance": "stackv2-0138.json.gz:125776", "repo_name": "MeshToolkit/MSTK", "revision_date": "2022-05-04T17:20:32", "revision_id": "207c4ea5f4264876d8614a61408235e91ba4ac0a", "snapshot_id": "1c023e030aded109cbcef6a5005aaf72ba67b372", "src_encoding": "UTF-8", "star_events_count": 27, "url": "https://raw.githubusercontent.com/MeshToolkit/MSTK/207c4ea5f4264876d8614a61408235e91ba4ac0a/src/misc/compare_funcs.c", "visit_date": "2022-05-16T21:30:20.583885" }
stackv2
/* Copyright 2019 Triad National Security, LLC. All rights reserved. This file is part of the MSTK project. Please see the license file at the root of this repository or at https://github.com/MeshToolkit/MSTK/blob/master/LICENSE */ #include <stdlib.h> #include "MSTK.h" #include "MSTK_private.h" #ifdef __cplusplus extern "C" { #endif int compareINT(const void *a, const void *b) { return ( *(int*)a - *(int*)b ); } int compareGlobalID(const void *a, const void *b) { return ( MEnt_GlobalID(*(MEntity_ptr*)a) - MEnt_GlobalID(*(MEntity_ptr*)b) ); } int compareID(const void *a, const void *b) { return ( MEnt_ID(*(MEntity_ptr*)a) - MEnt_ID(*(MEntity_ptr*)b) ); } int compareCoorDouble(const void * a, const void * b) { double tol = 1e-12; int i; double *coor1 = (double *)a; double *coor2 = (double *)b; for(i = 0; i < 3; i++) { if ( (coor1[i] - coor2[i]) > tol ) return 1; if ( (coor2[i] - coor1[i]) > tol ) return -1; } return 0; } int compareVertexCoor(const void *a, const void *b) { double coor1[3], coor2[3]; MV_Coords(*(MVertex_ptr*)a, coor1); MV_Coords(*(MVertex_ptr*)b, coor2); return compareCoorDouble(coor1, coor2); } /* compare endpoint global id of an edge */ int compareEdgeINT(const void *a, const void *b) { int *edge1_id = (int*)a; int *edge2_id = (int*)b; int maxgid1 = edge1_id[0]; int mingid1 = edge1_id[1]; int maxgid2 = edge2_id[0]; int mingid2 = edge2_id[1]; int tmp; if(maxgid1 < mingid1) {tmp = maxgid1; maxgid1 = mingid1; mingid1 = tmp;} if(maxgid2 < mingid2) {tmp = maxgid2; maxgid2 = mingid2; mingid2 = tmp;} if(maxgid1 > maxgid2) return 1; if(maxgid1 < maxgid2) return -1; if(mingid1 > mingid2) return 1; if(mingid1 < mingid2) return -1; return 0; } /* compare larger endpoint global id, then smaller endpoint global id */ int compareEdgeID(const void *a, const void *b) { MEdge_ptr me1 = *(MEdge_ptr*)a; MEdge_ptr me2 = *(MEdge_ptr*)b; int maxgid1 = MV_GlobalID(ME_Vertex(me1,0)); int mingid1 = MV_GlobalID(ME_Vertex(me1,1)); int maxgid2 = MV_GlobalID(ME_Vertex(me2,0)); int mingid2 = MV_GlobalID(ME_Vertex(me2,1)); int tmp; if(maxgid1 < mingid1) {tmp = maxgid1; maxgid1 = mingid1; mingid1 = tmp;} if(maxgid2 < mingid2) {tmp = maxgid2; maxgid2 = mingid2; mingid2 = tmp;} if(maxgid1 > maxgid2) return 1; if(maxgid1 < maxgid2) return -1; if(mingid1 > mingid2) return 1; if(mingid1 < mingid2) return -1; return 0; } /* first compare # of vertices, then compare the largest vertex global ID */ int compareFaceINT(const void *a, const void *b) { int *faceid1 = (int*)a, *faceid2 = (int*)b; int nfv1 = faceid1[0], nfv2 = faceid2[0]; int i; if( nfv1 > nfv2 ) return 1; if( nfv1 < nfv2 ) return -1; /* printf("before sort 1: "); for(i = 0; i < nfv1; i++) printf("Face ID: %d \t",faceid1[i+1]); */ qsort(faceid1+1,nfv1,sizeof(int),compareINT); qsort(faceid2+1,nfv2,sizeof(int),compareINT); /* printf("after sort 1: "); for(i = 0; i < nfv1; i++) printf("Face ID: %d \t",faceid1[i+1]); */ for(i = 0; i < nfv1; i++) { if ( faceid1[i+1] > faceid2[i+1] ) return 1; if ( faceid1[i+1] < faceid2[i+1] ) return -1; } return 0; } int compareFaceID(const void *a, const void *b) { MFace_ptr mf1 = *(MFace_ptr*)a, mf2 = *(MFace_ptr*)b; List_ptr mfverts1 = MF_Vertices(mf1,1,0), mfverts2 = MF_Vertices(mf2,1,0); int nfv1 = List_Num_Entries(mfverts1), nfv2 = List_Num_Entries(mfverts2); int i; if( nfv1 > nfv2 ) { List_Delete(mfverts1); List_Delete(mfverts2); return 1; } if( nfv1 < nfv2 ) { List_Delete(mfverts1); List_Delete(mfverts2); return -1; } List_Sort(mfverts1,nfv1,sizeof(MFace_ptr),compareGlobalID); List_Sort(mfverts2,nfv2,sizeof(MFace_ptr),compareGlobalID); for(i = 0; i < nfv1; i++) { if ( MV_GlobalID(List_Entry(mfverts1,i)) > MV_GlobalID(List_Entry(mfverts2,i)) ) { List_Delete(mfverts1); List_Delete(mfverts2); return 1; } if ( MV_GlobalID(List_Entry(mfverts1,i)) < MV_GlobalID(List_Entry(mfverts2,i)) ) { List_Delete(mfverts1); List_Delete(mfverts2); return -1; } } List_Delete(mfverts1); List_Delete(mfverts2); return 0; } int compareValence(const void *a, const void *b) { return ( MV_Num_Edges(*((MVertex_ptr*)a)) - MV_Num_Edges(*((MVertex_ptr*)b)) ); } #ifdef __cplusplus } #endif
2.609375
3
2024-11-18T21:50:47.582717+00:00
2019-12-16T02:56:36
c570e17a30a01f0fe54590487b91903566b500cc
{ "blob_id": "c570e17a30a01f0fe54590487b91903566b500cc", "branch_name": "refs/heads/master", "committer_date": "2019-12-16T02:56:36", "content_id": "fca7fee45df76ba8cf63e749aa646522177e908a", "detected_licenses": [ "CC0-1.0" ], "directory_id": "94d775686571dad021a835fc9a5e77cc9d15245a", "extension": "c", "filename": "SommaMassima.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 227911854, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 474, "license": "CC0-1.0", "license_type": "permissive", "path": "/05-3 - Sottoarray di somma massima/SommaMassima.c", "provenance": "stackv2-0138.json.gz:125905", "repo_name": "alessandro-antonelli/ALL-2014", "revision_date": "2019-12-16T02:56:36", "revision_id": "b28598942e12135386914297fc5c0052d5d279e5", "snapshot_id": "380581760b2734364f9f711a94639f3950758162", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/alessandro-antonelli/ALL-2014/b28598942e12135386914297fc5c0052d5d279e5/05-3 - Sottoarray di somma massima/SommaMassima.c", "visit_date": "2020-11-24T01:49:46.651446" }
stackv2
#include <stdlib.h> #include <stdio.h> int SommaMassima(int* a, int len) { int somma = 0; int sommaMax = 0; int i; for(i=0; i<len; i++) { if(somma < 0) somma = a[i]; else somma = somma + a[i]; if(somma > sommaMax) sommaMax = somma; } return sommaMax; } int main() { int len, i; scanf("%d", &len); int* a = malloc(len * sizeof(int)); for(i=0; i<len; i++) scanf("%d", &a[i]); int somma = SommaMassima(a, len); printf("%d\n", somma); return 0; }
3.4375
3
2024-11-18T21:50:48.048706+00:00
2018-02-15T17:08:24
a96aea8fe8c899ce32e2b8939bcac0fbd5539d58
{ "blob_id": "a96aea8fe8c899ce32e2b8939bcac0fbd5539d58", "branch_name": "refs/heads/master", "committer_date": "2018-02-15T17:08:24", "content_id": "b2fad06862ed226dc7b5026832a22616d1cb61e8", "detected_licenses": [ "Apache-2.0" ], "directory_id": "a20bd0a22427d7f5e1fbdea4a2a267e9f8de23d6", "extension": "c", "filename": "PrintThreeRegionsSudoku.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 121602819, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 26401, "license": "Apache-2.0", "license_type": "permissive", "path": "/PrintThreeRegionsSudoku.c", "provenance": "stackv2-0138.json.gz:126296", "repo_name": "jfourney/ftp-SudokuPuzzle-Solver", "revision_date": "2018-02-15T17:08:24", "revision_id": "d839717c5b452cf978e3f3323bbc4b0d9df1ba3f", "snapshot_id": "a1fd66b7e58282c6137976a73e6bc1fd2fa8b7f6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jfourney/ftp-SudokuPuzzle-Solver/d839717c5b452cf978e3f3323bbc4b0d9df1ba3f/PrintThreeRegionsSudoku.c", "visit_date": "2021-04-29T20:39:54.327690" }
stackv2
/*THIS PROGRAM CREATES OUTPUT FILES OF 450,000 SOLUTIONS EACH, THEN CLOSES, PAUSES, LETS YOU RENAME THE FILE, THEN OPENS THE FILE---REPEATING THE PROCESS OVER AND OVER, FOR MONTHS...... THE FIRST THREE ROWS (REGIONS), ARE FILLED WITH: 123456789, 456789123, 789123456.... THIS PROGRAM FIGURES OUT HOW MANY SOLUTIONS WILL BE HAD, WITH THESE 3 REGIONS FILLED IN... LATER, WE'LL RUN A PROGRAM TO PRINT THE POSSIBLE PERMUTATIONS, OF THESE FIRST THREE REGIONS, AND GIVE US THE COUNT, WHICH I BELIEVE TO BE 9!*6!*(3!^4)= 338,610,585,600..... */ #include <stdio.h> #include <stddef.h> //GLOBAL VARIABLES ................. int multipleTable[81][3]; //[0]-cand, [1]-y co-ord, [2]-x co-ord.... int multAnsTable[9][9]; //holds possible cands for all 81 cells, (between 1-9, for all 81 cells).... int regionalAnswerTable[9][9]; //holds region for each y, x..... struct point { int row; int column; } regionalDispatchTable[9][9]; int sub, errCode; //FUNCTION DECLARATIONS ............. void setupTables (void); void setupMultipleTable (void); void checkMultAnsTable (int y, int x); int main (void); //setupTables Function .................... void setupTables (void) { int x, y, region, a; // Initialize regionalAnswerTable ****************************************** for ( y = 0; y < 9; ++y ) for ( x = 0; x < 9; ++x ) regionalAnswerTable[y][x] = ( 3 * (y / 3)) + (x / 3); // Initialize regionalDispatchTable **************************************** for ( region = 0; region < 9; ++region ) { a = 0; for ( y = 0; y < 9; ++y ) for ( x = 0; x < 9; ++x ) if ( regionalAnswerTable[y][x] == region ) { regionalDispatchTable[region][a].row = y; regionalDispatchTable[region][a].column = x; ++a; } // ends if rAT .......ends for x.... ends for y ............ } // ends for region ........................ return; } //setupMultipleTable Function .............. void setupMultipleTable (void) { int x, y; sub = 0; for ( y = 0; y < 9; ++y ) for ( x = 0; x < 9; ++x, ++sub ) { multipleTable[sub][1] = y; multipleTable[sub][2] = x; } // ends for x ..... ends for y ........... return; } //checkMultAnsTable Function ................ void checkMultAnsTable (int y, int x) { int xx, yy, region, a, r, c; //check row for uniqueness.................... for ( xx = 0; xx < x; ++xx ) { if ( multAnsTable[y][xx] != multAnsTable[y][x] ) continue; ++errCode; return; } // ends for xx................................. //check column for uniqueness.................... for ( yy = 0; yy < y; ++yy ) { if ( multAnsTable[yy][x] != multAnsTable[y][x] ) continue; ++errCode; return; } // ends for yy................................. //check region for uniqueness.................... region = regionalAnswerTable[y][x]; for ( a = 0; a < 9; ++a ) { r = regionalDispatchTable[region][a].row; c = regionalDispatchTable[region][a].column; if ( (r == y) && (c == x) ) break; if ( multAnsTable[r][c] != multAnsTable[y][x] ) continue; ++errCode; return; } // ends for a............. return; } //main Function ......................... int main (void) { int x, y, xx, yy; long long int regCount = 0, billions = 0, printCount = 0; FILE *outputFile; if ( (outputFile = fopen("ThreeRegionsSolutions", "w")) == NULL ) { printf("***OUTPUT FILE -ThreeRegionsSolutions- COULD NOT BE OPENED!!!\n"); system("pause"); return 1; } // ends if output.... printf("THIS PROGRAM WILL TAKE SEVERAL MONTHS TO RUN!!!!\n"); setupTables(); setupMultipleTable(); for ( sub = 0; sub < 9; ++sub ) multAnsTable[0][sub] = (sub + 1); multAnsTable[1][0] = 4; multAnsTable[1][1] = 5; multAnsTable[1][2] = 6; multAnsTable[1][3] = 7; multAnsTable[1][4] = 8; multAnsTable[1][5] = 9; multAnsTable[1][6] = 1; multAnsTable[1][7] = 2; multAnsTable[1][8] = 3; multAnsTable[2][0] = 7; multAnsTable[2][1] = 8; multAnsTable[2][2] = 9; multAnsTable[2][3] = 1; multAnsTable[2][4] = 2; multAnsTable[2][5] = 3; multAnsTable[2][6] = 4; multAnsTable[2][7] = 5; multAnsTable[2][8] = 6; sub = 27; //54 for statements ............................................ for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; ++sub; for ( multipleTable[sub][0] = 1; multipleTable[sub][0] < 10; ++multipleTable[sub][0] ) { y = multipleTable[sub][1]; x = multipleTable[sub][2]; multAnsTable[y][x] = multipleTable[sub][0]; errCode = 0; checkMultAnsTable(y,x); if ( errCode ) continue; //72 for statements ...... //PRINT ANSWER TABLE OF THIS ELEMENT.......... ++printCount; for ( yy = 0; yy < 9; ++yy ) for ( xx = 0; xx < 9; ++xx ) fprintf(outputFile, "%1d", multAnsTable[yy][xx]); if ( printCount == 450000 ) { printCount = 0; fclose(outputFile); printf("END OF ANOTHER 450,000 SOLUTIONS FOR THIS FILE!!!!\n"); printf("RENAME ThreeRegionsSolutions TO ThreeRegionsSolutionsXXXX, THEN PRESS ANY KEY TO CONTINUE!!!\n"); system("pause"); system("pause"); FILE *outputFile; if ( (outputFile = fopen("ThreeRegionsSolutions", "w")) == NULL ) { printf("***OUTPUT FILE -ThreeRegionsSolutions- COULD NOT BE OPENED!!!\n"); system("pause"); return 1; } // ends if output.... } // ends if printCount....... //add to regCount --- check to see if == billion ---- ++regCount; if ( regCount == 1000000000 ) { ++billions; regCount = 0; } // ends if regCount ....... if ( billions < 0 ) { printf("OVERFLOW OF THE NUMBER, NEED HIGHER NUMBERS!!!!\n"); return 0; } } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } --sub; } // EIGHTYONERIGHTBRACKETS // 54 ending brackets for the 81 for statements......... //print the number of possible Sudoku solutions........... printf("THE NUMBER OF POSSIBLE SUDOKU SOLUTIONS FOR THIS PERMUTATION IS: "); printf("%lli%90lli !!!!\n", billions, regCount); printf("THE ACTUAL NUMBER OF POSSIBLE SOLUTIONS, IS THIS NUMBER MULTIPLIED BY THE NUMBER OF \ THREE REGIONS PERMUTATIONS, WHICH I BELIEVE TO BE 338,610,585,600...\n"); system("pause"); system("pause"); system("pause"); return 0; }
2.859375
3
2024-11-18T21:50:48.166634+00:00
2023-07-24T16:08:47
a81e9732120fc704d9f12c8b8d285c4a130f710e
{ "blob_id": "a81e9732120fc704d9f12c8b8d285c4a130f710e", "branch_name": "refs/heads/master", "committer_date": "2023-07-24T16:09:41", "content_id": "e76c9dcf80a450ae46e1d1c9f525df80b4f62cc3", "detected_licenses": [ "MIT" ], "directory_id": "65089dbc386e1184983c15fe3a2282763ae65960", "extension": "c", "filename": "libposix.c", "fork_events_count": 488, "gha_created_at": "2015-08-07T12:41:05", "gha_event_created_at": "2023-05-27T11:08:46", "gha_language": "C", "gha_license_id": "MIT", "github_id": 40359871, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6014, "license": "MIT", "license_type": "permissive", "path": "/gear-lib/libposix/libposix.c", "provenance": "stackv2-0138.json.gz:126555", "repo_name": "gozfree/gear-lib", "revision_date": "2023-07-24T16:08:47", "revision_id": "bffbfd25af4ff7b04ebfafdab391b55270b0273e", "snapshot_id": "9f4db1bce799ded1cf1f3411cb51bdfbcbe7c7bc", "src_encoding": "UTF-8", "star_events_count": 1771, "url": "https://raw.githubusercontent.com/gozfree/gear-lib/bffbfd25af4ff7b04ebfafdab391b55270b0273e/gear-lib/libposix/libposix.c", "visit_date": "2023-08-14T16:01:29.449910" }
stackv2
/****************************************************************************** * Copyright (C) 2014-2020 Zhifeng Gong <[email protected]> * * 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. ******************************************************************************/ #define _CRT_SECURE_NO_WARNINGS /* Disable safety warning for mbstowcs() */ #include "libposix.h" #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <wchar.h> void *memdup(const void *src, size_t len) { void *dst = NULL; if (len == 0) { return NULL; } dst = calloc(1, len); if (LIKELY(dst != NULL)) { memcpy(dst, src, len); } return dst; } struct iovec *iovec_create(size_t len) { struct iovec *vec = calloc(1, sizeof(struct iovec)); if (LIKELY(vec != NULL)) { vec->iov_len = len; vec->iov_base = calloc(1, len); if (UNLIKELY(vec->iov_base == NULL)) { free(vec); vec = NULL; } } return vec; } void iovec_destroy(struct iovec *vec) { if (LIKELY(vec != NULL)) { /* free(NULL) do nop */ free(vec->iov_base); free(vec); } } /** * Fast little endian check * NOTE: not applicable for PDP endian */ bool is_little_endian(void) { uint16_t x = 0x01; return *((uint8_t *) &x); } size_t mbs_to_wcs(const char *str, size_t len, wchar_t *dst, size_t dst_size) { size_t out_len; if (!str) return 0; out_len = dst ? (dst_size - 1) : mbstowcs(NULL, str, len); if (dst) { if (!dst_size) return 0; if (out_len) out_len = mbstowcs(dst, str, out_len + 1); dst[out_len] = 0; } return out_len; } size_t wcs_to_mbs(const wchar_t *str, size_t len, char *dst, size_t dst_size) { size_t out_len; if (!str) return 0; out_len = dst ? (dst_size - 1) : wcstombs(NULL, str, len); if (dst) { if (!dst_size) return 0; if (out_len) out_len = wcstombs(dst, str, out_len + 1); dst[out_len] = 0; } return out_len; } size_t utf8_to_wcs(const char *str, size_t len, wchar_t *dst, size_t dst_size) { size_t in_len; size_t out_len; if (!str) return 0; in_len = len ? len : strlen(str); out_len = dst ? (dst_size - 1) : utf8_to_wchar(str, in_len, NULL, 0, 0); if (dst) { if (!dst_size) return 0; if (out_len) out_len = utf8_to_wchar(str, in_len, dst, out_len + 1, 0); dst[out_len] = 0; } return out_len; } size_t wcs_to_utf8(const wchar_t *str, size_t len, char *dst, size_t dst_size) { size_t in_len; size_t out_len; if (!str) return 0; in_len = (len != 0) ? len : wcslen(str); out_len = dst ? (dst_size - 1) : wchar_to_utf8(str, in_len, NULL, 0, 0); if (dst) { if (!dst_size) return 0; if (out_len) out_len = wchar_to_utf8(str, in_len, dst, out_len + 1, 0); dst[out_len] = 0; } return out_len; } size_t mbs_to_wcs_ptr(const char *str, size_t len, wchar_t **pstr) { if (str) { size_t out_len = mbs_to_wcs(str, len, NULL, 0); *pstr = malloc((out_len + 1) * sizeof(wchar_t)); return mbs_to_wcs(str, len, *pstr, out_len + 1); } else { *pstr = NULL; return 0; } } size_t wcs_to_mbs_ptr(const wchar_t *str, size_t len, char **pstr) { if (str) { size_t out_len = wcs_to_mbs(str, len, NULL, 0); *pstr = malloc((out_len + 1) * sizeof(char)); return wcs_to_mbs(str, len, *pstr, out_len + 1); } else { *pstr = NULL; return 0; } } size_t utf8_to_wcs_ptr(const char *str, size_t len, wchar_t **pstr) { if (str) { size_t out_len = utf8_to_wcs(str, len, NULL, 0); *pstr = malloc((out_len + 1) * sizeof(wchar_t)); return utf8_to_wcs(str, len, *pstr, out_len + 1); } else { *pstr = NULL; return 0; } } size_t wcs_to_utf8_ptr(const wchar_t *str, size_t len, char **pstr) { if (str) { size_t out_len = wcs_to_utf8(str, len, NULL, 0); *pstr = malloc((out_len + 1) * sizeof(char)); return wcs_to_utf8(str, len, *pstr, out_len + 1); } else { *pstr = NULL; return 0; } } size_t utf8_to_mbs_ptr(const char *str, size_t len, char **pstr) { char *dst = NULL; size_t out_len = 0; if (str) { wchar_t *wstr = NULL; size_t wlen = utf8_to_wcs_ptr(str, len, &wstr); out_len = wcs_to_mbs_ptr(wstr, wlen, &dst); free(wstr); } *pstr = dst; return out_len; } size_t mbs_to_utf8_ptr(const char *str, size_t len, char **pstr) { char *dst = NULL; size_t out_len = 0; if (str) { wchar_t *wstr = NULL; size_t wlen = mbs_to_wcs_ptr(str, len, &wstr); out_len = wcs_to_utf8_ptr(wstr, wlen, &dst); free(wstr); } *pstr = dst; return out_len; }
2.328125
2
2024-11-18T21:50:48.229395+00:00
2018-12-01T21:15:44
bcc4f555ec877813681dea3ce568c46dc52a1041
{ "blob_id": "bcc4f555ec877813681dea3ce568c46dc52a1041", "branch_name": "refs/heads/master", "committer_date": "2018-12-01T21:15:44", "content_id": "c804d4008e54ef90a6299d423c7046a53fbf3302", "detected_licenses": [ "MIT" ], "directory_id": "3c038f3de30ce73280fd7a37a01b8257a910cbed", "extension": "c", "filename": "04.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 914, "license": "MIT", "license_type": "permissive", "path": "/Aula00_Conceitos_base/04.c", "provenance": "stackv2-0138.json.gz:126683", "repo_name": "Fabio-Morais/Prog2", "revision_date": "2018-12-01T21:15:44", "revision_id": "583ddb758048231ff29e962fabd277d03175a708", "snapshot_id": "d3f0bac3ad7e0a623b61c102212165deb1cea80a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Fabio-Morais/Prog2/583ddb758048231ff29e962fabd277d03175a708/Aula00_Conceitos_base/04.c", "visit_date": "2021-04-03T09:59:19.075014" }
stackv2
#include <stdio.h> #include <stdlib.h> int ordenado(int src[], int n) { int i, a = src[0]; for (i = 1; i < n; i++) { if (src[i] < a) { return 0; } a = src[i]; } return 1; } int main() { int i, *src, n; printf("Introduza o número de numeros: "); scanf("%d", &n); if (n > 100) { printf("So sao permitidas sequencias ate 100 numeros"); n = 100; } src = (int *) malloc(sizeof(int) * n); for (i = 0; i < n; i++) { printf("Introduza o %d numero: ", i + 1); scanf("%d", &src[i]); } if (ordenado(src, n)) { printf("\nO vetor esta ordenado!\nElementos do vetor por ordem decrescente\n{"); for (i = n - 1; i > 0; i--) { printf("%d,", src[i]); } printf("%d}\n", src[i]); } else { printf("\nO vetor não esta ordenado\n"); } return 0; }
3.640625
4
2024-11-18T21:50:48.557014+00:00
2016-06-07T12:31:58
f62da9eea7dd3fafd8c277f0852274c63417b45b
{ "blob_id": "f62da9eea7dd3fafd8c277f0852274c63417b45b", "branch_name": "refs/heads/master", "committer_date": "2016-06-07T12:31:58", "content_id": "81e215582ed977d99273907297635126a15fd163", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e35ae9a286362316a967b609a917a7a712cd98b8", "extension": "c", "filename": "poppler.c", "fork_events_count": 2, "gha_created_at": "2013-12-05T15:47:32", "gha_event_created_at": "2018-06-13T08:55:51", "gha_language": "C", "gha_license_id": null, "github_id": 14957888, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6129, "license": "Apache-2.0", "license_type": "permissive", "path": "/poppler.c", "provenance": "stackv2-0138.json.gz:127197", "repo_name": "easybiblabs/php-poppler-pdf", "revision_date": "2016-06-07T12:31:58", "revision_id": "fe05f61a3ce544d1d6fcc233ffbcacf2ad3f0a64", "snapshot_id": "0458e0c7e1559d23bf7b795de53327c8c88a224d", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/easybiblabs/php-poppler-pdf/fe05f61a3ce544d1d6fcc233ffbcacf2ad3f0a64/poppler.c", "visit_date": "2021-01-21T04:36:08.463120" }
stackv2
/* php boilerplate */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_poppler.h" /* poppler, etc. */ #include <poppler.h> #include <glib.h> #include <unistd.h> static zend_function_entry poppler_functions[] = { PHP_FE(poppler_pdf_open, NULL) PHP_FE(poppler_pdf_info, NULL) PHP_FE(poppler_pdf_text, NULL) PHP_FE(poppler_pdf_formatted_text, NULL) {NULL, NULL, NULL} }; zend_module_entry poppler_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif PHP_POPPLER_EXTNAME, poppler_functions, PHP_MINIT(poppler), PHP_MSHUTDOWN(poppler), NULL, NULL, NULL, #if ZEND_MODULE_API_NO >= 20010901 PHP_POPPLER_VERSION, #endif STANDARD_MODULE_PROPERTIES }; #ifdef COMPILE_DL_POPPLER ZEND_GET_MODULE(poppler) #endif int le_poppler_document; static void php_poppler_document_free(zend_rsrc_list_entry *rsrc TSRMLS_DC) { PopplerDocument *doc = (PopplerDocument*)rsrc->ptr; if (doc != NULL) { g_object_unref(doc); } } PHP_MINIT_FUNCTION(poppler) { le_poppler_document = zend_register_list_destructors_ex( php_poppler_document_free, NULL, PHP_POPPLER_DOCUMENT_NAME, module_number ); g_type_init(); return SUCCESS; } PHP_MSHUTDOWN_FUNCTION(poppler) { return SUCCESS; } /* main */ void add_assoc_maybe_string(zval *ret, const char *key, char *s) { if (s == NULL) { add_assoc_null(ret, key); } else { add_assoc_string(ret, key, s, 1); } } PHP_FUNCTION(poppler_pdf_open) { char *name; size_t name_len; gchar *uri; PopplerDocument *doc; GError *err = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) { RETURN_NULL(); } { /* file name handling */ /* XXX this is hacky... */ gchar *cwd; gchar *abs_name; cwd = g_get_current_dir(); if (!g_path_is_absolute(name)) { abs_name = g_build_filename(cwd, name, NULL); } else { abs_name = g_build_filename(name, NULL); } gfree(cwd); uri = g_filename_to_uri(abs_name, NULL, NULL); gfree(abs_name); if (uri == NULL) { /* TODO: throw exception? */ RETURN_NULL(); } } doc = poppler_document_new_from_file(uri, NULL, &err); free(uri); if (doc == NULL) { /* TODO: throw exception? */ /* php_printf("ERROR: %s\n", err->message); */ RETURN_NULL(); } ZEND_REGISTER_RESOURCE(return_value, doc, le_poppler_document); } PHP_FUNCTION(poppler_pdf_info) { PopplerDocument *doc; zval *zdoc; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zdoc) == FAILURE) { RETURN_NULL(); } ZEND_FETCH_RESOURCE(doc, PopplerDocument*, &zdoc, -1, PHP_POPPLER_DOCUMENT_NAME, le_poppler_document); array_init(return_value); add_assoc_maybe_string(return_value, "pdf_version", poppler_document_get_pdf_version_string(doc)); add_assoc_maybe_string(return_value, "title", poppler_document_get_title(doc)); add_assoc_maybe_string(return_value, "author", poppler_document_get_author(doc)); add_assoc_maybe_string(return_value, "subject", poppler_document_get_subject(doc)); add_assoc_maybe_string(return_value, "keywords", poppler_document_get_keywords(doc)); add_assoc_maybe_string(return_value, "creator", poppler_document_get_creator(doc)); add_assoc_maybe_string(return_value, "producer", poppler_document_get_producer(doc)); add_assoc_long(return_value, "pages", poppler_document_get_n_pages(doc)); add_assoc_long(return_value, "creation_date", poppler_document_get_creation_date(doc)); add_assoc_long(return_value, "modification_date", poppler_document_get_modification_date(doc)); } PHP_FUNCTION(poppler_pdf_text) { PopplerDocument *doc; PopplerPage *page; long page_i; char *text; size_t textlen; GList *attr_list; zval *zdoc; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &zdoc, &page_i) == FAILURE) { RETURN_NULL(); } ZEND_FETCH_RESOURCE(doc, PopplerDocument*, &zdoc, -1, PHP_POPPLER_DOCUMENT_NAME, le_poppler_document); if (page_i < 0 || page_i >= poppler_document_get_n_pages(doc)) { RETURN_NULL(); } page = poppler_document_get_page(doc, page_i); if (page == NULL) { RETURN_NULL(); } text = poppler_page_get_text(page); g_object_unref(page); RETURN_STRING(text, 1); } PHP_FUNCTION(poppler_pdf_formatted_text) { PopplerDocument *doc; PopplerPage *page; long page_i; char *text; size_t textlen; GList *attr_list; zval *zdoc; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &zdoc, &page_i) == FAILURE) { RETURN_NULL(); } ZEND_FETCH_RESOURCE(doc, PopplerDocument*, &zdoc, -1, PHP_POPPLER_DOCUMENT_NAME, le_poppler_document); if (page_i < 0 || page_i >= poppler_document_get_n_pages(doc)) { RETURN_NULL(); } page = poppler_document_get_page(doc, page_i); if (page == NULL) { RETURN_NULL(); } text = poppler_page_get_text(page); textlen = strlen(text); array_init(return_value); attr_list = poppler_page_get_text_attributes(page); { GList *el; PopplerTextAttributes *attr; zval *text_part; for (el = g_list_first(attr_list); el; el = el->next) { attr = el->data; ALLOC_INIT_ZVAL(text_part); array_init(text_part); add_assoc_stringl(text_part, "text", text + (attr->start_index), (attr->end_index) - (attr->start_index), 1); add_assoc_maybe_string(text_part, "font_name", attr->font_name); add_assoc_long(text_part, "font_size", attr->font_size); add_assoc_bool(text_part, "is_underlined", attr->is_underlined); add_next_index_zval(return_value, text_part); } } poppler_page_free_text_attributes(attr_list); g_object_unref(page); }
2.015625
2
2024-11-18T21:50:48.630568+00:00
2012-06-10T21:07:38
e142a9cec897235ea81744a323778a171898e4ab
{ "blob_id": "e142a9cec897235ea81744a323778a171898e4ab", "branch_name": "refs/heads/master", "committer_date": "2012-06-10T21:07:38", "content_id": "5bc0ff81ae5f617108220feb54facd8ae3377c76", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "60bface2b8a9d9170d1ed514428e07e1e3d1a766", "extension": "c", "filename": "interactive.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4894, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/interactive.c", "provenance": "stackv2-0138.json.gz:127329", "repo_name": "junftnt/whistlepig", "revision_date": "2012-06-10T21:07:38", "revision_id": "55e3c2fd4f91de3690aa867fcb13642b35157c74", "snapshot_id": "4f29e94e302f095d05869b28150463a312e1ea56", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/junftnt/whistlepig/55e3c2fd4f91de3690aa867fcb13642b35157c74/interactive.c", "visit_date": "2020-07-19T10:55:21.320739" }
stackv2
#include <inttypes.h> #include <stdio.h> #include <ctype.h> #include "whistlepig.h" #include "timer.h" typedef struct offset { long start_offset; long end_offset; } offset; static void make_lowercase(char* c, int len) { for(int i = 0; i < len; i++) c[i] = tolower(c[i]); } // map of docids into start/end offsets pairs KHASH_MAP_INIT_INT64(offsets, offset); static khash_t(offsets)* load_offsets(const char* base_path) { char path[1024]; snprintf(path, 1024, "%s.of", base_path); FILE* f = fopen(path, "r"); if(f == NULL) { fprintf(stderr, "cannot read %s, ignoring\n", path); return NULL; } khash_t(offsets)* h = kh_init(offsets); uint64_t doc_id; while(!feof(f)) { offset o; size_t read; read = fread(&doc_id, sizeof(doc_id), 1, f); if(read == 1) read = fread(&o.start_offset, sizeof(long), 1, f); if(read == 1) read = fread(&o.end_offset, sizeof(long), 1, f); if(read == 1) { int ret; khiter_t k = kh_put(offsets, h, doc_id, &ret); if(!ret) kh_del(offsets, h, k); kh_value(h, k) = o; } else break; } printf("loaded %d offsets from %s. last was %"PRIu64"\n", kh_size(h), path, doc_id); return h; } #define RESULTS_TO_SHOW 3 #define RESULT_SNIPPETS_TO_SHOW 3 #define MAX_SNIPPET_DOC_SIZE 64*1024 #define FIELD_NAME "body" #define OFFSET_PADDING 100 int main(int argc, char* argv[]) { wp_index* index; wp_error* e; khash_t(offsets)* offsets; if((argc < 2) || (argc > 3)) { fprintf(stderr, "Usage: %s <index basepath> [corpus path]\n", argv[0]); return -1; } offsets = load_offsets(argv[1]); DIE_IF_ERROR(wp_index_load(&index, argv[1])); //DIE_IF_ERROR(wp_index_dumpinfo(index, stdout)); FILE* corpus = NULL; if(argc == 3) corpus = fopen(argv[2], "r"); while(1) { char input[1024], output[1024]; uint64_t results[RESULTS_TO_SHOW]; wp_query* query; uint32_t total_num_results; TIMER(query); #define HANDLE_ERROR(v) e = v; if(e != NULL) { PRINT_ERROR(e, stdout); wp_error_free(e); continue; } printf("query: "); fflush(stdout); input[0] = 0; if(fgets(input, 1024, stdin) == NULL) break; if(input[0] == '\0') break; //make_lowercase(input, strlen(input)); HANDLE_ERROR(wp_query_parse(input, FIELD_NAME, &query)); if(query == NULL) continue; wp_query_to_s(query, 1024, output); printf("performing search: %s\n", output); RESET_TIMER(query); HANDLE_ERROR(wp_index_count_results(index, query, &total_num_results)); MARK_TIMER(query); printf("found %d results in %.1fms\n", total_num_results, (float)TIMER_MS(query)); if(total_num_results > 0) { uint32_t num_results; RESET_TIMER(query); HANDLE_ERROR(wp_index_setup_query(index, query)); HANDLE_ERROR(wp_index_run_query(index, query, RESULTS_TO_SHOW, &num_results, results)); HANDLE_ERROR(wp_index_teardown_query(index, query)); MARK_TIMER(query); printf("retrieved first %d results in %.1fms\n", num_results, (float)TIMER_MS(query)); for(unsigned int i = 0; i < num_results; i++) { //if((unsigned int)argc > i + 1) printf("doc %u -> %s", results[i].doc_id, argv[results[i].doc_id]); //else printf("doc %u", results[i].doc_id); printf("found doc %"PRIu64"\n", results[i]); if(offsets && corpus) { khiter_t k = kh_get(offsets, offsets, results[i]); if(k != kh_end(offsets)) { char buf[MAX_SNIPPET_DOC_SIZE]; uint32_t num_snippets; pos_t start_offsets[RESULT_SNIPPETS_TO_SHOW]; pos_t end_offsets[RESULT_SNIPPETS_TO_SHOW]; offset o; o = kh_value(offsets, k); fseek(corpus, o.start_offset, SEEK_SET); size_t size = o.end_offset - o.start_offset; if(size > MAX_SNIPPET_DOC_SIZE) size = MAX_SNIPPET_DOC_SIZE; size_t len = fread(buf, sizeof(char), size, corpus); buf[len] = '\0'; make_lowercase(buf, len); DIE_IF_ERROR(wp_snippetize_string(query, FIELD_NAME, buf, RESULT_SNIPPETS_TO_SHOW, &num_snippets, start_offsets, end_offsets)); printf("found %d occurrences within this doc\n", num_snippets); //printf(">> [%s] (%d)\n", buf, len); for(uint32_t j = 0; j < num_snippets; j++) { pos_t start = start_offsets[j] < OFFSET_PADDING ? 0 : (start_offsets[j] - OFFSET_PADDING); pos_t end = end_offsets[j] > (len - OFFSET_PADDING) ? len : end_offsets[j] + OFFSET_PADDING; char hack = buf[end]; buf[end] = '\0'; printf("| %s\n", &buf[start]); buf[end] = hack; } } printf("\n"); } } printf("\n"); } wp_query_free(query); printf("\n"); } DIE_IF_ERROR(wp_index_free(index)); return 0; }
2.46875
2
2024-11-18T21:50:49.111581+00:00
2023-08-13T17:11:39
f7326301c1cbda196b39aa86bd8ba9bba639177f
{ "blob_id": "f7326301c1cbda196b39aa86bd8ba9bba639177f", "branch_name": "refs/heads/master", "committer_date": "2023-08-13T17:11:39", "content_id": "a9fc052105d680e3e2a7fee6409f4ea439c33b85", "detected_licenses": [ "MIT" ], "directory_id": "40eadff029ed08d1c01ee93a735c1b46afca5c19", "extension": "c", "filename": "phashtable.c", "fork_events_count": 81, "gha_created_at": "2015-07-10T21:38:46", "gha_event_created_at": "2023-07-02T16:27:53", "gha_language": "C", "gha_license_id": "MIT", "github_id": 38903208, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5845, "license": "MIT", "license_type": "permissive", "path": "/src/phashtable.c", "provenance": "stackv2-0138.json.gz:127587", "repo_name": "saprykin/plibsys", "revision_date": "2023-08-13T17:11:39", "revision_id": "487bfd45a5b496693e07d6e76840951279a031b1", "snapshot_id": "59c5be91900e87e2606447c60de9d3ad9b699dbf", "src_encoding": "UTF-8", "star_events_count": 624, "url": "https://raw.githubusercontent.com/saprykin/plibsys/487bfd45a5b496693e07d6e76840951279a031b1/src/phashtable.c", "visit_date": "2023-08-17T00:16:48.121274" }
stackv2
/* * The MIT License * * Copyright (C) 2010-2019 Alexander Saprykin <[email protected]> * * 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. */ /* Hash table organized like this: table[hash key]->[list with values] * Note: this implementation is not intended to use on huge loads */ #include "pmem.h" #include "phashtable.h" #include <stdlib.h> typedef struct PHashTableNode_ PHashTableNode; struct PHashTableNode_ { PHashTableNode *next; ppointer key; ppointer value; }; struct PHashTable_ { PHashTableNode **table; psize size; }; /* Size of unique hash keys in hash table */ #define P_HASH_TABLE_SIZE 101 static puint pp_hash_table_calc_hash (pconstpointer pointer, psize modulo); static PHashTableNode * pp_hash_table_find_node (const PHashTable *table, pconstpointer key, puint hash); static puint pp_hash_table_calc_hash (pconstpointer pointer, psize modulo) { /* As simple as we can :) */ return (puint) (((psize) (P_POINTER_TO_INT (pointer) + 37)) % modulo); } static PHashTableNode * pp_hash_table_find_node (const PHashTable *table, pconstpointer key, puint hash) { PHashTableNode *ret; for (ret = table->table[hash]; ret != NULL; ret = ret->next) if (ret->key == key) return ret; return NULL; } P_LIB_API PHashTable * p_hash_table_new (void) { PHashTable *ret; if (P_UNLIKELY ((ret = p_malloc0 (sizeof (PHashTable))) == NULL)) { P_ERROR ("PHashTable::p_hash_table_new: failed(1) to allocate memory"); return NULL; } if (P_UNLIKELY ((ret->table = p_malloc0 (P_HASH_TABLE_SIZE * sizeof (PHashTableNode *))) == NULL)) { P_ERROR ("PHashTable::p_hash_table_new: failed(2) to allocate memory"); p_free (ret); return NULL; } ret->size = P_HASH_TABLE_SIZE; return ret; } P_LIB_API void p_hash_table_insert (PHashTable *table, ppointer key, ppointer value) { PHashTableNode *node; puint hash; if (P_UNLIKELY (table == NULL)) return; hash = pp_hash_table_calc_hash (key, table->size); if ((node = pp_hash_table_find_node (table, key, hash)) == NULL) { if (P_UNLIKELY ((node = p_malloc0 (sizeof (PHashTableNode))) == NULL)) { P_ERROR ("PHashTable::p_hash_table_insert: failed to allocate memory"); return; } /* Insert a new node in front of others */ node->key = key; node->value = value; node->next = table->table[hash]; table->table[hash] = node; } else node->value = value; } P_LIB_API ppointer p_hash_table_lookup (const PHashTable *table, pconstpointer key) { PHashTableNode *node; puint hash; if (P_UNLIKELY (table == NULL)) return NULL; hash = pp_hash_table_calc_hash (key, table->size); return ((node = pp_hash_table_find_node (table, key, hash)) == NULL) ? (ppointer) (-1) : node->value; } P_LIB_API PList * p_hash_table_keys (const PHashTable *table) { PList *ret = NULL; PHashTableNode *node; puint i; if (P_UNLIKELY (table == NULL)) return NULL; for (i = 0; i < table->size; ++i) for (node = table->table[i]; node != NULL; node = node->next) ret = p_list_append (ret, node->key); return ret; } P_LIB_API PList * p_hash_table_values (const PHashTable *table) { PList *ret = NULL; PHashTableNode *node; puint i; if (P_UNLIKELY (table == NULL)) return NULL; for (i = 0; i < table->size; ++i) for (node = table->table[i]; node != NULL; node = node->next) ret = p_list_append (ret, node->value); return ret; } P_LIB_API void p_hash_table_free (PHashTable *table) { PHashTableNode *node, *next_node; puint i; if (P_UNLIKELY (table == NULL)) return; for (i = 0; i < table->size; ++i) for (node = table->table[i]; node != NULL; ) { next_node = node->next; p_free (node); node = next_node; } p_free (table->table); p_free (table); } P_LIB_API void p_hash_table_remove (PHashTable *table, pconstpointer key) { PHashTableNode *node, *prev_node; puint hash; if (P_UNLIKELY (table == NULL)) return; hash = pp_hash_table_calc_hash (key, table->size); if (pp_hash_table_find_node (table, key, hash) != NULL) { node = table->table[hash]; prev_node = NULL; while (node != NULL) { if (node->key == key) { if (prev_node == NULL) table->table[hash] = node->next; else prev_node->next = node->next; p_free (node); break; } else { prev_node = node; node = node->next; } } } } P_LIB_API PList * p_hash_table_lookup_by_value (const PHashTable *table, pconstpointer val, PCompareFunc func) { PList *ret = NULL; PHashTableNode *node; puint i; pboolean res; if (P_UNLIKELY (table == NULL)) return NULL; for (i = 0; i < table->size; ++i) for (node = table->table[i]; node != NULL; node = node->next) { if (func == NULL) res = (node->value == val); else res = (func (node->value, val) == 0); if (res) ret = p_list_append (ret, node->key); } return ret; }
2.515625
3
2024-11-18T21:50:49.436623+00:00
2016-04-04T16:53:55
a40101f1c097ef1beb48526a54785a357249dd82
{ "blob_id": "a40101f1c097ef1beb48526a54785a357249dd82", "branch_name": "refs/heads/master", "committer_date": "2016-04-04T16:53:55", "content_id": "dc63ad6715ba2d51cdfb0b8ac5e8fd4d74cefd38", "detected_licenses": [ "Artistic-2.0" ], "directory_id": "6bb0b91ccd4c75f0be961018ae82fd742907f4d5", "extension": "c", "filename": "root.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 55249643, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 753, "license": "Artistic-2.0", "license_type": "permissive", "path": "/codebox/root.c", "provenance": "stackv2-0138.json.gz:127975", "repo_name": "buribu/sources", "revision_date": "2016-04-04T16:53:55", "revision_id": "e00ebf7305a3741195e48070b95270682cfd4008", "snapshot_id": "2662bfae687846f5b386981aef93fc3ac19f7247", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/buribu/sources/e00ebf7305a3741195e48070b95270682cfd4008/codebox/root.c", "visit_date": "2021-01-10T12:56:55.760077" }
stackv2
//Calculation of Roots of Quadratic Equation #include <stdio.h> #include <math.h> int main() { float a, b, c, determinant, r1,r2, real, imag; printf("Enter coefficients a, b and c: "); scanf("%f%f%f",&a,&b,&c); determinant=b*b-4*a*c; if (determinant>0) { r1= (-b+sqrt(determinant))/(2*a); r2= (-b-sqrt(determinant))/(2*a); printf("Roots are: %.2f and %.2f",r1 , r2); } else if (determinant==0) { r1 = r2 = -b/(2*a); printf("Roots are: %.2f and %.2f", r1, r2); } else { real= -b/(2*a); imag = sqrt(-determinant)/(2*a); printf("Roots are: %.2f+%.2fi and %.2f-%.2fi", real, imag, real, imag); } return 0; } //sent via Codebox - A quick reference app for the most common programming problems. //http://goo.gl/mq11jY
3.296875
3
2024-11-18T21:50:50.372868+00:00
2021-11-11T19:45:54
404bad2154033dc1b9184af359bcd360b9cc9ac9
{ "blob_id": "404bad2154033dc1b9184af359bcd360b9cc9ac9", "branch_name": "refs/heads/master", "committer_date": "2021-11-11T19:45:54", "content_id": "eba0dd9223c53c497a481c1d7b9f2a0ade3a2b47", "detected_licenses": [ "MIT" ], "directory_id": "8c8405e3bc6aa298afe8cb63239ac519b5f6c300", "extension": "c", "filename": "tutorial.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 25258696, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1385, "license": "MIT", "license_type": "permissive", "path": "/Drivers/ASYNC Drivers/windows/examples/tutorial.c", "provenance": "stackv2-0138.json.gz:128627", "repo_name": "commtech/fastcom_cd", "revision_date": "2021-11-11T19:45:54", "revision_id": "e3e2049b49b02c5bdfa0718ea3812d290b7d7c48", "snapshot_id": "beeb039e2776934c26be7c2c73606cc0eed51de1", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/commtech/fastcom_cd/e3e2049b49b02c5bdfa0718ea3812d290b7d7c48/Drivers/ASYNC Drivers/windows/examples/tutorial.c", "visit_date": "2021-11-23T14:36:25.182385" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <Windows.h> int main(void) { HANDLE h = 0; DWORD tmp; char odata[] = "Hello world!"; char idata[20]; DCB mdcb; COMMTIMEOUTS cto; /* Open port 0 in a blocking IO mode */ h = CreateFile("\\\\.\\COM3", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (h == INVALID_HANDLE_VALUE) { fprintf(stderr, "CreateFile failed with %d\n", GetLastError()); return EXIT_FAILURE; } memset(&mdcb, 0, sizeof(mdcb)); memset(&cto, 0, sizeof(cto)); if (BuildCommDCB("baud=115200 parity=N data=8 stop=1", &mdcb) == 0) { fprintf(stdout, "BuildCommDCB failed with %d\n", GetLastError()); return EXIT_FAILURE; } cto.ReadIntervalTimeout = 1; if (SetCommState(h, &mdcb) == FALSE) { fprintf (stderr, "SetCommState failed with %d\n", GetLastError()); return EXIT_FAILURE; } if (SetCommTimeouts(h, &cto) == FALSE) { fprintf(stdout, "SetCommTimeouts failed with %d\n", GetLastError()); return EXIT_FAILURE; } PurgeComm(h, PURGE_TXCLEAR | PURGE_RXCLEAR); /* Send "Hello world!" text */ WriteFile(h, odata, sizeof(odata), &tmp, NULL); /* Read the data back in (with our loopback connector) */ ReadFile(h, idata, sizeof(idata), &tmp, NULL); fprintf(stdout, "%s\n", idata); CloseHandle(h); return EXIT_SUCCESS; }
2.625
3
2024-11-18T21:50:50.896066+00:00
2021-01-15T18:42:36
28de2dafc97e93183860b351da5b2a5c9f6e572b
{ "blob_id": "28de2dafc97e93183860b351da5b2a5c9f6e572b", "branch_name": "refs/heads/main", "committer_date": "2021-01-15T18:42:36", "content_id": "e8d97a33e07d50e75b530689bf3544174a717499", "detected_licenses": [ "MIT" ], "directory_id": "16003c147c2b32fd0fa8a03adb52f0603a1900be", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 329992666, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 425, "license": "MIT", "license_type": "permissive", "path": "/t7_monikerta/main.c", "provenance": "stackv2-0138.json.gz:128890", "repo_name": "pepsifire/C-Perusteet", "revision_date": "2021-01-15T18:42:36", "revision_id": "2e836761f14d2ad0124eee7be1ea5b347607072d", "snapshot_id": "1a632993a1f5c1ca83ebf0fbfcb53d75d56875b2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/pepsifire/C-Perusteet/2e836761f14d2ad0124eee7be1ea5b347607072d/t7_monikerta/main.c", "visit_date": "2023-02-17T12:21:20.062533" }
stackv2
#include <stdio.h> #include <stdlib.h> int main() { int luku1, luku2; scanf("%d %d",&luku1,&luku2); if(luku1 == 0 || luku2 == 0) { printf("Nollalla ei saa jakaa!\n"); return 0; } if ( luku1 % luku2 == 0) { printf("Luku %d on luvun %d monikerta.", luku1,luku2); } else { printf("Luku %d ei ole luvun %d monikerta.",luku1,luku2); } }
2.625
3
2024-11-18T21:50:51.310199+00:00
2023-07-20T16:50:46
d0ebd1f1f8173eda14a0379faf8b7f02a3323b86
{ "blob_id": "d0ebd1f1f8173eda14a0379faf8b7f02a3323b86", "branch_name": "refs/heads/main", "committer_date": "2023-07-20T16:50:46", "content_id": "fb3f4c662b743e322733637fbde55082965b65b5", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "505585f1d89447adea3f9519f12255602acdb1b2", "extension": "c", "filename": "cvsDiurnal_FSA_kry.c", "fork_events_count": 120, "gha_created_at": "2017-10-05T17:20:03", "gha_event_created_at": "2023-09-14T20:38:05", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 105918649, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 30141, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/examples/cvodes/serial/cvsDiurnal_FSA_kry.c", "provenance": "stackv2-0138.json.gz:129148", "repo_name": "LLNL/sundials", "revision_date": "2023-07-20T16:50:46", "revision_id": "1ea097bb3bce207335ac35f0b5e78df5d71c6409", "snapshot_id": "11a879f8c8e7a5e40d78d13d0f9baed04d37a280", "src_encoding": "UTF-8", "star_events_count": 396, "url": "https://raw.githubusercontent.com/LLNL/sundials/1ea097bb3bce207335ac35f0b5e78df5d71c6409/examples/cvodes/serial/cvsDiurnal_FSA_kry.c", "visit_date": "2023-08-31T12:36:23.500757" }
stackv2
/* ----------------------------------------------------------------- * Programmer(s): Scott D. Cohen and Alan C. Hindmarsh and * Radu Serban @ LLNL * ----------------------------------------------------------------- * SUNDIALS Copyright Start * Copyright (c) 2002-2023, Lawrence Livermore National Security * and Southern Methodist University. * All rights reserved. * * See the top-level LICENSE and NOTICE files for details. * * SPDX-License-Identifier: BSD-3-Clause * SUNDIALS Copyright End * ----------------------------------------------------------------- * Example problem: * * An ODE system is generated from the following 2-species diurnal * kinetics advection-diffusion PDE system in 2 space dimensions: * * dc(i)/dt = Kh*(d/dx)^2 c(i) + V*dc(i)/dx + (d/dz)(Kv(z)*dc(i)/dz) * + Ri(c1,c2,t) for i = 1,2, where * R1(c1,c2,t) = -q1*c1*c3 - q2*c1*c2 + 2*q3(t)*c3 + q4(t)*c2 , * R2(c1,c2,t) = q1*c1*c3 - q2*c1*c2 - q4(t)*c2 , * Kv(z) = Kv0*exp(z/5) , * Kh, V, Kv0, q1, q2, and c3 are constants, and q3(t) and q4(t) * vary diurnally. The problem is posed on the square * 0 <= x <= 20, 30 <= z <= 50 (all in km), * with homogeneous Neumann boundary conditions, and for time t in * 0 <= t <= 86400 sec (1 day). * The PDE system is treated by central differences on a uniform * 10 x 10 mesh, with simple polynomial initial profiles. * The problem is solved with CVODES, with the BDF/GMRES method * (i.e. using the SUNLinSol_SPGMR linear solver) and the block-diagonal * part of the Newton matrix as a left preconditioner. A copy of * the block-diagonal part of the Jacobian is saved and * conditionally reused within the Precond routine. * * Optionally, CVODES can compute sensitivities with respect to the * problem parameters q1 and q2. * Any of three sensitivity methods (SIMULTANEOUS, STAGGERED, and * STAGGERED1) can be used and sensitivities may be included in the * error test or not (error control set on FULL or PARTIAL, * respectively). * * Execution: * * If no sensitivities are desired: * % cvsDiurnal_FSA_kry -nosensi * If sensitivities are to be computed: * % cvsDiurnal_FSA_kry -sensi sensi_meth err_con * where sensi_meth is one of {sim, stg, stg1} and err_con is one of * {t, f}. * -----------------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <cvodes/cvodes.h> /* main CVODES header file */ #include <nvector/nvector_serial.h> /* access to serial N_Vector */ #include <sunlinsol/sunlinsol_spgmr.h> /* access to SPGMR SUNLinearSolver */ #include <sundials/sundials_dense.h> /* use generic dense solver in precond. */ #include <sundials/sundials_types.h> /* defs. of realtype, sunindextype */ /* helpful macros */ #ifndef SQR #define SQR(A) ((A)*(A)) #endif /* Problem Constants */ #define NUM_SPECIES 2 /* number of species */ #define C1_SCALE RCONST(1.0e6) /* coefficients in initial profiles */ #define C2_SCALE RCONST(1.0e12) #define T0 RCONST(0.0) /* initial time */ #define NOUT 12 /* number of output times */ #define TWOHR RCONST(7200.0) /* number of seconds in two hours */ #define HALFDAY RCONST(4.32e4) /* number of seconds in a half day */ #define PI RCONST(3.1415926535898) /* pi */ #define XMIN RCONST(0.0) /* grid boundaries in x */ #define XMAX RCONST(20.0) #define ZMIN RCONST(30.0) /* grid boundaries in z */ #define ZMAX RCONST(50.0) #define XMID RCONST(10.0) /* grid midpoints in x,z */ #define ZMID RCONST(40.0) #define MX 15 /* MX = number of x mesh points */ #define MZ 15 /* MZ = number of z mesh points */ #define NSMX NUM_SPECIES*MX /* NSMX = NUM_SPECIES*MX */ #define MM (MX*MZ) /* MM = MX*MZ */ /* CVodeInit Constants */ #define RTOL RCONST(1.0e-5) /* scalar relative tolerance */ #define FLOOR RCONST(100.0) /* value of C1 or C2 at which tolerances */ /* change from relative to absolute */ #define ATOL (RTOL*FLOOR) /* scalar absolute tolerance */ #define NEQ (NUM_SPECIES*MM) /* NEQ = number of equations */ /* Sensitivity Constants */ #define NP 8 #define NS 2 #define ZERO RCONST(0.0) #define ONE RCONST(1.0) /* User-defined vector and matrix accessor macros: IJKth, IJth */ /* IJKth is defined in order to isolate the translation from the mathematical 3-dimensional structure of the dependent variable vector to the underlying 1-dimensional storage. IJth is defined in order to write code which indexes into small dense matrices with a (row,column) pair, where 1 <= row, column <= NUM_SPECIES. IJKth(vdata,i,j,k) references the element in the vdata array for species i at mesh point (j,k), where 1 <= i <= NUM_SPECIES, 0 <= j <= MX-1, 0 <= k <= MZ-1. The vdata array is obtained via the call vdata = N_VGetArrayPointer(v), where v is an N_Vector. For each mesh point (j,k), the elements for species i and i+1 are contiguous within vdata. IJth(a,i,j) references the (i,j)th entry of the small matrix realtype **a, where 1 <= i,j <= NUM_SPECIES. The small matrix routines in dense.h work with matrices stored by column in a 2-dimensional array. In C, arrays are indexed starting at 0, not 1. */ #define IJKth(vdata,i,j,k) (vdata[i-1 + (j)*NUM_SPECIES + (k)*NSMX]) #define IJth(a,i,j) (a[j-1][i-1]) /* Type : UserData contains preconditioner blocks, pivot arrays, problem parameters, and problem constants */ typedef struct { realtype *p; realtype **P[MX][MZ], **Jbd[MX][MZ]; sunindextype *pivot[MX][MZ]; realtype q4, om, dx, dz, hdco, haco, vdco; } *UserData; /* Prototypes of user-supplied functions */ static int f(realtype t, N_Vector y, N_Vector ydot, void *user_data); static int Precond(realtype tn, N_Vector y, N_Vector fy, booleantype jok, booleantype *jcurPtr, realtype gamma, void *user_data); static int PSolve(realtype tn, N_Vector y, N_Vector fy, N_Vector r, N_Vector z, realtype gamma, realtype delta, int lr, void *user_data); /* Prototypes of private functions */ static void ProcessArgs(int argc, char *argv[], booleantype *sensi, int *sensi_meth, booleantype *err_con); static void WrongArgs(char *name); static UserData AllocUserData(void); static void InitUserData(UserData data); static void FreeUserData(UserData data); static void SetInitialProfiles(N_Vector y, realtype dx, realtype dz); static void PrintOutput(void *cvode_mem, realtype t, N_Vector y); static void PrintOutputS(N_Vector *uS); static void PrintFinalStats(void *cvode_mem, booleantype sensi, booleantype err_con, int sensi_meth); static int check_retval(void *returnvalue, const char *funcname, int opt); /* *-------------------------------------------------------------------- * MAIN PROGRAM *-------------------------------------------------------------------- */ int main(int argc, char *argv[]) { SUNContext sunctx; void *cvode_mem; SUNLinearSolver LS; UserData data; realtype abstol, reltol, t, tout; N_Vector y; int iout, retval; realtype *pbar; int is, *plist; N_Vector *uS; booleantype sensi, err_con; int sensi_meth; pbar = NULL; plist = NULL; uS = NULL; y = NULL; data = NULL; cvode_mem = NULL; LS = NULL; /* Process arguments */ ProcessArgs(argc, argv, &sensi, &sensi_meth, &err_con); /* Problem parameters */ data = AllocUserData(); if(check_retval((void *)data, "AllocUserData", 2)) return(1); InitUserData(data); /* Create the SUNDIALS simulation context that all SUNDIALS objects require */ retval = SUNContext_Create(NULL, &sunctx); if (check_retval(&retval, "SUNContext_Create", 1)) return(1); /* Initial states */ y = N_VNew_Serial(NEQ, sunctx); if(check_retval((void *)y, "N_VNew_Serial", 0)) return(1); SetInitialProfiles(y, data->dx, data->dz); /* Tolerances */ abstol=ATOL; reltol=RTOL; /* Create CVODES object */ cvode_mem = CVodeCreate(CV_BDF, sunctx); if(check_retval((void *)cvode_mem, "CVodeCreate", 0)) return(1); retval = CVodeSetUserData(cvode_mem, data); if(check_retval(&retval, "CVodeSetUserData", 1)) return(1); retval = CVodeSetMaxNumSteps(cvode_mem, 2000); if(check_retval(&retval, "CVodeSetMaxNumSteps", 1)) return(1); /* Allocate CVODES memory */ retval = CVodeInit(cvode_mem, f, T0, y); if(check_retval(&retval, "CVodeInit", 1)) return(1); retval = CVodeSStolerances(cvode_mem, reltol, abstol); if(check_retval(&retval, "CVodeSStolerances", 1)) return(1); /* Create the SUNLinSol_SPGMR linear solver with left preconditioning and the default Krylov dimension */ LS = SUNLinSol_SPGMR(y, SUN_PREC_LEFT, 0, sunctx); if(check_retval((void *)LS, "SUNLinSol_SPGMR", 0)) return(1); /* Attach the linear sovler */ retval = CVodeSetLinearSolver(cvode_mem, LS, NULL); if (check_retval(&retval, "CVodeSetLinearSolver", 1)) return 1; /* Set the preconditioner solve and setup functions */ retval = CVodeSetPreconditioner(cvode_mem, Precond, PSolve); if(check_retval(&retval, "CVodeSetPreconditioner", 1)) return(1); printf("\n2-species diurnal advection-diffusion problem\n"); /* Forward sensitivity analysis */ if(sensi) { plist = (int *) malloc(NS * sizeof(int)); if(check_retval((void *)plist, "malloc", 2)) return(1); for(is=0; is<NS; is++) plist[is] = is; pbar = (realtype *) malloc(NS * sizeof(realtype)); if(check_retval((void *)pbar, "malloc", 2)) return(1); for(is=0; is<NS; is++) pbar[is] = data->p[plist[is]]; uS = N_VCloneVectorArray(NS, y); if(check_retval((void *)uS, "N_VCloneVectorArray", 0)) return(1); for(is=0;is<NS;is++) N_VConst(ZERO,uS[is]); retval = CVodeSensInit1(cvode_mem, NS, sensi_meth, NULL, uS); if(check_retval(&retval, "CVodeSensInit", 1)) return(1); retval = CVodeSensEEtolerances(cvode_mem); if(check_retval(&retval, "CVodeSensEEtolerances", 1)) return(1); retval = CVodeSetSensErrCon(cvode_mem, err_con); if(check_retval(&retval, "CVodeSetSensErrCon", 1)) return(1); retval = CVodeSetSensDQMethod(cvode_mem, CV_CENTERED, ZERO); if(check_retval(&retval, "CVodeSetSensDQMethod", 1)) return(1); retval = CVodeSetSensParams(cvode_mem, data->p, pbar, plist); if(check_retval(&retval, "CVodeSetSensParams", 1)) return(1); printf("Sensitivity: YES "); if(sensi_meth == CV_SIMULTANEOUS) printf("( SIMULTANEOUS +"); else if(sensi_meth == CV_STAGGERED) printf("( STAGGERED +"); else printf("( STAGGERED1 +"); if(err_con) printf(" FULL ERROR CONTROL )"); else printf(" PARTIAL ERROR CONTROL )"); } else { printf("Sensitivity: NO "); } /* In loop over output points, call CVode, print results, test for error */ printf("\n\n"); printf("========================================================================\n"); printf(" T Q H NST Bottom left Top right \n"); printf("========================================================================\n"); for (iout=1, tout = TWOHR; iout <= NOUT; iout++, tout += TWOHR) { retval = CVode(cvode_mem, tout, y, &t, CV_NORMAL); if(check_retval(&retval, "CVode", 1)) break; PrintOutput(cvode_mem, t, y); if (sensi) { retval = CVodeGetSens(cvode_mem, &t, uS); if(check_retval(&retval, "CVodeGetSens", 1)) break; PrintOutputS(uS); } printf("------------------------------------------------------------------------\n"); } /* Print final statistics */ PrintFinalStats(cvode_mem, sensi, err_con, sensi_meth); /* Free memory */ N_VDestroy(y); if (sensi) { N_VDestroyVectorArray(uS, NS); free(pbar); free(plist); } FreeUserData(data); CVodeFree(&cvode_mem); SUNLinSolFree(LS); SUNContext_Free(&sunctx); return(0); } /* *-------------------------------------------------------------------- * FUNCTIONS CALLED BY CVODES *-------------------------------------------------------------------- */ /* * f routine. Compute f(t,y). */ static int f(realtype t, N_Vector y, N_Vector ydot, void *user_data) { realtype q3, c1, c2, c1dn, c2dn, c1up, c2up, c1lt, c2lt; realtype c1rt, c2rt, czdn, czup, hord1, hord2, horad1, horad2; realtype qq1, qq2, qq3, qq4, rkin1, rkin2, s, vertd1, vertd2, zdn, zup; realtype q4coef, delz, verdco, hordco, horaco; realtype *ydata, *dydata; int jx, jz, idn, iup, ileft, iright; UserData data; realtype Q1, Q2, C3, A3, A4; data = (UserData) user_data; ydata = N_VGetArrayPointer(y); dydata = N_VGetArrayPointer(ydot); /* Load problem coefficients and parameters */ Q1 = data->p[0]; Q2 = data->p[1]; C3 = data->p[2]; A3 = data->p[3]; A4 = data->p[4]; /* Set diurnal rate coefficients. */ s = sin(data->om*t); if (s > ZERO) { q3 = exp(-A3/s); data->q4 = exp(-A4/s); } else { q3 = ZERO; data->q4 = ZERO; } /* Make local copies of problem variables, for efficiency. */ q4coef = data->q4; delz = data->dz; verdco = data->vdco; hordco = data->hdco; horaco = data->haco; /* Loop over all grid points. */ for (jz=0; jz < MZ; jz++) { /* Set vertical diffusion coefficients at jz +- 1/2 */ zdn = ZMIN + (jz - RCONST(0.5))*delz; zup = zdn + delz; czdn = verdco*exp(RCONST(0.2)*zdn); czup = verdco*exp(RCONST(0.2)*zup); idn = (jz == 0) ? 1 : -1; iup = (jz == MZ-1) ? -1 : 1; for (jx=0; jx < MX; jx++) { /* Extract c1 and c2, and set kinetic rate terms. */ c1 = IJKth(ydata,1,jx,jz); c2 = IJKth(ydata,2,jx,jz); qq1 = Q1*c1*C3; qq2 = Q2*c1*c2; qq3 = q3*C3; qq4 = q4coef*c2; rkin1 = -qq1 - qq2 + RCONST(2.0)*qq3 + qq4; rkin2 = qq1 - qq2 - qq4; /* Set vertical diffusion terms. */ c1dn = IJKth(ydata,1,jx,jz+idn); c2dn = IJKth(ydata,2,jx,jz+idn); c1up = IJKth(ydata,1,jx,jz+iup); c2up = IJKth(ydata,2,jx,jz+iup); vertd1 = czup*(c1up - c1) - czdn*(c1 - c1dn); vertd2 = czup*(c2up - c2) - czdn*(c2 - c2dn); /* Set horizontal diffusion and advection terms. */ ileft = (jx == 0) ? 1 : -1; iright =(jx == MX-1) ? -1 : 1; c1lt = IJKth(ydata,1,jx+ileft,jz); c2lt = IJKth(ydata,2,jx+ileft,jz); c1rt = IJKth(ydata,1,jx+iright,jz); c2rt = IJKth(ydata,2,jx+iright,jz); hord1 = hordco*(c1rt - RCONST(2.0)*c1 + c1lt); hord2 = hordco*(c2rt - RCONST(2.0)*c2 + c2lt); horad1 = horaco*(c1rt - c1lt); horad2 = horaco*(c2rt - c2lt); /* Load all terms into ydot. */ IJKth(dydata, 1, jx, jz) = vertd1 + hord1 + horad1 + rkin1; IJKth(dydata, 2, jx, jz) = vertd2 + hord2 + horad2 + rkin2; } } return(0); } /* * Preconditioner setup routine. Generate and preprocess P. */ static int Precond(realtype tn, N_Vector y, N_Vector fy, booleantype jok, booleantype *jcurPtr, realtype gamma, void *user_data) { realtype c1, c2, czdn, czup, diag, zdn, zup, q4coef, delz, verdco, hordco; realtype **(*P)[MZ], **(*Jbd)[MZ]; sunindextype retval; sunindextype *(*pivot)[MZ]; int jx, jz; realtype *ydata, **a, **j; UserData data; realtype Q1, Q2, C3; /* Make local copies of pointers in user_data, and of pointer to y's data */ data = (UserData) user_data; P = data->P; Jbd = data->Jbd; pivot = data->pivot; ydata = N_VGetArrayPointer(y); /* Load problem coefficients and parameters */ Q1 = data->p[0]; Q2 = data->p[1]; C3 = data->p[2]; if (jok) { /* jok = SUNTRUE: Copy Jbd to P */ for (jz=0; jz < MZ; jz++) for (jx=0; jx < MX; jx++) SUNDlsMat_denseCopy(Jbd[jx][jz], P[jx][jz], NUM_SPECIES, NUM_SPECIES); *jcurPtr = SUNFALSE; } else { /* jok = SUNFALSE: Generate Jbd from scratch and copy to P */ /* Make local copies of problem variables, for efficiency. */ q4coef = data->q4; delz = data->dz; verdco = data->vdco; hordco = data->hdco; /* Compute 2x2 diagonal Jacobian blocks (using q4 values computed on the last f call). Load into P. */ for (jz=0; jz < MZ; jz++) { zdn = ZMIN + (jz - RCONST(0.5))*delz; zup = zdn + delz; czdn = verdco*exp(RCONST(0.2)*zdn); czup = verdco*exp(RCONST(0.2)*zup); diag = -(czdn + czup + RCONST(2.0)*hordco); for (jx=0; jx < MX; jx++) { c1 = IJKth(ydata,1,jx,jz); c2 = IJKth(ydata,2,jx,jz); j = Jbd[jx][jz]; a = P[jx][jz]; IJth(j,1,1) = (-Q1*C3 - Q2*c2) + diag; IJth(j,1,2) = -Q2*c1 + q4coef; IJth(j,2,1) = Q1*C3 - Q2*c2; IJth(j,2,2) = (-Q2*c1 - q4coef) + diag; SUNDlsMat_denseCopy(j, a, NUM_SPECIES, NUM_SPECIES); } } *jcurPtr = SUNTRUE; } /* Scale by -gamma */ for (jz=0; jz < MZ; jz++) for (jx=0; jx < MX; jx++) SUNDlsMat_denseScale(-gamma, P[jx][jz], NUM_SPECIES, NUM_SPECIES); /* Add identity matrix and do LU decompositions on blocks in place. */ for (jx=0; jx < MX; jx++) { for (jz=0; jz < MZ; jz++) { SUNDlsMat_denseAddIdentity(P[jx][jz], NUM_SPECIES); retval = SUNDlsMat_denseGETRF(P[jx][jz], NUM_SPECIES, NUM_SPECIES, pivot[jx][jz]); if (retval != 0) return(1); } } return(0); } /* * Preconditioner solve routine */ static int PSolve(realtype tn, N_Vector y, N_Vector fy, N_Vector r, N_Vector z, realtype gamma, realtype delta, int lr, void *user_data) { realtype **(*P)[MZ]; sunindextype *(*pivot)[MZ]; int jx, jz; realtype *zdata, *v; UserData data; /* Extract the P and pivot arrays from user_data. */ data = (UserData) user_data; P = data->P; pivot = data->pivot; zdata = N_VGetArrayPointer(z); N_VScale(ONE, r, z); /* Solve the block-diagonal system Px = r using LU factors stored in P and pivot data in pivot, and return the solution in z. */ for (jx=0; jx < MX; jx++) { for (jz=0; jz < MZ; jz++) { v = &(IJKth(zdata, 1, jx, jz)); SUNDlsMat_denseGETRS(P[jx][jz], NUM_SPECIES, pivot[jx][jz], v); } } return(0); } /* *-------------------------------------------------------------------- * PRIVATE FUNCTIONS *-------------------------------------------------------------------- */ /* * Process and verify arguments to cvsfwdkryx. */ static void ProcessArgs(int argc, char *argv[], booleantype *sensi, int *sensi_meth, booleantype *err_con) { *sensi = SUNFALSE; *sensi_meth = -1; *err_con = SUNFALSE; if (argc < 2) WrongArgs(argv[0]); if (strcmp(argv[1],"-nosensi") == 0) *sensi = SUNFALSE; else if (strcmp(argv[1],"-sensi") == 0) *sensi = SUNTRUE; else WrongArgs(argv[0]); if (*sensi) { if (argc != 4) WrongArgs(argv[0]); if (strcmp(argv[2],"sim") == 0) *sensi_meth = CV_SIMULTANEOUS; else if (strcmp(argv[2],"stg") == 0) *sensi_meth = CV_STAGGERED; else if (strcmp(argv[2],"stg1") == 0) *sensi_meth = CV_STAGGERED1; else WrongArgs(argv[0]); if (strcmp(argv[3],"t") == 0) *err_con = SUNTRUE; else if (strcmp(argv[3],"f") == 0) *err_con = SUNFALSE; else WrongArgs(argv[0]); } } static void WrongArgs(char *name) { printf("\nUsage: %s [-nosensi] [-sensi sensi_meth err_con]\n",name); printf(" sensi_meth = sim, stg, or stg1\n"); printf(" err_con = t or f\n"); exit(0); } /* * Allocate memory for data structure of type UserData */ static UserData AllocUserData(void) { int jx, jz; UserData data; data = (UserData) malloc(sizeof *data); for (jx=0; jx < MX; jx++) { for (jz=0; jz < MZ; jz++) { (data->P)[jx][jz] = SUNDlsMat_newDenseMat(NUM_SPECIES, NUM_SPECIES); (data->Jbd)[jx][jz] = SUNDlsMat_newDenseMat(NUM_SPECIES, NUM_SPECIES); (data->pivot)[jx][jz] = SUNDlsMat_newIndexArray(NUM_SPECIES); } } data->p = (realtype *) malloc(NP*sizeof(realtype)); return(data); } /* * Load problem constants in data */ static void InitUserData(UserData data) { realtype Q1, Q2, C3, A3, A4, KH, VEL, KV0; /* Set problem parameters */ Q1 = RCONST(1.63e-16); /* Q1 coefficients q1, q2, c3 */ Q2 = RCONST(4.66e-16); /* Q2 */ C3 = RCONST(3.7e16); /* C3 */ A3 = RCONST(22.62); /* A3 coefficient in expression for q3(t) */ A4 = RCONST(7.601); /* A4 coefficient in expression for q4(t) */ KH = RCONST(4.0e-6); /* KH horizontal diffusivity Kh */ VEL = RCONST(0.001); /* VEL advection velocity V */ KV0 = RCONST(1.0e-8); /* KV0 coefficient in Kv(z) */ data->om = PI/HALFDAY; data->dx = (XMAX-XMIN)/(MX-1); data->dz = (ZMAX-ZMIN)/(MZ-1); data->hdco = KH/SQR(data->dx); data->haco = VEL/(RCONST(2.0)*data->dx); data->vdco = (ONE/SQR(data->dz))*KV0; data->p[0] = Q1; data->p[1] = Q2; data->p[2] = C3; data->p[3] = A3; data->p[4] = A4; data->p[5] = KH; data->p[6] = VEL; data->p[7] = KV0; } /* * Free user data memory */ static void FreeUserData(UserData data) { int jx, jz; for (jx=0; jx < MX; jx++) { for (jz=0; jz < MZ; jz++) { SUNDlsMat_destroyMat((data->P)[jx][jz]); SUNDlsMat_destroyMat((data->Jbd)[jx][jz]); SUNDlsMat_destroyArray((data->pivot)[jx][jz]); } } free(data->p); free(data); } /* * Set initial conditions in y */ static void SetInitialProfiles(N_Vector y, realtype dx, realtype dz) { int jx, jz; realtype x, z, cx, cz; realtype *ydata; /* Set pointer to data array in vector y. */ ydata = N_VGetArrayPointer(y); /* Load initial profiles of c1 and c2 into y vector */ for (jz=0; jz < MZ; jz++) { z = ZMIN + jz*dz; cz = SQR(RCONST(0.1)*(z - ZMID)); cz = ONE - cz + RCONST(0.5)*SQR(cz); for (jx=0; jx < MX; jx++) { x = XMIN + jx*dx; cx = SQR(RCONST(0.1)*(x - XMID)); cx = ONE - cx + RCONST(0.5)*SQR(cx); IJKth(ydata,1,jx,jz) = C1_SCALE*cx*cz; IJKth(ydata,2,jx,jz) = C2_SCALE*cx*cz; } } } /* * Print current t, step count, order, stepsize, and sampled c1,c2 values */ static void PrintOutput(void *cvode_mem, realtype t, N_Vector y) { long int nst; int qu, retval; realtype hu; realtype *ydata; ydata = N_VGetArrayPointer(y); retval = CVodeGetNumSteps(cvode_mem, &nst); check_retval(&retval, "CVodeGetNumSteps", 1); retval = CVodeGetLastOrder(cvode_mem, &qu); check_retval(&retval, "CVodeGetLastOrder", 1); retval = CVodeGetLastStep(cvode_mem, &hu); check_retval(&retval, "CVodeGetLastStep", 1); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("%8.3Le %2d %8.3Le %5ld\n", t,qu,hu,nst); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("%8.3e %2d %8.3e %5ld\n", t,qu,hu,nst); #else printf("%8.3e %2d %8.3e %5ld\n", t,qu,hu,nst); #endif printf(" Solution "); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("%12.4Le %12.4Le \n", IJKth(ydata,1,0,0), IJKth(ydata,1,MX-1,MZ-1)); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("%12.4e %12.4e \n", IJKth(ydata,1,0,0), IJKth(ydata,1,MX-1,MZ-1)); #else printf("%12.4e %12.4e \n", IJKth(ydata,1,0,0), IJKth(ydata,1,MX-1,MZ-1)); #endif printf(" "); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("%12.4Le %12.4Le \n", IJKth(ydata,2,0,0), IJKth(ydata,2,MX-1,MZ-1)); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("%12.4e %12.4e \n", IJKth(ydata,2,0,0), IJKth(ydata,2,MX-1,MZ-1)); #else printf("%12.4e %12.4e \n", IJKth(ydata,2,0,0), IJKth(ydata,2,MX-1,MZ-1)); #endif } /* * Print sampled sensitivities */ static void PrintOutputS(N_Vector *uS) { realtype *sdata; sdata = N_VGetArrayPointer(uS[0]); printf(" ----------------------------------------\n"); printf(" Sensitivity 1 "); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("%12.4Le %12.4Le \n", IJKth(sdata,1,0,0), IJKth(sdata,1,MX-1,MZ-1)); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("%12.4e %12.4e \n", IJKth(sdata,1,0,0), IJKth(sdata,1,MX-1,MZ-1)); #else printf("%12.4e %12.4e \n", IJKth(sdata,1,0,0), IJKth(sdata,1,MX-1,MZ-1)); #endif printf(" "); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("%12.4Le %12.4Le \n", IJKth(sdata,2,0,0), IJKth(sdata,2,MX-1,MZ-1)); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("%12.4e %12.4e \n", IJKth(sdata,2,0,0), IJKth(sdata,2,MX-1,MZ-1)); #else printf("%12.4e %12.4e \n", IJKth(sdata,2,0,0), IJKth(sdata,2,MX-1,MZ-1)); #endif sdata = N_VGetArrayPointer(uS[1]); printf(" ----------------------------------------\n"); printf(" Sensitivity 2 "); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("%12.4Le %12.4Le \n", IJKth(sdata,1,0,0), IJKth(sdata,1,MX-1,MZ-1)); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("%12.4e %12.4e \n", IJKth(sdata,1,0,0), IJKth(sdata,1,MX-1,MZ-1)); #else printf("%12.4e %12.4e \n", IJKth(sdata,1,0,0), IJKth(sdata,1,MX-1,MZ-1)); #endif printf(" "); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("%12.4Le %12.4Le \n", IJKth(sdata,2,0,0), IJKth(sdata,2,MX-1,MZ-1)); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("%12.4e %12.4e \n", IJKth(sdata,2,0,0), IJKth(sdata,2,MX-1,MZ-1)); #else printf("%12.4e %12.4e \n", IJKth(sdata,2,0,0), IJKth(sdata,2,MX-1,MZ-1)); #endif } /* * Print final statistics contained in iopt */ static void PrintFinalStats(void *cvode_mem, booleantype sensi, booleantype err_con, int sensi_meth) { long int nst; long int nfe, nsetups, nni, ncfn, netf; long int nfSe, nfeS, nsetupsS, nniS, ncfnS, netfS; long int nli, ncfl, npe, nps; int retval; retval = CVodeGetNumSteps(cvode_mem, &nst); check_retval(&retval, "CVodeGetNumSteps", 1); retval = CVodeGetNumRhsEvals(cvode_mem, &nfe); check_retval(&retval, "CVodeGetNumRhsEvals", 1); retval = CVodeGetNumLinSolvSetups(cvode_mem, &nsetups); check_retval(&retval, "CVodeGetNumLinSolvSetups", 1); retval = CVodeGetNumErrTestFails(cvode_mem, &netf); check_retval(&retval, "CVodeGetNumErrTestFails", 1); retval = CVodeGetNumNonlinSolvIters(cvode_mem, &nni); check_retval(&retval, "CVodeGetNumNonlinSolvIters", 1); retval = CVodeGetNumNonlinSolvConvFails(cvode_mem, &ncfn); check_retval(&retval, "CVodeGetNumNonlinSolvConvFails", 1); if (sensi) { retval = CVodeGetSensNumRhsEvals(cvode_mem, &nfSe); check_retval(&retval, "CVodeGetSensNumRhsEvals", 1); retval = CVodeGetNumRhsEvalsSens(cvode_mem, &nfeS); check_retval(&retval, "CVodeGetNumRhsEvalsSens", 1); retval = CVodeGetSensNumLinSolvSetups(cvode_mem, &nsetupsS); check_retval(&retval, "CVodeGetSensNumLinSolvSetups", 1); if (err_con) { retval = CVodeGetSensNumErrTestFails(cvode_mem, &netfS); check_retval(&retval, "CVodeGetSensNumErrTestFails", 1); } else { netfS = 0; } if ((sensi_meth == CV_STAGGERED) || (sensi_meth == CV_STAGGERED1)) { retval = CVodeGetSensNumNonlinSolvIters(cvode_mem, &nniS); check_retval(&retval, "CVodeGetSensNumNonlinSolvIters", 1); retval = CVodeGetSensNumNonlinSolvConvFails(cvode_mem, &ncfnS); check_retval(&retval, "CVodeGetSensNumNonlinSolvConvFails", 1); } else { nniS = 0; ncfnS = 0; } } retval = CVodeGetNumLinIters(cvode_mem, &nli); check_retval(&retval, "CVodeGetNumLinIters", 1); retval = CVodeGetNumLinConvFails(cvode_mem, &ncfl); check_retval(&retval, "CVodeGetNumLinConvFails", 1); retval = CVodeGetNumPrecEvals(cvode_mem, &npe); check_retval(&retval, "CVodeGetNumPrecEvals", 1); retval = CVodeGetNumPrecSolves(cvode_mem, &nps); check_retval(&retval, "CVodeGetNumPrecSolves", 1); printf("\nFinal Statistics\n\n"); printf("nst = %5ld\n\n", nst); printf("nfe = %5ld\n", nfe); printf("netf = %5ld nsetups = %5ld\n", netf, nsetups); printf("nni = %5ld ncfn = %5ld\n", nni, ncfn); if(sensi) { printf("\n"); printf("nfSe = %5ld nfeS = %5ld\n", nfSe, nfeS); printf("netfs = %5ld nsetupsS = %5ld\n", netfS, nsetupsS); printf("nniS = %5ld ncfnS = %5ld\n", nniS, ncfnS); } printf("\n"); printf("nli = %5ld ncfl = %5ld\n", nli, ncfl); printf("npe = %5ld nps = %5ld\n", npe, nps); } /* * Check function return value... * opt == 0 means SUNDIALS function allocates memory so check if * returned NULL pointer * opt == 1 means SUNDIALS function returns an integer value so check if * retval < 0 * opt == 2 means function allocates memory so check if returned * NULL pointer */ static int check_retval(void *returnvalue, const char *funcname, int opt) { int *retval; /* Check if SUNDIALS function returned NULL pointer - no memory allocated */ if (opt == 0 && returnvalue == NULL) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return(1); } /* Check if retval < 0 */ else if (opt == 1) { retval = (int *) returnvalue; if (*retval < 0) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed with retval = %d\n\n", funcname, *retval); return(1); }} /* Check if function returned NULL pointer - no memory allocated */ else if (opt == 2 && returnvalue == NULL) { fprintf(stderr, "\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return(1); } return(0); }
2.046875
2
2024-11-18T21:50:51.799066+00:00
2017-05-30T02:55:10
098fba03ca57b8377ee7e77cbf6cc68e647910ef
{ "blob_id": "098fba03ca57b8377ee7e77cbf6cc68e647910ef", "branch_name": "refs/heads/master", "committer_date": "2017-05-30T02:55:10", "content_id": "8594794179d1e783322a823da686d66b30ba5cd7", "detected_licenses": [ "Apache-2.0" ], "directory_id": "ef1cf0345efb31c82598f2ec59897a9ddd96c5b1", "extension": "c", "filename": "ejercicio1.c", "fork_events_count": 1, "gha_created_at": "2017-01-30T21:07:44", "gha_event_created_at": "2017-04-26T00:22:11", "gha_language": "HTML", "gha_license_id": null, "github_id": 80463779, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1663, "license": "Apache-2.0", "license_type": "permissive", "path": "/MNO/entrega_tareas_de_C/tarea4/18949/ejercicio1.c", "provenance": "stackv2-0138.json.gz:129800", "repo_name": "fernandatellezg/analisis-numerico-computo-cientifico", "revision_date": "2017-05-30T02:55:10", "revision_id": "07824e91ef4e75c27701aab0bb2e9f0badc6f4b6", "snapshot_id": "0b85b447be65e1a9b4cec41a795275a1c4d62a1e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fernandatellezg/analisis-numerico-computo-cientifico/07824e91ef4e75c27701aab0bb2e9f0badc6f4b6/MNO/entrega_tareas_de_C/tarea4/18949/ejercicio1.c", "visit_date": "2020-05-23T07:54:39.275329" }
stackv2
/* * ejercicio1.c * * Created on: Feb 27, 2017 * Author: Javier Quiroz */ #include<stdio.h> #include<string.h> #define MAX_LONG 200 #define CADENA_PRUEBA "Hola a todos" int longitud_string_vieja(char s[]){ int i; i=0; while(s[i] != '\0') i++; return i; } int longitud_string(char *s){ int i = 0; char *p = s; while(*(p) != '\0') { p++; i++; } return i; } /* * a) cambiar longitud_string a que use apuntadores * * Respuesta: Se presenta el driver siguiente para probar este inciso: Para ver * sus resultados a que cambiar * * b) Investiga el uso de la función scanf para que imprima la longitud de los * strings del archivo.txt: hamburguesas permisos exponencialmente 549 * $./ejercicio_1_scanf.out < archivo.txt * longitud hamburguesas: 12 longitud permisos: 8 longitud exponencialmente: 16 longitud 549: 3 */ int main(void){ // inciso a char string1[] = CADENA_PRUEBA; //definición y declaracion de variable e inicializacion. char string2[MAX_LONG]; //definición y declaracion. char string3[] = CADENA_PRUEBA; //definición y declaracion de variable e inicializacion. int tamanio = 0; printf( "a) \n"); printf("cadena: %s\n", string1); printf("longitud cadena: %d\n", longitud_string(string1)); strcpy(string2, "leer libros y revistas"); //inicializacion de string2 printf("cadena2: %s\n", string2); printf("longitud cadena: %d\n", longitud_string(string2)); //inciso b printf( "b) \n"); while ( ( tamanio = scanf( "%s", string3 ) ) > 0 ) printf( "Longitud %s: %d \n", string3, strlen(string3) ); return 0; }
3.171875
3
2024-11-18T21:50:51.911285+00:00
2018-04-27T17:23:21
a088c70fca76a8dfe817f16aeac1da197b979b35
{ "blob_id": "a088c70fca76a8dfe817f16aeac1da197b979b35", "branch_name": "refs/heads/master", "committer_date": "2018-04-27T17:23:21", "content_id": "c4fbd3f1defa37f33621b7902a4c3544c3ba6281", "detected_licenses": [ "MIT" ], "directory_id": "9f178e43126dffbef67fb003b81f0956230f42cf", "extension": "c", "filename": "mdb_kernel_common.c", "fork_events_count": 0, "gha_created_at": "2017-09-24T00:52:11", "gha_event_created_at": "2017-10-16T23:30:26", "gha_language": "C", "gha_license_id": null, "github_id": 104608712, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5215, "license": "MIT", "license_type": "permissive", "path": "/kernel_modules/mandelbrot/mdb_kernel_common.c", "provenance": "stackv2-0138.json.gz:129928", "repo_name": "GregoryIstratov/mdb", "revision_date": "2018-04-27T17:23:21", "revision_id": "306b17de869cbc164d00da921a78dcd40610c4c2", "snapshot_id": "d4ed4b324f04f281b9249cf38d6bdf0598315ade", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/GregoryIstratov/mdb/306b17de869cbc164d00da921a78dcd40610c4c2/kernel_modules/mandelbrot/mdb_kernel_common.c", "visit_date": "2021-09-13T09:18:08.652963" }
stackv2
#include "mdb_kernel_common.h" #include <klog.h> static uint32_t bailout_get_mod(uint32_t bailout) { if(bailout == 1) return 0; if (bailout < 256) return 1; if (bailout < 512) return 2; if (bailout < 1024) return 4; if (bailout < 2048) return 8; if (bailout < 4096) return 32; if (bailout < 8192) return 128; if (bailout < 16384) return 256; return 512; } static int event_keyboard(struct mdb_event_keyboard* event) { if (event->action == MDB_ACTION_PRESS || event->action == MDB_ACTION_REPEAT) { switch (event->key) { case MDB_KEY_1: mdb.scale *= 1.1; KLOG_SAY("scale %f", mdb.scale); break; case MDB_KEY_2: mdb.scale *= 0.9; KLOG_SAY("scale %f", mdb.scale); break; case MDB_KEY_3: mdb.bailout -= bailout_get_mod(mdb.bailout); KLOG_SAY("bailout %d", mdb.bailout); break; case MDB_KEY_4: mdb.bailout += bailout_get_mod(mdb.bailout); KLOG_SAY("bailout %d", mdb.bailout); break; case MDB_KEY_RIGHT: mdb.shift_x += 0.1 * mdb.scale; KLOG_SAY("shift x %f", mdb.shift_x); break; case MDB_KEY_LEFT: mdb.shift_x -= 0.1 * mdb.scale; KLOG_SAY("shift x %f", mdb.shift_x); break; case MDB_KEY_UP: mdb.shift_y += 0.1 * mdb.scale; KLOG_SAY("shift y %f", mdb.shift_y); break; case MDB_KEY_DOWN: mdb.shift_y -= 0.1 * mdb.scale; KLOG_SAY("shift y %f", mdb.shift_y); break; case MDB_KEY_F1: mdb.scale = 2.793042f; mdb.shift_x = -0.860787f; mdb.shift_y = 0.0f; break; case MDB_KEY_F2: mdb.scale = 0.00188964f; mdb.shift_x = -1.347385054652062f; mdb.shift_y = -0.063483549665202f; break; case MDB_KEY_F3: mdb.shift_x = -0.715882f; mdb.shift_y = -0.287651f; mdb.scale = 0.057683f; break; case MDB_KEY_F4: mdb.shift_x = 0.356868f; mdb.shift_y = -0.348140f; mdb.scale = 0.003869f; break; default: return MDB_FAIL; } } return MDB_SUCCESS; } int mdb_kernel_init(void) { /* View */ switch(2) { case 1: mdb.bailout = 1; mdb.scale = 2.793042f; mdb.shift_x = -0.860787f; mdb.shift_y = 0.0f; break; default: case 2: mdb.bailout = 256; mdb.scale = 0.00188964f; mdb.shift_x = -1.347385054652062f; mdb.shift_y = -0.063483549665202f; break; } KPARAM_INFO("BAILOUT", "%d", mdb.bailout); KPARAM_INFO("SCALE", "%f", mdb.scale); KPARAM_INFO("SHIFT-X", "%f", mdb.shift_x); KPARAM_INFO("SHIFT-Y", "%f", mdb.shift_y); return MDB_SUCCESS; } int mdb_kernel_shutdown(void) { return MDB_SUCCESS; } int mdb_kernel_event_handler(int type, void* event) { switch(type) { case MDB_EVENT_KEYBOARD: return event_keyboard((struct mdb_event_keyboard*)event); default: return MDB_FAIL; } return MDB_SUCCESS; } int mdb_kernel_metadata_query(int query, char* buff, uint32_t buff_size) { switch(query) { case MDB_KERNEL_META_NAME: return metadata_copy(GLOBAL_VAR(name), buff, buff_size); case MDB_KERNEL_META_VER_MAJ: return metadata_copy(GLOBAL_VAR(ver_maj), buff, buff_size); case MDB_KERNEL_META_VER_MIN: return metadata_copy(GLOBAL_VAR(ver_min), buff, buff_size); default: return MDB_QUERY_NO_PARAM; } } int mdb_kernel_set_size(uint32_t width, uint32_t height) { mdb.width = width; mdb.height = height; mdb.width_r = 1.0f / width; mdb.height_r = 1.0f / height; mdb.aspect_ratio = (float)width / height; return MDB_SUCCESS; } int mdb_kernel_set_surface(struct surface* surf) { mdb.surf = surf; return MDB_SUCCESS; }
2.265625
2
2024-11-18T21:50:52.016649+00:00
2021-09-30T20:15:52
50f4a3a15d626ca4836c2d09e323e68f782d4155
{ "blob_id": "50f4a3a15d626ca4836c2d09e323e68f782d4155", "branch_name": "refs/heads/main", "committer_date": "2021-09-30T20:15:52", "content_id": "f61801aefe270daa392baa202583231214e54097", "detected_licenses": [ "MIT" ], "directory_id": "32652c6817e03a4a2cf52b51fe375d33c09e35d9", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 405221323, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12886, "license": "MIT", "license_type": "permissive", "path": "/FreeRTOS_Task/main.c", "provenance": "stackv2-0138.json.gz:130056", "repo_name": "AhmedElDaly9/Tiva-C", "revision_date": "2021-09-30T20:15:52", "revision_id": "cc64b3327cd06ff851c18d10655348c2787654e8", "snapshot_id": "d7a0dc884f52de8afc664aa106a92646e123f343", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/AhmedElDaly9/Tiva-C/cc64b3327cd06ff851c18d10655348c2787654e8/FreeRTOS_Task/main.c", "visit_date": "2023-08-02T04:44:24.000795" }
stackv2
/* * FreeRTOS LED control through UART0 PC communication * The UART receives the inputs 'R' or 'G' or 'B' from the user corresponding to the required to toggle LED, * Then the sender task sends the valid inputs to a queue, * The auto-reload timer gives the semaphore required to make the signal of receiving a character in queue, * When the receiver task is able to take the semaphore it toggles the required LED, * SW2 is able to change the auto-reload timer periods to be either 3sec or 5sec or 10sec. * * * Created on: 15/09/2021 * Author: Ahmed El Daly */ #include <stdbool.h> #include <stdint.h> #include <assert.h> #include "FreeRTOS.h" #include "task.h" #include "semphr.h" #include "queue.h" #include "timers.h" #include "utils/uartstdio.h" #include "inc/hw_memmap.h" #include "inc/tm4c123gh6pm.h" #include "driverlib/sysctl.h" #include "driverlib/gpio.h" #include "driverlib/uart.h" #include "driverlib/pin_map.h" #include "driverlib/interrupt.h" void EnableInterrupts(void); void SystemInit(void){} #define Qsize 3 static uint8_t g_UART_Data; static QueueHandle_t g_QueueHandle = NULL; static SemaphoreHandle_t xSemphUARTReceive = NULL; static SemaphoreHandle_t xSemphQueueReceive = NULL; static TimerHandle_t xTimerReceive = NULL; BaseType_t xTimerReceiveStarted; TickType_t TimerReceivePeriods[3] = {3000,5000,10000}; /*---------------------------------------------------------------------------------------------------*/ /* * Function: UARTStringSend * -------------------- * Description: a function that receives the UART base address and string to send it through UART Tx port * * Parameters: * ui32Base: The required UART base address * Str : The string required to be sent * * returns: * (void) * *---------------------------------------------------------------------------------------------------*/ static void UARTStringSend(uint32_t ui32Base,uint8_t *Str) { /*Counter definition for looping over the to be sent string*/ uint8_t i=0; for (i=0; Str[i] != '\0'; i++) { /*Send the string character by character*/ UARTCharPut(ui32Base,Str[i]); } } /*---------------------------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------------------------*/ void RXTimerCallBack (TimerHandle_t xTimerReceive) { /*The Receiver task can receive the next input queue after a certain period of time*/ xSemaphoreGiveFromISR(xSemphQueueReceive,NULL); } void UART0_INT_Handler () { /*Receive the input character*/ g_UART_Data = UARTCharGet(UART0_BASE); /*Acknowledge the SenderTask that a character is received*/ xSemaphoreGiveFromISR(xSemphUARTReceive,NULL); /*Clear the flag of UART receive timeout interrupt*/ UARTIntClear(UART0_BASE,UART_INT_RT); } /*---------------------------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------------------------*/ void SenderTask (void * p) { /*Local variable to receive the global UART input variable for the task manipulation*/ uint8_t LEDcolor; while (1) { if (xSemaphoreTake(xSemphUARTReceive,portMAX_DELAY)==pdTRUE) { LEDcolor = g_UART_Data; /*Send the input to queue if and only if the input is valid*/ switch (LEDcolor) { case 'R': case 'r': if (xQueueSend(g_QueueHandle, (void *) (&LEDcolor) ,(TickType_t)0)== pdTRUE) { UARTStringSend(UART0_BASE, "--> Red LED Toggling In Queue\n\r"); /*Timer starts with every input to make sure that the last input will be served for the same period*/ xTimerStart(xTimerReceive,(TickType_t)0); } else { UARTStringSend(UART0_BASE, "!Not Enough Space In Queue\n\r"); } break; case 'G': case 'g': if (xQueueSend(g_QueueHandle, (void *) (&LEDcolor) ,(TickType_t)0)== pdTRUE) { UARTStringSend(UART0_BASE, "--> Green LED Toggling In Queue\n\r"); xTimerStart(xTimerReceive,(TickType_t)0); } else { UARTStringSend(UART0_BASE, "!Not Enough Space In Queue\n\r"); } break; case 'B': case 'b': if (xQueueSend(g_QueueHandle, (void *) (&LEDcolor) ,(TickType_t)0)== pdTRUE) { UARTStringSend(UART0_BASE, "--> Blue LED Toggling In Queue\n\r"); xTimerStart(xTimerReceive,(TickType_t)0); } else { UARTStringSend(UART0_BASE, "!Not Enough Space In Queue\n\r"); } break; default: UARTStringSend(UART0_BASE, "!Invalid input\n\r"); break; } } } } void ReceiverTask (void * p) { /*Local variable to receive the queues inputs for the task manipulation*/ uint8_t LEDcolor; /*Flag for the state of empty queue to avoid multiple prints*/ uint8_t flag=0; while (1) { if (xSemaphoreTake(xSemphQueueReceive,portMAX_DELAY)==pdTRUE) { if (xQueueReceive(g_QueueHandle, (void *) (&LEDcolor) ,(TickType_t)0) == pdTRUE) { switch (LEDcolor) { case 'R': case 'r': /**/ GPIOPinWrite(GPIO_PORTF_BASE,GPIO_PIN_1 ,~GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_1)); UARTStringSend(UART0_BASE,"$$ Red LED Toggled Successfully\n\r"); flag=0; break; case 'G': case 'g': /**/ GPIOPinWrite(GPIO_PORTF_BASE,GPIO_PIN_3 ,~GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_3)); UARTStringSend(UART0_BASE,"$$ Green LED Toggled Successfully\n\r"); flag=0; break; case 'B': case 'b': /**/ GPIOPinWrite(GPIO_PORTF_BASE,GPIO_PIN_2 ,~GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_2)); UARTStringSend(UART0_BASE,"$$ Blue LED Toggled Successfully\n\r"); flag=0; break; default: break; } } else { /*If the queue is clear, turn off all LEDs*/ if (flag==0) { GPIOPinWrite(GPIO_PORTF_BASE,GPIO_PIN_1| GPIO_PIN_2 |GPIO_PIN_3,0); UARTStringSend(UART0_BASE,"$$ No inputs left in Queue, LEDs are Turned off\n\r"); flag=1; } } } } } void GPIO_TimerPeriodTask (void *p) { /*Local variable to be TimerReceivePeriods array index*/ uint8_t index=0; while (1) { if (GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_0)==0) { /*300ms delay to avoid bouncing effect*/ vTaskDelay(pdMS_TO_TICKS(300)); if (GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_0)==0) { xQueueReset(g_QueueHandle); index++; if (index == 3) { index=0; } switch (index) { case 0: xTimerChangePeriod(xTimerReceive,pdMS_TO_TICKS(TimerReceivePeriods[index]),(TickType_t)0); UARTStringSend (UART0_BASE,"Timer period reset to 3 seconds, Queue is cleared\n\r"); break; case 1: xTimerChangePeriod(xTimerReceive,pdMS_TO_TICKS(TimerReceivePeriods[index]),(TickType_t)0); UARTStringSend (UART0_BASE,"Timer period increased to 5 seconds, Queue is cleared\n\r"); break; case 2: xTimerChangePeriod(xTimerReceive,pdMS_TO_TICKS(TimerReceivePeriods[index]),(TickType_t)0); UARTStringSend (UART0_BASE,"Timer period increased to 10 seconds, Queue is cleared\n\r"); break; default: UARTStringSend (UART0_BASE,"Invalid Timer period, ERROR\n\r"); break; } } } } } /*---------------------------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------------------------*/ static void PORTF_Init(void) { /*Enable and provide a clock to GPIO Port F in Run mode*/ SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF); while(!SysCtlPeripheralReady(SYSCTL_PERIPH_GPIOF)){} /*Unlock the GPIO PF1:PF3*/ GPIOUnlockPin(GPIO_PORTF_BASE,GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 ); /*Declare PF1:PF3 as output pins*/ GPIOPinTypeGPIOOutput (GPIO_PORTF_BASE,GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3); /*Declare PF0 as input pin*/ GPIOPinTypeGPIOInput(GPIO_PORTF_BASE, GPIO_PIN_0); /*Configure PF0 for a pull-up resistor*/ GPIOPadConfigSet(GPIO_PORTF_BASE, GPIO_PIN_0, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPU); } static void UART_Init (void) { /*Enable and provide a clock to UART0*/ SysCtlPeripheralEnable(SYSCTL_PERIPH_UART0); while(!SysCtlPeripheralReady(SYSCTL_PERIPH_UART0)){ } /*Enable and provide a clock to GPIO Port A in Run mode*/ SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA); while(!SysCtlPeripheralReady(SYSCTL_PERIPH_GPIOA)){} /*Enable UART0 with baudrate 115200, 8-bits data, one stop bit, no parity bit*/ UARTConfigSetExpClk(UART0_BASE, SysCtlClockGet(), 115200 ,(UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE | UART_CONFIG_PAR_NONE)); /*Configure Pin0 for UART0 Rx and Pin1 for UART1 Tx*/ GPIOPinConfigure(GPIO_PA0_U0RX); GPIOPinConfigure(GPIO_PA1_U0TX); GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1); /*Enable FIFO buffer*/ UARTFIFOEnable(UART0_BASE); /*Enable UART receive timeout interrupt*/ UARTIntRegister(UART0_BASE,UART0_INT_Handler); UARTIntEnable(UART0_BASE, UART_INT_RT); IntEnable(INT_UART0); IntMasterEnable(); } /*---------------------------------------------------------------------------------------------------*/ int main(void) { /*Setting the clock frequency to 80MHz*/ SysCtlClockSet(SYSCTL_SYSDIV_2_5 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ); /*Initialize PF0 as input and PF1:PF3 as outputs*/ PORTF_Init(); /*Initialize UART for UART0 and Enable UART Interrupts*/ UART_Init(); /*Auto-Reload Timer to determine the rate of receiving from queue*/ xTimerReceive = xTimerCreate ( "Receiver Timer", pdMS_TO_TICKS(TimerReceivePeriods[0]), pdTRUE,(void *) 0, RXTimerCallBack); /*Create characters queue for receiving inputs from UART*/ g_QueueHandle = xQueueCreate (Qsize, sizeof(uint8_t)); assert(g_QueueHandle != NULL); /*Binary semaphore to make a signal of receiving a character through UART*/ xSemphUARTReceive = xSemaphoreCreateBinary(); assert(xSemphUARTReceive != NULL); /*Binary semaphore to make a signal of sending a character in queue*/ xSemphQueueReceive = xSemaphoreCreateBinary(); assert(xSemphQueueReceive != NULL); /*Create the required tasks with the same priority to handle them using time-slicing technique*/ xTaskCreate(ReceiverTask, "ReceiverTask", 1000,NULL,1,NULL); xTaskCreate(SenderTask, "SenderTask", 1000,NULL,1,NULL); xTaskCreate(GPIO_TimerPeriodTask, "Change Timer Period Task", 1000, NULL, 1, NULL); /*Making sure that all the tasks are created successfully*/ if (ReceiverTask != NULL && SenderTask != NULL && GPIO_TimerPeriodTask != NULL) { UARTStringSend(UART0_BASE,"Enter 'R' for Toggling Red LED " "or 'G' for Toggling Green LED or 'B' for Toggling Blue LED\n\r"); vTaskStartScheduler(); } while(1) {} return 0; }
2.84375
3
2024-11-18T21:50:54.059937+00:00
2016-02-29T00:24:30
a37db607c8ac6e4f1a0f0ae08e32643620f382da
{ "blob_id": "a37db607c8ac6e4f1a0f0ae08e32643620f382da", "branch_name": "refs/heads/master", "committer_date": "2016-02-29T00:24:30", "content_id": "c567bd5e1bcdeaebc7af1166b54c5d4a554b9df7", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "faa5a27e5a73ec86fcb692779616b0787b6f4100", "extension": "c", "filename": "gf-bench.c", "fork_events_count": 3, "gha_created_at": "2015-10-13T02:35:39", "gha_event_created_at": "2016-02-09T23:37:19", "gha_language": "C", "gha_license_id": null, "github_id": 44147107, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1348, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/encryption/gf-bench.c", "provenance": "stackv2-0138.json.gz:131353", "repo_name": "ckennard/rnccdn", "revision_date": "2016-02-29T00:24:30", "revision_id": "70c77d780cbd3838acfbacd28a10804720660ff9", "snapshot_id": "01ed5f5e5993e9c91fe5e1d5ab505bd321588b3b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ckennard/rnccdn/70c77d780cbd3838acfbacd28a10804720660ff9/encryption/gf-bench.c", "visit_date": "2021-01-21T04:41:28.966808" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <sys/time.h> #include "gf.h" #include "mt64.h" // Space allocation #define SPACE 640000 // # of repeats #define REPEAT 200 // Actual repeat times is SPACE * REPEAT // Main int main(int argc, char **argv) { // Variables int i, j; struct timeval start, end; uint16_t *a, *b; // 16bit uint64_t *r; uint64_t rand_init[4] = {UINT64_C(0xfd308), UINT64_C(0x65ab8), UINT64_C(0x931cd54), UINT64_C(0x9475ea2)}; // Initialize GF GF16init(); // 16bit // Allocate if ((a = (uint16_t *)malloc(SPACE * 2)) == NULL) { // 16bit perror("malloc"); exit(1); } b = a + (SPACE / sizeof(uint16_t)); // 16bit // Initialize random generator // Input random numbers to a, b j = SPACE * 2 / sizeof(uint64_t); r = (uint64_t *)a; for (i = 0; i < j; i++) { r[i] = genrand64_int64(); } // Start measuring elapsed time gettimeofday(&start, NULL); // Get start time // Repeat calc in GF for (i = 0; i < REPEAT; i++) { for (j = 0; j < SPACE / sizeof(uint16_t); j++) { // Calculate in GF // To avoid elimination by cc's -O2 option, input result into a[j] a[j] = GF16mul(a[j], b[j]); // 16bit } } // Get end time gettimeofday(&end, NULL); // Print result printf("%ld\n", ((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec))); }
2.890625
3
2024-11-18T21:50:54.141565+00:00
2018-05-14T09:13:10
1091072a3a1ce3d7d6cf1320ab955487be8d0084
{ "blob_id": "1091072a3a1ce3d7d6cf1320ab955487be8d0084", "branch_name": "refs/heads/master", "committer_date": "2018-05-14T09:13:10", "content_id": "1a0b0609e1cc1d8c5e54a2bff3e99a9a911697b8", "detected_licenses": [ "MIT" ], "directory_id": "68daa50e6bff563b9681a4c84c71d7de899f718f", "extension": "c", "filename": "downcase_unicoc.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 131467195, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 302, "license": "MIT", "license_type": "permissive", "path": "/auto/unicoc/src-convertion/downcase_unicoc.c", "provenance": "stackv2-0138.json.gz:131483", "repo_name": "Tikubonn/unico", "revision_date": "2018-05-14T09:13:10", "revision_id": "c76de5309f8a3a6fda3110e463b7e9718ea530e3", "snapshot_id": "c7594d0af13f8ca7019361fa735df1d23d4aa924", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Tikubonn/unico/c76de5309f8a3a6fda3110e463b7e9718ea530e3/auto/unicoc/src-convertion/downcase_unicoc.c", "visit_date": "2020-03-14T05:34:06.267611" }
stackv2
#include <unico.h> #include <stddef.h> int downcase_unicoc (unicoc *uniout){ int status = downcase_unicoc(uniout); if (status){ size_t size = size_unicoc(uniout); int status = extend_unicoc(size * 2, uniout); if (status) return 1; return downcase_unicoc(uniout); } return 0; }
2
2
2024-11-18T21:50:54.314248+00:00
2020-02-18T10:14:20
7fc5ea991d1bdcda7c56fafe71a48fda6cd9bc76
{ "blob_id": "7fc5ea991d1bdcda7c56fafe71a48fda6cd9bc76", "branch_name": "refs/heads/master", "committer_date": "2020-02-18T10:14:20", "content_id": "be765368747286c6ca64b9ac39c24d1dc5c1b336", "detected_licenses": [ "MIT" ], "directory_id": "6eeca94441b7ddb4c9413a0f01be6f6c5d9e2494", "extension": "h", "filename": "BitStream64.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 235931970, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3157, "license": "MIT", "license_type": "permissive", "path": "/include/BitStream64.h", "provenance": "stackv2-0138.json.gz:131743", "repo_name": "NAP64/Memory-Compression-Measurements-Open", "revision_date": "2020-02-18T10:14:20", "revision_id": "eefc809027db98ac21aba1540e7a9e09a1cbe328", "snapshot_id": "ee311dbf20493ffb200956a67a5c35def1704db5", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/NAP64/Memory-Compression-Measurements-Open/eefc809027db98ac21aba1540e7a9e09a1cbe328/include/BitStream64.h", "visit_date": "2020-12-20T02:22:55.994005" }
stackv2
/* Healper code for data access Uses 64-bit register buffer to read/write data for 8-bit compression methods (It works well but speedup is unmeasured) By Yuqing Liu HEAP Lab, Virginia Tech Jun 2019 */ #ifndef BITSTREAM64 #define BITSTREAM64 #include <stdint.h> typedef struct { uint64_t buf; int8_t b_offset; uint8_t * dest; uint64_t d_offset; } BitStream64_t; typedef struct { uint8_t buf; int8_t b_offset; uint8_t * source; uint64_t s_offset; } BitStream8_t; void BitStream8_read_init(BitStream8_t * bs, uint8_t * source) { bs->buf = 0; bs->b_offset = 0; bs->source = source; bs->s_offset = 0; } uint64_t BitStream8_read(BitStream8_t * bs, int8_t size) { static uint8_t mask[] = {0, 1, 3, 7, 0xf, 0x1f, 0x3f, 0x7f, 0xff}; uint64_t res; if (size < 8 - bs->b_offset) { res = *(bs->source + bs->s_offset); res = res >> (8 - size - bs->b_offset); res = res & mask[size]; bs->b_offset += size; return res; } res = *(bs->source + bs->s_offset) & mask[8 - bs->b_offset]; size -= (8-bs->b_offset); bs->s_offset++; while (size >= 8) { res = res << 8; res |= *(bs->source + bs->s_offset); bs->s_offset++; size -= 8; } bs->b_offset = size; res = res << size; res |= (*(bs->source + bs->s_offset) >> (8 - size)) & mask[size]; return res; } void BitStream64_write8(uint8_t * dest, uint64_t eight, int count) { switch (count) { case 8: *(dest + 7) = eight & 0xff; case 7: *(dest + 6) = (eight >> 8) & 0xff; case 6: *(dest + 5) = (eight >> 16) & 0xff; case 5: *(dest + 4) = (eight >> 24) & 0xff; case 4: *(dest + 3) = (eight >> 32) & 0xff; case 3: *(dest + 2) = (eight >> 40) & 0xff; case 2: *(dest + 1) = (eight >> 48) & 0xff; case 1: *(dest) = (eight >> 56) & 0xff; } } void BitStream64_write_init(BitStream64_t * bs, uint8_t * dest) { bs->buf = 0; bs->b_offset = 0; bs->dest = dest; bs->d_offset = 0; } //Upper bits of payload must be 0! void BitStream64_write(BitStream64_t * bs, uint64_t payload, int8_t size) { if (bs->b_offset + size < 64) { bs->buf |= payload << (64 - bs->b_offset - size); bs->b_offset += size; } else { bs->b_offset = bs->b_offset + size - 64; bs->buf |= payload >> (bs->b_offset); //*(uint64_t*)(bs->dest + bs->d_offset) = bs->buf; BitStream64_write8(bs->dest + bs->d_offset, bs->buf, 8); bs->d_offset += 8; if (bs->b_offset == 0) bs->buf = 0; else bs->buf = payload << (64 - bs->b_offset); } } int BitStream64_write_finish(BitStream64_t * bs) { int8_t o = bs->b_offset; o = !(o % 8) ? o / 8 : o / 8 + 1; BitStream64_write8(bs->dest + bs->d_offset, bs->buf, o); return bs->d_offset + o; } #endif
3.03125
3
2024-11-18T21:50:54.401289+00:00
2022-01-27T14:17:23
6d0bb8f657f2732c91f7f32e89b0e57dc5d68c45
{ "blob_id": "6d0bb8f657f2732c91f7f32e89b0e57dc5d68c45", "branch_name": "refs/heads/master", "committer_date": "2022-01-27T14:17:23", "content_id": "93bf74ef69a8da72fdd2d6e6fb3e091c11fc1a18", "detected_licenses": [ "MIT" ], "directory_id": "39d49000aea30519e720f26ecfe0c6027c39f77b", "extension": "c", "filename": "avx512.c", "fork_events_count": 0, "gha_created_at": "2022-05-17T12:08:35", "gha_event_created_at": "2022-05-17T12:08:36", "gha_language": null, "gha_license_id": "MIT", "github_id": 493234535, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1364, "license": "MIT", "license_type": "permissive", "path": "/bench/transposition/vslice/avx512.c", "provenance": "stackv2-0138.json.gz:131874", "repo_name": "DadaIsCrazy/usuba", "revision_date": "2022-01-27T14:17:23", "revision_id": "62109072309e07b20c57f0ea8024e281370a6fc9", "snapshot_id": "a858785fc13e5ca448d9563ec41e3f90db91e9df", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/DadaIsCrazy/usuba/62109072309e07b20c57f0ea8024e281370a6fc9/bench/transposition/vslice/avx512.c", "visit_date": "2023-03-21T01:50:48.787640" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <x86intrin.h> #define TRANSPOSE4(x0, x1, x2, x3) \ do { \ __m512i t0, t1, t2; \ \ t0 = _mm512_unpacklo_epi32(x1,x0); \ t2 = _mm512_unpackhi_epi32(x1,x0); \ t1 = _mm512_unpacklo_epi32(x3,x2); \ x3 = _mm512_unpackhi_epi32(x3,x2); \ \ x0 = _mm512_unpacklo_epi64(t1,t0); \ x1 = _mm512_unpackhi_epi64(t1,t0); \ x2 = _mm512_unpacklo_epi64(x3,t2); \ x3 = _mm512_unpackhi_epi64(x3,t2); \ } while (0); #define NB_LOOP 1000000000 int main() { __m512i data[4]; for (int i = 0; i < 4; i++) data[i] = _mm512_set_epi64x(rand(),rand(),rand(),rand(), rand(),rand(),rand(),rand()); for (int i = 0; i < 100000; i++) TRANSPOSE4(data[0], data[1], data[2], data[3]); uint64_t timer = _rdtsc(); for (int i = 0; i < NB_LOOP; i++) TRANSPOSE4(data[0], data[1], data[2], data[3]); timer = _rdtsc() - timer; printf("%.2f cycles/byte\n", (double)timer / NB_LOOP / (64*4)); FILE* FP = fopen("/dev/null","w"); fwrite(data,32,4,FP); fclose(FP); }
2.328125
2
2024-11-18T21:50:54.538557+00:00
2018-10-26T20:16:05
02814dae67594b32557c8b528b8ec55137e5cf86
{ "blob_id": "02814dae67594b32557c8b528b8ec55137e5cf86", "branch_name": "refs/heads/master", "committer_date": "2018-10-26T20:16:05", "content_id": "be9918604cf6024cb16324bc5da605dc868c5726", "detected_licenses": [ "MIT" ], "directory_id": "e003b2724a8c342b2d1131cf38266857cc7e6928", "extension": "c", "filename": "singlelevel.c", "fork_events_count": 2, "gha_created_at": "2017-08-08T14:15:50", "gha_event_created_at": "2018-10-26T20:15:24", "gha_language": "C", "gha_license_id": null, "github_id": 99700632, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1594, "license": "MIT", "license_type": "permissive", "path": "/C/Directory System/Single Level/singlelevel.c", "provenance": "stackv2-0138.json.gz:132134", "repo_name": "philson-philip/Code-Lab", "revision_date": "2018-10-26T20:16:05", "revision_id": "d2d677058e036f11724194f801e0bbfe0e6a53c7", "snapshot_id": "a36fa432e73c0aa1ce6c3602cac483070f55eeb9", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/philson-philip/Code-Lab/d2d677058e036f11724194f801e0bbfe0e6a53c7/C/Directory System/Single Level/singlelevel.c", "visit_date": "2021-01-15T14:54:35.191497" }
stackv2
#include<stdio.h> #include<string.h> struct directory { char dirname[10],fname[10][10]; int count; }dir; void main() { int i,n,j; char f[100]; dir.count=0; //create a directory printf("\nEnter the name of the directory:"); scanf("%s",dir.dirname); //creation of a file system while(1) { printf("\n1.Create a file\t2.Delete a file\t3.Display all files\t4.Search for file\t5.Exit"); scanf("%d",&n); if(n==1) //Creating a file { printf("File name:"); scanf("%s",dir.fname[dir.count]); dir.count++; } else if(n==2) //Deleting a file { printf("\nEnter the file to be deleted:"); scanf("%s",f); for(i=0;i<dir.count;i++) { if(strcmp(f,dir.fname[i])==0) { printf("File %s is deleted ",f); for(j=i;j<dir.count;j++) { strcpy(dir.fname[j],dir.fname[j+1]); } dir.count--; } } if(i==dir.count) { printf("File %s not found",f); } } else if (n==3)//Displaying file { printf("\nThe list of files are:"); if(dir.count==0) { printf("\nThe directory is empty\n"); } for(i=0;i<dir.count;i++) { printf("%s",dir.fname[i]); } } else if(n==4)//Searching for a file { printf("\nEnter the file to be searched:"); scanf("%s",f); for(i=0;i<dir.count;i++) { if(strcmp(f,dir.fname[i])==0) { printf("File %s is present",f); break; } /*else { printf("File is absent"); }*/ } if(i==dir.count) { printf("File is absent"); } } else { break; } } }
3.453125
3
2024-11-18T21:50:54.609083+00:00
2020-07-02T18:41:08
9054b50718193da40942e7acfedb52dda29144dc
{ "blob_id": "9054b50718193da40942e7acfedb52dda29144dc", "branch_name": "refs/heads/master", "committer_date": "2020-07-02T18:41:08", "content_id": "8f1cf4ee934eb33974719c6689cb1a5178310f4c", "detected_licenses": [ "MIT" ], "directory_id": "9ea87c10180665db0db6fa36997704acc001692d", "extension": "c", "filename": "simplesock.c", "fork_events_count": 0, "gha_created_at": "2018-11-27T01:16:08", "gha_event_created_at": "2019-05-17T05:43:34", "gha_language": "Python", "gha_license_id": "MIT", "github_id": 159255786, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2793, "license": "MIT", "license_type": "permissive", "path": "/guides/c/libsample/toralib/simplesock.c", "provenance": "stackv2-0138.json.gz:132263", "repo_name": "ToraNova/library", "revision_date": "2020-07-02T18:41:08", "revision_id": "20b321302868e8c2ce8723c808aa9e7a313e2cb8", "snapshot_id": "8af942f4657ebc07043848616e5b75cdace67212", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ToraNova/library/20b321302868e8c2ce8723c808aa9e7a313e2cb8/guides/c/libsample/toralib/simplesock.c", "visit_date": "2021-07-13T07:57:40.631816" }
stackv2
/* simple socket connection library for c written for a machine learning tutorial [email protected] guided strongly by (credits to the original author) https://aticleworld.com/socket-programming-in-c-using-tcpip/ */ #include"dbg.h" #include<sys/socket.h> #include<arpa/inet.h> #include<unistd.h> #include<stdlib.h> #include<errno.h> #include"simplesock.h" extern int errno; int sockgen(short nonblock){ //create the socket connection int sockobj; sockobj = socket( AF_INET, nonblock? SOCK_STREAM | SOCK_NONBLOCK : SOCK_STREAM , 0); return sockobj; } int sockconn(int sockobj, const char *srvaddr,int portnum){ //connect to a socket server int retval = -1; struct sockaddr_in remote={0}; //setup connection params remote.sin_family = AF_INET; remote.sin_addr.s_addr = inet_addr(srvaddr); remote.sin_port = htons(portnum); //attempt to connect, obtaining the result code as retval. retval = connect(sockobj, (struct sockaddr *)&remote, sizeof(struct sockaddr_in)); log_info("Connection to %s on port %d returns %d",srvaddr,portnum,retval); return retval; } int sockbind(int sockobj, int portnum){ //bind the created socket int retval = -1; struct sockaddr_in remote={0}; //setup connection params remote.sin_addr.s_addr = htonl(INADDR_ANY); remote.sin_family = AF_INET; remote.sin_port = htons(portnum); retval = bind(sockobj,(struct sockaddr *)&remote,sizeof(struct sockaddr_in)); log_info("Socket bound to port %d returns %d",portnum,retval); return retval; } int sendbuf(int sockobj, char *sendbuffer, short buflen, short timeout_sec){ //send via the socket connection int retval = -1; struct timeval timeout; //setup the timeout timeout.tv_sec = timeout_sec; timeout.tv_usec = 0; //usec must be named to prevent out of domain errors if(setsockopt(sockobj,SOL_SOCKET, SO_SNDTIMEO, &timeout,sizeof(struct timeval)) < 0){ log_err("Socket set options failed. %d",timeout_sec); perror("Error :"); return -1; } //code enters here when setup is successful retval = send(sockobj, sendbuffer, buflen,0); log_info("Buffer %s of size %d sent with retval:%d",sendbuffer,buflen,retval); return retval; } int recvbuf(int sockobj, char *recvbuffer, short buflen, short timeout_sec){ //recv via the socket connection int retval = -1; struct timeval timeout; timeout.tv_sec = timeout_sec; timeout.tv_usec = 0; //usec must be named to prevent out of domain errors if(setsockopt(sockobj,SOL_SOCKET, SO_RCVTIMEO, &timeout,sizeof(struct timeval)) < 0){ log_err("Socket set options failed. %d",timeout_sec); perror("Error :"); return -1; } //code enters here when setup is successful retval = recv(sockobj, recvbuffer, buflen,0); log_info("Buffer %s of size %d recv with retval:%d",recvbuffer,buflen,retval); return retval; }
2.96875
3