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-18T21:30:13.309971+00:00
2017-10-31T05:14:25
8bf421d421bba706f35efa136c8446092b053e37
{ "blob_id": "8bf421d421bba706f35efa136c8446092b053e37", "branch_name": "refs/heads/master", "committer_date": "2017-10-31T05:14:25", "content_id": "33a1734182602aacd12d08bde7905ab6ec88acd4", "detected_licenses": [ "MIT" ], "directory_id": "a0b233852936f9422405c2af1f7279bf9b170886", "extension": "c", "filename": "DDIL_ExtKey.c", "fork_events_count": 1, "gha_created_at": "2019-08-07T06:06:30", "gha_event_created_at": "2019-08-07T06:06:30", "gha_language": null, "gha_license_id": null, "github_id": 200983498, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3053, "license": "MIT", "license_type": "permissive", "path": "/IAR/DDIL/src/DDIL_ExtKey.c", "provenance": "stackv2-0112.json.gz:191098", "repo_name": "ruinned/RL78_Board_IAR", "revision_date": "2017-10-31T05:14:25", "revision_id": "df379cbb4c259abb32246d08d8ec016eb26c7fad", "snapshot_id": "f24f214fe1d875f253e11ca9cec409792486be7a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ruinned/RL78_Board_IAR/df379cbb4c259abb32246d08d8ec016eb26c7fad/IAR/DDIL/src/DDIL_ExtKey.c", "visit_date": "2020-06-30T23:32:29.073565" }
stackv2
#include "DDIL_ExtKey.h" /** * Brief: * The ddil extent ket object[ ddil extkey num]. */ DDIL_EXTKEY_STRUCT DDIL_extKetObject[DDIL_EXTKEY_NUM] = { 0 }; /*外部按键驱动注册*/ /** * Function: * DDIL_ERROR_CODE DDIL_ExtKey_Register(DDIL_EXTKEY_INDEX index, DDIL_ExtKey_Init_FuncPtr init, * DDIL_ExtKey_GetStatus_FuncPtr getStatus, DDIL_ExtKey_WaitStatus_FuncPtr waitStatus) * * Brief: * Ddil extent key register. * * Author: * Dink * * Date: * 2017/10/15 * * Param: * index - Zero-based index of the. * init - The init. * getStatus - The get status. * waitStatus - The wait status. * * Returns: * A DDIL_ERROR_CODE. */ DDIL_ERROR_CODE DDIL_ExtKey_Register(DDIL_EXTKEY_INDEX index, DDIL_ExtKey_Init_FuncPtr init, DDIL_ExtKey_GetStatus_FuncPtr getStatus, DDIL_ExtKey_WaitStatus_FuncPtr waitStatus) { if (index >= DDIL_EXTKEY_NUM) return DDIL_ERROR_NUM_LIMIT; DDIL_extKetObject[index].init = init; DDIL_extKetObject[index].getStatus = getStatus; DDIL_extKetObject[index].waitStatus = waitStatus; return DDIL_ERROR_NONE; } /*初始化*/ /** * Function: DDIL_ERROR_CODE DDIL_ExtKey_Init(DDIL_EXTKEY_INDEX index) * * Brief: * Ddil extent key init. * * Author: * Dink * * Date: * 2017/10/15 * * Param: * index - Zero-based index of the. * * Returns: * A DDIL_ERROR_CODE. */ DDIL_ERROR_CODE DDIL_ExtKey_Init(DDIL_EXTKEY_INDEX index) { if (index >= DDIL_EXTKEY_NUM) return DDIL_ERROR_NUM_LIMIT; if (DDIL_extKetObject[index].init == NULL) return DDIL_ERROR_FUNC_NULL; return DDIL_extKetObject[index].init(); } /*获取状态,立即返回*/ /** * Function: * DDIL_ERROR_CODE DDIL_ExtKey_GetStatus(DDIL_EXTKEY_INDEX index, DDIL_EXTKEY_STATUS* status) * * Brief: * Ddil extent key get status. * * Author: * Dink * * Date: * 2017/10/15 * * Param: * index - Zero-based index of the. * status - [in,out] If non-null, the status. * * Returns: * A DDIL_ERROR_CODE. */ DDIL_ERROR_CODE DDIL_ExtKey_GetStatus(DDIL_EXTKEY_INDEX index, DDIL_EXTKEY_STATUS* status) { if (index >= DDIL_EXTKEY_NUM) return DDIL_ERROR_NUM_LIMIT; if (DDIL_extKetObject[index].getStatus == NULL) return DDIL_ERROR_FUNC_NULL; return DDIL_extKetObject[index].getStatus(status); } /*等待状态,直到等待到指定的状态才返回*/ /** * Function: * DDIL_ERROR_CODE DDIL_ExtKey_WaitStatus(DDIL_EXTKEY_INDEX index, DDIL_EXTKEY_STATUS status) * * Brief: * Ddil extent key wait status. * * Author: * Dink * * Date: * 2017/10/15 * * Param: * index - Zero-based index of the. * status - The status. * * Returns: * A DDIL_ERROR_CODE. */ DDIL_ERROR_CODE DDIL_ExtKey_WaitStatus(DDIL_EXTKEY_INDEX index, DDIL_EXTKEY_STATUS status) { if (index >= DDIL_EXTKEY_NUM) return DDIL_ERROR_NUM_LIMIT; if (DDIL_extKetObject[index].waitStatus == NULL) return DDIL_ERROR_FUNC_NULL; return DDIL_extKetObject[index].waitStatus(status); }
2.34375
2
2024-11-18T21:30:13.887501+00:00
2020-07-31T16:42:59
bbe4fdbef19d17246c7a05ed0b9a1c9804e10184
{ "blob_id": "bbe4fdbef19d17246c7a05ed0b9a1c9804e10184", "branch_name": "refs/heads/master", "committer_date": "2020-07-31T16:42:59", "content_id": "d4412f4ca148f61915f4e9c9eb363708efeddd56", "detected_licenses": [ "MIT" ], "directory_id": "ca1492484b7b510d974f7a551459f4ea47065305", "extension": "c", "filename": "attach.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 233876041, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1905, "license": "MIT", "license_type": "permissive", "path": "/usdt-test/attach.c", "provenance": "stackv2-0112.json.gz:191228", "repo_name": "gretay-js/probes", "revision_date": "2020-07-31T16:42:59", "revision_id": "fcd0eb07931257aff6908ca1713e9b3c0d468452", "snapshot_id": "a015239c189cbfb52c30ee2f39659e16aa96c5f5", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/gretay-js/probes/fcd0eb07931257aff6908ca1713e9b3c0d468452/usdt-test/attach.c", "visit_date": "2020-12-11T14:44:57.458183" }
stackv2
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <errno.h> #include <sys/ptrace.h> #include <sys/user.h> #include <sys/types.h> #include <sys/wait.h> int main(int argc, char *argv[]) { unsigned long addr; pid_t cpid = -1; // pid to attach ptrace to if(argc!=3) { fprintf(stderr, "Missing arguments.\n\ Usage: attach %s <pid> <hex-addr-to-rewrite>\n", argv[0] ); return 1; } if (sscanf(argv[1], "%d", &cpid) != 1) { fprintf(stderr, "Cannot read pid %s\n", argv[1]); return 1; }; if (sscanf(argv[2], "%lx", &addr) != 1) { fprintf(stderr, "Cannot read hexadecimal address to rewrite %s\n", argv[2]); return 1; }; if(ptrace(PTRACE_ATTACH, cpid, NULL, NULL)) { fprintf(stderr, "ptrace attach error\n"); return 1; } int status = 0; pid_t res = waitpid(cpid, &status, WUNTRACED); if ((res != cpid) || !(WIFSTOPPED(status)) ) { printf("Unexpected wait result res %d stat %x\n",res,status); exit(1); } fprintf(stderr, "Modifying address %lx in running process %d\n", addr, cpid); unsigned long data = ptrace(PTRACE_PEEKTEXT, cpid, addr, NULL); fprintf (stderr, "before: %lx\n", data); if ((data & 0xff) != 0x3d) { fprintf(stderr, "Unexpected instruction! %lx\n", (data & 0xff)); return 1; } data = (data & ~0xff) | 0xe8; fprintf (stderr, "after: %lx\n", data); ptrace(PTRACE_POKETEXT, cpid, addr, data); if(ptrace(PTRACE_CONT, cpid, NULL, NULL)==-1) { fprintf(stderr, "could not continue, errno=%d\n", errno); return 1; } wait(&status); if(!WIFEXITED(status)) { int signum = WSTOPSIG(status); struct user_regs_struct regs; ptrace(PTRACE_GETREGS, cpid, NULL, &regs); printf ("signal: %d, eip: 0x%08llx\n", signum, regs.rip); return status; } else { fprintf(stderr, "child exited\n"); } return 0; }
2.734375
3
2024-11-18T21:30:13.947531+00:00
2019-07-21T09:56:15
abaec7725c4513b828aef74a5ebd6f57443c34ff
{ "blob_id": "abaec7725c4513b828aef74a5ebd6f57443c34ff", "branch_name": "refs/heads/master", "committer_date": "2019-07-21T09:56:15", "content_id": "05f1c0188149f4f4ef96eca9d0e20ca21f6ccbf2", "detected_licenses": [ "MIT" ], "directory_id": "7f333d455bcfa082ac1a927f1996a4d2a16c0b3e", "extension": "c", "filename": "pbm.c", "fork_events_count": 0, "gha_created_at": "2019-07-21T11:25:54", "gha_event_created_at": "2019-07-21T11:25:54", "gha_language": null, "gha_license_id": "MIT", "github_id": 198047891, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3623, "license": "MIT", "license_type": "permissive", "path": "/misc/pbm.c", "provenance": "stackv2-0112.json.gz:191359", "repo_name": "mitchcurtis/bitmap", "revision_date": "2019-07-21T09:56:15", "revision_id": "f8883aeed06f60dcf9edcfda0e9402983ac28733", "snapshot_id": "7c0e570f12d63fdc2e5ec67cfba67815bcc00a4d", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/mitchcurtis/bitmap/f8883aeed06f60dcf9edcfda0e9402983ac28733/misc/pbm.c", "visit_date": "2022-03-06T14:02:02.705545" }
stackv2
/* Small program to convert Netpbm files to bitmap images. http://en.wikipedia.org/wiki/Netpbm_format */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "../bmp.h" static char *pbm_readfile(const char *fname) { FILE *f; long len,r; char *str; if(!(f = fopen(fname, "rb"))) return NULL; fseek(f, 0, SEEK_END); len = ftell(f); rewind(f); if(!(str = malloc(len+2))) return NULL; r = fread(str, 1, len, f); if(r != len) { free(str); return NULL; } fclose(f); str[len] = '\0'; return str; } static char *tokenize_pbm(char *s, char **r) { char *p = s, *e; if(!s && r) p = *r; if(!p) return NULL; start: while(isspace(*p)) p++; if(*p == '\0') return NULL; if(*p == '#') { while(*p != '\n') { if(*p == '\0') return NULL; p++; } goto start; } for(e = p; *e && !isspace(*e); e++); if(r) { if(*e != '\0') *r = e + 1; else *r = e; } *e = '\0'; return p; } struct bitmap *parse_pbm(const char *filename) { struct bitmap *bm = NULL; char *s = pbm_readfile(filename); char *p, *r; int type = 0, w, h, d = 1, x, y; if(!s) { fprintf(stderr, "error: Unable open %s\n", filename); return NULL; } p = tokenize_pbm(s, &r); if(!p) { fprintf(stderr, "error: Couldn't determine type\n"); goto error; } if(!strcmp(p, "P1")) { type = 1; } else if(!strcmp(p, "P2")) { type = 2; } else if(!strcmp(p, "P3")) { type = 3; } else { fprintf(stderr, "error: Invalid type %s\n", p); goto error; } #define GET_INT(v, error_msg) do{ if(!(p = tokenize_pbm(NULL, &r))) { \ fprintf(stderr, "error: %s\n", error_msg); \ goto error;\ }\ v = atoi(p); } while(0) GET_INT(w, "Bad width"); GET_INT(h, "Bad height"); if(type > 1) { GET_INT(d, "Bad depth"); } if(w <= 0 || h <= 0 || d <= 0) { fprintf(stderr, "error: invalid dimensions\n"); goto error; } printf("Creating bitmap %d x %d @ %d\n", w, h, d); bm = bm_create(w,h); for(y = 0; y < h; y++) { for(x = 0; x < w; x++) { int pr,pg,pb, c; switch(type) { case 1: case 2: GET_INT(pr, "Bad value"); pr = pr * 255 / d; pg = pr; pb = pr; break; case 3: GET_INT(pr, "Bad R value"); pr = pr * 255 / d; GET_INT(pg, "Bad G value"); pg = pg * 255 / d; GET_INT(pb, "Bad B value"); pb = pb * 255 / d; break; } c = 0xFF000000 | (pr << 16) | (pg << 8) | pb; bm_set(bm, x, y, c); } } goto done; error: if(bm) bm_free(bm); done: free(s); return bm; } #ifdef PBM_TEST int main(int argc, char *argv[]) { int i; for(i = 1; i < argc; i++) { struct bitmap *b = parse_pbm(argv[i]); if(b) { bm_save(b, "out.gif"); bm_free(b); } else { fprintf(stderr, "error: Unable to process %s\n", argv[i]); } } return 0; } #endif
3.15625
3
2024-11-18T21:30:14.071129+00:00
2010-04-07T05:32:00
2cc19b41493413e2ca34e7a80a2cceff8a8029fe
{ "blob_id": "2cc19b41493413e2ca34e7a80a2cceff8a8029fe", "branch_name": "refs/heads/master", "committer_date": "2010-04-07T05:32:00", "content_id": "4441f39c98af38b528855d4d7576796db872a4ad", "detected_licenses": [ "Apache-2.0" ], "directory_id": "4775e6f4bacaa291991bd9cb52eb9beb0ac7d1bf", "extension": "c", "filename": "message_queue.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": 9885, "license": "Apache-2.0", "license_type": "permissive", "path": "/reporting/c/src/message_queue.c", "provenance": "stackv2-0112.json.gz:191623", "repo_name": "enlight/wayward-metrics", "revision_date": "2010-04-07T05:32:00", "revision_id": "c6744797a4430fe4a0ea93551782c83b486c1ff2", "snapshot_id": "727c433d8a40ac32dd13c5eb63cbbde7ab97d582", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/enlight/wayward-metrics/c6744797a4430fe4a0ea93551782c83b486c1ff2/reporting/c/src/message_queue.c", "visit_date": "2021-01-10T21:36:15.164699" }
stackv2
#include "wayward/metrics/stdwwm.h" #include "wayward/metrics/message_queue.h" #include "wayward/metrics/allocator.h" #include "wayward/metrics/config.h" #include "wayward/metrics/thread.h" // This uses a concurrent queue based on http://www.cs.rochester.edu/u/michael/PODC96.html // but without the locks since we have a single reader and a single writer // thread for each queue. typedef struct _wwm_per_thread_queue_t_ *_wwm_per_thread_queue_t; //------------------------------------------------------------------------------ /** */ struct wwm_message_queue_t_ { wwm_connection_t connection; wwm_file_t file; wwm_thread_key_t per_thread_queue_key; wwm_thread_t background_thread; _wwm_per_thread_queue_t per_thread_queue_slist; wwm_buffer_t send_buffer; volatile bool shutdown_requested; }; //------------------------------------------------------------------------------ /** */ struct _wwm_per_thread_queue_t_ { wwm_message_queue_t owner; wwm_buffer_t head; wwm_buffer_t tail; _wwm_per_thread_queue_t next; }; static WWM_THREADPROC_RETTYPE WWM_THREADPROC _wwm_message_queue_start(void* queue); static void _wwm_message_queue_run(wwm_message_queue_t queue); static void _wwm_message_queue_add_per_thread_queue(wwm_message_queue_t queue, _wwm_per_thread_queue_t per_thread_queue); static void _wwm_message_queue_remove_per_thread_queue(wwm_message_queue_t queue, _wwm_per_thread_queue_t per_thread_queue); static _wwm_per_thread_queue_t _wwm_per_thread_queue_new(wwm_message_queue_t owner); static void _wwm_per_thread_queue_destroy(_wwm_per_thread_queue_t per_thread_queue); static void _wwm_per_thread_queue_enqueue(_wwm_per_thread_queue_t per_thread_queue, wwm_buffer_t buffer); static wwm_buffer_t _wwm_per_thread_queue_dequeue(_wwm_per_thread_queue_t per_thread_queue); //------------------------------------------------------------------------------ /** */ wwm_message_queue_t wwm_message_queue_new(void) { wwm_message_queue_t queue = (wwm_message_queue_t)g_wwm_allocator.calloc(1, sizeof(struct wwm_message_queue_t_)); queue->connection = NULL; queue->file = NULL; queue->send_buffer = wwm_buffer_new(5000); (void)wwm_thread_key_create(&(queue->per_thread_queue_key)); queue->background_thread = wwm_thread_new(); (void)wwm_thread_start(queue->background_thread, _wwm_message_queue_start, (void*)queue); return queue; } //------------------------------------------------------------------------------ /** */ void wwm_message_queue_destroy(wwm_message_queue_t queue) { queue->shutdown_requested = TRUE; (void)wwm_thread_join(queue->background_thread, NULL); wwm_thread_destroy(queue->background_thread); wwm_message_queue_exit_thread(queue); (void)wwm_thread_key_delete(queue->per_thread_queue_key); if (NULL != queue->connection) { wwm_connection_destroy(queue->connection); } if (NULL != queue->file) { wwm_file_destroy(queue->file); } wwm_buffer_destroy(queue->send_buffer); g_wwm_allocator.free(queue); } //------------------------------------------------------------------------------ /** If a thread makes use of a wwm_message_queue_t instance it did not create it should call this function prior to termination to ensure that any thread-specific resources obtained by the wwm_message_queue_t instance are released. */ void wwm_message_queue_exit_thread(wwm_message_queue_t queue) { void* ptq = wwm_thread_key_get(queue->per_thread_queue_key); if (NULL != ptq) { _wwm_per_thread_queue_destroy((_wwm_per_thread_queue_t)ptq); } } //------------------------------------------------------------------------------ /** */ void wwm_message_queue_set_connection(wwm_message_queue_t queue, wwm_connection_t conn) { queue->connection = conn; } //------------------------------------------------------------------------------ /** */ void wwm_message_queue_set_file(wwm_message_queue_t queue, wwm_file_t file) { queue->file = file; } //------------------------------------------------------------------------------ /** */ static WWM_THREADPROC_RETTYPE WWM_THREADPROC _wwm_message_queue_start(void* queue) { _wwm_message_queue_run((wwm_message_queue_t)queue); return 0; // Implied pthread_exit(NULL) } //------------------------------------------------------------------------------ /** */ static void _wwm_message_queue_run(wwm_message_queue_t queue) { while (FALSE == queue->shutdown_requested) { _wwm_per_thread_queue_t ptq; for (ptq = queue->per_thread_queue_slist; NULL != ptq; ptq = ptq->next) { int messages_handled = 0; wwm_buffer_t buffer = _wwm_per_thread_queue_dequeue(ptq); while (NULL != buffer) { queue->send_buffer = wwm_buffer_append_int32(queue->send_buffer, wwm_buffer_length(buffer)); queue->send_buffer = wwm_buffer_append_buffer(queue->send_buffer, buffer); messages_handled++; // XXX: Make this high water mark configurable: if (wwm_buffer_length(queue->send_buffer) > 50000) { if (NULL != queue->connection) { wwm_connection_send_buffer(queue->connection, queue->send_buffer); } if (NULL != queue->file) { wwm_file_send_buffer(queue->file, queue->send_buffer); } wwm_buffer_reset(queue->send_buffer); } buffer = _wwm_per_thread_queue_dequeue(ptq); } if (messages_handled > 0) { if (NULL != queue->connection) { wwm_connection_send_buffer(queue->connection, queue->send_buffer); } if (NULL != queue->file) { wwm_file_send_buffer(queue->file, queue->send_buffer); } wwm_buffer_reset(queue->send_buffer); } } } } //------------------------------------------------------------------------------ /** */ void wwm_message_queue_enqueue(wwm_message_queue_t queue, wwm_buffer_t buffer) { _wwm_per_thread_queue_t ptqueue = wwm_thread_key_get(queue->per_thread_queue_key); if (NULL == ptqueue) { ptqueue = _wwm_per_thread_queue_new(queue); wwm_thread_key_set(queue->per_thread_queue_key, ptqueue); } _wwm_per_thread_queue_enqueue(ptqueue, buffer); } //------------------------------------------------------------------------------ /** */ void wwm_message_queue_request_shutdown(wwm_message_queue_t queue) { queue->shutdown_requested = TRUE; } //------------------------------------------------------------------------------ /** */ static void _wwm_message_queue_add_per_thread_queue(wwm_message_queue_t queue, _wwm_per_thread_queue_t per_thread_queue) { if (NULL == queue->per_thread_queue_slist) { queue->per_thread_queue_slist = per_thread_queue; } else { _wwm_per_thread_queue_t tail = queue->per_thread_queue_slist; while (NULL != tail->next) { tail = tail->next; } tail->next = per_thread_queue; } } //------------------------------------------------------------------------------ /** */ static void _wwm_message_queue_remove_per_thread_queue(wwm_message_queue_t queue, _wwm_per_thread_queue_t per_thread_queue) { if (per_thread_queue == queue->per_thread_queue_slist) { queue->per_thread_queue_slist = per_thread_queue->next; } else { _wwm_per_thread_queue_t ptq; for (ptq = queue->per_thread_queue_slist; NULL != ptq->next; ptq = ptq->next) { if (per_thread_queue == ptq->next) { ptq->next = per_thread_queue->next; break; } } } } //------------------------------------------------------------------------------ /** */ static _wwm_per_thread_queue_t _wwm_per_thread_queue_new(wwm_message_queue_t owner) { _wwm_per_thread_queue_t ptqueue = (_wwm_per_thread_queue_t)g_wwm_allocator.malloc(sizeof(struct _wwm_per_thread_queue_t_)); ptqueue->owner = owner; ptqueue->head = ptqueue->tail = wwm_buffer_new(0); ptqueue->next = NULL; _wwm_message_queue_add_per_thread_queue(owner, ptqueue); return ptqueue; } //------------------------------------------------------------------------------ /** */ static void _wwm_per_thread_queue_destroy(_wwm_per_thread_queue_t per_thread_queue) { _wwm_message_queue_remove_per_thread_queue(per_thread_queue->owner, per_thread_queue); // XXX: Destroy any remaining items in the queue? } //------------------------------------------------------------------------------ /** */ static void _wwm_per_thread_queue_enqueue(_wwm_per_thread_queue_t per_thread_queue, wwm_buffer_t buffer) { MemoryBarrier(); wwm_buffer_set_next(per_thread_queue->tail, buffer); per_thread_queue->tail = buffer; } //------------------------------------------------------------------------------ /** */ static wwm_buffer_t _wwm_per_thread_queue_dequeue(_wwm_per_thread_queue_t per_thread_queue) { wwm_buffer_t old_head = per_thread_queue->head; wwm_buffer_t next_head = wwm_buffer_get_next(old_head); if (NULL == next_head) { // queue was empty. return NULL; } per_thread_queue->head = next_head; wwm_buffer_destroy(old_head); return next_head; }
2.5
2
2024-11-18T21:30:14.509780+00:00
2021-05-07T17:23:18
cb2926b52496c9dd734f7d51d074334f2bbc521b
{ "blob_id": "cb2926b52496c9dd734f7d51d074334f2bbc521b", "branch_name": "refs/heads/master", "committer_date": "2021-05-07T17:23:18", "content_id": "3f4beb839b9d12d54ecee6878f55b8693c856155", "detected_licenses": [ "MIT" ], "directory_id": "071351a7a15a754acecb28d0a23929485fe5a6b4", "extension": "c", "filename": "robo_base.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 313322104, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11063, "license": "MIT", "license_type": "permissive", "path": "/Robo_Base 2.0/robo_base.c", "provenance": "stackv2-0112.json.gz:192269", "repo_name": "2021IFRControlSystemGroup/Code_Library", "revision_date": "2021-05-07T17:23:18", "revision_id": "aafc2f7f665ce2405b1b28c5a9f1e544c90482ec", "snapshot_id": "0ed37e677b31c6c6676ddd29a65685c8ded5e755", "src_encoding": "GB18030", "star_events_count": 0, "url": "https://raw.githubusercontent.com/2021IFRControlSystemGroup/Code_Library/aafc2f7f665ce2405b1b28c5a9f1e544c90482ec/Robo_Base 2.0/robo_base.c", "visit_date": "2023-04-17T03:00:40.913697" }
stackv2
//文件名称: robo_base.c //对应头文件: robo_base.h //主要功能: // 调用motor_system封装的速度环/位置环/看门狗函数, 实现底盘控制 // //时间: // 2020/11/27 // //版本: 2.0V // //状态: // 已初步测试 // //测试内容: // 无电机情况下测试成功, 看门狗功能实现, 串口通信正常 //---------头文件引用部分---------// #include "robo_base.h" //--------------------------------// //---------变量声明部分-----------// ROBO_BASE Robo_Base; //--------------------------------// //---------外部变量声明部分-------// //--------------------------------// //--------------------------------------------------------------------------------------------------// //函数名称: // 位置环电机数据分析的接口函数 // //函数功能: // 读取Robo_Base对应的CAN口储存的数据, 根据电机号码来分辨是哪一个轮子的信息, 然后储存电机数据. // //参数类型: // ROBO_BASE 指针, 底盘结构体的指针 // uint8_t* 电机信息的数组, 推荐使用Rx_CAN变量, 这样可以不需要自己去声明. // uint32_t 电机号码 // //移植建议: // 直接对case的数据进行修改, 有几个位置环的轮子就加几个, 然后让指针指向对应的轮子就行. // //--------------------------------------------------------------------------------------------------// void Motor_Pos_Analysis(ROBO_BASE* Robo,uint8_t* RX_Data,uint32_t Motor_Num) { Pos_System* P_Motor=NULL; switch(Motor_Num) { case 0x201:P_Motor=&Robo->Pos_MotorLF;break; case 0x202:P_Motor=&Robo->Pos_MotorRF;break; case 0x203:P_Motor=&Robo->Pos_MotorRB;break; case 0x204:P_Motor=&Robo->Pos_MotorLB;break; default:break; }if(!P_Motor) return ; Pos_Info_Analysis(&P_Motor->Info,RX_Data); Feed_WatchDog(&P_Motor->Protect); } //--------------------------------------------------------------------------------------------------// //函数名称: // 速度环电机数据分析的接口函数 // //函数功能: // 读取Robo_Base对应的CAN口储存的数据, 根据电机号码来分辨是哪一个轮子的信息, 然后储存电机数据. // //参数类型: // ROBO_BASE 指针, 底盘结构体的指针 // uint8_t* 电机信息的数组, 推荐使用Rx_CAN变量, 这样可以不需要自己去声明. // uint32_t 电机号码 // //移植建议: // 直接对case的数据进行修改, 有几个速度环的轮子就加几个, 然后让指针指向对应的轮子就行. // //--------------------------------------------------------------------------------------------------// void Motor_Speed_Analysis(ROBO_BASE* Robo,uint8_t* RX_Data,uint32_t Motor_Num) { Speed_System* S_Motor=NULL; switch(Motor_Num) { case 0x201:S_Motor=&Robo->Speed_MotorLF;break; case 0x202:S_Motor=&Robo->Speed_MotorRF;break; case 0x203:S_Motor=&Robo->Speed_MotorRB;break; case 0x204:S_Motor=&Robo->Speed_MotorLB;break; default:break; }if(!S_Motor) return ; Speed_Info_Analysis(&S_Motor->Info,RX_Data); Feed_WatchDog(&S_Motor->Protect); } //--------------------------------------------------------------------------------------------------// //函数名称: // 系统输入输出值转化为字符串函数 // //函数功能: // 把速度环/位置环系统的输入输出值转化成字符串, 以便通过串口发送到上位机 // //参数类型: // int32_t 系统输出值 // int32_t 系统输入值 // //移植建议: // 如果担心数据特别大, 可以把temp的数据再调大一点, 但是需要保证缓冲区的长度够长 //--------------------------------------------------------------------------------------------------// void SystemIO_Usart_ToString(ROBO_BASE* Robo,int32_t System_Out,int32_t System_In) { uint8_t* Usart_Tx=Robo->Uart2.Tx_buffer; int32_t temp=1000000; uint8_t flag1=0; //转化系统输出值 Robo->Uart2.Tx_length=0; if(System_Out<0) Usart_Tx[Robo->Uart2.Tx_length++]='-',System_Out=-System_Out; else if(System_Out==0) Usart_Tx[Robo->Uart2.Tx_length++]='0',temp=0; while(temp!=0) { if(System_Out/temp!=0) { flag1=1; Usart_Tx[Robo->Uart2.Tx_length++]='0'+System_Out/temp; System_Out-=System_Out/temp*temp; if(System_Out==0) { temp/=10; while(temp!=0) { Usart_Tx[Robo->Uart2.Tx_length++]='0'; temp/=10; }break; } }else if(flag1) Usart_Tx[Robo->Uart2.Tx_length++]='0'; temp/=10; }Usart_Tx[Robo->Uart2.Tx_length++]=' '; temp=10000; flag1=0; //转化系统输入值 if(System_In<0) Usart_Tx[Robo->Uart2.Tx_length++]='-',System_In=-System_In; else if(System_In==0) Usart_Tx[Robo->Uart2.Tx_length++]='0',temp=0; while(temp!=0) { if(System_In/temp!=0) { flag1=1; Usart_Tx[Robo->Uart2.Tx_length++]='0'+System_In/temp; System_In-=System_In/temp*temp; if(System_In==0) { temp/=10; while(temp!=0) { Usart_Tx[Robo->Uart2.Tx_length++]='0'; temp/=10; }break; } }else if(flag1) Usart_Tx[Robo->Uart2.Tx_length++]='0'; temp/=10; } Usart_Tx[Robo->Uart2.Tx_length++]='\r'; Usart_Tx[Robo->Uart2.Tx_length]='\n'; } //--------------------------------------------------------------------------------------------------// //函数名称: // 底盘参数初始化 // //函数功能: // 初始化底盘所有的信息 // //参数类型: // ROBO_BASE 指针, 底盘结构体的指针 // //移植建议: // 有什么状态, 电机, 电机状态都先把数据封装进ROBO_BASE结构体里, 然后直接初始化就好了 // //--------------------------------------------------------------------------------------------------// void BASE_Init(ROBO_BASE *Robo) { Pos_System* P_Pos=NULL; P_Pos=&Robo->Pos_MotorLF; PID_Init(&P_Pos->Pos_PID, 0.3, 0, 0, 5000, 0, 0, 7000); P_Pos->Motor_Num=0; PID_Init(&P_Pos->Speed_PID, 5, 0, 0, 5000, 0, 0, 7000); P_Pos->Protect.Count_Time=WATCHDOG_TIME_MAX; SystemState_Set(&P_Pos->Protect,MISSING); P_Pos=&Robo->Pos_MotorRF; PID_Init(&P_Pos->Pos_PID, 0, 0, 0, 0, 0, 0, 0); P_Pos->Motor_Num=1; PID_Init(&P_Pos->Speed_PID, 0, 0, 0, 0, 0, 0, 0); P_Pos->Protect.Count_Time=WATCHDOG_TIME_MAX; SystemState_Set(&P_Pos->Protect,MISSING); P_Pos=&Robo->Pos_MotorRB; PID_Init(&P_Pos->Pos_PID, 0, 0, 0, 0, 0, 0, 0); P_Pos->Motor_Num=2; PID_Init(&P_Pos->Speed_PID, 0, 0, 0, 0, 0, 0, 0); P_Pos->Protect.Count_Time=WATCHDOG_TIME_MAX; SystemState_Set(&P_Pos->Protect,MISSING); P_Pos=&Robo->Pos_MotorLB; PID_Init(&P_Pos->Pos_PID, 0, 0, 0, 0, 0, 0, 0); P_Pos->Motor_Num=3; PID_Init(&P_Pos->Speed_PID, 0, 0, 0, 0, 0, 0, 0); P_Pos->Protect.Count_Time=WATCHDOG_TIME_MAX; SystemState_Set(&P_Pos->Protect,MISSING); Speed_System* P_Speed=NULL; P_Speed=&Robo->Speed_MotorLF; PID_Init(&P_Speed->Speed_PID, 5, 0, 0, 5000, 0, 0, 7000); P_Speed->Motor_Num=0; P_Speed->Protect.Count_Time=WATCHDOG_TIME_MAX; SystemState_Set(&P_Speed->Protect,MISSING); P_Speed=&Robo->Speed_MotorRF; PID_Init(&P_Speed->Speed_PID, 0, 0, 0, 0, 0, 0, 0); P_Speed->Motor_Num=1; P_Speed->Protect.Count_Time=WATCHDOG_TIME_MAX; SystemState_Set(&P_Speed->Protect,MISSING); P_Speed=&Robo->Speed_MotorRB; PID_Init(&P_Speed->Speed_PID, 0, 0, 0, 0, 0, 0, 0); P_Speed->Motor_Num=2; P_Speed->Protect.Count_Time=WATCHDOG_TIME_MAX; SystemState_Set(&P_Speed->Protect,MISSING); P_Speed=&Robo->Speed_MotorLB; PID_Init(&P_Speed->Speed_PID, 0, 0, 0, 0, 0, 0, 0); P_Speed->Motor_Num=3; P_Speed->Protect.Count_Time=WATCHDOG_TIME_MAX; SystemState_Set(&P_Speed->Protect,MISSING); } //--------------------------------------------------------------------------------------------------// //函数名称: // PID发送函数 // //函数功能: // 发送电机PID // //参数类型: // ROBO_BASE* 底盘结构体指针 // //移植建议: // 有需要啥环的控制就让指针指向这个系统, 然后调用对应的PID计算函数进行处理 // //--------------------------------------------------------------------------------------------------// void PID_Send(ROBO_BASE* Robo) { Base_WatchDog(Robo); Pos_System* P_Pos=NULL; P_Pos=&Robo->Pos_MotorLB; PID_Pos_Cal(P_Pos,Robo->Can2.Tx); P_Pos=&Robo->Pos_MotorRB; PID_Pos_Cal(P_Pos,Robo->Can2.Tx); P_Pos=&Robo->Pos_MotorLF; PID_Pos_Cal(P_Pos,Robo->Can2.Tx); P_Pos=&Robo->Pos_MotorRF; PID_Pos_Cal(P_Pos,Robo->Can2.Tx); Send_To_Motor(&hcan2,Robo->Can2.Tx); Speed_System* P_Speed=NULL; P_Speed=&Robo->Speed_MotorLB; PID_Speed_Cal(P_Speed,Robo->Can1.Tx); P_Speed=&Robo->Speed_MotorRB; PID_Speed_Cal(P_Speed,Robo->Can1.Tx); P_Speed=&Robo->Speed_MotorLF; PID_Speed_Cal(P_Speed,Robo->Can1.Tx); P_Speed=&Robo->Speed_MotorRF; PID_Speed_Cal(P_Speed,Robo->Can1.Tx); Send_To_Motor(&hcan1,Robo->Can2.Tx); } //--------------------------------------------------------------------------------------------------// //函数名称: // 底盘看门狗检测函数 // //函数功能: // 定时检测底盘上各个电机状态, 出现问题后调整底盘工作模式 // //参数类型: // ROBO_BASE* 底盘结构体指针 // //移植建议: // 需要添加或删除位置环系统就直接添加 // //--------------------------------------------------------------------------------------------------// void Base_WatchDog(ROBO_BASE* Robo) { RoboBaseState Error_State=SYSTEM_WORKING; Pos_System* P_Pos=NULL; P_Pos=&Robo->Pos_MotorLF; POS_SYSTEM_CHECK; P_Pos=&Robo->Pos_MotorRF; POS_SYSTEM_CHECK; P_Pos=&Robo->Pos_MotorRB; POS_SYSTEM_CHECK; P_Pos=&Robo->Pos_MotorLB; POS_SYSTEM_CHECK; Speed_System* P_Speed=NULL; P_Speed=&Robo->Speed_MotorLF; SPEED_SYSTEM_CHECK; P_Speed=&Robo->Speed_MotorRF; SPEED_SYSTEM_CHECK; P_Speed=&Robo->Speed_MotorRB; SPEED_SYSTEM_CHECK; P_Speed=&Robo->Speed_MotorLB; SPEED_SYSTEM_CHECK; Robo->State=Error_State; if(Error_State!=WORKING) LED_WARNING(Robo); } //--------------------------------------------------------------------------------------------------// //函数名称: // 底盘运行时间函数 // //函数功能: // 记录底盘运行时间 // //参数类型: // ROBO_BASE* 底盘结构体指针 // //--------------------------------------------------------------------------------------------------// void Counting_Time(ROBO_BASE* Robo) { Robo->Running_Time++; if(Robo->Running_Time>RUNNING_TIME_MAX) Robo->Running_Time=0; } //--------------------------------------------------------------------------------------------------// //函数名称: // 底盘LED报警函数 // //函数功能: // 当底盘处于非正常工作状态时, 通过控制LED闪烁特定情况来提示错误 // //参数类型: // ROBO_BASE* 底盘结构体指针 // //--------------------------------------------------------------------------------------------------// void LED_WARNING(ROBO_BASE* Robo) { static uint8_t State=1; static uint8_t Flag=0; if(State==(uint8_t)Robo->State) State=0; if(Robo->Running_Time%3000-(State*300)<100) { HAL_GPIO_WritePin(GPIOC,GPIO_PIN_1,GPIO_PIN_SET); } else { HAL_GPIO_WritePin(GPIOC,GPIO_PIN_1,GPIO_PIN_RESET); if(!Flag) Flag=1; } if(Flag) State++,Flag=0; }
2.46875
2
2024-11-18T21:30:14.599463+00:00
2016-05-30T00:44:07
ff5bddd08ea5544b9bbe1fd64fdb23cd24684f3b
{ "blob_id": "ff5bddd08ea5544b9bbe1fd64fdb23cd24684f3b", "branch_name": "refs/heads/master", "committer_date": "2016-05-30T00:44:07", "content_id": "f198040a19fb0e61d0987d529387270629e5ca48", "detected_licenses": [ "MIT" ], "directory_id": "489b2340f0ef1da50a605efd2ab451303920dbab", "extension": "c", "filename": "checksum.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 52045940, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 959, "license": "MIT", "license_type": "permissive", "path": "/Proj1/final/checksum.c", "provenance": "stackv2-0112.json.gz:192397", "repo_name": "peboson/NetworkProj", "revision_date": "2016-05-30T00:44:07", "revision_id": "12034173ba511d674fd88adc41862c2f2209d25e", "snapshot_id": "ed3b46d5d75ef947dfd1eb827f6926000e57c579", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/peboson/NetworkProj/12034173ba511d674fd88adc41862c2f2209d25e/Proj1/final/checksum.c", "visit_date": "2021-01-21T13:33:57.481537" }
stackv2
#include "checksum.h" uint32_t checksum32(uint32_t crc, void* buf, size_t len){ uint64_t sum=0; uint32_t *buf_uint32=buf; while(len){ sum+=(*buf_uint32); buf_uint32++; len-=4; } uint8_t *buf_uint8=(uint8_t *)buf_uint32; uint32_t remain=0; size_t i; for(i=0;i<4;i++){ remain=(remain<<8); if(len){ remain+=*buf_uint8; buf_uint8++; len--; } } sum+=remain; return (uint32_t)((sum>>32)+sum); } uint32_t deprecated_crc32(uint32_t crc, void* buf, size_t len){ crc = crc ^ ~0U; uint8_t *buf_uint8=buf; uint32_t POLY=0x04C11DB7; size_t i; while(len--){ crc=crc^((*buf_uint8)<<24); buf_uint8++; for(i=0;i<8;i++){ if(crc&0x80000000){ crc=(crc<<1)^POLY; }else{ crc<<=1; } } crc&=0xFFFFFFFF; } return crc; }
2.5
2
2024-11-18T21:30:15.318961+00:00
2020-04-17T19:20:02
276ebe38a67491402ee5e6f95f306bd41ac73b02
{ "blob_id": "276ebe38a67491402ee5e6f95f306bd41ac73b02", "branch_name": "refs/heads/master", "committer_date": "2020-04-17T19:20:02", "content_id": "33e2edc26867feb9122cd7db271dcd10ca4c5a0c", "detected_licenses": [ "MIT" ], "directory_id": "b3d708a7f5511c788338b94daec64432833c66d6", "extension": "c", "filename": "flock.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 226702065, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2347, "license": "MIT", "license_type": "permissive", "path": "/C/arbitrator/tests/locks/flock.c", "provenance": "stackv2-0112.json.gz:192656", "repo_name": "shlomif/ip-noise", "revision_date": "2020-04-17T19:20:02", "revision_id": "9f8050a88e15e9f359f558b2c231b0993f0785f9", "snapshot_id": "e144bacca55b0230be076762fe5f2f22e63eefb5", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/shlomif/ip-noise/9f8050a88e15e9f359f558b2c231b0993f0785f9/C/arbitrator/tests/locks/flock.c", "visit_date": "2020-09-28T05:38:30.469597" }
stackv2
#include <sys/file.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <pthread.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #define filename "mylock" #define NUM_READERS 5 #define NUM_WRITERS 2 struct context_struct { int writer; int index; }; typedef struct context_struct context_t; void * reader_thread(void * void_context) { context_t * context; int fd; context = (context_t *)void_context; fd = open(filename, O_RDONLY); while (1) { flock(fd, LOCK_SH); printf("Reader %i - Lock!\n", context->index); usleep(rand()%1000000); flock(fd, LOCK_UN); printf("Reader %i - Unlock!\n", context->index); usleep(rand()%1000000); } close(fd); return NULL; } void * writer_thread(void * void_context) { context_t * context; int fd; context = (context_t *)void_context; fd = open(filename, O_RDONLY); while (1) { flock(fd, LOCK_EX); printf("Writer %i - Lock!\n", context->index); usleep(rand()%1000000); flock(fd, LOCK_UN); printf("Writer %i - Unlock!\n", context->index); usleep(rand()%1000000); } close(fd); return NULL; } int main(int argc, char * argv[]) { context_t * context; pthread_t readers[NUM_READERS]; pthread_t writers[NUM_WRITERS]; int check; int a; for(a=0;a<NUM_READERS;a++) { context = malloc(sizeof(context)); context->index = a; context->writer = 0; check = pthread_create( &readers[a], NULL, reader_thread, context ); if (check != 0) { fprintf(stderr, "Could not create Reader #%i!\n", a); exit(-1); } } for(a=0;a<NUM_WRITERS;a++) { context = malloc(sizeof(context)); context->index = a; context->writer = 0; check = pthread_create( &writers[a], NULL, writer_thread, context ); if (check != 0) { fprintf(stderr, "Could not create Reader #%i!\n", a); exit(-1); } } while (1) { sleep(1); } }
3.15625
3
2024-11-18T21:30:15.500101+00:00
2018-06-09T12:00:54
331349b4fe45692dbf9ef3a0d7a1eb713cef13b9
{ "blob_id": "331349b4fe45692dbf9ef3a0d7a1eb713cef13b9", "branch_name": "refs/heads/master", "committer_date": "2018-06-09T12:00:54", "content_id": "4cc7b91e8b0ec70c0ac5d27f58088d83f139ed73", "detected_licenses": [ "MIT" ], "directory_id": "c249b1ad063f27997954212267beb60f0b722dee", "extension": "c", "filename": "File.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 136715783, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 526, "license": "MIT", "license_type": "permissive", "path": "/mie creazioni/Informatica/C/MyLibrary/MyLibrary/File.c", "provenance": "stackv2-0112.json.gz:192917", "repo_name": "andre-bisa/Archive", "revision_date": "2018-06-09T12:00:54", "revision_id": "9599342d684172391d8919714e5494082615efb8", "snapshot_id": "e7a91e62a02071594968080d2f65bff24f061f58", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/andre-bisa/Archive/9599342d684172391d8919714e5494082615efb8/mie creazioni/Informatica/C/MyLibrary/MyLibrary/File.c", "visit_date": "2020-03-19T16:26:57.462697" }
stackv2
// Bisacchi Andrea 0000753177 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include "File.h" //apre un file; FILE* openFile(char percorso[], char come[]) { FILE* file; if ((file = fopen(percorso, come)) == NULL) { perror("Errore nell'aprire il file!"); exit(1); } return file; } int readField(char buffer[], char sep, FILE *f) { int i = 0; char ch = fgetc(f); while (ch != sep && ch != 10 && ch != EOF) { buffer[i] = ch; i++; ch = fgetc(f); } buffer[i] = '\0'; return ch; }
2.703125
3
2024-11-18T21:30:15.850974+00:00
2018-06-24T18:26:16
4e39bd88260fa8c2bbf1251eb5fc22b29b03d827
{ "blob_id": "4e39bd88260fa8c2bbf1251eb5fc22b29b03d827", "branch_name": "refs/heads/master", "committer_date": "2018-06-24T18:26:16", "content_id": "6308f010d553ddeb0e0dde86177a01497e8f2d36", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "ee4b23a7d3e81ce72e1fafeaac50297bee0ca83d", "extension": "c", "filename": "mergesort.c", "fork_events_count": 2, "gha_created_at": "2018-03-03T12:27:59", "gha_event_created_at": "2018-03-30T21:37:29", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 123689848, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1190, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/exemplos/12-MergeSort/mergesort.c", "provenance": "stackv2-0112.json.gz:193179", "repo_name": "flaviovdf/estruturas-de-dados", "revision_date": "2018-06-24T18:26:16", "revision_id": "328b591f3a1b74cc6db2c1210f74d69fb2df225a", "snapshot_id": "fea1a5feb18901c4d63ad420b595d580fa683341", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/flaviovdf/estruturas-de-dados/328b591f3a1b74cc6db2c1210f74d69fb2df225a/exemplos/12-MergeSort/mergesort.c", "visit_date": "2021-01-25T14:22:51.643658" }
stackv2
#import <stdlib.h> int *merge(int *valuesL, int *valuesR, int nl, int nr) { int *result = (int *) malloc((nl+nr) * sizeof(int)); int i = 0; int j = 0; int k = 0; while (i < nl && j < nr) { if (valuesL[i] < valuesR[j]) { result[k] = valuesL[i]; i++; } else { result[k] = valuesR[j]; j++; } k++; } if (k < nl + nr) { for(; i < nl; i++) { result[k] = valuesL[i]; k++; } for(; j < nr; j++) { result[k] = valuesR[j]; k++; } } return result; } //end e start são inclusivos neste código int *mergesort(int *values, int start, int end) { int *result; if (end == start) { result = malloc(1 * sizeof(int)); result[0] = values[start]; return result; } int mid = (end + start) / 2; int *left = mergesort(values, start, mid); int *right = mergesort(values, mid+1, end); result = merge(left, right, mid-start+1, end-mid); free(left); free(right); return result; } int main(void) { int *values = (int *)malloc(5 * sizeof(int)); values[0] = 2; values[1] = 9; values[2] = 1; values[3] = 3; values[4] = 0; int *result = mergesort(values, 0, 4); return 0; }
3.390625
3
2024-11-18T21:30:16.043812+00:00
2018-01-23T09:34:35
c15ece8815af4476f6b0e74e83eb345c7676ff4f
{ "blob_id": "c15ece8815af4476f6b0e74e83eb345c7676ff4f", "branch_name": "refs/heads/master", "committer_date": "2018-01-23T09:34:35", "content_id": "cd30061fc0ccbe933259b3829ff2261ee2937d39", "detected_licenses": [ "Apache-2.0" ], "directory_id": "a61ff1ebcc142711cecd4104c89e9c1928df9d94", "extension": "c", "filename": "shared_memory.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": 4762, "license": "Apache-2.0", "license_type": "permissive", "path": "/shared_memory.c", "provenance": "stackv2-0112.json.gz:193312", "repo_name": "isakedo/shared_memory", "revision_date": "2018-01-23T09:34:35", "revision_id": "f621a51b4b471d15d99efbb30b88d90873045eb5", "snapshot_id": "1ec069817bab58cbdfb8a5c98c8d65edbbbcf01e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/isakedo/shared_memory/f621a51b4b471d15d99efbb30b88d90873045eb5/shared_memory.c", "visit_date": "2021-09-05T01:16:00.253594" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <linux/ioctl.h> #include <time.h> #include <fcntl.h> #include <string.h> /* Shutdown message ID */ #define SHUTDOWN_MSG 0xEF56A55A #define PING 0xEF56A559 #define WRITE_NOW 0xEF56A558 #define MEM_SIZE (sizeof(unsigned long)*1024) struct _payload { unsigned int message; unsigned long size; off_t data; }; static int fd, fdsm; struct _payload *i_payload; struct _payload *r_payload; #define RPMSG_GET_KFIFO_SIZE 1 #define RPMSG_GET_AVAIL_DATA_SIZE 2 #define RPMSG_GET_FREE_SPACE 3 #define RPMSG_HEADER_LEN 16 #define MAX_RPMSG_BUFF_SIZE (512 - RPMSG_HEADER_LEN) #define PAYLOAD_MIN_SIZE 1 #define PAYLOAD_MAX_SIZE (MAX_RPMSG_BUFF_SIZE - 24) #define NUM_PAYLOADS (PAYLOAD_MAX_SIZE/PAYLOAD_MIN_SIZE) int main(int argc, char *argv[]) { int flag = 1; int shutdown_msg = SHUTDOWN_MSG; int ping_msg = PING; int writenow_msg = WRITE_NOW; int cmd, ret; int size, bytes_rcvd, bytes_sent; int opt; char *rpmsg_dev="/dev/rpmsg0"; char *shared_mem="/dev/sharedmemory"; while ((opt = getopt(argc, argv, "d:")) != -1) { switch (opt) { case 'd': rpmsg_dev = optarg; break; default: printf("getopt return unsupported option: -%c\n",opt); break; } } printf("\r\n Shared memory test start \r\n"); printf("\r\n Open rpmsg dev! \r\n"); fd = open(rpmsg_dev, O_RDWR | O_NONBLOCK); if (fd < 0) { perror("Failed to open rpmsg file /dev/rpmsg0."); return -1; } fdsm = open(shared_mem, O_RDWR);//prueba abrir el módulo if (fdsm < 0) { perror("Failed to open /dev/sahredmemory."); return -1; } off_t address = ioctl(fdsm,0,0); printf("\r\n Query internal info .. \r\n"); ioctl(fd, RPMSG_GET_KFIFO_SIZE, &size); printf(" rpmsg kernel fifo size = %u \r\n", size); ioctl(fd, RPMSG_GET_FREE_SPACE, &size); printf(" rpmsg kernel fifo free space = %u \r\n", size); i_payload = (struct _payload *)malloc(sizeof(unsigned int) + sizeof(unsigned long) + PAYLOAD_MAX_SIZE); r_payload = (struct _payload *)malloc(sizeof(unsigned int) + sizeof(unsigned long) + PAYLOAD_MAX_SIZE); if (i_payload == 0 || r_payload == 0) { printf("ERROR: Failed to allocate memory for payload.\n"); return -1; } while (flag == 1) { printf("\r\n **************************************** \r\n"); printf(" Please enter command and press enter key\r\n"); printf(" **************************************** \r\n"); printf(" 1 - Bare metal writes one 4B data\r\n"); printf(" 2 - Linux writes one 4B data\r\n"); printf(" 3 - Read one 4B data\r\n"); printf(" 4 - Send data to remote core, retrieve the echo"); printf(" and validate its integrity .. \r\n"); printf(" 5 - Quit this application .. \r\n"); printf(" CMD>"); ret = scanf("%d", &cmd); if (!ret) { while (1) { if (getchar() == '\n') break; } printf("\r\n invalid command\r\n"); continue; } if (cmd == 1) { i_payload->message = writenow_msg; i_payload->data = address; i_payload->size = sizeof(unsigned int) + sizeof(unsigned long) + sizeof(i_payload->data); write(fd,i_payload,i_payload->size); printf("\r\n one 4B data writen by bare metal \r\n"); } else if (cmd == 2) { char buf[] = "1357"; write(fdsm,buf,sizeof(buf)); printf("\r\n one 4B data writen by bare metal \r\n"); } else if (cmd == 3) { char buf[4]; read(fdsm,buf,sizeof(buf)); printf("\r\nDATA: %x \r\n",buf[0]); printf("DATA: %x \r\n",buf[1]); printf("DATA: %x \r\n",buf[2]); printf("DATA: %x \r\n",buf[3]); } else if (cmd == 4) { i_payload->message = ping_msg; i_payload->data = "Echo"; i_payload->size = sizeof(unsigned int) + sizeof(unsigned long) + sizeof(i_payload->data); bytes_sent = write(fd,i_payload,i_payload->size); if (bytes_sent <= 0) { printf("\r\n Error sending data"); printf(" .. \r\n"); break; } printf("echo test: sent : %s\n", i_payload->data); bytes_rcvd = read(fd, r_payload,(sizeof(unsigned int) + sizeof(unsigned long)) + PAYLOAD_MAX_SIZE); while (bytes_rcvd <= 0) { usleep(10000); bytes_rcvd = read(fd, r_payload, (sizeof(unsigned int) + sizeof(unsigned long)) + PAYLOAD_MAX_SIZE); } printf("echo test: received : %s\n", r_payload->data); } else if (cmd == 5) { flag = 0; /* Send shutdown message to remote */ i_payload->message = shutdown_msg; i_payload->size = sizeof(unsigned int) + sizeof(unsigned long); write(fd,i_payload,i_payload->size); sleep(1); printf("\r\n Quitting application .. \r\n"); printf(" Shared memory test end \r\n"); } else { printf("\r\n invalid command! \r\n"); } } free(i_payload); free(r_payload); close(fd); close(fdsm); return 0; }
2.609375
3
2024-11-18T21:30:16.486531+00:00
2019-11-15T20:26:20
8cce5f50fb53a6faa193a10db4d67278ed8fddad
{ "blob_id": "8cce5f50fb53a6faa193a10db4d67278ed8fddad", "branch_name": "refs/heads/master", "committer_date": "2019-11-15T20:26:20", "content_id": "7400d59648f0cb6e846e517ff598db260b851998", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "7c2ea365f20ff3eaec12b7a5289c21f345373d40", "extension": "c", "filename": "sptree.c", "fork_events_count": 1, "gha_created_at": "2019-07-08T13:51:17", "gha_event_created_at": "2019-10-02T11:45:39", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 195821881, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 15672, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/nrncvode/sptree.c", "provenance": "stackv2-0112.json.gz:193444", "repo_name": "wwlytton/nrn", "revision_date": "2019-11-15T20:26:20", "revision_id": "32b01882064583582a7ac2b563c4babf874b14ea", "snapshot_id": "95892cb08b993d0cc9377d7136304bc9196723ef", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/wwlytton/nrn/32b01882064583582a7ac2b563c4babf874b14ea/src/nrncvode/sptree.c", "visit_date": "2020-06-17T05:59:34.145205" }
stackv2
/* * * sptree.c: The following code implements the basic operations on * an event-set or priority-queue implemented using splay trees: * Hines changed to void spinit(SPTREE**) for use with TQueue. * SPTREE *spinit( compare ) Make a new tree * int spempty(); Is tree empty? * SPBLK *spenq( n, q ) Insert n in q after all equal keys. * SPBLK *spdeq( np ) Return first key under *np, removing it. * SPBLK *spenqprior( n, q ) Insert n in q before all equal keys. * void splay( n, q ) n (already in q) becomes the root. * * In the above, n points to an SPBLK type, while q points to an * SPTREE. * * The implementation used here is based on the implementation * which was used in the tests of splay trees reported in: * * An Empirical Comparison of Priority-Queue and Event-Set Implementations, * by Douglas W. Jones, Comm. ACM 29, 4 (Apr. 1986) 300-311. * * The changes made include the addition of the enqprior * operation and the addition of up-links to allow for the splay * operation. The basic splay tree algorithms were originally * presented in: * * Self Adjusting Binary Trees, * by D. D. Sleator and R. E. Tarjan, * Proc. ACM SIGACT Symposium on Theory * of Computing (Boston, Apr 1983) 235-245. * * The enq and enqprior routines use variations on the * top-down splay operation, while the splay routine is bottom-up. * All are coded for speed. * * Written by: * Douglas W. Jones * * Translated to C by: * David Brower, daveb@rtech.uucp * * Thu Oct 6 12:11:33 PDT 1988 (daveb) Fixed spdeq, which was broken * handling one-node trees. I botched the pascal translation of * a VAR parameter. */ # include "sptree.h" /* USER SUPPLIED! */ /*extern char *emalloc();*/ /*---------------- * * spinit() -- initialize an empty splay tree * */ void spinit(SPTREE* q) { q->lookups = 0; q->lkpcmps = 0; q->enqs = 0; q->enqcmps = 0; q->splays = 0; q->splayloops = 0; q->root = NULL; } /*---------------- * * spempty() -- is an event-set represented as a splay tree empty? */ int spempty( SPTREE* q ) { return( q == NULL || q->root == NULL ); } /*---------------- * * spenq() -- insert item in a tree. * * put n in q after all other nodes with the same key; when this is * done, n will be the root of the splay tree representing q, all nodes * in q with keys less than or equal to that of n will be in the * left subtree, all with greater keys will be in the right subtree; * the tree is split into these subtrees from the top down, with rotations * performed along the way to shorten the left branch of the right subtree * and the right branch of the left subtree */ SPBLK * spenq( SPBLK* n, SPTREE* q ) { register SPBLK * left; /* the rightmost node in the left tree */ register SPBLK * right; /* the leftmost node in the right tree */ register SPBLK * next; /* the root of the unsplit part */ register SPBLK * temp; double key; register int Sct; /* Strcmp value */ q->enqs++; n->uplink = NULL; next = q->root; q->root = n; if( next == NULL ) /* trivial enq */ { n->leftlink = NULL; n->rightlink = NULL; } else /* difficult enq */ { key = n->key; left = n; right = n; /* n's left and right children will hold the right and left splayed trees resulting from splitting on n->key; note that the children will be reversed! */ q->enqcmps++; if ( STRCMP( next->key, key ) > 0 ) goto two; one: /* assert next->key <= key */ do /* walk to the right in the left tree */ { temp = next->rightlink; if( temp == NULL ) { left->rightlink = next; next->uplink = left; right->leftlink = NULL; goto done; /* job done, entire tree split */ } q->enqcmps++; if( STRCMP( temp->key, key ) > 0 ) { left->rightlink = next; next->uplink = left; left = next; next = temp; goto two; /* change sides */ } next->rightlink = temp->leftlink; if( temp->leftlink != NULL ) temp->leftlink->uplink = next; left->rightlink = temp; temp->uplink = left; temp->leftlink = next; next->uplink = temp; left = temp; next = temp->rightlink; if( next == NULL ) { right->leftlink = NULL; goto done; /* job done, entire tree split */ } q->enqcmps++; } while( STRCMP( next->key, key ) <= 0 ); /* change sides */ two: /* assert next->key > key */ do /* walk to the left in the right tree */ { temp = next->leftlink; if( temp == NULL ) { right->leftlink = next; next->uplink = right; left->rightlink = NULL; goto done; /* job done, entire tree split */ } q->enqcmps++; if( STRCMP( temp->key, key ) <= 0 ) { right->leftlink = next; next->uplink = right; right = next; next = temp; goto one; /* change sides */ } next->leftlink = temp->rightlink; if( temp->rightlink != NULL ) temp->rightlink->uplink = next; right->leftlink = temp; temp->uplink = right; temp->rightlink = next; next->uplink = temp; right = temp; next = temp->leftlink; if( next == NULL ) { left->rightlink = NULL; goto done; /* job done, entire tree split */ } q->enqcmps++; } while( STRCMP( next->key, key ) > 0 ); /* change sides */ goto one; done: /* split is done, branches of n need reversal */ temp = n->leftlink; n->leftlink = n->rightlink; n->rightlink = temp; } #if BBTQ != 4 && BBTQ != 5 n->cnt++; #endif return( n ); } /* spenq */ /*---------------- * * spdeq() -- return and remove head node from a subtree. * * remove and return the head node from the node set; this deletes * (and returns) the leftmost node from q, replacing it with its right * subtree (if there is one); on the way to the leftmost node, rotations * are performed to shorten the left branch of the tree */ SPBLK * spdeq( SPBLK** np ) /* pointer to a node pointer */ { register SPBLK * deq; /* one to return */ register SPBLK * next; /* the next thing to deal with */ register SPBLK * left; /* the left child of next */ register SPBLK * farleft; /* the left child of left */ register SPBLK * farfarleft; /* the left child of farleft */ if( np == NULL || *np == NULL ) { deq = NULL; } else { next = *np; left = next->leftlink; if( left == NULL ) { deq = next; *np = next->rightlink; if( *np != NULL ) (*np)->uplink = NULL; } else for(;;) /* left is not null */ { /* next is not it, left is not NULL, might be it */ farleft = left->leftlink; if( farleft == NULL ) { deq = left; next->leftlink = left->rightlink; if( left->rightlink != NULL ) left->rightlink->uplink = next; break; } /* next, left are not it, farleft is not NULL, might be it */ farfarleft = farleft->leftlink; if( farfarleft == NULL ) { deq = farleft; left->leftlink = farleft->rightlink; if( farleft->rightlink != NULL ) farleft->rightlink->uplink = left; break; } /* next, left, farleft are not it, rotate */ next->leftlink = farleft; farleft->uplink = next; left->leftlink = farleft->rightlink; if( farleft->rightlink != NULL ) farleft->rightlink->uplink = left; farleft->rightlink = left; left->uplink = farleft; next = farleft; left = farfarleft; } } return( deq ); } /* spdeq */ /*---------------- * * spenqprior() -- insert into tree before other equal keys. * * put n in q before all other nodes with the same key; after this is * done, n will be the root of the splay tree representing q, all nodes in * q with keys less than that of n will be in the left subtree, all with * greater or equal keys will be in the right subtree; the tree is split * into these subtrees from the top down, with rotations performed along * the way to shorten the left branch of the right subtree and the right * branch of the left subtree; the logic of spenqprior is exactly the * same as that of spenq except for a substitution of comparison * operators */ SPBLK * spenqprior( SPBLK* n, SPTREE* q ) { register SPBLK * left; /* the rightmost node in the left tree */ register SPBLK * right; /* the leftmost node in the right tree */ register SPBLK * next; /* the root of unsplit part of tree */ register SPBLK * temp; register int Sct; /* Strcmp value */ double key; n->uplink = NULL; next = q->root; q->root = n; if( next == NULL ) /* trivial enq */ { n->leftlink = NULL; n->rightlink = NULL; } else /* difficult enq */ { key = n->key; left = n; right = n; /* n's left and right children will hold the right and left splayed trees resulting from splitting on n->key; note that the children will be reversed! */ if( STRCMP( next->key, key ) >= 0 ) goto two; one: /* assert next->key < key */ do /* walk to the right in the left tree */ { temp = next->rightlink; if( temp == NULL ) { left->rightlink = next; next->uplink = left; right->leftlink = NULL; goto done; /* job done, entire tree split */ } if( STRCMP( temp->key, key ) >= 0 ) { left->rightlink = next; next->uplink = left; left = next; next = temp; goto two; /* change sides */ } next->rightlink = temp->leftlink; if( temp->leftlink != NULL ) temp->leftlink->uplink = next; left->rightlink = temp; temp->uplink = left; temp->leftlink = next; next->uplink = temp; left = temp; next = temp->rightlink; if( next == NULL ) { right->leftlink = NULL; goto done; /* job done, entire tree split */ } } while( STRCMP( next->key, key ) < 0 ); /* change sides */ two: /* assert next->key >= key */ do /* walk to the left in the right tree */ { temp = next->leftlink; if( temp == NULL ) { right->leftlink = next; next->uplink = right; left->rightlink = NULL; goto done; /* job done, entire tree split */ } if( STRCMP( temp->key, key ) < 0 ) { right->leftlink = next; next->uplink = right; right = next; next = temp; goto one; /* change sides */ } next->leftlink = temp->rightlink; if( temp->rightlink != NULL ) temp->rightlink->uplink = next; right->leftlink = temp; temp->uplink = right; temp->rightlink = next; next->uplink = temp; right = temp; next = temp->leftlink; if( next == NULL ) { left->rightlink = NULL; goto done; /* job done, entire tree split */ } } while( STRCMP( next->key, key ) >= 0 ); /* change sides */ goto one; done: /* split is done, branches of n need reversal */ temp = n->leftlink; n->leftlink = n->rightlink; n->rightlink = temp; } return( n ); } /* spenqprior */ /*---------------- * * splay() -- reorganize the tree. * * the tree is reorganized so that n is the root of the * splay tree representing q; results are unpredictable if n is not * in q to start with; q is split from n up to the old root, with all * nodes to the left of n ending up in the left subtree, and all nodes * to the right of n ending up in the right subtree; the left branch of * the right subtree and the right branch of the left subtree are * shortened in the process * * this code assumes that n is not NULL and is in q; it can sometimes * detect n not in q and complain */ void splay( SPBLK* n, SPTREE* q ) { register SPBLK * up; /* points to the node being dealt with */ register SPBLK * prev; /* a descendent of up, already dealt with */ register SPBLK * upup; /* the parent of up */ register SPBLK * upupup; /* the grandparent of up */ register SPBLK * left; /* the top of left subtree being built */ register SPBLK * right; /* the top of right subtree being built */ #if BBTQ != 4 && BBTQ != 5 n->cnt++; /* bump reference count */ #endif left = n->leftlink; right = n->rightlink; prev = n; up = prev->uplink; q->splays++; while( up != NULL ) { q->splayloops++; /* walk up the tree towards the root, splaying all to the left of n into the left subtree, all to right into the right subtree */ upup = up->uplink; if( up->leftlink == prev ) /* up is to the right of n */ { if( upup != NULL && upup->leftlink == up ) /* rotate */ { upupup = upup->uplink; upup->leftlink = up->rightlink; if( upup->leftlink != NULL ) upup->leftlink->uplink = upup; up->rightlink = upup; upup->uplink = up; if( upupup == NULL ) q->root = up; else if( upupup->leftlink == upup ) upupup->leftlink = up; else upupup->rightlink = up; up->uplink = upupup; upup = upupup; } up->leftlink = right; if( right != NULL ) right->uplink = up; right = up; } else /* up is to the left of n */ { if( upup != NULL && upup->rightlink == up ) /* rotate */ { upupup = upup->uplink; upup->rightlink = up->leftlink; if( upup->rightlink != NULL ) upup->rightlink->uplink = upup; up->leftlink = upup; upup->uplink = up; if( upupup == NULL ) q->root = up; else if( upupup->rightlink == upup ) upupup->rightlink = up; else upupup->leftlink = up; up->uplink = upupup; upup = upupup; } up->rightlink = left; if( left != NULL ) left->uplink = up; left = up; } prev = up; up = upup; } # ifdef DEBUG if( q->root != prev ) { /* fprintf(stderr, " *** bug in splay: n not in q *** " ); */ abort(); } # endif n->leftlink = left; n->rightlink = right; if( left != NULL ) left->uplink = n; if( right != NULL ) right->uplink = n; q->root = n; n->uplink = NULL; } /* splay */
2.640625
3
2024-11-18T21:30:18.007560+00:00
2020-12-26T16:46:14
556daafc6d4859c2db61f32fd4d25a9750f68547
{ "blob_id": "556daafc6d4859c2db61f32fd4d25a9750f68547", "branch_name": "refs/heads/main", "committer_date": "2020-12-26T16:46:14", "content_id": "b2d2c8297cde86548fd28506c8ebc475ed9ddf7a", "detected_licenses": [ "MIT", "Apache-2.0" ], "directory_id": "d9f2050f6813bc4a66fcb6458914422343dede23", "extension": "c", "filename": "pop.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 319149791, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1135, "license": "MIT,Apache-2.0", "license_type": "permissive", "path": "/_src/Lecture2_materials/SourceCode/P12/pop.c", "provenance": "stackv2-0112.json.gz:193575", "repo_name": "paullewallencom/spring-978-1-7891-3277-9", "revision_date": "2020-12-26T16:46:14", "revision_id": "61f2ed3d92a816d713bfed67c05b9e37a99843b4", "snapshot_id": "d725677d3540f425f3593933aec95b7c20238283", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/paullewallencom/spring-978-1-7891-3277-9/61f2ed3d92a816d713bfed67c05b9e37a99843b4/_src/Lecture2_materials/SourceCode/P12/pop.c", "visit_date": "2023-02-04T02:32:20.712363" }
stackv2
/* Pointer assignments program */ #include<stdio.h> #include<assert.h> #include<stdlib.h> struct node { int data; struct node* next; }; void append_data(struct node** headRef, int data) { assert(headRef != NULL); if (*headRef == NULL) { *headRef = (struct node*)malloc(sizeof(struct node)); (*headRef)->data = data; (*headRef)->next = NULL; return; } struct node* head = *headRef; while (head->next != NULL) { head = head->next; } head->next = (struct node*)malloc(sizeof(struct node)); head->next->data = data; head->next->next = NULL; } int pop(struct node** headRef) { assert(headRef != NULL); if (*headRef != NULL) { printf("Freeing: %d", (*headRef)->data); struct node* next = (*headRef)->next; int data = (*headRef)->data; (*headRef)->next = NULL; free(*headRef); *headRef = next; return data; } assert(0); } int main() { struct node* head = NULL; append_data(&head, 4); append_data(&head, 5); append_data(&head, 6); printf("Pop: %d", pop(&head)); printf("Pop: %d", pop(&head)); printf("Pop: %d", pop(&head)); }
3.625
4
2024-11-18T21:30:18.299739+00:00
2018-07-16T14:00:39
929b121e4f7128ed846a0f00b5572b43729f5e54
{ "blob_id": "929b121e4f7128ed846a0f00b5572b43729f5e54", "branch_name": "refs/heads/master", "committer_date": "2018-07-16T14:00:39", "content_id": "7c990cab50db1365a8febeb75d716491775e7759", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "22b1d5a4d5f325c5d999adf9337c6aed4c24eb8a", "extension": "c", "filename": "echo.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 134846406, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4149, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/echo/echo.c", "provenance": "stackv2-0112.json.gz:194101", "repo_name": "zhuzhonghua/scheme_nginx", "revision_date": "2018-07-16T14:00:39", "revision_id": "45ea207513339b3b5248a52b3d3dfa7b5420e55b", "snapshot_id": "29ac32c502441c599ab9cc0e8803029be309e682", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/zhuzhonghua/scheme_nginx/45ea207513339b3b5248a52b3d3dfa7b5420e55b/echo/echo.c", "visit_date": "2020-03-18T14:24:23.073121" }
stackv2
#include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> /* Module config */ typedef struct { ngx_str_t ed; } ngx_http_echo_loc_conf_t; static char *ngx_http_echo(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); static void *ngx_http_echo_create_loc_conf(ngx_conf_t *cf); static char *ngx_http_echo_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child); /* Directives */ static ngx_command_t ngx_http_echo_commands[] = { { ngx_string("echo"), NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1, ngx_http_echo, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_echo_loc_conf_t, ed), NULL }, ngx_null_command }; /* Http context of the module */ static ngx_http_module_t ngx_http_echo_module_ctx = { NULL, /* preconfiguration */ NULL, /* postconfiguration */ NULL, /* create main configuration */ NULL, /* init main configuration */ NULL, /* create server configuration */ NULL, /* merge server configuration */ ngx_http_echo_create_loc_conf, /* create location configration */ ngx_http_echo_merge_loc_conf /* merge location configration */ }; /* Module */ ngx_module_t ngx_http_echo_module = { NGX_MODULE_V1, &ngx_http_echo_module_ctx, /* module context */ ngx_http_echo_commands, /* module directives */ NGX_HTTP_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ NULL, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ NULL, /* exit process */ NULL, /* exit master */ NGX_MODULE_V1_PADDING }; /* Handler function */ static ngx_int_t ngx_http_echo_handler(ngx_http_request_t *r) { ngx_int_t rc; ngx_buf_t *b; ngx_chain_t out; ngx_http_echo_loc_conf_t *elcf; elcf = ngx_http_get_module_loc_conf(r, ngx_http_echo_module); if(!(r->method & (NGX_HTTP_HEAD|NGX_HTTP_GET|NGX_HTTP_POST))) { return NGX_HTTP_NOT_ALLOWED; } r->headers_out.content_type.len = sizeof("text/html") - 1; r->headers_out.content_type.data = (u_char *) "text/html"; r->headers_out.status = NGX_HTTP_OK; r->headers_out.content_length_n = elcf->ed.len; if(r->method == NGX_HTTP_HEAD) { rc = ngx_http_send_header(r); if(rc != NGX_OK) { return rc; } } b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t)); if(b == NULL) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "Failed to allocate response buffer."); return NGX_HTTP_INTERNAL_SERVER_ERROR; } out.buf = b; out.next = NULL; b->pos = elcf->ed.data; b->last = elcf->ed.data + (elcf->ed.len); b->memory = 1; b->last_buf = 1; rc = ngx_http_send_header(r); if(rc != NGX_OK) { return rc; } return ngx_http_output_filter(r, &out); } static char * ngx_http_echo(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { ngx_http_core_loc_conf_t *clcf; clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module); clcf->handler = ngx_http_echo_handler; ngx_conf_set_str_slot(cf,cmd,conf); return NGX_CONF_OK; } static void * ngx_http_echo_create_loc_conf(ngx_conf_t *cf) { ngx_http_echo_loc_conf_t *conf; conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_echo_loc_conf_t)); if (conf == NULL) { return NGX_CONF_ERROR; } conf->ed.len = 0; conf->ed.data = NULL; return conf; } static char * ngx_http_echo_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child) { ngx_http_echo_loc_conf_t *prev = parent; ngx_http_echo_loc_conf_t *conf = child; ngx_conf_merge_str_value(conf->ed, prev->ed, ""); return NGX_CONF_OK; }
2.265625
2
2024-11-18T21:30:19.540746+00:00
2017-03-14T23:05:07
2c032e4f330b281223f182ddd0e6e7006590221b
{ "blob_id": "2c032e4f330b281223f182ddd0e6e7006590221b", "branch_name": "refs/heads/master", "committer_date": "2017-03-14T23:05:07", "content_id": "526667056578de17a6fe53e5e73c5e83f217aecc", "detected_licenses": [ "MIT" ], "directory_id": "e2badd96718c8cfb9a361f4daa37d01385da5cd9", "extension": "c", "filename": "frisbee_array.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 98244441, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1354, "license": "MIT", "license_type": "permissive", "path": "/frisbee_array.c", "provenance": "stackv2-0112.json.gz:194489", "repo_name": "mmzdnp3/XV6-Kernel-Threads", "revision_date": "2017-03-14T23:05:07", "revision_id": "341c623827772a1beca702d4716e0765fcaf04a3", "snapshot_id": "0d11fc5da0a3c1af6ec92352f441240566bb65bf", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mmzdnp3/XV6-Kernel-Threads/341c623827772a1beca702d4716e0765fcaf04a3/frisbee_array.c", "visit_date": "2021-01-01T18:05:22.383776" }
stackv2
#include "types.h" #include "stat.h" #include "user.h" int numPasses; int numThreads; int currPass = 1; int holder = 0; arraylock_t lock; void passFrisbee(void* arg) { int threadnumber = *(int*)arg; int my_place; for(;;) { //printf(0,"\n\nThread %d acquiring lock\n\n", threadnumber); arraylock_acquire(&lock, &my_place); if(numPasses <= 0) { arraylock_release(&lock, &my_place); break; } if(holder != threadnumber) { arraylock_release(&lock, &my_place); continue; } holder++; if(holder == numThreads) { holder = 0; } printf(0, "Pass number no. %d, Thread %d is passing the token to %d\n", currPass, threadnumber, holder); numPasses--; currPass++; arraylock_release(&lock, &my_place); } return; } int main(int argc, char *argv[]) { if(argc != 3) { printf(0,"Usage: frisbee numThreads numPasses\n"); exit(); } numThreads = atoi(argv[1]); numPasses = atoi(argv[2]); printf(0,"Num Threads: %d, Num Passes: %d\n", numThreads, numPasses); arraylock_init(&lock, numThreads); int i,rc; for(i = 0; i < numThreads; i++) { int * t = malloc(sizeof(*t)); *t = i; rc = thread_create((void*)passFrisbee,(void*)t); } for(i = 0; i < numThreads; i++) { wait(); } printf(0,"Simulation of frisbee game has finished, %d rounds were played in total!\n", currPass-1); exit(); }
2.9375
3
2024-11-18T21:30:21.440547+00:00
2018-04-05T13:45:53
659a058bd6b1fe2843e17c8c261c35b789da1572
{ "blob_id": "659a058bd6b1fe2843e17c8c261c35b789da1572", "branch_name": "refs/heads/master", "committer_date": "2018-04-05T13:45:53", "content_id": "0da69a8f88b522e436f0742dd43e901dd8e63fde", "detected_licenses": [ "MIT" ], "directory_id": "2cac6968e748f2a0e5fe3ff127ad31bdfc2202cc", "extension": "h", "filename": "PBR.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 127533632, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5454, "license": "MIT", "license_type": "permissive", "path": "/assets/Shaders/PBR.h", "provenance": "stackv2-0112.json.gz:195271", "repo_name": "Atrix256/DX12Concise", "revision_date": "2018-04-05T13:45:53", "revision_id": "6b71f51549bbe61b5d80df7e91620cf252e722e2", "snapshot_id": "777310de4570b2cb8e2b14ce0dc0ee9e7edea83c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Atrix256/DX12Concise/6b71f51549bbe61b5d80df7e91620cf252e722e2/assets/Shaders/PBR.h", "visit_date": "2020-03-07T14:42:58.227040" }
stackv2
static const float c_roughnessEpsilon = 0.01f; static const float c_F0 = 0.04f; static const float c_pi = 3.14159265359f; float DistributionGGX(float3 N, float3 H, float roughness) { float a = roughness * roughness; float a2 = a * a; float NdotH = max(dot(N, H), 0.0); float NdotH2 = NdotH * NdotH; float nom = a2; float denom = (NdotH2 * (a2 - 1.0) + 1.0); denom = c_pi * denom * denom; return nom / denom; } float GeometrySchlickGGX(float NdotV, float roughness) { float r = (roughness + 1.0); float k = (r*r) / 8.0; float nom = NdotV; float denom = NdotV * (1.0 - k) + k; return nom / denom; } float GeometrySmith(float3 N, float3 V, float3 L, float roughness) { float NdotV = max(dot(N, V), 0.0); float NdotL = max(dot(N, L), 0.0); float ggx2 = GeometrySchlickGGX(NdotV, roughness); float ggx1 = GeometrySchlickGGX(NdotL, roughness); return ggx1 * ggx2; } float3 fresnelSchlickRoughness (float cosTheta, float3 F0, float roughness) { return F0 + (max(float3(1.0 - roughness, 1.0 - roughness, 1.0 - roughness), F0) - F0) * pow(1.0 - cosTheta, 5.0); } float3 fresnelSchlick (float cosTheta, float3 F0) { return F0 + (1.0 - F0) * pow(1.0 - cosTheta, 5.0); } float2 SampleSplitSum(float NdotV, float roughness, in Texture2D<float4> texIBLSplitSum) { float2 uv = float2(NdotV, roughness); uint w, h; texIBLSplitSum.GetDimensions(w, h); float halfPixelW = 0.5f / w; float halfPixelH = 0.5f / h; uv.x = clamp(uv.x, halfPixelW, 1.0f - halfPixelW); uv.y = clamp(uv.y, halfPixelH, 1.0f - halfPixelH); return texIBLSplitSum.Sample(sampleWrap, uv).rg; } float3 ImageBasedLighting (in float3 N, in float3 V, in float3 R, in float3 albedo, in float metallic, in float roughness, in float scalarF0, in TextureCube<float4> texIBLDiffuse, in TextureCube<float4> texIBLSpecular, in Texture2D<float4> texIBLSplitSum) { // avoid roughness asymptotes. Totally a legit, industry standard thing to do! if (roughness < c_roughnessEpsilon) roughness = c_roughnessEpsilon; else if (roughness > 1.0f - c_roughnessEpsilon) roughness = 1.0f - c_roughnessEpsilon; float3 F0 = float3(scalarF0, scalarF0, scalarF0); F0 = lerp(F0, albedo, metallic); float3 F = fresnelSchlickRoughness(max(dot(N, V), 0.0), F0, roughness); float3 kS = F; float3 kD = 1.0 - kS; kD *= 1.0 - metallic; // diffuse IBL float3 irradiance = texIBLDiffuse.Sample(sampleWrap, N * float3(1.0f, 1.0f, -1.0f)).rgb; float3 diffuse = irradiance * albedo; // specular IBL const float MAX_REFLECTION_LOD = 4.0; float3 prefilteredColor = texIBLSpecular.SampleLevel(sampleWrap, R * float3(1.0f, 1.0f, -1.0f), roughness * MAX_REFLECTION_LOD).rgb; float2 brdf = SampleSplitSum(max(dot(N, V), 0.0), roughness, texIBLSplitSum); float3 specular = prefilteredColor * (F * brdf.x + brdf.y); float3 ambient = (kD * diffuse + specular); return ambient; } float3 PositionalLight(in float3 worldPos, in float3 N, in float3 V, in float3 lightPos, in float3 lightColor, in float3 albedo, in float metallic, in float roughness, in float scalarF0) { // avoid roughness asymptotes. Totally a legit, industry standard thing to do! if (roughness < c_roughnessEpsilon) roughness = c_roughnessEpsilon; else if (roughness > 1.0f - c_roughnessEpsilon) roughness = 1.0f - c_roughnessEpsilon; float distance = length(lightPos - worldPos); float attenuation = 1.0 / (distance * distance); float3 L = normalize(lightPos - worldPos); float3 H = normalize(V + L); float3 radiance = lightColor * attenuation; float3 F0 = float3(scalarF0, scalarF0, scalarF0); F0 = lerp(F0, albedo, metallic); float3 F = fresnelSchlick(max(dot(H, V), 0.0), F0); float NDF = DistributionGGX(N, H, roughness); float G = GeometrySmith(N, V, L, roughness); float3 nominator = NDF * G * F; float denominator = 4.0 * max(dot(N, V), 0.0) * max(dot(N, L), 0.0); float3 specular = nominator / max(denominator, 0.001); float3 kS = F; float3 kD = float3(1.0f, 1.0f, 1.0f) - kS; kD *= 1.0 - metallic; float NdotL = max(dot(N, L), 0.0); return (kD * albedo / c_pi + specular) * radiance * NdotL; } float3 DirectionalLight(in float3 N, in float3 V, in float3 lightDir, in float3 lightColor, in float3 albedo, in float metallic, in float roughness, in float scalarF0) { // avoid roughness asymptotes. Totally a legit, industry standard thing to do! if (roughness < c_roughnessEpsilon) roughness = c_roughnessEpsilon; else if (roughness > 1.0f - c_roughnessEpsilon) roughness = 1.0f - c_roughnessEpsilon; float3 L = lightDir; float3 H = normalize(V + L); float3 radiance = lightColor; float3 F0 = float3(scalarF0, scalarF0, scalarF0); F0 = lerp(F0, albedo, metallic); float3 F = fresnelSchlick(max(dot(H, V), 0.0), F0); float NDF = DistributionGGX(N, H, roughness); float G = GeometrySmith(N, V, L, roughness); float3 nominator = NDF * G * F; float denominator = 4.0 * max(dot(N, V), 0.0) * max(dot(N, L), 0.0); float3 specular = nominator / max(denominator, 0.001); float3 kS = F; float3 kD = float3(1.0f, 1.0f, 1.0f) - kS; kD *= 1.0 - metallic; float NdotL = max(dot(N, L), 0.0); return (kD * albedo / c_pi + specular) * radiance * NdotL; }
2.296875
2
2024-11-18T21:30:21.661142+00:00
2019-01-21T20:31:18
931a35096755a3d004b9ec9701bb9718311ba5bd
{ "blob_id": "931a35096755a3d004b9ec9701bb9718311ba5bd", "branch_name": "refs/heads/master", "committer_date": "2019-01-21T20:31:18", "content_id": "7a276a5315a0606e142196ba14c8cc4d7266d6ee", "detected_licenses": [ "MIT" ], "directory_id": "e1e7d8dc656aec9ed0f6969ba32f93bcb65bc346", "extension": "c", "filename": "Multi_task.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 138931656, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5942, "license": "MIT", "license_type": "permissive", "path": "/Multi_task.c", "provenance": "stackv2-0112.json.gz:195660", "repo_name": "adityah-b/DeepDigger", "revision_date": "2019-01-21T20:31:18", "revision_id": "3615dd34d8c5085ba7356dd4e167f1c7dbec7089", "snapshot_id": "ea19b96d589e42dfc746f1583fe83b28f494a2a5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/adityah-b/DeepDigger/3615dd34d8c5085ba7356dd4e167f1c7dbec7089/Multi_task.c", "visit_date": "2020-03-21T19:08:20.104734" }
stackv2
#include <lpc17xx.h> #include <stdio.h> #include <stdbool.h> #include <RTL.h> #include "GLCD.h" #include "game.h" // Global Variables uint32_t min_row, min_col; uint32_t max_row, max_col; char map[MAX_SCREEN_WIDTH][MAX_SCREEN_LENGTH]; // Temporary // Tasks __task void updateDisplay(void); __task void pollPushButton(void); __task void pollJoystick(void); __task void updateFuelStatus(void); __task void moveRobot(void); __task void buyFuel(void); /* Character Struct */ typedef struct { volatile uint32_t x_pos, y_pos; uint32_t num_gold, num_silver, num_copper; uint32_t fuel_status; uint32_t num_points; bool is_flying; // Robot Inputs volatile uint32_t dir; volatile uint32_t select_action; } robot_t; robot_t robot; /* Character Struct */ /* Semaphore Implementation */ typedef uint32_t sem_t; sem_t action_performed, display_refreshed; void init(sem_t *s, uint32_t count) { *s = count; } void wait(sem_t *s) { __disable_irq(); while(*s ==0) { __enable_irq(); __disable_irq(); } (*s)--; __enable_irq(); } void signal(sem_t *s) { __disable_irq(); (*s)++; __enable_irq(); } /* Semaphore Implementation */ __task void mainTask(void) { // Create tasks os_tsk_create(updateDisplay, 1); os_tsk_create(pollPushButton, 2); os_tsk_create(pollJoystick, 2); os_tsk_create(updateFuelStatus, 3); os_tsk_create(moveRobot, 3); os_tsk_create(buyFuel, 4); os_tsk_delete_self(); } void loadBMP(int row, int col) { unsigned char *output_bmp; switch(map[row][col]) { // E R D G S C P X F // Dirt, gold, emerald, copper, sky, rock, path,fuel // TODO: digger in black path, digger in sky, case 'S': output_bmp = (unsigned char *)sky_bmp; break; case 'R': output_bmp = (unsigned char *)rock_bmp; break; case 'D': output_bmp = (unsigned char *)dirt_bmp; break; case 'G': output_bmp = (unsigned char *)gold_bmp; break; case 'E': output_bmp = (unsigned char *)emerald_bmp; break; case 'C': output_bmp = (unsigned char *)copper_bmp; break; case 'F': output_bmp = (unsigned char *)fuel_bmp; break; case 'X': if (row <= SURFACE) { if (robot.dir == LEFT) output_bmp = (unsigned char *)x_sky_left_bmp; else output_bmp = (unsigned char *)x_sky_right_bmp; } else { if (robot.dir == LEFT) output_bmp = (unsigned char *)x_path_left_bmp; else output_bmp = (unsigned char *)x_path_right_bmp; } break; default: output_bmp = (unsigned char *)path_bmp; break; } GLCD_Bitmap(row,col,40,40, output_bmp); } __task void updateDisplay(void) { os_itv_set(10); // Declare current row and column uint32_t row, col; while(1) { // Wait until something has changed on the screen wait(&action_performed); GLCD_SetTextColor(Blue); GLCD_SetBackColor(Blue); GLCD_Clear(Blue); for (row=min_row; row<max_row; row++) { for (col=min_col; col<max_col; col++) { // Print char value of array element at {row, col} on LCD Display output_bmp(row, col); } } // Signal that LCD Display has been redrawn signal(&display_refreshed); os_tsk_pass(); } } __task void pollPushButton(void) { os_itv_set(10); // Sensor Fusion Algorithm Initialization while(1) { // Wait until IMU data has been read wait(&cond_1); // Update data // Signal that sensorFusion algorithm has been run successfully signal(&cond_2); os_tsk_pass(); } } __task void pollJoystick(void) { os_itv_set(10); while(1) { // Wait until sensorFusion algorithm has been run wait(&cond_2); // Output data to game //printf("%f,%f,%f\n", sensor_fusion_getRoll(), -sensor_fusion_getYaw(), sensor_fusion_getPitch()); os_tsk_pass(); } } __task void updateFuelStatus(void) { os_itv_set(10); while(1) { // Wait until sensorFusion algorithm has been run wait(&cond_2); // Output data to game //printf("%f,%f,%f\n", sensor_fusion_getRoll(), -sensor_fusion_getYaw(), sensor_fusion_getPitch()); os_tsk_pass(); } } __task void moveRobot(void) { os_itv_set(10); while(1) { // Wait until sensorFusion algorithm has been run wait(&cond_2); // Output data to game //printf("%f,%f,%f\n", sensor_fusion_getRoll(), -sensor_fusion_getYaw(), sensor_fusion_getPitch()); os_tsk_pass(); } } int main(void) { unsigned char *direction, *button_pressed; uint32_t val; uint32_t mask = 15 << 23; unsigned char *digger_bmp2; int i = 160, j = 120; int count = 0; // Initialize semaphores to 0 init(&action_performed, 1); init(&display_refreshed, 0); // Initialize peripherals LED_setup(); GLCD_Init(); digger_bmp2 = (unsigned char *)digger_bmp; while (1) { val = LPC_GPIO1 -> FIOPIN; switch(~val & mask) { case 1 << 23 : //direction = "RIGHT "; i+=40; break; case 1 << 24 : //direction = "DOWN "; j+=40; break; case 1 << 25 : //direction = "LEFT "; i-=40; break; case 1 << 26 : //direction = "UP "; j-=40; break; default: direction = "No Dir"; } if (i+40 >= 320) i = 0; GLCD_SetTextColor(Blue); GLCD_SetBackColor(Blue); GLCD_Clear(Blue); while(count <= 1000) { count++; } count = 0; GLCD_Bitmap(i,j,40,40, digger_bmp2); // i+=40; while(count <= 10000000){ count++; } count = 0; } printf("Starting Program"); // Initialize main task //os_sys_init(mainTask); } /* run update map, map array should be 100x100 initially, min_row = 0, max_row = 6 min_col = 0, max_col = 8 in char array, position of robot marked with X when printing, if array[x_pos][y_pos] == X, run task to print robot bitmap then continue from there */
2.234375
2
2024-11-18T22:23:37.816942+00:00
2021-08-04T13:22:36
4e5e28cfeedc698c0eaeb47eb14bc1aa85c5cdb0
{ "blob_id": "4e5e28cfeedc698c0eaeb47eb14bc1aa85c5cdb0", "branch_name": "refs/heads/master", "committer_date": "2021-08-04T13:22:36", "content_id": "9297bdc9e1a3b1b0a1a3d4e38989ae5889e88893", "detected_licenses": [ "MIT" ], "directory_id": "0886915293fb19f899e53080127400fda11571f3", "extension": "c", "filename": "OscError.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 174867293, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4453, "license": "MIT", "license_type": "permissive", "path": "/OSC.Native/OscError.c", "provenance": "stackv2-0115.json.gz:66864", "repo_name": "BobbyCannon/Sproto", "revision_date": "2021-08-04T13:22:36", "revision_id": "5764e98220bc43a1a8033e34264324649b468928", "snapshot_id": "dd96f167a606bce31b48544eadaf44786070a2f5", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/BobbyCannon/Sproto/5764e98220bc43a1a8033e34264324649b468928/OSC.Native/OscError.c", "visit_date": "2021-10-30T19:29:39.789704" }
stackv2
#include "OscCommon.h" #include "OscError.h" /* * @brief Returns the error message associated with the error code. * * Example use: * @code * OscMessage oscMessage; * const OscError oscError = OscMessageInitialize(&oscMessage, "/example/address/pattern"); * printf(OscErrorGetMessage(oscError)); * @endcode * * @param oscError Error code returned by library function. * @return Error message string. */ char* OscErrorGetMessage(const OscError oscError) { #ifdef OSC_ERROR_MESSAGES_ENABLED switch (oscError) { case OscErrorNone: return (char *) &"No error."; /* Common errors */ case OscErrorDestinationTooSmall: return (char *) &"Destination size too small to contain the number of bytes available."; case OscErrorSizeIsNotMultipleOfFour: return (char *) &"OSC packet or OSC contents size must be a multiple of four."; case OscErrorCallbackFunctionUndefined: return (char *) &"Callback function undefined."; /* OscAddress errors */ case OscErrorNotEnoughPartsInAddressPattern: return (char *) &"Not enough parts in OSC address pattern to get part at specified index."; /* OscMessage errors */ case OscErrorNoSlashAtStartOfMessage: return (char *) &"OSC address pattern does not start with a slash character."; case OscErrorAddressPatternTooLong: return (char *) &"OSC address pattern length cannot exceed MAX_OSC_ADDRESS_PATTERN_LENGTH."; case OscErrorTooManyArguments: return (char *) &"Number of arguments cannot exceed MAX_NUMBER_OF_ARGUMENTS."; case OscErrorArgumentsSizeTooLarge: return (char *) &"Total arguments size cannot exceed MAX_ARGUMENTS_SIZE."; case OscErrorUndefinedAddressPattern: return (char *) &"Undefined OSC address pattern."; case OscErrorMessageSizeTooSmall: return (char *) &"OSC message size too small to be a valid OSC message."; case OscErrorMessageSizeTooLarge: return (char *) &"OSC message size cannot exceed MAX_OSC_MESSAGE_SIZE."; case OscErrorSourceEndsBeforeEndOfAddressPattern: return (char *) &"Source data ends before the end of address pattern."; case OscErrorSourceEndsBeforeStartOfTypeTagString: return (char *) &"Source data ends before the start of type tag string."; case OscErrorTypeTagStringToLong: return (char *) &"Type tag string length cannot exceed MAX_OSC_TYPE_TAG_STRING_LENGTH."; case OscErrorSourceEndsBeforeEndOfTypeTagString: return (char *) &"Source data ends before the end of type tag string."; case OscErrorUnexpectedEndOfSource: return (char *) &"Unexpected end of source data."; case OscErrorNoArgumentsAvailable: return (char *) &"No arguments available."; case OscErrorUnexpectedArgumentType: return (char *) &"Unexpected argument type."; case OscErrorMessageTooShortForArgumentType: return (char *) &"OSC message is too short to contain argument type."; /* OscBundle errors */ case OscErrorBundleFull: return (char *) &"Not enough space available in OSC bundle to contain contents."; case OscErrorBundleSizeTooSmall: return (char *) &"OSC bundle size too small to be a valid OSC bundle."; case OscErrorBundleSizeTooLarge: return (char *) &"OSC bundle size cannot exceed MAX_OSC_BUNDLE_SIZE."; case OscErrorNoHashAtStartOfBundle: return (char *) &"OSC bundle does not start with a hash character."; case OscErrorBundleElementNotAvailable: return (char *) &"OSC bundle element not available."; case OscErrorNegativeBundleElementSize: return (char *) &"OSC bundle element size cannot be negative."; case OscErrorInvalidElementSize: return (char *) &"OSC bundle too short to contain the OSC bundle element size."; /* OscPacket errors */ case OscErrorInvalidContents: return (char *) &"OSC contents is not an OSC bundle or OSC message."; case OscErrorPacketSizeTooLarge: return (char *) &"OSC packet size cannot exceed MAX_OSC_PACKET_SIZE."; case OscErrorContentsEmpty: return (char *) &"OSC contents size cannot be zero."; /* OscSlip errors */ case OscErrorEncodedSlipPacketTooLong: return (char *) &"Encoded SLIP packet size cannot exceed OSC_SLIP_DECODER_BUFFER_SIZE."; case OscErrorUnexpectedByteAfterSlipEsc: return (char *) &"Unexpected byte after SLIP ESC byte."; case OscErrorDecodedSlipPacketTooLong: return (char *) &"Decoded SLIP packet size cannot exceed MAX_OSC_PACKET_SIZE."; } return (char *) &"Unknown error."; #else return (char *) &"OSC error."; #endif }
2.421875
2
2024-11-18T22:23:38.048087+00:00
2019-01-09T21:56:56
fd97ca6e5effeb66ac107ea1d0aa73f1c3e8d86e
{ "blob_id": "fd97ca6e5effeb66ac107ea1d0aa73f1c3e8d86e", "branch_name": "refs/heads/master", "committer_date": "2019-01-09T21:56:56", "content_id": "aecb044624cd968e86c6f4468166e9d29b64649d", "detected_licenses": [ "MIT" ], "directory_id": "627fae9e6a2cc3c6bc199797ab675ff5429a1894", "extension": "c", "filename": "_json_test.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 22792137, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5183, "license": "MIT", "license_type": "permissive", "path": "/src/_json_test.c", "provenance": "stackv2-0115.json.gz:66992", "repo_name": "vslinko/json", "revision_date": "2019-01-09T21:56:56", "revision_id": "4402f3c1de8ed50182c1cd3bfcb9b698e344e7e5", "snapshot_id": "dec57764200624f1f70e12fdc5b3d85a22892157", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/vslinko/json/4402f3c1de8ed50182c1cd3bfcb9b698e344e7e5/src/_json_test.c", "visit_date": "2021-10-10T10:54:38.669196" }
stackv2
/* Copyright (c) 2014 Vyacheslav Slinko * * 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 <string.h> #include <vstd/test.h> #include "./json.h" #define ASSERT_SUCCESSFUL_PARSING(source_json) \ parse_result = json_parse(source_json, strlen(source_json)); \ tassert(parse_result); \ tassert(parse_result->error == 0); \ tassert(parse_result->value); \ stringify_result = json_stringify(parse_result->value); \ tassert(strcmp(source_json, stringify_result) == 0); \ json_value_free(parse_result->value); \ json_parse_result_free(parse_result); \ free(stringify_result); #define ASSERT_FAILED_PARSING(source_json, _error, _error_position) \ parse_result = json_parse(source_json, strlen(source_json)); \ tassert(parse_result); \ tassert(parse_result->error > 0); \ tassert(!parse_result->value); \ tassert(parse_result->error == _error); \ tassert(parse_result->error_position == _error_position); \ json_parse_result_free(parse_result); static struct json_parse_result *parse_result; static char *stringify_result; static void test_json() { ASSERT_SUCCESSFUL_PARSING("null") ASSERT_SUCCESSFUL_PARSING("true") ASSERT_SUCCESSFUL_PARSING("false") ASSERT_SUCCESSFUL_PARSING("1") ASSERT_SUCCESSFUL_PARSING("1.0") ASSERT_SUCCESSFUL_PARSING("-1.0") ASSERT_SUCCESSFUL_PARSING("-1.0e-1") ASSERT_SUCCESSFUL_PARSING("-1.0e+2") ASSERT_SUCCESSFUL_PARSING("-1.0E3") ASSERT_SUCCESSFUL_PARSING("\"string\"") ASSERT_SUCCESSFUL_PARSING("\"string with \\\" escaped quote\"") ASSERT_SUCCESSFUL_PARSING("\"UTF-8 строка\"") ASSERT_SUCCESSFUL_PARSING("[null,true,false,1,\"string\"]") ASSERT_SUCCESSFUL_PARSING("{\"array\":[null,true,false,1,\"string\"]}") ASSERT_SUCCESSFUL_PARSING("[[],[]]") ASSERT_SUCCESSFUL_PARSING("{\"a\":1,\"b\":2}") ASSERT_SUCCESSFUL_PARSING("{\"a\":{},\"b\":{}}") ASSERT_FAILED_PARSING("", JSON_ERROR_EMPTY_FILE, 0) ASSERT_FAILED_PARSING("string without quotes", JSON_ERROR_UNEXPECTED_TOKEN, 0) ASSERT_FAILED_PARSING("[1", JSON_ERROR_UNEXPECTED_TOKEN, 2) ASSERT_FAILED_PARSING("{1}", JSON_ERROR_UNEXPECTED_TOKEN, 1) ASSERT_FAILED_PARSING("{", JSON_ERROR_UNEXPECTED_TOKEN, 1) ASSERT_FAILED_PARSING("{\"a\": 1", JSON_ERROR_UNEXPECTED_TOKEN, 7) ASSERT_FAILED_PARSING("{\"a\" 1}", JSON_ERROR_UNEXPECTED_TOKEN, 5) } VSTD_TEST_REGISTER_UNIT(test_json, 10000, NULL, NULL) /* * 1 000 000 times per 1 second */ #define PARSE_BENCHMARK_TRIES 1000000 static char sources[PARSE_BENCHMARK_TRIES][100]; static struct json_parse_result **links; static void benchmark_json_parse_setup() { int i; for (i = 0; i < PARSE_BENCHMARK_TRIES; i++) { sprintf(sources[i], "{\"array\":[null,true,false,-1.0e-2,\"string\",%f]}", ((double) rand()) / RAND_MAX); } links = malloc(sizeof(struct json_parse_result *) * PARSE_BENCHMARK_TRIES); tassert(links); } static void benchmark_json_parse_teardown() { int i; for (i = 0; i < PARSE_BENCHMARK_TRIES; i++) { json_value_free(links[i]->value); json_parse_result_free(links[i]); } free(links); } static void benchmark_json_parse() { struct json_parse_result *result; int i; for (i = 0; i < PARSE_BENCHMARK_TRIES; i++) { result = json_parse(sources[i], strlen(sources[i])); links[i] = result; } } VSTD_TEST_REGISTER_BENCHMARK(benchmark_json_parse, 1.0, benchmark_json_parse_setup, benchmark_json_parse_teardown) /* * 7 500 000 times per 1 second */ static void benchmark_json_stringify() { char *source; struct json_parse_result *result; char *stringified; int i; source = "{\"array\":[null,true,false,-1.0e-2,\"string\"]}"; result = json_parse(source, strlen(source)); for (i = 0; i < 7500000; i++) { stringified = json_stringify(result->value); free(stringified); } json_value_free(result->value); json_parse_result_free(result); } VSTD_TEST_REGISTER_BENCHMARK(benchmark_json_stringify, 1.0, NULL, NULL)
2.328125
2
2024-11-18T22:23:38.778905+00:00
2018-09-22T03:33:15
477daa6e8dd27bf42b4e14700ff07d21e4a97706
{ "blob_id": "477daa6e8dd27bf42b4e14700ff07d21e4a97706", "branch_name": "refs/heads/master", "committer_date": "2018-09-22T03:33:15", "content_id": "6fb36abdf7b68b31f65624b244b8e924168c8e6f", "detected_licenses": [ "MIT" ], "directory_id": "ee24ba563cf8d7c5bb8c95ae8e10233b476b97cf", "extension": "h", "filename": "Matrix4x4_SSE.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 149842030, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 20731, "license": "MIT", "license_type": "permissive", "path": "/Editor/NativePlugin/RayTrace/src/core/Math2/Matrix4x4_SSE.h", "provenance": "stackv2-0115.json.gz:67379", "repo_name": "wachel/block", "revision_date": "2018-09-22T03:33:15", "revision_id": "c04b4531f19ae3373e5dbec403af9c90719fc581", "snapshot_id": "32f8334a70d053cdf9dc3eb0215f35ba9a1d788b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/wachel/block/c04b4531f19ae3373e5dbec403af9c90719fc581/Editor/NativePlugin/RayTrace/src/core/Math2/Matrix4x4_SSE.h", "visit_date": "2020-03-29T11:13:28.371466" }
stackv2
#ifndef _MATRIX4x4_SSE_ #define _MATRIX4x4_SSE_ #include "Vector4_SSE.h" // //class Matrix4x4SSE; // //__declspec(align(16)) extern Matrix4x4SSE g_MatrixSSE_Identity; //__declspec(align(16)) extern Vector4SSE g_VectorSSE_quat2mat_x0; //__declspec(align(16)) extern Vector4SSE g_VectorSSE_quat2mat_x1; //__declspec(align(16)) extern Vector4SSE g_VectorSSE_quat2mat_x2; // //inline Vector4SSE operator*(Vector4SSE &v, Matrix4x4SSE &matrix); //inline Matrix4x4SSE operator*(Matrix4x4SSE &a, Matrix4x4SSE &b); // //class Matrix4x4SSE //{ //public: // union // { // struct // { // float m_00, m_01, m_02, m_03; // float m_10, m_11, m_12, m_13; // float m_20, m_21, m_22, m_23; // float m_30, m_31, m_32, m_33; // }; // // struct // { // Vector4SSE m_Vec0, m_Vec1, m_Vec2, m_Vec3; // }; // }; // //public: // inline Matrix4x4SSE() // { // // } // // inline Matrix4x4SSE( // float f00, float f01, float f02, float f03, // float f10, float f11, float f12, float f13, // float f20, float f21, float f22, float f23, // float f30, float f31, float f32, float f33 // ) // { // m_00 = f00; m_01 = f01; m_02 = f02; m_03 = f03; // m_10 = f10; m_11 = f11; m_12 = f12; m_13 = f13; // m_20 = f20; m_21 = f21; m_22 = f22; m_23 = f23; // m_30 = f30; m_31 = f31; m_32 = f32; m_33 = f33; // } // // inline void Identity(void) // { // /* // *this = g_MatrixSSE_Identity; // */ // m_Vec0.Set(1.0f, 0.0f, 0.0f, 0.0f); // m_Vec1.Set(0.0f, 1.0f, 0.0f, 0.0f); // m_Vec2.Set(0.0f, 0.0f, 1.0f, 0.0f); // m_Vec3.Set(0.0f, 0.0f, 0.0f, 1.0f); // } // // static Matrix4x4SSE IdentityMatrix(void) // { // return g_MatrixSSE_Identity; // } // // inline void SetRow(int row, Vector4SSE &vec) // { // assert(row>=0 && row<4); // Vector4SSE *rows = &m_Vec0; // rows[row] = vec; // } // // inline void SetColumn(int column, Vector4SSE &vec) // { // assert(column>=0 && column<4); // float *p = &m_00 + column; // p[0] = vec.GetX(); // p[4] = vec.GetY(); // p[8] = vec.GetZ(); // p[12] = vec.GetW(); // } // // inline Vector4SSE &GetRow(int row) // { // assert(row>=0 && row<4); // Vector4SSE *rows = &m_Vec0; // return rows[row]; // } // // inline Vector4SSE GetColumn(int column) // { // assert(column>=0 && column<4); // Vector4SSE vec; // float *p = &m_00 + column; // // vec.SetX(p[0]); // vec.SetY(p[4]); // vec.SetZ(p[8]); // vec.SetW(p[12]); // // return vec; // } // // // assume input vec.w equals 1 // // result.w is garbage // inline Vector4SSE TransformVec3(Vector4SSE &vec) // { // Vector4SSE result; // // __m128 vxxxx = _mm_shuffle_ps(vec.m_Vec, vec.m_Vec, _MM_SHUFFLE(0, 0, 0, 0) ); // __m128 vyyyy = _mm_shuffle_ps(vec.m_Vec, vec.m_Vec, _MM_SHUFFLE(1, 1, 1, 1) ); // __m128 vzzzz = _mm_shuffle_ps(vec.m_Vec, vec.m_Vec, _MM_SHUFFLE(2, 2, 2, 2) ); // // __m128 temp; // // result.m_Vec = _mm_mul_ps(vxxxx, m_Vec0.m_Vec); // // temp = _mm_mul_ps(vyyyy, m_Vec1.m_Vec); // result.m_Vec = _mm_add_ps(result.m_Vec, temp); // // temp = _mm_mul_ps(vzzzz, m_Vec2.m_Vec); // result.m_Vec = _mm_add_ps(result.m_Vec, temp); // // result.m_Vec = _mm_add_ps(result.m_Vec, m_Vec3.m_Vec); // // return result; // } // // // this = R * this // void Rotate( Vector4SSE &v, float radian) // { // float fSin, fCos; // FastMath::SinCos(radian, fSin, fCos); // float fOneMinusCos = 1.0f - fCos; // // Vector4SSE xxxx = v.GetXXXX(); // Vector4SSE yyyy = v.GetYYYY(); // Vector4SSE zzzz = v.GetZZZZ(); // Vector4SSE SinVector(fSin); // Vector4SSE v_Mul_Sin = v * SinVector; // Vector4SSE multipler = fOneMinusCos * v; multipler.SetW(0.0f); // Vector4SSE add; // // Matrix4x4SSE local; // local.Identity(); // // add.Set(fCos, v_Mul_Sin.GetZ(), -v_Mul_Sin.GetY(), 0.0f); // local.m_Vec0 = xxxx * multipler + add; // // add.Set(-v_Mul_Sin.GetZ(), fCos, v_Mul_Sin.GetX(), 0.0f); // local.m_Vec1 = yyyy * multipler + add; // // add.Set(v_Mul_Sin.GetY(), -v_Mul_Sin.GetX(), fCos, 0.0f); // local.m_Vec2 = zzzz * multipler + add; // // *this = local * (*this); // } // // // replace current matrix // void Rotate_Replace( Vector4CPU &v, float radian) // { // float x = v.x; // float y = v.y; // float z = v.z; // float w = v.w; // // float fSin, fCos; // FastMath::SinCos(radian, fSin, fCos); // // m_00 = ( x * x ) * ( 1.0f - fCos ) + fCos; // m_01 = ( x * y ) * ( 1.0f - fCos ) + (z * fSin); // m_02 = ( x * z ) * ( 1.0f - fCos ) - (y * fSin); // m_03 = 0.0f; // // m_10 = ( y * x ) * ( 1.0f - fCos ) - (z * fSin); // m_11 = ( y * y ) * ( 1.0f - fCos ) + fCos ; // m_12 = ( y * z ) * ( 1.0f - fCos ) + (x * fSin); // m_13 = 0.0f; // // m_20 = ( z * x ) * ( 1.0f - fCos ) + (y * fSin); // m_21 = ( z * y ) * ( 1.0f - fCos ) - (x * fSin); // m_22 = ( z * z ) * ( 1.0f - fCos ) + fCos; // m_23 = 0.0f; // // m_30 = 0.0f; // m_31 = 0.0f; // m_32 = 0.0f; // m_33 = 1.0f; // } // // // this = Rx * this // void RotateX( const float radian ) // { // float Sin, Cos; // FastMath::SinCos(radian, Sin, Cos); // // Vector4SSE SinVector(Sin); // Vector4SSE CosVector(Cos); // // Vector4SSE t0 = m_Vec1 * CosVector + m_Vec2 * SinVector; // Vector4SSE t1 = m_Vec2 * CosVector - m_Vec1 * SinVector; // // m_Vec1 = t0; // m_Vec2 = t1; // } // // // replace current matrix // void RotateX_Replace( const float radian ) // { // float fSin, fCos; // FastMath::SinCos(radian, fSin, fCos); // // m_Vec0.Set(1.0f, 0.0f, 0.0f, 0.0f); // m_Vec1.Set(0.0f, fCos, fSin, 0.0f); // m_Vec2.Set(0.0f, -fSin, fCos, 0.0f); // m_Vec3.Set(0.0f, 0.0f, 0.0f, 1.0f); // } // // // this = Ry * this // void RotateY( const float radian ) // { // float Sin, Cos; // FastMath::SinCos(radian, Sin, Cos); // // Vector4SSE SinVector(Sin); // Vector4SSE CosVector(Cos); // // Vector4SSE t0 = m_Vec0 * CosVector - m_Vec2 * SinVector; // Vector4SSE t1 = m_Vec0 * SinVector + m_Vec2 * CosVector; // // m_Vec0 = t0; // m_Vec2 = t1; // } // // // replace current matrix // void RotateY_Replace( const float radian ) // { // float fSin, fCos; // FastMath::SinCos(radian, fSin, fCos); // // m_Vec0.Set( fCos, 0.0f,-fSin, 0.0f); // m_Vec1.Set( 0.0f, 1.0f, 0.0f, 0.0f); // m_Vec2.Set( fSin, 0.0f, fCos, 0.0f); // m_Vec3.Set( 0.0f, 0.0f, 0.0f, 1.0f); // } // // // this = Rz * this // void RotateZ( const float radian ) // { // float Sin, Cos; // FastMath::SinCos(radian, Sin, Cos); // // Vector4SSE SinVector(Sin); // Vector4SSE CosVector(Cos); // // Vector4SSE t0 = m_Vec0 * CosVector + m_Vec1 * SinVector; // Vector4SSE t1 = m_Vec1 * CosVector - m_Vec0 * SinVector; // // m_Vec0 = t0; // m_Vec1 = t1; // } // // // replace current matrix // void RotateZ_Replace( const float radian ) // { // float fSin, fCos; // FastMath::SinCos(radian, fSin, fCos); // // m_Vec0.Set( fCos, fSin, 0.0f, 0.0f); // m_Vec1.Set(-fSin, fCos, 0.0f, 0.0f); // m_Vec2.Set( 0.0f, 0.0f, 1.0f, 0.0f); // m_Vec3.Set( 0.0f, 0.0f, 0.0f, 1.0f); // } // // void Scale(Vector4SSE &scale) // { // m_Vec0 *= scale; // m_Vec1 *= scale; // m_Vec2 *= scale; // m_Vec3 *= scale; // } // // void Scale(float x, float y, float z) // { // Vector4SSE vScale(x, y, z, 1.0f); // Scale(vScale); // //Matrix4x4 scale_replace(x, y, z); // //*this = *this * scale; // } // // void Scale_Replace(Vector4SSE &scale) // { // Scale_Replace(scale[0], scale[1], scale[2]); // } // // void Scale_Replace(float x, float y, float z) // { // m_Vec0.Set(x, 0, 0, 0); // m_Vec1.Set(0, y, 0, 0); // m_Vec2.Set(0, 0, z, 0); // m_Vec3.Set(0, 0, 0, 1); // } // // inline Matrix4x4SSE &FastInvert(void) // { // Vector4SSE pos = VectorInvertSign(m_Vec3); // m_Vec3 = g_MatrixSSE_Identity.m_Vec3; // // Transpose(); // Translate(pos); // // return *this; // } // // Matrix4x4SSE &Invert(void); // // inline Matrix4x4SSE &Transpose(void) // { // _MM_TRANSPOSE4_PS(m_Vec0.m_Vec, m_Vec1.m_Vec, m_Vec2.m_Vec, m_Vec3.m_Vec); // // return *this; // } // // // this = T * this // void Translate(float x, float y, float z) // { // Vector4SSE xxxx(x); // Vector4SSE yyyy(y); // Vector4SSE zzzz(z); // // m_Vec3 += m_Vec0 * xxxx + m_Vec1 * yyyy + m_Vec2 * zzzz; // } // // // this = T * this // void Translate(Vector4SSE &v) // { // Vector4SSE xxxx = v.GetXXXX(); // Vector4SSE yyyy = v.GetYYYY(); // Vector4SSE zzzz = v.GetZZZZ(); // // m_Vec3 += m_Vec0 * xxxx + m_Vec1 * yyyy + m_Vec2 * zzzz; // } // // void Translate_Replace(float x, float y, float z) // { // Identity(); // // m_Vec3[0] = x; // m_Vec3[1] = y; // m_Vec3[2] = z; // } // // void Translate_Replace(Vector4SSE &v) // { // Identity(); // // m_Vec3 = v; // } // // void TranslateX(float d) // { // Vector4SSE dddd(d); // m_Vec3 += m_Vec0 * dddd; // } // // void TranslateY(float d) // { // Vector4SSE dddd(d); // m_Vec3 += m_Vec1 * dddd; // } // // void TranslateZ(float d) // { // Vector4SSE dddd(d); // m_Vec3 += m_Vec2 * dddd; // } // // Vector4SSE RotateVector(Vector4SSE &vec) // { // Vector4SSE result; // // result = vec.GetXXXX() * m_Vec0; // result += vec.GetYYYY() * m_Vec1; // result += vec.GetZZZZ() * m_Vec2; // // return result; // } // // void NoTranslate(void) // { // m_Vec3 = IdentityMatrix()[3]; // } // // void NoRotate(void) // { // m_Vec0 = IdentityMatrix()[0]; // m_Vec1 = IdentityMatrix()[1]; // m_Vec2 = IdentityMatrix()[2]; // } // // void SetMatrix3x4(Matrix4x4SSE &mat) // { // m_Vec0 = mat[0]; // m_Vec1 = mat[1]; // m_Vec2 = mat[2]; // } // // void ConsoleOutput(void); // // // operator // inline float &operator() (int i, int j) // { // assert(i>=0 && i<4); // assert(j>=0 && j<4); // return GetRow(i)[j]; // } // // inline Vector4SSE &operator[](int row) // { // return GetRow(row); // } // // inline Matrix4x4SSE &operator=(Matrix4x4SSE &rhs) // { // m_Vec0 = rhs.m_Vec0; // m_Vec1 = rhs.m_Vec1; // m_Vec2 = rhs.m_Vec2; // m_Vec3 = rhs.m_Vec3; // // return *this; // } // // inline Matrix4x4SSE &operator=(float f) // { // __m128 ffff = _mm_set_ps1(f); // // m_Vec0.m_Vec = ffff; // m_Vec1.m_Vec = ffff; // m_Vec2.m_Vec = ffff; // m_Vec3.m_Vec = ffff; // // return *this; // } // // inline Matrix4x4SSE &operator+=(float f) // { // __m128 ffff = _mm_set_ps1(f); // // m_Vec0.m_Vec = _mm_add_ps(m_Vec0.m_Vec, ffff); // m_Vec1.m_Vec = _mm_add_ps(m_Vec1.m_Vec, ffff); // m_Vec2.m_Vec = _mm_add_ps(m_Vec2.m_Vec, ffff); // m_Vec3.m_Vec = _mm_add_ps(m_Vec3.m_Vec, ffff); // // return *this; // } // // inline Matrix4x4SSE &operator+=(Matrix4x4SSE &rhs) // { // m_Vec0.m_Vec = _mm_add_ps(m_Vec0.m_Vec, rhs.m_Vec0.m_Vec); // m_Vec1.m_Vec = _mm_add_ps(m_Vec1.m_Vec, rhs.m_Vec1.m_Vec); // m_Vec2.m_Vec = _mm_add_ps(m_Vec2.m_Vec, rhs.m_Vec2.m_Vec); // m_Vec3.m_Vec = _mm_add_ps(m_Vec3.m_Vec, rhs.m_Vec3.m_Vec); // // return *this; // } // // inline Matrix4x4SSE &operator-=(float f) // { // __m128 ffff = _mm_set_ps1(f); // // m_Vec0.m_Vec = _mm_sub_ps(m_Vec0.m_Vec, ffff); // m_Vec1.m_Vec = _mm_sub_ps(m_Vec1.m_Vec, ffff); // m_Vec2.m_Vec = _mm_sub_ps(m_Vec2.m_Vec, ffff); // m_Vec3.m_Vec = _mm_sub_ps(m_Vec3.m_Vec, ffff); // // return *this; // } // // inline Matrix4x4SSE &operator-=(Matrix4x4SSE &rhs) // { // m_Vec0.m_Vec = _mm_sub_ps(m_Vec0.m_Vec, rhs.m_Vec0.m_Vec); // m_Vec1.m_Vec = _mm_sub_ps(m_Vec1.m_Vec, rhs.m_Vec1.m_Vec); // m_Vec2.m_Vec = _mm_sub_ps(m_Vec2.m_Vec, rhs.m_Vec2.m_Vec); // m_Vec3.m_Vec = _mm_sub_ps(m_Vec3.m_Vec, rhs.m_Vec3.m_Vec); // // return *this; // } // // inline Matrix4x4SSE &operator*=(float f) // { // __m128 ffff = _mm_set_ps1(f); // // m_Vec0.m_Vec = _mm_mul_ps(m_Vec0.m_Vec, ffff); // m_Vec1.m_Vec = _mm_mul_ps(m_Vec1.m_Vec, ffff); // m_Vec2.m_Vec = _mm_mul_ps(m_Vec2.m_Vec, ffff); // m_Vec3.m_Vec = _mm_mul_ps(m_Vec3.m_Vec, ffff); // // return *this; // } // // inline Matrix4x4SSE &operator*=(Matrix4x4SSE &rhs) // { // m_Vec0 = m_Vec0 * rhs; // m_Vec1 = m_Vec1 * rhs; // m_Vec2 = m_Vec2 * rhs; // m_Vec3 = m_Vec3 * rhs; // // return *this; // } // // inline Matrix4x4SSE &operator/=(float f) // { // __m128 ffff = _mm_set_ps1(f); // // m_Vec0.m_Vec = _mm_div_ps(m_Vec0.m_Vec, ffff); // m_Vec1.m_Vec = _mm_div_ps(m_Vec1.m_Vec, ffff); // m_Vec2.m_Vec = _mm_div_ps(m_Vec2.m_Vec, ffff); // m_Vec3.m_Vec = _mm_div_ps(m_Vec3.m_Vec, ffff); // // return *this; // } // //}; // //inline bool operator==(Matrix4x4SSE &a, Matrix4x4SSE &b) //{ // // true if all vectors equal to each other // bool result = a.m_Vec0==b.m_Vec0 && a.m_Vec1==b.m_Vec1 && a.m_Vec2==b.m_Vec2 && a.m_Vec3==b.m_Vec3; // return result; //} // //inline bool operator!=(Matrix4x4SSE &a, Matrix4x4SSE &b) //{ // // true if any one vector not-equal // bool result = a.m_Vec0!=b.m_Vec0 || a.m_Vec1!=b.m_Vec1 || a.m_Vec2!=b.m_Vec2 || a.m_Vec3!=b.m_Vec3; // return result; //} // //inline Matrix4x4SSE operator+(Matrix4x4SSE &a, float f) //{ // Matrix4x4SSE result = a; // result += f; // return result; //} // //inline Matrix4x4SSE operator+(float f, Matrix4x4SSE &a) //{ // Matrix4x4SSE result = a; // result += f; // return result; //} // //inline Matrix4x4SSE operator+(Matrix4x4SSE &a, Matrix4x4SSE &b) //{ // Matrix4x4SSE result; // // result.m_Vec0 = a.m_Vec0 + b.m_Vec0; // result.m_Vec1 = a.m_Vec1 + b.m_Vec1; // result.m_Vec2 = a.m_Vec2 + b.m_Vec2; // result.m_Vec3 = a.m_Vec3 + b.m_Vec3; // // return result; //} // //inline Matrix4x4SSE operator-(Matrix4x4SSE &a, float f) //{ // Matrix4x4SSE result = a; // result -= f; // return result; //} // //inline Matrix4x4SSE operator-(float f, Matrix4x4SSE &a) //{ // Matrix4x4SSE result = a; // result -= f; // return result; //} // //inline Matrix4x4SSE operator-(Matrix4x4SSE &a, Matrix4x4SSE &b) //{ // Matrix4x4SSE result; // // result.m_Vec0 = a.m_Vec0 - b.m_Vec0; // result.m_Vec1 = a.m_Vec1 - b.m_Vec1; // result.m_Vec2 = a.m_Vec2 - b.m_Vec2; // result.m_Vec3 = a.m_Vec3 - b.m_Vec3; // // return result; //} // // //inline Vector4SSE operator*(Vector4SSE &vec, Matrix4x4SSE &matrix) //{ // /* // Vector4SSE result; // // __m128 vxxxx = _mm_shuffle_ps(vec.m_Vec, vec.m_Vec, _MM_SHUFFLE(0, 0, 0, 0) ); // __m128 vyyyy = _mm_shuffle_ps(vec.m_Vec, vec.m_Vec, _MM_SHUFFLE(1, 1, 1, 1) ); // __m128 vzzzz = _mm_shuffle_ps(vec.m_Vec, vec.m_Vec, _MM_SHUFFLE(2, 2, 2, 2) ); // __m128 vwwww = _mm_shuffle_ps(vec.m_Vec, vec.m_Vec, _MM_SHUFFLE(3, 3, 3, 3) ); // // __m128 temp; // // result.m_Vec = _mm_mul_ps(vxxxx, matrix.m_Vec0.m_Vec); // // temp = _mm_mul_ps(vyyyy, matrix.m_Vec1.m_Vec); // result.m_Vec = _mm_add_ps(result.m_Vec, temp); // // temp = _mm_mul_ps(vzzzz, matrix.m_Vec2.m_Vec); // result.m_Vec = _mm_add_ps(result.m_Vec, temp); // // temp = _mm_mul_ps(vwwww, matrix.m_Vec3.m_Vec); // result.m_Vec = _mm_add_ps(result.m_Vec, temp); // */ // // Vector4SSE result; // // result = vec.GetXXXX() * matrix.m_Vec0; // result += vec.GetYYYY() * matrix.m_Vec1; // result += vec.GetZZZZ() * matrix.m_Vec2; // result += vec.GetWWWW() * matrix.m_Vec3; // // return result; //} // //inline Vector4SSE operator*(Matrix4x4SSE &matrix, Vector4SSE &vec) //{ // // Vector4SSE result; // // result[0] = VectorDot(vec, matrix[0]).GetX(); // result[1] = VectorDot(vec, matrix[1]).GetX(); // result[2] = VectorDot(vec, matrix[2]).GetX(); // result[3] = VectorDot(vec, matrix[3]).GetX(); // // return result; // //} // //inline Matrix4x4SSE operator*(Matrix4x4SSE &a, Matrix4x4SSE &b) //{ // Matrix4x4SSE result; // // /* // register __m128 v0 = b.m_Vec0.m_Vec; // register __m128 v1 = b.m_Vec1.m_Vec; // register __m128 v2 = b.m_Vec2.m_Vec; // register __m128 v3 = b.m_Vec3.m_Vec; // // register __m128 v; // register __m128 broadcast; // register __m128 vsum; // register __m128 vtemp; // // v = a.m_Vec0.m_Vec; // broadcast = _mm_shuffle_ps(v, v, _MM_SHUFFLE(0,0,0,0)); // xxxx // vsum = _mm_mul_ps(broadcast, v0); // broadcast = _mm_shuffle_ps(v, v, _MM_SHUFFLE(1,1,1,1)); // yyyy // vtemp = _mm_mul_ps(broadcast, v1); // vsum = _mm_add_ps(vtemp, vsum); // broadcast = _mm_shuffle_ps(v, v, _MM_SHUFFLE(2,2,2,2)); // zzzz // vtemp = _mm_mul_ps(broadcast, v2); // vsum = _mm_add_ps(vtemp, vsum); // broadcast = _mm_shuffle_ps(v, v, _MM_SHUFFLE(3,3,3,3)); // wwww // vtemp = _mm_mul_ps(broadcast, v3); // result.m_Vec0.m_Vec = _mm_add_ps(vtemp, vsum); // // v = a.m_Vec1.m_Vec; // broadcast = _mm_shuffle_ps(v, v, _MM_SHUFFLE(0,0,0,0)); // xxxx // vsum = _mm_mul_ps(broadcast, v0); // broadcast = _mm_shuffle_ps(v, v, _MM_SHUFFLE(1,1,1,1)); // yyyy // vtemp = _mm_mul_ps(broadcast, v1); // vsum = _mm_add_ps(vtemp, vsum); // broadcast = _mm_shuffle_ps(v, v, _MM_SHUFFLE(2,2,2,2)); // zzzz // vtemp = _mm_mul_ps(broadcast, v2); // vsum = _mm_add_ps(vtemp, vsum); // broadcast = _mm_shuffle_ps(v, v, _MM_SHUFFLE(3,3,3,3)); // wwww // vtemp = _mm_mul_ps(broadcast, v3); // result.m_Vec1.m_Vec = _mm_add_ps(vtemp, vsum); // // v = a.m_Vec2.m_Vec; // broadcast = _mm_shuffle_ps(v, v, _MM_SHUFFLE(0,0,0,0)); // xxxx // vsum = _mm_mul_ps(broadcast, v0); // broadcast = _mm_shuffle_ps(v, v, _MM_SHUFFLE(1,1,1,1)); // yyyy // vtemp = _mm_mul_ps(broadcast, v1); // vsum = _mm_add_ps(vtemp, vsum); // broadcast = _mm_shuffle_ps(v, v, _MM_SHUFFLE(2,2,2,2)); // zzzz // vtemp = _mm_mul_ps(broadcast, v2); // vsum = _mm_add_ps(vtemp, vsum); // broadcast = _mm_shuffle_ps(v, v, _MM_SHUFFLE(3,3,3,3)); // wwww // vtemp = _mm_mul_ps(broadcast, v3); // result.m_Vec2.m_Vec = _mm_add_ps(vtemp, vsum); // // v = a.m_Vec3.m_Vec; // broadcast = _mm_shuffle_ps(v, v, _MM_SHUFFLE(0,0,0,0)); // xxxx // vsum = _mm_mul_ps(broadcast, v0); // broadcast = _mm_shuffle_ps(v, v, _MM_SHUFFLE(1,1,1,1)); // yyyy // vtemp = _mm_mul_ps(broadcast, v1); // vsum = _mm_add_ps(vtemp, vsum); // broadcast = _mm_shuffle_ps(v, v, _MM_SHUFFLE(2,2,2,2)); // zzzz // vtemp = _mm_mul_ps(broadcast, v3); // vsum = _mm_add_ps(vtemp, vsum); // broadcast = _mm_shuffle_ps(v, v, _MM_SHUFFLE(3,3,3,3)); // wwww // vtemp = _mm_mul_ps(broadcast, v3); // result.m_Vec3.m_Vec = _mm_add_ps(vtemp, vsum); // */ // // // turned out the simplified, non-assembly version is faster... Peter Pon // result.m_Vec0 = // a.m_Vec0.GetXXXX() * b.m_Vec0 + // a.m_Vec0.GetYYYY() * b.m_Vec1 + // a.m_Vec0.GetZZZZ() * b.m_Vec2 + // a.m_Vec0.GetWWWW() * b.m_Vec3; // // result.m_Vec1 = // a.m_Vec1.GetXXXX() * b.m_Vec0 + // a.m_Vec1.GetYYYY() * b.m_Vec1 + // a.m_Vec1.GetZZZZ() * b.m_Vec2 + // a.m_Vec1.GetWWWW() * b.m_Vec3; // // result.m_Vec2 = // a.m_Vec2.GetXXXX() * b.m_Vec0 + // a.m_Vec2.GetYYYY() * b.m_Vec1 + // a.m_Vec2.GetZZZZ() * b.m_Vec2 + // a.m_Vec2.GetWWWW() * b.m_Vec3; // // result.m_Vec3 = // a.m_Vec3.GetXXXX() * b.m_Vec0 + // a.m_Vec3.GetYYYY() * b.m_Vec1 + // a.m_Vec3.GetZZZZ() * b.m_Vec2 + // a.m_Vec3.GetWWWW() * b.m_Vec3; // // return result; //} // //inline Matrix4x4SSE operator*(Matrix4x4SSE &a, float f) //{ // Matrix4x4SSE result; // // __m128 ffff = _mm_set_ps1(f); // // result.m_Vec0.m_Vec = _mm_mul_ps(a.m_Vec0.m_Vec, ffff); // result.m_Vec1.m_Vec = _mm_mul_ps(a.m_Vec1.m_Vec, ffff); // result.m_Vec2.m_Vec = _mm_mul_ps(a.m_Vec2.m_Vec, ffff); // result.m_Vec3.m_Vec = _mm_mul_ps(a.m_Vec3.m_Vec, ffff); // // return result; //} // //inline Matrix4x4SSE operator*(float f, Matrix4x4SSE &a) //{ // Matrix4x4SSE result; // __m128 ffff = _mm_set_ps1(f); // // result.m_Vec0.m_Vec = _mm_mul_ps(a.m_Vec0.m_Vec, ffff); // result.m_Vec1.m_Vec = _mm_mul_ps(a.m_Vec1.m_Vec, ffff); // result.m_Vec2.m_Vec = _mm_mul_ps(a.m_Vec2.m_Vec, ffff); // result.m_Vec3.m_Vec = _mm_mul_ps(a.m_Vec3.m_Vec, ffff); // // return result; //} // //inline Matrix4x4SSE operator/(Matrix4x4SSE &matrix, float f) //{ // Matrix4x4SSE result; // __m128 ffff = _mm_set_ps1(f); // // result.m_Vec0.m_Vec = _mm_div_ps(matrix.m_Vec0.m_Vec, ffff); // result.m_Vec1.m_Vec = _mm_div_ps(matrix.m_Vec1.m_Vec, ffff); // result.m_Vec2.m_Vec = _mm_div_ps(matrix.m_Vec2.m_Vec, ffff); // result.m_Vec3.m_Vec = _mm_div_ps(matrix.m_Vec3.m_Vec, ffff); // // return result; //} // //inline Matrix4x4SSE Matrix4x4Transpose(Matrix4x4SSE &matrix) //{ // Matrix4x4SSE result = matrix; // result.Transpose(); // return result; //} // //inline Vector4SSE Matrix4x4TransformVector3(Vector4SSE &v, Matrix4x4SSE &matrix) //{ // Vector4SSE result; // // result = v.GetXXXX() * matrix.m_Vec0; // result += v.GetYYYY() * matrix.m_Vec1; // result += v.GetZZZZ() * matrix.m_Vec2; // result += matrix.m_Vec3; // // return result; //} // //inline Matrix4x4SSE Matrix4x4FastInvert(Matrix4x4SSE &matrix) //{ // Matrix4x4SSE invmatrix = matrix; // invmatrix.FastInvert(); // return invmatrix; //} // //void Matrix4x4Rotate(Matrix4x4SSE &matrix, Vector4SSE &v, float radian); //void Matrix4x4FromQuaternion(Matrix4x4SSE &matrix, Vector4SSE &v); //void Matrix4x4FromQuaternionAndTransform(Matrix4x4SSE &matrix, Vector4SSE &q, Vector4SSE &t = g_MatrixSSE_Identity.m_Vec3 ); //void QuaternionFromMatrix4x4(Matrix4x4SSE &matrix, Vector4SSE &quaternion); #endif // _MATRIX4x4_SSE_
2.09375
2
2024-11-18T22:23:40.100251+00:00
2019-07-12T16:37:54
247b5601ce98354eb12b3135bd25d6d2ba497c9c
{ "blob_id": "247b5601ce98354eb12b3135bd25d6d2ba497c9c", "branch_name": "refs/heads/master", "committer_date": "2019-07-12T16:37:54", "content_id": "831d24356850b9441ee8cda0705b7d7f30889b50", "detected_licenses": [ "MIT" ], "directory_id": "d0a1a7e976ed24bef51b3722b4eb1a9dcc74a6a0", "extension": "h", "filename": "sha.h", "fork_events_count": 1, "gha_created_at": "2018-05-29T16:06:22", "gha_event_created_at": "2019-09-30T16:23:15", "gha_language": "C", "gha_license_id": "MIT", "github_id": 135321402, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4120, "license": "MIT", "license_type": "permissive", "path": "/rfc6234-master/sha.h", "provenance": "stackv2-0115.json.gz:68023", "repo_name": "Ansaya/Personal-HomeKit-HAP", "revision_date": "2019-07-12T16:37:54", "revision_id": "b749c699361239c20f225a88f84939f15d445f93", "snapshot_id": "7ca5fcdae63418c0cd3826ca034f39f6ae5b4369", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/Ansaya/Personal-HomeKit-HAP/b749c699361239c20f225a88f84939f15d445f93/rfc6234-master/sha.h", "visit_date": "2021-06-07T20:10:16.957313" }
stackv2
#include "../Configuration.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus enum { shaSuccess = 0, shaNull, /* Null pointer parameter */ shaInputTooLong, /* input data too long */ shaStateError, /* called Input after FinalBits or Result */ shaBadParam /* passed a bad parameter */ }; /* * This structure will hold context information for the HMAC * keyed-hashing operation. */ typedef struct HMACContext { int hashSize; /* hash size of SHA being used */ int blockSize; /* block size of SHA being used */ SHACTX shaContext; /* SHA context */ unsigned char k_opad[SHA_BlockSize]; /* outer padding - key XORd with opad */ int Computed; /* Is the MAC computed? */ int Corrupted; /* Cumulative corruption code */ } HMACContext; /* * This structure will hold context information for the HKDF * extract-and-expand Key Derivation Functions. */ typedef struct HKDFContext { HMACContext hmacContext; int hashSize; /* hash size of SHA being used */ unsigned char prk[SHA_DIGESTSIZE]; /* pseudo-random key - output of hkdfInput */ int Computed; /* Is the key material computed? */ int Corrupted; /* Cumulative corruption code */ } HKDFContext; /* * Function Prototypes */ int SHA512Reset(SHACTX *c); int SHA512Input(SHACTX *c, const void *data, unsigned int len); int SHA512FinalBits(SHACTX *c, const void *data, unsigned int len); int SHA512Result(SHA512_CTX *c, unsigned char *md); /* * HMAC Keyed-Hashing for Message Authentication, RFC 2104, * for all SHAs. * This interface allows a fixed-length text input to be used. */ extern int hmac(const unsigned char *text, /* pointer to data stream */ int text_len, /* length of data stream */ const unsigned char *key, /* pointer to authentication key */ int key_len, /* length of authentication key */ uint8_t digest[SHA_DIGESTSIZE]); /* caller digest to fill in */ /* * HMAC Keyed-Hashing for Message Authentication, RFC 2104, * for all SHAs. * This interface allows any length of text input to be used. */ extern int hmacReset(HMACContext *context, const unsigned char *key, int key_len); extern int hmacInput(HMACContext *context, const unsigned char *text, int text_len); extern int hmacFinalBits(HMACContext *context, uint8_t bits, unsigned int bit_count); extern int hmacResult(HMACContext *context, uint8_t digest[SHA_DIGESTSIZE]); /* * HKDF HMAC-based Extract-and-Expand Key Derivation Function, * RFC 5869, for all SHAs. */ extern int hkdf(const unsigned char *salt, int salt_len, const unsigned char *ikm, int ikm_len, const unsigned char *info, int info_len, uint8_t okm[ ], int okm_len); extern int hkdfExtract(const unsigned char *salt, int salt_len, const unsigned char *ikm, int ikm_len, uint8_t prk[SHA_DIGESTSIZE]); extern int hkdfExpand(const uint8_t prk[ ], int prk_len, const unsigned char *info, int info_len, uint8_t okm[ ], int okm_len); /* * HKDF HMAC-based Extract-and-Expand Key Derivation Function, * RFC 5869, for all SHAs. * This interface allows any length of text input to be used. */ extern int hkdfReset(HKDFContext *context, const unsigned char *salt, int salt_len); extern int hkdfInput(HKDFContext *context, const unsigned char *ikm, int ikm_len); extern int hkdfFinalBits(HKDFContext *context, uint8_t ikm_bits, unsigned int ikm_bit_count); extern int hkdfResult(HKDFContext *context, uint8_t prk[SHA_DIGESTSIZE], const unsigned char *info, int info_len, uint8_t okm[SHA_DIGESTSIZE], int okm_len); #ifdef __cplusplus } #endif // __cplusplus
2.40625
2
2024-11-18T22:23:40.292343+00:00
2020-05-18T17:08:01
9be85b02176cb8ec6ae48dad1121937bb4ec8c92
{ "blob_id": "9be85b02176cb8ec6ae48dad1121937bb4ec8c92", "branch_name": "refs/heads/master", "committer_date": "2020-05-18T17:08:01", "content_id": "3df05a21890a6d7e69af1904861c1233e6c7c9e2", "detected_licenses": [ "MIT" ], "directory_id": "81aeb6e88d8931161506a3afc3a02a6738ac3697", "extension": "c", "filename": "data.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 265006857, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5864, "license": "MIT", "license_type": "permissive", "path": "/src/data.c", "provenance": "stackv2-0115.json.gz:68153", "repo_name": "imStudd/Self-Organizing-Map", "revision_date": "2020-05-18T17:08:01", "revision_id": "408688e0c92d97d8e3db325195a8ba35ee8bb8be", "snapshot_id": "dd968e20e5d6a9067c8c7670a34b3214595707fc", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/imStudd/Self-Organizing-Map/408688e0c92d97d8e3db325195a8ba35ee8bb8be/src/data.c", "visit_date": "2022-07-23T01:02:11.198405" }
stackv2
#include "data.h" static char *data_names = NULL; Data *init_data(const char *const buffer) { char *buf = NULL, *token1, *save1, *token2, *save2; size_t size_line = 0, size_col = 0; Data *data = NULL; buf = malloc(strlen(buffer) * sizeof(char)); if (buf == NULL) { fprintf(stderr, "Memory allocation error\n"); return NULL; } strcpy(buf, buffer); data = malloc(sizeof(Data)); if (data == NULL) { fprintf(stderr, "Memory allocation error\n"); free(buf); return NULL; } token1 = strtok_r(buf, "\n", &save1); while (token1 != NULL) { if (size_col == 0) { token2 = strtok_r(token1, ",", &save2); while (token2 != NULL) { token2 = strtok_r(NULL, ",", &save2); ++size_col; } } ++size_line; token1 = strtok_r(NULL, "\n", &save1); } data->classes = NULL; data->data_size = size_line; data->values_data_size = size_col - 1; data->classes_size = 0; data->data = malloc(data->data_size * sizeof(Data_t)); if (data->data == NULL) { fprintf(stderr, "Memory allocation error\n"); free(buf); free(data); return NULL; } for (size_t i = 0; i < data->data_size; ++i) { data->data[i].values = malloc(data->values_data_size * sizeof(double)); if (data->data[i].values == NULL) { fprintf(stderr, "Memory allocation error\n"); free(buf); free(data); return NULL; } data->data[i].norm = 0.0; } free(buf); return data; } int load_data_configuration(const Config_t *const config) { size_t size = strlen(config->data_names); if (size == 0) return 0; data_names = malloc(size); if (data_names == NULL) { fprintf(stderr, "Memory allocation error\n"); return -1; } strcpy(data_names, config->data_names); return 0; } void free_data(Data *data) { for (size_t i = 0; i < data->data_size; ++i) { free(data->data[i].values); } free_list(data->classes); free(data->data); free(data); free(data_names); } int format_data(char *const buffer, Data *const data) { size_t i = 0; char *token, *end; List *class = NULL; token = strtok(buffer, ",\n"); while (token != NULL) { for (size_t j = 0; j < data->values_data_size; ++j) { data->data[i].values[j] = strtod(token, &end); if (end == token) { printf("Invalid character line %ld.\n", i + 1); return -1; } token = strtok(NULL, ",\n"); } class = existing_class(data->classes, token); if (class == NULL) { class = create_list_item(strlen(token) * sizeof(char)); strcpy((char *)class->data, token); data->classes = push_front(data->classes, class); if (data->classes == NULL) return -1; data->classes_size++; class = data->classes; } data->data[i].class = class; ++i; token = strtok(NULL, ",\n"); } return 0; } void normalize_data(Data *const data) { for (size_t i = 0; i < data->data_size; ++i) { for (size_t j = 0; j < data->values_data_size; ++j) { data->data[i].norm += data->data[i].values[j] * data->data[i].values[j]; } data->data[i].norm = sqrt(data->data[i].norm); if (data->data[i].norm != 0) { for (size_t j = 0; j < data->values_data_size; ++j) { data->data[i].values[j] /= data->data[i].norm; } } } } double *calculate_data_averages(const Data *const data) { double *averages = malloc(data->values_data_size * sizeof(double)); if (averages == NULL) { fprintf(stderr, "Memory allocation error\n"); return NULL; } memset(averages, 0, data->values_data_size * sizeof(double)); for (size_t i = 0; i < data->values_data_size; ++i) { for (size_t j = 0; j < data->data_size; ++j) { averages[i] += data->data[j].values[i]; } } for (size_t i = 0; i < data->values_data_size; ++i) { averages[i] /= (double)data->data_size; } return averages; } void print_data(const Data *const data) { char *token, *buffer = NULL; printf(" N \t "); if (data_names != NULL) { buffer = malloc(strlen(data_names)); if (buffer == NULL) { fprintf(stderr, "Memory allocation error\n"); return; } strcpy(buffer, data_names); token = strtok(buffer, ","); while (token != NULL) { printf("%s \t ", token); token = strtok(NULL, ","); } } // printf("Norm \n"); printf("\n"); for (size_t i = 0; i < data->data_size; ++i) { printf(" %ld \t ", i); for (size_t j = 0; j < data->values_data_size; ++j) { printf("%f \t ", data->data[i].values[j]); } printf("%s\n", (char *)data->data[i].class->data); // printf("%f\n", data->data[i].norm); // buggy wtf } printf("Data size: %ld\t Values data size: %ld\t Number of classes: %ld\n", data->data_size, data->values_data_size, data->classes_size); free(buffer); } void print_classes(const Data *const data) { List *c = data->classes; printf("Id \t Name\n"); while (c != NULL) { printf("%d \t %s\n", c->id, (char *)c->data); c = c->next; } printf("Number of classes: %ld\n", data->classes_size); }
2.78125
3
2024-11-18T22:23:40.619800+00:00
2014-08-02T18:37:04
8aa3b93de434bc9762628e06424fac46cd69796d
{ "blob_id": "8aa3b93de434bc9762628e06424fac46cd69796d", "branch_name": "refs/heads/master", "committer_date": "2014-08-02T18:37:04", "content_id": "30cdb08933563551fcec54be50dadb7422a7a608", "detected_licenses": [ "Apache-2.0" ], "directory_id": "b6759b04c7ef6405655a7501270e94d20c72e26c", "extension": "h", "filename": "Ping.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": 503, "license": "Apache-2.0", "license_type": "permissive", "path": "/Car Control/protonetWP/include/message/Ping.h", "provenance": "stackv2-0115.json.gz:68281", "repo_name": "dogfaceone1/BEEP-Platform", "revision_date": "2014-08-02T18:37:04", "revision_id": "9823d8b7f351df1591f8127f05844bde3a88dd20", "snapshot_id": "6bdf8929b29daa645754aa5e7c1e1f3214d335dd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dogfaceone1/BEEP-Platform/9823d8b7f351df1591f8127f05844bde3a88dd20/Car Control/protonetWP/include/message/Ping.h", "visit_date": "2021-01-22T05:16:07.729908" }
stackv2
/* This file was autogenerated. All changes will be undone. */ /* Message: Ping, ID: 0002*/ #ifndef _PING_H_ #define _PING_H_ #include <marshal.h> #include <message.h> typedef struct { float64_t timestamp; } ping_t; msg_offset pack_ping( ping_t* ping, msg_offset offset); msg_offset unpack_ping( msg_offset offset, ping_t* out_ptr); void encode_ping( uint8_t src_id, uint8_t dest_id, uint8_t msg_ttl, uint8_t seq_number, ping_t* tx_msg, proto_msg_t* msg); #endif
2
2
2024-11-18T22:23:40.802351+00:00
2020-08-06T08:12:04
36186e30af465c12c2d9c149ca229fff0263ef25
{ "blob_id": "36186e30af465c12c2d9c149ca229fff0263ef25", "branch_name": "refs/heads/master", "committer_date": "2020-08-06T08:12:04", "content_id": "a8c57c643da63593de71f7a7af566ead2423f05a", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "c15b4f7311e4df224de3ed7765cca0647984664c", "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": 285370001, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1080, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/source.c", "provenance": "stackv2-0115.json.gz:68538", "repo_name": "irgangla/shell", "revision_date": "2020-08-06T08:12:04", "revision_id": "852add8974e7b4f429430fd61199dab3f14b3730", "snapshot_id": "f5b2c2aed969336f149a983b3dd72cd66b735e9e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/irgangla/shell/852add8974e7b4f429430fd61199dab3f14b3730/src/source.c", "visit_date": "2022-11-28T13:25:01.606943" }
stackv2
#include <errno.h> #include "shell.h" #include "source.h" void unget_char(struct source_s *src) { if(src->curpos < 0) { return; } src->curpos--; } char next_char(struct source_s *src) { if(!src || !src->buffer) { errno = ENODATA; return ERRCHAR; } if(src->curpos == INIT_SRC_POS) { src->curpos = -1; } if(++src->curpos >= src->bufsize) { src->curpos = src->bufsize; return EOF; } return src->buffer[src->curpos]; } char peek_char(struct source_s *src) { if(!src || !src->buffer) { errno = ENODATA; return ERRCHAR; } long pos = src->curpos; if(pos == INIT_SRC_POS) { pos++; } pos++; if(pos >= src->bufsize) { return EOF; } return src->buffer[pos]; } void skip_white_spaces(struct source_s *src) { char c; if(!src || !src->buffer) { return; } while(((c = peek_char(src)) != EOF) && (c == ' ' || c == '\t')) { next_char(src); } }
2.875
3
2024-11-18T22:23:43.211994+00:00
2017-01-09T10:21:29
47cff235420ab662811100278def721077a0d728
{ "blob_id": "47cff235420ab662811100278def721077a0d728", "branch_name": "refs/heads/master", "committer_date": "2017-01-09T10:21:29", "content_id": "923566ece2c0067aa78036cf44b249a9a4e53a36", "detected_licenses": [ "MIT" ], "directory_id": "56240fc4712d9d2b3147d9281c0f4cb5ccae216c", "extension": "h", "filename": "banking.h", "fork_events_count": 0, "gha_created_at": "2016-07-21T13:25:18", "gha_event_created_at": "2017-01-09T10:15:15", "gha_language": "Shell", "gha_license_id": null, "github_id": 63871436, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 829, "license": "MIT", "license_type": "permissive", "path": "/includes/banking.h", "provenance": "stackv2-0115.json.gz:68924", "repo_name": "iamcaleberic/genesis", "revision_date": "2017-01-09T10:21:29", "revision_id": "9134f08f35ef536153583256b6223d91d27a6771", "snapshot_id": "56490b313ff55e51e858d3aa700c9f92a4e6de28", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/iamcaleberic/genesis/9134f08f35ef536153583256b6223d91d27a6771/includes/banking.h", "visit_date": "2021-01-17T19:57:42.723444" }
stackv2
#include <stdio.h> #include <stdlib.h> float accountBalance, amount; void initalizeAccount(); void getBalance(void); void askCustomer(void); void updateAccount(float amount); void addGift(float giftAmount); void thankYou(void); void initalizeAccount(){ accountBalance = 0.0; } void addGift(float giftAmount){ accountBalance += giftAmount; } void askCustomer(void){ printf("Next Trasaction....\n"); printf("Enter amount to credit(positve) or debit(negative): "); scanf("%f\n",&amount ); } void getBalance(void){ printf("\n The current account balance is £ %.2f\n", accountBalance); } void updateAccount(float amount){ accountBalance += amount; printf("The account was updated with £ %.2f\n",amount ); } void thankYou(void) { printf("-------------Thank you for banking with us-----------------\n" ); }
3.046875
3
2024-11-18T22:23:43.274705+00:00
2018-11-21T13:04:09
3e34b22eab5a940a07a52b8b6525d07a56793e72
{ "blob_id": "3e34b22eab5a940a07a52b8b6525d07a56793e72", "branch_name": "refs/heads/master", "committer_date": "2018-11-21T13:04:09", "content_id": "e721ce361c948a05cf9c4ca92ee4cd7d60ddcaef", "detected_licenses": [ "MIT" ], "directory_id": "cf6c5cde3a8d24891bd95887ad47867394490c17", "extension": "c", "filename": "verification.c", "fork_events_count": 0, "gha_created_at": "2015-11-20T00:02:42", "gha_event_created_at": "2018-11-21T13:04:10", "gha_language": "C", "gha_license_id": null, "github_id": 46527954, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2411, "license": "MIT", "license_type": "permissive", "path": "/Collector/SRC/verification.c", "provenance": "stackv2-0115.json.gz:69053", "repo_name": "kaldoran/Send-file-P2P", "revision_date": "2018-11-21T13:04:09", "revision_id": "dcb8d44ccaecca70c99786f5e6ea92529b8e6aff", "snapshot_id": "d1e3dc00b99bb1e5735ec0666ec69d579a9166a5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kaldoran/Send-file-P2P/dcb8d44ccaecca70c99786f5e6ea92529b8e6aff/Collector/SRC/verification.c", "visit_date": "2020-12-25T21:12:59.986652" }
stackv2
//---------------------------------------------------------- // AUTEUR : REYNAUD Nicolas | // FICHIER : verification.c | // DATE : 08/02/15 | //---------------------------------------------------------- #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include "error.h" #include "verification.h" void hexToString(unsigned char outbuf[SHA_DIGEST_LENGTH], char outsha[40]) { int i; for ( i = 0; i < SHA_DIGEST_LENGTH; i++) { sprintf( outsha + i * 2, "%02x", outbuf[i]); } } bool checkFile(FILE* file, Index* index) { bool full = TRUE; int i; unsigned char inbuf[index->pack_size]; for ( i = 0; i < index->nb_package; i++ ) { memset(inbuf, '\0', index->pack_size); fread ((char*)inbuf, index->pack_size, 1, file); if( !checkVol(index, inbuf, sizeof(inbuf), i)) { DEBUG_MSG("\t - Volume %d missing\n", i); full = FALSE; } } if ( full ) { printf("\t - we've got all volume\n"); } else { printf("\t - Some volume is missing\n"); } return full; } bool checkVol(Index* index, unsigned char* vol, int vol_size, int id_vol) { char outsha[40]; unsigned char outbuf[SHA_DIGEST_LENGTH]; SHA1(vol, vol_size, outbuf); hexToString(outbuf, outsha); if ( strcmp(outsha, index->sha[id_vol]) == 0 ) { index->local_vols[id_vol] = '1'; return TRUE; } index->local_vols[id_vol] = '0'; return FALSE; } bool fileExist(const char* filename) { struct stat s; if ( stat(filename, &s) == -1 ) { printf("[ERROR] '%s' does not exist.\n", filename); return FALSE; } if ( s.st_mode & S_IFDIR ) { printf("[ERROR] '%s' is a directory.\n", filename); return FALSE; } return TRUE; } bool verifPort(int port) { if(port <= 1024){ printf("[ERROR] The port must be greater than 1024.\n"); return FALSE; } if(port > 65536) { printf("[ERROR] The port must be lower than 65536.\n"); return FALSE; } return TRUE; } bool isComplet(const char* vol) { for ( ; *vol != '\0'; vol++ ) { if ( *vol == '0' ) { return FALSE; } } return TRUE; }
2.59375
3
2024-11-18T22:23:43.336817+00:00
2019-05-07T22:50:34
cad8d3b651068518bf505de9962a2545ce554274
{ "blob_id": "cad8d3b651068518bf505de9962a2545ce554274", "branch_name": "refs/heads/master", "committer_date": "2019-05-07T22:50:34", "content_id": "54036f276152d384d8c3a6fb36f793d8dd5c58e8", "detected_licenses": [ "MIT" ], "directory_id": "075d1c91268025e5428e2690cb06197723b3032f", "extension": "c", "filename": "timer0_timer.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 185488217, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1623, "license": "MIT", "license_type": "permissive", "path": "/Aulas/7aula/timer0_timer.c", "provenance": "stackv2-0115.json.gz:69181", "repo_name": "rafaelmcam/RTOs_ChibiOS", "revision_date": "2019-05-07T22:50:34", "revision_id": "08d8e21f2c7185d2c47846f67cbfba70c706d689", "snapshot_id": "9389c408d716b9c95885ce841f8c96132a75256f", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/rafaelmcam/RTOs_ChibiOS/08d8e21f2c7185d2c47846f67cbfba70c706d689/Aulas/7aula/timer0_timer.c", "visit_date": "2020-05-20T08:59:23.547776" }
stackv2
#include <avr/io.h> #include <avr/cpufunc.h> #include <avr/interrupt.h> /* * Constantes utilizadas no código */ /* * Definição de funções */ void setup_timer0(void) { /* * Para as macros abaixo e outras, veja o arquivo * /usr/lib/avr/include/avr/iom328p.h */ OCR0A = 250; TCCR0A = (1 << WGM01); TCCR0B = (1 << CS01) | (1 << CS00); TIMSK0 = (1 << OCIE0A); sei(); } /* -------------------------------------*/ void setup_main(void) { LED_DDR |= (1 << LED_PINNBR); LED_PORT |= (1 << LED_PINNBR); sei(); /* Seta flag principal de habilitação de interrupções */ } /* -------------------------------------*/ /* * Interrupt handlers devem ser definidos com a macros * ISR(), que é definida no arquivo avr/interrupt.h. * Veja também a página * http://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html */ volatile uint16_t ms; volatile uint16_t ms_set; volatile uint8_t ring_flag; ISR(TIMER0_COMPA_vect) { if (ms) if(!--ms) { ms = ms_set; ring_flag = 1; } } /* -------------------------------------*/ int main(void) { int8_t step = 25; const uint16_t max_delay = 500, min_delay = 100; ms_set = 100; ms = ms_set; setup_timer0(); setup_main(); while(1) { while (!ring_flag) ; cli(); ring_flag = 0; ms_set += step; if ((ms_set > max_delay) || (ms_set < min_delay)) { step = -step; ms_set += 2*step; } sei(); LED_PIN = 1 << LED_PINNBR; } return 0; }
2.578125
3
2024-11-18T22:23:43.817710+00:00
2020-04-02T13:45:02
0421facd62a8b430826ec0ed2ca680c65294c826
{ "blob_id": "0421facd62a8b430826ec0ed2ca680c65294c826", "branch_name": "refs/heads/master", "committer_date": "2020-04-02T13:45:02", "content_id": "469eed81f476982111f6739ea54b85730c119696", "detected_licenses": [ "MIT" ], "directory_id": "56db76294cce4686c7109fc3f3bb5693978aee33", "extension": "c", "filename": "input.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 250882334, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 470, "license": "MIT", "license_type": "permissive", "path": "/input.c", "provenance": "stackv2-0115.json.gz:69440", "repo_name": "pylover/3djoy", "revision_date": "2020-04-02T13:45:02", "revision_id": "9074bcd59c14fce4029ee3b08518e3264febe885", "snapshot_id": "03781b6bfbab432fd10bde6bd91dbc6f9554aee1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/pylover/3djoy/9074bcd59c14fce4029ee3b08518e3264febe885/input.c", "visit_date": "2021-05-17T16:53:24.429036" }
stackv2
#include "common.h" #include <fcntl.h> #include <sys/epoll.h> static int inputfd; int inputopen(int epollfd) { struct epoll_event ev; inputfd = open(settings.input, O_RDONLY); if (inputfd == ERR) { return ERR; } ev.events = EPOLLIN; ev.data.fd = inputfd; if (epoll_ctl(epollfd, EPOLL_CTL_ADD, inputfd, &ev) == ERR) { perrorf("epoll_ctl: EPOLL_CTL_ADD, input device"); return ERR; } return inputfd; }
2.203125
2
2024-11-18T22:23:43.896162+00:00
2018-05-16T05:20:52
92aa39141f421dcb7d5921ff8ca0b8d9696efd47
{ "blob_id": "92aa39141f421dcb7d5921ff8ca0b8d9696efd47", "branch_name": "refs/heads/master", "committer_date": "2018-05-16T05:20:52", "content_id": "c534bb553310c4ee7c7fa8b865c5f578b0263528", "detected_licenses": [ "MIT" ], "directory_id": "cbc5bd74d2f92a4b6eee4fc1474d02ac635f56b0", "extension": "c", "filename": "mm.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": 7466, "license": "MIT", "license_type": "permissive", "path": "/heaps/min-max/mm.c", "provenance": "stackv2-0115.json.gz:69570", "repo_name": "wuzijia2018/algo", "revision_date": "2018-05-16T05:20:52", "revision_id": "05c5f727bbe82185ec969bd4c6caa713ca7c34e5", "snapshot_id": "5ff876a9304889b0d63281c3b02ac820d9415745", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/wuzijia2018/algo/05c5f727bbe82185ec969bd4c6caa713ca7c34e5/heaps/min-max/mm.c", "visit_date": "2021-09-14T16:32:36.676755" }
stackv2
#include "mm.h" // NOTE: Implementation reference: "Min-Max Heaps and Generalized Priority Queues" // (Atkinson, et. al) // http://www.akira.ruc.dk/~keld/teaching/algoritmedesign_f03/Artikler/02/Atkinson86.pdf static int getDepth(Position pos); static void percolateUpMin(Position pos, MinMaxHeap H); static void percolateUpMax(Position pos, MinMaxHeap H); static void percolateDownMax(Position pos, MinMaxHeap H); static void percolateDownMin(Position pos, MinMaxHeap H); struct MinMaxHeapStruct { int Capacity; int Size; int *Elements; }; MinMaxHeap initializeMMH(int maxElements) { MinMaxHeap H = malloc(sizeof(struct MinMaxHeapStruct)); assert(H); H->Capacity = maxElements; H->Size = 0; H->Elements = malloc((H->Capacity+1) * sizeof(struct MinMaxHeapStruct)); H->Elements[0] = INT_MIN; return H; } int deleteMinMHH(MinMaxHeap H) { int i, child; int minElement, lastElement; if(isEmpty(H)) fatal("Heap is empty!"); minElement = H->Elements[1]; lastElement = H->Elements[H->Size--]; for(i = 1; i*4 <= H->Size; i = child) { // Find the child with min value child = i*4 + findMin(&H->Elements[i*4], min(4, H->Size-i*4)); if(lastElement > H->Elements[child]) H->Elements[i] = H->Elements[child]; else break; } H->Elements[i] = lastElement; return minElement; } static int findMaxMMHIdx(MinMaxHeap H) { return H->Elements[2] > H->Elements[3] ? 2: 3; } int deleteMaxMHH(MinMaxHeap H) { int i, child; int maxElement, lastElement; if(isEmpty(H)) fatal("Heap is empty!"); maxElement = findMaxMMH(H); lastElement = H->Elements[H->Size--]; for(i = findMaxMMHIdx(H); i*4 <= H->Size; i = child) { // Find the child with max value child = i*4 + findMax(&H->Elements[i*4], min(4, H->Size-i*4)); if(lastElement < H->Elements[child]) H->Elements[i] = H->Elements[child]; else break; } H->Elements[i] = lastElement; return maxElement; } void destroyMinMaxHeap(MinMaxHeap H) { free(H->Elements); free(H); } void makeEmptyMMH(MinMaxHeap H) { H->Size = 0; } /* * return the depth (level) that the given node * represented by pos is at. */ static int getDepth(Position pos) { int depth = 0; while((pos /= 2) > 0) depth++; return depth; } static void percolateUpMin(Position pos, MinMaxHeap H) { if (pos/4 > 0) // has grandparent if (H->Elements[pos] < H->Elements[pos/4]) { H->Elements[pos/4] = H->Elements[pos]; percolateUpMin(pos/4, H); } } static void percolateUpMax(Position pos, MinMaxHeap H) { if (pos/4 > 0) if (H->Elements[pos] > H->Elements[pos/4]) { H->Elements[pos/4] = H->Elements[pos]; percolateUpMax(pos/4, H); } } void insertMHH(int X, MinMaxHeap H) { if(isFull(H)) fatal("Heap is full!"); H->Elements[++H->Size] = X; if(getDepth(H->Size) % 2 == 0) // even (min) level { if (H->Size/2 > 0 && X > H->Elements[H->Size/2]) { swap(&H->Elements[H->Size/2], &H->Elements[H->Size]); percolateUpMax(H->Size/2, H); } } else // odd (max) level { if (H->Size/2 > 0 && X < H->Elements[H->Size/2]) { swap(&H->Elements[H->Size/2], &H->Elements[H->Size]); percolateUpMin(H->Size/2, H); } } } int findMinMMH(MinMaxHeap H) { return H->Elements[1]; } int findMaxMMH(MinMaxHeap H) { return H->Elements[2] > H->Elements[3] ? H->Elements[2] : H->Elements[3]; } int isEmpty(MinMaxHeap H) { return H->Size==0; } int isFull(MinMaxHeap H) { return H->Size == H->Capacity; } MinMaxHeap initializeMinMaxHeapFromArray(int* array, int arrayLength) { MinMaxHeap H = initializeMMH(arrayLength); int i; for(i = 0; i < arrayLength; i++) insertMHH(array[i], H); return H; } /* * return the index of the smallest of children and * grandchildren (if any) of i */ static int idxOfSmallestChildrenAndGrandChildren(Position pos, MinMaxHeap H) { int idx1, idx2; idx1 = findMin(&H->Elements[pos*2],2); if (pos*4 <= H->Size) { idx2 = findMin(&H->Elements[pos*4],min(4, H->Size-pos*4)); return H->Elements[pos*2 + idx1] > H->Elements[pos*4 + idx2] ? pos*4 + idx2 : pos*2 + idx1; } else return idx1; } /* * return the index of the biggest of children and * grandchildren (if any) of i */ static int idxOfBiggestChildrenAndGrandChildren(Position pos, MinMaxHeap H) { int idx1, idx2; idx1 = pos*2 + findMax(&H->Elements[pos*2],2); if (pos*4 <= H->Size) { idx2 = pos*4 + findMax(&H->Elements[pos*4],min(4, H->Size-pos*4)); return H->Elements[idx1] > H->Elements[idx2] ? idx1 : idx2; } else return idx1; } static void percolateDownMax(Position pos, MinMaxHeap H) { int m, i = pos; if(i*2 <= H->Size) // has children { m = idxOfBiggestChildrenAndGrandChildren(pos, H); #ifdef DEBUG printf("m: %d\t H->Elements[m]:%d\n", m, H->Elements[m]); #endif if (m/2 != i) // m is a grandchild of i { if(H->Elements[m] > H->Elements[i]) { swap(&H->Elements[m], &H->Elements[i]); } percolateDownMax(m, H); } else // m is a child of i { if(H->Elements[m] > H->Elements[i]) swap(&H->Elements[m], &H->Elements[i]); } } } static void percolateDownMin(Position pos, MinMaxHeap H) { int m, i = pos; if(i*2 <= H->Size) // has children { m = idxOfSmallestChildrenAndGrandChildren(pos, H); #ifdef DEBUG printf("m: %d\t H->Elements[m]:%d\n", m, H->Elements[m]); #endif if (m/2 != i) // m is a grandchild of i { if(H->Elements[m] < H->Elements[i]) { swap(&H->Elements[m], &H->Elements[i]); } percolateDownMin(m, H); } else // m is a child of i { if(H->Elements[m] < H->Elements[i]) swap(&H->Elements[m], &H->Elements[i]); } } } MinMaxHeap buildMMH(int* array, int arrayLength) { MinMaxHeap H = initializeMMH(2*arrayLength); // We first construct a complete binary tree int i; for (i = 1; i < arrayLength + 1; i++) H->Elements[i] = array[i-1]; H->Size = arrayLength; #ifdef DEBUG printf("H->Size: %d\n", H->Size); printArray(&H->Elements[1], H->Size); #endif // Restore the min-max binary heap property for(i = H->Size / 2; i > 0; i--) { if(getDepth(i) % 2 == 0) // even (min) level { percolateDownMin(i, H); #ifdef DEBUG printf("After percolateDownMin:\n"); printArray(&H->Elements[1], H->Size); #endif } else // odd (max) level { percolateDownMax(i, H); #ifdef DEBUG printf("After percolateDownMax:\n"); printArray(&H->Elements[1], H->Size); #endif } } return H; } static void mmh_print_dot_aux(MinMaxHeap H, FILE* stream) { int i; for(i=1; i*2 <= H->Size; i++) { fprintf(stream, "node%d [label=%d];\n", i, H->Elements[i]); fprintf(stream, "node%d [label=%d];\n", 2*i, H->Elements[2*i]); fprintf(stream, "node%d->node%d;\n", i, 2*i); if (i*2 != H->Size) { fprintf(stream, "node%d [label=%d];\n", 2*i+1, H->Elements[2*i+1]); fprintf(stream, "node%d->node%d;\n", i, 2*i+1); } } } void mmh_print_dot(MinMaxHeap H, FILE* stream) { fprintf(stream, "digraph MinMaxHeap {\n"); mmh_print_dot_aux(H, stream); fprintf(stream, "}\n"); }
3.40625
3
2024-11-18T22:23:43.956814+00:00
2021-07-03T13:13:15
8d87f3f12585704462066b830e7d5f8afddbdab1
{ "blob_id": "8d87f3f12585704462066b830e7d5f8afddbdab1", "branch_name": "refs/heads/main", "committer_date": "2021-07-03T13:13:15", "content_id": "c5aa2dc19ed1cf8685eebd1809e19f331b261cb9", "detected_licenses": [ "Apache-2.0" ], "directory_id": "76d50404956852a0cebe6977f740dfae78623faf", "extension": "c", "filename": "617a.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 381626187, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 154, "license": "Apache-2.0", "license_type": "permissive", "path": "/617a.c", "provenance": "stackv2-0115.json.gz:69699", "repo_name": "kratos6753/codeforces", "revision_date": "2021-07-03T13:13:15", "revision_id": "634efaf8f8ccee3ffcda3239d030f5a732e19d21", "snapshot_id": "e6928bd98af633da25eb430acb38d00b839c4e5f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kratos6753/codeforces/634efaf8f8ccee3ffcda3239d030f5a732e19d21/617a.c", "visit_date": "2023-06-11T05:11:51.415835" }
stackv2
#include <stdio.h> #include <math.h> int main(int argc, char const *argv[]) { double x; scanf("%lf", &x); printf("%d\n", (int)ceil(x/5)); return 0; }
2.203125
2
2024-11-18T22:23:44.564031+00:00
2014-01-13T06:30:35
d7a1cf047d6bbf3b8b2bb2f229ef36760fee7a78
{ "blob_id": "d7a1cf047d6bbf3b8b2bb2f229ef36760fee7a78", "branch_name": "refs/heads/master", "committer_date": "2014-01-13T06:30:35", "content_id": "c107f91b70c60a26c1a8d6b91d4bfb3f32717d8b", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "eddfd9a2a577a48d80d857d214374485955d863f", "extension": "c", "filename": "sem.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 4071291, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10472, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/CoOS/kernel/sem.c", "provenance": "stackv2-0115.json.gz:70216", "repo_name": "xinyun/CoOS", "revision_date": "2014-01-13T06:30:35", "revision_id": "c0f96927afab7568eed3af1549e3b63eddadcfb1", "snapshot_id": "7dd667ff53cda0ed1c7a18fd9aab4a4c8f8c8987", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/xinyun/CoOS/c0f96927afab7568eed3af1549e3b63eddadcfb1/CoOS/kernel/sem.c", "visit_date": "2020-12-30T18:38:00.634036" }
stackv2
/** ******************************************************************************* * @file sem.c * @version V1.1.4 * @date 2011.04.20 * @brief Semaphore management implementation code of CooCox CoOS kernel. ******************************************************************************* * @copy * * INTERNAL FILE,DON'T PUBLIC. * * <h2><center>&copy; COPYRIGHT 2009 CooCox </center></h2> ******************************************************************************* */ /*---------------------------- Include ---------------------------------------*/ #include <coocox.h> #if CFG_SEM_EN >0 /** ******************************************************************************* * @brief Create a semaphore * @param[in] initCnt Semaphore valid counter. * @param[in] maxCnt Semaphore max initialize counter. * @param[in] sortType Semaphore sort type. * @param[out] None * @retval E_CREATE_FAIL Create semaphore fail. * @retval others Create semaphore successful. * * @par Description * @details This function is called to create a semaphore. ******************************************************************************* */ OS_EventID CoCreateSem(U16 initCnt,U16 maxCnt,U8 sortType) { P_ECB pecb; #if CFG_PAR_CHECKOUT_EN >0 if(initCnt > maxCnt) { return E_CREATE_FAIL; /* Invalid 'initCnt' or 'maxCnt' */ } if ((sortType != EVENT_SORT_TYPE_FIFO) && (sortType != EVENT_SORT_TYPE_PRIO)) { return E_CREATE_FAIL; /* Illegal sort type,return error */ } #endif /* Create a semaphore type event control block */ pecb = CreatEvent(EVENT_TYPE_SEM,sortType,Co_NULL); if(pecb == Co_NULL) /* If failed to create event block */ { return E_CREATE_FAIL; } pecb->eventCounter = initCnt;/* Initialize event block */ pecb->initialEventCounter = maxCnt; return (pecb->id); /* Return event id */ } /** ******************************************************************************* * @brief Delete a semaphore * @param[in] id Event ID which to be deleted. * @param[in] opt Delete option. * @arg == OPT_DEL_ANYWAY Delete semaphore always * @arg == OPT_DEL_NO_PEND Delete semaphore only when no task pending on. * @param[out] None * @retval E_INVALID_ID Invalid event ID. * @retval E_INVALID_PARAMETER Invalid parameter. * @retval E_TASK_WAITTING Tasks waitting for the event,delete fail. * @retval E_OK Event deleted successful. * * @par Description * @details This function is called to delete a semaphore. * * @note ******************************************************************************* */ StatusType CoDelSem(OS_EventID id,U8 opt) { P_ECB pecb; #if CFG_PAR_CHECKOUT_EN >0 if(id >= CFG_MAX_EVENT) { return E_INVALID_ID; } #endif pecb = &EventTbl[id]; #if CFG_PAR_CHECKOUT_EN >0 if(pecb->eventType != EVENT_TYPE_SEM) { return E_INVALID_ID; /* The event type is not semaphore */ } #endif return (DeleteEvent(pecb,opt));/* Delete the semaphore event control block*/ } /** ******************************************************************************* * @brief Accept a semaphore without waitting * @param[in] id Event ID * @param[out] None * @retval E_INVALID_ID Invalid event ID. * @retval E_SEM_EMPTY No semaphore exist. * @retval E_OK Get semaphore successful. * * @par Description * @details This function is called accept a semaphore without waitting. ******************************************************************************* */ StatusType CoAcceptSem(OS_EventID id) { P_ECB pecb; #if CFG_PAR_CHECKOUT_EN >0 if(id >= CFG_MAX_EVENT) { return E_INVALID_ID; } #endif pecb = &EventTbl[id]; #if CFG_PAR_CHECKOUT_EN >0 if( pecb->eventType != EVENT_TYPE_SEM) { return E_INVALID_ID; } #endif OsSchedLock(); if(pecb->eventCounter > 0) /* If semaphore is positive,resource available */ { pecb->eventCounter--; /* Decrement semaphore only if positive */ OsSchedUnlock(); return E_OK; } else /* Resource is not available */ { OsSchedUnlock(); return E_SEM_EMPTY; } } /** ******************************************************************************* * @brief wait for a semaphore * @param[in] id Event ID. * @param[in] timeout The longest time for writting semaphore. * @para 0 * @para 0x1~0xff * @param[out] None * @retval E_CALL Error call in ISR. * @retval E_INVALID_ID Invalid event ID. * @retval E_TIMEOUT Semaphore was not received within the specified * 'timeout' time. * @retval E_OK The call was successful and your task owns the * resource,or the event you are waiting for occurred. * * @par Description * @details This function is called to waits for a semaphore. * @note IF this function is called in ISR,nothing to do and return immediately. ******************************************************************************* */ StatusType CoPendSem(OS_EventID id,U32 timeout) { P_ECB pecb; P_OSTCB curTCB; if(OSIntNesting > 0) /* If the caller is ISR */ { return E_CALL; } #if CFG_PAR_CHECKOUT_EN >0 if(id >= CFG_MAX_EVENT) { return E_INVALID_ID; } #endif pecb = &EventTbl[id]; #if CFG_PAR_CHECKOUT_EN >0 if(pecb->eventType != EVENT_TYPE_SEM) { return E_INVALID_ID; } #endif if(OSSchedLock != 0) /* Schdule is locked? */ { return E_OS_IN_LOCK; /* Yes,error return */ } OsSchedLock(); if(pecb->eventCounter > 0) /* If semaphore is positive,resource available */ { pecb->eventCounter--; /* Decrement semaphore only if positive */ OsSchedUnlock(); return E_OK; } else /* Resource is not available */ { curTCB = TCBRunning; if(timeout == 0) /* If time-out is not configured */ { EventTaskToWait(pecb,curTCB); /* Block task until event occurs */ OsSchedUnlock(); curTCB->pmail = Co_NULL; return E_OK; } else /* If time-out is configured */ { /* Block task until event or timeout occurs */ EventTaskToWait(pecb,curTCB); InsertDelayList(curTCB,timeout); OsSchedUnlock(); if (curTCB->pmail == Co_NULL) /* If pmail is Co_NULL, time-out occurred*/ { return E_TIMEOUT; } else /* Event occurred or event have been deleted*/ { curTCB->pmail = Co_NULL; return E_OK; } } } } /** ******************************************************************************* * @brief Post a semaphore * @param[in] id id of event control block associated with the desired semaphore. * @param[out] None * @retval E_INVALID_ID Parameter id passed was invalid event ID. * @retval E_SEM_FULL Semaphore full. * @retval E_OK Semaphore had post successful. * * @par Description * @details This function is called to post a semaphore to corresponding event. * * @note ******************************************************************************* */ StatusType CoPostSem(OS_EventID id) { P_ECB pecb; #if CFG_PAR_CHECKOUT_EN >0 if(id >= CFG_MAX_EVENT) { return E_INVALID_ID; } #endif pecb = &EventTbl[id]; #if CFG_PAR_CHECKOUT_EN >0 if(pecb->eventType != EVENT_TYPE_SEM) /* Invalid event control block type */ { return E_INVALID_ID; } #endif /* Make sure semaphore will not overflow */ if(pecb->eventCounter == pecb->initialEventCounter) { return E_SEM_FULL; /* The counter of Semaphore reach the max number*/ } OsSchedLock(); if(pecb->eventTCBList != Co_NULL) { EventTaskToRdy(pecb); OsSchedUnlock(); return E_OK; } pecb->eventCounter++; /* Increment semaphore count to register event */ EventTaskToRdy(pecb); /* Check semaphore event waiting list */ OsSchedUnlock(); return E_OK; } /** ******************************************************************************* * @brief Post a semaphore in ISR * @param[in] id identifier of event control block associated with the * desired semaphore. * @param[out] None * @retval E_INVALID_ID Parameter id passed was invalid event ID. * @retval E_NO_TASK_WAITTING There are one more tasks waitting for the event. * @retval E_OK Semaphore had signaled successful. * * @par Description * @details This function is called in ISR to post a semaphore to corresponding * event. * @note ******************************************************************************* */ #if CFG_MAX_SERVICE_REQUEST > 0 StatusType isr_PostSem(OS_EventID id) { if(OSSchedLock > 0) /* If scheduler is locked,(the caller is ISR) */ { /* Initiate a post service handling request */ if(InsertInSRQ(SEM_REQ,id,Co_NULL) == Co_FALSE) { return E_SEV_REQ_FULL; /* If service request queue is full */ } else /* Operate successfully */ { return E_OK; } } else { return(CoPostSem(id)); /* Post semaphore */ } } #endif #endif
2.78125
3
2024-11-18T22:23:45.431624+00:00
2016-07-31T00:09:39
755d897c8f63218fe2b49ff0b882099f18c35e90
{ "blob_id": "755d897c8f63218fe2b49ff0b882099f18c35e90", "branch_name": "refs/heads/master", "committer_date": "2016-07-31T00:09:39", "content_id": "702b39c99db78f19fecce90b7989276ab6c65eb1", "detected_licenses": [ "MIT" ], "directory_id": "e4ebe115cdc36af922f32fdeb0636ecf1b066100", "extension": "c", "filename": "HashMap.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 13810128, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1789, "license": "MIT", "license_type": "permissive", "path": "/dataStructures/hashmap/HashMap.c", "provenance": "stackv2-0115.json.gz:70860", "repo_name": "odeke-em/utils", "revision_date": "2016-07-31T00:09:39", "revision_id": "9a0ed5bb4a2809d0a442e1a74c71edd9563f84cf", "snapshot_id": "6a24506786ac8b6ec8b5f36d0d21ed000ac01ca8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/odeke-em/utils/9a0ed5bb4a2809d0a442e1a74c71edd9563f84cf/dataStructures/hashmap/HashMap.c", "visit_date": "2020-04-06T03:41:16.122745" }
stackv2
// Author: Emmanuel Odeke <odeke@ualberta.ca> #include <stdlib.h> #include <pthread.h> #include "RTrie.h" #include "HashMap.h" inline HashMap *allocHashMap(void) { return (HashMap *)malloc(sizeof(HashMap)); } inline HashMap *newHashMap(const UInt base) { HashMap *hm = allocHashMap(); assert((hm != NULL)); hm->map = NULL; hm->base = base; return hm; } HashMap *destroyHashMap(HashMap *hm) { if (hm != NULL) { hm->map = destroyRTrie(hm->map, hm->base); pthread_mutex_t destMutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&destMutex); free(hm); hm = NULL; pthread_mutex_unlock(&destMutex); } return hm; } HashMap *put(HashMap *hm, const ULInt hash, void *data, const UInt allocStyle) { if (hm != NULL) { if (hm->map == NULL) hm->map = newRTrie(hm->base); DataSav dataSav = {.isHeapd=allocStyle, .data=data, .prevFreer=free}; hm->map = (RTrie *)putRTrie(hm->map, &dataSav, hash, hm->base); } return hm; } void *get(HashMap *hm, const ULInt hash) { void *retr = NULL; if (hm != NULL && hm->map != NULL) retr = getRTrie(hm->map, NULL, hash, hm->base); return retr; } HashMap *pop(HashMap *hm, const ULInt hash, void (*prevFreer)(void *), const void **popSave) { if (hm != NULL && hm->map != NULL && popSave != NULL) { DataSav dSav = {.prevFreer=prevFreer}; *popSave = popRTrie(hm->map, &dSav, hash, hm->base); } return hm; } #ifdef _HASHMAP_MAIN int main() { HashMap *hm = newHashMap(10); hm = put(hm, 9, (void *)hm, 0); void *retr; hm = pop(hm, 9, free, (const void **)&retr); printf("retr: %p\n", retr); destroyHashMap(hm); return 0; } #endif // _HASHMAP_MAIN
2.875
3
2024-11-18T22:23:45.497924+00:00
2020-03-06T12:46:01
2b0ad5f5b21446bab5cdc00ce803d756129e6441
{ "blob_id": "2b0ad5f5b21446bab5cdc00ce803d756129e6441", "branch_name": "refs/heads/master", "committer_date": "2020-03-06T12:46:01", "content_id": "73cfc5fe8b92eb1c78aba9c25f610780b139f11c", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "ab8fc6dc5ec52a03d3b947eaef6e4c9bb054823c", "extension": "c", "filename": "usart1.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 245389465, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4784, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/Projects/STM32L053R8-Nucleo/Applications/Bluetooth_LE/SensorDemo/USART/usart1.c", "provenance": "stackv2-0115.json.gz:70988", "repo_name": "polya-xue/Wearable-indoor-navigation-system", "revision_date": "2020-03-06T12:46:01", "revision_id": "4aaaf220c9a42eba7935c708eacfee1e97a61c9c", "snapshot_id": "4291600f0c5d267eefbadc911c089c0e2f02e265", "src_encoding": "GB18030", "star_events_count": 2, "url": "https://raw.githubusercontent.com/polya-xue/Wearable-indoor-navigation-system/4aaaf220c9a42eba7935c708eacfee1e97a61c9c/Projects/STM32L053R8-Nucleo/Applications/Bluetooth_LE/SensorDemo/USART/usart1.c", "visit_date": "2021-02-23T01:24:17.537085" }
stackv2
#include "usart1.h" #include "gpio.h" /* USER CODE BEGIN 0 */ uint8_t USART_RX_BUF[USART_REC_LEN]; //接收缓冲,最大USART_REC_LEN个字节. //接收状态 //bit15, 接收完成标志 //bit14, 接收到0x0d //bit13~0, 接收到的有效字节数目 uint16_t USART_RX_STA=0; //接收状态标记 /* USER CODE END 0 */ UART_HandleTypeDef huart1; extern UART_HandleTypeDef huart2; /* USART1 init function */ void MX_USART1_UART_Init(void) { huart1.Instance = USART1; huart1.Init.BaudRate = 115200; huart1.Init.WordLength = UART_WORDLENGTH_8B; huart1.Init.StopBits = UART_STOPBITS_1; huart1.Init.Parity = UART_PARITY_NONE; huart1.Init.Mode = UART_MODE_TX_RX; huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE; huart1.Init.OverSampling = UART_OVERSAMPLING_8; huart1.Init.OneBitSampling = UART_ONEBIT_SAMPLING_DISABLED; huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT; HAL_UART_Init(&huart1); } void HAL_UART_MspInit(UART_HandleTypeDef* huart) { GPIO_InitTypeDef GPIO_InitStruct; if(huart->Instance==USART1) { /* Peripheral clock enable */ __USART1_CLK_ENABLE(); /**USART1 GPIO Configuration PA9 ------> USART1-TX PA10 ------> USART1-RX */ GPIO_InitStruct.Pin = GPIO_PIN_9|GPIO_PIN_10; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; GPIO_InitStruct.Alternate = GPIO_AF4_USART1; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); __HAL_UART_ENABLE_IT(&huart1,UART_IT_RXNE); /* Peripheral interrupt init*/ HAL_NVIC_SetPriority(USART1_IRQn, 0, 0); HAL_NVIC_EnableIRQ(USART1_IRQn); } if(huart->Instance==USART2) { /* Peripheral clock enable */ __USART2_CLK_ENABLE(); /**USART2 GPIO Configuration PA2 ------> USART2_TX PA3 ------> USART2_RX */ GPIO_InitStruct.Pin = GPIO_PIN_2|GPIO_PIN_3; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; GPIO_InitStruct.Alternate = GPIO_AF4_USART2; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); __HAL_UART_ENABLE_IT(&huart2,UART_IT_RXNE); /* Peripheral interrupt init*/ HAL_NVIC_SetPriority(USART2_IRQn, 0, 0); HAL_NVIC_EnableIRQ(USART2_IRQn); } } void HAL_UART_MspDeInit(UART_HandleTypeDef* huart) { if(huart->Instance==USART1) { /* Peripheral clock disable */ __USART1_CLK_DISABLE(); /**USART2 GPIO Configuration PA2 ------> USART1_TX PA3 ------> USART1_RX */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_9|GPIO_PIN_10); /* Peripheral interrupt Deinit*/ HAL_NVIC_DisableIRQ(USART1_IRQn); } if(huart->Instance==USART2) { /* Peripheral clock disable */ __USART2_CLK_DISABLE(); /**USART2 GPIO Configuration PA2 ------> USART2_TX PA3 ------> USART2_RX */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_2|GPIO_PIN_3); /* Peripheral interrupt Deinit*/ HAL_NVIC_DisableIRQ(USART2_IRQn); } } //#if 1 //#pragma import(__use_no_semihosting) ////标准库需要的支持函数 //struct __FILE //{ // int handle; //}; //FILE __stdout; ////定义_sys_exit()以避免使用半主机模式 //void _sys_exit(int x) //{ // x = x; //} // ////重定义fputc函数 //int fputc(int ch, FILE *f) //{ // while((USART1->ISR&0X40)==0);//循环发送,直到发送完毕 // USART1->TDR = (uint8_t) ch; // return ch; //} //#endif void USART1_IRQHandler(void) //串口1中断服务程序 { uint8_t Res; HAL_UART_IRQHandler(&huart1); if(__HAL_UART_GET_IT(&huart1, UART_IT_RXNE) != RESET) // { USART1->RQR |= 0x08;//?? RXNE Res =USART1->RDR;//USARTx_RX_Data(&UartHandle); if((USART_RX_STA&0x8000)==0)// { if(USART_RX_STA&0x4000)// { if(Res!=0x0a)USART_RX_STA=0;// else USART_RX_STA|=0x8000; // } else //?????0X0D { if(Res==0x0d)USART_RX_STA|=0x4000; else { USART_RX_BUF[USART_RX_STA&0X3FFF]=Res ; USART_RX_STA++; if(USART_RX_STA>(USART_REC_LEN-1))USART_RX_STA=0;// } } } } HAL_NVIC_ClearPendingIRQ(USART1_IRQn); } /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
2.484375
2
2024-11-18T22:23:45.557243+00:00
2017-05-05T02:27:46
00630d6bc76cb31386a8dc0674dbcafbfef711c9
{ "blob_id": "00630d6bc76cb31386a8dc0674dbcafbfef711c9", "branch_name": "refs/heads/master", "committer_date": "2017-05-05T02:27:46", "content_id": "872be6e0e519655ed0d00b13ac1544c328b23852", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "f4f1a909aeb89e13ec61794e4341dacb85c6fb94", "extension": "h", "filename": "menu.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 90329030, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1371, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/menu.h", "provenance": "stackv2-0115.json.gz:71116", "repo_name": "HaHaSDP-UCSC/haha-on-sockets", "revision_date": "2017-05-05T02:27:46", "revision_id": "febe88fa10c45641c44e469eae38fbf0cadde9e7", "snapshot_id": "74837612fff1bc5079f4fecc9cb196739b185f20", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/HaHaSDP-UCSC/haha-on-sockets/febe88fa10c45641c44e469eae38fbf0cadde9e7/src/menu.h", "visit_date": "2021-01-20T10:10:09.772882" }
stackv2
/** * @file menu.c * @brief Menu and MenuItems library defines * @author August Valera (avalera) * @version * @date 2017-02-28 */ // TODO: Implement menus with stack memory instead of malloc() #ifndef _HA_MENU_ #define _HA_MENU_ #include "halib.h" #include "lcd.h" #define MENU_MAXLEN 32 #define MENU_WRAP true typedef struct MenuItem MenuItem; typedef struct MenuItem { void (*onView)(); void (*onClick)(); char value[MENU_MAXLEN]; bool active; MenuItem* parent; MenuItem* child; MenuItem* prev; MenuItem* next; } MenuItem; typedef struct Menu { MenuItem* root; MenuItem* current; } Menu; typedef enum MenuDirection { MENU_UNDEF = 0, MENU_UP, MENU_DOWN, MENU_LEFT, MENU_RIGHT } MenuDirection; Menu* menuInit(void); int menuMove(Menu* menu, MenuDirection direct); int menuSetLcd(Menu* menu); int menuDestroy(Menu* this); MenuItem* menuItemInit(MenuItem* parent, char* value); int menuItemSetValue(MenuItem* this, char* value); void menuItemPrintTree(MenuItem* this); void menuItemPrintTreeHelper(MenuItem* this, int level); MenuItem* menuItemGetNext(MenuItem* this); MenuItem* menuItemGetPrev(MenuItem* this); MenuItem* menuItemGetLast(MenuItem* this); int menuItemDestroy(MenuItem* this); void* menuItemOnViewDefault(Menu* menu); void* menuItemOnClickDefault(Menu* menu); #endif // _HA_MENU_
2.015625
2
2024-11-18T22:23:46.696741+00:00
2016-09-23T21:49:33
086c8b9165f79f633559cb0adac980e897bf8d6e
{ "blob_id": "086c8b9165f79f633559cb0adac980e897bf8d6e", "branch_name": "refs/heads/master", "committer_date": "2016-09-23T21:49:33", "content_id": "405ef5d17d917e48ac01c97e359e7bf3c1fe430a", "detected_licenses": [ "Unlicense" ], "directory_id": "8dc4fda86cd76862a5cef736dc67cb60a2def90d", "extension": "c", "filename": "repatch.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": 7992, "license": "Unlicense", "license_type": "permissive", "path": "/thcrap/src/repatch.c", "provenance": "stackv2-0115.json.gz:71504", "repo_name": "SinSiXX/thcrap", "revision_date": "2016-09-23T21:49:33", "revision_id": "9e70b329eea360dfcfc0abeda192a00a8434bfaa", "snapshot_id": "8cf85e007a9f99dd66c9d5129521902e17486abd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/SinSiXX/thcrap/9e70b329eea360dfcfc0abeda192a00a8434bfaa/thcrap/src/repatch.c", "visit_date": "2021-01-11T06:54:51.672892" }
stackv2
/** * Touhou Community Reliant Automatic Patcher * Main DLL * * ---- * * Hot-repatching. */ #include "thcrap.h" #include "repatch.h" /** * This module monitors all patches for external changes to their files, then * calls all "repatch" module functions if there have been any. * * Windows provides various ways to achieve this (see * http://qualapps.blogspot.com/2010/05/understanding-readdirectorychangesw.html). * Since we want to limit repatching to the files that actually did change, * change notifications are not an option. We also can't rely on a window * handle, which rules out SHChangeNotifyRegister(). NTFS Change Journals seem * to be tied to that specific file system, which alone makes this solution a * rather bad idea before even trying it. * This only leaves ReadDirectoryChangesW(). We use this function with the * I/O completion port strategy to monitor all patch directories using one * single port handle. * * However, that function still has one glaring design flaw: It forces us to * use a fixed-size buffer for what should essentially be a variable-size * queue. As a result, it is perfectly possible to lose file changes between * two calls if the change buffer was too small to hold everything that * happened during two calls to the function. * * Well, this means that we have to write some code around that function to * actually use it properly. This implementation uses two separate threads to * achieve what seems to be a pretty decent performance. * * • The "watcher" thread focuses exclusively on monitoring the changes by * repeatedly calling ReadDirectoryChangesW() for all patch directories and * buffering relevant changes in a performant way. * This is *very* important, as we must spend as little time as possible on * one filled buffer. * * • The separate "collector" thread waits for a fixed amount of time, then * calls mod_func_run("repatch"), passing the current repatch buffer before * flushing it. */ static HANDLE *dir_handles = NULL; static int dir_handles_num = 0; // Repatch buffer. // A JSON object that receives the names of all changed files as the changes // are detected. static json_t *files_changed = NULL; static CRITICAL_SECTION cs_changed = {0}; static HANDLE event_shutdown = NULL; static HANDLE thread_watch = NULL; static HANDLE thread_collect = NULL; static volatile size_t changes_total = 0; // Amount of milliseconds to wait before triggering the collector thread #define COLLECT_THRESHOLD 1000 // 64K is more than 8 times as much as my system would crank out in a single // watch loop while being bombarded with a cmd file creation FOR loop using // names being close to MAX_PATH in length - so I guess it 'ought to be enough // for anybody'™? #define WATCH_BUFFER_SIZE 65536 void repatch_add(OVERLAPPED *ol) { FILE_NOTIFY_INFORMATION *p = (FILE_NOTIFY_INFORMATION*)ol->Pointer; DWORD next_offset; do { size_t fn_utf16_len = (p->FileNameLength / 2); size_t fn_utf8_len = fn_utf16_len * UTF8_MUL; VLA(char, fn_utf8, fn_utf8_len); next_offset = p->NextEntryOffset; fn_utf8_len = WideCharToMultiByte( CP_UTF8, 0, p->FileName, fn_utf16_len, fn_utf8, fn_utf8_len, NULL, NULL ); fn_utf8[fn_utf8_len] = 0; str_slash_normalize(fn_utf8); EnterCriticalSection(&cs_changed); // Marginally faster, and ensures correct counting of changes. if(!json_object_get(files_changed, fn_utf8)) { json_object_set_new(files_changed, fn_utf8, json_integer((json_int_t)ol->hEvent)); InterlockedIncrement(&changes_total); } LeaveCriticalSection(&cs_changed); VLA_FREE(fn_utf8); if(next_offset) { p = (FILE_NOTIFY_INFORMATION*)((BYTE*)p + next_offset); } } while(next_offset); } DWORD WINAPI repatch_collector(void *param) { while(WaitForSingleObject(event_shutdown, COLLECT_THRESHOLD) == WAIT_TIMEOUT) { if(json_object_size(files_changed) > 0) { json_t *files_changed_copy = NULL; log_printf("Repatching...\n"); EnterCriticalSection(&cs_changed); files_changed_copy = json_copy(files_changed); json_object_clear(files_changed); LeaveCriticalSection(&cs_changed); mod_func_run_all("repatch", files_changed_copy); json_decref(files_changed_copy); } } return 0; } DWORD WINAPI repatch_watcher(void *param) { DWORD ret_changes = TRUE; DWORD ret_queue = FALSE; DWORD ret_shutdown = WAIT_TIMEOUT; BYTE buf[WATCH_BUFFER_SIZE]; int i; DWORD byte_ret_max = 0; OVERLAPPED ol_changes = {0}; HANDLE hIOCompPort = CreateIoCompletionPort( INVALID_HANDLE_VALUE, NULL, PROJECT_VERSION(), 0 ); for(i = 0; i < dir_handles_num; i++) { if(dir_handles[i] != INVALID_HANDLE_VALUE) { CreateIoCompletionPort(dir_handles[i], hIOCompPort, i, 0); } } while(!ret_queue && ret_shutdown == WAIT_TIMEOUT) { DWORD byte_ret = 0; DWORD key; OVERLAPPED *ol = NULL; // IMPORTANT. If we don't use a completion routine and this is not NULL, // ReadDirectoryChangesW() will think that we want to use the // GetOverlappedResult() notification strategy, which requires a valid // event handle. Since the ID we put in there is something else entirely, // the function *will fail* with ERROR_INVALID_HANDLE. ol_changes.hEvent = NULL; ol_changes.Pointer = buf; ret_queue = W32_ERR_WRAP(GetQueuedCompletionStatus( hIOCompPort, &byte_ret, &key, &ol, COLLECT_THRESHOLD )); for(i = 0; i < dir_handles_num; i++) { ret_changes = W32_ERR_WRAP(ReadDirectoryChangesW( dir_handles[i], ol_changes.Pointer, sizeof(buf), TRUE, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE, &byte_ret, &ol_changes, NULL )); if(byte_ret) { byte_ret_max = max(byte_ret_max, byte_ret); } if(!ret_queue && ol) { ol->hEvent = (HANDLE)key; repatch_add(ol); } else if(ret_queue == WAIT_TIMEOUT) { ret_queue = 0; } } ret_shutdown = WaitForSingleObject(event_shutdown, 0); } log_printf( "Shutting down repatch watcher thread.\n" "Statistics:\n" "----\n" "• Last error codes: %d (queue), %d (changes)\n" "• Total number of file changes parsed: %d\n" "• Maximum buffer fill state: %d/%d bytes\n" "----\n", ret_queue, ret_changes, changes_total, byte_ret_max, WATCH_BUFFER_SIZE ); CloseHandle(hIOCompPort); return 0; } int repatch_mod_init(void) { DWORD thread_id; const json_t *patches = json_object_get(runconfig_get(), "patches"); size_t i; json_t *patch_info; size_t patches_num = json_array_size(patches); if(!patches_num) { return 1; } dir_handles = calloc(sizeof(HANDLE), patches_num); if(!dir_handles) { return 2; } json_array_foreach(patches, i, patch_info) { const char *archive = json_object_get_string(patch_info, "archive"); HANDLE hDir = INVALID_HANDLE_VALUE; if(GetFileAttributes(archive) & FILE_ATTRIBUTE_DIRECTORY) { hDir = CreateFile(archive, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE // Yes. This would otherwise prevent *files* in the // directory from being deleted or renamed, too. | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL ); } dir_handles[dir_handles_num++] = hDir; } InitializeCriticalSection(&cs_changed); files_changed = json_object(); event_shutdown = CreateEvent(NULL, TRUE, FALSE, NULL); thread_watch = CreateThread(NULL, 0, repatch_watcher, NULL, 0, &thread_id); thread_collect = CreateThread(NULL, 0, repatch_collector, NULL, 0, &thread_id); return 0; } void repatch_mod_exit(void) { SetEvent(event_shutdown); WaitForSingleObject(thread_watch, INFINITE); WaitForSingleObject(thread_collect, INFINITE); CloseHandle(thread_watch); CloseHandle(thread_collect); thread_watch = NULL; CloseHandle(event_shutdown); SAFE_FREE(dir_handles); event_shutdown = NULL; dir_handles_num = 0; files_changed = json_decref_safe(files_changed); DeleteCriticalSection(&cs_changed); }
2
2
2024-11-18T22:23:47.139861+00:00
2019-11-03T12:28:44
42a98c167c5ea49842aec9b884ecca738fa36cca
{ "blob_id": "42a98c167c5ea49842aec9b884ecca738fa36cca", "branch_name": "refs/heads/master", "committer_date": "2019-11-03T12:28:44", "content_id": "91ce05f14246331619b796fc501a69949b8e1c66", "detected_licenses": [ "MIT" ], "directory_id": "72901bd8391d8f6fd1a7f8c34075e7f42eafff16", "extension": "h", "filename": "cpu.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 32609744, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1476, "license": "MIT", "license_type": "permissive", "path": "/include/cpu.h", "provenance": "stackv2-0115.json.gz:72151", "repo_name": "jansky/JanskyProcessor", "revision_date": "2019-11-03T12:28:44", "revision_id": "ad311974c11459c8e28e294a9e570b7b5ad77276", "snapshot_id": "70cb056e91a83d76b3dedbf60dde3a3ed74ad781", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/jansky/JanskyProcessor/ad311974c11459c8e28e294a9e570b7b5ad77276/include/cpu.h", "visit_date": "2021-01-23T15:08:47.178892" }
stackv2
#pragma once #include <stdbool.h> #include "types.h" #include "memory.h" #include "interop.h" typedef struct CPU { bool halted; //Registers DWORD ar1; DWORD ar2; DWORD ar3; DWORD ar4; DWORD ar5; DWORD ip; DWORD bp; DWORD sp; DWORD sb; float fr1; float fr2; float fr3; float fr4; float fr5; DWORD nr1; DWORD nr2; DWORD nr3; DWORD nr4; DWORD nr5; DWORD nr6; DWORD nr7; DWORD or1; DWORD cr1; DWORD pr1; DWORD pr2; float fpr1; float fpr2; DWORD flr1; INTEROP_INFO *iinfo; } CPU; typedef struct CPURESULT { int error; uint32_t address; BYTE instruction; } CPURESULT; CPU *cpu_init(void); CPURESULT *cpu_result_create(int error, uint32_t address, BYTE instruction); CPURESULT *cpu_exec_instruction(CPU *cpu, RAMUNIT *ram, bool oninterrupt); DWORD get_value_from_register(CPU *cpu, DWORD regid); bool put_value_in_register(CPU *cpu, DWORD regid, DWORD value); DWORD get_value(CPU *cpu, RAMUNIT *ram, BYTE loc_id, DWORD location); bool put_value(CPU *cpu, RAMUNIT *ram, BYTE loc_id, DWORD location, DWORD value); void print_end_dump(CPU *cpu, CPURESULT *result, RAMUNIT *ram); bool stack_push(CPU *cpu, RAMUNIT *ram, DWORD value); DWORD stack_pop(CPU *cpu, RAMUNIT *ram); bool do_cpu_interrupt(CPU *cpu, RAMUNIT *ram, BYTE id); #define CPURESULT_SUCCESS 0x00 #define CPURESULT_ILLEGALACCESS 0x01 #define CPURESULT_INSTRUCTIONNOEXIST 0x02 #define CPURESULT_STACKFLOWERROR 0x03 #define CPURESULT_BIOSERROR 0x04
2.078125
2
2024-11-18T22:23:47.387970+00:00
2023-03-28T18:38:38
7e01ca8db44e56e3858cf0869a205b255f5dff67
{ "blob_id": "7e01ca8db44e56e3858cf0869a205b255f5dff67", "branch_name": "refs/heads/master", "committer_date": "2023-03-28T18:38:38", "content_id": "99e6e5d22ac04479cf4a45c4fbf77bb4496477b6", "detected_licenses": [ "MIT" ], "directory_id": "4d54680efc2f8eb89031096378f46f965ec4753f", "extension": "c", "filename": "src_hops.c", "fork_events_count": 227, "gha_created_at": "2017-07-03T18:57:58", "gha_event_created_at": "2023-05-23T20:51:55", "gha_language": "C", "gha_license_id": "MIT", "github_id": 96141583, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 15765, "license": "MIT", "license_type": "permissive", "path": "/src/source/src_hops.c", "provenance": "stackv2-0115.json.gz:72408", "repo_name": "introlab/odas", "revision_date": "2023-03-28T18:38:38", "revision_id": "a07e6276a91c46f14b57b66ef2f28360e50af02d", "snapshot_id": "ae7ef5097e4773875ecd467800622b6ddfbca690", "src_encoding": "UTF-8", "star_events_count": 666, "url": "https://raw.githubusercontent.com/introlab/odas/a07e6276a91c46f14b57b66ef2f28360e50af02d/src/source/src_hops.c", "visit_date": "2023-05-28T10:22:43.365407" }
stackv2
/** * \file src_hops.c * \author François Grondin <francois.grondin2@usherbrooke.ca> * \version 2.0 * \date 2018-03-18 * \copyright * * 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 <source/src_hops.h> src_hops_obj * src_hops_construct(const src_hops_cfg * src_hops_config, const msg_hops_cfg * msg_hops_config) { src_hops_obj * obj; unsigned int nBytes; obj = (src_hops_obj *) malloc(sizeof(src_hops_obj)); obj->timeStamp = 0; obj->hopSize = msg_hops_config->hopSize; obj->nChannels = msg_hops_config->nChannels; obj->fS = msg_hops_config->fS; obj->format = format_clone(src_hops_config->format); obj->interface = interface_clone(src_hops_config->interface); if (src_hops_config->channel_map != NULL) { // Will not be null if in pulseaudio mode memcpy(&obj->cm, src_hops_config->channel_map, sizeof(pa_channel_map)); } else if (obj->interface->type == interface_pulseaudio) { // Can't be null if we are in pulseaudio mode printf("Error: Pulseaudio interface requires channel map.\n"); exit(EXIT_FAILURE); } memset(obj->bytes, 0x00, 4 * sizeof(char)); if (!((obj->interface->type == interface_file || obj->interface->type == interface_soundcard || obj->interface->type == interface_pulseaudio || obj->interface->type == interface_socket) && (obj->format->type == format_binary_int08 || obj->format->type == format_binary_int16 || obj->format->type == format_binary_int24 || obj->format->type == format_binary_int32))) { printf("Source hops: Invalid interface and/or format.\n"); exit(EXIT_FAILURE); } obj->buffer = (char *) malloc(sizeof(char) * obj->hopSize * obj->nChannels * 4); memset(obj->buffer, 0x00, sizeof(char) * obj->hopSize * obj->nChannels * 4); switch (obj->format->type) { case format_binary_int08: obj->bufferSize = obj->hopSize * obj->nChannels * 1; break; case format_binary_int16: obj->bufferSize = obj->hopSize * obj->nChannels * 2; break; case format_binary_int24: obj->bufferSize = obj->hopSize * obj->nChannels * 3; break; case format_binary_int32: obj->bufferSize = obj->hopSize * obj->nChannels * 4; break; } obj->out = (msg_hops_obj *) NULL; return obj; } void src_hops_destroy(src_hops_obj * obj) { free((void *) obj->buffer); format_destroy(obj->format); interface_destroy(obj->interface); free((void *) obj); } void src_hops_connect(src_hops_obj * obj, msg_hops_obj * out) { obj->out = out; } void src_hops_disconnect(src_hops_obj * obj) { obj->out = (msg_hops_obj *) NULL; } void src_hops_open(src_hops_obj * obj) { switch (obj->interface->type) { case interface_file: src_hops_open_interface_file(obj); break; case interface_soundcard: src_hops_open_interface_soundcard(obj); break; case interface_pulseaudio: src_hops_open_interface_pulseaudio(obj); break; case interface_socket: src_hops_open_interface_socket(obj); break; default: printf("Source hops: Invalid interface type.\n"); exit(EXIT_FAILURE); break; } } void src_hops_open_interface_file(src_hops_obj * obj) { obj->fp = fopen(obj->interface->fileName, "rb"); if (obj->fp == NULL) { printf("Cannot open file %s\n", obj->interface->fileName); exit(EXIT_FAILURE); } } void src_hops_open_interface_soundcard(src_hops_obj * obj) { snd_pcm_hw_params_t * hw_params; snd_pcm_format_t format; int err; switch (obj->format->type) { case format_binary_int08: format = SND_PCM_FORMAT_S8; break; case format_binary_int16: format = SND_PCM_FORMAT_S16_LE; break; case format_binary_int24: format = SND_PCM_FORMAT_S24_LE; break; case format_binary_int32: format = SND_PCM_FORMAT_S32_LE; break; default: printf("Source hops: Invalid format.\n"); exit(EXIT_FAILURE); break; } if ((err = snd_pcm_open(&(obj->ch), obj->interface->deviceName, SND_PCM_STREAM_CAPTURE, 0)) < 0) { printf("Source hops: Cannot open audio device %s: %s\n", obj->interface->deviceName, snd_strerror(err)); exit(EXIT_FAILURE); } if ((err = snd_pcm_hw_params_malloc(&hw_params)) < 0) { printf("Source hops: Cannot allocate hardware parameter structure: %s\n", snd_strerror(err)); exit(EXIT_FAILURE); } if ((err = snd_pcm_hw_params_any(obj->ch, hw_params)) < 0) { printf("Source hops: Cannot initialize hardware parameter structure: %s\n", snd_strerror(err)); exit(EXIT_FAILURE); } if ((err = snd_pcm_hw_params_set_access(obj->ch, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) { printf("Source hops: Cannot set access type: %s\n", snd_strerror(err)); exit(EXIT_FAILURE); } if ((err = snd_pcm_hw_params_set_format(obj->ch, hw_params, format)) < 0) { printf("Source hops: Cannot set sample format: %s\n", snd_strerror(err)); exit(EXIT_FAILURE); } if ((err = snd_pcm_hw_params_set_rate(obj->ch, hw_params, obj->fS, 0)) < 0) { printf("Source hops: Cannot set sample rate: %s\n", snd_strerror(err)); exit(EXIT_FAILURE); } if ((err = snd_pcm_hw_params_set_channels(obj->ch, hw_params, obj->nChannels)) < 0) { printf("Source hops: Cannot set channel count: %s\n", snd_strerror(err)); exit(EXIT_FAILURE); } if ((err = snd_pcm_hw_params(obj->ch, hw_params)) < 0) { printf("Source hops: Cannot set parameters: %s\n", snd_strerror(err)); exit(EXIT_FAILURE); } snd_pcm_hw_params_free(hw_params); if ((err = snd_pcm_prepare(obj->ch)) < 0) { printf("Source hops: Cannot prepare audio interface for use: %s\n", snd_strerror(err)); exit(EXIT_FAILURE); } } void src_hops_open_interface_pulseaudio(src_hops_obj * obj) { pa_sample_format_t format; switch (obj->format->type) { case format_binary_int08: format = PA_SAMPLE_U8; break; case format_binary_int16: format = PA_SAMPLE_S16LE; break; case format_binary_int24: format = PA_SAMPLE_S24LE; break; case format_binary_int32: format = PA_SAMPLE_S32LE; break; default: printf("Source hops: Invalid format.\n"); exit(EXIT_FAILURE); break; } obj->ss.format = format; obj->ss.rate = obj->fS; obj->ss.channels = obj->nChannels; int err; if (!(obj->pa = pa_simple_new(NULL, "Odas", PA_STREAM_RECORD, obj->interface->deviceName, "record", &obj->ss, &obj->cm, NULL, &err))) { printf("Source hops: Cannot open pulseaudio device %s: %s\n", obj->interface->deviceName, pa_strerror(err)); exit(EXIT_FAILURE); } } void src_hops_open_interface_socket(src_hops_obj * obj) { memset(&(obj->sserver), 0x00, sizeof(struct sockaddr_in)); obj->sserver.sin_family = AF_INET; obj->sserver.sin_addr.s_addr = inet_addr(obj->interface->ip); obj->sserver.sin_port = htons(obj->interface->port); obj->sid = socket(AF_INET, SOCK_STREAM, 0); if ((connect(obj->sid, (struct sockaddr *) &(obj->sserver), sizeof(obj->sserver))) < 0) { printf("Source hops: Cannot connect to server\n"); exit(EXIT_FAILURE); } } void src_hops_close(src_hops_obj * obj) { switch (obj->interface->type) { case interface_file: src_hops_close_interface_file(obj); break; case interface_soundcard: src_hops_close_interface_soundcard(obj); break; case interface_pulseaudio: src_hops_close_interface_pulseaudio(obj); break; case interface_socket: src_hops_close_interface_socket(obj); break; default: printf("Source hops: Invalid interface type.\n"); exit(EXIT_FAILURE); break; } } void src_hops_close_interface_file(src_hops_obj * obj) { fclose(obj->fp); } void src_hops_close_interface_soundcard(src_hops_obj * obj) { snd_pcm_close(obj->ch); } void src_hops_close_interface_pulseaudio(src_hops_obj * obj) { if (obj->pa != NULL) pa_simple_free(obj->pa); } void src_hops_close_interface_socket(src_hops_obj * obj) { close(obj->sid); } int src_hops_process(src_hops_obj * obj) { int rtnValue; switch (obj->format->type) { case format_binary_int08: src_hops_process_format_binary_int08(obj); break; case format_binary_int16: src_hops_process_format_binary_int16(obj); break; case format_binary_int24: src_hops_process_format_binary_int24(obj); break; case format_binary_int32: src_hops_process_format_binary_int32(obj); break; default: printf("Source hops: Invalid format type.\n"); exit(EXIT_FAILURE); break; } switch (obj->interface->type) { case interface_file: rtnValue = src_hops_process_interface_file(obj); break; case interface_soundcard: rtnValue = src_hops_process_interface_soundcard(obj); break; case interface_pulseaudio: rtnValue = src_hops_process_interface_pulseaudio(obj); break; case interface_socket: rtnValue = src_hops_process_interface_socket(obj); break; default: printf("Source hops: Invalid interface type.\n"); exit(EXIT_FAILURE); break; } obj->timeStamp++; obj->out->timeStamp = obj->timeStamp; return rtnValue; } int src_hops_process_interface_file(src_hops_obj * obj) { unsigned int nBytesTotal; int rtnValue; nBytesTotal = fread(obj->buffer, sizeof(char), obj->bufferSize, obj->fp); if (nBytesTotal == obj->bufferSize) { rtnValue = 0; } else { rtnValue = -1; } return rtnValue; } int src_hops_process_interface_soundcard(src_hops_obj * obj) { unsigned int nSamples; int rtnValue; int err; if (err = snd_pcm_readi(obj->ch, obj->buffer, obj->hopSize) > 0) { rtnValue = 0; } else { rtnValue = -1; } return rtnValue; } int src_hops_process_interface_pulseaudio(src_hops_obj * obj) { int rtnValue; int err; if (pa_simple_read(obj->pa, obj->buffer, obj->bufferSize, &err) < 0) { rtnValue = -1; } else { rtnValue = 0; } return rtnValue; } int src_hops_process_interface_socket(src_hops_obj * obj) { unsigned int nBytesTotal; int rtnValue; // ssize_t recv(int sockfd, void *buf, size_t len, int flags); nBytesTotal = recv(obj->sid, obj->buffer, obj->bufferSize, MSG_WAITALL); if (nBytesTotal == obj->bufferSize) { rtnValue = 0; } else { rtnValue = -1; } return rtnValue; } void src_hops_process_format_binary_int08(src_hops_obj * obj) { unsigned int iSample; unsigned int iChannel; unsigned int nBytes; float sample; nBytes = 1; for (iSample = 0; iSample < obj->hopSize; iSample++) { for (iChannel = 0; iChannel < obj->nChannels; iChannel++) { memcpy(&(obj->bytes[4 - nBytes]), &(obj->buffer[(iSample * obj->nChannels + iChannel) * nBytes]), sizeof(char) * nBytes); sample = pcm_signedXXbits2normalized(obj->bytes, nBytes); obj->out->hops->array[iChannel][iSample] = sample; } } } void src_hops_process_format_binary_int16(src_hops_obj * obj) { unsigned int iSample; unsigned int iChannel; unsigned int nBytes; float sample; nBytes = 2; for (iSample = 0; iSample < obj->hopSize; iSample++) { for (iChannel = 0; iChannel < obj->nChannels; iChannel++) { memcpy(&(obj->bytes[4 - nBytes]), &(obj->buffer[(iSample * obj->nChannels + iChannel) * nBytes]), sizeof(char) * nBytes); sample = pcm_signedXXbits2normalized(obj->bytes, nBytes); obj->out->hops->array[iChannel][iSample] = sample; } } } void src_hops_process_format_binary_int24(src_hops_obj * obj) { unsigned int iSample; unsigned int iChannel; unsigned int nBytes; float sample; nBytes = 3; for (iSample = 0; iSample < obj->hopSize; iSample++) { for (iChannel = 0; iChannel < obj->nChannels; iChannel++) { memcpy(&(obj->bytes[4 - nBytes]), &(obj->buffer[(iSample * obj->nChannels + iChannel) * nBytes]), sizeof(char) * nBytes); sample = pcm_signedXXbits2normalized(obj->bytes, nBytes); obj->out->hops->array[iChannel][iSample] = sample; } } } void src_hops_process_format_binary_int32(src_hops_obj * obj) { unsigned int iSample; unsigned int iChannel; unsigned int nBytes; float sample; nBytes = 4; for (iSample = 0; iSample < obj->hopSize; iSample++) { for (iChannel = 0; iChannel < obj->nChannels; iChannel++) { memcpy(&(obj->bytes[4 - nBytes]), &(obj->buffer[(iSample * obj->nChannels + iChannel) * nBytes]), sizeof(char) * nBytes); sample = pcm_signedXXbits2normalized(obj->bytes, nBytes); obj->out->hops->array[iChannel][iSample] = sample; } } } src_hops_cfg * src_hops_cfg_construct(void) { src_hops_cfg * cfg; cfg = (src_hops_cfg *) malloc(sizeof(src_hops_cfg)); cfg->format = (format_obj *) NULL; cfg->interface = (interface_obj *) NULL; return cfg; } void src_hops_cfg_destroy(src_hops_cfg * src_hops_config) { if (src_hops_config->format != NULL) { format_destroy(src_hops_config->format); } if (src_hops_config->interface != NULL) { interface_destroy(src_hops_config->interface); } if (src_hops_config->channel_map != NULL) { free((void *) src_hops_config->channel_map); } free((void *) src_hops_config); }
2.109375
2
2024-11-18T22:23:47.629797+00:00
2016-11-03T15:27:18
cb158e4ddf0ce4e81efa26d1352aae821df9b31f
{ "blob_id": "cb158e4ddf0ce4e81efa26d1352aae821df9b31f", "branch_name": "refs/heads/master", "committer_date": "2016-11-03T15:27:18", "content_id": "647c83c592d20a2a3860c18574fcc1abedff58a8", "detected_licenses": [ "MIT" ], "directory_id": "4bad17ae6d01fccbbb20c1f6eb327070138f8cf4", "extension": "c", "filename": "file_practice.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": 3666, "license": "MIT", "license_type": "permissive", "path": "/File/file_practice.c", "provenance": "stackv2-0115.json.gz:72794", "repo_name": "Becavalier/playground-linux", "revision_date": "2016-11-03T15:27:18", "revision_id": "b6d391f9b3f546bfc9e6f9404774765fc6b52937", "snapshot_id": "739bb965864f9f2a7888dbe763d87b8dde0c14be", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Becavalier/playground-linux/b6d391f9b3f546bfc9e6f9404774765fc6b52937/File/file_practice.c", "visit_date": "2021-06-08T13:07:17.860692" }
stackv2
/** * 文件系统调用(由 Linux/Unix 直接提供)方法: * * open / read / write / close / ioctl * lseek / fstat / stat / lstat / dup / dup2 * * 1、执行系统调用时,Linux 必须从用户态切换到内核态; * 2、硬件会限制对底层系统调用一次所能读写的数据块大小; * * 三种文件描述符:0 / 1 / 2 * 对应标准库中的:stdin / stdout / stderr * * 标准I/O库方法: * * fopen / fread / fwrite / fclose * fflush / fseek * fgetc / getc / getchar * fputs / puts / putchar * fgets / gets * printf / fprintf / sprintf * scanf / fsacnf / ssanf * * 调试 Segmentation fault (core dumped): * 设置 core 文件最大块大小: ulimit -c 512 * 进入 gdb 进行调试: gdb 【运行程序名】 core * 使用 bt 命令进行调试: bt */ #include <unistd.h> #include <fcntl.h> #include <stdio.h> #include <strings.h> #include <sys/types.h> #include <sys/stat.h> #define yearsecs (60 * 60 * 24 * 365) int main(int argc, char *argv[]) { char* args; if(argc == 2) { args = argv[1]; } if(strcasecmp(args, "system") == 0) { int file_in, file_out, read_len; // Just a buffer char buf[1024]; struct stat statbuf; mode_t modes; if ((file_in = open("file.in", O_RDONLY)) != -1) { fstat(file_in, &statbuf); // Print the info of file "file.in" // fdisk -l => sda1 => 8/1 printf("st_dev: %d\\%d\n", major(statbuf.st_dev), minor(statbuf.st_dev)); printf("st_gid: %d\n", statbuf.st_gid); printf("st_uid: %d\n", statbuf.st_uid); printf("st_atime: %ld\n", (long) (statbuf.st_atime / yearsecs) + 1970); printf("st_ctime: %ld\n", (long) (statbuf.st_ctime / yearsecs) + 1970); if(S_ISREG(statbuf.st_mode)) { printf("%s\n", "This is a normal file."); } if(S_ISCHR(statbuf.st_mode) || S_ISBLK(statbuf.st_mode)) { printf(" (%s) rdev = %d/%d", (S_ISCHR(statbuf.st_mode)) ? "character" : "block", major(statbuf.st_rdev), minor(statbuf.st_rdev)); } // Create a new file "file.out" file_out = open("file.out", O_WRONLY|O_APPEND|O_CREAT|O_EXCL, S_IWUSR); if(file_out == -1) { printf("%s\n", "Error occurred when creating file 'file.out', trying to remove it."); // } while((read_len = read(file_in, buf, sizeof(buf))) > 0) { write(file_out, buf, read_len); } } if(close(file_in) == -1 || close(file_out) == -1) { printf("%s\n", "Error occurred when closing file."); } } if(strcasecmp(args, "stdio") == 0) { FILE *file_in, *file_out; char buf[1024], char_buf; // Create a new file "file.out" /* 使用r+选项,将r选择项的功能扩充为即允许读也允许写文件。(该文件必须存在) 使用w+选项建立一个可读可写的新文件。(若文件不存在则建立文件) 使用a+可以从文件的当前位置开始往文件中添加内容,而用可同时读写文件。(若文件不存在则建立文件,若存在则将数据添加到文件尾)。 */ file_out = fopen("file.out", "a+"); if((file_in = fopen("file.in", "r")) != NULL) { while(!feof(file_in)) { int count = fread(buf, sizeof(buf), 1, file_in); if(count > 0) { fwrite(buf, sizeof(buf), count, file_out); } // fflush(file_out); } // Detect the rest fseek(file_out, 0, SEEK_END); fseek(file_in, ftell(file_out), SEEK_SET); while(!feof(file_in)) { int count = fread(&char_buf, sizeof(char_buf), 1, file_in); if(count > 0) { fwrite(&char_buf, sizeof(char_buf), count, file_out); } } fclose(file_in); fclose(file_out); } } }
2.78125
3
2024-11-18T22:23:47.761336+00:00
2020-09-07T21:28:52
86e6bf2a1e6f2d0854a8490d177ac5481027cb75
{ "blob_id": "86e6bf2a1e6f2d0854a8490d177ac5481027cb75", "branch_name": "refs/heads/master", "committer_date": "2020-09-07T21:28:52", "content_id": "0897e9347b84d34d4f999e599f80cac5cb2a8c02", "detected_licenses": [ "MIT" ], "directory_id": "a1dc793c7a5a21caa9747e21998ebdda05af7083", "extension": "h", "filename": "MapData.h", "fork_events_count": 0, "gha_created_at": "2020-09-05T16:25:02", "gha_event_created_at": "2020-09-07T21:28:53", "gha_language": "C", "gha_license_id": "MIT", "github_id": 293112485, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8147, "license": "MIT", "license_type": "permissive", "path": "/source/Map/MapData.h", "provenance": "stackv2-0115.json.gz:73051", "repo_name": "monyarm/phoenix_doom", "revision_date": "2020-09-07T21:28:52", "revision_id": "78c75f985803b94b981469ac32764169ed56aee4", "snapshot_id": "5748488b58361ab5642b251b5d798e64c7e7efbc", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/monyarm/phoenix_doom/78c75f985803b94b981469ac32764169ed56aee4/source/Map/MapData.h", "visit_date": "2022-12-14T03:48:31.754451" }
stackv2
#pragma once #include "Base/Angle.h" #include "Base/Macros.h" #include "Game/DoomDefines.h" struct line_t; struct mobj_t; // Point in a map (2d coords) struct vertex_t { Fixed x; Fixed y; }; // The same as 'vertex_t', except in floating point format struct vertexf_t { float x; float y; }; // Vector struct struct vector_t { Fixed x; // X,Y start of line Fixed y; Fixed dx; // Distance traveled (delta) Fixed dy; }; // Describe a playfield sector (Polygon) struct sector_t { NON_ASSIGNABLE_STRUCT(sector_t) Fixed floorheight; // Floor height Fixed ceilingheight; // Top and bottom height uint32_t FloorPic; // Floor texture # uint32_t CeilingPic; // If ceilingpic==-1, draw sky uint32_t lightlevel; // Light override uint32_t special; // Special event number uint32_t tag; // Event tag uint32_t soundtraversed; // 0 = untraversed, 1,2 = sndlines -1 mobj_t* soundtarget; // thing that made a sound (or null) uint32_t blockbox[BOXCOUNT]; // mapblock bounding box for height changes Fixed SoundX; // For any sounds played by the sector Fixed SoundY; // For any sounds played by the sector uint32_t validcount; // if == validcount, already checked mobj_t* thinglist; // list of mobjs in sector void* specialdata; // Thinker struct for reversable actions uint32_t linecount; // Number of lines in polygon line_t** lines; // [linecount] size }; // Data for a line side struct side_t { NON_ASSIGNABLE_STRUCT(side_t) float texXOffset; // Column texture offset (X) float texYOffset; // Row texture offset (Y) uint32_t toptexture; // Wall textures uint32_t bottomtexture; uint32_t midtexture; sector_t* sector; // Pointer to parent sector }; // Slope type for a line enum slopetype_e { ST_HORIZONTAL, ST_VERTICAL, ST_POSITIVE, ST_NEGATIVE }; // Data for a line struct line_t { NON_ASSIGNABLE_STRUCT(line_t) vertex_t v1; // X,Ys for the line ends vertex_t v2; vertexf_t v1f; // The same in float format vertexf_t v2f; uint32_t flags; // Bit flags (ML_) for states uint32_t special; // Event number uint32_t tag; // Event tag number side_t* SidePtr[2]; // Sidenum[1] will be NULL if one sided Fixed bbox[BOXCOUNT]; // Bounding box for quick clipping slopetype_e slopetype; // To aid move clipping sector_t* frontsector; // Front line side sector sector_t* backsector; // Back side sector (NULL if one sided) uint32_t fineangle; // Index to get sine / cosine for sliding // Intrusive/non-property fields uint32_t validCount; // Keeps track of whether the line has been visited during certain operations float v1DrawDepth; // Depth of v1 and v2 when drawn float v2DrawDepth; uint8_t drawnSideIndex; // Which side of the line is being rendered bool bIsInFrontOfSprite; // Used during sprite clipping: stores if the line is considered in front of the sprite }; // Flags that can be applied to a line static constexpr uint32_t ML_BLOCKING = 0x1; // Line blocks all movement static constexpr uint32_t ML_BLOCKMONSTERS = 0x2; // Line blocks monster movement static constexpr uint32_t ML_TWOSIDED = 0x4; // This line has two sides static constexpr uint32_t ML_DONTPEGTOP = 0x8; // Top texture is bottom anchored static constexpr uint32_t ML_DONTPEGBOTTOM = 0x10; // Bottom texture is bottom anchored static constexpr uint32_t ML_SECRET = 0x20; // Don't map as two sided: IT'S A SECRET! static constexpr uint32_t ML_SOUNDBLOCK = 0x40; // don't let sound cross two of these static constexpr uint32_t ML_DONTDRAW = 0x80; // don't draw on the automap static constexpr uint32_t ML_MAPPED = 0x100; // set if allready drawn in automap // Structure for a line segment struct seg_t { NON_ASSIGNABLE_STRUCT(seg_t) vertexf_t v1; // Source and dest points vertexf_t v2; angle_t angle; // Angle of the vector float texXOffset; // Extra texture offset in the x direction side_t* sidedef; // Pointer to the connected side line_t* linedef; // Pointer to the connected line sector_t* frontsector; // Sector on the front side sector_t* backsector; // NULL for one sided lines float lightMul; // Wall light multiplier (used for fake contrast) uint8_t getLineSideIndex() const noexcept { return (linedef->SidePtr[0] == sidedef) ? 0 : 1; } }; // Subsector structure struct subsector_t { NON_ASSIGNABLE_STRUCT(subsector_t) sector_t* sector; // Pointer to parent sector uint32_t numsublines; // Number of subsector lines seg_t* firstline; // Pointer to the first line }; // BSP partition line struct node_t { NON_ASSIGNABLE_STRUCT(node_t) vector_t Line; Fixed bbox[2][BOXCOUNT]; // Bounding box for each child void* Children[2]; // If low bit is set then it's a subsector }; //------------------------------------------------------------------------------------------------------------------------------------------ // DC: BSP nodes use the lowest bit of their child pointers to indicate whether or not the child // pointed to is a subsector or just another BSP node. These 3 functions help with checking for // the prescence of this flag and adding/removing it from a node child pointer. //------------------------------------------------------------------------------------------------------------------------------------------ inline bool isBspNodeASubSector(const void* const pPtr) { return ((((uintptr_t) pPtr) & 1) != 0); } inline void* markBspNodeAsSubSector(void* const pPtr) { // Set the lowest bit to mark the node's child pointer as a subsector return (void*)(((uintptr_t) pPtr) | 1); } inline void* getActualBspNodePtr(void* const pPtr) { // Remove the lowest bit to get the actual child pointer for a node. // May be set in order to indicate that the child is a subsector: const uintptr_t mask = ~((uintptr_t) 1); return (void*)(((uintptr_t) pPtr) & mask); } // Pointers to global map data for ease of access extern const vertex_t* gpVertexes; extern uint32_t gNumVertexes; extern sector_t* gpSectors; extern uint32_t gNumSectors; extern side_t* gpSides; extern uint32_t gNumSides; extern line_t* gpLines; extern uint32_t gNumLines; extern const seg_t* gpLineSegs; extern uint32_t gNumLineSegs; extern const subsector_t* gpSubSectors; extern uint32_t gNumSubSectors; extern node_t* gpBSPTreeRoot; extern const uint8_t* gpRejectMatrix; // For fast sight rejection extern line_t*** gpBlockMapLineLists; // For each blockmap entry, a pointer to a list of line pointers (all lines in the block) extern mobj_t** gpBlockMapThingLists; // For each blockmap entry, a pointer to the first thing in a linked list of things (all things in the block) extern uint32_t gBlockMapWidth; extern uint32_t gBlockMapHeight; extern Fixed gBlockMapOriginX; extern Fixed gBlockMapOriginY; // Load all map data for the specified map and release it void mapDataInit(const uint32_t mapNum); void mapDataShutdown();
2.34375
2
2024-11-18T22:23:47.830970+00:00
2020-04-17T00:22:40
e94a26ffc6a30940c51e41de593dbc7d251764e6
{ "blob_id": "e94a26ffc6a30940c51e41de593dbc7d251764e6", "branch_name": "refs/heads/master", "committer_date": "2020-04-17T00:22:40", "content_id": "e0c9170bd64b4d0584b658b5d1dbcd7fd3b0300d", "detected_licenses": [ "Apache-2.0" ], "directory_id": "a559503e31dbc2a8833fb2af33d9b8596974d6ca", "extension": "h", "filename": "async.h", "fork_events_count": 4, "gha_created_at": "2018-05-03T03:45:59", "gha_event_created_at": "2020-04-17T00:22:42", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 131938571, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5282, "license": "Apache-2.0", "license_type": "permissive", "path": "/async.h", "provenance": "stackv2-0115.json.gz:73179", "repo_name": "coecms/mppnccombine-fast", "revision_date": "2020-04-17T00:22:40", "revision_id": "025c7193bd43418319db378f6553d1d115eec1d5", "snapshot_id": "2e9913277a4d90858ba155b0e8adb33dae339e02", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/coecms/mppnccombine-fast/025c7193bd43418319db378f6553d1d115eec1d5/async.h", "visit_date": "2021-07-18T18:45:07.132466" }
stackv2
/* * Copyright 2018 * * \author <scott.wales@unimelb.edu.au> * * 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. */ #ifndef ASYNC_H #define ASYNC_H #ifdef __cplusplus extern "C" { #endif #include <stdlib.h> #include <stdint.h> #include "hdf5.h" #include "mpi.h" #include "netcdf.h" typedef struct { int idx; } varid_t; //! Get info about a variable in the output file /** * For direct chunk writes to work the compression parameters must match * between the input and output files. Use this function to query the * parameters of the output file, then compare the results against the values * returned by nc_inq_var_deflate() on the input file. * * \param varid: Variable handle obtained with open_variable_async * \param ndims: Number of dimensions * \param chunk[ndims] (out): Chunk shape * \param deflate (out): Compression enabled * \param deflate_level (out): Compression level * \param shuffle (out): Shuffle filter enabled * \param async_writer_rank: MPI rank of writer process */ void variable_info_async( varid_t varid, size_t ndims, size_t chunk[], int * deflate, int * deflate_level, int * shuffle, int async_writer_rank ); //! Write data to the file, using the dataset filters /** * This writes uncompressed data, as obtained by nc_get_vara() on the input * file. It is slower than direct chunk writes, as the data must be put through * a compression filter, but is more flexible as it can be used to write * partial or unaligned chunks. * * \param varid: Variable handle obtained with open_variable_async * \param ndims: Number of dimensions * \param offset[ndims]: Offset of this data's origin in the collated dataset * \param shape[ndims]: Shape of this data array * \param buffer: Compressed chunk data * \param type: NetCDF type of the data * \param async_writer_rank: MPI rank of writer process * \param request (out): MPI request for the communication * * request must be sent to MPI_Wait for the message to complete */ void write_uncompressed_async( varid_t varid, size_t ndims, const size_t offset[], const size_t shape[], const void * buffer, nc_type type, int async_writer_rank, MPI_Request * request); //! Write a compressed chunk directly to the file /** * This writes compressed chunks, as obtained by opening the input file in HDF5 * and calling H5DOread_chunk(). This is faster than copying uncompressed data, * but the chunking and compression parameters must be identical on the input * and output files, and the chunk must lay on the chunk boundary of the output * file. variable_info_async() can be used to determine the chunk layout and * compression settings of the variable in the output file. * * \param varid: Variable handle obtained with open_variable_async * \param ndims: Number of dimensions * \param filter_mask: HDF5 filter information (must match the output file) * \param offset[ndims]: Offset of this chunk's origin in the collated dataset (must * be on a chunk boundary of the output file) * \param data_size: Size of the compressed chunk in bytes * \param buffer: Compressed chunk data * \param async_writer_rank: MPI rank of writer process * \param request [out]: MPI request for the communication * * request must be sent to MPI_Wait for the message to complete */ void write_chunk_async( varid_t varid, size_t ndims, uint32_t filter_mask, const hsize_t offset[], size_t data_size, const void * buffer, int async_writer_rank, MPI_Request * request ); //! Open a variable in the async writer /** * \param varname: Variable name * \param len: Length of varname, including the closing '/0' * \param async_writer_rank: MPI rank of writer process * * \returns a handle to the variable in the output file */ varid_t open_variable_async( const char * varname, size_t len, // Total length including '/0' int async_writer_rank ); //! Close a variable in the async writer /** * \param varid: Variable handle obtained with open_variable_async * \param async_writer_rank: MPI rank of writer process * * varid is no longer a valid handle after this call */ void close_variable_async( varid_t varid, int async_writer_rank ); //! Close the async writer /** * \param async_writer_rank: MPI rank of writer process */ void close_async( int async_writer_rank ); //! Async runner to accept writes /** * Called by the Writer to accept async messages sent by the Readers. Once all * Readers have sent close_async() messages this will return * * \param filename: Output filename * * \returns total size written */ size_t run_async_writer( const char * filename ); #ifdef __cplusplus } #endif #endif
2.078125
2
2024-11-18T22:23:47.963553+00:00
2019-09-12T11:49:48
b9b07c6efeb0e6dff69eb0dc43bf3e3e46d14aa2
{ "blob_id": "b9b07c6efeb0e6dff69eb0dc43bf3e3e46d14aa2", "branch_name": "refs/heads/master", "committer_date": "2019-09-12T11:49:48", "content_id": "3edcd2d3f44cc27577998751efd1a762bb3e1878", "detected_licenses": [ "MIT" ], "directory_id": "d1346e5e55242697ca22e602519b2220c25054a1", "extension": "h", "filename": "opengl_rendering.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 196866966, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3306, "license": "MIT", "license_type": "permissive", "path": "/src/opengl_rendering.h", "provenance": "stackv2-0115.json.gz:73308", "repo_name": "glitchheart/glitchheartengine", "revision_date": "2019-09-12T11:49:48", "revision_id": "7adf14475f8feb6239e12a9ce2cfd9c005592443", "snapshot_id": "c773d08ab3ce619fa0dc156927e31dd4707a9916", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/glitchheart/glitchheartengine/7adf14475f8feb6239e12a9ce2cfd9c005592443/src/opengl_rendering.h", "visit_date": "2021-06-25T10:12:56.611584" }
stackv2
#ifndef OPENGL_H #define OPENGL_H #if defined(__APPLE__) #define GLFW_INCLUDE_GLCOREARB #endif #include <GLFW/glfw3.h> // IMGUI struct InternalImGuiState { char glsl_version_string[32] = ""; GLuint font_texture = 0; GLuint shader_handle = 0; GLuint vert_handle = 0; GLuint frag_handle = 0; i32 attrib_location_tex = 0; i32 attrib_location_proj_mtx = 0; i32 attrib_location_vtx_pos = 0; i32 attrib_location_vtx_uv = 0; i32 attrib_location_vtx_color = 0; u32 vbo_handle = 0; u32 elements_handle = 0; }; // ENDIMGUI struct ShaderGL { GLuint program; int handle; GLuint vert_program; GLuint geo_program; GLuint frag_program; GLint uniform_locations[1024]; i32 location_count; }; struct Texture { GLuint handle; i32 width; i32 height; }; struct Buffer { GLuint vao; GLuint vbo; GLuint ibo; GLint vertex_buffer_size; GLint vertex_count; GLint index_buffer_size; GLint index_buffer_count; size_t size; GLenum usage; }; struct UniformBuffer { GLuint ubo; size_t size; GLenum usage; u8* memory; }; struct Framebuffer { u32 width; u32 height; GLuint buffer_handle; GLuint tex0_loc; GLuint tex_color_buffer_handles[4]; i32 tex_color_buffer_count; GLuint depth_buffer_handles[4]; i32 depth_buffer_count; GLuint vao; GLuint vbo; GLuint ebo; b32 multisampled; i32 samples; b32 hdr; b32 has_shadow_map; struct { i32 width; i32 height; } shadow_map; GLuint shadow_map_handle; }; struct RenderState { InternalImGuiState imgui_state; struct { GLuint shader_program; GLuint vao; } current_state; GLFWwindow *window; b32 vsync_active; i32 window_width; i32 window_height; i32 framebuffer_width; i32 framebuffer_height; i32 dpi_scale; r32 density_factor; i32 refresh_rate; b32 paused; r64 screen_dpi; r32 contrast; r32 brightness; char* window_title; r64 frame_delta; r64 total_delta; GLint viewport[4]; r64 delta_time; b32 should_close; b32 mouse_locked; r64 fps; struct { Framebuffer framebuffers[global_max_framebuffers]; i32 framebuffer_count; } v2; Framebuffer shadow_map_buffer; u32 framebuffer_quad_vertices_size = 16 * sizeof(GLfloat); GLuint bound_vertex_buffer; GLuint bound_texture; GLfloat framebuffer_quad_vertices[16] = { -1.0f, 1.0f, 0, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0, 0.0f }; GLuint quad_indices[6] = { 0, 1, 2, 0, 2, 3 }; GLuint quad_index_buffer; GLuint framebuffer_quad_vao; GLuint framebuffer_quad_vbo; ShaderGL *gl_shaders; i32 gl_shader_count; GLFWcursor* cursors[6]; RenderState() {} MemoryArena* perm_arena; // TODO: Make this into a framebuffer arena maybe? MemoryArena framebuffer_arena; MemoryArena string_arena; }; struct RenderingState { RenderState *render_state; Renderer *renderer; }; RenderingState rendering_state; #endif
2.0625
2
2024-11-18T22:23:48.029706+00:00
2022-02-16T23:16:25
8c9d51bff5104c908a87d946609226c72b2aa4dd
{ "blob_id": "8c9d51bff5104c908a87d946609226c72b2aa4dd", "branch_name": "refs/heads/master", "committer_date": "2022-02-16T23:16:25", "content_id": "b82b598a1cd1464cc1124046106e20f611c3f64c", "detected_licenses": [ "Zlib" ], "directory_id": "38eabc5e53c62428f130f6cfa0bba04bd4e6b857", "extension": "h", "filename": "HueColorPicker.h", "fork_events_count": 9, "gha_created_at": "2014-08-26T12:33:14", "gha_event_created_at": "2022-08-29T13:55:57", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 23350910, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4294, "license": "Zlib", "license_type": "permissive", "path": "/Sources/ObjectivelyMVC/HueColorPicker.h", "provenance": "stackv2-0115.json.gz:73438", "repo_name": "jdolan/ObjectivelyMVC", "revision_date": "2022-02-16T23:16:25", "revision_id": "f1c4b3c8bf8a3a0a915f6dd39e52728d64d1ffe2", "snapshot_id": "2955978b14d27bfec71e7500c771b8b119984913", "src_encoding": "UTF-8", "star_events_count": 24, "url": "https://raw.githubusercontent.com/jdolan/ObjectivelyMVC/f1c4b3c8bf8a3a0a915f6dd39e52728d64d1ffe2/Sources/ObjectivelyMVC/HueColorPicker.h", "visit_date": "2022-12-04T17:21:38.522049" }
stackv2
/* * ObjectivelyMVC: Object oriented MVC framework for OpenGL, SDL2 and GNU C. * Copyright (C) 2014 Jay Dolan <jay@jaydolan.com> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. */ #pragma once #include <ObjectivelyMVC/Input.h> #include <ObjectivelyMVC/StackView.h> #include <ObjectivelyMVC/Slider.h> /** * @file * @brief Hue color picker. */ typedef struct HueColorPickerDelegate HueColorPickerDelegate; typedef struct HueColorPicker HueColorPicker; typedef struct HueColorPickerInterface HueColorPickerInterface; /** * @brief The HueColorPicker delegate protocol. */ struct HueColorPickerDelegate { /** * @brief The delegate self-reference. */ ident self; /** * @brief Called by the HueColorPicker when hue selection changes. * @param hueColorPicker The HueColorPicker. * @param hue The hue (0.0 - 360.0). * @param saturation The saturation (0.0 - 1.0). * @param value The brightness value (0.0 - 1.0). */ void (*didPickColor)(HueColorPicker *hueColorPicker, double hue, double saturation, double value); }; /** * @brief The HueColorPicker type. * @extends Control * @ingroup Controls */ struct HueColorPicker { /** * @brief The superclass. */ Control control; /** * @brief The interface. * @protected */ HueColorPickerInterface *interface; /** * @brief The hue preview. */ View *colorView; /** * @brief The delegate. */ HueColorPickerDelegate delegate; /** * @brief The Input. */ Input *hueInput; /** * @brief The Slider. */ Slider *hueSlider; /** * @brief The color componenets. * @remarks Only `hue` is mutable via the interface. */ double hue, saturation, value; /** * @brief The StackView. */ StackView *stackView; }; /** * @brief The HueColorPicker interface. */ struct HueColorPickerInterface { /** * @brief The superclass interface. */ ControlInterface controlInterface; /** * @fn HueColorPicker *HueColorPicker::initWithFrame(HueColorPicker *self, const SDL_Rect *frame) * @brief Initializes this HueColorPicker with the specified frame. * @param self The HueColorPicker. * @param frame The frame. * @return The initialized HueColorPicker, or `NULL` on error. * @memberof HueColorPicker */ HueColorPicker *(*initWithFrame)(HueColorPicker *self, const SDL_Rect *frame); /** * @fn SDL_Color HueColorPicker::rgbColor(const HueColorPicker *self); * @param self The HueColorPicker. * @return The RGB color. * @memberof HueColorPicker */ SDL_Color (*rgbColor)(const HueColorPicker *self); /** * @fn void HueColorPicker::setColor(HueColorPicker *self, double hue, double saturation, double value) * @brief Sets the color of the HueColorPicker. * @param self The HueColorPicker. * @param hue The hue. * @param saturation The saturation. * @param value The brightness value. * @memberof HueColorPicker */ void (*setColor)(HueColorPicker *self, double hue, double saturation, double value); /** * @fn void HueColorPicker::setRGBColor(HueColorPicker *self, const SDL_Color *color) * @brief Sets the color of the HueColorPicker. * @param self The HueColorPicker. * @param color The RGB color. * @memberof HueColorPicker */ void (*setRGBColor)(HueColorPicker *self, const SDL_Color *color); }; /** * @fn Class *HueColorPicker::_HueColorPicker(void) * @brief The HueColorPicker archetype. * @return The HueColorPicker Class. * @memberof HueColorPicker */ OBJECTIVELYMVC_EXPORT Class *_HueColorPicker(void);
2.109375
2
2024-11-18T22:23:48.428556+00:00
2023-07-01T22:47:53
61995de17e1002e126e9376b9289207c107daa4a
{ "blob_id": "61995de17e1002e126e9376b9289207c107daa4a", "branch_name": "refs/heads/master", "committer_date": "2023-07-01T22:47:53", "content_id": "775f63735e1770fd6b69fda95b8265208c65a744", "detected_licenses": [ "Apache-2.0" ], "directory_id": "ddd07c7d6573be0e633356c0aaa2c3e03f06e395", "extension": "h", "filename": "interrupt_in.h", "fork_events_count": 26, "gha_created_at": "2016-07-04T22:11:10", "gha_event_created_at": "2023-07-01T22:47:55", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 62590379, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1230, "license": "Apache-2.0", "license_type": "permissive", "path": "/control/mtrain/API/c/Inc/interrupt_in.h", "provenance": "stackv2-0115.json.gz:73955", "repo_name": "RoboJackets/robocup-firmware", "revision_date": "2023-07-01T22:47:53", "revision_id": "52a4ac5171ee50543251870711c88653319d6c09", "snapshot_id": "8a53cfcd941112a49359012d3e9f91be5d09d8ed", "src_encoding": "UTF-8", "star_events_count": 29, "url": "https://raw.githubusercontent.com/RoboJackets/robocup-firmware/52a4ac5171ee50543251870711c88653319d6c09/control/mtrain/API/c/Inc/interrupt_in.h", "visit_date": "2023-07-09T13:30:36.069027" }
stackv2
#ifndef __INTERRUPT_IN_H #define __INTERRUPT_IN_H #ifdef __cplusplus extern "C" { #endif #include "pin_defs.h" typedef enum { INTERRUPT_RISING = GPIO_MODE_IT_RISING, INTERRUPT_FALLING = GPIO_MODE_IT_FALLING, INTERRUPT_RISING_FALLING = GPIO_MODE_IT_RISING_FALLING } interrupt_mode; /** Configures GPIO pin for interruptin * * Defaults to no pull type and both edge detection * * @param pin Pin def external to board * @param function Function linked to interrupt */ void interruptin_init(pin_name pin, void (*function)()); // void (*function)(void) /** Configures GPIO pin for interruptin * * @param pin Pin def external to board * @param function Function linked to interrupt * @param pull Pin pull type (pull up, pull down, or no pull) * @param mode Interrupt mode (rising edge, falling edge, or both edges) */ void interruptin_init_ex(pin_name pin, void (*function)(), pull_type pull, interrupt_mode mode); /** Deinits GPIO pin * * @param pin Pin def external to board */ void interruptin_deinit(pin_name pin); /** Reads current value of pin * * @param pin Pin def external to board * @return 1 (high) or 0 (low) */ int interruptin_read(pin_name pin); #ifdef __cplusplus } #endif #endif
2.515625
3
2024-11-18T22:23:48.855692+00:00
2020-04-30T13:24:42
4c7b9e91f98744cb212090bfba99adea34a2586e
{ "blob_id": "4c7b9e91f98744cb212090bfba99adea34a2586e", "branch_name": "refs/heads/main", "committer_date": "2020-04-30T13:24:42", "content_id": "9feea76ce7adf1242c0772103cd201c45ce080f0", "detected_licenses": [ "MIT" ], "directory_id": "4d73c93fda9e9dbd0cb110b7670e7a813b6466e0", "extension": "c", "filename": "watson.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 259627696, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8425, "license": "MIT", "license_type": "permissive", "path": "/src/watson.c", "provenance": "stackv2-0115.json.gz:74084", "repo_name": "davidofferman/xfce4-watson-plugin", "revision_date": "2020-04-30T13:24:42", "revision_id": "496b7ea44806a716b58ba6fdf785dc1783f503c8", "snapshot_id": "12408044cec504e47f66391fc3262b1aeb0fee25", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/davidofferman/xfce4-watson-plugin/496b7ea44806a716b58ba6fdf785dc1783f503c8/src/watson.c", "visit_date": "2022-11-09T08:34:42.044760" }
stackv2
#include <gtk/gtk.h> #include <libxfce4util/libxfce4util.h> #include <libxfce4panel/libxfce4panel.h> #include <mjson/mjson.h> #include "utils.h" #include "watson.h" /** * config_path * ----------- * Returns a NULL terminated string with the path to the watson * configuration directory. The returned string must be free'd with * `g_free()`. * * @param const char * Optional file name inside Watson config * @return char * */ static gchar * config_path(const gchar *file) { const gchar *config_dir; gchar *path; config_dir = g_get_user_config_dir(); path = g_build_filename(config_dir, "watson", file, NULL); return path; } /** * icon_new * -------- * Creates a GTK Widget of the current icon type. * * @param enum watson_icon * @param int * @return GtkWidget * */ static GtkWidget * icon_new(enum watson_icon icon, int size) { GError *error = NULL; GdkPixbuf *pix = NULL; gchar *file = NULL; GtkWidget *image; switch (icon) { case ICON_ACTIVE: file = g_build_filename(WATSON_DATADIR, "active.svg", NULL); break; case ICON_INACTIVE: file = g_build_filename(WATSON_DATADIR, "inactive.svg", NULL); break; default: /* do nothing */ break; } if(file) { pix = gdk_pixbuf_new_from_file_at_scale(file, size, size, FALSE, &error); } if (pix) { image = gtk_image_new_from_pixbuf(pix); g_object_unref(pix); } else { if (file) { DBG("gdk_pixbuf_new_from_file_at_scale(%s): %s", file, error->message); g_error_free(error); } image = gtk_image_new_from_icon_name("image-missing", 0); } if (file) { g_free(file); } return image; } /** * icon_update * ------------------ * Updates the displayed icon in the plugin. * * @param struct watson_plugin * * @param enum WatsonIconType * @return void */ static void icon_update(struct watson_plugin *watson, enum watson_icon icon) { int size; if (watson->icon) { gtk_widget_destroy(watson->icon); } size = plugin_get_icon_size(watson->plugin); watson->icon = icon_new(icon, size); gtk_container_add(GTK_CONTAINER(watson->box), watson->icon); gtk_widget_show(watson->icon); } /** * state_free * ---------- * Free memory for `struct watson_state`. * * @param WatsonState * * @return void */ static void state_free(struct watson_state *state) { g_slice_free(struct watson_state, state); } /** * state_new * --------- * get the state of the external Watson program. Free using * `state_free`. * * @return WatsonState * */ static struct watson_state * state_new(void) { size_t content_len; gchar *path, *content; int json_size, scontent_len; const char *json_ptr; enum mjson_tok json_tok; struct watson_state *state; state = g_slice_new0(struct watson_state); path = config_path("state"); if (g_file_get_contents(path, &content, &content_len, NULL) == FALSE) { state_free(state); state = NULL; goto clean; } /** * Parse JSON */ scontent_len = (content_len > INT_MAX ? INT_MAX : (int)content_len); json_tok = mjson_find(content, scontent_len, "$.project", &json_ptr, &json_size); if (json_tok == MJSON_TOK_STRING) { state->status = STATUS_ACTIVE; } else { state->status = STATUS_INACTIVE; } /** * Cleanup */ clean: g_free(path); g_free(content); return state; } /** * watson_update * ------------- * Updates the plugin based on it's currently saved state. * * @param struct watson_plugin * * @return void */ static void watson_update(struct watson_plugin *watson) { enum watson_icon icon; switch (watson->status) { case STATUS_ACTIVE: icon = ICON_ACTIVE; break; case STATUS_INACTIVE: icon = ICON_INACTIVE; break; default: icon = ICON_INACTIVE; break; } icon_update(watson, icon); } /** * watson_process * -------------- * Processes external data to update the plugin state. * * @param struct watson_plugin * * @return void */ static void watson_process(struct watson_plugin *watson) { struct watson_state *state; state = state_new(); if (!state) { watson->status = STATUS_INACTIVE; } else { watson->status = state->status; } state_free(state); } /** * watson_notify_event * ------------------ * Callback for when the notify library. Handles events for the Watson * configuration files and then updates the plugin state. * * @param NotifyEvent * * @param struct watson_plugin * * @return void */ static void watson_file_changed(GFileMonitor *monitor, GFile *file, GFile *other, GFileMonitorEvent evtype, struct watson_plugin *watson) { (void) monitor; (void) file; (void) other; (void) evtype; TRACE("file changed"); watson_process(watson); watson_update(watson); } /** * monitor_free * ------------ * Free the monitor structure * * @param struct watson_monitor * * @return void */ void monitor_free(struct watson_monitor *monitor) { if (!monitor) { return; } g_object_unref(monitor->file); g_object_unref(monitor->monitor); g_slice_free(struct watson_monitor, monitor); } /** * monitor_new * ----------- * Monitor a file * * @param gchar * * @return GFileMonitor */ static struct watson_monitor * monitor_new(gchar *filename, GCallback cb, void *userp) { struct watson_monitor *wm; GError *error = NULL; wm = g_slice_new0(struct watson_monitor); wm->file = g_file_new_for_path(filename); wm->monitor = g_file_monitor(wm->file, G_FILE_MONITOR_NONE, NULL, &error); if (!wm->monitor) { fprintf(stderr, "unable to monitor %s: %s\n", filename, error->message); g_error_free(error); monitor_free(wm); return NULL; } g_signal_connect( G_OBJECT(wm->monitor), "changed", cb, userp); return wm; } /** * watson_new * ---------- * Creates the Watson Plugin for the XFCE4 Panel. * * @param XfcePanelPlugin * * @return struct watson_plugin * */ static struct watson_plugin * watson_new(XfcePanelPlugin *plugin) { GtkOrientation orientation; struct watson_plugin *watson; gchar *watson_state_file; watson = g_slice_new0(struct watson_plugin); watson->plugin = plugin; watson->status = STATUS_INACTIVE; /** * File Monitor */ watson_state_file = config_path("state"); watson->monitor = monitor_new( watson_state_file, G_CALLBACK(watson_file_changed), watson); /** * Panel Variables */ orientation = xfce_panel_plugin_get_orientation(plugin); /** * Create Container */ watson->evnt_box = gtk_event_box_new(); watson->box = gtk_box_new(orientation, 2); gtk_widget_set_halign(watson->box, GTK_ALIGN_CENTER); gtk_widget_set_valign(watson->box, GTK_ALIGN_CENTER); gtk_container_add(GTK_CONTAINER(watson->evnt_box), watson->box); gtk_widget_show_all(watson->evnt_box); /** * Cleanup */ g_free(watson_state_file); return watson; } /** * watson_free * ----------- * Cleans up the Watson Plugin that was created using `watson_new` * * @param XfcePanelPlugin * * @param struct watson_plugin * * @return void */ static void watson_free(XfcePanelPlugin *plugin, struct watson_plugin *watson) { (void)plugin; GtkWidget *dialog; dialog = g_object_get_data(G_OBJECT(watson->plugin), "dialog"); if (G_UNLIKELY(dialog != NULL)) { gtk_widget_destroy(dialog); } monitor_free(watson->monitor); gtk_widget_destroy(watson->box); g_slice_free(struct watson_plugin, watson); } /** * plugin_size_changed * ------------------- * Callback for when the XFCE4 Panel size has changed. * * @param XfcePanelPlugin * * @param int * @param struct watson_plugin * * @return gboolean */ static gboolean plugin_size_changed(XfcePanelPlugin *plugin, int size, struct watson_plugin *watson) { (void)plugin; (void)size; watson_update(watson); return TRUE; } /** * plugin_construct * ---------------- * The entry point for the XFCE4 Panel Plugin. * * @param XfcePanelPlugin * * @return void */ static void plugin_construct(XfcePanelPlugin *plugin) { struct watson_plugin *watson; /** * Configure XFCE4 Panel Plugin */ xfce_panel_plugin_set_small(plugin, TRUE); /** * Initialize Plugin */ watson = watson_new(plugin); gtk_container_add(GTK_CONTAINER(plugin), watson->evnt_box); watson_process(watson); watson_update(watson); /** * Connect to signals */ g_signal_connect( G_OBJECT(plugin), "free-data", G_CALLBACK(watson_free), watson); g_signal_connect( G_OBJECT(plugin), "size-changed", G_CALLBACK(plugin_size_changed), watson); } /** * Register the plugin */ XFCE_PANEL_PLUGIN_REGISTER(plugin_construct);
2.140625
2
2024-11-18T22:23:49.384928+00:00
2006-02-24T03:01:30
801b5c4cee2c224a92c70825c8debea3b54653d3
{ "blob_id": "801b5c4cee2c224a92c70825c8debea3b54653d3", "branch_name": "refs/heads/master", "committer_date": "2006-02-24T03:01:30", "content_id": "58003b06404d0b8faab83891abd142fb1e809918", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "a042a384d78421588e814054727f16ab0cc0faec", "extension": "c", "filename": "wordcut_mkdict.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 8879463, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8429, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/v4/wordcut/wordcut/wordcut_mkdict.c", "provenance": "stackv2-0115.json.gz:74604", "repo_name": "veer66/thaiwordseg", "revision_date": "2006-02-24T03:01:30", "revision_id": "48acaea851126256deb4aa18c53a395eb8b7bde4", "snapshot_id": "03b6da359889df1714940326519620c961ceb2d2", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/veer66/thaiwordseg/48acaea851126256deb4aa18c53a395eb8b7bde4/v4/wordcut/wordcut/wordcut_mkdict.c", "visit_date": "2023-02-24T16:35:36.574435" }
stackv2
/* * * Copyright (C) 2003 Vee Satayamas * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * 1. Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * 3. The name of the author may not be used to endorse or * promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * */ #include<stdio.h> #include<stdlib.h> #include<stdint.h> #include<string.h> #include<assert.h> #include<fcntl.h> #include<unistd.h> #include<sys/stat.h> #define TAB_SIZE 0x100 typedef struct trienode_t{ int complete; uint32_t data; struct linktab_t* linktab; } TrieNode; typedef struct linktab_t { size_t size; TrieNode *link[TAB_SIZE]; } LinkTab; TrieNode *root; int verbose=0; TrieNode* new_trienode() { TrieNode *tmp; tmp=malloc(sizeof(TrieNode)); if (tmp==NULL) { fprintf (stderr,"%s:%d: Could not allocate memory for trie node.\n",__FILE__,__LINE__); exit(1); } tmp->complete=0; tmp->linktab=NULL; return tmp; } void trie_init() { root=new_trienode(); }; LinkTab* new_linktab() { LinkTab *tmp; tmp=malloc(sizeof(LinkTab)); if (tmp==NULL) { fprintf (stderr,"%s:%d: Could not allocate memory for link table.\n",__FILE__,__LINE__); exit(1); } tmp->size=0; memset(tmp->link,0,sizeof(tmp->link)); return tmp; } void trie_add(const char *str) { uint8_t *key=(uint8_t *)str , *i; TrieNode *node=root; for(i=key;*i!=(uint8_t)'\0';i++) { /* looking for exist link */ if (node->linktab!=NULL && node->linktab->link[*i]!=NULL) { node=node->linktab->link[*i]; } else { if(node->linktab==NULL) { node->linktab=new_linktab(); } node->linktab->link[*i]=new_trienode(); node->linktab->size++; node=node->linktab->link[*i]; } } node->complete=1; } void load_dict(const char* filename) { #define MAX_BUF 0x400 FILE *fp; char buffer[MAX_BUF]; if((fp=fopen(filename,"r"))==NULL) { fprintf (stderr,"%s:%d: Could not open dictionary.\n",__FILE__,__LINE__); exit(1); } while(fgets(buffer,MAX_BUF,fp)!=NULL) { char *tok_buffer; tok_buffer=strtok(buffer,"\n\r\t "); trie_add(tok_buffer); } fclose(fp); } char dump_buffer[1024]; void dump_(TrieNode *node,int c) { if (node==NULL) return; if (node->complete) { int i; for(i=0;i<c;i++) { printf ("%c",dump_buffer[i]); } printf ("\n"); } if (node->linktab!=NULL && node->linktab->size>0) { int i; LinkTab *tab=node->linktab; for(i=0;i<TAB_SIZE;i++) { if (tab->link[i]!=NULL) { dump_buffer[c]=(char)i; dump_(tab->link[i],c+1); } } } } void dump() { dump_(root,0); } #define OUTSIZE 1000000 uint8_t outb[OUTSIZE]; #define LINK_SIZE 3 unsigned int encode_(TrieNode *node,int start) { int cpos; uint8_t header=0,size; assert (node!=NULL); cpos=start; if (node->complete) { header=(header|1); } if (node->linktab==NULL || node->linktab->size<=1) { header=(header|2); } if (verbose) printf ("Header=%d\n",header); outb[cpos]=header; cpos++; #ifdef ENABLE_DATA if (node->complete) { /* skip data */ cpos=cpos+4; } #endif if (node->linktab==NULL || node->linktab->size==0) { if (verbose) printf ("!!! NULL NODE\n"); size = 0; outb[cpos]=0; cpos++; return cpos; } else if (node->linktab->size==1) { int i,flag=1,c=0,j; unsigned int lpos,xpos; uint8_t buffer[1024]; int k; TrieNode* next; if (verbose) printf ("!!! COMPRESS NODE\n"); while(flag) { for(i=0;i<TAB_SIZE;i++) { if (node->linktab->link[i]!=NULL) { next=node->linktab->link[i]; buffer[c]=(uint8_t)i; c++; if( next->complete || next->linktab->size != 1 ) { node=next; flag=0; break; } else { node=next; } } } } assert (c>0); /* write size */ outb[cpos]=(uint8_t)c; cpos++; for(j=0;j<c;j++) { outb[cpos]=buffer[j]; cpos++; } lpos=cpos+LINK_SIZE; xpos=encode_(node,lpos); if(lpos > 0x00FFFFFF) { fprintf(stderr,"Dictionary size is too big\n"); exit(1); } /* Little Endian */ for(k=0;k<LINK_SIZE;k++) { outb[cpos]=(uint8_t)(lpos & 0xFF); cpos++; lpos = (lpos >> 8); } return xpos; } else { unsigned int tsize,i,lpos,xpos; int k; if (verbose) printf ("!!! NORMAL NODE\n"); assert(node->linktab->size>1); tsize=node->linktab->size; if (verbose) printf ("### cpos=%d size=%d\n",cpos,tsize); outb[cpos] = (0xFF & tsize); cpos++; lpos=cpos+(tsize*(LINK_SIZE+1)); for(i=0;i<TAB_SIZE;i++) { if(node->linktab->link[i]!=NULL) { outb[cpos]=(uint8_t)i; cpos++; xpos=encode_(node->linktab->link[i],lpos); /* write */ for(k=0;k<LINK_SIZE;k++) { outb[cpos]=(uint8_t)(lpos & 0xFF); cpos++; lpos = (lpos >> 8); } lpos=xpos; } } return lpos; } } void encode(int *size) { *size=encode_(root,1); } int main (int argc,char** argv) { int size,fd; char *fn1,*fn2; size_t ret,x=0; FILE *fp; if (argc<3) { fprintf (stderr,"Usage: wordcut_mkdict (-v) <plain dict> <encoded dict>\n"); exit(1); } if (argc==4) { if (strcmp(argv[1],"-v")==0) { verbose=1; } else { fprintf (stderr,"Usage: wordcut_mkdict (-v) <plain dict> <encoded dict>\n"); exit(1); } fn1=argv[2]; fn2=argv[3]; } else { fn1=argv[1]; fn2=argv[2]; } trie_init(); load_dict(fn1); /* dump(); printf ("\n"); */ encode(&size); /* printf ("Size = %d\n",size); */ /* for(i=0;i<size;i++) { printf ("#%d/%d ",i,outb[i]); } printf ("\n"); */ fp=fopen(fn2,"w"); if (!fp) { fprintf (stderr,"%s:%d: Can't open file %s\n",__FILE__,__LINE__,fn2); exit(1); } if (fwrite(outb,1,size,fp)!=size) { fprintf (stderr,"Could not write result.\n"); exit(1); } fclose(fp); return 0; }
2.28125
2
2024-11-18T22:23:49.598961+00:00
2018-10-08T02:03:43
0bc43418a72c84a34e2d40149ec63ac4aa0b30e7
{ "blob_id": "0bc43418a72c84a34e2d40149ec63ac4aa0b30e7", "branch_name": "refs/heads/master", "committer_date": "2018-10-09T02:45:53", "content_id": "2c8adb7c65f2b0efa2a05b6a497c4c82936efdc6", "detected_licenses": [ "MIT" ], "directory_id": "e0b181ba95bf4691394d969fa3c01322212a57b0", "extension": "c", "filename": "getpwent.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 150646413, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 573, "license": "MIT", "license_type": "permissive", "path": "/db-files/getpwent.c", "provenance": "stackv2-0115.json.gz:74996", "repo_name": "lucvoo/slibc", "revision_date": "2018-10-08T02:03:43", "revision_id": "2f356f934078425b620b047d6344b85912d219a4", "snapshot_id": "adcfd7af217fc4fe021feb79b1ee0733f80f1495", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/lucvoo/slibc/2f356f934078425b620b047d6344b85912d219a4/db-files/getpwent.c", "visit_date": "2020-03-30T02:43:51.948479" }
stackv2
#include "_pwd.h" #include <paths.h> // for _PATH_PASSWD #include <values/NULL.h> // FIXME: split in 3 files? static parse_state_t state; void setpwent(void) { if (state.buf) state.ptr = state.buf; else __libc_parse_start(_PATH_PASSWD, &state); } void endpwent(void) { __libc_parse_finish(&state); } struct passwd *getpwent(void) { static char buf[PWDBUF_SIZE]; static struct passwd pwd; if (!state.buf) if (__libc_parse_start(_PATH_PASSWD, &state)) return NULL; if (__libc_getpwent(&pwd, buf, sizeof(buf), &state)) return NULL; return &pwd; }
2.15625
2
2024-11-18T22:23:49.787568+00:00
2020-09-20T18:49:07
84980e09f86143335112d7adf375ba4aef3d36e6
{ "blob_id": "84980e09f86143335112d7adf375ba4aef3d36e6", "branch_name": "refs/heads/master", "committer_date": "2020-09-20T18:49:07", "content_id": "89e8d5d00df17d3a3e1c37a286d5c1c3aaf812b8", "detected_licenses": [ "MIT" ], "directory_id": "50e52e20bbb3b80d57d4bf398bedb61c40c17e98", "extension": "c", "filename": "estado.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 296779468, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1110, "license": "MIT", "license_type": "permissive", "path": "/codigos/estado.c", "provenance": "stackv2-0115.json.gz:75258", "repo_name": "welenmota75/TADS-PFDA1", "revision_date": "2020-09-20T18:49:07", "revision_id": "aae31c256a7ce3958424358284a881ec3496ee89", "snapshot_id": "51e91d44e37f599d73d2edee5ba178d9e5b14afe", "src_encoding": "IBM852", "star_events_count": 0, "url": "https://raw.githubusercontent.com/welenmota75/TADS-PFDA1/aae31c256a7ce3958424358284a881ec3496ee89/codigos/estado.c", "visit_date": "2022-12-18T00:36:31.965926" }
stackv2
#include <stdio.h> #include <conio.h> #include <locale.h> #include <stdlib.h> char estciv; main() { setlocale(LC_ALL,""); INICIO: system ("color 70"); system("cls"); printf("\n\n\n\n\t\t\tforneša o estado civil"); printf("\n\n\n\t\t\t\[c] = casado"); printf("\n\n\n\t\t\t\[s] = solteiro"); printf("\n\n\n\t\t\t\[d] = dirvorciado"); printf("\n\n\n\t\t\t\[o] = outros"); printf ("\n\n\n\n\t\t\tsua opcao:"); fflush(stdin); scanf("%c", &estciv); switch(estciv) { case 'c': case 'C' : printf("\n\nCasado"); break; case 's': case 'S': printf("\n\nsolteiro"); break; case 'd': case 'D': printf("\n\ndivorciado"); break; case 'o': case 'O': printf("\n\noutros"); break; default : { system ("color 47"); system ("cls"); printf("\n\nopcaoinvalida!!!\a\a\a"); getch(); goto INICIO; } } getch(); }
2.8125
3
2024-11-18T22:23:50.130316+00:00
2019-12-30T13:43:35
1f464e2d18a3a5cdb6f5451b71d5877e383112c5
{ "blob_id": "1f464e2d18a3a5cdb6f5451b71d5877e383112c5", "branch_name": "refs/heads/master", "committer_date": "2019-12-30T13:43:35", "content_id": "46c4a9d96340fdbcd7215ca90399a5f26eb2fbf3", "detected_licenses": [ "MIT", "BSD-2-Clause" ], "directory_id": "1dd397fa88b66877c669711f8a479c2fe61de440", "extension": "c", "filename": "main.c", "fork_events_count": 1, "gha_created_at": "2019-01-19T03:32:21", "gha_event_created_at": "2019-01-19T03:32:21", "gha_language": null, "gha_license_id": "NOASSERTION", "github_id": 166502179, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1756, "license": "MIT,BSD-2-Clause", "license_type": "permissive", "path": "/regression/cbmc-concurrency/atomic_section_sc3/main.c", "provenance": "stackv2-0115.json.gz:75515", "repo_name": "fanhy2114/yogar-cbmc", "revision_date": "2019-12-30T13:43:35", "revision_id": "4e61ef2853158bf183f9fe31b12bf048cefa643a", "snapshot_id": "bc707ccb927f6e5a2c23c188619e7bb997d9369e", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/fanhy2114/yogar-cbmc/4e61ef2853158bf183f9fe31b12bf048cefa643a/regression/cbmc-concurrency/atomic_section_sc3/main.c", "visit_date": "2020-04-17T10:27:50.033647" }
stackv2
//http://www.ibm.com/developerworks/java/library/j-jtp04186/index.html //Listing 2. A nonblocking counter using CAS #define __VERIFIER_atomic_CAS(v, e, u, r, flag) \ { \ __CPROVER_atomic_begin(); \ if(*v == e) \ { \ *flag = 1, *v = u, *r = 1; \ } \ else \ { \ *r = 0; \ } \ __CPROVER_atomic_end() ; \ } volatile unsigned value = 0; /*helpers for the property*/ volatile unsigned inc_flag = 0; volatile unsigned dec_flag = 0; void X__VERIFIER_atomic_assert1(unsigned inc__v) { __CPROVER_atomic_begin(); unsigned inc__v_l=inc__v; unsigned dec_flag_l=dec_flag; unsigned value_l=value; __CPROVER_atomic_end(); __CPROVER_assert(dec_flag_l || value_l > inc__v_l, ""); } unsigned inc() { unsigned inc__v, inc__vn, inc__casret; { inc__v = value; if(inc__v == 0u-1) { return 0; /*increment failed, return min*/ } inc__vn = inc__v + 1; __VERIFIER_atomic_CAS(&value,inc__v,inc__vn,&inc__casret,&inc_flag); } __CPROVER_assume(! (inc__casret==0)); X__VERIFIER_atomic_assert1(inc__v); return inc__vn; } void X__VERIFIER_atomic_assert2(unsigned dec__v) { __CPROVER_atomic_begin(); unsigned dec__v_l=dec__v; unsigned inc_flag_l=inc_flag; unsigned value_l=value; __CPROVER_atomic_end(); __CPROVER_assert(inc_flag_l || value_l < dec__v_l, ""); } unsigned dec() { unsigned dec__v, dec__vn, dec__casret; { dec__v = value; if(dec__v == 0) { return 0u-1; /*decrement failed, return max*/ } dec__vn = dec__v - 1; __VERIFIER_atomic_CAS(&value,dec__v,dec__vn,&dec__casret,&dec_flag); } __CPROVER_assume(! (dec__casret==0)); X__VERIFIER_atomic_assert2(dec__v); return dec__vn; } int main(){ __CPROVER_ASYNC_1: inc(); __CPROVER_ASYNC_1: dec(); __CPROVER_ASYNC_1: dec(); return 0; }
2.953125
3
2024-11-18T22:23:50.188731+00:00
2017-10-11T16:40:49
cae31d5d9c43e1b579d0fdeab6517ba5769999c0
{ "blob_id": "cae31d5d9c43e1b579d0fdeab6517ba5769999c0", "branch_name": "refs/heads/master", "committer_date": "2017-10-11T16:40:49", "content_id": "af12d6c07989c5ab3b956addf0ed1c48b49a4a03", "detected_licenses": [ "Apache-2.0", "MIT" ], "directory_id": "6c301b3172a883ecd0587d31020e4f7b42bf288e", "extension": "c", "filename": "test-crypto.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 58013004, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5725, "license": "Apache-2.0,MIT", "license_type": "permissive", "path": "/runtime/posix/test-crypto.c", "provenance": "stackv2-0115.json.gz:75646", "repo_name": "Northshoot/RavelLang", "revision_date": "2017-10-11T16:40:49", "revision_id": "846164fcd503d21a962a95516eb18ef3740d5b8d", "snapshot_id": "2770a4ac865236d7f0b0dcd8c9fa88df02329135", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Northshoot/RavelLang/846164fcd503d21a962a95516eb18ef3740d5b8d/runtime/posix/test-crypto.c", "visit_date": "2021-05-15T01:07:02.990050" }
stackv2
#include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "api/keys.h" #include "api/crypto.h" #include <wolfssl/options.h> #define WOLFSSL_AES_COUNTER #define WOLFSSL_AES_DIRECT #include <wolfssl/wolfcrypt/aes.h> #include <wolfssl/wolfcrypt/sha256.h> #define USE_WOLF_SHA #ifndef USE_WOLF_SHA #include "sha256.h" typedef SHA256_CTX sha256_context_t; #else typedef Sha256 sha256_context_t; static void sha256_init(sha256_context_t *ctx) { wc_InitSha256(ctx); } static void sha256_update(sha256_context_t *ctx, const uint8_t data[], size_t len) { wc_Sha256Update(ctx, data, len); } static void sha256_final(sha256_context_t *ctx, uint8_t hash[]) { wc_Sha256Final(ctx, hash); } #endif #define IV_SIZE 8 #define FULL_IV_SIZE 16 #define CIPHER_BLOCK_SIZE 16 #define AES_KEY_SIZE 16 #define MAC_SIZE 16 #define FULL_MAC_SIZE 32 #define MAC_KEY_SIZE 64 #define IPAD 0x36 #define OPAD 0x5C #ifndef SHA256_BLOCK_SIZE #define SHA256_BLOCK_SIZE 64 #endif #define SHA256_OUTPUT_SIZE 32 static void reverse_bytes(uint8_t *bytes, size_t length) { size_t i; for (i = 0; i < length/2; i++) { uint8_t tmp = bytes[i]; bytes[i] = bytes[length-1-i]; bytes[length-1-i] = tmp; } } static void hmac_sha256(uint8_t *data, size_t length, const uint8_t *key, uint8_t *output, size_t output_length) { uint8_t sha256_block[SHA256_BLOCK_SIZE]; uint8_t sha256_output[SHA256_OUTPUT_SIZE]; size_t i; sha256_context_t inner_hash, outer_hash; sha256_init(&inner_hash); sha256_init(&outer_hash); for (i = 0; i < SHA256_BLOCK_SIZE; i++) sha256_block[i] = key[i] ^ OPAD; sha256_update (&outer_hash, sha256_block, SHA256_BLOCK_SIZE); for (i = 0; i < SHA256_BLOCK_SIZE; i++) sha256_block[i] = key[i] ^ IPAD; sha256_update (&inner_hash, sha256_block, SHA256_BLOCK_SIZE); sha256_update (&inner_hash, data, length); sha256_final (&inner_hash, sha256_output); //reverse_bytes (sha256_output, SHA256_OUTPUT_SIZE); sha256_update (&outer_hash, sha256_output, SHA256_OUTPUT_SIZE); sha256_final (&outer_hash, sha256_output); //reverse_bytes (sha256_output, SHA256_OUTPUT_SIZE); memcpy(output, sha256_output, output_length); } static void gen_data(uint8_t *into, size_t length) { size_t i; for (i = 0; i < length; i++) { into[i] = rand(); } } static const uint8_t key_buffer[64] = { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; static void test_hmac() { RavelKey key = { .key_id = 0, .buffer = key_buffer, .length = sizeof(key_buffer) }; uint8_t *buffer = malloc(1024 + 16); uint8_t mac_1[16], *mac_2; int i, j; static const uint8_t first_packet[] = { 3, 1, 0, 0, 0, 0, 42 }; memcpy(buffer, first_packet, sizeof(first_packet)); ravel_crypto_apply_mac (buffer, sizeof(first_packet), sizeof(first_packet), &key); fprintf (stderr, "\nWolfcrypt: "); for (j = 0; j < 16; j++) { fprintf(stderr, "%x", buffer[sizeof(first_packet) + j]); } hmac_sha256 (buffer, sizeof (first_packet), key.buffer, mac_1, 16); fprintf (stderr, "\nOur: "); for (j = 0; j < 16; j++) { fprintf(stderr, "%x", mac_1[j]); } fprintf (stderr, "\n"); for (i = 0; i < 100000; i++) { gen_data(buffer, 1024); // first the wolfssl implementation ravel_crypto_apply_mac (buffer, 1024, 1024, &key); mac_2 = buffer+1024; // then our implementation hmac_sha256 (buffer, 1024, key.buffer, mac_1, 16); if (memcmp(mac_1, mac_2, 16) != 0) { fprintf(stderr, "Found problem!\nBuffer: "); for (j = 0; j < 1024; j++) { fprintf(stderr, "%x", buffer[j]); } fprintf (stderr, "\nWolfcrypt: "); for (j = 0; j < 16; j++) { fprintf(stderr, "%x", mac_2[j]); } fprintf (stderr, "\nOur: "); for (j = 0; j < 16; j++) { fprintf(stderr, "%x", mac_1[j]); } fprintf (stderr, "\n"); break; } } free(buffer); } static void test_sha() { uint8_t *buffer = malloc(1024 + 16); uint8_t hash_1[32], hash_2[32]; int i, j; for (i = 0; i < 100000; i++) { gen_data(buffer, 1024); // first the wolfssl implementation Sha256 sha; wc_InitSha256(&sha); wc_Sha256Update(&sha, buffer, 1024); wc_Sha256Final(&sha, hash_1); // then our implementation sha256_context_t lib_hash; sha256_init(&lib_hash); sha256_update (&lib_hash, buffer, 1024); sha256_final(&lib_hash, hash_2); if (memcmp(hash_1, hash_2, 32) != 0) { fprintf(stderr, "Found problem!\nBuffer: "); for (j = 0; j < 1024; j++) { fprintf(stderr, "%x", buffer[j]); } fprintf (stderr, "\nWolfcrypt: "); for (j = 0; j < 32; j++) { fprintf(stderr, "%x", hash_1[j]); } fprintf (stderr, "\nLib: "); for (j = 0; j < 32; j++) { fprintf(stderr, "%x", hash_2[j]); } fprintf (stderr, "\n"); break; } } free(buffer); } int main() { fprintf(stderr, "Test SHA\n"); test_sha(); fprintf(stderr, "Test HMAC\n"); test_hmac(); }
2.515625
3
2024-11-18T22:23:51.164738+00:00
2020-01-29T13:25:31
b650b94aee01b9e1fec772ab9229135894193b56
{ "blob_id": "b650b94aee01b9e1fec772ab9229135894193b56", "branch_name": "refs/heads/master", "committer_date": "2020-01-29T13:25:31", "content_id": "4277bb825096f51d4064cfe17dba153bf11421bd", "detected_licenses": [ "MIT" ], "directory_id": "28072067ba17e990b2f442297f544b3c0e067d35", "extension": "c", "filename": "STACK.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 236986130, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1403, "license": "MIT", "license_type": "permissive", "path": "/STACK.c", "provenance": "stackv2-0115.json.gz:76038", "repo_name": "deadMan5357/C_projects", "revision_date": "2020-01-29T13:25:31", "revision_id": "5284f51e7adc41b767ca69be1cc50946b6077f4d", "snapshot_id": "fec42fa83d593e27355dccabff72d8ff00133629", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/deadMan5357/C_projects/5284f51e7adc41b767ca69be1cc50946b6077f4d/STACK.c", "visit_date": "2020-12-23T01:10:08.245952" }
stackv2
#include<stdio.h> #define size 100 struct stack { int a[size]; int top; }; struct stack s; void push(); void pop(); void display(); void isempty(); void isfull(); int main() { int ch=99; s.top=-1; while(ch!=0) { printf("\n1.pushing \n2.popping \n3.display \n0.exit \n"); scanf("%d",&ch); switch(ch) { case 1: isfull(); push(); display(); break; case 2: isempty(); pop(); display(); break; case 3: display(); break; } } return(0); } void isfull() { if(s.top==size-1) printf("insertion cannot be done\n"); } void isempty() { if(s.top==-1) printf("deletion not possible\n"); } void push() { int a; if(s.top==size-1) printf("Stack is full\n"); else { printf("enter the number to be pushed\n"); scanf("%d",&a); s.top=s.top+1; s.a[s.top] = a; } return; } void pop() { int a; a=s.a[s.top]; printf("popped element is %d\n",a); s.top=s.top-1; return; } void display() { int i; if(s.top==-1) printf("stack is empty\n"); else { printf("stack elements are\n"); for(i=s.top;i>=0;i--) printf("%d\t",s.a[i]); } }
3.75
4
2024-11-18T22:23:52.877271+00:00
2009-08-23T20:23:41
5c43733dcc4700add009ff5b34825ab4f9eca5a1
{ "blob_id": "5c43733dcc4700add009ff5b34825ab4f9eca5a1", "branch_name": "refs/heads/master", "committer_date": "2009-08-23T20:23:41", "content_id": "8d3d0815240e8bd7a94d17c0cbd5118bd08a8ca5", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "f6b07febbc266f90e22c228de88214fe496b9eaf", "extension": "c", "filename": "mod_instantmirror.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 221278, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5647, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/im1/lighttpd-1.4.23/src/mod_instantmirror.c", "provenance": "stackv2-0115.json.gz:76427", "repo_name": "atulagrwl/InstantMirror", "revision_date": "2009-08-23T20:23:41", "revision_id": "2711c313b580e0e4f8246437eec8cf2eb61f521d", "snapshot_id": "be3ddd12e169e5242b2a4ec37094c203f4796b79", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/atulagrwl/InstantMirror/2711c313b580e0e4f8246437eec8cf2eb61f521d/im1/lighttpd-1.4.23/src/mod_instantmirror.c", "visit_date": "2021-01-18T14:46:11.160581" }
stackv2
#include <ctype.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include "base.h" #include "log.h" #include "buffer.h" #include "plugin.h" #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #define SOCK_PATH "../../socketfd" /** * this is a instantmirror for a lighttpd plugin * * */ /* plugin config for all request/connections */ typedef struct { array *match; } plugin_config; typedef struct { PLUGIN_DATA; buffer *match_buf; plugin_config **config_storage; plugin_config conf; } plugin_data; typedef struct { enum { REWRITE_STATE_UNSET, REWRITE_STATE_FINISHED} state; int loops; } handler_ctx; static handler_ctx * handler_ctx_init() { handler_ctx * hctx; hctx = calloc(1, sizeof(*hctx)); hctx->state = REWRITE_STATE_UNSET; hctx->loops = 0; return hctx; } static void handler_ctx_free(handler_ctx *hctx) { free(hctx); } /* init the plugin data */ INIT_FUNC(mod_instantmirror_init) { plugin_data *p; p = calloc(1, sizeof(*p)); p->match_buf = buffer_init(); return p; } /* detroy the plugin data */ FREE_FUNC(mod_instantmirror_free) { plugin_data *p = p_d; UNUSED(srv); if (!p) return HANDLER_GO_ON; if (p->config_storage) { size_t i; for (i = 0; i < srv->config_context->used; i++) { plugin_config *s = p->config_storage[i]; if (!s) continue; array_free(s->match); free(s); } free(p->config_storage); } buffer_free(p->match_buf); free(p); return HANDLER_GO_ON; } /* handle plugin config and check values */ SETDEFAULTS_FUNC(mod_instantmirror_set_defaults) { plugin_data *p = p_d; size_t i = 0; config_values_t cv[] = { { "instantmirror.array", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 0 */ { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET } }; if (!p) return HANDLER_ERROR; p->config_storage = calloc(1, srv->config_context->used * sizeof(specific_config *)); for (i = 0; i < srv->config_context->used; i++) { plugin_config *s; s = calloc(1, sizeof(plugin_config)); s->match = array_init(); cv[0].destination = s->match; p->config_storage[i] = s; if (0 != config_insert_values_global(srv, ((data_config *)srv->config_context->data[i])->value, cv)) { return HANDLER_ERROR; } } return HANDLER_GO_ON; } #define PATCH(x) \ p->conf.x = s->x; static int mod_instantmirror_patch_connection(server *srv, connection *con, plugin_data *p) { size_t i, j; plugin_config *s = p->config_storage[0]; PATCH(match); /* skip the first, the global context */ for (i = 1; i < srv->config_context->used; i++) { data_config *dc = (data_config *)srv->config_context->data[i]; s = p->config_storage[i]; /* condition didn't match */ if (!config_check_cond(srv, con, dc)) continue; /* merge config */ for (j = 0; j < dc->value->used; j++) { data_unset *du = dc->value->data[j]; if (buffer_is_equal_string(du->key, CONST_STR_LEN("instantmirror.array"))) { PATCH(match); } } } return 0; } #undef PATCH URIHANDLER_FUNC(mod_rewrite_con_reset) { plugin_data *p = p_d; UNUSED(srv); if (con->plugin_ctx[p->id]) { handler_ctx_free(con->plugin_ctx[p->id]); con->plugin_ctx[p->id] = NULL; } return HANDLER_GO_ON; } URIHANDLER_FUNC(mod_instantmirror_uri_handler) { struct sockaddr_un remote; int s,t,len; char path[100], i[2]; handler_ctx *hctx; plugin_data *p = p_d; if (con->plugin_ctx[p->id]) { hctx = con->plugin_ctx[p->id]; if (hctx->loops++ > 100) { log_error_write(srv, __FILE__, __LINE__, "s", "ENDLESS LOOP IN rewrite-rule DETECTED ... aborting request, perhaps you want to use url.rewrite-once instead of url.rewrite-repeat"); return HANDLER_ERROR; } if (hctx->state == REWRITE_STATE_FINISHED) return HANDLER_GO_ON; } UNUSED(srv); log_error_write(srv, __FILE__, __LINE__, "s s", con->uri.path->ptr, "-- handling file as instantmirror file"); if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } remote.sun_family = AF_UNIX; strcpy(remote.sun_path, SOCK_PATH); len = strlen(remote.sun_path) + sizeof(remote.sun_family); if (connect(s, (struct sockaddr *)&remote, len) == -1) { perror("connect"); exit(1); } log_error_write(srv, __FILE__, __LINE__, "s s", con->uri.path->ptr, "-- handling file as instantmirror file CONNECTED"); if (send(s, con->uri.path->ptr, strlen(con->uri.path->ptr)+1, 0) == -1) { perror("send"); exit(1); } if(recv(s, i, 2, 0) == -1) { perror("recv i"); exit(1); } if(strcmp(i,"0") == 0) return HANDLER_GO_ON; if(recv(s, path, 100, 0) == -1) { perror("recv"); exit(1); } log_error_write(srv, __FILE__, __LINE__, "s s", path, "-- handling file as instantmirror file AFTER CONNECTED"); buffer_reset(con->request.uri); buffer_append_string(con->request.uri,path); close(s); if (con->plugin_ctx[p->id] == NULL) { hctx = handler_ctx_init(); con->plugin_ctx[p->id] = hctx; } else { hctx = con->plugin_ctx[p->id]; } hctx->state = REWRITE_STATE_FINISHED; return HANDLER_COMEBACK; } /* this function is called at dlopen() time and inits the callbacks */ int mod_instantmirror_plugin_init(plugin *p) { p->version = LIGHTTPD_VERSION_ID; p->name = buffer_init_string("instantmirror"); p->init = mod_instantmirror_init; p->handle_uri_clean = mod_instantmirror_uri_handler; p->set_defaults = mod_instantmirror_set_defaults; p->cleanup = mod_instantmirror_free; p->connection_reset = mod_rewrite_con_reset; p->data = NULL; return 0; }
2.046875
2
2024-11-18T22:23:53.086914+00:00
2015-02-11T17:46:49
a2a42409102db7941979cb316a30aaa3003a6c32
{ "blob_id": "a2a42409102db7941979cb316a30aaa3003a6c32", "branch_name": "refs/heads/master", "committer_date": "2015-02-11T17:46:49", "content_id": "ebabf49bebc765e6727e68cb20440e7a5c8ed3d5", "detected_licenses": [ "MIT" ], "directory_id": "7e8572ca863a894946981793de1e0ff8acf32673", "extension": "c", "filename": "fifo.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 30546377, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2102, "license": "MIT", "license_type": "permissive", "path": "/fifo.c", "provenance": "stackv2-0115.json.gz:76556", "repo_name": "futr/megax8libs", "revision_date": "2015-02-11T17:46:49", "revision_id": "8b1ab722cae3b31127399f3c7700701e3ee4a9cc", "snapshot_id": "bc930ff9e3f1806a45765d1aee7dc968f0c472eb", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/futr/megax8libs/8b1ab722cae3b31127399f3c7700701e3ee4a9cc/fifo.c", "visit_date": "2021-01-15T11:49:08.373628" }
stackv2
#include "fifo.h" void fifo_init( FIFO *fifo, void *data, size_t data_size, size_t pad, size_t length ) { /* 初期化とフラッシュ */ fifo->data = data; fifo->data_size = data_size; fifo->length = length; fifo->pad = pad; fifo->end = data + ( length - 1 ) * ( pad + data_size ); fifo->level = 0; /* ポインター初期化 */ fifo->w = data; fifo->r = data; } char fifo_read( FIFO *fifo, void *dest ) { /* 読み込み */ /* 空なら失敗 */ if ( fifo->level == 0 ) { return 0; } /* 読み込み */ memcpy( dest, fifo->r, fifo->data_size ); /* ポインターをすすめる */ if ( fifo->r < fifo->end ) { /* すすめる */ fifo->r += fifo->pad + fifo->data_size; } else { /* 先頭に戻る */ fifo->r = fifo->data; } fifo->level--; return 1; } char fifo_write( FIFO *fifo, void *source ) { /* 書き込み */ unsigned char *next_w; /* 次の座標を計算 */ if ( fifo->w < fifo->end ) { next_w = fifo->w + fifo->pad + fifo->data_size; } else { next_w = fifo->data; } /* 書き込み ( 仮にオーバーフローしていても書き込む ) */ memcpy( fifo->w, source, fifo->data_size ); /* 読み込みに追いついてなければ進む */ if ( next_w != fifo->r ) { fifo->w = next_w; } /* レベル制御 */ if ( fifo->level < fifo->length ) { fifo->level++; } return 1; } char fifo_can_read( FIFO *fifo ) { /* 読み込めるか */ if ( fifo->level ) { return 1; } else { return 0; } } char fifo_can_write( FIFO *fifo ) { /* 書き込めるか */ if ( fifo->level < fifo->length ) { return 1; } else { return 0; } } size_t fifo_level( FIFO *fifo ) { /* 現在のデーター数を返す */ return fifo->level; } void fifo_clear( FIFO *fifo ) { /* Clear fifo data */ fifo->level = 0; fifo->r = fifo->data; fifo->w = fifo->data; }
3.09375
3
2024-11-18T22:23:53.148012+00:00
2019-12-09T07:20:01
097997cfe45ada23394bf653b003705e66822237
{ "blob_id": "097997cfe45ada23394bf653b003705e66822237", "branch_name": "refs/heads/master", "committer_date": "2019-12-09T07:20:01", "content_id": "48d001f585d34967d607463f3951c9d0efa3b7c6", "detected_licenses": [ "MIT" ], "directory_id": "1aef565eaa1c3cebc1876a72bbb741ef7c5014dc", "extension": "c", "filename": "simple_test.c", "fork_events_count": 0, "gha_created_at": "2019-11-01T17:22:27", "gha_event_created_at": "2019-12-08T04:13:38", "gha_language": "C", "gha_license_id": null, "github_id": 219031171, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2676, "license": "MIT", "license_type": "permissive", "path": "/test/win/x86/simple_test.c", "provenance": "stackv2-0115.json.gz:76687", "repo_name": "spartajet/sensor", "revision_date": "2019-12-09T07:20:01", "revision_id": "79e4c4652abca0dc2522cda36eb7bb9876a04785", "snapshot_id": "91a48845ccf9b860ce89780c80ccdef130a31ce0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/spartajet/sensor/79e4c4652abca0dc2522cda36eb7bb9876a04785/test/win/x86/simple_test.c", "visit_date": "2020-09-01T18:55:57.718891" }
stackv2
// // Created by guoxi on 2019/11/1. // #include <stdio.h> #include <string.h> #include "libserialport.h" #include <windows.h> const char *desired_port = "COM3"; struct sp_port *port; enum sp_return; void list_ports() { int i; struct sp_port **ports; enum sp_return error = sp_list_ports(&ports); if (error == SP_OK) { for (i = 0; ports[i]; i++) { printf("Found port: '%s'\n", sp_get_port_name(ports[i])); } sp_free_port_list(ports); } else { printf("No serial devices detected\n"); } printf("\n"); } void parse_serial(unsigned char *byte_buff, int byte_num) { int i = 0; for (i = 0; i < byte_num; i++) { if (byte_buff[i] == 0xA5) { if ((byte_num - i) < 35) //小于一包数据不处理 { return; } if (byte_buff[i + 35] != 0x0D) //包最后一字节不是0x0D { continue; } float SerialData[8]; memcpy(&SerialData[0], &byte_buff[i + 1], 32); printf("Time: %f, Channel1: %f,Channel2: %f,Channel3: %f,Channel4: %f,Channel5: %f," "Channel5: %f, Temperature: %f\n", SerialData[0], SerialData[1], SerialData[2], SerialData[3], SerialData[4], SerialData[5], SerialData[6], SerialData[7]); i += 35; } } } int main(int argc, char *argv[]) { printf("start\n"); list_ports(); printf("Opening port '%s' \n", desired_port); enum sp_return error = sp_get_port_by_name(desired_port, &port); if (error == SP_OK) { error = sp_open(port, SP_MODE_READ_WRITE); printf("Port '%s' Opened\n", desired_port); if (error == SP_OK) { sp_set_baudrate(port, 921600); sp_set_parity(port, SP_PARITY_NONE); sp_set_bits(port, 8); sp_set_stopbits(port, 1); while (1) { Sleep(200); // can do something else in mean time int bytes_waiting = sp_input_waiting(port);//输入端口等待 if (bytes_waiting > 0) { printf("Bytes waiting %i\n", bytes_waiting); char byte_buff[512]; int byte_num = 0; byte_num = sp_nonblocking_read(port, byte_buff, 512); parse_serial(byte_buff, byte_num); } fflush(stdout); } sp_close(port); } else { printf("Error opening serial device\n"); } } else { printf("Error finding serial device\n"); } return 0; }
2.84375
3
2024-11-18T22:23:54.443557+00:00
2018-12-18T09:00:51
a52fa17bf3b27e936763871eaba52e64c0e76d33
{ "blob_id": "a52fa17bf3b27e936763871eaba52e64c0e76d33", "branch_name": "refs/heads/master", "committer_date": "2018-12-18T09:00:51", "content_id": "df2c14b30b92f09dcb8b0a608f6247fd0c4429b1", "detected_licenses": [ "MIT" ], "directory_id": "d55b1559b106f561c3ea475e93c2ecc06849fdd1", "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": 293802422, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3710, "license": "MIT", "license_type": "permissive", "path": "/util.c", "provenance": "stackv2-0115.json.gz:77331", "repo_name": "iamsubhranil/The8085_v2", "revision_date": "2018-12-18T09:00:51", "revision_id": "68fc264f2501e9e8c12559e595684dcbfb7fcf21", "snapshot_id": "40b95eaede2b7f785bd197cda6df5ea9f586761e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/iamsubhranil/The8085_v2/68fc264f2501e9e8c12559e595684dcbfb7fcf21/util.c", "visit_date": "2023-03-18T03:07:00.778614" }
stackv2
#include <stdio.h> #include "common.h" #include "display.h" #include "util.h" char *readFile(const char *path) { FILE *file = fopen(path, "rb"); if(file == NULL) { perr("Could not open file \"%s\".\n", path); return NULL; } fseek(file, 0L, SEEK_END); size_t fileSize = ftell(file); rewind(file); char *buffer = (char *)malloc(fileSize + 1); if(buffer == NULL) { perr("Not enough memory to read \"%s\".\n", path); return NULL; } size_t bytesRead = fread(buffer, sizeof(char), fileSize, file); if(bytesRead < fileSize) { perr("Could not read file \"%s\".\n", path); return NULL; } buffer[bytesRead] = '\0'; fclose(file); return buffer; } bool parse_hex_byte(const char *str, u8 *store) { char *end = NULL; u32 val; val = strtol(str, &end, 16); if(*end != 0) { perr("Bad byte '%s'!", str); return 0; } if(val > 0xff) { perr("Byte out of range : '%s'!", str); return 0; } *store = val; return 1; } bool parse_hex_16(const char *str, u16 *store) { char *end = NULL; u32 addr; addr = strtol(str, &end, 16); if(*end != 0) { perr("Bad address '%s'!", str); return 0; } if(addr > 0xffff) { perr("Address out of range : '%s'!", str); return 0; } *store = addr; return 1; } // clang-format off int get_string_index(Keyword *keywords, siz numKeywords, const char *string, siz length) { siz start = 0, end = 0; // Find the initial boundary while(start < numKeywords && // the array is not out of bounds and (string[0] > keywords[start].str[0] // ( there are still letters to come or || (string[0] == keywords[start].str[0] // ( this is the required letter and && length != keywords[start].length))) { // the length doesn't match)) start++; } if(start == numKeywords // array exhausted or || string[0] != keywords[start].str[0]) // this is not the initial letter that was searched return -1; end = start; // Find the terminate boundary while(end < numKeywords // the array is not out of bounds and && keywords[end].str[0] == string[0] // the letters match and /*&& keywords[end].length == length*/) // the lengths match end++; siz temp = start, matching = 1; while(temp < end && matching < length) { // the search is in boundary and not all letters have been checked if(keywords[temp].str[matching] == string[matching]) // if: present letter matches matching++; // then: check for the next letter else{ // else: present letter doesn't match temp++; // so: check for the next word while(temp < end && keywords[temp].length != length) temp++; } } if(matching == length) // all letters have matched return temp; return -1; } // clang-format on // Assumes 0 <= max <= RAND_MAX // Returns in the closed interval [0, max] i64 random_at_most(i64 max) { i64 // max <= RAND_MAX < ULONG_MAX, so this is okay. num_bins = max + 1, num_rand = (i64)RAND_MAX + 1, bin_size = num_rand / num_bins, defect = num_rand % num_bins; i64 x; do { x = random(); } // This is carefully written not to overflow while(num_rand - defect <= (i64)x); // Truncated division is intentional return x / bin_size; }
2.6875
3
2024-11-18T22:23:58.097777+00:00
2017-06-21T17:18:32
c8568e00e5e9b6550e042fc0387dbbbcc09f9b34
{ "blob_id": "c8568e00e5e9b6550e042fc0387dbbbcc09f9b34", "branch_name": "refs/heads/master", "committer_date": "2017-06-21T17:18:32", "content_id": "a71fbdc706f36a72009298f81889ae4994227655", "detected_licenses": [ "Apache-2.0" ], "directory_id": "5e7f6461f1677a5fa449b6abd7f4a735f864e5dd", "extension": "c", "filename": "json_parser.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 70306015, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 15476, "license": "Apache-2.0", "license_type": "permissive", "path": "/lib/format/json/json_parser.c", "provenance": "stackv2-0115.json.gz:77460", "repo_name": "ozdevguy/C-General-Library", "revision_date": "2017-06-21T17:18:32", "revision_id": "8e2cc206604e5c4f13df6e9c3e388b5902d00d9a", "snapshot_id": "d4a0b0d1cce55235212dbda4e55f705dd46ea6a3", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ozdevguy/C-General-Library/8e2cc206604e5c4f13df6e9c3e388b5902d00d9a/lib/format/json/json_parser.c", "visit_date": "2020-05-23T08:10:11.300975" }
stackv2
/* ozdevguy | C General Libraries Copyright 2016 Bobby Crawford (ozdevguy) 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. json_parser.c ======================================================================== */ /* INTERNAL OPERATIONS */ json_object* int_json_parse_object(json_obj_parser* parser, json_parse_error* error); //Eliminate whitespace before a variable name. bool int_json_parse_var_beg_ws(json_obj_parser* parser, json_parse_error* error){ utf8_char* current_char; while((current_char = _string_get_next(parser->json_string))){ if(current_char->value != 32) break; } if(!current_char){ error->code = JSON_ERROR_STRING_TERMINATED; error->line = parser->json_string->iter_pos - 1; return false; } else if(current_char->value != 34){ error->code = JSON_ERROR_INVALID_SYNTAX; error->line = parser->json_string->iter_pos - 1; return false; } _string_iterator_rewind(parser->json_string); return true; } //Eliminate general whitespace. void int_json_parse_elim_ws(json_obj_parser* parser, json_parse_error* error){ utf8_char* current_char; while((current_char = _string_get_next(parser->json_string))){ if(current_char->value != 32) break; } _string_iterator_rewind(parser->json_string); } //Return variable name. string* int_json_parse_var_name(json_obj_parser* parser, json_parse_error* error){ string* var_name; utf8_char* current_char; var_name = _string_new(parser->ctx); _string_get_next(parser->json_string); while((current_char = _string_get_next(parser->json_string))){ if(current_char->value == 92) _string_append_fchar(var_name, _string_get_next(parser->json_string)); else if(current_char->value == 34) break; else _string_append_fchar(var_name, current_char); } //Check the string. if(!var_name->length){ error->code = JSON_ERROR_INVALID_NAME; error->line = parser->json_string->iter_pos - 1; _string_delete(var_name); return 0; } else if(!current_char){ error->code = JSON_ERROR_STRING_TERMINATED; error->line = parser->json_string->iter_pos - 1; _string_delete(var_name); return 0; } return var_name; } //Check name-value separator. bool int_json_parse_check_sep(json_obj_parser* parser, json_parse_error* error){ utf8_char* current_char; bool separator_found = false; while((current_char = _string_get_next(parser->json_string))){ if(current_char->value == 58) separator_found = true; else if(current_char->value != 32) break; } if(!separator_found){ error->code = JSON_ERROR_INVALID_SEPARATOR; error->line = parser->json_string->iter_pos - 1; return false; } else if(!current_char){ error->code = JSON_ERROR_STRING_TERMINATED; error->line = parser->json_string->iter_pos - 1; return false; } _string_iterator_rewind(parser->json_string); return true; } //Check variable data type. uint8_t int_json_parse_var_type(json_obj_parser* parser, json_parse_error* error){ utf8_char* current_char; current_char = _string_get_next(parser->json_string); _string_iterator_rewind(parser->json_string); //String data type. if(current_char->value == 34) return JSON_TYPE_STRING; //This is a scalar type. if((current_char->value > 47 && current_char->value < 58 ) || current_char->value == 46 || current_char->value == 45) return JSON_TYPE_SCALAR; //This is a character type. if(current_char->value == 39) return JSON_TYPE_CHAR; //This is a boolean type. if(current_char->value == 84 || current_char->value == 116 || current_char->value == 70 || current_char->value == 102) return JSON_TYPE_BOOL; //This is an object type. if(current_char->value == 123) return JSON_TYPE_OBJECT; //This is an array type. if(current_char->value == 91) return JSON_TYPE_ARRAY; //This is a null type. if(current_char->value == 78 || current_char->value == 110) return JSON_TYPE_NULL; error->code = JSON_ERROR_INVALID_TYPE; error->line = parser->json_string->iter_pos - 1; return JSON_TYPE_UNDEFINED; } json_item* int_json_parse_var_type_string(json_obj_parser* parser, json_parse_error* error){ json_item* item; utf8_char* current_char; string* value; current_char = _string_get_next(parser->json_string); value = _string_new(parser->ctx); while((current_char = _string_get_next(parser->json_string))){ if(current_char->value == 92) _string_append_fchar(value, _string_get_next(parser->json_string)); else if(current_char->value == 34) break; else _string_append_fchar(value, current_char); } if(!current_char){ error->code = JSON_ERROR_STRING_TERMINATED; error->line = parser->json_string->iter_pos - 1; _string_delete(value); return 0; } item = allocate(parser->ctx, sizeof(json_item)); item->ctx = parser->ctx; item->type = JSON_TYPE_STRING; item->data = value; return item; } json_item* int_json_parse_var_type_scalar(json_obj_parser* parser, json_parse_error* error){ size_t s; char* temp; double* d_ptr; long* l_ptr; json_item* item; utf8_char* current_char; string* value; bool is_float = false; bool invalid_char = false; value = _string_new(parser->ctx); current_char = _string_get_next(parser->json_string); if(current_char->value == 45) _string_append_fbytes(value, "-"); else _string_iterator_rewind(parser->json_string); while((current_char = _string_get_next(parser->json_string))){ if(current_char->value == 46 && !is_float) is_float = true; else if(current_char->value == 46) break; if((current_char->value > 47 && current_char->value < 58) || current_char->value == 46) _string_append_fchar(value, current_char); else break; } temp = _string_pull(value, &s); _string_delete(value); if(!current_char){ error->code = JSON_ERROR_STRING_TERMINATED; error->line = parser->json_string->iter_pos - 1; destroy(parser->ctx, temp); return 0; } item = allocate(parser->ctx, sizeof(json_item)); //Parse a new floating point number. if(is_float){ d_ptr = allocate(parser->ctx, sizeof(double)); *d_ptr = atof(temp); item->type = JSON_TYPE_FLOAT; item->data = d_ptr; } //Parse a new integer. else{ l_ptr = allocate(parser->ctx, sizeof(long)); *l_ptr = atol(temp); item->type = JSON_TYPE_INT; item->data = l_ptr; } destroy(parser->ctx, temp); _string_iterator_rewind(parser->json_string); return item; } json_item* int_json_parse_var_type_bool(json_obj_parser* parser, json_parse_error* error){ json_item* item; utf8_char* current_char; bool valid = false; size_t tpos; size_t fpos; item = allocate(parser->ctx, sizeof(json_item)); item->type = JSON_TYPE_BOOL; _string_set_ci(parser->json_string, true); tpos = _string_position_fbytes(parser->json_string, "true", parser->json_string->iter_pos); if(tpos == parser->json_string->iter_pos){ parser->json_string->iter_pos += 4; valid = true; item->data = (void*)1; } fpos = _string_position_fbytes(parser->json_string, "false", parser->json_string->iter_pos); if(fpos == parser->json_string->iter_pos){ parser->json_string->iter_pos += 5; valid = true; item->data = (void*)0; } if(!valid){ error->code = JSON_ERROR_INVALID_TYPE; error->line = parser->json_string->iter_pos; destroy(parser->ctx, item); return 0; } return item; } json_item* int_json_parse_var_type_object(json_obj_parser* parser, json_parse_error* error){ json_item* item; item = allocate(parser->ctx, sizeof(json_item)); item->type = JSON_TYPE_OBJECT; return item; } json_item* _int_json_parse_var_type_array(json_obj_parser* parser, json_parse_error* error){ json_item* item; item = allocate(parser->ctx, sizeof(json_item)); item->type = JSON_TYPE_ARRAY; return item; } //Create an item from the given type. json_item* int_json_create_item(json_obj_parser* parser, json_parse_error* error, uint8_t var_type){ json_item* item; //Now, get the data based on the variable type. if(var_type == JSON_TYPE_STRING){ if(!(item = int_json_parse_var_type_string(parser, error))) return 0; return item; } if(var_type == JSON_TYPE_SCALAR){ if(!(item = int_json_parse_var_type_scalar(parser, error))) return 0; return item; } if(var_type == JSON_TYPE_OBJECT){ if(!(item = int_json_parse_var_type_object(parser, error))) return 0; return item; } if(var_type == JSON_TYPE_BOOL){ if(!(item = int_json_parse_var_type_bool(parser, error))) return 0; return item; } if(var_type == JSON_TYPE_ARRAY){ if(!(item = _int_json_parse_var_type_array(parser, error))) return 0; return item; } } //Parse the next variable... json_item* int_json_parse_variable(json_obj_parser* parser, string** var_name, json_parse_error* error){ uint8_t var_type; //First, we need to eliminate whitespace before the variable name. if(!int_json_parse_var_beg_ws(parser, error)) return 0; //Now, we need to get our variable name. if(!(*var_name = int_json_parse_var_name(parser, error))) return 0; //Ensure a proper name-value separator has been used. if(!int_json_parse_check_sep(parser, error)) return 0; //Check the variable type. if(!(var_type = int_json_parse_var_type(parser, error))) return 0; return int_json_create_item(parser, error, var_type); } uint8_t int_json_parse_check_more(json_obj_parser* parser, json_parse_error* error){ utf8_char* current_char; while((current_char = _string_get_next(parser->json_string))){ if(current_char->value == 44) return JSON_MORE_EXISTS; if(current_char->value == 125) return JSON_END_OBJECT; if(current_char->value == 93) return JSON_END_ARRAY; if(current_char->value != 32){ error->code = JSON_ERROR_INVALID_SYNTAX; error->line = parser->json_string->iter_pos - 1; return JSON_ERROR; } } } //Parse/build a JSON array. json_array* int_json_parse_array(json_obj_parser* parser, json_parse_error* error){ standard_library_context* ctx; json_array* current_array; json_array* new_array; json_object* new_object; bool cont = true; //Parse an item. json_item* item; uint8_t type; uint8_t more_exists; //The first thing we need to do is check to make sure the current string character is an opening square bracket. if(_string_get_next(parser->json_string)->value != 91) return 0; ctx = parser->ctx; //Create a new array. current_array = allocate(ctx, sizeof(json_array)); current_array->ctx = ctx; current_array->items = _vector_new(ctx, sizeof(json_item), 2); //Get each element of the array. while(1){ //Eliminate whitespace before the next array element. int_json_parse_elim_ws(parser, error); //Get the type of the next array element. if((type = int_json_parse_var_type(parser, error)) == JSON_TYPE_UNDEFINED){ _json_array_delete(current_array); return 0; } //Get the item. if(!(item = int_json_create_item(parser, error, type))){ _json_array_delete(current_array); return 0; } if(item->type == JSON_TYPE_OBJECT){ //Next, we need to do a recursive call to parse the embedded object. if(!(new_object = int_json_parse_object(parser, error))){ destroy(ctx, item); _json_array_delete(current_array); return 0; } item->data = new_object; } else if(item->type == JSON_TYPE_ARRAY){ if(!(new_array = int_json_parse_array(parser, error))){ destroy(ctx, item); _json_array_delete(current_array); return 0; } item->data = new_array; } _vector_add(current_array->items, item); destroy(ctx, item); //Now, check to see if more variables exist in the current object. more_exists = int_json_parse_check_more(parser, error); if(more_exists == JSON_END_ARRAY) break; else if(more_exists != JSON_MORE_EXISTS){ error->code = JSON_ERROR_INVALID_SYNTAX; error->line = parser->json_string->iter_pos - 1; _json_array_delete(current_array); return 0; } } return current_array; } //Parse/build a JSON object. json_object* int_json_parse_object(json_obj_parser* parser, json_parse_error* error){ standard_library_context* ctx; json_object* current_object; json_object* new_object; json_array* new_array; //Parse a variable. string* var_name; json_item* item; uint8_t more_exists; //The first thing we need to do is check to make sure the current string character is an opening curly brace. if(_string_get_next(parser->json_string)->value != 123){ error->code = JSON_ERROR_INVALID_SYNTAX; error->line = 0; return 0; } ctx = parser->ctx; //Create a new object. current_object = allocate(ctx, sizeof(json_object)); current_object->ctx = ctx; current_object->table = _hashmap_new(ctx, 10); current_object->del_objects = true; while((item = int_json_parse_variable(parser, &var_name, error))){ if(item->type == JSON_TYPE_OBJECT){ //Next, we need to do a recursive call to parse the embedded object. if(!(new_object = int_json_parse_object(parser, error))){ destroy(ctx, item); _string_delete(var_name); _json_object_delete(current_object); return 0; } item->data = new_object; } else if(item->type == JSON_TYPE_ARRAY){ if(!(new_array = int_json_parse_array(parser, error))) { destroy(ctx, item); _string_delete(var_name); _json_object_delete(current_object); return 0; } item->data = new_array; } _hashmap_insert(current_object->table, var_name, item); _string_delete(var_name); //Now, check to see if more variables exist in the current object. more_exists = int_json_parse_check_more(parser, error); if(more_exists == JSON_END_OBJECT) break; else if(more_exists != JSON_MORE_EXISTS){ error->code = JSON_ERROR_INVALID_SYNTAX; error->line = parser->json_string->iter_pos - 1; _json_object_delete(current_object); return 0; } } if(!item){ _json_object_delete(current_object); return 0; } return current_object; } //Parse a JSON string. json_object* _json_build(standard_library_context* ctx, string* input, json_parse_error* error){ json_object* json_obj; json_obj_parser* parser; if(!ctx || !input) return 0; //First, we trim the input string. _string_trim(input); //Next, we make sure the first character is an opening curly brace. if(_string_position_fbytes(input, "{", 0)) return 0; //Reset the string iterator. _string_reset_iterator(input); //Create a new parser object. parser = allocate(ctx, sizeof(json_obj_parser)); parser->ctx = ctx; parser->json_string = input; //Parse! json_obj = int_json_parse_object(parser, error); //Destroy the parser object. destroy(ctx, parser); return json_obj; } //Parse a JSON string (char/byte array). json_object* _json_build_fbytes(standard_library_context* ctx, byte* input, json_parse_error* error){ string* new_string; json_object* json_obj; if(!ctx || !input) return 0; new_string = _string_new_fbytes(ctx, input); json_obj = _json_build(ctx, new_string, error); _string_delete(new_string); return json_obj; }
2.171875
2
2024-11-18T22:23:58.183924+00:00
2018-02-27T21:01:13
736845cc1a40fd1f508d2bb85833f3de80f74411
{ "blob_id": "736845cc1a40fd1f508d2bb85833f3de80f74411", "branch_name": "refs/heads/master", "committer_date": "2018-02-27T21:01:13", "content_id": "2765d796fd08abe6e76735967e24d422b9249a01", "detected_licenses": [ "MIT" ], "directory_id": "0b405ce28e7a7fb243676fc72e1d066c466a0c33", "extension": "c", "filename": "capshift.c", "fork_events_count": 0, "gha_created_at": "2018-02-02T14:40:16", "gha_event_created_at": "2018-02-05T14:36:50", "gha_language": "C", "gha_license_id": null, "github_id": 119992732, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12090, "license": "MIT", "license_type": "permissive", "path": "/capshift.c", "provenance": "stackv2-0115.json.gz:77592", "repo_name": "njbuch/capshift", "revision_date": "2018-02-27T21:01:13", "revision_id": "f1b867059518b2e115f53c23badb39ed6d815f90", "snapshot_id": "17a5acea2da47ca2431b5bb39be3cfc7860a84eb", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/njbuch/capshift/f1b867059518b2e115f53c23badb39ed6d815f90/capshift.c", "visit_date": "2021-05-04T21:57:32.735020" }
stackv2
#define _XOPEN_SOURCE // This is required to compile cross-platform #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "capshift.h" #include "debug.h" #define SWVERSION "v0.3 beta" #define SWRELEASEDATE "February 2018" #define DEBUG 0 // capshift (pCAP time SHIFT) shifts the timestamps in pcap files by the specified time // delta value. // Written by Foeh Mannay & Niels Jakob Buch // This software is released under the Modified BSD license. params_t *parseParams(int argc, char *argv[]){ // Returns a struct with various parameters or NULL if invalid unsigned int i = 1; char *timestring = NULL, *endptr = NULL, *datestring = NULL, *offsetstring = NULL; params_t *parameters = (params_t*)malloc(sizeof(params_t)); if(parameters == NULL) return(NULL); // Set some defaults parameters->infile = NULL; parameters->outfile = NULL; parameters->mode = 0; parameters->sign = ADD; // Look for the various flags, then store the corresponding value while(i < argc){ if(strcmp(argv[i],"-r") == 0){ parameters->infile = argv[++i]; i++; continue; } if(strcmp(argv[i],"-w") == 0){ parameters->outfile = argv[++i]; i++; continue; } if(strcmp(argv[i],"-o") == 0){ offsetstring = argv[++i]; i++; continue; } if(strcmp(argv[i],"-d") == 0){ datestring = argv[++i]; i++; continue; } if(strcmp(argv[i],"-t") == 0){ timestring = argv[++i]; i++; continue; } // If we get any unrecognised parameters just fail return(NULL); } // If the input files still aren't set, bomb if((parameters->infile == NULL) || (parameters->outfile == NULL)) return(NULL); if ((datestring != NULL) && (timestring != NULL) && (offsetstring == NULL)) { // the case of exact time AND DATE, set parameters abs, secs, usecs and sign parameters->mode = 1; // Means absolute displacement char *result = malloc(strlen(datestring)+1+strlen(timestring)+1); //+1 for the null-terminator //in real code you would check for errors in malloc here strcpy(result, datestring); strcat(result, " "); strcat(result, timestring); struct tm tm; time_t t; strptime(result, "%d-%m-%Y %H:%M:%S", &tm); tm.tm_isdst = -1; /* Not set by strptime(); tells mktime() to determine whether daylight saving time is in effect */ t = mktime(&tm); debug_print("Offset for mode 1: %d\n", (int)t); parameters->usecs = 0; parameters->secs = (int)t; return(parameters); } if ((datestring != NULL) && (timestring == NULL) && (offsetstring == NULL)) { // the case of exact date only (keep time-of-day), set parameters abs, secs, usecs and sign parameters->mode = 2; // Means absolute char *time = " 00:00:00"; char *result = malloc(strlen(datestring)+strlen(time)+1); //+1 for the null-terminator //in real code you would check for errors in malloc here strcpy(result, datestring); strcat(result, time); struct tm tm; time_t t; strptime(result, "%d-%m-%Y %H:%M:%S", &tm); tm.tm_isdst = -1; /* Not set by strptime(); tells mktime() to determine whether daylight saving time is in effect */ t = mktime(&tm); debug_print("DEBUG: Offset for mode 2: %d\n", (int)t); parameters->usecs = 0; parameters->secs = (int)t; return(parameters); } if ((datestring == NULL) && (timestring != NULL) && (offsetstring == NULL)) { // the case of exact time only, set parameters abs, secs, usecs and sign parameters->mode = 3; // Means absolute char *date = " 1-1-1970 "; char *result = malloc(strlen(date)+strlen(timestring)+1); //+1 for the null-terminator //in real code you would check for errors in malloc here strcpy(result, date); strcat(result, timestring); struct tm tm; time_t t; strptime(result, "%d-%m-%Y %H:%M:%S", &tm); tm.tm_isdst = -1; /* Not set by strptime(); tells mktime() to determine whether daylight saving time is in effect */ t = mktime(&tm); debug_print("DEBUG: Offset for mode 3: %d\n", (int)t); parameters->usecs = 0; parameters->secs = (int)t; return(parameters); } if ((datestring == NULL) && (timestring == NULL) && (offsetstring != NULL)) { debug_print("DEBUG: A relative offset is the case...%s\n", offsetstring); // the case of exact offset, set parameters abs, secs, usecs and sign parameters->mode = 4; // Means relative // If there is a + or - present, set the sign accordingly switch(offsetstring[0]){ case '-': parameters->sign = SUBTRACT; offsetstring++; break; case '+': parameters->sign = ADD; offsetstring++; break; } // If there are non-numeric characters present, bail out if((offsetstring[0] < '0') || (offsetstring[0] > '9')) return(NULL); // Grab the seconds parameters->secs = strtol(offsetstring, &endptr, 10); // Look for a decimal point, if present then grab and scale out microseconds if(endptr[0] == '.'){ offsetstring = endptr + 1; parameters->usecs = strtol(offsetstring, &endptr, 10); // scale the usecs field as appropriate for place value i = endptr - offsetstring; while(i < 6){ parameters->usecs *= 10; i++; } while(i > 6){ parameters->usecs /= 10; i--; } } else parameters->usecs = 0; if(endptr[0] != '\x00') return(NULL); return(parameters); } return(parameters); } int parse_pcap(FILE *capfile, FILE *outfile, guint32 sign, guint32 secs, guint32 usecs, guint32 mode){ char *memblock = NULL; guint32 caplen = 0; int count = 0; pcaprec_hdr_t *rechdr = NULL; int first_timestamp_found = 0; // Start parsing the capture file: rewind(capfile); clearerr(capfile); memblock = (char*)malloc(sizeof(pcap_hdr_t)); if(memblock == NULL){ printf("Insufficient memory to load capture header.\n"); return(0); } // Read the pcap header if(fread (memblock, 1, sizeof(pcap_hdr_t), capfile) != sizeof(pcap_hdr_t)){ printf("Truncated capture file header - aborting.\n"); if(memblock != NULL) free(memblock); return(0); } // Verify the magic number in the header indicates a pcap file if(((pcap_hdr_t*)memblock)->magic_number != 2712847316){ printf("\nError!\nThis is not a valid pcap file. If it has been saved as pcap-ng\nconsider converting it to original pcap format with tshark or similar.\n"); if(memblock != NULL) free(memblock); return(0); } // Allocate memory for the PCAP record header rechdr = (pcaprec_hdr_t*)malloc(sizeof(pcaprec_hdr_t)); if(rechdr == NULL){ printf("Error: unable to allocate memory for pcap record header!\n"); return(0); } // Clone the input file's header rewind(outfile); clearerr(outfile); if(fwrite(memblock, 1, sizeof(pcap_hdr_t), outfile) != sizeof(pcap_hdr_t)){ printf("Error: unable to write pcap header to output file!\n"); return(0); } // Read in each frame. while((!feof(capfile)) & (!ferror(capfile))) { free(memblock); // Get the packet record header and examine it for the packet size caplen = fread (rechdr, 1, sizeof(pcaprec_hdr_t), capfile); if(caplen != sizeof(pcaprec_hdr_t)){ if(caplen > 0) printf("Error: Truncated pcap file reading record header, %u/%lu!\n", caplen, sizeof(pcaprec_hdr_t)); break; } // Adjust timestamp as required, handling over/underflow if (first_timestamp_found == 0) { debug_print("Now seeing the first raw packet. Timestamp -> %d\n", (int)rechdr->ts_sec ); first_timestamp_found = 1; switch(mode){ case 1: // time and day fixed debug_print("Setting time and day (mode 1)\n", NULL); if ((int)rechdr->ts_sec > secs) { secs = (int)rechdr->ts_sec - secs; sign = SUBTRACT; } else { secs = secs - (int)rechdr->ts_sec; sign = ADD; } break; case 2: // date only debug_print("Setting date only (mode 2)\n", NULL); int timeofday = (int)rechdr->ts_sec % 86400; secs = secs + timeofday; if ((int)rechdr->ts_sec > secs) { secs = (int)rechdr->ts_sec - secs; sign = SUBTRACT; } else { secs = secs - (int)rechdr->ts_sec; sign = ADD; } break; case 3: // time only debug_print("Setting time only (mode 3)\n", NULL); timeofday = (int)rechdr->ts_sec % 86400; secs = (int)rechdr->ts_sec - timeofday + secs; if ((int)rechdr->ts_sec > secs) { secs = (int)rechdr->ts_sec - secs; sign = SUBTRACT; } else { secs = secs - (int)rechdr->ts_sec; sign = ADD; } break; case 4: // offset debug_print("Setting offset (mode 4)\n", NULL); break; } debug_print("Time adjustment sign:%d and value:%d", sign, secs); } if(sign == SUBTRACT){ rechdr->ts_sec -= secs; if (usecs > rechdr->ts_usec){ rechdr->ts_sec--; rechdr->ts_usec += (1000000 - usecs); } else { rechdr->ts_usec -= usecs; } } else { rechdr->ts_sec += secs; rechdr->ts_usec += usecs; if (rechdr->ts_usec > 1000000){ rechdr->ts_sec++; rechdr->ts_usec -= 1000000; } } caplen = rechdr->incl_len; memblock = malloc(caplen); if(memblock == NULL){ printf("Error: Could not allocate memory for pcap data!\n"); return(count); } // Get the actual packet data and copy it verbatim if(fread (memblock, 1, caplen, capfile) != caplen){ printf("Error: Truncated pcap file reading capture!\n"); break; } // Write the adjusted packet header if(fwrite(rechdr, 1, sizeof(pcaprec_hdr_t), outfile) != sizeof(pcaprec_hdr_t)){ printf("Error: unable to write pcap record header to output file!\n"); return(0); } // Write the packet data if(fwrite(memblock, 1, caplen, outfile) != caplen){ printf("Error: unable to write frame to output pcap file\n"); return(0); } count++; } if(rechdr != NULL) free(rechdr); return(count); } int main(int argc, char *argv[]){ // The main function basically just calls other functions to do the work. params_t *parameters = NULL; FILE *infile = NULL, *outfile = NULL; // Parse our command line parameters and verify they are usable. If not, show help. parameters = parseParams(argc, argv); if(parameters == NULL){ printf("\n\n _ _ __ _ \n"); printf(" | | (_)/ _| | \n"); printf(" ___ __ _ _ __ ___| |__ _| |_| |_ \n"); printf(" / __/ _` | '_ \\/ __| '_ \\| | _| __| \n"); printf("| (_| (_| | |_) \\__ \\ | | | | | | |_ \n"); printf(" \\___\\__,_| .__/|___/_| |_|_|_| \\__|\n"); printf(" | | \n"); printf(" |_| \n"); printf("\ncapshift: a utility to adjust the timestamps of pcap files.\n"); printf("Written by Niels Jakob Buch & Foeh Mannay.\n"); printf("Version %s, %s\n\n", SWVERSION, SWRELEASEDATE); printf("Usage:\n"); printf("%s -r inputcapfile -w outputcapfile [time option]\n\n",argv[0]); printf("Where inputcapfile is a tcpdump-style .cap file\n"); printf("outputcapfile is the file where the time-shifted version will be saved\n"); printf("[time option] is:\n"); printf(" -o offset -: offset is the number of seconds (and microseconds) to shift by (e.g. -1.5, +0.200)\n"); printf(" -d date -: where date is the day shift to, keeping the time-of-day.\n"); printf(" -t time -: where time is the time-of-day to shift to, keeping the day.\n"); printf(" -d date -t time -: where date and time is the time AND day to shift to.\n\n\n"); return(1); } // Attempt to open the input capture file for reading: infile = fopen(parameters->infile,"rb"); if (infile == NULL) { printf("\nError!\nUnable to open input capture file!\n"); return(1); } // Attempt to open the output capture file for writing: outfile = fopen(parameters->outfile, "wb"); if(outfile == NULL){ printf("Error - could not open output file!\n"); return(1); } printf("\n%d frames processed.\n", parse_pcap(infile, outfile, parameters->sign, parameters->secs, parameters->usecs, parameters->mode)); fclose(infile); fclose(outfile); return(0); }
2.703125
3
2024-11-18T22:23:58.683264+00:00
2019-09-27T21:47:32
92dac8c843087de0e6a953a901beebb79f144c86
{ "blob_id": "92dac8c843087de0e6a953a901beebb79f144c86", "branch_name": "refs/heads/master", "committer_date": "2019-09-27T21:47:32", "content_id": "f025f3bce5982d7add7fdc5d605d4eda81f33b99", "detected_licenses": [ "MIT" ], "directory_id": "f63531f304d705679a3d150bdc9d6ea6431f603e", "extension": "c", "filename": "meuC2.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 204083942, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 239, "license": "MIT", "license_type": "permissive", "path": "/meuC2.c", "provenance": "stackv2-0115.json.gz:77722", "repo_name": "LH-blip/webdesign", "revision_date": "2019-09-27T21:47:32", "revision_id": "3c00f61df01db7282a19d183b3ded669666e18de", "snapshot_id": "fb3ebccf5677b8e6eed0934adc49b15a69e60a91", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/LH-blip/webdesign/3c00f61df01db7282a19d183b3ded669666e18de/meuC2.c", "visit_date": "2020-07-09T21:04:07.626332" }
stackv2
#include <stdio.h> main () { float base, h, area; printf("escreva a base do triangulo: "); scanf("%f",&base); printf("escreva a altura do triangulo: "); scanf("%f",&h); area=(base*h); { printf("Resultado%.0f",area); } }
2.28125
2
2024-11-18T22:23:59.303728+00:00
2023-01-30T10:03:23
a978a457318901988142097972e80e071ace3ac6
{ "blob_id": "a978a457318901988142097972e80e071ace3ac6", "branch_name": "refs/heads/main", "committer_date": "2023-01-30T10:03:23", "content_id": "cc86634beff081175e6c83a2677a546f25592ba7", "detected_licenses": [ "MIT" ], "directory_id": "d0dc556f8b1d18ecbadef182bafd97b632dd3104", "extension": "c", "filename": "i2cdev.c", "fork_events_count": 36, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 315618086, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7883, "license": "MIT", "license_type": "permissive", "path": "/common/esp-idf-lib/components/i2cdev/i2cdev.c", "provenance": "stackv2-0115.json.gz:78112", "repo_name": "PacktPublishing/Internet-of-Things-with-ESP32", "revision_date": "2023-01-30T10:03:23", "revision_id": "3ada8b905e53961940511636991a839059de7cd1", "snapshot_id": "da3f2c57e2bd871b134b22841fd275c51f88d487", "src_encoding": "UTF-8", "star_events_count": 114, "url": "https://raw.githubusercontent.com/PacktPublishing/Internet-of-Things-with-ESP32/3ada8b905e53961940511636991a839059de7cd1/common/esp-idf-lib/components/i2cdev/i2cdev.c", "visit_date": "2023-02-08T13:58:32.585403" }
stackv2
/** * @file i2cdev.c * * ESP-IDF I2C master thread-safe functions for communication with I2C slave * * Copyright (C) 2018 Ruslan V. Uss <https://github.com/UncleRus> * * MIT Licensed as described in the file LICENSE */ #include <string.h> #include <freertos/FreeRTOS.h> #include <freertos/task.h> #include <esp_log.h> #include "i2cdev.h" static const char *TAG = "I2CDEV"; typedef struct { SemaphoreHandle_t lock; i2c_config_t config; bool installed; } i2c_port_state_t; static i2c_port_state_t states[I2C_NUM_MAX]; #define SEMAPHORE_TAKE(port) do { \ if (!xSemaphoreTake(states[port].lock, CONFIG_I2CDEV_TIMEOUT / portTICK_RATE_MS)) \ { \ ESP_LOGE(TAG, "Could not take port mutex %d", port); \ return ESP_ERR_TIMEOUT; \ } \ } while (0) #define SEMAPHORE_GIVE(port) do { \ if (!xSemaphoreGive(states[port].lock)) \ { \ ESP_LOGE(TAG, "Could not give port mutex %d", port); \ return ESP_FAIL; \ } \ } while (0) esp_err_t i2cdev_init() { memset(states, 0, sizeof(states)); for (int i = 0; i < I2C_NUM_MAX; i++) { states[i].lock = xSemaphoreCreateMutex(); if (!states[i].lock) { ESP_LOGE(TAG, "Could not create port mutex %d", i); return ESP_FAIL; } } return ESP_OK; } esp_err_t i2cdev_done() { for (int i = 0; i < I2C_NUM_MAX; i++) { if (!states[i].lock) continue; if (states[i].installed) { SEMAPHORE_TAKE(i); i2c_driver_delete(i); states[i].installed = false; SEMAPHORE_GIVE(i); } vSemaphoreDelete(states[i].lock); states[i].lock = NULL; } return ESP_OK; } esp_err_t i2c_dev_create_mutex(i2c_dev_t *dev) { if (!dev) return ESP_ERR_INVALID_ARG; ESP_LOGV(TAG, "[0x%02x at %d] creating mutex", dev->addr, dev->port); dev->mutex = xSemaphoreCreateMutex(); if (!dev->mutex) { ESP_LOGE(TAG, "[0x%02x at %d] Could not create device mutex", dev->addr, dev->port); return ESP_FAIL; } return ESP_OK; } esp_err_t i2c_dev_delete_mutex(i2c_dev_t *dev) { if (!dev) return ESP_ERR_INVALID_ARG; ESP_LOGV(TAG, "[0x%02x at %d] deleting mutex", dev->addr, dev->port); vSemaphoreDelete(dev->mutex); return ESP_OK; } esp_err_t i2c_dev_take_mutex(i2c_dev_t *dev) { if (!dev) return ESP_ERR_INVALID_ARG; ESP_LOGV(TAG, "[0x%02x at %d] taking mutex", dev->addr, dev->port); if (!xSemaphoreTake(dev->mutex, CONFIG_I2CDEV_TIMEOUT / portTICK_RATE_MS)) { ESP_LOGE(TAG, "[0x%02x at %d] Could not take device mutex", dev->addr, dev->port); return ESP_ERR_TIMEOUT; } return ESP_OK; } esp_err_t i2c_dev_give_mutex(i2c_dev_t *dev) { if (!dev) return ESP_ERR_INVALID_ARG; ESP_LOGV(TAG, "[0x%02x at %d] giving mutex", dev->addr, dev->port); if (!xSemaphoreGive(dev->mutex)) { ESP_LOGE(TAG, "[0x%02x at %d] Could not give device mutex", dev->addr, dev->port); return ESP_FAIL; } return ESP_OK; } inline static bool cfg_equal(const i2c_config_t *a, const i2c_config_t *b) { return a->scl_io_num == b->scl_io_num && a->sda_io_num == b->sda_io_num #if HELPER_TARGET_IS_ESP32 && a->master.clk_speed == b->master.clk_speed #elif HELPER_TARGET_IS_ESP8266 && HELPER_TARGET_VERSION > HELPER_TARGET_VERSION_ESP8266_V3_2 && a->clk_stretch_tick == b->clk_stretch_tick #endif && a->scl_pullup_en == b->scl_pullup_en && a->sda_pullup_en == b->sda_pullup_en; } static esp_err_t i2c_setup_port(const i2c_dev_t *dev) { if (dev->port >= I2C_NUM_MAX) return ESP_ERR_INVALID_ARG; esp_err_t res; if (!cfg_equal(&dev->cfg, &states[dev->port].config)) { ESP_LOGD(TAG, "Reconfiguring I2C driver on port %d", dev->port); i2c_config_t temp; memcpy(&temp, &dev->cfg, sizeof(i2c_config_t)); temp.mode = I2C_MODE_MASTER; // Driver reinstallation if (states[dev->port].installed) i2c_driver_delete(dev->port); #if HELPER_TARGET_IS_ESP32 if ((res = i2c_param_config(dev->port, &temp)) != ESP_OK) return res; if ((res = i2c_driver_install(dev->port, temp.mode, 0, 0, 0)) != ESP_OK) return res; #endif #if HELPER_TARGET_IS_ESP8266 #if HELPER_TARGET_VERSION > HELPER_TARGET_VERSION_ESP8266_V3_2 // Clock Stretch time, depending on CPU frequency temp.clk_stretch_tick = dev->timeout_ticks ? dev->timeout_ticks : I2CDEV_MAX_STRETCH_TIME; #endif if ((res = i2c_driver_install(dev->port, temp.mode)) != ESP_OK) return res; if ((res = i2c_param_config(dev->port, &temp)) != ESP_OK) return res; #endif states[dev->port].installed = true; memcpy(&states[dev->port].config, &temp, sizeof(i2c_config_t)); ESP_LOGD(TAG, "I2C driver successfully reconfigured on port %d", dev->port); } #if HELPER_TARGET_IS_ESP32 int t; if ((res = i2c_get_timeout(dev->port, &t)) != ESP_OK) return res; // Timeout cannot be 0 uint32_t ticks = dev->timeout_ticks ? dev->timeout_ticks : I2CDEV_MAX_STRETCH_TIME; if ((ticks != t) && (res = i2c_set_timeout(dev->port, ticks)) != ESP_OK) return res; ESP_LOGD(TAG, "Timeout: ticks = %d (%d usec) on port %d", dev->timeout_ticks, dev->timeout_ticks / 80, dev->port); #endif return ESP_OK; } esp_err_t i2c_dev_read(const i2c_dev_t *dev, const void *out_data, size_t out_size, void *in_data, size_t in_size) { if (!dev || !in_data || !in_size) return ESP_ERR_INVALID_ARG; SEMAPHORE_TAKE(dev->port); esp_err_t res = i2c_setup_port(dev); if (res == ESP_OK) { i2c_cmd_handle_t cmd = i2c_cmd_link_create(); if (out_data && out_size) { i2c_master_start(cmd); i2c_master_write_byte(cmd, dev->addr << 1, true); i2c_master_write(cmd, (void *)out_data, out_size, true); } i2c_master_start(cmd); i2c_master_write_byte(cmd, (dev->addr << 1) | 1, true); i2c_master_read(cmd, in_data, in_size, I2C_MASTER_LAST_NACK); i2c_master_stop(cmd); res = i2c_master_cmd_begin(dev->port, cmd, CONFIG_I2CDEV_TIMEOUT / portTICK_RATE_MS); if (res != ESP_OK) ESP_LOGE(TAG, "Could not read from device [0x%02x at %d]: %d", dev->addr, dev->port, res); i2c_cmd_link_delete(cmd); } SEMAPHORE_GIVE(dev->port); return res; } esp_err_t i2c_dev_write(const i2c_dev_t *dev, const void *out_reg, size_t out_reg_size, const void *out_data, size_t out_size) { if (!dev || !out_data || !out_size) return ESP_ERR_INVALID_ARG; SEMAPHORE_TAKE(dev->port); esp_err_t res = i2c_setup_port(dev); if (res == ESP_OK) { i2c_cmd_handle_t cmd = i2c_cmd_link_create(); i2c_master_start(cmd); i2c_master_write_byte(cmd, dev->addr << 1, true); if (out_reg && out_reg_size) i2c_master_write(cmd, (void *)out_reg, out_reg_size, true); i2c_master_write(cmd, (void *)out_data, out_size, true); i2c_master_stop(cmd); res = i2c_master_cmd_begin(dev->port, cmd, CONFIG_I2CDEV_TIMEOUT / portTICK_RATE_MS); if (res != ESP_OK) ESP_LOGE(TAG, "Could not write to device [0x%02x at %d]: %d", dev->addr, dev->port, res); i2c_cmd_link_delete(cmd); } SEMAPHORE_GIVE(dev->port); return res; } esp_err_t i2c_dev_read_reg(const i2c_dev_t *dev, uint8_t reg, void *in_data, size_t in_size) { return i2c_dev_read(dev, &reg, 1, in_data, in_size); } esp_err_t i2c_dev_write_reg(const i2c_dev_t *dev, uint8_t reg, const void *out_data, size_t out_size) { return i2c_dev_write(dev, &reg, 1, out_data, out_size); }
2.703125
3
2024-11-18T22:24:05.855331+00:00
2022-06-13T19:31:23
34443b0447c5816a981775d234a1b4a66bd0b75e
{ "blob_id": "34443b0447c5816a981775d234a1b4a66bd0b75e", "branch_name": "refs/heads/master", "committer_date": "2022-06-13T19:31:23", "content_id": "a80d6fc61b5e796caa0f8b4540b2913f95b701f4", "detected_licenses": [ "MIT" ], "directory_id": "84a6c6f1dfb1f6bab21375c7ce8cee2528af7f4b", "extension": "c", "filename": "nxtval-test.c", "fork_events_count": 5, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 127787645, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 633, "license": "MIT", "license_type": "permissive", "path": "/examples/mpi/Using_MPI/advanced/nxtval-test.c", "provenance": "stackv2-0115.json.gz:78369", "repo_name": "shawfdong/ams250", "revision_date": "2022-06-13T19:31:23", "revision_id": "34aad90e2fdd4f75ad5c245b573d46ff99dad5e9", "snapshot_id": "ad78fef2e39149663d72884b660a056d82126f5d", "src_encoding": "UTF-8", "star_events_count": 12, "url": "https://raw.githubusercontent.com/shawfdong/ams250/34aad90e2fdd4f75ad5c245b573d46ff99dad5e9/examples/mpi/Using_MPI/advanced/nxtval-test.c", "visit_date": "2022-06-17T09:02:24.102871" }
stackv2
#include "mpi.h" #include "nxtval.h" #include <stdio.h> int main( int argc, char *argv[] ) { MPI_Comm counter_comm, worker_comm; MPI_Init( &argc, &argv ); MPE_Counter_create( MPI_COMM_WORLD, &worker_comm, &counter_comm ); if (worker_comm != MPI_COMM_NULL) { /* I am one of the workers; the master doesn't exit create until MPE_Counter_free is called */ int value, rank; MPI_Comm_rank( counter_comm, &rank ); MPE_Counter_nxtval( counter_comm, &value ); printf( "[%d] received value %d\n", rank, value ); MPE_Counter_free( &worker_comm, &counter_comm ); } MPI_Finalize( ); return 0; }
2.765625
3
2024-11-18T22:24:05.938313+00:00
2020-09-26T17:07:25
e64095c3247e5ae60f9d7c09be5e0c1ba9b8b64e
{ "blob_id": "e64095c3247e5ae60f9d7c09be5e0c1ba9b8b64e", "branch_name": "refs/heads/main", "committer_date": "2020-09-26T17:07:25", "content_id": "d4c40a1a3c83b5e0ba85f626aec318f32890a9f7", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "9a6f2c81e0310f877064e2f064e6149fa3840878", "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": 121703965, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 212, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/ch18/e15/main.c", "provenance": "stackv2-0115.json.gz:78498", "repo_name": "gdonald/cpama", "revision_date": "2020-09-26T17:07:25", "revision_id": "5c6343bae106fcde053a3746467cbfe23f559b71", "snapshot_id": "c6f301f1b28352bf8bad4228d571dabc5807c76a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gdonald/cpama/5c6343bae106fcde053a3746467cbfe23f559b71/ch18/e15/main.c", "visit_date": "2021-07-23T07:39:52.222848" }
stackv2
#include <stdio.h> int main(void) { // (a) static int s; printf("s: %d\n", s); // no warning, already initialized int t; printf("t: %d\n", t); // warning: variable 't' is uninitialized return 0; }
2.78125
3
2024-11-18T22:24:06.255481+00:00
2018-10-27T12:57:55
a2af87e0dab7daa8a11abe7bcc3d434e899a3b1f
{ "blob_id": "a2af87e0dab7daa8a11abe7bcc3d434e899a3b1f", "branch_name": "refs/heads/master", "committer_date": "2018-10-27T12:57:55", "content_id": "ffff3926df85877000b24ad31680d6684c736b9d", "detected_licenses": [ "MIT" ], "directory_id": "3f7bf2a08e4c8f75b190a6d88a363bc9dda4c258", "extension": "c", "filename": "smmastmatcher.c", "fork_events_count": 18, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 59149204, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8551, "license": "MIT", "license_type": "permissive", "path": "/tests/smmastmatcher.c", "provenance": "stackv2-0115.json.gz:78629", "repo_name": "igor84/summus", "revision_date": "2018-10-27T12:57:55", "revision_id": "7ec1f42821a6dc2ada710e323106a96d8370a58d", "snapshot_id": "9787b554d7eb98828068f44d776cc8424945813d", "src_encoding": "UTF-8", "star_events_count": 249, "url": "https://raw.githubusercontent.com/igor84/summus/7ec1f42821a6dc2ada710e323106a96d8370a58d/tests/smmastmatcher.c", "visit_date": "2021-01-17T02:44:35.508556" }
stackv2
#include "smmastmatcher.h" #include <assert.h> static const char* NODES_DONT_MATCH = "Node kinds don't match"; static const char* NODES_TYPES_DONT_MATCH = "Node's types don't match"; static const char* NODES_REPRS_DONT_MATCH = "Nodes representations don't match"; static void processStatement(CuTest* tc, PSmmAstNode exStmt, PSmmAstNode gotStmt); static void processBlock(CuTest* tc, PSmmAstBlockNode exBlock, PSmmAstBlockNode gotBlock); static void assertNodeFlagsEqual(CuTest* tc, PSmmAstNode ex, PSmmAstNode got) { CuAssertUIntEquals_Msg(tc, "Ident flag doesn't match", ex->isIdent, got->isIdent); CuAssertUIntEquals_Msg(tc, "Const flag doesn't match", ex->isConst, got->isConst); CuAssertUIntEquals_Msg(tc, "BinOp flag doesn't match", ex->isBinOp, got->isBinOp); } static void assertNodesEqual(CuTest* tc, PSmmAstNode ex, PSmmAstNode got) { CuAssertIntEquals_Msg(tc, NODES_DONT_MATCH, ex->kind, got->kind); if (ex->type && got->type) { CuAssertIntEquals_Msg(tc, NODES_TYPES_DONT_MATCH, ex->type->kind, got->type->kind); } else { CuAssertPtrEquals_Msg(tc, NODES_TYPES_DONT_MATCH, ex->type, got->type); } assertNodeFlagsEqual(tc, ex, got); if (got->kind == nkSmmCast) return; if (got->token && ex->token) { CuAssertStrEquals_Msg(tc, NODES_REPRS_DONT_MATCH, ex->token->repr, got->token->repr); } else { CuAssertPtrEquals_Msg(tc, "Token presence not matched", ex->token, got->token); } } static void processExpression(CuTest* tc, PSmmAstNode exExpr, PSmmAstNode gotExpr) { assertNodesEqual(tc, exExpr, gotExpr); switch (gotExpr->kind) { case nkSmmAdd: case nkSmmFAdd: case nkSmmSub: case nkSmmFSub: case nkSmmMul: case nkSmmFMul: case nkSmmUDiv: case nkSmmSDiv: case nkSmmFDiv: case nkSmmURem: case nkSmmSRem: case nkSmmFRem: case nkSmmAndOp: case nkSmmOrOp: case nkSmmXorOp: case nkSmmEq: case nkSmmNotEq: case nkSmmGt: case nkSmmGtEq: case nkSmmLt: case nkSmmLtEq: { processExpression(tc, exExpr->left, gotExpr->left); processExpression(tc, exExpr->left, gotExpr->left); break; } case nkSmmNeg: case nkSmmNot: case nkSmmCast: { processExpression(tc, exExpr->left, gotExpr->left); break; } case nkSmmCall: { PSmmAstCallNode exCallNode = (PSmmAstCallNode)exExpr; PSmmAstCallNode gotCallNode = (PSmmAstCallNode)gotExpr; PSmmAstNode exArg = exCallNode->args; PSmmAstNode gotArg = gotCallNode->args; while (gotArg) { CuAssertPtrNotNullMsg(tc, "Got unexpected arg in call", exArg); processExpression(tc, exArg, gotArg); exArg = exArg->next; gotArg = gotArg->next; } CuAssertPtrEquals_Msg(tc, "Call args don't match", exArg, gotArg); break; } case nkSmmParam: case nkSmmIdent: case nkSmmConst: // No additional matching needed break; case nkSmmInt: CuAssertUIntEquals_Msg(tc, "Int values does not match", exExpr->token->uintVal, gotExpr->token->uintVal); break; case nkSmmFloat: CuAssertDblEquals_Msg(tc, "Float values does not match", exExpr->token->floatVal, gotExpr->token->floatVal, 0); break; case nkSmmBool: CuAssertUIntEquals_Msg(tc, "Bool values does not match", exExpr->token->boolVal, gotExpr->token->boolVal); break; default: assert(false && "Got unexpected node type in processExpression"); break; } } static void processLocalSymbols(CuTest* tc, PSmmAstDeclNode exDecl, PSmmAstDeclNode gotDecl) { while (gotDecl) { CuAssertPtrNotNullMsg(tc, "Got more global declarations than expected", exDecl); CuAssertIntEquals_Msg(tc, NODES_DONT_MATCH, exDecl->kind, gotDecl->kind); CuAssertPtrEquals_Msg(tc, NODES_TYPES_DONT_MATCH, exDecl->left->left->type, gotDecl->left->left->type); assertNodeFlagsEqual(tc, (PSmmAstNode)exDecl, (PSmmAstNode)gotDecl); assertNodesEqual(tc, exDecl->left, gotDecl->left); assertNodesEqual(tc, exDecl->left->left, gotDecl->left->left); if (gotDecl->left->left->kind == nkSmmConst) { processExpression(tc, exDecl->left->right, gotDecl->left->right); } exDecl = exDecl->nextDecl; gotDecl = gotDecl->nextDecl; } } static void processAssignment(CuTest* tc, PSmmAstNode exStmt, PSmmAstNode gotStmt) { assertNodesEqual(tc, exStmt->left, gotStmt->left); processExpression(tc, exStmt->right, gotStmt->right); } static void processReturn(CuTest* tc, PSmmAstNode exStmt, PSmmAstNode gotStmt) { if (gotStmt->left) { CuAssertPtrNotNullMsg(tc, "Got unexpected return expression", exStmt); processExpression(tc, exStmt->left, gotStmt->left); } else { CuAssertPtrEquals_Msg(tc, "No expected return expression", exStmt->left, gotStmt->left); } } static void processStatement(CuTest* tc, PSmmAstNode exStmt, PSmmAstNode gotStmt) { CuAssertPtrNotNullMsg(tc, "Got more statements than expected", exStmt); assertNodesEqual(tc, exStmt, gotStmt); switch (gotStmt->kind) { case nkSmmBlock: { PSmmAstBlockNode newExBlock = (PSmmAstBlockNode)exStmt; PSmmAstBlockNode newGotBlock = (PSmmAstBlockNode)gotStmt; CuAssertIntEquals_Msg(tc, NODES_DONT_MATCH, newExBlock->scope->kind, newGotBlock->scope->kind); processLocalSymbols(tc, newExBlock->scope->decls, newGotBlock->scope->decls); processBlock(tc, newExBlock, newGotBlock); break; } case nkSmmAssignment: processAssignment(tc, exStmt, gotStmt); break; case nkSmmDecl: assertNodesEqual(tc, exStmt->left, gotStmt->left); processAssignment(tc, exStmt->left, gotStmt->left); break; case nkSmmReturn: processReturn(tc, exStmt, gotStmt); break; default: processExpression(tc, exStmt, gotStmt); break; } } static void processBlock(CuTest* tc, PSmmAstBlockNode exBlock, PSmmAstBlockNode gotBlock) { PSmmAstNode exStmt = exBlock->stmts; PSmmAstNode gotStmt = gotBlock->stmts; while (gotStmt) { processStatement(tc, exStmt, gotStmt); exStmt = exStmt->next; gotStmt = gotStmt->next; } } static void processGlobalSymbols(CuTest* tc, PSmmAstDeclNode exDecl, PSmmAstDeclNode gotDecl) { while (gotDecl) { CuAssertPtrNotNullMsg(tc, "Got more global declarations than expected", exDecl); CuAssertIntEquals_Msg(tc, NODES_DONT_MATCH, exDecl->kind, gotDecl->kind); assertNodesEqual(tc, exDecl->left, gotDecl->left); if (gotDecl->left->kind == nkSmmFunc) { assertNodesEqual(tc, exDecl->left, gotDecl->left); PSmmAstFuncDefNode exFuncNode = (PSmmAstFuncDefNode)exDecl->left; PSmmAstFuncDefNode gotFuncNode = (PSmmAstFuncDefNode)gotDecl->left; PSmmAstParamNode exParam = exFuncNode->params; PSmmAstParamNode gotParam = gotFuncNode->params; while (gotParam) { CuAssertPtrNotNullMsg(tc, "Got more parameters than expected", exDecl); assertNodesEqual(tc, (PSmmAstNode)exParam, (PSmmAstNode)gotParam); exParam = exParam->next; gotParam = gotParam->next; } CuAssertPtrEquals_Msg(tc, "Unexpected number of parameters", exParam, gotParam); if (exFuncNode->params) { CuAssertUIntEquals_Msg(tc, "Unexpected parameters count", exFuncNode->params->count, gotFuncNode->params->count); } if (gotFuncNode->body) { CuAssertPtrNotNullMsg(tc, "Unexpected function body", exFuncNode->body); CuAssertIntEquals_Msg(tc, NODES_DONT_MATCH, exFuncNode->body->kind, gotFuncNode->body->kind); CuAssertIntEquals_Msg(tc, NODES_DONT_MATCH, exFuncNode->body->scope->kind, gotFuncNode->body->scope->kind); processLocalSymbols(tc, exFuncNode->body->scope->decls, gotFuncNode->body->scope->decls); processBlock(tc, exFuncNode->body, gotFuncNode->body); } else { CuAssertPtrEquals_Msg(tc, "No expected function body", exFuncNode->body, gotFuncNode->body); } } else { CuAssertPtrEquals_Msg(tc, NODES_TYPES_DONT_MATCH, exDecl->left->left->type, gotDecl->left->left->type); assertNodesEqual(tc, exDecl->left->left, gotDecl->left->left); CuAssertPtrNotNullMsg(tc, "Global decl must have initializer", gotDecl->left->right); if (exDecl->left->left->isConst) { processExpression(tc, exDecl->left->right, gotDecl->left->right); } } exDecl = exDecl->nextDecl; gotDecl = gotDecl->nextDecl; } } void smmAssertASTEquals(CuTest* tc, PSmmAstNode ex, PSmmAstNode got) { CuAssertIntEquals_Msg(tc, NODES_DONT_MATCH, ex->kind, got->kind); CuAssertStrEquals_Msg(tc, "Module names don't match", ex->token->repr, got->token->repr); PSmmAstBlockNode exBlock = (PSmmAstBlockNode)ex->next; PSmmAstBlockNode gotBlock = (PSmmAstBlockNode)got->next; CuAssertIntEquals_Msg(tc, NODES_DONT_MATCH, exBlock->kind, gotBlock->kind); CuAssertIntEquals_Msg(tc, NODES_DONT_MATCH, exBlock->scope->kind, gotBlock->scope->kind); processGlobalSymbols(tc, exBlock->scope->decls, gotBlock->scope->decls); processBlock(tc, exBlock, gotBlock); }
2.328125
2
2024-11-18T22:24:06.340458+00:00
2016-04-12T14:59:53
e33d3c9074d7ff81968dc5f3a5281da5140dde40
{ "blob_id": "e33d3c9074d7ff81968dc5f3a5281da5140dde40", "branch_name": "refs/heads/master", "committer_date": "2016-04-12T14:59:53", "content_id": "8c0d31e2b4d573872e906df41046782402004f96", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "6beb664cff08e5875853f22441fadf0879e713d5", "extension": "h", "filename": "mvvonmises_likelihood.h", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 45543757, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1955, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/mvvonmises_likelihood.h", "provenance": "stackv2-0115.json.gz:78758", "repo_name": "lrodriguezlujan/mvcircular", "revision_date": "2016-04-12T14:59:53", "revision_id": "f42966ebfc69a742c0b7cbd63d850e99936d57b9", "snapshot_id": "ef703a53fcb85cf7c01544611e739f79cc0de7a6", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/lrodriguezlujan/mvcircular/f42966ebfc69a742c0b7cbd63d850e99936d57b9/src/mvvonmises_likelihood.h", "visit_date": "2021-01-10T08:17:19.638751" }
stackv2
/******************* * * $Date:$ * $Revision:$ * $Author:$ * $HeadUrl:$ * $Id: mvvonmises.c 13 2015-04-17 08:17:47Z lrodriguez $ **/ #ifndef _MVVM_LIKELIHOOD_H_ #define _MVVM_LIKELIHOOD_H_ /************* * Likelihood */ /* Transforms theta to Sin(theta-mu) * * Computes Sin(theta-mu) / Cos(theta-mu) for each variable in the dataset. * * @param [in] n * @param [in] p * @param [in] theta * @param [in] mu * @param [out] S * @param [out] C * */ void mv_theta_cos_sinTransform(int n, int p, double*theta, double* mu, long double *S, long double *C); /*** * Multivaraite von mises density. Not normalized * * @param [in] p * @param [in] theta * @param [in] mu * @param [in] kappa * @param [in] Lambda * * @return Density val * */ double mvvm_density_unregularized(int p, double *theta, double *mu, double *kappa, double *lambda); /***** * Optimized version. Computes simplified log likelihood and its derivatives * * Removes constant terms. Uses matrix multiplications. Reduce number of trigonometric opers. * Reuses terms. Marginal mu is not longer needed, derivatives are simplified as well. * * Instead of PL we will name it "loss function" * * Lambda is taken as a full row-leading pxp matrix with 0's in the diagonal. But d_lambda is only * computed for the upper triangle. * * If d_kappa or d_lambda are NULL, derivatives are not computed. * * To even speed up the process a little bit more, we make the following assumptions: * * Mu is 0 for every j * (input) Theta_i_j = Sin( (real) Theta_i_j - (real)mu_j ) * * * @param [in] n * @param [in] p * @param [in] kappa * @param [in] lambda * @param [in] theta * @param [out] ro * @param [out] d_kappa * @param [out] d_lambda * * @return loss function value */ long double mv_vonmises_lossFunction(int n,int p, double* kappa, double* lambda, long double *S, long double *C, long double *ro, double *d_kappa, double *d_lambda); #endif
2.1875
2
2024-11-18T22:24:07.320035+00:00
2015-04-30T10:20:32
01c817db1fedd2f138b50128d871cb1a0053cced
{ "blob_id": "01c817db1fedd2f138b50128d871cb1a0053cced", "branch_name": "refs/heads/master", "committer_date": "2015-04-30T10:20:32", "content_id": "4eb3131e8b2c3c4a6c52ca889a49da8249707b73", "detected_licenses": [ "Apache-2.0" ], "directory_id": "678b454f4767b18f0fc1dd6b7e8f7ea2bc02b242", "extension": "c", "filename": "05.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 25061516, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1340, "license": "Apache-2.0", "license_type": "permissive", "path": "/C/AULA6/Josinaldo/Exercicios/05.c", "provenance": "stackv2-0115.json.gz:78887", "repo_name": "GADS2014M/Exercicios", "revision_date": "2015-04-30T10:20:32", "revision_id": "da09c69db6b15fa220666de26aa2a7ab16ff6cc3", "snapshot_id": "1dcc4697c25ef1e8947d2f712eddbf5c803e6fda", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/GADS2014M/Exercicios/da09c69db6b15fa220666de26aa2a7ab16ff6cc3/C/AULA6/Josinaldo/Exercicios/05.c", "visit_date": "2020-12-30T14:56:10.111132" }
stackv2
#include <stdio.h> /* 5. Faça um programa que processe a matriz abaixo, sendo que cada linha representa um aluno e cada coluna as suas notas. O programa deverá mostrar a média de cada aluno e a média da turma. Implemente dois procedimentos. Implemente, pelo menos, dois procedimentos. 5 7 4 5 6 7 3 5 2 4 5 6 8 9 7 2 6 4 */ const int linhas = 6; const int colunas = 3; void mediaAluno(int mat[][colunas]){ int i, j; float mediaAluno; for(i=0;i < linhas;i++){ mediaAluno = 0; float mediaAluno = 0; for(j=0;j < colunas;j++){ mediaAluno += mat[i][j]; } mediaAluno = (float) mediaAluno / colunas; printf("Aluno %d, media = %2.1f\n", i+1, mediaAluno); } } void mediaTurma(int mat[][colunas]){ int i, j; float notasAluno, mediaTurma = 0; for(i=0;i < linhas;i++){ notasAluno = 0; for(j=0;j < colunas;j++){ notasAluno += mat[i][j]; } mediaTurma += notasAluno; } mediaTurma = (float) mediaTurma / linhas; printf("Media da turma = %2.1f", mediaTurma); } main(){ int mat[6][3] = {{5,7,4},{5,6,7},{3,5,2},{4,5,6},{8,9,7},{2,6,4}}; // Calcula e exibe média Aluno mediaAluno(mat); // Calcula e exibe média da turma mediaTurma(mat); }
3.796875
4
2024-11-18T22:24:07.706079+00:00
2020-12-09T02:52:37
321d97509e90a60745617b3d01f42cbd1a34304f
{ "blob_id": "321d97509e90a60745617b3d01f42cbd1a34304f", "branch_name": "refs/heads/main", "committer_date": "2020-12-09T02:52:37", "content_id": "10752342e5789a4ec085a2f1b2aaa1828d041d4c", "detected_licenses": [ "MIT" ], "directory_id": "1b5fb75354e24ba76aea3bdb78533fa2fd1b2f26", "extension": "c", "filename": "linkedlist.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 319821092, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4072, "license": "MIT", "license_type": "permissive", "path": "/linkedlist.c", "provenance": "stackv2-0115.json.gz:79276", "repo_name": "DSBarradas/MP3_Audio_Catalog", "revision_date": "2020-12-09T02:52:37", "revision_id": "237d962f7f21854d754e5d677e84a1c4965ce341", "snapshot_id": "0d05070f3ce0c4e7d60e7392e9cdc139539d5301", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/DSBarradas/MP3_Audio_Catalog/237d962f7f21854d754e5d677e84a1c4965ce341/linkedlist.c", "visit_date": "2023-01-22T03:48:34.407155" }
stackv2
/** * name: linkedlist.c * created on: 2020-06-22 * author: Daniel Barradas */ /* ********************* COMENTÁRIO ******************************** * Assume-se, nas funções deste módulo, que os elementos de cada * lista vão ser inseridos em ordem lexicografica, uma vez que a * ordeção das tags é feita antes da criação da árvore binária. * (onde vão ser inseridas as listas) * *******************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "tagtype.h" #include "tag.h" #include "linkedlist.h" /**====================================================================================== Function Name: findElem Description: This function searches for the last element on the list Parameters: TreeListNode *head: reference to the head of the list Return: TreeListNode *: reference to last element of the list =======================================================================================*/ TreeListNode *findElem( TreeListNode *head ) { TreeListNode *prev = head; while(prev->next != NULL) // checks if the current elem has a next elem prev = prev->next; // saves the next elem to check in the next iteration return prev; // returns the tail of the linked list } /**====================================================================================== Function Name: insertElem Description: This function inserts an element to a linked list Parameters: TreeListNode *head: pointer to the head (first element of the list) MP3Tag_t *tag: pointer to a tag in dynamic memory Return: Doesnt have =======================================================================================*/ void insertElem( TreeListNode *head, MP3Tag_t *tag ) { TreeListNode *tail, *new; tail = findElem(head); if( tail->tag != tag ) { new = malloc(sizeof(TreeListNode)); if(new == NULL) { fprintf(stderr, "%s (line %d): COULD NOT ALLOCATE MEMORY.\n", __FILE__, __LINE__); exit(1); } /* Inicialization of the pointers of the new element */ new->next = NULL; new->tag = tag; /* Insertion of the new element in the list */ tail->next = new; } } /**====================================================================================== Function Name: printList Description: This function prints a list of elements with at least one word equal Parameters: TreeListNode *head: pointer to the head (first element of the list) Return: Doesnt have =======================================================================================*/ void printList( TreeListNode *head ) { if(head->tag != NULL){ printf(" TITLE: %-31s", head->tag->title); printf(" ARTIST: %-31s", head->tag->artist); printf(" ALBUM: %-31s",head->tag->album); if( head->tag->year != YEAR_UNKNOWN ) printf(" YEAR: %-10d", head->tag->year); else printf(" YEAR: %-10s", ERROR); printf(" COMMENT: %-31s", head->tag->comment); if( head->tag->track != '\0' ) printf(" TRACK: %-10d", head->tag->track); else printf(" TRACK: %-10s", ERROR); if( head->tag->genre != GENRE_UNKNOWN ) printf(" GENRE: %-10d", head->tag->genre); else printf(" GENRE: %-10s", ERROR); if( head->tag->fileName != NULL ) printf(" FILE: %-10s", head->tag->fileName); else printf(" FILE: %-10s", ERROR); printf("\n"); } if(head->next != NULL) printList(head->next); } /**====================================================================================== Function Name: freeList Description: This fucntion frees a linked list of a tree node Parameters: TreeListNode *head: pointer to the head (first element of the list) Return: Doesnt have =======================================================================================*/ void freeList( TreeListNode *head ) { if(head->next != NULL) // checks if there are more elements and if positive frees them freeList( head->next ); free(head); // frees the element passed to the fucntion }
3.28125
3
2024-11-18T22:24:07.775141+00:00
2019-08-09T05:54:28
82f725dee1f9d5f65bd99105fa86ab858948ae73
{ "blob_id": "82f725dee1f9d5f65bd99105fa86ab858948ae73", "branch_name": "refs/heads/master", "committer_date": "2019-08-09T05:54:28", "content_id": "a99bab5477fe74fffdb4c22163628364ce4cf2db", "detected_licenses": [ "MIT" ], "directory_id": "6e87a1be6d28c5b406c3182a01f6db8b90147991", "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": 200764438, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1510, "license": "MIT", "license_type": "permissive", "path": "/libuv-dox-master/examples/09-thread-create/main.c", "provenance": "stackv2-0115.json.gz:79406", "repo_name": "codediy/php_uv_test", "revision_date": "2019-08-09T05:54:28", "revision_id": "d814d3e2ea6eb4980041c9703e3fe82fdedabb88", "snapshot_id": "dff5d95bb4ad5bd33f7f9cc10d0b8e3ed04d7864", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/codediy/php_uv_test/d814d3e2ea6eb4980041c9703e3fe82fdedabb88/libuv-dox-master/examples/09-thread-create/main.c", "visit_date": "2020-06-30T07:19:08.902672" }
stackv2
#include <stdio.h> #include <assert.h> #include <unistd.h> #include "../libuv/include/uv.h" #define ERROR(msg, code) do { \ fprintf(stderr, "%s: [%s: %s]\n", msg, uv_err_name((code)), uv_strerror((code))); \ assert(0); \ } while(0); void hare_entry(void *args) { int tracklen = *((int*) args); while(tracklen--) { sleep(1); fprintf(stderr, "hare ran one more step\n"); } fprintf(stderr, "hare done running!\n"); } void tortoise_entry(void *args) { int tracklen = *((int*) args); while(tracklen--) { sleep(3); fprintf(stderr, "tortoise ran one more step\n"); } fprintf(stderr, "tortoise done running!\n"); } // https://github.com/thlorenz/libuv-dox/blob/master/methods.md#thread-local-storage int main() { int r; int tracklen = 5; uv_thread_t hare_id; uv_thread_t tortoise_id; r = uv_thread_create(&hare_id, hare_entry, &tracklen); if (r) ERROR("thread_create", r); r = uv_thread_create(&tortoise_id, tortoise_entry, &tracklen); if (r) ERROR("thread_create", r); // no second param (ala pthread_join) which allows target thread passing back value to calling thread // instead send values via http://nikhilm.github.io/uvbook/threads.html#inter-thread-communication r = uv_thread_join(&hare_id); if (r) ERROR("thread_join", r); r = uv_thread_join(&tortoise_id); if (r) ERROR("thread_join", r); return 0; }
2.875
3
2024-11-18T22:24:13.029956+00:00
2020-10-18T06:43:29
a392af584744f0ea0949cf3638963d0ea3b29d0c
{ "blob_id": "a392af584744f0ea0949cf3638963d0ea3b29d0c", "branch_name": "refs/heads/master", "committer_date": "2020-10-18T06:43:29", "content_id": "446187b5ec1f94213b71c9e959c5b49b41f4f623", "detected_licenses": [ "MIT" ], "directory_id": "c246aa51b80c66a972f4025efcb986386ac44d2e", "extension": "c", "filename": "ptracehook.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 93111500, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1232, "license": "MIT", "license_type": "permissive", "path": "/ptracehook.c", "provenance": "stackv2-0115.json.gz:79535", "repo_name": "rvalles/2003_kernelsec", "revision_date": "2020-10-18T06:43:29", "revision_id": "b4000a45320ec7fcf59b6512b2158dfd5775df73", "snapshot_id": "f1d57cb4b5c2cb075b59602db54e30bab6799b1f", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/rvalles/2003_kernelsec/b4000a45320ec7fcf59b6512b2158dfd5775df73/ptracehook.c", "visit_date": "2021-01-23T10:57:21.201215" }
stackv2
/* PTrace access control module. * * With this module loaded, only UID 0 and defined GID are allowed to use ptrace() syscall. * Have fun. * * Roc Vallès Domènech */ #define __KERNEL__ #define MODULE #include <linux/kernel.h> #include <linux/module.h> #include <linux/version.h> #include <linux/mm.h> #include <linux/ctype.h> #include <linux/unistd.h> /* set the group that's allowed here */ #define GID 4 MODULE_AUTHOR("rvalles"); MODULE_DESCRIPTION("Limits ptrace() syscall access."); MODULE_LICENSE("GPL"); extern void *sys_call_table[]; int (*o_ptrace)(int, int, void *, void *); int my_ptrace(int request, int pid, void *addr, void *data) { int returnvalue; int group; if(current->uid) for(group = 0;(group < current->ngroups - 1) && (current->groups[group] != GID);group++); if((!current->uid) || (current->groups[group] == GID)) { returnvalue = (*o_ptrace)(request, pid, addr, data); } else { return -1; } return returnvalue; } int init_module() { o_ptrace = sys_call_table[__NR_ptrace]; sys_call_table[__NR_ptrace] = my_ptrace; printk("ptrace hook loaded correctly\n"); return 0; } void cleanup_module() { sys_call_table[__NR_ptrace] = o_ptrace; printk("ptrace hook removed\n"); }
2.625
3
2024-11-18T22:24:14.284772+00:00
2014-08-23T06:03:36
98e83f0705fa65a68d06068d1bfbdd8498fab6f4
{ "blob_id": "98e83f0705fa65a68d06068d1bfbdd8498fab6f4", "branch_name": "refs/heads/master", "committer_date": "2014-08-23T06:03:36", "content_id": "ce3d1aaf6303937848867f017ea33bacbcbdb849", "detected_licenses": [ "Apache-2.0" ], "directory_id": "edeba35a66877fc8e8fed1a92542d514855c844a", "extension": "h", "filename": "linked_list.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": 1434, "license": "Apache-2.0", "license_type": "permissive", "path": "/ebe_parser/linked_list.h", "provenance": "stackv2-0115.json.gz:79665", "repo_name": "burnsba/EBE", "revision_date": "2014-08-23T06:03:36", "revision_id": "39ca094ce9b99a42edb3a6cdd064e9b6f7924bd7", "snapshot_id": "c1685d5d991a48f2f72e64fb30f840b4b74d599a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/burnsba/EBE/39ca094ce9b99a42edb3a6cdd064e9b6f7924bd7/ebe_parser/linked_list.h", "visit_date": "2016-09-06T15:21:40.403601" }
stackv2
#ifndef __LINKED_LIST_H__ #define __LINKED_LIST_H__ #include <stdint.h> // Doubly linked list node. // Tailored for use in expression parsing and evaluation typedef struct linked_list_node { struct linked_list_node* next; struct linked_list_node* prev; // Pointer to string containing variable name char** var_name; // Value of the variable size_t var_value; // number of times this variable has appeared size_t count; // Unique id of the variable size_t id; } linked_list_node; // Doubly linked list structure typedef struct linked_list { // very first item; there is no head->prev struct linked_list_node* head; // very last item; there is no tail->next struct linked_list_node* tail; size_t length; } linked_list; // Mallocs a new node initializing the contents to 0 linked_list_node* linked_list_node_init(); // Mallocs a new node initializing the contents to 0. // Name, value, and id of the node are set according to parameters linked_list_node* linked_list_node_init_values(char** name, size_t value, size_t id); // Mallocs a new linked list linked_list* linked_list_init(); // Frees the linked list and all of its nodes void linked_list_free(linked_list* list); // Appends an item to the end of the linked list void linked_list_append(linked_list* list, linked_list_node* node); // Prints the contents of each node in the linked list. void printf_linked_list(linked_list* list); #endif
2.796875
3
2024-11-18T22:24:14.357748+00:00
2017-11-03T01:37:25
e4a67f5663fc63f64f2c2cb5a7ed4c58f620da89
{ "blob_id": "e4a67f5663fc63f64f2c2cb5a7ed4c58f620da89", "branch_name": "refs/heads/master", "committer_date": "2017-11-03T01:37:25", "content_id": "3271f7f8a207713a310eabb7ec94efe772e76668", "detected_licenses": [ "MIT" ], "directory_id": "4b08f38c6ab99a10d16d61ba666b338883fbe668", "extension": "c", "filename": "p7-9.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 105112515, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1211, "license": "MIT", "license_type": "permissive", "path": "/lupv1e/ch07/p7-9.c", "provenance": "stackv2-0115.json.gz:79793", "repo_name": "yuweijun/books", "revision_date": "2017-11-03T01:37:25", "revision_id": "5be0fec3adce236875fef0f9e1ed8d91ef4acbfe", "snapshot_id": "2cb31389ede7ef220a5f5823f8bb48262c4cf40a", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/yuweijun/books/5be0fec3adce236875fef0f9e1ed8d91ef4acbfe/lupv1e/ch07/p7-9.c", "visit_date": "2021-09-20T19:29:54.747478" }
stackv2
#include "ch07.h" static sigjmp_buf jmpbuf; static volatile sig_atomic_t canjmp=0; static int sigalrm_appear=0; void pr_mask(const char *str) { sigset_t sigset; int i; sigprocmask(0, NULL, &sigset); printf(" %s\n",str); for(i = 1; i < NSIG; i++) if(sigismember(&sigset,i)) psignal(i,"---"); } static void sig_usr1(int signo) { time_t startime; if(canjmp == 0) return; /* 不期望的訊號,忽略*/ pr_mask("starting sig_usr1: "); alarm(3); /* 3秒之後產生SIGALRM訊號 */ while(!sigalrm_appear); /* 等待SIGALRM */ pr_mask("finishing sig_usr1:"); canjmp = 0; siglongjmp(jmpbuf,1); /* 跳回到main,不傳回 */ } static void sig_alrm(int signo) { pr_mask("in sig_alrm: "); sigalrm_appear = 1; return; } int main(void) { signal(SIGUSR1,sig_usr1); signal(SIGALRM,sig_alrm); pr_mask("starting main:"); if (sigsetjmp(jmpbuf,1)){ pr_mask("ending main: "); exit(EXIT_SUCCESS); } canjmp = 1; /* 標志sigsetjmp()已被呼叫過*/ for (;;) pause(); /* 等待訊號 */ }
2.59375
3
2024-11-18T22:24:14.892999+00:00
2021-01-26T21:03:48
f9629a5ebf6813cbd57b6794d30ab245e302f947
{ "blob_id": "f9629a5ebf6813cbd57b6794d30ab245e302f947", "branch_name": "refs/heads/main", "committer_date": "2021-01-26T21:03:48", "content_id": "1c8e96873609c1d35faa21f8f8cae5abc249ec89", "detected_licenses": [ "MIT" ], "directory_id": "2edbd9b4562b715c7b1e9b4d2533ca0430855d49", "extension": "c", "filename": "play.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 323719095, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2787, "license": "MIT", "license_type": "permissive", "path": "/play.c", "provenance": "stackv2-0115.json.gz:79923", "repo_name": "chelyabinsk/glfw-test", "revision_date": "2021-01-26T21:03:48", "revision_id": "78dee169c64fbe70a135884c9510f76200b08fe8", "snapshot_id": "408382ec0be82fe6751924b1d66ac52e795b3a8d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/chelyabinsk/glfw-test/78dee169c64fbe70a135884c9510f76200b08fe8/play.c", "visit_date": "2023-02-21T23:48:59.584299" }
stackv2
#include <ao/ao.h> #include <mpg123.h> #include <fftw3.h> // Inlcude the FFT #include <iostream> #include <fstream> #include <math.h> #define BITS 8 int main(int argc, char *argv[]) { mpg123_handle *mh; char *buffer; size_t buffer_size; size_t done; int err; int driver; ao_device *dev; ao_sample_format format; int channels, encoding; long rate; if(argc < 2) exit(0); /* initializations */ ao_initialize(); driver = ao_default_driver_id(); mpg123_init(); mh = mpg123_new(NULL, &err); buffer_size = mpg123_outblock(mh); buffer = (char*)malloc(buffer_size * sizeof(unsigned char)); /* open the file and get the decoding format */ mpg123_open(mh, argv[1]); mpg123_getformat(mh, &rate, &channels, &encoding); /* set the output format and open the output device */ format.bits = mpg123_encsize(encoding) * BITS; format.rate = rate; format.channels = channels; format.byte_format = AO_FMT_NATIVE; format.matrix = 0; dev = ao_open_live(driver, &format, NULL); double time = 0; // Initialise FFT float *in; fftwf_complex *out; fftwf_plan p; unsigned flag; in = (float*) fftwf_malloc(sizeof(float) * buffer_size); out = (fftwf_complex*) fftwf_malloc(sizeof(fftwf_complex) * buffer_size); //p = fftwf_plan_dft_r2c_1d(buffer_size, in, out, FFTW_FORWARD, FFTW_ESTIMATE); //p = fftwf_plan_dft_r2c_1d(buffer_size, in, out,flag); p = fftwf_plan_dft_r2c_1d(buffer_size,in, out,flag); /* decode and play */ while (mpg123_read(mh, buffer, buffer_size, &done) == MPG123_OK){ ao_play(dev, buffer, done); time += 0.25*buffer_size/rate; //mpg123_tellframe -- find current frame number std::cout << mpg123_tellframe(mh) << std::endl; // Copy buffer for FFT for(int i=0;i<buffer_size/2;i++) in[i] = buffer[i]; // Do the FFT fftwf_execute(p); // std::ofstream myfile; // myfile.open ("fft_out.csv"); // for(int i=0;i<buffer_size/2;i++){ // //std::cout << 2.0f*sqrt(out[0][i]*out[0][i] + out[1][i]*out[1][i]) << " "; // // Save FFT to a text file // myfile << i << "," << 2.0f*sqrt(out[0][i]*out[0][i] + out[1][i]*out[1][i]) << "\n"; // } // std:: cout << "rate=" << rate << " samples=" << buffer_size << std::endl; // myfile.close(); // Try to do FFT on the buffer //break; } //time += 0.25*buffer_size/rate; std::cout << time << std::endl; /* clean up */ fftwf_destroy_plan(p); fftwf_free(out); fftwf_free(in); free(buffer); ao_close(dev); mpg123_close(mh); mpg123_delete(mh); mpg123_exit(); ao_shutdown(); return 0; }
2.40625
2
2024-11-18T22:24:15.169507+00:00
2019-05-20T07:15:30
b992086f96f751ac1e1fe23142c92f6471c98c7e
{ "blob_id": "b992086f96f751ac1e1fe23142c92f6471c98c7e", "branch_name": "refs/heads/master", "committer_date": "2019-05-20T07:15:30", "content_id": "687dbfe16a1f9bf14608b4a615eef4d38a383757", "detected_licenses": [ "MIT" ], "directory_id": "9d8bf1e51d054d946b6c734cb734215c107e9ce8", "extension": "c", "filename": "example_6.6.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 174721625, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1172, "license": "MIT", "license_type": "permissive", "path": "/feladatok_megoldas/6_Fuggvenyek/example_6.6.c", "provenance": "stackv2-0115.json.gz:80308", "repo_name": "pekmil/CTutorial", "revision_date": "2019-05-20T07:15:30", "revision_id": "e5d8e1b2d7cbab98669757219dfa212267d5f14a", "snapshot_id": "477c8b5855bcbe42b7f4eebce5dfd758ce04e10c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/pekmil/CTutorial/e5d8e1b2d7cbab98669757219dfa212267d5f14a/feladatok_megoldas/6_Fuggvenyek/example_6.6.c", "visit_date": "2020-04-27T22:03:10.862911" }
stackv2
/*************************************************************************************************************************************** * 6.6 Feladat * * Írjon függvényt, amely két számot vár paraméterül és eredményül visszaadja a két szám maximumát * * Írjon programot, amely beolvas egy hatelemű tömböt és az előzőleg megírt függvény segítségével megkeresi a tömb legnagyobb elemét. * ***************************************************************************************************************************************/ #include <stdio.h> #define N 6 int max(int egyik, int masik) { if (egyik>masik) return egyik; else return masik; } int main() { int tomb[N]; int i; printf("Kerem a tomb elemeit:\n"); for (i=0; i<N; i++) { scanf("%d", &tomb[i]); } int legnagyobb=tomb[0]; for (i=1; i<N; i++) { legnagyobb=max(legnagyobb, tomb[i]); } printf("A tomb legnagyobb eleme: %d.\n", legnagyobb); // itt most szandekosan nem torodunk az index-szel return 0; }
3.234375
3
2024-11-18T22:24:15.307939+00:00
2018-07-03T07:32:40
5a0460a0e044a50eff68b7fe0551d934ccc4ec23
{ "blob_id": "5a0460a0e044a50eff68b7fe0551d934ccc4ec23", "branch_name": "refs/heads/master", "committer_date": "2018-07-03T07:32:40", "content_id": "dd645fb1673b4f5522dafe169d9e98374acc90a2", "detected_licenses": [ "MIT" ], "directory_id": "4525a45c920fcf2bf2ce50091c7120c9e5789ca3", "extension": "c", "filename": "client.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 137972416, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1327, "license": "MIT", "license_type": "permissive", "path": "/src/Robot-Software-Enginering/socket/src/client.c", "provenance": "stackv2-0115.json.gz:80566", "repo_name": "HilbertXu/Ultraman_Homework", "revision_date": "2018-07-03T07:32:40", "revision_id": "e5f98f95057d7afe60ee13ce2ae8d7a5ee023b08", "snapshot_id": "36c07ec5d5ea62eba9d0c2b5737cbefacfbacb9d", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/HilbertXu/Ultraman_Homework/e5f98f95057d7afe60ee13ce2ae8d7a5ee023b08/src/Robot-Software-Enginering/socket/src/client.c", "visit_date": "2020-03-21T01:58:31.272327" }
stackv2
//socket #include <sys/types.h> #include <sys/socket.h> #include <sys/wait.h> #include <arpa/inet.h> #include <unistd.h> #include <netdb.h> #include <errno.h> #include <netinet/in.h> // #include <string.h> #include <stdio.h> #include <stdlib.h> int SERVEPORT= 30000; void client(char* t) { printf("start client\n"); //nh_.getParam("SERVEPORT", SERVEPORT); //nh_.getParam("SERVER_IP", SERVER_IP); int sockfd, recvbytes; struct hostent *host; struct sockaddr_in serv_addr; if (( sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket error!"); exit(1); } bzero(&serv_addr,sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(SERVEPORT); serv_addr.sin_addr.s_addr= inet_addr("127.0.0.1"); //serv_addr.sin_addr = inet_addr(SERVER_IP); if (connect(sockfd, (struct sockaddr *)&serv_addr,sizeof(struct sockaddr)) == -1) { perror("connect error!"); exit(1); } printf("strlen(t) = %d\n",strlen(t)); send(sockfd, t, 100, 0); sleep(2); //strcpy(test.name, "orange"); //send(sockfd, (char*)&test, sizeof(test), 0); //sleep(1); printf("end client"); close(sockfd); return; } int main(int argc, char** argv) { char message[100]; strcpy(message, "hello server\n"); printf(message); client(message); sleep(1); return 0; }
2.640625
3
2024-11-18T22:24:15.390241+00:00
2021-09-02T05:02:37
69815f342cb5c1268067a2cc8b563f4280321fc8
{ "blob_id": "69815f342cb5c1268067a2cc8b563f4280321fc8", "branch_name": "refs/heads/main", "committer_date": "2021-09-08T22:14:26", "content_id": "28aebece7c739c243acd652b951a2f7b578aa179", "detected_licenses": [ "MIT" ], "directory_id": "d3dbde5badcffc34f3c5ba9185acfe745cf0f95e", "extension": "h", "filename": "ttydev.h", "fork_events_count": 0, "gha_created_at": "2021-08-03T05:46:50", "gha_event_created_at": "2021-08-03T05:46:50", "gha_language": null, "gha_license_id": null, "github_id": 392205200, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1667, "license": "MIT", "license_type": "permissive", "path": "/include/myst/ttydev.h", "provenance": "stackv2-0115.json.gz:80696", "repo_name": "manojrupireddy/mystikos", "revision_date": "2021-09-02T05:02:37", "revision_id": "2151cf13455a25b9695318b8a50b7f27dd3bbb2a", "snapshot_id": "eb71e085c83b827219fa367caf987ab988f73a7f", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/manojrupireddy/mystikos/2151cf13455a25b9695318b8a50b7f27dd3bbb2a/include/myst/ttydev.h", "visit_date": "2023-07-26T02:25:28.434799" }
stackv2
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #ifndef _MYST_TTYDEV_H #define _MYST_TTYDEV_H #include <myst/defs.h> #include <myst/fdops.h> typedef struct myst_ttydev myst_ttydev_t; typedef struct myst_tty myst_tty_t; struct myst_ttydev { myst_fdops_t fdops; int (*td_create)( myst_ttydev_t* ttydev, int fd, /* STDIN_FILENO | STDOUT_FILENO | STDERR_FILENO */ myst_tty_t** tty); ssize_t (*td_read)( myst_ttydev_t* ttydev, myst_tty_t* tty, void* buf, size_t count); ssize_t (*td_write)( myst_ttydev_t* ttydev, myst_tty_t* tty, const void* buf, size_t count); ssize_t (*td_readv)( myst_ttydev_t* ttydev, myst_tty_t* tty, const struct iovec* iov, int iovcnt); ssize_t (*td_writev)( myst_ttydev_t* ttydev, myst_tty_t* tty, const struct iovec* iov, int iovcnt); int (*td_fstat)( myst_ttydev_t* ttydev, myst_tty_t* tty, struct stat* statbuf); int (*td_ioctl)( myst_ttydev_t* ttydev, myst_tty_t* tty, unsigned long request, long arg); int (*td_fcntl)(myst_ttydev_t* ttydev, myst_tty_t* tty, int cmd, long arg); int (*td_dup)( myst_ttydev_t* ttydev, const myst_tty_t* tty, myst_tty_t** tty_out); int (*td_close)(myst_ttydev_t* ttydev, myst_tty_t* tty); int (*td_target_fd)(myst_ttydev_t* ttydev, myst_tty_t* tty); int (*td_get_events)(myst_ttydev_t* ttydev, myst_tty_t* tty); }; myst_ttydev_t* myst_ttydev_get(void); #endif /* _MYST_TTYDEV_H */
2.21875
2
2024-11-18T22:24:15.479215+00:00
2011-09-19T15:24:28
3048547addb0acad870ec46a6fee01ce2ccfabdd
{ "blob_id": "3048547addb0acad870ec46a6fee01ce2ccfabdd", "branch_name": "refs/heads/master", "committer_date": "2011-09-19T15:24:28", "content_id": "4b2b4a8ff9ae068688096d82a50afbae0ea5098e", "detected_licenses": [ "NCSA" ], "directory_id": "bc0b701fc41f2218af511c4ecbd675c8bf365f1c", "extension": "c", "filename": "strcat-002.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": 344, "license": "NCSA", "license_type": "permissive", "path": "/test/cstdlib/strcat-002.c", "provenance": "stackv2-0115.json.gz:80826", "repo_name": "lygstate/safecode-mirror", "revision_date": "2011-09-19T15:24:28", "revision_id": "27e48405e9cd268a53429226c51bdffe9fb8fb6a", "snapshot_id": "768810a51816e6abc6f190a0b72ea27d1fc7df09", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lygstate/safecode-mirror/27e48405e9cd268a53429226c51bdffe9fb8fb6a/test/cstdlib/strcat-002.c", "visit_date": "2021-01-18T06:46:23.842583" }
stackv2
// RUN: test.sh -c -e -t %t %s // Try concatenating from an unterminated source string. This should // fail. #include <stdlib.h> #include <string.h> void do_cat(char *src) { char f[100] = "meow"; strcat(f, src); } int main() { char *n = malloc(10); strcpy(n, "meow"); memset(&n[4], 'a', 6); do_cat(n); free(n); return 0; }
2.90625
3
2024-11-18T22:24:15.640250+00:00
2019-01-16T23:19:12
64ffa40fecc005fcf32a42957c5b25fb5ca2131b
{ "blob_id": "64ffa40fecc005fcf32a42957c5b25fb5ca2131b", "branch_name": "refs/heads/master", "committer_date": "2019-01-16T23:19:12", "content_id": "9120fc284b269ac98b850fc6b945d238e3dbc4bd", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "97f4e038e27feae7a47cbac549d86df023e485c8", "extension": "h", "filename": "core.h", "fork_events_count": 0, "gha_created_at": "2019-01-16T23:22:01", "gha_event_created_at": "2019-01-16T23:22:01", "gha_language": null, "gha_license_id": "BSD-3-Clause", "github_id": 166126929, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1644, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/include/core.h", "provenance": "stackv2-0115.json.gz:81085", "repo_name": "firebolt55439/ls_extended", "revision_date": "2019-01-16T23:19:12", "revision_id": "64f39a5347e0b6f0eddc3d008d17570a54209cf9", "snapshot_id": "37960983d6af1bddf4ea6e87ebd8dca2f7f90f22", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/firebolt55439/ls_extended/64f39a5347e0b6f0eddc3d008d17570a54209cf9/include/core.h", "visit_date": "2020-04-17T02:16:21.470016" }
stackv2
/* Copyright (c) 2018, Electrux All rights reserved. Using the BSD 3-Clause license for the project, main LICENSE file resides in project's root directory. Please read that file and understand the license terms before using or altering the project. */ #ifndef CORE_H #define CORE_H #include <stdlib.h> #include <stdint.h> static const uint8_t VERSION_MAIN = 1; static const uint8_t VERSION_SUB = 0; static const uint8_t VERSION_PATCH = 8; enum ERRORS { SUCCESS, LOC_NOT_OPENED, STR_VEC_INIT_FAIL, }; void split_file( const char * file, char * name, char * ext ); // created to allow colored display using string interpolation // and printf like syntax for variables // padding, if > 0 will allow right padding for the string to display // option values are: // 0 -> stdout // 1 -> stderr // 2 -> test ( no display ) void _display( const int padding, const int option, const char * fmt, ... ); // these definitions allow for various use scenarios of _display function // if we use fmt parameter explicitly here, it will cause error if there is no // variable argument to be used ( unless we opt for the gcc extension: ##__VA_ARGS__ ) // so, instead, we just let it use fmt as a variadic argument as well #define display( ... ) _display( 0, 0, __VA_ARGS__ ) #define display_err( ... ) _display( 0, 1, __VA_ARGS__ ) #define display_test( ... ) _display( 0, 2, __VA_ARGS__ ) #define display_padded( padding, ... ) _display( padding, 0, __VA_ARGS__ ) uint8_t extra_space_count( const char * str, const int used_bytes ); uint64_t get_extra_spaces( const char * str ); size_t utf8_strlen( const char * _s ); #endif // CORE_H
2.375
2
2024-11-18T22:24:15.696605+00:00
2016-05-29T09:16:42
42051388d31e50914349780e6616213817e9160f
{ "blob_id": "42051388d31e50914349780e6616213817e9160f", "branch_name": "refs/heads/master", "committer_date": "2016-05-29T09:16:42", "content_id": "4ec7c4b4a6a6ceb6f36c5ec3a6c56fa9ee6861d6", "detected_licenses": [ "NCSA" ], "directory_id": "3d80d68564da1f1d650988a1fafe221d749cdc31", "extension": "c", "filename": "mmu_fault_load.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 189500579, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 651, "license": "NCSA", "license_type": "permissive", "path": "/test/MMU/mmu_fault_load.c", "provenance": "stackv2-0115.json.gz:81213", "repo_name": "heyitsanthony/klee-mc", "revision_date": "2016-05-29T09:16:42", "revision_id": "184a809930c4f7823526a11474b1446dd7d92afb", "snapshot_id": "ede73456fa0e928e67529ae19ae4723d483acfd3", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/heyitsanthony/klee-mc/184a809930c4f7823526a11474b1446dd7d92afb/test/MMU/mmu_fault_load.c", "visit_date": "2020-05-30T03:18:24.188711" }
stackv2
// RUN: gcc %s -O0 -I../../../include/ -o %t1 // RUN: klee-mc -pipe-solver -sym-mmu-type=fork -use-sym-mmu - ./%t1 2>%t1.err >%t1.out // RUN: ls klee-last | grep ptr.err // // RUN: klee-mc -pipe-solver -sym-mmu-type=uniqptr -use-sym-mmu - ./%t1 2>%t1.err >%t1.out // RUN: ls klee-last | grep ptr.err /* this tests loading a primitive with the mmu */ /* right now it's not a very good test-- needs to * check patterns; not 0 */ #include "klee/klee.h" #include <unistd.h> int main(int argc, char *argv[]) { uint64_t c; uint64_t *p64; if (read(0, &c, sizeof(c)) != sizeof(c)) return 0; p64 = (void*)c; ksys_assume_eq(*p64, 0); return 0; }
2.0625
2
2024-11-18T22:24:16.328165+00:00
2015-10-13T23:22:42
9b479654379c47fa53813874f53eeba4f83d1d7c
{ "blob_id": "9b479654379c47fa53813874f53eeba4f83d1d7c", "branch_name": "refs/heads/master", "committer_date": "2015-10-13T23:22:42", "content_id": "a1bc7ce6dde96a7946526c16a9d79b5a617d6ae7", "detected_licenses": [ "MIT" ], "directory_id": "dd4708e15dcb967d0ce3059c60c174689e7aa252", "extension": "h", "filename": "e3x_event.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": 990, "license": "MIT", "license_type": "permissive", "path": "/include/e3x_event.h", "provenance": "stackv2-0115.json.gz:81862", "repo_name": "hotelzululima/telehash-c", "revision_date": "2015-10-13T23:22:42", "revision_id": "3afbd648e05498516cbba67a58a38e061db606ca", "snapshot_id": "335252a548bbb8a88a91f61ec47beea171a9464a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/hotelzululima/telehash-c/3afbd648e05498516cbba67a58a38e061db606ca/include/e3x_event.h", "visit_date": "2021-01-21T18:15:44.485854" }
stackv2
#ifndef e3x_event_h #define e3x_event_h #include "lob.h" // simple timer eventing (for channels) that can be replaced by different backends // an event is just a lob packet and ordering value typedef struct e3x_event_struct *e3x_event_t; // create a list/group of events, give prime number to create a hashtable of that size for faster id lookups e3x_event_t e3x_event_new(uint32_t prime, uint64_t now); void e3x_event_free(e3x_event_t ev); // the number of ms in the future from now for the next event (for scheduling), 0 if events waiting, max-uint32 if none uint32_t e3x_event_at(e3x_event_t ev, uint64_t now); // remove and return the oldest event, after an event_at returned 0 lob_t e3x_event_get(e3x_event_t ev); // 0 is delete, event is unique per id // id must be stored in the event somewhere, and this uses the event->id, next, and chaining values only // wait is ms in the future from now void e3x_event_set(e3x_event_t ev, lob_t event, char *id, uint32_t wait); #endif
2.0625
2
2024-11-18T22:24:16.614349+00:00
2020-04-17T19:20:02
1822c7387208efe2fa7a7bec9cfb54d357302546
{ "blob_id": "1822c7387208efe2fa7a7bec9cfb54d357302546", "branch_name": "refs/heads/master", "committer_date": "2020-04-17T19:20:02", "content_id": "79c16437bd713277b4589c686679c10a17dd8af9", "detected_licenses": [ "MIT" ], "directory_id": "b3d708a7f5511c788338b94daec64432833c66d6", "extension": "c", "filename": "rwlock.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 226702065, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6253, "license": "MIT", "license_type": "permissive", "path": "/C/arbitrator/rwlock.c", "provenance": "stackv2-0115.json.gz:82254", "repo_name": "shlomif/ip-noise", "revision_date": "2020-04-17T19:20:02", "revision_id": "9f8050a88e15e9f359f558b2c231b0993f0785f9", "snapshot_id": "e144bacca55b0230be076762fe5f2f22e63eefb5", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/shlomif/ip-noise/9f8050a88e15e9f359f558b2c231b0993f0785f9/C/arbitrator/rwlock.c", "visit_date": "2020-09-28T05:38:30.469597" }
stackv2
/* * rwlock.c - Part of the IP-Noise project. * Written by Shlomi Fish & Roy Glasberg * The Computer Networks Laboratory * The Electrical Engineering Department * The Technion * * This code is distributed under the public domain. * * * * Implementation of a Readers-Writers lock for POSIX threads. Plain and * simple. This code is based on the code of the ZThreads library, but it * is not derived from it. * * */ #ifndef __KERNEL__ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #else #include "k_stdlib.h" #endif #include "rwlock.h" /* * Initialize a new readers-writers lock * */ #ifndef __KERNEL__ static const pthread_mutex_t mutex_initializer = PTHREAD_MUTEX_INITIALIZER; static const pthread_cond_t cond_initializer = PTHREAD_COND_INITIALIZER; ip_noise_rwlock_t * ip_noise_rwlock_alloc() { ip_noise_rwlock_t * lock; lock = malloc(sizeof(ip_noise_rwlock_t)); lock->active_readers = lock->active_writers = 0; lock->waiting_readers = lock->waiting_writers = 0; lock->mutex_lock = mutex_initializer; pthread_mutex_init(&(lock->mutex_lock), NULL); lock->cond_read = cond_initializer; pthread_cond_init(&(lock->cond_read), NULL); lock->cond_write = cond_initializer; pthread_cond_init(&(lock->cond_write), NULL); return lock; } void ip_noise_rwlock_free(ip_noise_rwlock_t * lock) { pthread_mutex_destroy(&(lock->mutex_lock)); pthread_cond_destroy(&(lock->cond_read)); pthread_cond_destroy(&(lock->cond_write)); free(lock); } inline int ip_noise_rwlock_allow_reader(ip_noise_rwlock_t * lock) { return (lock->active_writers == 0) && (lock->waiting_writers == 0); } inline int ip_noise_rwlock_allow_writer(ip_noise_rwlock_t * lock) { return ((lock->active_writers == 0) && (lock->active_readers == 0)); } void ip_noise_rwlock_down_read(ip_noise_rwlock_t * lock) { int ret = 0; pthread_mutex_lock(&(lock->mutex_lock)); lock->waiting_readers++; while (! ip_noise_rwlock_allow_reader(lock)) { ret = pthread_cond_wait(&(lock->cond_read), &(lock->mutex_lock)); if (ret != 0) { break; } } lock->waiting_readers--; if (ret == 0) { lock->active_readers++; } pthread_mutex_unlock(&(lock->mutex_lock)); } void ip_noise_rwlock_down_write(ip_noise_rwlock_t * lock) { int ret = 0; pthread_mutex_lock(&(lock->mutex_lock)); lock->waiting_writers++; while (! ip_noise_rwlock_allow_writer(lock) ) { ret = pthread_cond_wait(&(lock->cond_write), &(lock->mutex_lock)); if (ret != 0) { break; } } lock->waiting_writers--; if (ret == 0) { lock->active_writers++; } pthread_mutex_unlock(&(lock->mutex_lock)); } void ip_noise_rwlock_up_read(ip_noise_rwlock_t * lock) { pthread_mutex_lock(&(lock->mutex_lock)); lock->active_readers--; lock->fairness_counter--; pthread_cond_broadcast(&(lock->cond_write)); pthread_cond_signal(&(lock->cond_read)); pthread_mutex_unlock(&(lock->mutex_lock)); } void ip_noise_rwlock_up_write(ip_noise_rwlock_t * lock) { pthread_mutex_lock(&(lock->mutex_lock)); lock->active_writers--; lock->fairness_counter++; /* Notify all */ pthread_cond_broadcast(&(lock->cond_write)); pthread_cond_signal(&(lock->cond_read)); pthread_mutex_unlock(&(lock->mutex_lock)); } #else /* * This is the code for the kernel. Basically, all it does is initialize * a mutex. A mutex can serve as a (very limited) readers-writers lock * * */ ip_noise_rwlock_t * ip_noise_rwlock_alloc(void) { ip_noise_rwlock_t * ret; ret = malloc(sizeof(ip_noise_rwlock_t)); #if 0 pthread_mutex_init(ret, NULL); #else *ret = RW_LOCK_UNLOCKED; #endif return ret; } void ip_noise_rwlock_free(ip_noise_rwlock_t * lock) { #if 0 pthread_mutex_destroy(lock); #endif free(lock); } #endif /* * The rest is a test program to test the rwlock. It can be safely ignored. * * */ #if 0 ip_noise_rwlock_t * mylock; #define NUM_READERS 5 #define NUM_WRITERS 2 struct context_struct { int writer; int index; }; typedef struct context_struct context_t; void * reader_thread(void * void_context) { context_t * context; context = (context_t *)void_context; while (1) { ip_noise_rwlock_down_read(mylock); printf("Reader %i - Lock!\n", context->index); usleep(rand()%1000000); ip_noise_rwlock_up_read(mylock); printf("Reader %i - Unlock!\n", context->index); usleep(rand()%1000000); } return NULL; } void * writer_thread(void * void_context) { context_t * context; context = (context_t *)void_context; while (1) { ip_noise_rwlock_down_write(mylock); printf("Writer %i - Lock!\n", context->index); usleep(rand()%1000000); printf("Writer %i - Unlock!\n", context->index); ip_noise_rwlock_up_write(mylock); usleep(rand()%1000000); } return NULL; } int main(int argc, char * argv[]) { context_t * context; pthread_t readers[NUM_READERS]; pthread_t writers[NUM_WRITERS]; int check; int a; mylock = ip_noise_rwlock_alloc(); for(a=0;a<NUM_READERS;a++) { context = malloc(sizeof(context)); context->index = a; context->writer = 0; check = pthread_create( &readers[a], NULL, reader_thread, context ); if (check != 0) { fprintf(stderr, "Could not create Reader #%i!\n", a); exit(-1); } } for(a=0;a<NUM_WRITERS;a++) { context = malloc(sizeof(context)); context->index = a; context->writer = 0; check = pthread_create( &writers[a], NULL, writer_thread, context ); if (check != 0) { fprintf(stderr, "Could not create Reader #%i!\n", a); exit(-1); } } while(1) { sleep(1); } return 0; } #endif
2.640625
3
2024-11-18T22:24:18.629363+00:00
2017-12-21T07:32:07
4693c9bdfcccb4c84e58e4ee2e6a069f753c2a8d
{ "blob_id": "4693c9bdfcccb4c84e58e4ee2e6a069f753c2a8d", "branch_name": "refs/heads/master", "committer_date": "2017-12-21T07:32:07", "content_id": "113c4ec6994e0b21571bbcd8fa724293f2537cf0", "detected_licenses": [ "MIT" ], "directory_id": "58e4226b5bfb3cd41a47b7a7e4509ffdb9806d85", "extension": "c", "filename": "inventory.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 88330523, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 16198, "license": "MIT", "license_type": "permissive", "path": "/inventory.c", "provenance": "stackv2-0115.json.gz:82383", "repo_name": "ahmednooor/basic-inventory-c", "revision_date": "2017-12-21T07:32:07", "revision_id": "ed656ed5779da61ae78da6195d882137ca309a51", "snapshot_id": "6d21c0db9506fa80e4187f32e2497b1d839126f8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ahmednooor/basic-inventory-c/ed656ed5779da61ae78da6195d882137ca309a51/inventory.c", "visit_date": "2021-01-19T17:33:30.741769" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> #include "lib/cs50.h" #include "lib/cs50.c" typedef struct _item { char ID[9]; char name[201]; float qty; float avgUnitCost; } _item; int loadInventory(void); int showInventoryList(void); int writeInventoryToFile(void); int addNewInventoryItem(void); int deleteInventoryItem(void); int addQuantity(void); int removeQuantity(void); int searchInventoryItem(void); _item inventory[100]; int counter = 0; int main(void) { loadInventory(); printf("\n-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n B a s i c I n v e n t o r y S y s t e m |\n-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n"); while (1) { printf("\n# MENU\n# 0 - EXIT\n# 1 - Add new inventory item\n# 2 - Delete inventory item\n# 3 - Add quantity to an inventory item\n# 4 - Subtract quantity from an inventory item\n# 5 - Show complete inventory list\n# 6 - Search for an inventory item\n\n"); int menuIndex; menuIndex = get_int(); if (menuIndex == 0) { return 0; } else if (menuIndex == 1) { addNewInventoryItem(); } else if (menuIndex == 2) { deleteInventoryItem(); } else if (menuIndex == 3) { addQuantity(); } else if (menuIndex == 4) { removeQuantity(); } else if (menuIndex == 5) { showInventoryList(); } else if (menuIndex == 6) { searchInventoryItem(); } else { continue; } } } int loadInventory() { FILE* database = fopen("database/inventory.txt", "r"); if (database == NULL) { printf("Could not open database.\n"); return 1; } char c = '0'; while (c != EOF) { if (c != EOF) { _item item; inventory[counter] = item; inventory[counter].qty = 0.0; inventory[counter].avgUnitCost = 0.0; } int i = 0; while (c != EOF) { c = fgetc(database); if (c == '\n' || c == EOF) { if (c == '\n') { inventory[counter].ID[i] = '\0'; } break; } else { inventory[counter].ID[i] = c; i++; } } int j = 0; while (c != EOF) { c = fgetc(database); if (c == '\n' || c == EOF) { if (c == '\n') { inventory[counter].name[j] = '\0'; } break; } else { inventory[counter].name[j] = c; j++; } } int k = 0; int floatSwitch = 0; int decimalCounter = 0; while (c != EOF) { c = fgetc(database); if (c == '\n' || c == EOF) { break; } else { if (c == '.') { floatSwitch = 1; decimalCounter = 1; } else { if (floatSwitch == 0) { inventory[counter].qty = (inventory[counter].qty * 10.0) + (1.0 * (c - '0')); } else { inventory[counter].qty = (inventory[counter].qty) + 1.0 * ((1.0 * (c - '0')) / powf(10.0, decimalCounter)); decimalCounter++; } } k++; } } int l = 0; floatSwitch = 0; decimalCounter = 0; while (c != EOF) { c = fgetc(database); if (c == '\n' || c == EOF) { break; } else { if (c == '.') { floatSwitch = 1; decimalCounter = 1; } else { if (floatSwitch == 0) { inventory[counter].avgUnitCost = (inventory[counter].avgUnitCost * 10.0) + (1.0 * (c - '0')); } else { inventory[counter].avgUnitCost = (inventory[counter].avgUnitCost) + 1.0 * ((1.0 * (c - '0')) / powf(10.0, decimalCounter)); decimalCounter++; } } l++; } } if (c != EOF) { counter++; } } fclose(database); return 0; } int showInventoryList(void) { int columnWidth = 0; for (int i = 0; i < counter; i++) { for (int j = 0; j < counter; j++) { if (strlen(inventory[i].name) >= strlen(inventory[j].name)) { columnWidth = strlen(inventory[i].name); } else { break; } } } printf("\n### Inventory List ###\n\n"); printf("%-10s\t%-*s\t%s\t%s\n", "ID", (columnWidth + 4), "NAME", "QTY", "AvgUnitCost"); for (int i = 0; i < counter; i++) { printf("%-10s\t%-*s\t%.2f\t%.2f\n", inventory[i].ID, (columnWidth + 4), inventory[i].name, inventory[i].qty, inventory[i].avgUnitCost); } printf("\nPress Enter to return to MENU.\n"); getchar(); return 0; } int writeInventoryToFile(void) { FILE* database = fopen("database/inventory.txt", "w"); if (database == NULL) { printf("Could not open database.\n"); return 1; } for (int i = 0; i < counter; i++) { for (int j = 0; j < strlen(inventory[i].ID); j++) { fputc(inventory[i].ID[j], database); } fputc('\n', database); for (int j = 0; j < strlen(inventory[i].name); j++) { fputc(inventory[i].name[j], database); } fputc('\n', database); fprintf(database, "%f\n", inventory[i].qty); fprintf(database, "%f\n", inventory[i].avgUnitCost); } fclose(database); return 0; } int addNewInventoryItem(void) { printf("\n### New Inventory Item Addition ###\n\n"); char IDsearch[500]; printf("Enter the ID of Product. (Maximum 8 characters): "); fgets(IDsearch, sizeof(IDsearch), stdin); IDsearch[strcspn(IDsearch, "\r\n")] = 0; if (strlen(IDsearch) != 0) { while (strlen(IDsearch) > 8) { printf("Exceeded 8 characters. Please try again: "); fgets(IDsearch, sizeof(IDsearch), stdin); IDsearch[strcspn(IDsearch, "\r\n")] = 0; } int i = 0; for (i = 0; i < counter; i++) { if (strcmp(IDsearch, inventory[i].ID) == 0) { break; } } if (strcmp(IDsearch, inventory[i].ID) != 0) { _item item; inventory[counter] = item; strcpy(inventory[counter].ID, IDsearch); printf("Enter the Name of Product. (Maximum 200 characters): "); fgets(inventory[counter].name, sizeof(inventory[counter].name), stdin); inventory[counter].name[strcspn(inventory[counter].name, "\r\n")] = 0; while (strlen(inventory[counter].name) > 200) { printf("Exceeded 200 characters. Please try again: "); fgets(inventory[counter].name, sizeof(inventory[counter].name), stdin); inventory[counter].name[strcspn(inventory[counter].name, "\r\n")] = 0; } printf("Enter the Quantity of Product in numbers. (e.g. 10.00): "); inventory[counter].qty = get_double(); printf("Enter the Total Cost of above entered Quantity in numbers. (e.g. 10.00): "); float totalCost = get_double(); inventory[counter].avgUnitCost = inventory[counter].qty != 0.0 ? totalCost / inventory[counter].qty : 0.0; counter++; writeInventoryToFile(); printf("\nNew inventory item added.\n"); printf("%-10s\t%-*s\t%s\t%s\n", "ID", (int) (strlen(inventory[counter - 1].name) + 4), "NAME", "QTY", "AvgUnitCost"); printf("%-10s\t%-*s\t%.2f\t%.2f\n", inventory[counter - 1].ID, (int) (strlen(inventory[counter - 1].ID) + 4), inventory[counter - 1].name, inventory[counter - 1].qty, inventory[counter - 1].avgUnitCost); printf("\nPress Enter to return to MENU.\n"); getchar(); return 0; } else { printf("\nAnother inventory item of the same ID exists already. Please use a different ID.\n"); printf("Press Enter to return to MENU.\n"); getchar(); return 1; } } else { return 1; } } int deleteInventoryItem(void) { printf("\n### Inventory Item Deletion ###\n\n"); char IDsearch[500]; printf("Enter the ID of Product to Delete. (Maximum 8 characters): "); fgets(IDsearch, sizeof(IDsearch), stdin); IDsearch[strcspn(IDsearch, "\r\n")] = 0; if (strlen(IDsearch) != 0) { while (strlen(IDsearch) > 8) { printf("Exceeded 8 characters. Please try again: "); fgets(IDsearch, sizeof(IDsearch), stdin); IDsearch[strcspn(IDsearch, "\r\n")] = 0; } int i = 0; for (i = 0; i < counter; i++) { if (strcmp(IDsearch, inventory[i].ID) == 0) { break; } } if (strcmp(IDsearch, inventory[i].ID) == 0) { printf("\nThe following inventory item will be deleted.\n"); printf("%-10s\t%-*s\t%s\t%s\n", "ID", (int) (strlen(inventory[i].name) + 4), "NAME", "QTY", "AvgUnitCost"); printf("%-10s\t%-*s\t%.2f\t%.2f\n", inventory[i].ID, (int) (strlen(inventory[i].name) + 4), inventory[i].name, inventory[i].qty, inventory[i].avgUnitCost); printf("\nDo you want to proceed? y/n: "); char yn; yn = get_char(); if (yn == 'y' || yn == 'Y') { inventory[i] = inventory[counter - 1]; _item item; inventory[counter - 1] = item; counter--; writeInventoryToFile(); printf("\nIventory item deleted. Press Enter to return to MENU.\n"); getchar(); return 0; } else { return 0; } } else { printf("\nThe ID did not match with any inventory item.\n"); printf("Press Enter to return to MENU.\n"); getchar(); return 1; } } else { return 1; } } int addQuantity(void) { printf("\n### Inventory Item Quantity Addition ###\n\n"); char IDsearch[500]; printf("Enter the ID of Product to be increased in quantity. (Maximum 8 characters): "); fgets(IDsearch, sizeof(IDsearch), stdin); IDsearch[strcspn(IDsearch, "\r\n")] = 0; if (strlen(IDsearch) != 0) { while (strlen(IDsearch) > 8) { printf("Exceeded 8 characters. Please try again: "); fgets(IDsearch, sizeof(IDsearch), stdin); IDsearch[strcspn(IDsearch, "\r\n")] = 0; } int i = 0; for (i = 0; i < counter; i++) { if (strcmp(IDsearch, inventory[i].ID) == 0) { break; } } if (strcmp(IDsearch, inventory[i].ID) == 0) { printf("Enter the Quantity to add. (e.g. 10.00): "); float newQty = get_double(); printf("Enter the Total Cost of added Quantity in numbers. (e.g. 10.00): "); float newTotalCost = get_double(); inventory[i].avgUnitCost = inventory[i].qty + newQty != 0.0 ? ((inventory[i].avgUnitCost * inventory[i].qty) + newTotalCost) / (inventory[i].qty + newQty) : 0.0; inventory[i].qty = inventory[i].qty + newQty; writeInventoryToFile(); printf("\nInventory item updated.\n"); printf("%-10s\t%-*s\t%s\t%s\n", "ID", (int) (strlen(inventory[i].name) + 4), "NAME", "QTY", "AvgUnitCost"); printf("%-10s\t%-*s\t%.2f\t%.2f\n", inventory[i].ID, (int) (strlen(inventory[i].name) + 4), inventory[i].name, inventory[i].qty, inventory[i].avgUnitCost); printf("\nPress Enter to return to MENU.\n"); getchar(); return 0; } else { printf("\nThe ID did not match with any inventory item.\n"); printf("Press Enter to return to MENU.\n"); getchar(); return 1; } } else { return 1; } } int removeQuantity(void) { printf("\n### Inventory Item Quantity Subtraction ###\n\n"); char IDsearch[500]; printf("Enter the ID of Product to be decreased in quantity. (Maximum 8 characters): "); fgets(IDsearch, sizeof(IDsearch), stdin); IDsearch[strcspn(IDsearch, "\r\n")] = 0; if (strlen(IDsearch) != 0) { while (strlen(IDsearch) > 8) { printf("Exceeded 8 characters. Please try again: "); fgets(IDsearch, sizeof(IDsearch), stdin); IDsearch[strcspn(IDsearch, "\r\n")] = 0; } int i = 0; for (i = 0; i < counter; i++) { if (strcmp(IDsearch, inventory[i].ID) == 0) { break; } } if (strcmp(IDsearch, inventory[i].ID) == 0) { printf("Enter the Quantity to subtract. (e.g. 10.00): "); float newQty = get_double(); printf("Enter the Total Cost of subtracted Quantity in numbers. (e.g. 10.00): "); float newTotalCost = get_double(); inventory[i].avgUnitCost = inventory[i].qty - newQty != 0.0 ? ((inventory[i].avgUnitCost * inventory[i].qty) - newTotalCost) / (inventory[i].qty - newQty) : 0.0; inventory[i].qty = inventory[i].qty - newQty; writeInventoryToFile(); printf("\nInventory item updated.\n"); printf("%-10s\t%-*s\t%s\t%s\n", "ID", (int) (strlen(inventory[i].name) + 4), "NAME", "QTY", "AvgUnitCost"); printf("%-10s\t%-*s\t%.2f\t%.2f\n", inventory[i].ID, (int) (strlen(inventory[i].name) + 4), inventory[i].name, inventory[i].qty, inventory[i].avgUnitCost); printf("\nPress Enter to return to MENU.\n"); getchar(); return 0; } else { printf("\nThe ID did not match with any inventory item.\n"); printf("Press Enter to return to MENU.\n"); getchar(); return 1; } } else { return 1; } } int searchInventoryItem(void) { printf("\n### Inventory Item Search ###\n\n"); char IDsearch[500]; printf("Enter the ID of Product to Search. (Maximum 8 characters): "); fgets(IDsearch, sizeof(IDsearch), stdin); IDsearch[strcspn(IDsearch, "\r\n")] = 0; if (strlen(IDsearch) != 0) { while (strlen(IDsearch) > 8) { printf("Exceeded 8 characters. Please try again: "); fgets(IDsearch, sizeof(IDsearch), stdin); IDsearch[strcspn(IDsearch, "\r\n")] = 0; } int i = 0; for (i = 0; i < counter; i++) { if (strcmp(IDsearch, inventory[i].ID) == 0) { break; } } if (strcmp(IDsearch, inventory[i].ID) == 0) { printf("\nSearched inventory item.\n"); printf("%-10s\t%-*s\t%s\t%s\n", "ID", (int) (strlen(inventory[i].name) + 4), "NAME", "QTY", "AvgUnitCost"); printf("%-10s\t%-*s\t%.2f\t%.2f\n", inventory[i].ID, (int) (strlen(inventory[i].name) + 4), inventory[i].name, inventory[i].qty, inventory[i].avgUnitCost); printf("\nPress Enter to return to MENU.\n"); getchar(); return 0; } else { printf("\nThe ID did not match with any inventory item.\n"); printf("Press Enter to return to MENU.\n"); getchar(); return 1; } } else { return 1; } }
2.84375
3
2024-11-18T22:24:19.389572+00:00
2021-07-10T18:21:36
019d9d304e726be41b3a876eaf2ea3bd0be0915d
{ "blob_id": "019d9d304e726be41b3a876eaf2ea3bd0be0915d", "branch_name": "refs/heads/main", "committer_date": "2021-07-10T18:21:36", "content_id": "4b191ca401e013a20c11eaaf5291d1b001dcc7ea", "detected_licenses": [ "MIT" ], "directory_id": "f8fdbe88d9cfe1c9b9a74f0f80833f743ab6ef60", "extension": "c", "filename": "ex3.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 346798186, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 606, "license": "MIT", "license_type": "permissive", "path": "/Guiões/Guião 5/ex3.c", "provenance": "stackv2-0115.json.gz:83160", "repo_name": "FranciscoReisIzquierdo/Sistemas-Operativos", "revision_date": "2021-07-10T18:21:36", "revision_id": "c695fa041ebcb0cd1976de67e699e9fcd959c13a", "snapshot_id": "8812ebd974dfebc16540f57ebe349dd0b7722a65", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/FranciscoReisIzquierdo/Sistemas-Operativos/c695fa041ebcb0cd1976de67e699e9fcd959c13a/Guiões/Guião 5/ex3.c", "visit_date": "2023-06-17T14:26:26.081366" }
stackv2
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys/wait.h> #define MAX_SIZE 1024 int main(int argc, char *argv[]){ int fd[2]; int status= pipe(fd); if(status< 0){ perror("Error!\n"); exit(1); } else{ size_t pid; if((pid= fork())== 0){ close(fd[1]); dup2(fd[0], 0); close(fd[0]); int res= execlp("wc", "wc", NULL); _exit(1); } else{ int bytes; char command[MAX_SIZE]; close(fd[0]); while((bytes= read(0, command, MAX_SIZE))> 0) write(fd[1], command, bytes); close(fd[1]); wait(NULL); } return 0; } }
2.453125
2
2024-11-18T22:24:19.624338+00:00
2020-05-20T17:15:52
f7a83ba6afe83af3f264c294f25b537f0ca21c23
{ "blob_id": "f7a83ba6afe83af3f264c294f25b537f0ca21c23", "branch_name": "refs/heads/master", "committer_date": "2020-05-20T17:15:52", "content_id": "c2afb8b732e9f9fbf067b1ed2ab04ebb7b4b2080", "detected_licenses": [ "MIT" ], "directory_id": "3178d0e649f7347940d2ab6be26f0f0d5ee402f8", "extension": "c", "filename": "get_input.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": 1898, "license": "MIT", "license_type": "permissive", "path": "/src/input/get_input.c", "provenance": "stackv2-0115.json.gz:83289", "repo_name": "kali-y23/ush", "revision_date": "2020-05-20T17:15:52", "revision_id": "9c68429a24d0212741f4d4db2b895c55c08191c1", "snapshot_id": "179fda8c20003cbb22200db3e37c1f97f71e6107", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kali-y23/ush/9c68429a24d0212741f4d4db2b895c55c08191c1/src/input/get_input.c", "visit_date": "2022-07-15T18:49:42.067293" }
stackv2
#include "ush.h" void mx_print_line(t_input *in) { mx_shuffle_text(in); mx_printstr(in->line + in->cur_x); ++(in->cur_x); ++(in->win_x); mx_update_cursor(in); } void mx_ctrl_d(t_ush *ush) { if (ush->in->line[0]) { tputs(tgetstr("dc", NULL), 1, mx_printnbr); for (size_t i = ush->in->cur_x; i <= strlen(ush->in->line); i++) ush->in->line[i] = ush->in->line[i + 1]; tputs(tgetstr("cd", NULL), 1, mx_printnbr); mx_printstr(ush->in->line + ush->in->cur_x); mx_update_cursor(ush->in); } else { mx_printstr("\n"); exit(ush->exit_code > 0); } } static void read_input(t_ush *ush) { mx_init_terminal_data(); ush->in->winsize = tgetnum("co"); ush->in->key = 0; read(0, &ush->in->key, 4); if ((ush->in->key >= 32 && ush->in->key < 127)) mx_print_line(ush->in); ush->in->key == MX_LEFT ? mx_arrow_left(ush->in) : (void)0; ush->in->key == MX_RIGHT ? mx_arrow_right(ush->in) : (void)0; ush->in->key == MX_BACKSPACE ? mx_backspace(ush->in) : (void)0; ush->in->key == MX_UP && ush->history ? mx_arrow_up(ush) : (void)0; ush->in->key == MX_DOWN && ush->history ? mx_arrow_down(ush) : (void)0; if (ush->in->key == MX_CTRL_C) { mx_printchar('\n'); mx_print_prompt(ush); mx_init_line(ush); } else if (ush->in->key == MX_CTRL_D) mx_ctrl_d(ush); else if (ush->in->key == MX_ALT_1) mx_change_prompt(ush); } char *mx_get_line(t_ush *ush) { mx_init_line(ush); mx_enable_input_mode(ush); while (ush->in->key != MX_ENTER) read_input(ush); mx_disable_input_mode(ush); mx_printstr("\n"); if (ush->in->line[0]) mx_add_cmd(&(ush->history), mx_create_hist_node(ush->in->line)); ush->current = ush->history; ush->in->chars_after_newline = 0; return ush->in->line; }
2.21875
2
2024-11-18T22:24:19.713078+00:00
2021-01-27T08:24:47
ed90a136b69629fc6d533f83b1b2ad0e2b77802e
{ "blob_id": "ed90a136b69629fc6d533f83b1b2ad0e2b77802e", "branch_name": "refs/heads/master", "committer_date": "2021-01-27T08:24:47", "content_id": "3867c62009be206d74850669d5eb999ed5f835a9", "detected_licenses": [ "MIT" ], "directory_id": "9f765b728cb542155090e2f933cd2e81009949d5", "extension": "c", "filename": "BinaryCmdParse.c", "fork_events_count": 1, "gha_created_at": "2020-02-06T20:10:25", "gha_event_created_at": "2020-02-06T20:10:26", "gha_language": null, "gha_license_id": "MIT", "github_id": 238774966, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5092, "license": "MIT", "license_type": "permissive", "path": "/lib/src/BinaryCmdParse.c", "provenance": "stackv2-0115.json.gz:83421", "repo_name": "juchong/TR_IMU_Platform", "revision_date": "2021-01-27T08:24:47", "revision_id": "fd54e0206ebf86c48d430089b2e03540e7b575fd", "snapshot_id": "7566fdc588c5aca6fa1c0c2439daddf93ff5527b", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/juchong/TR_IMU_Platform/fd54e0206ebf86c48d430089b2e03540e7b575fd/lib/src/BinaryCmdParse.c", "visit_date": "2021-07-20T14:16:43.686020" }
stackv2
/* The MIT License (MIT) Copyright (c) 2019 Techno Road Inc. 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 <libraries.h> #include "string.h" #include "stdlib.h" #define CMDBUF_LEN 64 static volatile char CMDBUF[CMDBUF_LEN]; // SPI to USB mode // Compatible with ADI DRIVER void BinaryCmdParse(char* cmd,u32 len) { // Exit if there are not enough received characters if(len < 3)cmd[0] =0; if(cmd[0] == 0x5A){ // Initial setting command //Do not change settings, but only reply char buf[2] ={0xFF,0x00}; U_putd(buf,2); }else if(cmd[0] == 0x61){ // Data manipulation command #if defined(ADIS1649X) if(cmd[1] == PAGE0_BURST_CMD){ //Burst mode u16 rb[18]; memset(rb,0,sizeof(rb)); // Read the sensor value ADIS_32bit_READ(rb); char sb[128]; memset(sb,0,sizeof(sb)); // Creating transmission packet sb[0] = 0xff; for(int i =0;i<18;i++){ sb[i*2+3] =rb[i]>>8 &0xff; sb[i*2+4] =rb[i] &0xff; } //Because of the special format of USB-ISS, //it is sent at 10 character delimiter at the time of burst read. if(len ==38){ U_putd(sb,40); }else{ U_putd(sb,len); } #else if(cmd[1] == BURST_CMD){ //Burst mode u16 rb[10]; memset(rb,0,sizeof(rb)); // Read the sensor value ADIS_NoBloking_RegRead(BURST_CMD); for(int i =0;i<10;i++){ rb[i]=ADIS_NoBloking_RegRead(0); } char sb[128]; memset(sb,0,sizeof(sb)); // Creating transmission packet sb[0] = 0xff; for(int i =0;i<10;i++){ sb[i*2+3] =rb[i]>>8 &0xff; sb[i*2+4] =rb[i] &0xff; } //Because of the special format of USB-ISS, //it is sent at 10 character delimiter at the time of burst read. if(len ==24){ U_putd(sb,30); }else{ U_putd(sb,len); } #endif }else if((cmd[1]&0x80) == 0){ // Read command //Because the received character is always odd, //forced termination occurs even if(len %2==0)return; // Read the sensor value u16 rb[128]; memset(rb,0,sizeof(rb)); int j = 0; for(int i=1;i<len;i+=2){ rb[j++] =ADIS_NoBloking_RegRead(cmd[i]); } char sb[128]; memset(sb,0,sizeof(sb)); // Creating transmission packet sb[0]=0xff; for(int i=0;i<((len-1)/2);i++){ sb[(i*2)+1] =rb[i]>>8 &0xff; sb[(i*2)+2] =rb[i]&0xff; } // Transmission U_putd(sb,len); }else if((cmd[1]&0x80) != 0){ // Write command //Because the received character is always odd, //forced termination occurs even if(len %2==0)return; for(int i=1;i<len;i+=2){ ADIS_RegWrite_8bit(cmd[i],cmd[i+1]); } char sb[128]; memset(sb,0,sizeof(sb)); // Transmission sb[0]=0xff; U_putd(sb,len); } } // For processing time confirmation DEBUG_PIN1_LOW; } #define TIME_CNT_LIM 0x200 void ReadBinaryCmd(){ static vu32 time_cnt = 0; static vu32 RECVBUF_LEN = 0; if(IsEnable_UART()){ //Separate processing with UART and USB. // UART processing if(U_get_cap()!=0){ //Evaluate the number of characters received // For processing time confirmation DEBUG_PIN1_HIGH; // Store received characters in buffer LD1_ON; char rb= U_getc(); CMDBUF[RECVBUF_LEN++] =rb; time_cnt =0; LD1_OFF; }else{ // Add counter for timeout if(RECVBUF_LEN >0){ time_cnt++; } } // Process the command if a timeout occurs. if(time_cnt >TIME_CNT_LIM){ // Command parse BinaryCmdParse((char*)CMDBUF,RECVBUF_LEN); RECVBUF_LEN =0; time_cnt=0; memset((char*)CMDBUF,0,sizeof(CMDBUF)); } }else{ //USB processing if(USB_get_cap()!=0){ // For processing time confirmation DEBUG_PIN1_HIGH; // Store received packets in command buffer u8 pl =USB_get_pl_ring_buf(); for(int i=0;i<pl;i++){ char rb= USB_getc(); CMDBUF[RECVBUF_LEN++] =rb; } // Command parse BinaryCmdParse((char*)CMDBUF,RECVBUF_LEN); RECVBUF_LEN =0; memset((char*)CMDBUF,0,sizeof(CMDBUF)); } } }
2.265625
2
2024-11-18T22:24:19.912266+00:00
2016-03-18T11:17:31
a50a9fbcf3a1bc5a22213c6cfdeec1626f47b605
{ "blob_id": "a50a9fbcf3a1bc5a22213c6cfdeec1626f47b605", "branch_name": "refs/heads/master", "committer_date": "2016-03-18T11:17:31", "content_id": "550f05c6b0466af07230248156d8d04e4423a1ac", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "0eb58c70ff708b680f07c2a783c387c15834d384", "extension": "h", "filename": "bitableread.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 28685145, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12721, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/include/bitableread.h", "provenance": "stackv2-0115.json.gz:83680", "repo_name": "ConorStokes/bitable", "revision_date": "2016-03-18T11:17:31", "revision_id": "670144308894371f15268e111049d46cc73716ce", "snapshot_id": "119cc8d175b192b459379da12145e19de5252c3b", "src_encoding": "UTF-8", "star_events_count": 15, "url": "https://raw.githubusercontent.com/ConorStokes/bitable/670144308894371f15268e111049d46cc73716ce/include/bitableread.h", "visit_date": "2021-01-21T12:06:48.791109" }
stackv2
/* Copyright (c) 2015, Conor Stokes All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS 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 OWNER 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. */ /** @file * @brief Interface for reading from a bitable. * Note that readable bitables are immutable and that apart from allocating/opening and closing the table, no resource allocation is directly performed. */ #ifndef BITABLE_READ_H__ #define BITABLE_READ_H__ #pragma once #include "bitablecommon.h" #ifdef __cplusplus extern "C" { #endif /** A bitable that can be read from. * Allocate on the heap using bitable_read_allocate. Open an allocated one from the file system using bitable_read_open. */ typedef struct BitableReadable BitableReadable; /** A cursor - represents a position in the bitable that contains a key value pair. * Cursors index into the leaf level directly (page and item within the leaf page). */ typedef struct BitableCursor { /** The leaf page the cursor is located in. */ uint64_t page; /** The individual item in the page the cursor is located at. */ int32_t item; } BitableCursor; /** Operations that can be used with the find function. */ typedef enum BitableFindOperation { /** Lower bound search - use this to find the item at the start of a range (inclusive). */ BFO_LOWER = 0, /** Upper bound search - use this to find the item at the end of a range (inclusive). */ BFO_UPPER = 1, /** Exact match search - will return an error if the find operation doesn't result in an exact match. */ BFO_EXACT = 2 } BitableFindOperation; /** Allocate a zeroed readable bitable, to be used with bitable_read_open (can be re-used multiple times, when a table is closed). * @return The allocated readable bitable. */ BITABLE_API BitableReadable* bitable_read_allocate(); /** Open a bitable from the file system for reading. * Apart from bitable_read_allocate, this is the only read function that allocates memory directly (memory may be demand paged * for reading from the memory mapped files). * It is safe to open the same path multiple times with different BitableReadable instances, even in different processes. * You should not try and re-use the same BitableReadable instance without closing it. * Closing/opening with regards to the BitableReadable instance are not thread safe operations so they should only be done exclusively. * Memory mapped within bitable_read_open should be protected to be read only. * @param [out] table The previously allocated readable bitable to open into. Should not be null. * @param path The path to the bitable to open, in UTF8 encoding (even on Windows extended charactesr are supported). Should not be null. * @param openFlags The flags to use for opening the bitable - note reading hints will be applied to leaf and large value files only, * @param comparison A comparison function that will be used to compare keys for searching. This should match the sort order when the keys were appended. Should not be null. * @return BR_SUCCESS if the table could be successfully opened for reading, an error code otherwise (BR_ALREADY_OPEN, BR_FILE_OPERATION_FAILED, BR_FILE_TOO_SMALL, BR_HEADER_CORRUPT, BR_FILE_OPEN_FAILED, BR_FILE_TOO_LARGE). */ BITABLE_API BitableResult bitable_read_open( BitableReadable* table, const char* path, BitableReadOpenFlags openFlags, BitableComparisonFunction* comparison ); /** Close the file handles (etc) associated with a previously opened readable bitable. * Note, this operation can be called on an already closed table (idempotence). * This does not free the memory associated with the BitableReadable, so it can be re-used. * Closing/opening with regards to the BitableReadable instance are not thread safe operations so they should only be done exclusively. * @param table The readable bitable to close. Should not be null. * @return BR_SUCCESS if the table could be successfully closed. */ BITABLE_API BitableResult bitable_read_close( BitableReadable* table ); /** Close the file handles (etc) associated with a previously opened readable bitable and frees the memory associated with it. * Note, this operation can be called on an already closed table to de-allocate it. * Closing/opening with regards to the BitableReadable instance are not thread safe operations so they should only be done exclusively. * @param table The readable bitable to close. Should not be null. */ BITABLE_API void bitable_read_free( BitableReadable* table ); /** Get the statistics associated with a particular bitable (including the number of items, depth, page size, key and value alignments etc). * This method is thread-safe on an open table (but the table must be open for the duration of the call). * @param table The open readable bitable to get the stats from. Should not be null. * @param [out] stats The stats from the table. Should not be null. * @return BR_SUCCESS if the stats could successfully be retrieved. */ BITABLE_API BitableResult bitable_readable_stats( const BitableReadable* table, BitableStats* stats ); /** Given a key and find operation, find a matching position in the bitable and populate the cursor with it. * This method is thread-safe on an open table (but the table must be open for the duration of the call), as it does not modify the bitable. * BFO_EXACT searches will only find exact key matches, BFO_LOWER will find the lower inclusive bound of a range. BFO_UPPER will find the upper inclusive bound of a range search. * Note that this function does not allocate memory from the heap, but it may cause memory to be demand paged (memory mapped file). * @param [out] cursor The cursor that will be populated with the find position. Should not be null. * @param table The open readable bitable to find the key in. Should not be null. * @param searchKey The key to search for. Should not be null. * @param operation The operation to use for searching. * @return BR_SUCCESS if the operation is successful. BR_KEY_NOT_FOUND is the operation is BFO_EXACT and the key doesn't exist in the bitable. BR_END_OF_SEQUENCE if the operation is an upper/lower bound and the bound is outside the bitable range. */ BITABLE_API BitableResult bitable_find( BitableCursor* cursor, const BitableReadable* table, const BitableValue* searchKey, BitableFindOperation operation ); /** Populate the cursor with the first position (beginning) of the bitable. * This method is thread-safe on an open table (but the table must be open for the duration of the call). * @param [out] cursor The cursor that will be populated with the first position. Should not be null. * @param table The open readable bitable to get the position of. Should not be null. * @return BR_SUCCESS if the operation is successful. BR_END_OF_SEQUENCE if the bitable is empty. */ BITABLE_API BitableResult bitable_first( BitableCursor* cursor, const BitableReadable* table ); /** Populate the cursor with the last position (at the end) of the bitable. * This method is thread-safe on an open table (but the table must be open for the duration of the call). * @param [out] cursor The cursor that will be populated with the last position. Should not be null. * @param table The open readable bitable to get the position of. Should not be null. * @return BR_SUCCESS if the operation is successful. BR_END_OF_SEQUENCE if the bitable is empty. */ BITABLE_API BitableResult bitable_last( BitableCursor* cursor, const BitableReadable* table ); /** Populate the cursor with the next position from its current value. * This method is thread-safe on an open table (but the table must be open for the duration of the call). * @param [in,out] cursor The cursor that will be incremented to the next position. Should not be null. * @param table The open readable bitable to perform the operation with. Should not be null. * @return BR_SUCCESS if the operation is fdsuccessful. BR_END_OF_SEQUENCE if the next position is beyond the end of the sequence. */ BITABLE_API BitableResult bitable_next( BitableCursor* cursor, const BitableReadable* table ); /** Populate the cursor with the previous position from its current value. * This method is thread-safe on an open table (but the table must be open for the duration of the call). * @param [in,out] cursor The cursor that will be decremented to the previous position. Should not be null. * @param table The open readable bitable to perform the operation with. Should not be null. * @return BR_SUCCESS if the operation is successful. BR_END_OF_SEQUENCE if the next position is beyond the end of the sequence. */ BITABLE_API BitableResult bitable_previous( BitableCursor* cursor, const BitableReadable* table ); /** Read the key at a particular cursor position from the bitable. * This method is thread-safe on an open table (but the table must be open for the duration of the call). * @param cursor The cursor position that will be read from. Should not be null. * @param table The open readable bitable to read from. Should not be null. * @param [out] key The key to read out. Should not be null. * @return BR_SUCCESS if the operation is successful. BR_INVALID_CURSOR_LOCATION if the cursor position isn't valid. */ BITABLE_API BitableResult bitable_key( const BitableCursor* cursor, const BitableReadable* table, BitableValue* key ); /** Read the value at a particular cursor position from the bitable. * This method is thread-safe on an open table (but the table must be open for the duration of the call). * @param cursor The cursor position that will be read from. Should not be null. * @param table The open readable bitable to read from. Should not be null. * @param [out] value The key value read out. * @return BR_SUCCESS if the operation is successful. BR_INVALID_CURSOR_LOCATION if the cursor position isn't valid. */ BITABLE_API BitableResult bitable_value( const BitableCursor* cursor, const BitableReadable* table, BitableValue* value ); /** Read both the key and value value at a particular cursor position from the bitable. * This method is thread-safe on an open table (but the table must be open for the duration of the call). * @param cursor The cursor position that will be read from. Should not be null. * @param table The open readable bitable to read from. Should not be null. * @param [out] key The key to read out. Should not be null. * @param [out] value The key value read out. Should not be null. * @return BR_SUCCESS if the operation is successful. BR_INVALID_CURSOR_LOCATION if the cursor position isn't valid. */ BITABLE_API BitableResult bitable_key_value_pair( const BitableCursor* cursor, const BitableReadable* table, BitableValue* key, BitableValue* value ); /** Read the indice (0 based) at a particular cursor position. * The indice number of key value pairs before the one at the cursor. * This method is thread-safe on an open table (but the table must be open for the duration of the call). * @param cursor The cursor position that will be read from. Should not be null. * @param table The open readable bitable to read from. Should not be null. * @param [out] indice The indice to read out. Should not be null. * @return BR_SUCCESS if the operation is successful. BR_INVALID_CURSOR_LOCATION if the cursor position isn't valid. */ BITABLE_API BitableResult bitable_indice( const BitableCursor* cursor, const BitableReadable* table, uint64_t* indice ); #ifdef __cplusplus } #endif #endif // -- BITABLE_READ_H__
2.203125
2
2024-11-18T22:24:19.977137+00:00
2021-02-04T15:43:10
e63c2d3ba9bfcd2a2a6e291e003483bb2fadfc62
{ "blob_id": "e63c2d3ba9bfcd2a2a6e291e003483bb2fadfc62", "branch_name": "refs/heads/master", "committer_date": "2021-02-04T15:43:10", "content_id": "fe2935b41f572c78257e1e6f97731c7c07f4acf2", "detected_licenses": [ "MIT" ], "directory_id": "78f78bfecc4e3de2bf452178d4e8cbc6758110c4", "extension": "c", "filename": "startup.c", "fork_events_count": 9, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 43736411, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8610, "license": "MIT", "license_type": "permissive", "path": "/samples/cortex/mx-gcc/common/stm32/l0xx/startup.c", "provenance": "stackv2-0115.json.gz:83810", "repo_name": "scmrtos/scmrtos-sample-projects", "revision_date": "2021-02-04T15:43:10", "revision_id": "3b34a485b6ca4b16705c250383ae5d30c81966f1", "snapshot_id": "249f6259b4b7de99854aad10f7de177289d1d3b3", "src_encoding": "UTF-8", "star_events_count": 10, "url": "https://raw.githubusercontent.com/scmrtos/scmrtos-sample-projects/3b34a485b6ca4b16705c250383ae5d30c81966f1/samples/cortex/mx-gcc/common/stm32/l0xx/startup.c", "visit_date": "2021-11-17T14:55:35.186727" }
stackv2
/******************************************************************************* * Startup file for STM32L053 Cortex-M0+ MCU * * The file is prepared for: * * STM32L051xx, STM32L052xx, STM32L053xx * STM32L062xx, STM32L063xx, STM32L061xx *******************************************************************************/ #include <string.h> extern unsigned char _sidata; extern unsigned char _sdata; extern unsigned char _edata; extern unsigned char _sbss; extern unsigned char _ebss; extern unsigned long _estack; extern unsigned long __ctors_start__; extern unsigned long __ctors_end__; extern unsigned long __dtors_start__; extern unsigned long __dtors_end__; void Reset_Handler(void) __attribute__((__interrupt__)); /* Core interrupt vectors */ void NMI_Handler(void); void HardFault_Handler(void); void SVC_Handler(void); void DebugMon_Handler(void); void PendSV_Handler(void); void SysTick_Handler(void); /* Device interrupt vectors */ void WWDG_IRQHandler (void); void PVD_IRQHandler (void); void RTC_IRQHandler (void); void FLASH_IRQHandler (void); void RCC_IRQHandler (void); void RCC_CRS_IRQHandler (void); void EXTI0_1_IRQHandler (void); void EXTI2_3_IRQHandler (void); void EXTI4_15_IRQHandler (void); void TSC_IRQHandler (void); void DMA1_Channel1_IRQHandler (void); void DMA1_Channel2_3_IRQHandler (void); void DMA1_Channel4_5_6_7_IRQHandler(void); void ADC1_COMP_IRQHandler (void); void LPTIM1_IRQHandler (void); void TIM2_IRQHandler (void); void TIM6_DAC_IRQHandler (void); void TIM21_IRQHandler (void); void TIM22_IRQHandler (void); void I2C1_IRQHandler (void); void I2C2_IRQHandler (void); void SPI1_IRQHandler (void); void SPI2_IRQHandler (void); void USART1_IRQHandler (void); void USART2_IRQHandler (void); void LPUART1_IRQHandler (void); void RNG_LPUART1_IRQHandler (void); void AES_LPUART1_IRQHandler (void); void AES_RNG_LPUART1_IRQHandler (void); void LCD_IRQHandler (void); void USB_IRQHandler (void); /****************************************************************************** * * Vector table for a Cortex M0. * ******************************************************************************/ typedef void( *const intfunc )( void ); __attribute__ ((used)) __attribute__ ((section(".isr_vector"))) void (* const g_pfnVectors[])(void) = { (intfunc)((unsigned long)&_estack), /* Core interrupt vectors */ Reset_Handler, NMI_Handler, HardFault_Handler, 0, 0, 0, 0, 0, 0, 0, SVC_Handler, DebugMon_Handler, 0, PendSV_Handler, SysTick_Handler, /* Device interrupt vectors */ WWDG_IRQHandler, /* Window WatchDog */ PVD_IRQHandler, /* PVD through EXTI Line detection */ RTC_IRQHandler, /* RTC through the EXTI line */ FLASH_IRQHandler, /* FLASH */ #if defined (STM32L051xx) || defined (STM32L061xx) RCC_IRQHandler, /* RCC */ #else RCC_CRS_IRQHandler, /* RCC and CRS */ #endif EXTI0_1_IRQHandler, /* EXTI Line 0 and 1 */ EXTI2_3_IRQHandler, /* EXTI Line 2 and 3 */ EXTI4_15_IRQHandler, /* EXTI Line 4 to 15 */ #if defined (STM32L051xx) || defined (STM32L061xx) 0, #else TSC_IRQHandler, /* TSC */ #endif DMA1_Channel1_IRQHandler, // DMA1 Channel 1 DMA1_Channel2_3_IRQHandler, // DMA1 Channel 2 and Channel 3 DMA1_Channel4_5_6_7_IRQHandler, // DMA1 Channel 4, Channel 5, Channel 6 and Channel 7 ADC1_COMP_IRQHandler, // ADC1, COMP1 and COMP2 LPTIM1_IRQHandler, // LPTIM1 0, // Reserved TIM2_IRQHandler, // TIM2 0, // Reserved #if defined (STM32L051xx) || defined (STM32L061xx) TIM6_IRQHandler, // TIM6 #else TIM6_DAC_IRQHandler, // TIM6 and DAC #endif 0, // Reserved 0, // Reserved TIM21_IRQHandler, // TIM21 0, // Reserved TIM22_IRQHandler, // TIM22 I2C1_IRQHandler, // I2C1 I2C2_IRQHandler, // I2C2 SPI1_IRQHandler, // SPI1 SPI2_IRQHandler, // SPI2 USART1_IRQHandler, // USART1 USART2_IRQHandler, // USART2 #if defined (STM32L051xx) LPUART1_IRQHandler, // LPUART1 #elif defined (STM32L052xx) || defined (STM32L053xx) RNG_LPUART1_IRQHandler, // RNG and LPUART1 #elif defined (STM32L061xx) AES_LPUART1_IRQHandler, // AES and LPUART1 #else AES_RNG_LPUART1_IRQHandler, // AES, RNG and LPUART1 #endif #if defined (STM32L053xx) || defined (STM32L063xx) LCD_IRQHandler, // LCD #else 0, #endif #if defined (STM32L052xx) || defined (STM32L053xx) || defined (STM32L062xx) || defined (STM32L063xx) USB_IRQHandler // USB #else 0 #endif }; extern void init_HW(void); extern int main(void); void Reset_Handler(void) { memcpy(&_sdata, &_sidata, &_edata - &_sdata); // copy initialized variables memset(&_sbss, 0, &_ebss - &_sbss); // zero-fill uninitialized variables init_HW(); // initialize hardware before calling constructors // call constructors for(unsigned long *ctors = &__ctors_start__; ctors < &__ctors_end__; ) ((void(*)(void))(*ctors++))(); main(); } /******************************************************************************* * * Provide weak aliases for each Exception handler to the Default_Handler. * As they are weak aliases, any function with the same name will override * this definition. * *******************************************************************************/ #pragma weak NMI_Handler = Default_Handler #pragma weak HardFault_Handler = Default_Handler #pragma weak SVC_Handler = Default_Handler #pragma weak DebugMon_Handler = Default_Handler #pragma weak PendSV_Handler = Default_Handler #pragma weak SysTick_Handler = Default_Handler #pragma weak WWDG_IRQHandler = Default_Handler #pragma weak PVD_IRQHandler = Default_Handler #pragma weak RTC_IRQHandler = Default_Handler #pragma weak FLASH_IRQHandler = Default_Handler #pragma weak RCC_IRQHandler = Default_Handler #pragma weak RCC_CRS_IRQHandler = Default_Handler #pragma weak EXTI0_1_IRQHandler = Default_Handler #pragma weak EXTI2_3_IRQHandler = Default_Handler #pragma weak EXTI4_15_IRQHandler = Default_Handler #pragma weak TSC_IRQHandler = Default_Handler #pragma weak DMA1_Channel1_IRQHandler = Default_Handler #pragma weak DMA1_Channel2_3_IRQHandler = Default_Handler #pragma weak DMA1_Channel4_5_6_7_IRQHandler = Default_Handler #pragma weak ADC1_COMP_IRQHandler = Default_Handler #pragma weak LPTIM1_IRQHandler = Default_Handler #pragma weak TIM2_IRQHandler = Default_Handler #pragma weak TIM6_DAC_IRQHandler = Default_Handler #pragma weak TIM21_IRQHandler = Default_Handler #pragma weak TIM22_IRQHandler = Default_Handler #pragma weak I2C1_IRQHandler = Default_Handler #pragma weak I2C2_IRQHandler = Default_Handler #pragma weak SPI1_IRQHandler = Default_Handler #pragma weak SPI2_IRQHandler = Default_Handler #pragma weak USART1_IRQHandler = Default_Handler #pragma weak USART2_IRQHandler = Default_Handler #pragma weak LPUART1_IRQHandler = Default_Handler #pragma weak RNG_LPUART1_IRQHandler = Default_Handler #pragma weak AES_LPUART1_IRQHandler = Default_Handler #pragma weak AES_RNG_LPUART1_IRQHandler = Default_Handler #pragma weak LCD_IRQHandler = Default_Handler #pragma weak USB_IRQHandler = Default_Handler void Default_Handler(void) { for (;;); }
2.078125
2
2024-11-18T22:24:20.413020+00:00
2017-10-19T23:39:44
4dce8560e6ff12e879b146668bf37fe25740355d
{ "blob_id": "4dce8560e6ff12e879b146668bf37fe25740355d", "branch_name": "refs/heads/master", "committer_date": "2017-10-19T23:39:44", "content_id": "f9721f8aab086c03549cb0e081434acb9954d4e7", "detected_licenses": [ "MIT" ], "directory_id": "7c70978579edb4a17c4cf3e1a34d89c082df19a3", "extension": "c", "filename": "resolve.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": 5919, "license": "MIT", "license_type": "permissive", "path": "/resolve.c", "provenance": "stackv2-0115.json.gz:84326", "repo_name": "nh2/fsnoop", "revision_date": "2017-10-19T23:39:44", "revision_id": "4b8d0c4ff62dd4623a49dee143cc66e914398d34", "snapshot_id": "22562a7e5d1deadb4505a4d7aa8e412746fe337a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nh2/fsnoop/4b8d0c4ff62dd4623a49dee143cc66e914398d34/resolve.c", "visit_date": "2021-05-06T19:26:28.752644" }
stackv2
#include <errno.h> #include <linux/limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/fanotify.h> #include <unistd.h> #include "cache.h" extern unsigned char optCache; ssize_t sprintmask (const unsigned long long mask, char* dst) { char* dest = dst; int retlen = 0, len = 0; // Was this a FAN_ACCESS? if (mask & FAN_ACCESS) { // Sure enough. Append some nice output len = sprintf (dest, "Access,"); // Move the dest pointer to the new end dest += len; // Make the length longerererer retlen += len; } // Was this a FAN_MODIFY? if (mask & FAN_MODIFY) { // Sure enough. Append some nice output len = sprintf (dest, "Modify,"); // Move the dest pointer to the new end dest += len; // Make the length longerererer retlen += len; } // Was this a FAN_CLOSE_WRITE? if (mask & FAN_CLOSE_WRITE) { // Sure enough. Append some nice output len = sprintf (dest, "Close+Write,"); // Move the dest pointer to the new end dest += len; // Make the length longerererer retlen += len; } // Was this a FAN_CLOSE_NOWRITE? if (mask & FAN_CLOSE_NOWRITE) { // Sure enough. Append some nice output len = sprintf (dest, "Close,"); // Move the dest pointer to the new end dest += len; // Make the length longerererer retlen += len; } // Was this a FAN_OPEN? if (mask & FAN_OPEN) { // Sure enough. Append some nice output len = sprintf (dest, "Open,"); // Move the dest pointer to the new end dest += len; // Make the length longerererer retlen += len; } // Was this a FAN_Q_OVERFLOW? if (mask & FAN_Q_OVERFLOW) { // Sure enough. Append some nice output len = sprintf (dest, "Overflow,"); // Move the dest pointer to the new end dest += len; // Make the length longerererer retlen += len; } // Was this a FAN_OPEN_PERM? if (mask & FAN_OPEN_PERM) { // Sure enough. Append some nice output len = sprintf (dest, "Open+PermissionCheck,"); // Move the dest pointer to the new end dest += len; // Make the length longerererer retlen += len; } // Was this a FAN_ACCESS_PERM? if (mask & FAN_ACCESS_PERM) { // Sure enough. Append some nice output len = sprintf (dest, "Access+PermissionCheck,"); // Move the dest pointer to the new end dest += len; // Make the length longerererer retlen += len; } // Was this a FAN_ONDIR? if (mask & FAN_ONDIR) { // Sure enough. Append some nice output len = sprintf (dest, "Directory,"); // Move the dest pointer to the new end dest += len; // Make the length longerererer retlen += len; } // Was this a FAN_EVENT_ON_CHILD? if (mask & FAN_EVENT_ON_CHILD) { // Sure enough. Append some nice output len = sprintf (dest, "ChildInfo,"); // Move the dest pointer to the new end dest += len; // Make the length longerererer retlen += len; } // Did we write anything? if (dest != dst) { // Aww yissss! Move dest back one byte so it's on the last comma dest--; // Shorten the length by one because we backed up retlen--; } // Set the last byte to NULL *dest = '\0'; // Return the length return (retlen); } void fileByFD (int fd, char* dst, ssize_t len) { char fdPath [PATH_MAX], filePath [PATH_MAX]; ssize_t filePathLen; // Clear all the buffers memset (fdPath, 0, sizeof (fdPath)); memset (filePath, 0, sizeof (filePath)); memset (dst, 0, len); // Build the fd path buffer sprintf (fdPath, "/proc/self/fd/%d", fd); // Read the fd symlink filePathLen = readlink (fdPath, filePath, sizeof (filePath) - 1); // Did we get a path? if (filePathLen == -1) { // No :-( strncpy (dst, "(unknown)", len - 1); } else { // Yes! strncpy (dst, filePath, len - 1); } } void exeByPID (int pid, char* dst, ssize_t len) { char exePath [PATH_MAX], filePath [PATH_MAX]; ssize_t filePathLen; // Clear all the buffers memset (exePath, 0, sizeof (exePath)); memset (filePath, 0, sizeof (filePath)); memset (dst, 0, len); // Build the PID path buffer sprintf (exePath, "/proc/%d/exe", pid); // Read the exe symlink filePathLen = readlink (exePath, filePath, sizeof (filePath) - 1); // Did we get a path? if (filePathLen == -1) { // No, Are we using the cache? if (optCache) { // Gimme the cash! pidCacheGet (pid, filePath, PATH_MAX, NULL, 0); // Did the cache have anything? if (strlen (filePath) == 0) { // No :-( strncpy (dst, "(unknown)", len - 1); } else { // Sure did! strncpy (dst, filePath, len - 1); } } else { // No cache strncpy (dst, "(unknown)", len - 1); } } else { // Yes! strncpy (dst, filePath, len - 1); // Set the PID->exe in the cache pidCacheSet (pid, filePath, NULL); } } void cmdlineByPID (int pid, char* dst, ssize_t len) { char cmdlinePath [PATH_MAX]; char* buffer; ssize_t bufferLen = 0; int offset; FILE* fd; // Clear all the buffers memset (cmdlinePath, 0, sizeof (cmdlinePath)); memset (dst, 0, len); // Build the PID path buffer sprintf (cmdlinePath, "/proc/%d/cmdline", pid); // Open the cmdline file fd = fopen (cmdlinePath, "r"); // Did it open? if (fd == NULL) { // No return; } // Move to the end of the cmdline fseek (fd, 0, SEEK_END); // Get the current position to see how long the file is bufferLen = ftell (fd); // Move back to the beginning so we can read fseek (fd, 0, SEEK_SET); // Allocate a buffer to fit the cmdline file buffer = malloc (bufferLen + 1); // Allocated? if (buffer == NULL) { // Shizzle fclose (fd); // Bail return; } // Read in the file fread (buffer, bufferLen, 1, fd); // Close it fclose (fd); // Move through every byte in the file for (offset = 0; offset < bufferLen - 1; offset++) { // If it's a NULL... if (*(buffer + offset) == '\0') { // Change it to a space *(buffer + offset) = ' '; } } // Copy upto len bytes from the cmdline to the return buffer strncpy (dst, buffer, len); // Free the buffer free (buffer); }
2.34375
2
2024-11-18T22:24:20.490947+00:00
2022-05-10T01:09:55
b606aa8f1afc04ad462a28ccce7bff85d282f279
{ "blob_id": "b606aa8f1afc04ad462a28ccce7bff85d282f279", "branch_name": "refs/heads/master", "committer_date": "2022-05-10T01:09:55", "content_id": "34c35e3322ff28e343381aea0dd0f9a790b47c2e", "detected_licenses": [ "MIT" ], "directory_id": "88da1ccdd6d5a76ebfd2c91e1d367da1d1477cee", "extension": "c", "filename": "move.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 85685521, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3461, "license": "MIT", "license_type": "permissive", "path": "/Year-3/Client-Server-Programming/SocketFiles/move.c", "provenance": "stackv2-0115.json.gz:84454", "repo_name": "CrimsonPrince/College-Work", "revision_date": "2022-05-10T01:09:55", "revision_id": "02fb65b0902d0dc899b843a297ab0e412fdf75fc", "snapshot_id": "ea943199a5e922ec232e087dbf494522dcbc9150", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/CrimsonPrince/College-Work/02fb65b0902d0dc899b843a297ab0e412fdf75fc/Year-3/Client-Server-Programming/SocketFiles/move.c", "visit_date": "2022-05-26T02:11:10.047169" }
stackv2
#include < stdio.h > #include < stdlib.h > #include < string.h > #include < unistd.h > #include < sys / types.h > #include < sys / socket.h > #include < netinet / in .h > #include < arpa / inet.h > #include "Practical.h" int main(int argc, char * argv[]) { char recvbuffer[BUFSIZE], sendbuffer[BUFSIZE], request_resp[20], balance_msg[20]; // text buffers 13 int scanfRtn = 0, numBytes = 0, credit = 0, balance = 0, charge_req = 10; ssize_t numBytesSent; if (argc < 3) // Test for correct number of arguments DieWithUserMessage("Parameter(s)", "<Server Address> <Server Port>"); char * servIP = argv[1]; // First arg: server IP address (dotted quad) in_port_t servPort = atoi(argv[2]); // Create a reliable, stream socket using TCP 25 int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sock < 0) DieWithSystemMessage("socket() failed"); // Construct the server address structure struct sockaddr_in servAddr; // Server address memset( & servAddr, 0, sizeof(servAddr)); // Zero out structure servAddr.sin_family = AF_INET; // IPv4 address family // Convert IP address int rtnVal = inet_pton(AF_INET, servIP, & servAddr.sin_addr.s_addr); if (rtnVal == 0) DieWithUserMessage("inet_pton() failed", "invalid address string"); else if (rtnVal < 0) DieWithSystemMessage("inet_pton() failed"); servAddr.sin_port = htons(servPort); // Server port // Establish the connection to the movieServer if (connect(sock, (struct sockaddr * ) & servAddr, sizeof(servAddr)) < 0) DieWithSystemMessage("connect() failed"); snprintf(sendbuffer, sizeof(sendbuffer), "MOVIE_REQUEST: %d\r\n\r\n", charge_req); numBytesSent = send(sock, sendbuffer, strlen(sendbuffer), 0); if (numBytesSent < 0) DieWithSystemMessage("send() failed"); while ((numBytes = recv(sock, recvbuffer, BUFSIZE - 1, 0)) > 0) { if (strstr(recvbuffer, "\r\n\r\n") > 0) break; } if (numBytes < 0) DieWithSystemMessage("recv() failed"); sscanf(recvbuffer, "%s\r\n%s %d", request_resp, balance_msg, & balance); // message expected is of the form //MOVIE_GRANTED\r\nCURRENT_BALANCE: %d\r\n\r\n //or, MOVIE_REJECTED\r\nCURRENT_BALANCE: %d\r\n\r\n if (strcmp(request_resp, "MOVIE_GRANTED") == 0) { printf("\nYou can download your movie. Your new balance is: %d\n\n", balance); } //end If else { printf("\nYou do not have enough credit. Please top-up your account.\n\n"); do { printf("\nEnter top-up amount (minimum is 10 credits): "); while ((scanfRtn = scanf("%d", & credit)) != 1) // checking for non-numeric values { printf("\rEnter a numeric value: "); getchar(); //eliminating non-numeric values } } while (credit < 10); //end user-entry do-while loop memset(sendbuffer, 0, BUFSIZE); //initialze sendbuff to all zeroes before use snprintf(sendbuffer, sizeof(sendbuffer), "TOP_UP: %d\r\n\r\n", credit); numBytesSent = send(sock, sendbuffer, strlen(sendbuffer), 0); if (numBytesSent < 0) DieWithSystemMessage("send() failed"); } //end Else fputc('\n', stdout); // Print a final linefeed 95 close(sock); //close the connected socket exit(0); //exit the program gracefully }
2.78125
3
2024-11-18T22:24:20.544576+00:00
2021-11-14T17:41:45
58402b890763594d66faee88624d6a746863d1bf
{ "blob_id": "58402b890763594d66faee88624d6a746863d1bf", "branch_name": "refs/heads/master", "committer_date": "2021-11-14T17:41:45", "content_id": "d68da677a24f5c908635ef6ac4c17b004899896a", "detected_licenses": [ "Apache-2.0" ], "directory_id": "4a9e8189b0bdd1d74775c946f0f80677d7460ef0", "extension": "h", "filename": "testdef.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 101104836, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 930, "license": "Apache-2.0", "license_type": "permissive", "path": "/test/testdef.h", "provenance": "stackv2-0115.json.gz:84583", "repo_name": "akwilson/collections", "revision_date": "2021-11-14T17:41:45", "revision_id": "b5746883f567c89b7386536d2fc15c5094530241", "snapshot_id": "6603e841291ea4c9caef533a2007f818022881e1", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/akwilson/collections/b5746883f567c89b7386536d2fc15c5094530241/test/testdef.h", "visit_date": "2021-12-02T15:41:58.025251" }
stackv2
#ifndef TESTDEF_H #define TESTDEF_H // == RESIZE ARRAY ============================================================ char *ra_add(void); char *ra_add_adjust(void); char *ra_remove(void); char *ra_remove_adjust(void); char *ra_check_errors(void); char *ra_exchange(void); char *ra_copy_array(void); char *ra_insert(void); char *ra_replace(void); // == PRIORITY QUEUE ========================================================== char *pq_add_items(void); char *pq_peek_items(void); char *pq_pop_items(void); char *pq_pop_items_max(void); char *pq_iterate_items(void); char *pq_copy_queue(void); // == HASH TABLE ============================================================== char *ht_add_items(void); char *ht_replace(void); char *ht_get_items(void); char *ht_iterate_sparse(void); char *ht_iterate(void); char *ht_iterate_sparse_ish(void); char *ht_iterate_empty(void); char *ht_remove_items(void); char *ht_copy(void); #endif
2
2
2024-11-18T22:24:21.614306+00:00
2023-03-03T16:51:16
2085a533898fdc67d82a32934d7f44909999a517
{ "blob_id": "2085a533898fdc67d82a32934d7f44909999a517", "branch_name": "refs/heads/master", "committer_date": "2023-03-03T16:51:16", "content_id": "5e5735f4d320b452f480c2307c16c6643194092a", "detected_licenses": [ "Apache-2.0" ], "directory_id": "8b7ca87e28214dac0756b03467be4963fe3cdba6", "extension": "c", "filename": "console-interface.c", "fork_events_count": 0, "gha_created_at": "2014-08-08T07:13:15", "gha_event_created_at": "2023-02-25T12:28:44", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 22749230, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5542, "license": "Apache-2.0", "license_type": "permissive", "path": "/sidplayer/console-interface.c", "provenance": "stackv2-0115.json.gz:84713", "repo_name": "jgilje/reveller", "revision_date": "2023-03-03T16:51:16", "revision_id": "73f9a5873c3f54e04f1b53d93f8fcd466b7cfd47", "snapshot_id": "34a797fb2b36dad6fc63dff3a0ff5892cf8082a6", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/jgilje/reveller/73f9a5873c3f54e04f1b53d93f8fcd466b7cfd47/sidplayer/console-interface.c", "visit_date": "2023-03-05T01:36:00.749903" }
stackv2
#include "console-interface.h" #include "platform-support.h" #include "6510.h" #if defined unix || (defined(__APPLE__) && defined(__MACH__)) #include <termios.h> #include <unistd.h> #include <fcntl.h> #include <poll.h> #endif #if defined _WIN32 #include <conio.h> #endif void continuosPlay(void) { reveller->resume(); #if defined unix || (defined(__APPLE__) && defined(__MACH__)) struct termios currentTerm; struct termios originalTerm; tcgetattr(STDIN_FILENO, &currentTerm); originalTerm = currentTerm; currentTerm.c_lflag &= ~(ECHO | ICANON | IEXTEN); currentTerm.c_cc[VMIN] = 1; currentTerm.c_cc[VTIME] = 0; tcsetattr(STDIN_FILENO, TCSANOW, &currentTerm); printf("Playing... (any key to stop)..."); fflush(stdout); if (reveller->write_handle) { struct pollfd pollfds[2]; memset(&pollfds, 0, sizeof(struct pollfd) * 2); pollfds[0].fd = STDIN_FILENO; pollfds[0].events = POLLIN; pollfds[1].fd = reveller->write_handle(); pollfds[1].events = POLLOUT; int ok = 1; while (ok) { int ret = poll(&pollfds[0], 2, -1); if (ret > 0) { if (pollfds[0].revents & POLLIN) { ok = 0; } if (pollfds[1].revents & POLLOUT) { int32_t next = c64_play(); reveller->usleep(next); } } else { reveller->abort("Failed poll() in continuosPlay()\n"); ok = 0; } } } else { int originalFcntl = fcntl(STDIN_FILENO, F_GETFL, 1); if (fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK) < 0) { reveller->abort("Failed to set stdin nonblocking\n"); } while (getc(stdin) < 0) { int32_t next = c64_play(); reveller->usleep(next); } if (fcntl(STDIN_FILENO, F_SETFL, originalFcntl) < 0) { reveller->abort("Failed to restore stdin\n"); } } tcsetattr(STDIN_FILENO, TCSAFLUSH, &originalTerm); printf("\n"); fflush(stdout); #elif defined _WIN32 while (! _kbhit()) { int32_t next = c64_play(); next = next * ((float) sh.hz / 1000000.0f); platform_usleep(next); } _getch(); printf("\n"); fflush(stdout); #else #error Unimplemented continuosPlay for this platform #endif reveller->pause(); } char* nextToken(char* in) { int i; for (i = 0; i < strlen(in); i++) { if (in[i] == ' ') { in[i] = 0x0; return(&in[i + 1]); } } return NULL; } void console_interface(void) { char input[256]; char *args; int song = 0; int interactive = 0; while(1) { printf("6510> "); input[0] = 0x0; fgets(input, 256, stdin); if (input[0] == 0x0) { printf("\n"); exit(0); } input[strlen(input) - 1] = 0x0; args = nextToken(input); if (! strcmp(input, "help") || ! strcmp(input, "h")) { printf("\n6510 Commands\n" "(h)elp\n" "(p)lay [iterations]\n" "(s)ong <subgsong>\n" "(l)oad <file>\n" "(d)umpmem\n" "(i)nteractive (toggle)\n" "power <on/off>\n" "(q)uit\n" ); } else if (! strcmp(input, "load") || ! strcmp(input, "l")) { if (reveller_input_file) { fclose(reveller_input_file); } reveller_input_file = fopen(args, "rb"); if (reveller_input_file == 0) { printf("ERROR: File %s not found\n", args); } c64_setSubSong(0); } else if (! strcmp(input, "play") || ! strcmp(input, "p")) { int i; if (! reveller_input_file) { printf("No SID is loaded\n"); continue; } if (args) { i = strtoul(args, NULL, 0); if (i < 0) { printf("Invalid song\n"); continue; } } else { continuosPlay(); continue; } // sanitize input (code scanners get happy) if (i > 0xffff) { i = 0xffff; } // START PLAY printf("Starting PlayAddr %d times\n", i); { int j; reveller->resume(); for (j = 0; j < i; j++) { c64_play(); reveller->usleep(1000000 / 55); } reveller->pause(); } } else if (! strcmp(input, "song") || ! strcmp(input, "s")) { int i; if (! reveller_input_file) { printf("No SID is loaded\n"); continue; } if (args) { i = strtoul(args, NULL, 0); if (i < 0) { printf("Invalid song\n"); continue; } song = i; c64_setSubSong(song); printf("Song is now %d\n", song); continuosPlay(); } } else if (! strcmp(input, "dump") || ! strcmp(input, "d")) { c64_dumpMem(); } else if (! strcmp(input, "quit") || ! strcmp(input, "q")) { if (reveller->shutdown) { reveller->shutdown(); } fflush(NULL); printf("Bye\n"); exit(0); } else if (! strcmp(input, "interactive") || ! strcmp(input, "i")) { if (interactive) { printf("Disabling interactive mode\n"); interactive = 0; reveller->pause(); } else { printf("Enabling interactive mode\n"); interactive = 1; reveller->resume(); } } else if (! strcmp(input, "power")) { if (! strcmp(args, "on")) { reveller->power(1); } else if (! strcmp(args, "off")) { reveller->power(0); } } else if (interactive && reveller_input_file) { printf("Starting PlayAddr 1 time\n"); interpret(1, sh.playAddress); } fflush(stdout); } }
2.140625
2
2024-11-18T22:24:21.833413+00:00
2014-08-25T12:15:58
d6682379f38bdb6f7c886f7b881da40aac001eb9
{ "blob_id": "d6682379f38bdb6f7c886f7b881da40aac001eb9", "branch_name": "refs/heads/master", "committer_date": "2014-08-25T12:15:58", "content_id": "a409624d8a1511a746f381e503f37493452feaca", "detected_licenses": [ "MIT" ], "directory_id": "8ddc56d6f6b7be0d8ba756ab9e85c6a82a8ed7ae", "extension": "c", "filename": "memtr.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 23311848, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2730, "license": "MIT", "license_type": "permissive", "path": "/memtr.c", "provenance": "stackv2-0115.json.gz:84972", "repo_name": "Kervius/memtr", "revision_date": "2014-08-25T12:15:58", "revision_id": "27c7bd93ac2a85335cab5129d9857c91a9f7a476", "snapshot_id": "8a855cf62545a4e0f09f4eb04b252fcf098ba832", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Kervius/memtr/27c7bd93ac2a85335cab5129d9857c91a9f7a476/memtr.c", "visit_date": "2016-08-04T16:07:37.616273" }
stackv2
#define _GNU_SOURCE 1 #include <stdlib.h> #include <stdio.h> #include <string.h> #include <dlfcn.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> static int is_initd = 0; static int is_on = 0; static int memtr_fd = -1; typedef void *(*malloc_type)(size_t size); typedef void (*free_type)(void *ptr); typedef void *(*calloc_type)(size_t nmemb, size_t size); typedef void *(*realloc_type)(void *ptr, size_t size); static malloc_type orig_malloc; static free_type orig_free; static calloc_type orig_calloc; static realloc_type orig_realloc; static void memtr_init() { char *p; if (is_initd) return; is_initd = 1; p = getenv("MEMTR"); if (p) { memtr_fd = open( p, O_CREAT|O_TRUNC|O_RDWR, 0666 ); } orig_malloc = (malloc_type)dlsym( RTLD_NEXT, "malloc" ); orig_free = (free_type)dlsym( RTLD_NEXT, "free" ); orig_calloc = (calloc_type)dlsym( RTLD_NEXT, "calloc" ); orig_realloc = (realloc_type)dlsym( RTLD_NEXT, "realloc" ); if (orig_malloc && orig_free && orig_realloc && orig_calloc && memtr_fd >= 0) { is_on = 1; } } void itoa(unsigned long i, char *b) { unsigned long shifter = i; char *p = b; do { ++p; shifter = shifter/10; } while (shifter); *p = '\0'; do { *--p = '0' + i%10; i = i/10; } while (i); } void itox(unsigned long i, char *b) { static const char hd[16] = "0123456789abcdef"; int k; *b = '0'; b++; *b = 'x'; b++; for (k=sizeof(long)-1; k>=0; k--) { unsigned long mask = 0xf0 << (k*8); *b = hd[ ((i & mask)>>4) >> (k*8) ]; b++; *b = hd[ (i & (mask>>4)) >> (k*8) ]; b++; } *b = 0; } static void memtr_print( const char *name, size_t size, void *ptr ) { char buf1[128], buf2[32]; char *p; int len; if (is_on) { p = buf1; len = strlen(name); memcpy( p, name, len ); p += len; *p = '\t'; p++; itoa( (int)size, buf2 ); len = strlen( buf2 ); memcpy( p, buf2, len ); p += len; *p = '\t'; p++; itox( (unsigned long)ptr, buf2 ); len = strlen( buf2 ); memcpy( p, buf2, len ); p += len; *p = '\n'; p++; write( memtr_fd, buf1, p - buf1 ); } } void *malloc(size_t size) { void *p; memtr_init(); memtr_print( "m<", size, 0 ); p = orig_malloc( size ); memtr_print( "m>", size, p ); return p; } void free(void *ptr) { memtr_init(); memtr_print( "f<", 0, ptr ); orig_free( ptr ); memtr_print( "f>", 0, ptr ); } void *calloc(size_t nmemb, size_t size) { void *p; memtr_init(); memtr_print( "c<", nmemb*size, 0 ); p = orig_calloc( nmemb, size ); memtr_print( "c>", nmemb*size, p ); return p; } void *realloc(void *ptr, size_t size) { void *p; memtr_init(); memtr_print( "r<", size, ptr ); p = orig_realloc( ptr, size ); memtr_print( "r>", size, p ); return p; }
2.78125
3
2024-11-18T22:24:26.035289+00:00
2023-08-20T06:13:11
2a1d7dd314e4507b1731464015ace7343ee8748b
{ "blob_id": "2a1d7dd314e4507b1731464015ace7343ee8748b", "branch_name": "refs/heads/master", "committer_date": "2023-08-20T06:13:11", "content_id": "5b6ab81ac3f5ab32f29ab1790e7c8345b60d14fa", "detected_licenses": [ "MIT" ], "directory_id": "309e1045a872514f82e7b3987f97b38c28b03e41", "extension": "c", "filename": "ffmpeg_sound_player.c", "fork_events_count": 9, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 19373094, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6965, "license": "MIT", "license_type": "permissive", "path": "/rouziclib/fileio/ffmpeg_sound_player.c", "provenance": "stackv2-0115.json.gz:85101", "repo_name": "Photosounder/rouziclib", "revision_date": "2023-08-20T06:13:11", "revision_id": "fdc965964b13edf8c110fb1258d422856b5180dc", "snapshot_id": "ca51421f59389ed153cbd9598b7045772fdeed9b", "src_encoding": "UTF-8", "star_events_count": 43, "url": "https://raw.githubusercontent.com/Photosounder/rouziclib/fdc965964b13edf8c110fb1258d422856b5180dc/rouziclib/fileio/ffmpeg_sound_player.c", "visit_date": "2023-08-24T23:51:23.023879" }
stackv2
#ifdef RL_FFMPEG int audio_player_load_thread(audio_player_data_t *data) { int i, ip=-1, must_seek=0, ip0=-1, ip1; double ts_req=0., ts0=NAN, ts0_end=0., ts1=NAN; ffframe_info_t info; int ret=0, sample_count; float *buf=NULL; size_t buf_as=0, buf_pos=0; while (data->thread_on) { loop_start: rl_mutex_lock(&data->mutex); // if we're jumping back or forward if (data->speed < 0. || data->ts_req < ts_req || (data->ts_req - ts1 > 60. && isnan(ts1)==0)) { ip = -1; ts0 = NAN; ts0_end = 0.; ts1 = NAN; must_seek = 1; ip0 = -1; ip1 = -1; } ts_req = data->ts_req; rl_mutex_unlock(&data->mutex); // Pause the loading if the frame to be replaced next is still needed if (ts_req >= ts0 && ts_req < ts0_end && must_seek==0 && data->thread_on && circ_index(ip+1, data->frame_as)==ip0) { sleep_ms(1); goto loop_start; } if (llabs(double_diff_ulp(data->speed, 1.)) < 100) { // Load the frame, either by seeking or sequentially buf_pos = 0; ret = ff_load_audio_fl32(data->stream, data->path, must_seek, ts_req, &buf, &buf_as, &buf_pos); if (ret >= 0) sample_count = data->stream->frame->nb_samples; } if (ret <= 0) sleep_ms(20); // if the frame was empty just wait else { info = ff_make_frame_info(data->stream); rl_mutex_lock(&data->mutex); // Add the frame to the tables ip = circ_index(ip + 1, data->frame_as); // if new frame replaces old frame[ip0] if (ip==ip0) { ip0 = circ_index(ip + 1, data->frame_as); ts0 = data->frame[ip0].info.ts; ts0_end = data->frame[ip0].info.ts_end; } if (isnan(ts0)) // init ts0 { ip0 = ip; ts0 = MINN(ts_req, info.ts); // in case info.ts is higher than ts_req ts0_end = info.ts_end; } ts1 = info.ts_end; ip1 = ip; data->frame[ip].used = 1; data->frame[ip].sample_count = sample_count; data->frame[ip].channels = data->stream->frame->ch_layout.nb_channels; data->frame[ip].samplerate = data->stream->codec_ctx->sample_rate; alloc_enough_and_copy(&data->frame[ip].buffer, buf, data->frame[ip].len = ret, &data->frame[ip].as, sizeof(float), 1.); data->frame[ip].info = info; if (must_seek==0) data->frame[ip].info.ts = data->frame[circ_index(ip - 1, data->frame_as)].info.ts_end; data->frame[ip].info.ts_end = data->frame[ip].info.ts + (double) sample_count / data->frame[ip].samplerate; rl_mutex_unlock(&data->mutex); } must_seek = 0; } ffstream_close_free(data->stream); return 0; } void audio_player_thread_exit(audio_player_data_t *data) { int i; rl_mutex_lock(&data->mutex); for (i=0; i < data->frame_as; i++) { free(data->frame[i].buffer); memset(&data->frame[i], 0, sizeof(audframe_t)); } rl_mutex_unlock(&data->mutex); } void audio_player_main(audio_player_data_t *data, char *path, double ts_req, double speed, double volume) { int start_thread=1, stop_thread=1, jump=0; // Close the old stream and open the new one if (path && data->path) if (strcmp(path, data->path)==0) { start_thread = 0; stop_thread = 0; } if (path==NULL) start_thread = 0; // Init the data if (data->init==0) { data->init = 1; rl_mutex_init(&data->mutex); data->frame = calloc(data->frame_as = 600, sizeof(audframe_t)); data->stream = calloc(1, sizeof(ffstream_t)); } if (stop_thread) { data->thread_on = 0; audiosys_bus_unregister(data); audio_player_thread_exit(data); free_null(&data->path); } if (start_thread) { // Initialise new data data->path = make_string_copy(path); data->duration = ff_get_audio_duration(NULL, data->path); data->ts_req = 0.; data->ifr = -1; data->is = -1; data->thread_on = 1; rl_thread_create(&data->thread_handle, audio_player_load_thread, data); } // Update values rl_mutex_lock(&data->mutex); if (fabs(data->ts_cb - ts_req) > 2. * audiosys.sec_per_buf + 0.05) // FIXME calculate whether to jump or not better jump = 1; if (jump) fprintf_rl(stdout, "jump to ts %.4f\n", ts_req); // Set the time offset if (jump || start_thread) data->ts_cb = ts_req; //data->time_offset = get_time_hr() - ts_req; data->ts_req = rangelimit(ts_req - 1., 0., data->duration); data->speed = speed; data->volume = volume; rl_mutex_unlock(&data->mutex); // Register the callback int audio_bus_index = audiosys_bus_register(audio_player_callback, data, 0, 0.); } void audio_player_callback(float *stream, audiosys_t *sys, int bus_index, audio_player_data_t *data) { int i, ifr; double t, ibl, vol_t; int debug=1; // Deinit if (stream==NULL) { data->thread_on = 0; if (bus_index == -1) // this signals a blocking deinitialisation rl_thread_join_and_null(&data->thread_handle); data->vol1 = NAN; return; } // Only play if speed == 1 and thread_on if (fabs(data->speed - 1.) >= 2e-14 || data->thread_on==0) { data->vol1 = NAN; return; } rl_mutex_lock(&data->mutex); // Prepare volume interpolation data->vol0 = data->vol1; if (isnan(data->vol0)) data->vol0 = data->volume; data->vol1 = data->volume; ibl = 1. / (double) sys->buffer_len; // Go through each sample for (t=data->ts_cb, i=0; i < sys->buffer_len; i++, t+=sys->sec_per_sample) { // Search for frame when no frame is selected if (data->ifr = -1) { // Search for frame that contains the requested timestamp for (ifr=0; ifr < data->frame_as; ifr++) if (t >= data->frame[ifr].info.ts && t < data->frame[ifr].info.ts_end) { data->ifr = ifr; data->is = (t - data->frame[ifr].info.ts) * data->frame[ifr].samplerate; if (data->is > data->frame[ifr].sample_count-1) data->ifr = -1; else break; } } // Interpolate volume vol_t = mix(data->vol0, data->vol1, (double) i * ibl); //if (data->vol0 != data->vol1 && ((i & 0xFF) == 0 || i == sys->buffer_len -1)) fprintf_rl(stdout, "mix(%.6f , %.6f, %.6f) = %.6f (%4d/%4d)\n", data->vol0, data->vol1, (double) i * ibl, vol_t, i, sys->buffer_len); // Copy samples from frame if (data->ifr != -1) { if (data->frame[data->ifr].channels==1) { stream[i*2 ] += data->frame[data->ifr].buffer[data->is] * vol_t; stream[i*2+1] += data->frame[data->ifr].buffer[data->is] * vol_t; } else { stream[i*2 ] += data->frame[data->ifr].buffer[data->is*data->frame[data->ifr].channels] * vol_t; stream[i*2+1] += data->frame[data->ifr].buffer[data->is*data->frame[data->ifr].channels + 1] * vol_t; } } else if (debug) { debug = 0; double min_ts=1e9, max_ts=-1.; for (ifr=0; ifr < data->frame_as; ifr++) { min_ts = MINN(min_ts, data->frame[ifr].info.ts); max_ts = MAXN(max_ts, data->frame[ifr].info.ts_end); } fprintf_rl(stdout, "No sample for ts %.4f (ts available: %.4f to %.4f\n", t, min_ts, max_ts); } // Iterate to next sample data->is++; if (data->is == data->frame[data->ifr].sample_count) { data->ifr = -1; } } data->ts_cb += sys->sec_per_buf; rl_mutex_unlock(&data->mutex); } #endif
2.1875
2
2024-11-18T22:24:26.107079+00:00
2015-03-25T14:41:52
4db2e1d3ed95e4355dc9595ef668f6a2b982beae
{ "blob_id": "4db2e1d3ed95e4355dc9595ef668f6a2b982beae", "branch_name": "refs/heads/master", "committer_date": "2015-03-25T14:41:52", "content_id": "cf18ea989566279d141ba0a496a7c028f62168b0", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "e403b58518257b03d1d16ee1244958d03693332e", "extension": "c", "filename": "helpers.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 32690494, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 647, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/helpers.c", "provenance": "stackv2-0115.json.gz:85229", "repo_name": "bceverly/privateim", "revision_date": "2015-03-25T14:41:52", "revision_id": "144f81f86187dd0b4fc11bbd2e4d76097d7784b2", "snapshot_id": "61358219bad86ce661f759ee1f323a9b342c3ad6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bceverly/privateim/144f81f86187dd0b4fc11bbd2e4d76097d7784b2/src/helpers.c", "visit_date": "2021-01-10T20:20:42.871554" }
stackv2
#include <stdio.h> #include <string.h> #include "helpers.h" #ifdef __OSX__ size_t strlcpy(char *dst, const char *src, size_t dstsize) { strncpy(dst, src, dstsize); dst[dstsize] = 0x00; } size_t strlcat(char *dst, const char *src, size_t dstsize) { strncat(dst, src, dstsize); dst[dstsize] = 0x00; } #endif void trim_str(char *in_string, int string_len) { char tmp_buf[string_len + 1]; tmp_buf[0] = 0x00; int in_pos = 0; int out_pos = 0; for (in_pos = 0 ; in_pos < string_len ; in_pos++) { if (in_string[in_pos] != '\n') { tmp_buf[out_pos] = in_string[in_pos]; out_pos++; } } strncpy(in_string, tmp_buf, string_len); }
2.796875
3
2024-11-18T22:24:26.632829+00:00
2023-08-30T23:07:48
8e5b2908b2c61d3e0fd57b02f2d5dd5440b47336
{ "blob_id": "8e5b2908b2c61d3e0fd57b02f2d5dd5440b47336", "branch_name": "refs/heads/master", "committer_date": "2023-08-30T23:07:48", "content_id": "99834a3b69e4b811f558e1b78df6b345ef9e4eec", "detected_licenses": [ "PostgreSQL" ], "directory_id": "8a51a96f61699f0318315ccc89cef39f6866f2b5", "extension": "c", "filename": "recovery_gen.c", "fork_events_count": 4807, "gha_created_at": "2010-09-21T11:35:45", "gha_event_created_at": "2023-09-09T13:59:15", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 927442, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4141, "license": "PostgreSQL", "license_type": "permissive", "path": "/src/fe_utils/recovery_gen.c", "provenance": "stackv2-0115.json.gz:85876", "repo_name": "postgres/postgres", "revision_date": "2023-08-30T23:07:48", "revision_id": "b5934bfd6071fed3a38cea0cfaa93afda63d9c0c", "snapshot_id": "979febf2b41c00090d1256228f768f33e7ef3b6f", "src_encoding": "UTF-8", "star_events_count": 13691, "url": "https://raw.githubusercontent.com/postgres/postgres/b5934bfd6071fed3a38cea0cfaa93afda63d9c0c/src/fe_utils/recovery_gen.c", "visit_date": "2023-08-31T00:10:01.373472" }
stackv2
/*------------------------------------------------------------------------- * * recovery_gen.c * Generator for recovery configuration * * Portions Copyright (c) 2011-2023, PostgreSQL Global Development Group * *------------------------------------------------------------------------- */ #include "postgres_fe.h" #include "common/logging.h" #include "fe_utils/recovery_gen.h" #include "fe_utils/string_utils.h" static char *escape_quotes(const char *src); /* * Write recovery configuration contents into a fresh PQExpBuffer, and * return it. */ PQExpBuffer GenerateRecoveryConfig(PGconn *pgconn, char *replication_slot) { PQconninfoOption *connOptions; PQExpBufferData conninfo_buf; char *escaped; PQExpBuffer contents; Assert(pgconn != NULL); contents = createPQExpBuffer(); if (!contents) pg_fatal("out of memory"); /* * In PostgreSQL 12 and newer versions, standby_mode is gone, replaced by * standby.signal to trigger a standby state at recovery. */ if (PQserverVersion(pgconn) < MINIMUM_VERSION_FOR_RECOVERY_GUC) appendPQExpBufferStr(contents, "standby_mode = 'on'\n"); connOptions = PQconninfo(pgconn); if (connOptions == NULL) pg_fatal("out of memory"); initPQExpBuffer(&conninfo_buf); for (PQconninfoOption *opt = connOptions; opt && opt->keyword; opt++) { /* Omit empty settings and those libpqwalreceiver overrides. */ if (strcmp(opt->keyword, "replication") == 0 || strcmp(opt->keyword, "dbname") == 0 || strcmp(opt->keyword, "fallback_application_name") == 0 || (opt->val == NULL) || (opt->val != NULL && opt->val[0] == '\0')) continue; /* Separate key-value pairs with spaces */ if (conninfo_buf.len != 0) appendPQExpBufferChar(&conninfo_buf, ' '); /* * Write "keyword=value" pieces, the value string is escaped and/or * quoted if necessary. */ appendPQExpBuffer(&conninfo_buf, "%s=", opt->keyword); appendConnStrVal(&conninfo_buf, opt->val); } if (PQExpBufferDataBroken(conninfo_buf)) pg_fatal("out of memory"); /* * Escape the connection string, so that it can be put in the config file. * Note that this is different from the escaping of individual connection * options above! */ escaped = escape_quotes(conninfo_buf.data); termPQExpBuffer(&conninfo_buf); appendPQExpBuffer(contents, "primary_conninfo = '%s'\n", escaped); free(escaped); if (replication_slot) { /* unescaped: ReplicationSlotValidateName allows [a-z0-9_] only */ appendPQExpBuffer(contents, "primary_slot_name = '%s'\n", replication_slot); } if (PQExpBufferBroken(contents)) pg_fatal("out of memory"); PQconninfoFree(connOptions); return contents; } /* * Write the configuration file in the directory specified in target_dir, * with the contents already collected in memory appended. Then write * the signal file into the target_dir. If the server does not support * recovery parameters as GUCs, the signal file is not necessary, and * configuration is written to recovery.conf. */ void WriteRecoveryConfig(PGconn *pgconn, char *target_dir, PQExpBuffer contents) { char filename[MAXPGPATH]; FILE *cf; bool use_recovery_conf; Assert(pgconn != NULL); use_recovery_conf = PQserverVersion(pgconn) < MINIMUM_VERSION_FOR_RECOVERY_GUC; snprintf(filename, MAXPGPATH, "%s/%s", target_dir, use_recovery_conf ? "recovery.conf" : "postgresql.auto.conf"); cf = fopen(filename, use_recovery_conf ? "w" : "a"); if (cf == NULL) pg_fatal("could not open file \"%s\": %m", filename); if (fwrite(contents->data, contents->len, 1, cf) != 1) pg_fatal("could not write to file \"%s\": %m", filename); fclose(cf); if (!use_recovery_conf) { snprintf(filename, MAXPGPATH, "%s/%s", target_dir, "standby.signal"); cf = fopen(filename, "w"); if (cf == NULL) pg_fatal("could not create file \"%s\": %m", filename); fclose(cf); } } /* * Escape a string so that it can be used as a value in a key-value pair * a configuration file. */ static char * escape_quotes(const char *src) { char *result = escape_single_quotes_ascii(src); if (!result) pg_fatal("out of memory"); return result; }
2.140625
2
2024-11-18T22:24:26.824271+00:00
2021-01-09T14:40:30
ab981e2c8efb3fd2d53c9e7d7fef73c72c16ad0c
{ "blob_id": "ab981e2c8efb3fd2d53c9e7d7fef73c72c16ad0c", "branch_name": "refs/heads/master", "committer_date": "2021-01-09T14:40:30", "content_id": "34c60c9b76dfde50fe3fc8502c82106af16db4ab", "detected_licenses": [ "Apache-2.0" ], "directory_id": "515d64a9558fc7ec3d8579d969c7adbf6638990b", "extension": "c", "filename": "listnew.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 185108759, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 941, "license": "Apache-2.0", "license_type": "permissive", "path": "/DataStructure/list/listnew.c", "provenance": "stackv2-0115.json.gz:86004", "repo_name": "aiter/cs", "revision_date": "2021-01-09T14:40:30", "revision_id": "4357c0c70bc323f4184ffc3087a553245ec864c4", "snapshot_id": "d63243844f7f84b6e651339e0f5dcadd925fca9d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/aiter/cs/4357c0c70bc323f4184ffc3087a553245ec864c4/DataStructure/list/listnew.c", "visit_date": "2021-06-24T09:34:25.679076" }
stackv2
#include<stdio.h> #include<stdlib.h> struct Node { int data; struct Node * next; }; static void reverse(struct Node ** head_ref) { struct Node * prev = NULL; struct Node * current = *head_ref; struct Node * next = NULL; while(current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } *head_ref = prev; } void push(struct Node ** head_ref, int new_data) { struct Node * new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = *head_ref; *head_ref = new_node; } void printList(struct Node* head) { struct Node *tmp = head; while(tmp != NULL) { printf("%d ", tmp->data); tmp = tmp->next; } } int main(void) { struct Node * head = NULL; push(&head,1); push(&head,10); push(&head,21); push(&head,131); push(&head,104); printList(head); reverse(&head); printf("\nReversed Linked list \n"); printList(head); getchar(); }
3.546875
4
2024-11-18T22:24:26.931635+00:00
2019-10-10T22:15:58
4e8d19aadcc76bd66ad3583eac836395ff44c995
{ "blob_id": "4e8d19aadcc76bd66ad3583eac836395ff44c995", "branch_name": "refs/heads/master", "committer_date": "2019-10-10T22:15:58", "content_id": "81ac1cc2d95f42aaee65394b47ac2134a1575a45", "detected_licenses": [ "MIT" ], "directory_id": "6ea45db13ee842438bb2f542587e1cc367244962", "extension": "c", "filename": "test.c", "fork_events_count": 0, "gha_created_at": "2019-10-10T02:20:40", "gha_event_created_at": "2019-10-10T02:20:41", "gha_language": null, "gha_license_id": "MIT", "github_id": 214067013, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1002, "license": "MIT", "license_type": "permissive", "path": "/test/test.c", "provenance": "stackv2-0115.json.gz:86133", "repo_name": "jotaro-sama/siphash-c", "revision_date": "2019-10-10T22:15:58", "revision_id": "444ca325a148bbf54f4b0cd619f681ee5645671a", "snapshot_id": "4c34a2eba4544269d2f93be2f63e809a7c9e1d61", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jotaro-sama/siphash-c/444ca325a148bbf54f4b0cd619f681ee5645671a/test/test.c", "visit_date": "2020-08-09T10:16:52.609890" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include "../src/siphash.h" #define test(expected, key, input, c, d, length) \ do { \ uint64_t output = siphash(key, input, c, d, length); \ assert(expected == output); \ } while(0); int main () { char* test_string = "hello"; size_t test_string_length = strlen(test_string); test(4402678656023170274, "0123456789ABCDEF", test_string, 2, 4, test_string_length); /* test default hash */ test(4402678656023170274, "0123456789ABCDEFF", test_string, 2, 4, test_string_length); /* extra byte ignored */ test(14986662229302055855UL, "0123456789ABCDEF", test_string, 4, 8, test_string_length); /* check compression changes */ test(0xa129ca6149be45e5, "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e", 2, 4, 15); /* example in Appendix A of the paper */ return 0; }
2.59375
3
2024-11-18T22:24:27.351014+00:00
2020-09-02T23:46:34
34196ce0090477ab725a53da5c90a2bd1bcff5df
{ "blob_id": "34196ce0090477ab725a53da5c90a2bd1bcff5df", "branch_name": "refs/heads/master", "committer_date": "2020-09-02T23:46:34", "content_id": "f004ed55a3348ce8c9f90737a1bf645b3e6f44c2", "detected_licenses": [ "MIT" ], "directory_id": "6f0b7753233ebf4768a4bec47b142c7045e0c89e", "extension": "c", "filename": "color_mix_light.c", "fork_events_count": 1, "gha_created_at": "2020-01-23T10:00:05", "gha_event_created_at": "2020-03-08T19:51:04", "gha_language": "C", "gha_license_id": null, "github_id": 235767297, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1259, "license": "MIT", "license_type": "permissive", "path": "/src/color/color_mix_light.c", "provenance": "stackv2-0115.json.gz:86520", "repo_name": "VictorTennekes/miniRT", "revision_date": "2020-09-02T23:46:34", "revision_id": "a1589a2e3c3288bcacc660101ddfad06f391d3ef", "snapshot_id": "6bf4c647fe68f868e4903a116c0335b78c5a7a73", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/VictorTennekes/miniRT/a1589a2e3c3288bcacc660101ddfad06f391d3ef/src/color/color_mix_light.c", "visit_date": "2020-12-19T15:03:45.510770" }
stackv2
/* ************************************************************************** */ /* */ /* :::::::: */ /* color_mix_light.c :+: :+: */ /* +:+ */ /* By: vtenneke <vtenneke@student.codam.nl> +#+ */ /* +#+ */ /* Created: 2020/06/03 13:13:32 by vtenneke #+# #+# */ /* Updated: 2020/06/03 13:13:32 by vtenneke ######## odam.nl */ /* */ /* ************************************************************************** */ /* ** Calculate the color a colored surface will reflect when a color of light ** falls on it. ** ** @param : {t_color} color ** @param : {t_color} light ** ** @return : {t_color} */ #include <minirt.h> t_color color_mix_light(t_color color, t_color light) { return (color_new(color.r * light.r / 255, color.g * light.g / 255, color.b * light.b / 255)); }
2.59375
3
2024-11-18T22:24:27.523071+00:00
2019-01-24T06:15:00
075c7b224913404f0f157132e7e4ba81bdfe4dc0
{ "blob_id": "075c7b224913404f0f157132e7e4ba81bdfe4dc0", "branch_name": "refs/heads/master", "committer_date": "2019-01-24T06:15:00", "content_id": "ffb9026d4c5f10fd61804196a510b2cb05d51e4f", "detected_licenses": [ "MIT" ], "directory_id": "de8824f5b97f80cf0d0184c1e4eb02f044c85ff2", "extension": "c", "filename": "mm.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": 36378, "license": "MIT", "license_type": "permissive", "path": "/mm.c", "provenance": "stackv2-0115.json.gz:86777", "repo_name": "chenw23/malloc_lab", "revision_date": "2019-01-24T06:15:00", "revision_id": "4c44b0212538174b151676373877207801ce965e", "snapshot_id": "f8296acb170839a5cd19819ff5b32397a9248f19", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/chenw23/malloc_lab/4c44b0212538174b151676373877207801ce965e/mm.c", "visit_date": "2021-10-11T09:03:53.032890" }
stackv2
/**************************************************************************** * MallocLab for CS:APP 3e * * Student ID: 16307110064 * * @author Wang, Chen * * @date December, 14th, 2018 * * * * * * @brief Sophisticated, 32-bit and 64-bit clean allocator based on * * segregated free lists and boundary tag coalescing, modified based on the * * code described in the CS:APP3e text. Blocks must be aligned to double * * word (8 byte) boundaries. Minimum block size is 24 bytes. * * * * @details This implementation adapts various data structures to complete * * the task from different perspectives. In general, a Binary Search Tree is* * adapted to speed up the speed of looking for a vacant block in memory. * * Besides, two facilitating lists are also adapted so that the small blocks* * can be inserted directly into the list, saving the time of searching in * * the binary search tree. * * Therefore, the global variables clearly displays this point. * * In addition to the @var heap_list_p variable defined by the textbook, * * there are the other global variables indicating the root of the binary * * search tree, the address of the 8 byte list, and the address of the 16 * * byte list. * ***************************************************************************/ #include <stdio.h> #include <string.h> #include "mm.h" #include "memlib.h" /**** The headers defined on lab release and should NOT be changed ******/ /* If you want debugging output, use the following macro. When you hand * in, remove the #define DEBUG line. */ #ifdef DEBUG # define dbg_printf(...) printf(__VA_ARGS__) #else # define dbg_printf(...) #endif /* do not change the following! */ #ifdef DRIVER /* create aliases for driver tests */ #define malloc mm_malloc #define free mm_free #define realloc mm_realloc #define calloc mm_calloc #endif /* def DRIVER */ /*************************** END *****************************************/ /**************** Basic constants provided by text book *********************/ #define WSIZE 4 /* Word and header/footer size (bytes) */ #define DSIZE 8 /* Double word size (bytes) */ #define CHUNKSIZE (1<<8) /* Extend heap by this amount (bytes), [modified from 1<<12 to 1<<8] */ /*************************** END *****************************************/ /******************** Constants of my own definition ************************/ //Header and footer sign, 8 bytes #define HEADER_FOOTER 8 //Minimum block size #define MIN_BLOCK_SIZE 24 /*************************** END *****************************************/ /**************** Basic macros provided by text book *********************/ #define MAX(x, y) ((x) > (y)? (x) : (y)) /* Pack a size and allocated bit into a word */ #define PACK(size, alloc) ((size) | (alloc)) /* Read and write a word at address p */ #define GET(p) (*(unsigned int *)(p)) #define PUT(p, val) (*(unsigned int *)(p) = (val)) /* Read the size and allocated fields from address p */ #define GET_SIZE(p) (GET(p) & (~0x7)) #define GET_ALLOC(p) (GET(p) & (0x1)) /* Given block ptr bp, compute address of its header and footer */ /* Removed unnecessary casting.*/ #define HDRP(bp) (bp - WSIZE) #define FTRP(bp) (bp + GET_SIZE(HDRP(bp)) - DSIZE) /*************************** END *****************************************/ /****************** Macros of my own definition ***************************/ /* Get the 64 bit pointer of the address stored in the address p */ #define GET_PTR(p) (void *)(GET(p)|0x800000000) #define PTR2INT(p) (unsigned int)(long)p /* Determine whether the previous block is allocated and free from header */ #define PREV_ALLOC(header_ptr) (GET(header_ptr) & (0x2)) #define PREV_FREE(header_ptr) (GET(header_ptr) & (0x4)) #define SET_PREV_ALLOC(bp) (GET(HDRP(bp)) |= 0x2) #define RESET_PREV_ALLOC(bp) (GET(HDRP(bp)) &= ~0x2) #define SET_PREV_FREE(bp) (GET(HDRP(bp)) |= 0x4) #define RESET_PREV_FREE(bp) (GET(HDRP(bp)) &= ~0x4) /*Given pointer p at the second word of the data structure, compute addresses of its RIGHT,PARENT and SIBLING pointer, left is itself */ #define RIGHT(p) (p + WSIZE) #define PARENT(p) (p + 2 * WSIZE) #define SIBLING(p) (p + 3 * WSIZE) /*Given block pointer bp, get the POINTER of its directions*/ #define GET_PREV(bp) (PREV_FREE(HDRP(bp)) ? (bp - DSIZE): (bp - GET_SIZE(bp - DSIZE)) ) #define GET_NEXT(bp) (bp + GET_SIZE(bp - WSIZE)) /*************************** END *****************************************/ /**** Basic static functions provided by text book (in mm-textbook.c)*******/ /********** Function prototypes for internal helper routines ***************/ static void *extend_heap(size_t size); static void place(void *bp, size_t a_size); static void *find_fit(size_t a_size); static void *coalesce(void *bp); /*************************** END ****************************************/ /************ Static functions of my own definition ************************/ /****Self defined function prototypes for internal helper routines *******/ static inline int is_prev_free(void *bp); static void insert_node(void *bp); static void delete_node(void *bp); static void print_block(void *bp); static void check_tree(void *node); static void check_list_8(void *bp); static void check_list_16(void *bp); /*************************** END *****************************************/ /*** Basic global variables provided by text book (in mm-textbook.c)*******/ static char *heap_list_p;/* Pointer to first block */ /*************************** END ****************************************/ /************* Global variables of my own definition ************************/ static void *root;//root of the BST static void *list_16;//head of the 16-byte list static void *list_8;//head of the 8-byte list static void *HEAP_NIL = (void *) 0x800000000;//virtual NULL pointer (0x800000000) /*************************** END ****************************************/ /******************** CORE FUNCTION *************************************** **The declaration of this function is defined in mm.h and cannot be changed* * * * mm_init - Initialize the memory manager * ***************************************************************************/ int mm_init(void) { /* create the initial empty heap */ if ((heap_list_p = mem_sbrk(6 * WSIZE)) == (void *) -1) return -1; PUT(heap_list_p + (2 * WSIZE), 0); /* Alignment padding */ PUT(heap_list_p + (3 * WSIZE), PACK(DSIZE, 1)); /* Prologue header */ PUT(heap_list_p + (4 * WSIZE), PACK(DSIZE, 1)); /* Prologue footer */ PUT(heap_list_p + (5 * WSIZE), PACK(0, 3)); /* Epilogue header */ heap_list_p += (4 * WSIZE); /*init the global variables*/ root = HEAP_NIL; list_16 = HEAP_NIL; list_8 = HEAP_NIL; /* Extend the empty heap with a free block of CHUNKSIZE bytes */ if (extend_heap(MIN_BLOCK_SIZE) == 0) return -1; return 0; } /******************** CORE FUNCTION *************************************** **The declaration of this function is defined in mm.h and cannot be changed* * * * malloc - Allocate a block with at least size bytes of payload * * When the initialization process is done, the application can use malloc * * method to get a allocated block. The size of the block should be the * * multiple of the alignment. The general implementation idea of this method* * is the same as the one on the textbook and this version of implementation* * have such functions described as below. The variation from the textbook * * version is the searching for free list method that I have to operate on * * a binary search tree. * * a) Ignore spurious requests; * * b) Adjust block size to include overhead and alignment requirements; * * c) Search the free list for a fit; * * d) If no fit found. Get more memory and place the block. * * e) Place the block into the returned fit place * ***************************************************************************/ void *malloc(size_t size) { char *bp; /* Ignore spurious requests */ if (size <= 0) return 0; /* Adjust block size to include overhead and alignment requirements. */ size_t a_size = ((size + WSIZE) + (DSIZE - 1)) & ~0x7; /* adjusted block size */ /* Search the free list for a fit */ if ((bp = find_fit(a_size)) == HEAP_NIL) { /* No fit found. Get more memory and place the block */ extend_heap(a_size); bp = find_fit(a_size); } place(bp, a_size); return bp; } /******************** CORE FUNCTION *************************************** **The declaration of this function is defined in mm.h and cannot be changed* * free - Free a block * * This method returns without modifying block content in two cases: * * a) The block pointer is @code NULL @endcode; * * b) The block pointer is not @code NULL @endcode but the ALLOCATED tag in * * the head part of the block is 0 indicating that this block is not * * allocated. After returning on these abnormal conditions, the free * * function writes the flag symbol on both the head and the foot of the * * block. * * Finally, this method calls the @code coalesce @endcode methods which * * coalesces the currently freed block with its adjacent blocks and insert * * the newly coalesced block into the binary search tree. * ***************************************************************************/ void free(void *bp) { if (bp == 0) return; void *header_ptr = HDRP(bp); if (GET_ALLOC(header_ptr) == 0) return; int size = GET_SIZE(header_ptr); int sign = is_prev_free(bp); PUT(header_ptr, PACK(size, sign)); PUT(FTRP(bp), PACK(size, sign)); insert_node(coalesce(bp)); } /******************** CORE FUNCTION *************************************** **The declaration of this function is defined in mm.h and cannot be changed* * realloc - Change the size of the block by mallocing a new block, copying * * its data, and freeing the old block(basic idea of naive * * implementation). * * In this version of implementation, it behaves according to the following * * criteria: * * 1) When a @code NULL @endcode pointer is transferred into this method, * * it does nothing more than the malloc method. * * 2) When the size of the new required block is zero, it just frees the * * original block. * * 3) If the new block size is equal to or less than the old block size, * * it modifies the old block to contain the new size * * 4) If the new block size is greater than the old block size and the next * * is free, it coalesces the two block into one block and put the new * * size into the newly generated block. * ***************************************************************************/ void *realloc(void *ptr, size_t size) { /* If old ptr is NULL, then this is just malloc. */ if (ptr == 0) return mm_malloc(size); /* If size == 0 then this is just free, and we return NULL. */ if (size == 0) { mm_free(ptr); return 0; } /* Adjust block size to include overhead and alignment requirements. */ unsigned int new_size = (unsigned int) (((size + WSIZE) + (DSIZE - 1)) & ~0x7); void *header_ptr = HDRP(ptr); unsigned int old_size = GET_SIZE(header_ptr); void *next = GET_NEXT(ptr); void *next_header_ptr = HDRP(next);/* new size is less than/equal to old size */ unsigned int next_alloc = GET_ALLOC(next_header_ptr); unsigned int compound_size = old_size + GET_SIZE(next_header_ptr); int new_free_size = !next_alloc ? (compound_size - new_size) : (old_size - new_size); if (new_free_size >= HEADER_FOOTER) { if (!next_alloc) delete_node(next); PUT(header_ptr, PACK(new_size, 1 | is_prev_free(ptr))); void *new_next = GET_NEXT(ptr); PUT(HDRP(new_next), PACK(new_free_size, 2)); PUT(FTRP(new_next), PACK(new_free_size, 2)); insert_node(coalesce(new_next)); return ptr; } if (!next_alloc && (compound_size >= new_size)) { delete_node(next); PUT(header_ptr, PACK(compound_size, 1 | is_prev_free(ptr))); SET_PREV_ALLOC(next); return ptr; } // The next block is allocated or the sum of the size of the two blocks is less than new size // OK no more way to optimize, I can only find the fit one from the list void *new_ptr; if ((new_ptr = find_fit(new_size)) == HEAP_NIL) { extend_heap(new_size); new_ptr = find_fit(new_size); } place(new_ptr, new_size); /*copy content from memory*/ memcpy(new_ptr, ptr, old_size - WSIZE); mm_free(ptr); return new_ptr; } /******************** CORE FUNCTION *************************************** **The declaration of this function is defined in mm.h and cannot be changed* * calloc - Allocate the block and set it to zero. * * This function will not be tested and this implementation is basic. * ***************************************************************************/ void *calloc(size_t nmemb, size_t size) { size_t bytes = nmemb * size; void *newptr = malloc(bytes); memset(newptr, 0, bytes); return newptr; } /****** END of the main parts of the core functions,**********************/ /**************************************************************************/ /************* below are facilitating static functions ********************/ /**************************************************************************** * @brief This inline method is a simple method that tests whether the * * previous block of the given block pointer is free. * ***************************************************************************/ static inline int is_prev_free(void *bp) { void *header_ptr = HDRP(bp); return PREV_ALLOC(header_ptr) | PREV_FREE(header_ptr); } /**************************************************************************** * @brief extend_heap - Extend heap with free block and return its block * * pointer * * @details * * This method is called under two circumstances: * * when the heap is initialized and when a find_fit method cannot find a * * block with required size. * * Before making the system call to increase the heap size, this method * * first checks whether the last block is free. If last block is free, then * * it subtracts the size of the free block from the required extension size.* * This can maximize the space utilization. * * It should be noted that if the last block is not allocated, then after * * the process of extending heap, the last block and the newly generated * * block should be coalesced. * ***************************************************************************/ static void *extend_heap(size_t size_) { char *bp; void *end = mem_heap_hi() - 3; int size = (int) size_; int is_end_alloc = PREV_ALLOC(end); if (!is_end_alloc) { if (PREV_FREE(end)) size -= DSIZE; else size -= GET_SIZE(end - 4); } size = MAX(CHUNKSIZE, size); bp = mem_sbrk(size); /* Initialize free block header/footer and the epilogue header */ int sign = 0 | is_prev_free(bp); PUT(HDRP(bp), PACK(size, sign)); /* Free block header */ PUT(FTRP(bp), PACK(size, sign)); /* Free block footer */ PUT(HDRP(GET_NEXT(bp)), PACK(0, 1)); /* New epilogue header */ /* Coalesce if the previous block was free */ if (!is_end_alloc) bp = coalesce(bp); insert_node(bp); return bp; } /**************************************************************************** * @brief coalesce - Boundary tag coalescing. Return ptr to coalesced block * * @details The implementation of this method is adhere to the guideline of * * the textbook. There are totally four cases when a block transferred into * * the method. The first case is both its previous block and its next block * * are allocated, the second case is its previous block is allocated but * * its next block is not allocated, the third case is its previous block is * * not allocated but its next block is allocated, and the last case is * * neither its previous block nor its next block is allocated. * ***************************************************************************/ static void *coalesce(void *bp) { void *header_ptr = HDRP(bp); void *next = GET_NEXT(bp); void *next_header_ptr = HDRP(next); size_t size = GET_SIZE(header_ptr); size_t prev_alloc = PREV_ALLOC(header_ptr); size_t next_alloc = GET_ALLOC(next_header_ptr); if (prev_alloc && next_alloc) { /* Case 1 */ return bp; } else if (prev_alloc) { /* Case 2 */ size += GET_SIZE(next_header_ptr); delete_node(GET_NEXT(bp)); int sign = 0 | is_prev_free(bp); PUT(header_ptr, PACK(size, sign)); PUT(FTRP(bp), PACK(size, sign)); return bp; } else if (next_alloc) { /* Case 3 */ void *prev = GET_PREV(bp); int sign = 0 | is_prev_free(prev); delete_node(prev); size += GET_SIZE(HDRP(prev)); PUT(HDRP(prev), PACK(size, sign)); PUT(FTRP(prev), PACK(size, sign)); return prev; } else { /* Case 4 */ void *prev = GET_PREV(bp); void *prev_header_ptr = HDRP(prev); size += GET_SIZE(prev_header_ptr) + GET_SIZE(next_header_ptr); delete_node(prev); delete_node(next); int sign = 0 | is_prev_free(bp); PUT(prev_header_ptr, PACK(size, sign)); PUT(FTRP(prev), PACK(size, sign)); return prev; } } /**************************************************************************** * @brief place - Place block of a_size bytes at start of free block bp and * * split if remainder would be at least minimum block size. * * @details This method places the requested block into memory. * * If the remaining space after inserting the current block is greater than * * or equal to the size required by the header plus the footer, then a new * * block will occupy the remaining new space. Otherwise, the newly inserted * * block will occupy the entire space. * ***************************************************************************/ static void place(void *bp, size_t a_size) { unsigned int block_size = GET_SIZE(HDRP(bp)); size_t remaining_size = block_size - a_size; int pre_free = 1 | is_prev_free(bp); delete_node(bp); if ((remaining_size) >= HEADER_FOOTER) { PUT(HDRP(bp), PACK(a_size, pre_free)); bp = GET_NEXT(bp); PUT(HDRP(bp), PACK(remaining_size, 2)); PUT(FTRP(bp), PACK(remaining_size, 2)); insert_node(coalesce(bp)); } else PUT(HDRP(bp), PACK(block_size, pre_free)); } /**************************************************************************** * @brief find_fit - Find a fit for a block with a_size bytes * * @details This implementation of find fit adopts a best fit strategy * * Before traversing the binary search tree. Two other small lists are * * maintained for saving the time of searching for small size blocks. * * The first list contains all the blocks with a size of 8 bytes. Note that * * due to the restriction of alignment and the header and footer overhead, * * the minimal block size if 8 bytes. * * The second list contains all the blocks with a size between 8 and 16 * * bytes. * * The two lists above all adapts a segregated list style. * * When searching along the tree, it enters the tree from the root, records * * the fitting block and compares the size of the required space and the * * size of the current node in the tree. The tree follows the convention of * * the normal BST that the left child of a node is less than the current * * node and the right child of a node is greater than the current node. * * When completing searching, the @var fit will record the block with the * * least size but can hold the required block. * * @note It should be noted that the two short lists might have not been * * initialized. In such case, the search in the BST is performed. * * @return The small list if the required size is small and the selected * * list is initialized; the block most close to but greater than the size * * required; the blank node if the required size is greater than the block * * with the greatest size in the binary search tree. * ***************************************************************************/ static void *find_fit(size_t a_size) { if (a_size == 8 && list_8 != HEAP_NIL) return list_8; if (a_size <= 16 && list_16 != HEAP_NIL) return list_16; /* the most fit block */ void *fit = HEAP_NIL; /* The currently searching node pointer */ void *searching = root; /* Search from the root of the tree to the bottom */ while (searching != HEAP_NIL) /*Record the currently */ if (a_size <= GET_SIZE(HDRP(searching))) { fit = searching; searching = GET_PTR(searching); } else searching = GET_PTR(RIGHT(searching)); return fit; } /**************************************************************************** * @brief insert_node: Inserts the new block into the linking system * * @details If the size of the node is 8 or 16, then the block will be * * linked to other nodes with the same size in a way behaving like the * * explicit linking list. The root of the link list, aka the root, are two * * global variables. The priority of the two small lists is higher than the * * binary search tree. That is, the small blocks will not go into the system* * of the binary search tree. If the size of the block is greater than 16, * * then this method will search the binary search tree for a fitting place. * * The while loop will continue finding until it finds a place that can * * exactly hold the required block or the @var current_node reaches the end.* * It maintains the other pointers when a node is to be inserted into the * * tree. * * @note It should be noted that in this version of implementation, multiple* * nodes with the same size is allowed. The nodes with the same size simply * * become siblings with each other. * ***************************************************************************/ static void insert_node(void *bp) { RESET_PREV_ALLOC(GET_NEXT(bp)); void *header_ptr = HDRP(bp); size_t block_size = GET_SIZE(header_ptr); if (block_size == 8) { SET_PREV_FREE(GET_NEXT(bp)); PUT(bp, PTR2INT(list_8)); list_8 = bp; return; } if (block_size == 16) { //if the block size = 16; insert it to the head of the 16-byte list PUT(bp, 0); PUT(RIGHT(bp), PTR2INT(list_16)); PUT(list_16, PTR2INT(bp)); list_16 = bp; return; } void *parent = HEAP_NIL; void *current_node = root; int direction = -1; /* loop to locate the position */ while (1) { if (current_node == HEAP_NIL) { PUT(bp, 0); PUT(RIGHT(bp), 0); PUT(PARENT(bp), PTR2INT(parent)); PUT(SIBLING(bp), 0); break; } void *curr_header_ptr = HDRP(current_node); /* Case 1: size of the block exactly matches the node. */ if (GET_SIZE(header_ptr) == GET_SIZE(curr_header_ptr)) { PUT(bp, GET(current_node)); PUT(RIGHT(bp), GET(RIGHT(current_node))); PUT(PARENT(GET_PTR(current_node)), PTR2INT(bp)); PUT(PARENT(GET_PTR(RIGHT(current_node))), PTR2INT(bp)); PUT(PARENT(bp), PTR2INT(parent)); PUT(SIBLING(bp), PTR2INT(current_node)); PUT(current_node, PTR2INT(bp)); break; } /* Case 2: size of the block is less than that of the node. */ else if (GET_SIZE(header_ptr) < GET_SIZE(curr_header_ptr)) { parent = current_node; direction = 0; current_node = GET_PTR(current_node); } /* Case 3 size of the block is greater than that of the node. */ else { parent = current_node; direction = 1; current_node = GET_PTR(RIGHT(current_node)); } } if (direction == -1) root = bp; else if (direction == 0) PUT(parent, PTR2INT(bp)); else PUT(RIGHT(parent), PTR2INT(bp)); } /**************************************************************************** * @brief delete_node Removes the node from the link list, maintains the * * link to this node from other nodes. * * @details If the block size is 8 bytes, then it maintains the link list of* * 8 bytes. * The method iterates through the list searching for the global variable, * * the entry of the list, then it removes this block from the list. The time* * complexity of this operation is O(n). If the block size is 16 bytes, then* * it maintains the link list of 16 bytes. The method fixes the left block * * and the right block removing block. The time complexity of this operation* * is O(1). If it is not the cases above, then the block is in the tree. * * If the removing node has a sibling, then the sibling takes the place of * * removing node, taking over the pointers to parent and children. If the * * removing node has no sibling and has only one or no child, then handling * * is simple as well. The relationship pointers can be maintained in a * * couple of lines of codes. The trickiest case is when the node has no * * sibling, and when it has both children. In this case, we wont delete the * * required node directly but rather let its successor take its place and * * remove the place of its successor. Because the successor of an internal * * node is sure to be a leaf node. Then removing the place of its successor * * is simpler. * ***************************************************************************/ static void delete_node(void *bp) { SET_PREV_ALLOC(GET_NEXT(bp)); int block_size = GET_SIZE(HDRP(bp)); if (block_size == 8) { RESET_PREV_FREE(GET_NEXT(bp)); void *current_block = list_8; if (current_block == bp) { list_8 = GET_PTR(bp); return; } while (current_block != HEAP_NIL) { if (GET_PTR(current_block) == bp) break; current_block = GET_PTR(current_block); } PUT(current_block, PTR2INT(GET_PTR(bp))); return; } if (block_size == 16) { void *left_block = GET_PTR(bp); void *right_block = GET_PTR(RIGHT(bp)); if (bp == list_16) list_16 = right_block; PUT(RIGHT(left_block), PTR2INT(right_block)); PUT(right_block, PTR2INT(left_block)); return; } /* If the removing node has siblings, the handling is simple */ if (GET(bp) != 0 && GET_PTR(SIBLING(GET_PTR(bp))) == bp) { PUT(SIBLING(GET_PTR(bp)), PTR2INT(GET_PTR(SIBLING(bp)))); PUT(GET_PTR(SIBLING(bp)), PTR2INT(GET_PTR(bp))); return; } /* If the removing node is the sole node with its size in the * binary search tree, the handling is more complex. * */ else if (GET(SIBLING(bp)) == 0) { if (GET(RIGHT(bp)) != 0) { void *successor = GET_PTR(RIGHT(bp)); while (GET(successor) != 0) successor = GET_PTR(successor); void *origin_l = GET_PTR(bp); void *origin_r = GET_PTR(RIGHT(bp)); void *successor_r = GET_PTR(RIGHT(successor)); void *successor_p = GET_PTR(PARENT(successor)); if (bp != root) { void *bpP = GET_PTR(PARENT(bp)); if (GET_PTR(bpP) == bp) PUT(bpP, PTR2INT(successor)); else PUT(RIGHT(bpP), PTR2INT(successor)); PUT(PARENT(successor), PTR2INT(bpP)); } else { root = successor; PUT(PARENT(successor), 0); } PUT(successor, PTR2INT(origin_l)); PUT(PARENT(origin_l), PTR2INT(successor)); if (successor != origin_r) { PUT(RIGHT(successor), PTR2INT(origin_r)); PUT(PARENT(origin_r), PTR2INT(successor)); PUT(successor_p, PTR2INT(successor_r)); PUT(PARENT(successor_r), PTR2INT(successor_p)); } return; } if (bp == root) root = GET_PTR(bp); if (GET_PTR(GET_PTR(PARENT(bp))) == bp) PUT(GET_PTR(PARENT(bp)), PTR2INT(GET_PTR(bp))); else PUT(RIGHT(GET_PTR(PARENT(bp))), PTR2INT(GET_PTR(bp))); PUT(PARENT(GET_PTR(bp)), PTR2INT(GET_PTR(PARENT(bp)))); return; } /* Case that the block is first one in the node. */ void *sibling = GET_PTR(SIBLING(bp)); if (bp == root) {/* the node is the root */ root = sibling; PUT(PARENT(sibling), 0); } else {/* the node is not the root */ if (GET_PTR(GET_PTR(PARENT(bp))) == bp) PUT(GET_PTR(PARENT(bp)), PTR2INT(sibling)); else PUT(RIGHT(GET_PTR(PARENT(bp))), PTR2INT(sibling)); PUT(PARENT(sibling), PTR2INT(GET_PTR(PARENT(bp)))); } PUT(sibling, GET(bp)); PUT(RIGHT(sibling), GET(RIGHT(bp))); PUT(PARENT(GET_PTR(bp)), PTR2INT(sibling)); PUT(PARENT(GET_PTR(RIGHT(bp))), PTR2INT(sibling)); } /****** END of the functions of the memory management part,************* ****** below are heap checking function and its auxiliary functions*****/ /******************** CORE FUNCTION *************************************** **The declaration of this function is defined in mm.h and cannot be changed* * In order to get more refined control of the heap checking process, * * different level of verbose is used to instruct the method about what info* * to display. * * Option 0 indicates that only the check block message are displayed rather* * than the details of the block * * Option 1 indicates that the heap block is printed out on the screen * * * Option 2 indicates that the entire Binary Search Tree will be printed in * * a pre-order traversal. In comparision with the traversal of the * * typical binary search tree, the brother nodes will be printed in* * a line. * * Option 3 indicates that the two explicit lists for 8 byte block and 16 * * byte block will be printed. It will not display info about the * * binary search tree. * ***************************************************************************/ void mm_checkheap(int option) { char *bp = heap_list_p; if (option == 1) printf("Heap (%p):\n", (void *) heap_list_p); if ((GET_SIZE(heap_list_p) != DSIZE) || !GET_ALLOC(heap_list_p)) printf("Bad prologue header\n"); if (option == 1) print_block(heap_list_p); for (bp = GET_NEXT(bp); GET_SIZE(HDRP(bp)) > 0; bp = GET_NEXT(bp)) { if (option == 1) print_block(bp); if ((size_t) bp % 8) printf("Error: %p is not double word aligned\n", (void *) bp); } if (option == 1) print_block(bp); if (GET_SIZE(HDRP(bp)) != 0 || !GET_ALLOC(HDRP(bp))) printf("Bad epilogue header\n"); if (option == 2) { printf("=============tree=============\n"); check_tree(root); } if (option == 3) { printf("=========list_8(size = 8)==========\n"); check_list_8(list_8); printf("=========list_16(size = 16)==========\n"); check_list_16(list_16); } } /*print the information of a block, including the address, size and allocated bit*/ static void print_block(void *bp) { void *header = HDRP(bp); int head_size = GET_SIZE(header); if (head_size == 0) { printf("%p: EOL\n", bp); return; } printf("%p--prev_e_free bit[%d] prev-alloc bit[%d] allocated bit[%d] size[%d]\n", bp, PREV_FREE(header) != 0, PREV_ALLOC(header) != 0, GET_ALLOC(header), head_size); } /*check a free block in the BST print the block and check the next node in the list including the brother node Then check the left child node and the right child node */ static void check_tree(void *node) { if (node != HEAP_NIL) { print_block(node); printf("\tparent:%p;\tbrother:%p;\n\tleft:%p;\tright:%p\n", GET_PTR(PARENT(node)), GET_PTR(SIBLING(node)), GET_PTR(node), GET_PTR(RIGHT(node))); void *temp1 = GET_PTR(SIBLING(node)); while (temp1 != HEAP_NIL) { print_block(temp1); printf("\tparent:%p;\tbrother:%p;\n\tleft:%p;\tright:%p\n", GET_PTR(PARENT(temp1)), GET_PTR(SIBLING(temp1)), GET_PTR(temp1), GET_PTR(RIGHT(temp1))); temp1 = GET_PTR(SIBLING(temp1)); } check_tree(GET_PTR(node)); check_tree(GET_PTR(RIGHT(node))); } } /*check a 16-bit free block in the list_16 print the block and check the next node in the list */ static void check_list_16(void *bp) { if (bp != HEAP_NIL) { print_block(bp); printf("\tleft:%p;\tright:%p\n", GET_PTR(bp), GET_PTR(RIGHT(bp))); check_list_16(GET_PTR(RIGHT(bp))); } } /*check a 16-bit free block in the list_8 print the block and check the next node in the list */ static void check_list_8(void *bp) { if (bp != HEAP_NIL) { print_block(bp); printf("\tleft:%p\n", GET_PTR(bp)); check_list_8(GET_PTR(bp)); } }
2.453125
2
2024-11-18T22:24:27.901976+00:00
2021-07-22T04:03:06
9b8d87c6766b5df742a65e075a210305dc3e1720
{ "blob_id": "9b8d87c6766b5df742a65e075a210305dc3e1720", "branch_name": "refs/heads/master", "committer_date": "2021-07-22T22:29:50", "content_id": "f52acd64d78cc5317d05e4217e35a8fc01f4e946", "detected_licenses": [ "MIT" ], "directory_id": "7b87508fb25939daa7d790aad2fdb5a19b707001", "extension": "c", "filename": "lcoroutm.c", "fork_events_count": 4, "gha_created_at": "2018-01-05T01:58:43", "gha_event_created_at": "2021-07-22T22:20:59", "gha_language": "Lua", "gha_license_id": "MIT", "github_id": 116328059, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7322, "license": "MIT", "license_type": "permissive", "path": "/src/lcoroutm.c", "provenance": "stackv2-0115.json.gz:87035", "repo_name": "renatomaia/coutil", "revision_date": "2021-07-22T04:03:06", "revision_id": "813a299f3f438b58ab07fc7041eeca62853aece8", "snapshot_id": "b4e578512a5e7affb603c37072940a568fffb998", "src_encoding": "UTF-8", "star_events_count": 13, "url": "https://raw.githubusercontent.com/renatomaia/coutil/813a299f3f438b58ab07fc7041eeca62853aece8/src/lcoroutm.c", "visit_date": "2023-06-24T17:29:13.183554" }
stackv2
#include "lmodaux.h" #include "loperaux.h" #include "lttyaux.h" #include "lchaux.h" #include <luamem.h> typedef struct StateCoro { lua_CFunction results; lua_CFunction cancel; uv_work_t work; lua_State *L; } StateCoro; #define tostateco(L) ((StateCoro *)luaL_checkudata(L,1,LCU_STATECOROCLS)) static int doloaded (lua_State *L, lua_State *NL, int status) { if (status != LUA_OK) { /* error (message is on top of the stack) */ size_t len; const char *errmsg = lua_tolstring(NL, -1, &len); lua_pushboolean(L, 0); lua_pushlstring(L, errmsg, len); lua_close(NL); return 2; /* return nil plus error message */ } else { StateCoro *stateco = lcuT_newudreq(L, StateCoro); stateco->L = NL; luaL_setmetatable(L, LCU_STATECOROCLS); return 1; } } /* succ [, errmsg] = coroutine.load(chunk, chunkname, mode) */ static int coroutine_load (lua_State *L) { size_t l; const char *s = luamem_checkarray(L, 1, &l); const char *chunkname = luaL_optstring(L, 2, s); const char *mode = luaL_optstring(L, 3, NULL); lua_State *NL = lcuL_newstate(L); /* create a similar state */ int status = luaL_loadbufferx(NL, s, l, chunkname, mode); return doloaded(L, NL, status); } /* succ [, errmsg] = coroutine.loadfile(filepath, mode) */ static int coroutine_loadfile (lua_State *L) { const char *fpath = luaL_optstring(L, 1, NULL); const char *mode = luaL_optstring(L, 2, NULL); lua_State *NL = lcuL_newstate(L); /* create a similar state */ int status = luaL_loadfilex(NL, fpath, mode); return doloaded(L, NL, status); } static void freestate(StateCoro *stateco) { if (stateco->L) { lua_close(stateco->L); stateco->L = NULL; } } static int freepending(lua_State *L) { (void)L; return 1; /* same as 'stateco->cancel == NULL' */ } /* getmetatable(co).__{gc,close}(co) */ static int coroutine_gc(lua_State *L) { StateCoro *stateco = tostateco(L); if (stateco->work.type == UV_WORK) stateco->cancel = freepending; /* lua_close */ else freestate(stateco); return 0; } /* succ = coroutine.close(co) */ static int coroutine_close(lua_State *L) { StateCoro *stateco = tostateco(L); lua_State *co = stateco->L; int status; luaL_argcheck(L, stateco->work.type != UV_WORK, 1, "cannot close a running coroutine"); lua_settop(L, 1); status = co ? lua_status(co) : LUA_OK; if (status == LUA_OK || status == LUA_YIELD) { lua_pushboolean(L, 1); } else { lua_pushboolean(L, 0); lcuL_pushfrom(L, co, -1, "error"); } coroutine_gc(L); return lua_gettop(L)-1; } static int suspended (lua_State *co) { switch (lua_status(co)) { case LUA_OK: return lua_gettop(co); case LUA_YIELD: return 1; default: return 0; } } /* status = coroutine.status(co) */ static int coroutine_status(lua_State *L) { StateCoro *stateco = tostateco(L); if (stateco->work.type == UV_WORK) lua_pushliteral(L, "running"); else { lua_State *co = stateco->L; if (co && suspended(co)) lua_pushliteral(L, "suspended"); else lua_pushliteral(L, "dead"); } return 1; } /* succ [, errmsg] = system.resume(coroutine) */ static int returnvalues (lua_State *L) { return lua_gettop(L)-1; /* return all except the coroutine (arg #1) */ } static void uv_onworking(uv_work_t* request) { StateCoro *stateco = (StateCoro *)lcu_req2ud(request); lua_State *co = stateco->L; int narg = lua_gettop(co); int status; if (lua_status(co) == LUA_OK) --narg; /* function on stack */ status = lua_resume(co, NULL, narg, &narg); lcu_assert(lua_checkstack(co, 2)); lua_pushinteger(co, narg); lua_pushinteger(co, status); } static void uv_onworked(uv_work_t* work, int status) { uv_loop_t *loop = work->loop; uv_req_t *request = (uv_req_t *)work; StateCoro *stateco = (StateCoro *)lcu_req2ud(request); lua_State *co = stateco->L; lua_State *thread = lcuU_endudreq(loop, request); if (thread) { int nret; if (status == UV_ECANCELED) { lua_settop(co, lua_status(co) == LUA_OK); lua_pushboolean(thread, 0); lua_pushliteral(thread, "canceled"); nret = 2; } else { int lstatus = (int)lua_tointeger(co, -1); nret = (int)lua_tointeger(co, -2); lua_pop(co, 2); /* remove lstatus and nret values */ if (lstatus == LUA_OK || lstatus == LUA_YIELD) { lua_pushboolean(thread, 1); /* return 'true' to signal success */ if (lcuL_movefrom(thread, co, nret, "return value") != LUA_OK) { lua_pop(co, nret); /* remove results anyway */ lua_pushboolean(thread, 0); lua_replace(thread, -3); /* remove 'true' that signals success */ nret = 2; } } else { lua_pushboolean(thread, 0); if (lcuL_pushfrom(thread, co, -1, "error") != LUA_OK) { lua_pop(co, 1); /* remove error anyway */ } nret = 2; } } lcuU_resumeudreq(loop, request, nret); } else { /* if not executed, remove arguments (LUA_OK when function is on stack) */ lua_settop(co, status == UV_ECANCELED && lua_status(co) == LUA_OK); } if (stateco->cancel == freepending) { freestate(stateco); stateco->cancel = NULL; } } static int k_setupwork (lua_State *L, uv_req_t *request, uv_loop_t *loop, lcu_Operation *op) { StateCoro *stateco = (StateCoro *)lua_touserdata(L, 1); lua_State *co = stateco->L; int narg = lua_gettop(L)-1; int err; lcu_assert(request == (uv_req_t *)&stateco->work); lcu_assert(op == NULL); if (lcuL_movefrom(co, L, narg, "argument") != LUA_OK) { const char *msg = lua_tostring(co, -1); lua_pushboolean(L, 0); lua_pushstring(L, msg); lua_pop(co, 1); return 2; } err = uv_queue_work(loop, &stateco->work, uv_onworking, uv_onworked); if (err < 0) { lua_pop(co, narg); /* restore coroutine stack */ return lcuL_pusherrres(L, err); } return -1; /* yield on success */ } static int system_resume (lua_State *L) { StateCoro *stateco = tostateco(L); if (stateco->work.type == UV_WORK) { lua_pushboolean(L, 0); lua_pushstring(L, "cannot resume running coroutine"); return 2; } if (stateco->L == NULL || !suspended(stateco->L)) { lua_pushboolean(L, 0); lua_pushstring(L, "cannot resume dead coroutine"); return 2; } return lcuT_resetudreqk(L, lcu_getsched(L), (lcu_UdataRequest *)stateco, k_setupwork, returnvalues, NULL); } LCUI_FUNC void lcuM_addcoroutf (lua_State *L) { static const luaL_Reg upvf[] = { {"resume", system_resume}, {NULL, NULL} }; lcuM_setfuncs(L, upvf, LCU_MODUPVS); } LCUMOD_API int luaopen_coutil_coroutine (lua_State *L) { static const luaL_Reg meta[] = { {"__index", NULL}, {"__gc", coroutine_gc}, {"__close", coroutine_gc}, {NULL, NULL} }; static const luaL_Reg modf[] = { {"load", coroutine_load}, {"loadfile", coroutine_loadfile}, {"close", coroutine_close}, {"status", coroutine_status}, {NULL, NULL} }; (void)lcuTY_tostdiofd(L); /* must be available to be copied to new threads */ (void)lcuCS_tochannelmap(L); /* map shall be GC after 'syscoro' on Lua close */ luaL_newlib(L, modf); luaL_newmetatable(L, LCU_STATECOROCLS); luaL_setfuncs(L, meta, 0); /* add metamethods to metatable */ lua_pushvalue(L, -2); /* push library */ lua_setfield(L, -2, "__index"); /* metatable.__index = library */ lua_pop(L, 1); /* pop metatable */ return 1; }
2.0625
2
2024-11-18T22:24:28.168647+00:00
2019-09-04T13:19:55
00029dcc0fd2fb89f713701da85254f9ea65d109
{ "blob_id": "00029dcc0fd2fb89f713701da85254f9ea65d109", "branch_name": "refs/heads/master", "committer_date": "2019-09-04T13:19:55", "content_id": "d9688b8dd945a2b2856ab0b45e5a764c5ce58c10", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "22928ccffb86d08db26143355df7199bc3985e00", "extension": "c", "filename": "main.c", "fork_events_count": 3, "gha_created_at": "2019-03-10T09:59:14", "gha_event_created_at": "2023-01-03T17:43:43", "gha_language": "JavaScript", "gha_license_id": "BSD-2-Clause", "github_id": 174805519, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1958, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/board_firmware/src/main.c", "provenance": "stackv2-0115.json.gz:87293", "repo_name": "larsgk/web-microbit", "revision_date": "2019-09-04T13:19:55", "revision_id": "9b3ce07ff655cb40dda84400517649e9db27d344", "snapshot_id": "822855b474cf74b21a36cd5c22154a095ddc9fdf", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/larsgk/web-microbit/9b3ce07ff655cb40dda84400517649e9db27d344/board_firmware/src/main.c", "visit_date": "2023-01-08T19:35:07.501780" }
stackv2
#include <zephyr.h> #include <misc/printk.h> #include <gpio.h> #include <device.h> #include <stdio.h> #include <bluetooth/bluetooth.h> #include <bluetooth/hci.h> #include <bluetooth/conn.h> #include <bluetooth/uuid.h> #include <bluetooth/gatt.h> #include <display/mb_display.h> #include "gatt_service.h" #include "button_handler.h" #include "microbit_display.h" // BT Advertised service(s) static const struct bt_data ad[] = { BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)), BT_DATA_BYTES(BT_DATA_UUID128_ALL, 0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12, 0x78, 0x56, 0x34, 0x12, 0x78, 0x56, 0x34, 0x12), }; static void connected(struct bt_conn *conn, u8_t err) { if (err) { printk("Connection failed (err %u)\n", err); mb_show_smiley(false); } else { printk("Connected\n"); mb_show_smiley(true); } } static void disconnected(struct bt_conn *conn, u8_t reason) { printk("Disconnected (reason %u)\n", reason); mb_show_smiley(false); } static struct bt_conn_cb conn_callbacks = { .connected = connected, .disconnected = disconnected, }; static void bt_ready(int err) { if (err) { printk("Bluetooth init failed (err %d)\n", err); return; } printk("Bluetooth initialized\n"); gatt_service_init(); err = bt_le_adv_start(BT_LE_ADV_CONN_NAME, ad, ARRAY_SIZE(ad), NULL, 0); if (err) { printk("Advertising failed to start (err %d)\n", err); return; } printk("Advertising successfully started\n"); } void main(void) { int err; // Init Bluetooth Low Energy. err = bt_enable(bt_ready); if (err) { printk("Bluetooth init failed (err %d)\n", err); return; } bt_conn_cb_register(&conn_callbacks); // Init button handler. button_handler_init(); // Show a small animation show the board is ready. mb_show_ready_animation(); while (1) { // Every second... k_sleep(1000); // ...send 'heartbeat' count over GATT send_message(GATT_MSG_HEARTBEAT, NULL, 0); } }
2.265625
2
2024-11-18T22:24:28.725121+00:00
2020-08-20T03:01:59
4338de970c9527de0d4c37962f2553185d6e76c1
{ "blob_id": "4338de970c9527de0d4c37962f2553185d6e76c1", "branch_name": "refs/heads/master", "committer_date": "2020-08-20T03:01:59", "content_id": "507e6a925cc53c3f0bb42d0818b6c4822cc08340", "detected_licenses": [ "MIT" ], "directory_id": "d3474ed6242ef5c2f0078a959287220ebe515ac4", "extension": "h", "filename": "Symbol.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 274801955, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3075, "license": "MIT", "license_type": "permissive", "path": "/Symbol.h", "provenance": "stackv2-0115.json.gz:87421", "repo_name": "PolyglotSymposium/metacore", "revision_date": "2020-08-20T03:01:59", "revision_id": "61aea5553b26fb29d7343680f331441d98e98d70", "snapshot_id": "899cfa6124b4e988ea9b4593ad4cab98793dd848", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/PolyglotSymposium/metacore/61aea5553b26fb29d7343680f331441d98e98d70/Symbol.h", "visit_date": "2022-12-03T08:52:56.390314" }
stackv2
#ifndef __METACORE_SYMBOL_H__ #define __METACORE_SYMBOL_H__ /* I assert: 1. Having Lisp/Prolog-style symbols in your language is fantastic. 2. Having a global symbol table sucks. Giant global state. Blech. 3. Interning strings for symbols feels heavy. So, can't we just represent symbols by words? (We'll assume that modern hardware is moving enough toward 64-bit that we can safely equate "word" and "64 bits".) Can't we just have some deterministic algorithm to convert back and forth? The answer is, of course, "yes"; the real question is not the tractability, but how to do this without driving the users of the language crazy---bearing in mind, of course, that this is intended as a somewhat low-level language for bootstrapping the system, and while it needs to be readable and writable, it does not need to be anyone's favorite language, unless a minimalism nerd, who won't mind a little bit of inconvenience anyhow. It is desirable for the algorithm to be straightforward since we are going for minimalism and speed. It should not be excessively difficult to implement, and it should run fast, since symbols are going to be bread and butter. The obvious thing to do is some human-friendly base-X encoding. Human-friendly, not in the sense that the programmer can easily convert to the decimal form in his mind (for that should not be important), but in that it provides you enough characters to form relatively pleasant identifiers. A base-X encoding, because that will be lossless. But what base should be used? The primary factors when choosing a base are: 1. The number of characters available to the programmer in identifiers. 2. The maximum length of identifiers that will fit into 64 bits. However, there is a further kink in that it would be nice to have the syntactic convenience available in most languages, that identifiers are distinguishable from numbers by the first character being non-numeric, despite numeric symbols being allowed. 1 2 3 4 5 6 7 8 9 10 11 12 13 2⁵ × 2⁵ × 2⁵ × 2⁵ × 2⁵ × 2⁵ × 2⁵ × 2⁵ × 2⁵ × 2⁵ × 2⁵ × 2⁵ × 2⁴ 5 10 15 20 25 30 35 40 45 50 55 60 64 Little-endian. Twelve 32-character digits; the thirteenth is 16 characters. An underscore can be used as syntactic sugar to skip specifying the rest of the base-32 digits, i.e. populate them with a's (zeros), to allow an easy way to name identifiers with numbers at the end, e.g. `x_0` and `x_1`, which will be equivalent to `xaaaaaaaaaaa0` and `xaaaaaaaaaaa1`, respectively. */ typedef unsigned long Symbol; const Symbol compressChar(const char); const Symbol compress13thChar(const char); /** * Returns `!!!!!!!!!!!!!` on failure (which is therefore indistinguishable from * succeeding with the maximum symbol). */ const Symbol compressSymbol(const char* const); const char decompressChar(const Symbol); const char decompress13thChar(const Symbol); char* decompressSymbol(const Symbol); #endif
2.4375
2
2024-11-18T22:25:09.510334+00:00
2020-09-29T11:01:39
fd6719ad06058a0c4c99eccb05d913da8076e7b6
{ "blob_id": "fd6719ad06058a0c4c99eccb05d913da8076e7b6", "branch_name": "refs/heads/master", "committer_date": "2020-09-29T11:01:39", "content_id": "6b5a572c0f7a221e4c814d8e41fcd56fdb3db240", "detected_licenses": [ "MIT" ], "directory_id": "95db6ac4595857b85260fd89ee9ddcf7f7a5fc59", "extension": "c", "filename": "MGNumc.C", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 85963223, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 829, "license": "MIT", "license_type": "permissive", "path": "/libs/CPPLibs/MGNumc.C", "provenance": "stackv2-0115.json.gz:108574", "repo_name": "hchouTW/AMSProject", "revision_date": "2020-09-29T11:01:39", "revision_id": "c18c8d3ff887874af3b7aab6525bd3a89b31e83c", "snapshot_id": "073052b65dd411395ee4119f9d089203bff5536d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/hchouTW/AMSProject/c18c8d3ff887874af3b7aab6525bd3a89b31e83c/libs/CPPLibs/MGNumc.C", "visit_date": "2021-01-23T02:13:23.199163" }
stackv2
#ifndef __CPPLibs_MGNumc_C__ #define __CPPLibs_MGNumc_C__ #include "MGNumc.h" namespace MGNumc { template <class IntType, typename std::enable_if<std::is_integral<IntType>::value, int>::type> inline short Compare(IntType a, IntType b) { if (a == b) return 0; else if (a > b) return 1; else return -1; } template <class RealType, typename std::enable_if<std::is_floating_point<RealType>::value, int>::type> inline short Compare(RealType a, RealType b) { RealType diff = std::fabs(a - b); if (!std::isfinite(diff)) return 0; if (diff < std::numeric_limits<RealType>::epsilon() * 5.0e3) return 0; else if (a > b) return 1; else return -1; } } // namespace MGNumc #endif // __CPPLibs_MGNumc_C__
2.3125
2
2024-11-18T22:25:09.603570+00:00
2019-10-09T12:05:44
07b8b4944f360fb26d7741bf2ffc6e39051cb4a3
{ "blob_id": "07b8b4944f360fb26d7741bf2ffc6e39051cb4a3", "branch_name": "refs/heads/master", "committer_date": "2019-10-09T12:05:44", "content_id": "96290f723290dcfc86d9f8a9e1daf8fde8d5460c", "detected_licenses": [ "MIT" ], "directory_id": "facaf6f188812f003343c89249aad278ef5d3164", "extension": "c", "filename": "ssd_i2c.c", "fork_events_count": 1, "gha_created_at": "2019-09-13T11:42:44", "gha_event_created_at": "2019-10-09T12:05:45", "gha_language": "C", "gha_license_id": "MIT", "github_id": 208253325, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12987, "license": "MIT", "license_type": "permissive", "path": "/src/drivers/ssd_i2c.c", "provenance": "stackv2-0115.json.gz:108704", "repo_name": "ksonter95/SSD1803A-C-API", "revision_date": "2019-10-09T12:05:44", "revision_id": "479b311af7176438642036b9b1f7ba5d306fceb8", "snapshot_id": "6ec5e5f573abadc5207c8fd237f78eeaf5f7a434", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ksonter95/SSD1803A-C-API/479b311af7176438642036b9b1f7ba5d306fceb8/src/drivers/ssd_i2c.c", "visit_date": "2020-07-25T10:05:22.824342" }
stackv2
/* ========================================================================== */ /**@file src/drivers/ssd_i2c.c * * I2C interface to the MPU. * * ==========================================================================\n * Project: SSD1803A-C-API * System: Raspberry Pi * Created: 13/09/2019 12:42:11 PM ksonter \n * Copyright (c) 2019, Kieran Sonter * ==========================================================================\n * Description: \n * This driver is only used internally within the SSD1803A library and it * provides an interface to any I2C pigpio functions formatted to be understood * by the SSD1803A display MPU. As such, it provides the following functions: * - i2c_init(): Initialises the I2C hardware drivers. * - i2c_deinit(): Deinitialises the I2C hardware drivers. * - i2c_write(): Conducts an I2C write operation. * - i2c_read(): Conducts an I2C read operation. * * For any further information on these functions, see the function comments * shown below. * ========================================================================== */ /* === Includes ============================================================= */ #include "ssd_i2c.h" #include <pigpio.h> #include <stdio.h> #include "ssd1803a.h" #include "ssd_pigpio.h" /* === Defines ============================================================== */ /* I2C configuration */ #define ADDRESS_BASE 0x3CU #define I2C_FLAGS 0x00 /* Control bytes */ #define CONTROL_BYTE_DATA 0x40 #define CONTROL_BYTE_COMMAND_FURTHER 0x80 #define CONTROL_BYTE_COMMAND_LAST 0x00 /* === Enumerations ========================================================= */ /* === Structures =========================================================== */ /* === Typedefs ============================================================= */ /* === Global Variables ===================================================== */ int16_t m_I2cHandle = (int16_t) STATUS_INVALID_HANDLE; /* === Function Prototypes ================================================== */ /* ========================================================================== */ /* ========================================================================== */ /* ========================================================================== */ /* ========================================================================== */ /** * @details This function implements the following objectives: * -# Open the I2C interface to the MPU. * * @param [in] bus I2C bus number on the RPi that is connected to the I2C * bus on the display MPU. * @param [in] sa0 Least significant bit of the I2C address at which the * display MPU can be found. * * @retval STATUS_OK If the I2C hardware was successfully initialised. * @retval STATUS_NOT_INITIALISED If the pigpio library has not been previously * initialised with a call to pigpio_init(). * @retval STATUS_NO_HANDLE If there is no available handle to assign to the * display MPU I2C bus. * @retval STATUS_FAILED_OPEN If I2C interface failed to be opened. * @retval STATUS_ALREADY_OPEN If this function (i2c_init()) had already been * called and successfully opened an interface to the display MPU. * @retval STATUS_INVALID_BUS, STATUS_INVALID_ADDRESS, and STATUS_INVALID_FLAGS * are theoretically possible return values from the function i2cOpen, however * they should never occur due to the restrictions on the data types i2c_bus_t * and sa0_bit_t. * ========================================================================== */ status_t i2c_init( i2c_bus_t bus, sa0_bit_t sa0) { /* pigpio library is not initialised */ if (!pigpio_is_initialised()) { LOG_TO_STDERR(); return STATUS_NOT_INITIALISED; } /* Interface to MPU has already been opened */ if (m_I2cHandle != STATUS_INVALID_HANDLE) { LOG_TO_STDERR(); return STATUS_ALREADY_OPEN; } /* Open the I2C interface */ status_t ret = i2cOpen(bus, ADDRESS_BASE | sa0, I2C_FLAGS); /* Opened the I2C interface */ if (ret >= STATUS_OK) { m_I2cHandle = (int16_t)ret; ret = STATUS_OK; } else { LOG_TO_STDERR(); } return ret; } /* ========================================================================== */ /** * @details This function implements the following objectives: * -# Close the I2C interface to the MPU. * * retval STATUS_OK If the I2C hardware was successfully deinitialised. * retval STATUS_INVALID_HANDLE If the I2C hardware was not successfully * initialised before calling this function. * ========================================================================== */ status_t i2c_deinit(void) { status_t ret = STATUS_OK; /* I2C interface has not yet been opened */ if (m_I2cHandle == STATUS_INVALID_HANDLE) { LOG_TO_STDERR(); return STATUS_INVALID_HANDLE; } ret = i2cClose((uint16_t)m_I2cHandle); m_I2cHandle = STATUS_INVALID_HANDLE; if (ret != STATUS_OK) { LOG_TO_STDERR(); } return ret; } /* ========================================================================== */ /** * @details This function implements the following objectives: * -# Constructs the bytes that comprise the I2C transaction according to * structure shown below. * -# Write the data to the display MPU over the I2C interface. * * The transaction order is shown below: * S Addr Wr [A] Control #1 [A] Command [A] Control #2 [A] Data [A] P * | | | | * +------- n times -------+ +-- m times --+ * Control/Command words Data bytes * Where: * - S: Start bit * - P: Stop bit * - A: Accept bit * - Wr: Write bit (= 0) * - Addr: 7-bit I2C address of the display MPU. * - [...]: Data transmitted from the display MPU. * - Control: Byte used to communicate the meaning of the next byte. The * byte structure is shown below. * +-----------------------------------------------+ * | C0 | D/C | 0 | 0 | 0 | 0 | 0 | 0 | * +-----------------------------------------------+ * Where: * - C0: Continuation bit. For C0 = 1, more Control/Command words * will proceed after the next command byte. For C0 = 0, * the next bytes will only be data bytes. * - D/C: Data/Command bit. For D/C = 1, the next byte is to be * interpretted as a data byte. For D/C = 0, the next byte * is to be interpretted as a command byte. * Specifically: * - Control #1: 0b10000000 * - Control #2: 0b01000000 * - Command: Byte used to change the setting of the display MPU. * - Data: Data to be written to DDRAM/CGRAM/SEGRAM. * * @param [in] commands: Array of command bytes to populate the Command * portion of the I2C transaction shown above. * @param [in] commandsLen: Number of command words to be included in the * I2C transaction. This is the value of "n" in the above transaction order * diagram. * @param [in] data: Array of data bytes to populate the Data portion of * the I2C transaction shown above. * @param [in] dataLen: Number of data bytes to be included in the I2C * transaction. This is the value of "m" in the above transaction order * diagram. * * @pre commands must point to a section of memory that has been previously * allocated and is commandsLen bytes long. * @pre data must point to a section of memory that has been previously * allocated and is dataLen bytes long. * * @retval STATUS_OK If the commands and data were successfully transmitted to * the display MPU. * @retval STATUS_INVALID_HANDLE If the I2C hardware was not successfully * initialised before calling this function. * @retval STATUS_INVALID_PARAM If the number of bytes to be written to the * display MPU is <= 0 (commandsLen + dataLen <= 0). * @retval STATUS_FAILED_WRITE If the message failed to be successfully written * to the display MPU. * ========================================================================== */ status_t i2c_write( uint8_t *commands, uint8_t commandsLen, uint8_t *data, uint8_t dataLen) { /* I2C interface has not yet been opened */ if (m_I2cHandle == STATUS_INVALID_HANDLE) { LOG_TO_STDERR(); return STATUS_INVALID_HANDLE; } /* Initialise the message */ uint16_t length; length = (uint16_t)(2 * commandsLen + (dataLen > 0 ? 1 + dataLen : 0)); uint8_t message[length]; /* Add the control/command byte words */ for (uint8_t i = 0; i < commandsLen; i++) { message[2 * i] = CONTROL_BYTE_COMMAND_FURTHER; message[2 * i + 1] = commands[i]; } /* Add the data control byte */ if (dataLen > 0) { message[2 * commandsLen] = CONTROL_BYTE_DATA; } /* Add the data */ for (uint16_t i = 0; i < dataLen; i++) { message[2 * commandsLen + 1 + i] = data[i]; } /* Transmit the message to the MPU */ status_t ret = (status_t) i2cWriteDevice( (uint16_t)m_I2cHandle, (char *)message, length ); if (ret != STATUS_OK) { LOG_TO_STDERR(); } return ret; } /* ========================================================================== */ /** * @details This function implements the following objectives: * -# Read data from the DDRAM/CGRAM/SEGRAM. * * The transaction order is shown below: * S Addr Wr [A] Control #1 [A] P S Addr Rd [A] [Data] [A] P * | | * +-- n times --+ * Where: * - S: Start bit * - P: Stop bit * - A: Accept bit * - Wr: Write bit (= 0) * - Rd: Read bit (= 1) * - Addr: 7-bit I2C address of the display MPU. * - [...]: Data transmitted from the display MPU. * - Control: Byte used to communicate the meaning of the next byte. The * byte structure is shown below. * +-----------------------------------------------+ * | C0 | D/C | 0 | 0 | 0 | 0 | 0 | 0 | * +-----------------------------------------------+ * Where: * - C0: Continuation bit. For read, C0 will always be 0. * - D/C: Data/Command bit. For D/C = 1, the next byte(s) to be * received should be the busy flag/address/part ID. For * For D/C = 0, the next byte(s) to be received should be * data stored in the display MPU RAM (DDRAM/CGRAM/SEGRAM, * depending which RAM is being currently used). * Specifically: * - Control #1: 0b01000000 (readRam == 1), 0b00000000 (readRam == * 0) * - Command: Byte used to change the setting of the display MPU. * - Data: Data to be read from DDRAM/CGRAM/SEGRAM or busy flag/address/ * part ID. * * If readRam == true, then the first byte of data will be a dummy byte, and as * such has no meaning. If readRam == false, then the format of the returned * data will be as shown below: * +-----------------------------------------------+ * data0: | BF | AC6 | AC5 | AC4 | AC3 | AC2 | AC1 | AC0 | * +-----------------------------------------------+ * +-----------------------------------------------+ * data1: | BF | ID6 | ID5 | ID4 | ID3 | ID2 | ID1 | ID0 | * +-----------------------------------------------+ * Where: * - BF: Busy flag. BF = 1 indicates that the display MPU is still busy * processing a previous I2C command. * - AC6:AC0: Address counter. Next address to be written to/read from. * - ID6:ID0: Part ID. Will be 0x1A. * * @param [in] readRam Flag indicating whether the read operation is to * return the data in the display MPU RAM (readRam == true) or the busy flag/ * address counter value/part ID. * @param [out] data Pointer to the memory address where the data read from * the display MPU is to be stored. * @param [in] dataLen Number of data bytes to be read from the display * MPU. * * @pre data must point to a section of memory that has been previously * allocated and is dataLen bytes long. * @pre If readRam == false, then dataLen == 2. * @pre dataLen > 0 * * @retval STATUS_OK If the data was successfully received from the display MPU. * @retval STATUS_INVALID_HANDLE If the I2C hardware was not successfully * initialised before calling this function. * @retval STATUS_INVALID_PARAM If the number of bytes to be read from the * display MPU is <= 0 (dataLen <= 0). * @retval STATUS_FAILED_WRITE If the message failed to be successfully written * to the display MPU. * @retval STATUS_FAILED_READ If the message failed to be successfully read from * the display MPU. * ========================================================================== */ status_t i2c_read( bool readRam, uint8_t *data, uint8_t dataLen) { /* Transmit the control byte */ int32_t ret = i2cWriteByte( (uint16_t)m_I2cHandle, readRam ? CONTROL_BYTE_DATA : CONTROL_BYTE_COMMAND_LAST ); if (ret < STATUS_OK) { LOG_TO_STDERR(); return (status_t)ret; } /* Receive the data */ ret = i2cReadDevice( (uint16_t)m_I2cHandle, (char *)data, dataLen ); if (ret < STATUS_OK) { LOG_TO_STDERR(); } return (ret < STATUS_OK) ? (status_t)ret : STATUS_OK; }
2.359375
2
2024-11-18T22:25:09.659855+00:00
2018-01-10T00:14:07
133316bf6830f182240d899a3b3a075274d0a018
{ "blob_id": "133316bf6830f182240d899a3b3a075274d0a018", "branch_name": "refs/heads/master", "committer_date": "2018-01-10T00:14:07", "content_id": "7fd39860ca0cc350e0a8caa55a90d142afdc828a", "detected_licenses": [ "NCSA" ], "directory_id": "2459cd54c786e7e2a912df5ecb52f327b67698dc", "extension": "c", "filename": "time.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 106232313, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 351, "license": "NCSA", "license_type": "permissive", "path": "/llvm time measuring/time.c", "provenance": "stackv2-0115.json.gz:108835", "repo_name": "bangtoven/llvm", "revision_date": "2018-01-10T00:14:07", "revision_id": "da487d138010b9e165afb8d8ab25d4aa73c04717", "snapshot_id": "f514b2e0e4f26f48f596f7320e673c283c5d5db2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bangtoven/llvm/da487d138010b9e165afb8d8ab25d4aa73c04717/llvm time measuring/time.c", "visit_date": "2021-09-03T14:58:02.489650" }
stackv2
#include <time.h> #include <sys/time.h> #include <stdio.h> double getCurrentTime() { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); printf("%ld\t", ts.tv_nsec); return ts.tv_sec + ts.tv_nsec/1000000000.0; } int main() { for (int i=0; i<1000; i++) { double t = getCurrentTime(); printf("%.9lf\n", t); } return 0; }
2.71875
3