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-18T22:25:09.753921+00:00
2018-10-07T20:58:43
3a3b9a31869f0c0b41066582b5ec2ad798557646
{ "blob_id": "3a3b9a31869f0c0b41066582b5ec2ad798557646", "branch_name": "refs/heads/master", "committer_date": "2018-10-07T20:58:43", "content_id": "5f40155bf239a5bf49efbb546e89554041486e90", "detected_licenses": [ "MIT" ], "directory_id": "2dcd1333d8be4b5f81354fe9363ee06fccdb5205", "extension": "c", "filename": "poly.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": 12651, "license": "MIT", "license_type": "permissive", "path": "/src/poly.c", "provenance": "stackv2-0115.json.gz:108963", "repo_name": "janlanecki/polynomial-calculator", "revision_date": "2018-10-07T20:58:43", "revision_id": "a893b049d8f52abdd82f19fc6af5fdc4ee5aa92c", "snapshot_id": "fc8caa1757e69b346730c84136431a0f739e60a5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/janlanecki/polynomial-calculator/a893b049d8f52abdd82f19fc6af5fdc4ee5aa92c/src/poly.c", "visit_date": "2020-03-31T06:29:43.826217" }
stackv2
/** @file Implementation of the polynomial class @author Jan Łanecki <jl385826@students.mimuw.edu.pl> @copyright University of Warsaw, Poland @date 2017-05-11, 2017-06-18 */ #include <assert.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include "poly.h" void PolyDestroy(Poly *p) { if (PolyIsCoeff(p)) return; Mono* m = p->list; while (m != NULL) { Mono* next = m->next; MonoDestroy(m); free(m); m = next; } p->list = NULL; } Poly PolyClone(const Poly *p) { if (PolyIsCoeff(p)) return *p; Poly r; Mono *mp = p->list, *mr = malloc(sizeof(Mono)); assert(mr != NULL); r.list = mr; while (mp->next != NULL) { *mr = MonoClone(mp); mr->next = malloc(sizeof(Mono)); assert(mr->next != NULL); mp = mp->next; mr = mr->next; } *mr = MonoClone(mp); mr->next = NULL; return r; } static Poly PolyAddCoeff(const Poly* p, poly_coeff_t c ); /** * Adds a coefficient to a polynomial which isn't a constant. * @param[in] p : non constant polynomial * @param[in] c : coefficient * @return */ static Poly PolyAddPolyCoeff(const Poly* p, poly_coeff_t c) { assert(!PolyIsCoeff(p)); if (c == 0) return PolyClone(p); Poly r; Mono *mp = p->list, *mr; if (mp->exp == 0) { Poly temp = PolyAddCoeff(&p->list->p, c); if (PolyIsZero(&temp)) { assert(mp->next != NULL); mp = mp->next; mr = malloc(sizeof(Mono)); assert(mr != NULL); r.list = mr; *mr = MonoClone(mp); mp = mp->next; } else if (PolyIsCoeff(&temp) && mp->next == NULL) { return temp; } else { mr = malloc(sizeof(Mono)); assert(mr != NULL); r.list = mr; *mr = MonoFromPoly(&temp, 0); mp = mp->next; } } else { mr = malloc(sizeof(Mono)); assert(mr != NULL); r.list = mr; *mr = (Mono) {.p = PolyFromCoeff(c), .exp = 0, .next = NULL}; } while(mp != NULL) { mr->next = malloc(sizeof(Mono)); assert(mr->next != NULL); mr = mr->next; *mr = MonoClone(mp); mp = mp->next; } mr->next = NULL; return r; } /** * Adds a coefficient to a polynomial. * @param[in] p : polynomial * @param[in] c : coefficient * @return `p + c` */ static Poly PolyAddCoeff(const Poly* p, poly_coeff_t c) { if (PolyIsCoeff(p)) return PolyFromCoeff(p->coeff + c); else return PolyAddPolyCoeff(p, c); } /** * Adds two normal polynomials. * @param[in] p : non constant polynomial * @param[in] q : non constant polynomial * @return */ static Poly PolyAddPolyPoly(const Poly *p, const Poly *q) { assert(!PolyIsCoeff(p) && !PolyIsCoeff(q)); bool added = true; Mono *mp = p->list, *mq = q->list, *mr = malloc(sizeof(Mono)), *mprev = NULL; assert(mr != NULL); Poly r = (Poly) {.list = mr}; while (mp != NULL || mq != NULL) { if (mq == NULL || mp != NULL && mp->exp < mq->exp) { assert(!PolyIsZero(&mp->p)); *mr = MonoClone(mp); mp = mp->next; } else if (mp == NULL || mp->exp > mq->exp) { assert(!PolyIsZero(&mq->p)); *mr = MonoClone(mq); mq = mq->next; } else { Poly temp = PolyAdd(&mp->p, &mq->p); if (!PolyIsZero(&temp)) *mr = MonoFromPoly(&temp, mp->exp); else added = false; mp = mp->next; mq = mq->next; } if (added) { mr->next = malloc(sizeof(Mono)); assert(mr->next != NULL); mprev = mr; mr = mr->next; } else added = true; } if (mr != r.list) { free(mr); mprev->next = NULL; if (r.list->next == NULL && r.list->exp == 0 && PolyIsCoeff(&r.list->p)) { Poly temp = PolyFromCoeff(r.list->p.coeff); free(r.list); r = temp; } } else { //nothing was added r = PolyFromCoeff(0); free(mr); } return r; } Poly PolyAdd(const Poly *p, const Poly *q) { if (PolyIsCoeff(p)) return PolyAddCoeff(q, p->coeff); else if (PolyIsCoeff(q)) return PolyAddCoeff(p, q->coeff); else return PolyAddPolyPoly(p, q); } /** * Compares monomials. * @param a : monomial pointer * @param b : monomial pointer * @return -1 <, 0 =, 1 > */ static poly_exp_t MonoCmp(const void* m, const void* n) { return ((const Mono *) m)->exp - ((const Mono *) n)->exp; } Poly PolyAddMonos(unsigned count, const Mono monos[]) { Mono *arr = calloc(count, sizeof(Mono)); assert(arr != NULL); memcpy(arr, monos, count * sizeof(Mono)); qsort(arr, count, sizeof(Mono), MonoCmp); Mono *dummy, *head, *prev = NULL; dummy = head = malloc(sizeof(Mono)); assert(dummy != NULL); for (unsigned i = 0; i < count; i++) { if (head == dummy || head->exp != arr[i].exp) { assert(!PolyIsZero(&arr[i].p)); head->next = malloc(sizeof(Mono)); assert(head->next != NULL); prev = head; head = head->next; *head = arr[i]; } else { Mono m = (Mono) {.p = PolyAdd(&head->p, &arr[i].p), .exp = head->exp, .next = NULL}; PolyDestroy(&head->p); PolyDestroy(&arr[i].p); if (PolyIsZero(&m.p)) { free(head); head = prev; prev->next = NULL; } else *head = m; } } Poly r = (Poly) {.list = dummy->next}; free(dummy); if (r.list == NULL) r.coeff = 0; else if (r.list->next == NULL && r.list->exp == 0 && PolyIsCoeff(&r.list->p)) { Poly temp = r.list->p; free(r.list); r = temp; } free(arr); return r; } /** * Returns number of terms of a polynomial. * @param p * @return */ static unsigned PolyLength(const Poly* p) { if (PolyIsCoeff(p)) return 0; else { unsigned count = 0; Mono* m = p->list; while (m != NULL) { count++; m = m->next; } return count; } } /** * Muliplies two non constant polynomials. * @param[in] p : non constant polynomial * @param[in] q : non constant polynomial * @return `p * q` */ static Poly PolyMulPolyPoly(const Poly *p, const Poly *q) { unsigned p_len = PolyLength(p), q_len = PolyLength(q); unsigned count = p_len * q_len, k = 0; Mono* arr = calloc(count, sizeof(struct Mono)); Mono *mp = p->list, *mq = q->list; for (unsigned i = 0; i < p_len; i++) { for (unsigned j = 0; j < q_len; j++) { arr[k++] = (Mono) {.p = PolyMul(&mp->p, &mq->p), .exp = mp->exp + mq->exp, .next = NULL}; mq = mq->next; } mq = q->list; mp = mp->next; } Poly r = PolyAddMonos(count, arr); free(arr); return r; } static Poly PolyMulCoeff(const Poly *p, poly_coeff_t c); /** * Muliplies a non constant polynomial by a coefficient. * @param[in] p : non constant polynomial * @param[in] c : coefficient * @return `p * c` */ static Poly PolyMulPolyCoeff(const Poly *p, poly_coeff_t c) { if (c == 0) return PolyZero(); Mono *mr = malloc(sizeof(Mono)), *mp = p->list; assert(mr != NULL); Mono *mprev = mr; Poly r = (Poly) {.list = mr}; while (mp != NULL) { Mono m = (Mono) {.p = PolyMulCoeff(&mp->p, c), .exp = mp->exp, .next = NULL}; if (!PolyIsZero(&m.p)) { *mr = m; mprev = mr; mr->next = malloc(sizeof(Mono)); assert(mr->next != NULL); mr = mr->next; } mp = mp->next; } if (mprev == mr) r = PolyZero(); else mprev->next = NULL; free(mr); return r; } /** * Multiplies a polynomial by a coefficient. * @param[in] p : polynomial * @param[in] c : coefficient * @return `p * c` */ static Poly PolyMulCoeff(const Poly *p, poly_coeff_t c) { if (PolyIsCoeff(p)) return PolyFromCoeff(p->coeff * c); else return PolyMulPolyCoeff(p, c); } Poly PolyMul(const Poly *p, const Poly *q) { if (PolyIsCoeff(p)) return PolyMulCoeff(q, p->coeff); else if (PolyIsCoeff(q)) return PolyMulCoeff(p, q->coeff); else return PolyMulPolyPoly(p, q); } Poly PolyNeg(const Poly *p) { if (PolyIsCoeff(p)) return PolyFromCoeff(-1 * p->coeff); Mono *mn = malloc(sizeof(Mono)), *mp = p->list; assert(mn != NULL); Poly neg = (Poly) {.list = mn}; while(mp != NULL) { mn->p = PolyNeg(&mp->p); mn->exp = mp->exp; if (mp->next == NULL) mn->next = NULL; else { mn->next = malloc(sizeof(Mono)); assert(mn->next != NULL); mn = mn->next; } mp = mp->next; } return neg; } Poly PolySub(const Poly *p, const Poly *q) { Poly neg = PolyNeg(q); Poly r = PolyAdd(p, &neg); PolyDestroy(&neg); return r; } poly_exp_t PolyDegBy(const Poly *p, unsigned var_idx) { if (PolyIsCoeff(p)) { if (PolyIsZero(p)) return -1; else return 0; } else if (var_idx == 0) { Mono *m = p->list; while (m->next != NULL) m = m->next; return m->exp; } else { poly_exp_t max = -1; Mono *m = p->list; while (m != NULL) { poly_exp_t deg = PolyDegBy(&m->p, var_idx - 1); if (deg > max) max = deg; m = m->next; } return max; } } poly_exp_t PolyDeg(const Poly *p) { if (PolyIsCoeff(p)) { if (PolyIsZero(p)) return -1; else return 0; } else { poly_exp_t max = -1; Mono *m = p->list; while (m != NULL) { poly_exp_t deg = PolyDeg(&m->p) + m->exp; if (deg > max) max = deg; m = m->next; } return max; } } bool PolyIsEq(const Poly *p, const Poly *q) { if (PolyIsCoeff(p) != PolyIsCoeff(q)) return false; else if (PolyIsCoeff(p)) return p->coeff == q->coeff; else { Mono *mp = p->list, *mq = q->list; while (mp != NULL && mq != NULL) { if (mp->exp != mq->exp || !PolyIsEq(&mp->p, &mq->p)) return false; mp = mp->next; mq = mq->next; } if (mp == NULL && mq == NULL) return true; else return false; } } /** * Evaluates @f$base^exp@f$. * @param[in] base * @param[in] exp * @return @f$base^exp@f$ */ static poly_coeff_t BinPower(poly_coeff_t base, poly_exp_t exp) { poly_coeff_t result = 1; while (exp > 0) { if (exp % 2) result *= base; base *= base; exp /= 2; } return result; } Poly PolyAt(const Poly *p, poly_coeff_t x) { if (PolyIsCoeff(p)) return PolyClone(p); Poly r = PolyZero(); poly_exp_t exp = 0; poly_coeff_t pow = 1; Mono *m = p->list; while (m != NULL) { pow *= BinPower(x, m->exp - exp); exp = m->exp; Poly pi = PolyMulCoeff(&m->p, pow); Poly q = PolyAdd(&r, &pi); PolyDestroy(&pi); PolyDestroy(&r); r = q; m = m->next; } return r; } /** * Returns polynomial @p p with each variable @p x_i substitued with * polynomial @p x[i]. Variables with index equal to or larger than * count are substituted with 0. * Takes ownership of the polynomial @p p. * @param p * @param count * @param x * @param idx * @return */ static void PolyComposeHelp(Poly *p, unsigned count, const Poly x[], unsigned idx) { if (count == idx) { Poly temp = PolyFromCoeff(PolyAtZeros(p)); PolyDestroy(p); *p = temp; } else if (!PolyIsCoeff(p)) { for (int i = 0; i < p->size; i++) PolyComposeHelp(&p->arr[i].p, count, x, idx + 1); Poly insert = x[idx]; PolyComposeAtRoot(p, &insert); } } Poly PolyCompose(const Poly *p, unsigned count, const Poly x[]) { Poly clone = PolyClone(p); PolyComposeHelp(&clone, count, x, 0); return clone; }
3.046875
3
2024-11-18T22:25:09.884393+00:00
2019-10-14T06:28:25
38eacecc1d5423599c4312e0743832fce2854c11
{ "blob_id": "38eacecc1d5423599c4312e0743832fce2854c11", "branch_name": "refs/heads/master", "committer_date": "2019-10-14T06:28:25", "content_id": "bb66c450ba68bb9a202e22e61ef32eb69adb3bb7", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "be4c8ac930f6264989751d4f91befa3731cc39cc", "extension": "c", "filename": "thread.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 213841618, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5645, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/examples/platforms/sirius/vcrtos/core/thread.c", "provenance": "stackv2-0115.json.gz:109092", "repo_name": "darkostack/openvc", "revision_date": "2019-10-14T06:28:25", "revision_id": "a2aff21eed7668dc78281a0223060bb8e35ad7dc", "snapshot_id": "94915ac1f04764970969aa663c69d1220da6af8a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/darkostack/openvc/a2aff21eed7668dc78281a0223060bb8e35ad7dc/examples/platforms/sirius/vcrtos/core/thread.c", "visit_date": "2020-08-08T13:37:50.857822" }
stackv2
#include <errno.h> #include <stdio.h> #include "assert.h" #include "thread.h" #include "irq.h" #include "bitarithm.h" #include "sched.h" #define ENABLE_DEBUG (0) #include "debug.h" volatile thread_t *thread_get(kernel_pid_t pid) { if (pid_is_valid(pid)) { return sched_threads[pid]; } return NULL; } int thread_getstatus(kernel_pid_t pid) { volatile thread_t *t = thread_get(pid); return t ? (int)t->status : (int)STATUS_NOT_FOUND; } const char *thread_getname(kernel_pid_t pid) { volatile thread_t *thread = thread_get(pid); return thread ? thread->name : NULL; return NULL; } void thread_sleep(void) { if (irq_is_in()) { return; } unsigned state = irq_disable(); sched_set_status((thread_t *)sched_active_thread, STATUS_SLEEPING); irq_restore(state); thread_yield_higher(); } int thread_wakeup(kernel_pid_t pid) { DEBUG("thread_wakeup: Trying to wakeup PID %" PRIkernel_pid "...\n", pid); unsigned old_state = irq_disable(); thread_t *other_thread = (thread_t *) thread_get(pid); if (!other_thread) { DEBUG("thread_wakeup: Thread does not exist!\n"); } else if (other_thread->status == STATUS_SLEEPING) { DEBUG("thread_wakeup: Thread is sleeping.\n"); sched_set_status(other_thread, STATUS_RUNNING); irq_restore(old_state); sched_switch(other_thread->priority); return 1; } else { DEBUG("thread_wakeup: Thread is not sleeping!\n"); } irq_restore(old_state); return (int)STATUS_NOT_FOUND; } void thread_yield(void) { unsigned old_state = irq_disable(); thread_t *me = (thread_t *)sched_active_thread; if (me->status >= STATUS_ON_RUNQUEUE) { clist_lpoprpush(&sched_runqueues[me->priority]); } irq_restore(old_state); thread_yield_higher(); } void thread_add_to_list(list_node_t *list, thread_t *thread) { assert (thread->status < STATUS_ON_RUNQUEUE); uint16_t my_prio = thread->priority; list_node_t *new_node = (list_node_t*)&thread->rq_entry; while (list->next) { thread_t *list_entry = container_of((clist_node_t*)list->next, thread_t, rq_entry); if (list_entry->priority > my_prio) { break; } list = list->next; } new_node->next = list->next; list->next = new_node; } uintptr_t thread_measure_stack_free(char *stack) { uintptr_t *stackp = (uintptr_t *)stack; /* assume that the comparison fails before or after end of stack */ /* assume that the stack grows "downwards" */ while (*stackp == (uintptr_t) stackp) { stackp++; } uintptr_t space_free = (uintptr_t) stackp - (uintptr_t) stack; return space_free; } kernel_pid_t thread_create(char *stack, int stacksize, char priority, int flags, thread_task_func_t function, void *arg, const char *name) { if (priority >= SCHED_PRIO_LEVELS) { return -EINVAL; } int total_stacksize = stacksize; /* align the stack on 16/32bit boundary */ uintptr_t misalignment = (uintptr_t) stack % ALIGN_OF(void *); if (misalignment) { misalignment = ALIGN_OF(void *) - misalignment; stack += misalignment; stacksize -= misalignment; } /* make room for the thread control block */ stacksize -= sizeof(thread_t); /* round down the stacksize to a multiple of thread_t alignments (usually * 16/32bit) */ stacksize -= stacksize % ALIGN_OF(thread_t); if (stacksize < 0) { DEBUG("thread_create: stacksize is too small!\n"); } /* allocate our thread control block at the top of our stackspace */ thread_t *cb = (thread_t *) (stack + stacksize); if (flags & THREAD_CREATE_STACKTEST) { /* assign each int of the stack the value of it's address */ uintptr_t *stackmax = (uintptr_t *) (stack + stacksize); uintptr_t *stackp = (uintptr_t *) stack; while (stackp < stackmax) { *stackp = (uintptr_t) stackp; stackp++; } } else { /* create stack guard */ *(uintptr_t *) stack = (uintptr_t) stack; } unsigned state = irq_disable(); kernel_pid_t pid = KERNEL_PID_UNDEF; for (kernel_pid_t i = KERNEL_PID_FIRST; i <= KERNEL_PID_LAST; ++i) { if (sched_threads[i] == NULL) { pid = i; break; } } if (pid == KERNEL_PID_UNDEF) { DEBUG("thread_create(): too many threads!\n"); irq_restore(state); return -EOVERFLOW; } sched_threads[pid] = cb; cb->pid = pid; cb->sp = thread_stack_init(function, arg, stack, stacksize); cb->stack_start = stack; cb->stack_size = total_stacksize; cb->name = name; cb->priority = priority; cb->status = STATUS_STOPPED; cb->rq_entry.next = NULL; #ifdef MODULE_CORE_MSG cb->wait_data = NULL; cb->msg_waiters.next = NULL; cib_init(&(cb->msg_queue), 0); cb->msg_array = NULL; #endif sched_num_threads++; DEBUG("Created thread %s. PID: %" PRIkernel_pid ". Priority: %u.\n", name, cb->pid, priority); if (flags & THREAD_CREATE_SLEEPING) { sched_set_status(cb, STATUS_SLEEPING); } else { sched_set_status(cb, STATUS_PENDING); if (!(flags & THREAD_CREATE_WOUT_YIELD)) { irq_restore(state); sched_switch(priority); return pid; } } irq_restore(state); return pid; }
2.8125
3
2024-11-18T22:25:09.961408+00:00
2016-12-31T14:59:27
e1486b20a0b48408b481fd004e1dcd824caf56f5
{ "blob_id": "e1486b20a0b48408b481fd004e1dcd824caf56f5", "branch_name": "refs/heads/master", "committer_date": "2016-12-31T14:59:27", "content_id": "2bde8579fc5c9abb7bca77bd81e37b959240afb8", "detected_licenses": [ "MIT" ], "directory_id": "4d60accab748720bf64efffe8b7fc84d0aa4451a", "extension": "c", "filename": "tutorial_5.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 77195624, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2470, "license": "MIT", "license_type": "permissive", "path": "/tutorial_5.c", "provenance": "stackv2-0115.json.gz:109221", "repo_name": "dengwenyi88/test_libevent", "revision_date": "2016-12-31T14:59:27", "revision_id": "b2b48587bf4d7e3a2717518db5bd51c59c89002a", "snapshot_id": "a03740d7a55932bdeda56b81557a5b8f1b58d8e9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dengwenyi88/test_libevent/b2b48587bf4d7e3a2717518db5bd51c59c89002a/tutorial_5.c", "visit_date": "2021-01-13T03:47:29.836677" }
stackv2
#include <event2/event-config.h> #include <netinet/in.h> #include <sys/socket.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <pthread.h> #include <event2/event.h> #include <event2/util.h> #include <event2/buffer.h> #include <event2/thread.h> #include <evthread-internal.h> #include <mm-internal.h> #include <compat/sys/queue.h> void* thread_run(void*); struct Node { int data; TAILQ_ENTRY(Node) node; }; TAILQ_HEAD(Queue,Node); struct BlockingQueue { struct Queue queue; void* empty_cond; void* queue_mu; }; void BQUEUE_INIT(struct BlockingQueue* head) { TAILQ_INIT(&head->queue); EVTHREAD_ALLOC_LOCK(head->queue_mu,0); EVTHREAD_ALLOC_COND(head->empty_cond); } void BQUEUE_PUSH(struct BlockingQueue* head,struct Node*node){ EVLOCK_LOCK(head->queue_mu,0); if( TAILQ_EMPTY(&head->queue) ){ EVTHREAD_COND_SIGNAL(head->empty_cond); } TAILQ_INSERT_TAIL(&head->queue,node,node); EVLOCK_UNLOCK(head->queue_mu,0); } struct Node* BQUEUE_POP(struct BlockingQueue* head) { struct Node* node = NULL; EVLOCK_LOCK(head->queue_mu,0); while( TAILQ_EMPTY(&head->queue)) { EVTHREAD_COND_WAIT(head->empty_cond,head->queue_mu); } node = TAILQ_FIRST(&head->queue); TAILQ_REMOVE(&head->queue,node,node); EVLOCK_UNLOCK(head->queue_mu,0); return node; } void print_qu(struct Queue* q) { struct Node* tmp; TAILQ_FOREACH(tmp,q,node){ printf("data :%d\n",tmp->data); } } void free_qu(struct Queue* root) { struct Node* tmp; TAILQ_FOREACH(tmp,root,node){ TAILQ_REMOVE(root,tmp,node); mm_free(tmp); } } int main(int argc, char **argv) { pthread_t t_pid; struct BlockingQueue queue; struct Node* tmp; evthread_use_pthreads(); BQUEUE_INIT(&queue); pthread_create(&t_pid,NULL,thread_run,(void*)&queue); while(1){ tmp = mm_malloc(sizeof(struct Node)); tmp->data = rand()%10000; BQUEUE_PUSH(&queue,tmp); } printf("main loop exit\n"); return (0); } void* thread_run(void* arg) { struct BlockingQueue* queue = (struct BlockingQueue*)arg; struct Node* tmp; while(1) { tmp = BQUEUE_POP(queue); if(tmp != NULL){ printf("thread_run :%d\n",tmp->data); mm_free(tmp); } } printf("thread_run exit\n"); return 0; }
2.734375
3
2024-11-18T22:25:10.034328+00:00
2023-08-24T07:58:02
c21b8fc697dd9594b87a1d30d14879e35478ccea
{ "blob_id": "c21b8fc697dd9594b87a1d30d14879e35478ccea", "branch_name": "refs/heads/master", "committer_date": "2023-08-24T07:58:02", "content_id": "08585a0da7791acfe78dcd7f3f01a7374ab6e4c4", "detected_licenses": [ "MIT" ], "directory_id": "cb9ffece95cef31e363b55d9e07e21cc22a446eb", "extension": "h", "filename": "wms.h", "fork_events_count": 0, "gha_created_at": "2022-10-08T03:25:12", "gha_event_created_at": "2023-08-12T08:28:55", "gha_language": "C", "gha_license_id": "MIT", "github_id": 547652064, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6059, "license": "MIT", "license_type": "permissive", "path": "/src/wms.h", "provenance": "stackv2-0115.json.gz:109349", "repo_name": "ktabata/suika2", "revision_date": "2023-08-24T07:58:02", "revision_id": "b7f9812c5171a3ed035d4eef8fb81971f5816415", "snapshot_id": "9cfef91eff89e37aa5a012c03823537b746773b3", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/ktabata/suika2/b7f9812c5171a3ed035d4eef8fb81971f5816415/src/wms.h", "visit_date": "2023-08-24T16:18:09.471296" }
stackv2
/* * Watermelon Script * Copyright (c) 2022, Keiichi Tabata. All rights reserved. */ #ifndef WMS_H #define WMS_H #include <stdbool.h> /* * Runtime Structure */ struct wms_runtime; /* * Execution */ /* Parse script and get runtime. */ struct wms_runtime *wms_make_runtime(const char *script); /* Get parse error line. */ int wms_get_parse_error_line(void); /* Get parse error column. */ int wms_get_parse_error_column(void); /* Execute main function. */ bool wms_run(struct wms_runtime *rt); /* Get runtime error line. */ int wms_get_runtime_error_line(struct wms_runtime *rt); /* Get runtime error message. */ const char *wms_get_runtime_error_message(struct wms_runtime *rt); /* Cleanup runtime. */ void wms_free_runtime(struct wms_runtime *rt); /* Must be implemented by the main code. */ int wms_printf(const char *s, ...); /* Must be implemented by the main code. */ int wms_readline(char *buf, size_t len); /* * Foreign Function Interface */ /* Value type. */ struct wms_value; /* Array element type. */ struct wms_array_element; /* Pointer to foreign function. */ typedef bool (*wms_ffi_func_ptr)(struct wms_runtime *rt); /* FFI function table. */ struct wms_ffi_func_tbl { wms_ffi_func_ptr func_ptr; const char *func_name; const char *param_name[16]; }; /* Register a foreign function. */ bool wms_register_ffi_func_tbl(struct wms_runtime *rt, struct wms_ffi_func_tbl *ffi_func_tbl, int count); /* Get the value of value. */ bool wms_get_var_value(struct wms_runtime *rt, const char *symbol, struct wms_value **ret); /* Get the type of `struct wms_value`. */ bool wms_is_int(struct wms_runtime *rt, struct wms_value *val); bool wms_is_float(struct wms_runtime *rt, struct wms_value *val); bool wms_is_str(struct wms_runtime *rt, struct wms_value *val); bool wms_is_array(struct wms_runtime *rt, struct wms_value *val); /* Get the value of `struct wms_value`. */ bool wms_get_int_value(struct wms_runtime *rt, struct wms_value *val, int *ret); bool wms_get_float_value(struct wms_runtime *rt, struct wms_value *val, double *ret); bool wms_get_str_value(struct wms_runtime *rt, struct wms_value *val, const char **ret); /* Array element traverse. */ struct wms_array_elem *wms_get_first_array_elem(struct wms_runtime *rt, struct wms_value *array); struct wms_array_elem *wms_get_next_array_elem(struct wms_runtime *rt, struct wms_array_elem *prev); /* Set the value of a variable. */ bool wms_make_int_var(struct wms_runtime *rt, const char *symbol, int val, struct wms_value **ret); bool wms_make_float_var(struct wms_runtime *rt, const char *symbol, double val, struct wms_value **ret); bool wms_make_str_var(struct wms_runtime *rt, const char *symbol, const char *val, struct wms_value **ret); bool wms_make_array_var(struct wms_runtime *rt, const char *symbol, struct wms_value **ret); /* Getters for array element. */ bool wms_get_array_elem(struct wms_runtime *rt, struct wms_value *array, struct wms_value *index, struct wms_value **ret); bool wms_get_array_elem_by_int_for_int(struct wms_runtime *rt, struct wms_value *array, int index, int *ret); bool wms_get_array_elem_by_int_for_float(struct wms_runtime *rt, struct wms_value *array, int index, double *ret); bool wms_get_array_elem_by_int_for_str(struct wms_runtime *rt, struct wms_value *array, int index, const char **ret); bool wms_get_array_elem_by_int_for_array(struct wms_runtime *rt, struct wms_value *array, int index, struct wms_value **ret); bool wms_get_array_elem_by_float_for_int(struct wms_runtime *rt, struct wms_value *array, double index, int *ret); bool wms_get_array_elem_by_float_for_float(struct wms_runtime *rt, struct wms_value *array, double index, double *ret); bool wms_get_array_elem_by_float_for_str(struct wms_runtime *rt, struct wms_value *array, double index, const char **ret); bool wms_get_array_elem_by_float_for_array(struct wms_runtime *rt, struct wms_value *array, double index, struct wms_value **ret); bool wms_get_array_elem_by_str_for_int(struct wms_runtime *rt, struct wms_value *array, const char *index, int *ret); bool wms_get_array_elem_by_str_for_float(struct wms_runtime *rt, struct wms_value *array, const char *index, double *ret); bool wms_get_array_elem_by_str_for_str(struct wms_runtime *rt, struct wms_value *array, const char *index, const char **ret); bool wms_get_array_elem_by_str_for_array(struct wms_runtime *rt, struct wms_value *array, const char *index, struct wms_value **ret); /* Setters for array element. */ bool wms_set_array_elem(struct wms_runtime *rt, struct wms_value *array, struct wms_value *index, struct wms_value *val); bool wms_set_array_elem_by_int_for_int(struct wms_runtime *rt, struct wms_value *array, int index, int val); bool wms_set_array_elem_by_int_for_float(struct wms_runtime *rt, struct wms_value *array, int index, double val); bool wms_set_array_elem_by_int_for_str(struct wms_runtime *rt, struct wms_value *array, int index, const char *val); bool wms_set_array_elem_by_int_for_array(struct wms_runtime *rt, struct wms_value *array, int index, struct wms_value *val); bool wms_set_array_elem_by_float_for_int(struct wms_runtime *rt, struct wms_value *array, double index, int val); bool wms_set_array_elem_by_float_for_float(struct wms_runtime *rt, struct wms_value *array, double index, double val); bool wms_set_array_elem_by_float_for_str(struct wms_runtime *rt, struct wms_value *array, double index, const char *val); bool wms_set_array_elem_by_float_for_array(struct wms_runtime *rt, struct wms_value *array, double index, struct wms_value *val); bool wms_set_array_elem_by_str_for_int(struct wms_runtime *rt, struct wms_value *array, const char *index, int val); bool wms_set_array_elem_by_str_for_float(struct wms_runtime *rt, struct wms_value *array, const char *index, double val); bool wms_set_array_elem_by_str_for_str(struct wms_runtime *rt, struct wms_value *array, const char *index, const char *val); bool wms_set_array_elem_by_str_for_array(struct wms_runtime *rt, struct wms_value *array, const char *index, struct wms_value *val); #endif
2.4375
2
2024-11-18T22:25:10.113961+00:00
2021-05-05T23:07:49
a2a7fd60d4f6d51171a8316b9b41a758131217b8
{ "blob_id": "a2a7fd60d4f6d51171a8316b9b41a758131217b8", "branch_name": "refs/heads/master", "committer_date": "2021-05-07T12:56:53", "content_id": "27dc6eeded9942479c491b3d3b41279bc52150c6", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "270100d25c2a2289ff422342cdcc6fe3ccfab114", "extension": "c", "filename": "flash.c", "fork_events_count": 2, "gha_created_at": "2017-07-16T21:22:14", "gha_event_created_at": "2018-08-19T17:30:34", "gha_language": "C", "gha_license_id": null, "github_id": 97411995, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 840, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/flash.c", "provenance": "stackv2-0115.json.gz:109479", "repo_name": "pmamonov/stm32f103c8t6", "revision_date": "2021-05-05T23:07:49", "revision_id": "f60d662ac75f0f7e165809960894144418e3425b", "snapshot_id": "e601de30dc8f085220d457f5b6de3f717b14cb7c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/pmamonov/stm32f103c8t6/f60d662ac75f0f7e165809960894144418e3425b/src/flash.c", "visit_date": "2021-06-05T14:10:13.625754" }
stackv2
#include "flash.h" #include "string.h" #include "FreeRTOS.h" #include "semphr.h" struct app_flash_s app_flash; xSemaphoreHandle flash_lock = NULL; int flash_save() { int i; xSemaphoreTake(flash_lock, portMAX_DELAY); app_flash.deadbeef = 0xdeadbeef; FLASH_Unlock(); FLASH_ClearFlag(FLASH_FLAG_BSY | FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR); FLASH_ErasePage(APP_FLASH); for (i = 0; i < sizeof(app_flash); i += sizeof(uint32_t)) FLASH_ProgramWord(APP_FLASH + i, *((uint32_t *)((void *)&app_flash + i))); FLASH_Lock(); xSemaphoreGive(flash_lock); return 0; } int flash_load() { flash_lock = xSemaphoreCreateMutex(); if (!flash_is_valid()) return 1; memcpy(&app_flash, (void *)APP_FLASH, sizeof(app_flash)); return 0; } int flash_is_valid() { return *(uint32_t *)APP_FLASH == 0xdeadbeef; }
2.328125
2
2024-11-18T22:25:10.211582+00:00
2017-02-01T20:47:25
6d1ea5b99be871bf6573420aae1ccdd10c6bbd95
{ "blob_id": "6d1ea5b99be871bf6573420aae1ccdd10c6bbd95", "branch_name": "refs/heads/master", "committer_date": "2017-02-01T20:47:25", "content_id": "f82959443fd2d7936c189aeb8b39a4a7c78f19ff", "detected_licenses": [ "MIT" ], "directory_id": "a19bbf35133416748f7b67654cd193890922b633", "extension": "h", "filename": "map.h", "fork_events_count": 0, "gha_created_at": "2017-02-01T20:08:43", "gha_event_created_at": "2017-02-01T20:08:44", "gha_language": null, "gha_license_id": null, "github_id": 80659121, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1825, "license": "MIT", "license_type": "permissive", "path": "/src/linked_list/map.h", "provenance": "stackv2-0115.json.gz:109609", "repo_name": "attermann/SIP2SMPP", "revision_date": "2017-02-01T20:47:25", "revision_id": "27d0c4bd7b797f2ba90214333eb0d6118efb72cf", "snapshot_id": "d19133ccfe1b9023209945ec4a4d1a468184fc56", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/attermann/SIP2SMPP/27d0c4bd7b797f2ba90214333eb0d6118efb72cf/src/linked_list/map.h", "visit_date": "2021-01-25T06:45:33.106310" }
stackv2
#ifndef MAP_H_INCLUDED #define MAP_H_INCLUDED #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #ifndef _VALUE_ #define _VALUE_ typedef void(*free_value)(void**); typedef void*(*copy_value)(const void*); typedef int(*compare_value)(const void*, const void*); #endif #ifndef _KEY_ #define _KEY_ typedef void(*free_key)(void**); typedef void*(*copy_key)(const void*); typedef int(*compare_key)(const void*, const void*); #endif #ifndef SIZE_MAX #define SIZE_MAX ((size_t) - 1) #endif /** * This enum is used for establish the status of Map */ typedef enum _map_error{ MAP_OK = 0, MAP_DESTROY, MAP_FULL, MAP_KEY_EXIST, MAP_KEY_NOT_EXIST, MAP_VALUE_EXIST, MAP_VALUE_NOT_EXIST, MAP_COPY_FUNC_NULL } map_error; typedef struct _iterator_map{ void *key; void *value;//mapped_type struct _iterator_map *previous; struct _iterator_map *next; }iterator_map; typedef struct _map{ iterator_map *begin; free_key _key_free; copy_key _key_copy; compare_key _key_compare; free_value _value_free; copy_value _value_copy; compare_value _value_compare; size_t _size; } map; map* new_map(free_key,copy_key,compare_key,free_value,copy_value,compare_value); map_error map_set(map *This, void *key, void *value); map_error map_setByCopy(map *This, void *key, void *value); void* map_get(map *This, const void *key); iterator_map* map_find(map *This, const void *key); bool map_exist(map *This, const void *key); map_error map_erase(map *This, void *key); map_error map_destroy(map **This); size_t map_size(map *This); //struct _iterator_map* map_begin(map *This); //struct _iterator_map* map_end(map *This); #endif // MAP_H_INCLUDED
2.484375
2
2024-11-18T22:25:10.344937+00:00
2022-11-01T05:29:04
7d0aaf923be3e03d777d5d6f476e7972d6cc801a
{ "blob_id": "7d0aaf923be3e03d777d5d6f476e7972d6cc801a", "branch_name": "refs/heads/master", "committer_date": "2022-11-01T05:29:04", "content_id": "2e3c665bdc709fce4490ec21153b929baaaa148d", "detected_licenses": [ "MIT" ], "directory_id": "601d283e1cf70ade91c849f13dac482cb8283a61", "extension": "h", "filename": "HD44780.h", "fork_events_count": 39, "gha_created_at": "2016-12-25T15:47:27", "gha_event_created_at": "2022-11-01T05:19:02", "gha_language": "C", "gha_license_id": "MIT", "github_id": 77332596, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 436, "license": "MIT", "license_type": "permissive", "path": "/stm8s/examples/Demo_MMA8452/HD44780.h", "provenance": "stackv2-0115.json.gz:109739", "repo_name": "lujji/stm8-bare-min", "revision_date": "2022-11-01T05:29:04", "revision_id": "27c36ae3255ae08b294c0a0f61e3fd261e172580", "snapshot_id": "671ef8cb830950f8f74791f324077fb5a6a4313b", "src_encoding": "UTF-8", "star_events_count": 115, "url": "https://raw.githubusercontent.com/lujji/stm8-bare-min/27c36ae3255ae08b294c0a0f61e3fd261e172580/stm8s/examples/Demo_MMA8452/HD44780.h", "visit_date": "2022-11-12T05:41:59.288372" }
stackv2
#ifndef HD44780_H #define HD44780_H #include <stdint.h> #include <stm8s.h> #define HD44780_CMD_CLEAR 0x01 /* * Initialize LCD and corresponding IO pins */ void LCD_init(); /* * Write char to display */ void LCD_putc(char c); /* * Set LCD cursor * * @param col: 0 .. 15 * @param row: 0 .. 1 */ void LCD_goto(uint8_t col, uint8_t row); /* * Send command to display */ void LCD_cmd(uint8_t cmd); #endif /* HD44780_H */
2.125
2
2024-11-18T22:25:10.425804+00:00
2020-01-30T15:52:16
14e1d2e7a81b00df1b9d203ad817aafb223a0dda
{ "blob_id": "14e1d2e7a81b00df1b9d203ad817aafb223a0dda", "branch_name": "refs/heads/master", "committer_date": "2020-01-30T15:52:16", "content_id": "02ada615c3fafe84d85daccf119d9213994e82cc", "detected_licenses": [ "MIT" ], "directory_id": "40de3da30239862f11a946166b50438174c2fd4e", "extension": "c", "filename": "bak.fortune.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 237240459, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1587, "license": "MIT", "license_type": "permissive", "path": "/lib/wizards/nalle/bak.fortune.c", "provenance": "stackv2-0115.json.gz:109870", "repo_name": "vlehtola/questmud", "revision_date": "2020-01-30T15:52:16", "revision_id": "8bc3099b5ad00a9e0261faeb6637c76b521b6dbe", "snapshot_id": "f53b7205351f30e846110300d60b639d52d113f8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/vlehtola/questmud/8bc3099b5ad00a9e0261faeb6637c76b521b6dbe/lib/wizards/nalle/bak.fortune.c", "visit_date": "2020-12-23T19:59:44.886028" }
stackv2
// By Nalle, December 2003. Fortunes ripped from linux's 'fortune'. #define FORTUNE_DIR "/wizards/nalle/fortune/" #define BUFFER_SIZE 5000 string *files = ({ "art", "computers", "cookie", "drugs", "love", "magic", "medicine", "men-women", "pets" }); // To check the amount, in shell do -> 'grep "%" men-women | wc -l' int *amounts = ({ 461, 1038, 1141, 208, 151, 29, 73, 584, 51 }); string give_fortune(string type) { int i, n, readat; int now_at; int type_int, fortune, read_at; string buffy, result; // Initial checks and sanity if(!type) type = files[random(sizeof(files))]; type_int = member_array( type, files ); if(type_int == -1) type_int = random(sizeof(files)); fortune = random(amounts[type_int]); read_at = 0; i = 0; n = 0; next = 0; now_at = 0; while( n < 5000000 && n < fortune) { buffy = read_bytes( FORTUNE_DIR + files[ type_int ], read_at, BUFFER_SIZE ); if(!buffy) { write("File read error. (read_at == "+read_at+", n == "+n+" fortune == "+fortune+")\n"); break; } for( now_at = 0; n < fortune; n++ ) { if( strstr( buffy, "%", now_at + 1 ) == -1 ) { read_at += BUFFER_SIZE; // Buffer spent break; } else { now_at = strstr( buffy, "%", now_at + 1 ); } } } result = read_bytes( FORTUNE_DIR + files[ type_int ], read_at+now_at, 1000 ); write("read_at == "+read_at+", n == "+n+", fortune == "+fortune+", now_at == "+now_at+" type == "+type+"\n"); return result[ 0 .. strstr(result, "%", 1) ]; // return result; } string *query_categories() { return files; }
2.3125
2
2024-11-18T22:25:10.541428+00:00
2017-06-15T10:23:53
a19a01669d3713fc299148b60e1d52614acbfa79
{ "blob_id": "a19a01669d3713fc299148b60e1d52614acbfa79", "branch_name": "refs/heads/master", "committer_date": "2017-06-15T10:23:53", "content_id": "a29e3250c8d543353ba5969f550f156753a141c9", "detected_licenses": [ "Apache-2.0" ], "directory_id": "1432974064ecf6e82da3606f311fb77ec56f5b73", "extension": "c", "filename": "parse_config_file.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": 7712, "license": "Apache-2.0", "license_type": "permissive", "path": "/R-CarM3/src/services/pci/modules/hw/src/parse/parse_config_file.c", "provenance": "stackv2-0115.json.gz:109999", "repo_name": "passdedd/R-CarM3_Salvator_qnx70", "revision_date": "2017-06-15T10:23:53", "revision_id": "d6cf43d4a4edf2a5264a027917854f2d43098ff2", "snapshot_id": "60eecbb226ebfcb52a7d6b8eb589e7191f3521d5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/passdedd/R-CarM3_Salvator_qnx70/d6cf43d4a4edf2a5264a027917854f2d43098ff2/R-CarM3/src/services/pci/modules/hw/src/parse/parse_config_file.c", "visit_date": "2021-06-17T21:00:59.254785" }
stackv2
/* * $QNXLicenseC: * Copyright (c) 2012, 2016 QNX Software Systems. All Rights Reserved. * * You must obtain a written license from and pay applicable license fees to QNX * Software Systems before you may reproduce, modify or distribute this software, * or any work that includes all or part of this software. Free development * licenses are available for evaluation and non-commercial purposes. For more * information visit http://licensing.qnx.com or email licensing@qnx.com. * * This file may contain contributions from others. Please review this entire * file for other proprietary rights or license notices, as well as the QNX * Development Suite License Guide at http://licensing.qnx.com/license-guide/ * for other information. * $ */ #include <stdio.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <string.h> #include <ctype.h> #include "private/pci_slog.h" #include "parse.h" static known_section_types_t known_section_types[] = { {.name = "interrupts", .len = sizeof("interrupts") - 1, .section_parser = parse_section_interrupts}, {.name = "slots", .len = sizeof("slots") - 1, .section_parser = parse_section_slots}, {.name = "aspace", .len = sizeof("aspace") - 1, .section_parser = parse_section_aspace}, {.name = "rbar", .len = sizeof("rbar") - 1, .section_parser = parse_section_rbar}, }; /* =============================================================================== process_section_hw_specific This function pointer is provided to allow for a HW specific module to hook into the processing of a HW configuration file. The intention is that in some situations we may want to add a section to a HW configuration file that has no applicability to any other HW module. Although we could just add the section definition to 'hw_cfg_t' and similarly add it to the 'known_section_types[]' above, if this section truly was not applicable to any other HW module we would be unnecessarily increasing the size of every other module for a section that they will never see. Instead, to accommodate such scenarios, a HW specific module can set this function pointer to its own 'process_section_xxx()' function. As each section is found, the HW specific module will be given an opportunity to handle the section itself. The function returns true or false depending on whether or not it processed the section. If it does not process the section and the section is known, the default processing of the common parsing code will be done. */ __attribute__ ((visibility ("internal"))) process_section_hw_specific_f process_section_hw_specific = NULL; static bool_t find_section(const char *start, const char *end, section_info_t *section_info, hw_cfg_t *cfg); static void process_section(section_info_t *section_info, hw_cfg_t *cfg); /* =============================================================================== parse_config_file This function is called to parse a HW configuration file and fill in the <cfg> parameter */ __attribute__ ((visibility ("internal"))) void parse_config_file(const char const *fname, hw_cfg_t *cfg) { if (fname == NULL) return; else if (*fname == '\0') return; { struct stat s; const char const *fp = MAP_FAILED; int fd = open(fname, O_RDONLY); if ((fd >= 0) && (fstat(fd, &s) == 0) && ((fp = mmap(NULL, s.st_size, PROT_READ, MAP_SHARED, fd, 0)) != MAP_FAILED)) { /* lets parse the file */ section_info_t section_info; const char *end_of_file = fp + s.st_size - 1; // points to the last valid byte of the file slog_info(0, "++ HW Config file '%s' parse start ++", fname); find_section(fp, end_of_file, &section_info, cfg); slog_info(0, "++ HW Config file '%s' parse end ++", fname); } else { slog_warn(0, "%s environment variable set to %s but could not be opened or otherwise read", PCI_ENVVAR_HW_CONFIG, fname); } if (fp != MAP_FAILED) munmap((void *)fp, s.st_size); if (fd >= 0) close(fd); } } /* =============================================================================== find_section This function will search for a valid section tag between <start> and <end> inclusive. A valid section tag consists of the SECTION_HDR_START_CHAR, a section name and a SECTION_HDR_END_CHAR. The section name may be surrounded by whitespace characters only (tabs or spaces). Finding a valid section tag does not mean the section is known, only that a valid section tag exists If a valid section tag is found, the <section> info is updated. As part of updating the <section_info>, the end of the section is required. This information is obtained by searching for the next section. If the next section is found, the end of the current section is 1 byte less than the start of the next. If its not found, the end of the section is <end>. As we recurse down finding sections, eventually no more will be found. At that point we process the section (starting from the last section found) and unwinding back up to the beginning. The reason for processing this way is so that we don't duplicate the section processing in order to find the next section */ static bool_t find_section(const char *start, const char *end, section_info_t *section_info, hw_cfg_t *cfg) { bool_t section_found = false; const char *section_hdr_start = find_token(SECTION_HDR_START_CHAR, start, end); if (section_hdr_start != NULL) { const char *section_hdr_end = find_token(SECTION_HDR_END_CHAR, section_hdr_start + 1, end); if (section_hdr_end != NULL) { /* determine whether a valid name exists between section_hdr_start and section_hdr_end */ uint_t section_name_len; const char *section_name = find_name(section_hdr_start + 1, section_hdr_end - 1, &section_name_len, NULL); if (section_name != NULL) { section_found = true; /* section tag exists. Find the end of the section by searching for the next section tag */ section_info_t next_section_info; bool_t next_section_found = find_section(section_hdr_end + 1, end, &next_section_info, cfg); section_info->start = section_hdr_start; section_info->name.str = section_name; section_info->name.len = section_name_len; section_info->params.start = section_hdr_end + 1; if (next_section_found) section_info->params.end = next_section_info.start - 1; else section_info->params.end = end; bool_t section_processed = false; if (process_section_hw_specific != NULL) { section_processed = process_section_hw_specific(section_info, cfg, NULL); } if (!section_processed) process_section(section_info, cfg); } } } return section_found; } /* =============================================================================== process_section */ static void process_section(section_info_t *section_info, hw_cfg_t *cfg) { uint_t i; /* determine whether this is a known section and if so, parse it */ for (i=0; i<NELEMENTS(known_section_types); i++) { if (strncasecmp(section_info->name.str, known_section_types[i].name, section_info->name.len) == 0) { /* parse the parameters for the section */ void (*parse_section)() = known_section_types[i].section_parser; char *str; MAKE_TMP_STRING(str, section_info->name.str, section_info->name.len); slog_info(0, "+++ Parsing section [%s] start +++", str); parse_section(section_info->params.start, section_info->params.end, cfg); slog_info(0, "+++ Parsing section [%s] end +++", str); break; } } } #if defined(__QNXNTO__) && defined(__USESRCVERSION) #include <sys/srcversion.h> __SRCVERSION("$URL: http://svn.ott.qnx.com/product/branches/7.0.0/beta/services/pci/modules/hw/src/parse/parse_config_file.c $ $Rev: 798837 $") #endif
2.21875
2
2024-11-18T22:25:10.889931+00:00
2016-08-23T15:51:06
aba0cbbc16729323d83e40e8e28c222a2daf7bf8
{ "blob_id": "aba0cbbc16729323d83e40e8e28c222a2daf7bf8", "branch_name": "refs/heads/master", "committer_date": "2016-08-23T15:51:06", "content_id": "e9c9ea0710b2ca24dce2b91ee8fc58d16ba117b6", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "560be6d398e9fb92afe281933395019d4332445a", "extension": "c", "filename": "THZTensorLapack.c", "fork_events_count": 1, "gha_created_at": "2016-02-05T15:28:15", "gha_event_created_at": "2016-02-05T15:28:16", "gha_language": null, "gha_license_id": null, "github_id": 51154676, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 14485, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/lib/THZ/generic/THZTensorLapack.c", "provenance": "stackv2-0115.json.gz:110515", "repo_name": "PhilippPelz/ztorch", "revision_date": "2016-08-23T15:51:06", "revision_id": "76e7bad0d9cb061091e869f123a5390317ad767e", "snapshot_id": "f03547460d62d0b79025e0ca3c74a85e3d905d36", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/PhilippPelz/ztorch/76e7bad0d9cb061091e869f123a5390317ad767e/lib/THZ/generic/THZTensorLapack.c", "visit_date": "2021-01-18T08:41:51.655663" }
stackv2
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #ifndef THZ_GENERIC_FILE #define THZ_GENERIC_FILE "generic/THZTensorLapack.c" #else static int THZTensor_(lapackClone)(THZTensor *r_, THZTensor *m, int forced) { int clone; if (!forced && m->stride[0] == 1 && m->stride[1] == m->size[0]) { clone = 0; THZTensor_(set)(r_,m); } else { clone = 1; /* we need to copy */ THZTensor_(resize2d)(r_,m->size[1],m->size[0]); THZTensor_(transpose)(r_,NULL,0,1); THZTensor_(copy)(r_,m); } return clone; } THZ_API void THZTensor_(gesv)(THZTensor *rb_, THZTensor *ra_, THZTensor *b, THZTensor *a) { int n, nrhs, lda, ldb, info; THIntTensor *ipiv; THZTensor *ra__; THZTensor *rb__; int clonea; int cloneb; int destroya; int destroyb; if (a == NULL || ra_ == a) /* possibly destroy the inputs */ { ra__ = THZTensor_(new)(); clonea = THZTensor_(lapackClone)(ra__,ra_,0); destroya = 1; } else /*we want to definitely clone and use ra_ and rb_ as computational space*/ { clonea = THZTensor_(lapackClone)(ra_,a,1); ra__ = ra_; destroya = 0; } if (b == NULL || rb_ == b) /* possibly destroy the inputs */ { rb__ = THZTensor_(new)(); cloneb = THZTensor_(lapackClone)(rb__,rb_,0); destroyb = 1; } else /*we want to definitely clone and use ra_ and rb_ as computational space*/ { cloneb = THZTensor_(lapackClone)(rb_,b,1); rb__ = rb_; destroyb = 0; } THArgCheck(ra__->nDimension == 2, 1, "A should be 2 dimensional"); THArgCheck(rb__->nDimension == 2, 2, "b should be 2 dimensional"); THArgCheck(ra__->size[0] == ra__->size[1], 1, "A should be square"); THArgCheck(rb__->size[0] == ra__->size[0], 2, "A,b size incomptable"); n = (int)ra__->size[0]; nrhs = (int)rb__->size[1]; lda = n; ldb = n; ipiv = THIntTensor_newWithSize1d((long)n); THZLapack_(gesv)(n, nrhs, THZTensor_(data)(ra__), lda, THIntTensor_data(ipiv), THZTensor_(data)(rb__), ldb, &info); /* clean up */ if (destroya) { if (clonea) { THZTensor_(copy)(ra_,ra__); } THZTensor_(free)(ra__); } if (destroyb) { if (cloneb) { THZTensor_(copy)(rb_,rb__); } THZTensor_(free)(rb__); } if (info < 0) { THError("Lapack gesv : Argument %d : illegal value", -info); } else if (info > 0) { THError("Lapack gesv : U(%d,%d) is zero, singular U.", info,info); } THIntTensor_free(ipiv); } THZ_API void THZTensor_(gels)(THZTensor *rb_, THZTensor *ra_, THZTensor *b, THZTensor *a) { int m, n, nrhs, lda, ldb, info, lwork; THZTensor *work = NULL; real wkopt = 0; THZTensor *ra__; THZTensor *rb__; int clonea; int cloneb; int destroya; int destroyb; if (a == NULL || ra_ == a) /* possibly destroy the inputs */ { ra__ = THZTensor_(new)(); clonea = THZTensor_(lapackClone)(ra__,ra_,0); destroya = 1; } else /*we want to definitely clone and use ra_ and rb_ as computational space*/ { clonea = THZTensor_(lapackClone)(ra_,a,1); ra__ = ra_; destroya = 0; } if (b == NULL || rb_ == b) /* possibly destroy the inputs */ { rb__ = THZTensor_(new)(); cloneb = THZTensor_(lapackClone)(rb__,rb_,0); destroyb = 1; } else /*we want to definitely clone and use ra_ and rb_ as computational space*/ { cloneb = THZTensor_(lapackClone)(rb_,b,1); rb__ = rb_; destroyb = 0; } THArgCheck(ra__->nDimension == 2, 1, "A should be 2 dimensional"); THArgCheck(ra_->size[0] == rb__->size[0], 2, "size incompatible A,b"); m = ra__->size[0]; n = ra__->size[1]; nrhs = rb__->size[1]; lda = m; ldb = m; info = 0; /* get optimal workspace size */ THZLapack_(gels)('N', m, n, nrhs, THZTensor_(data)(ra__), lda, THZTensor_(data)(rb__), ldb, &wkopt, -1, &info); lwork = (int)wkopt; work = THZTensor_(newWithSize1d)(lwork); THZLapack_(gels)('N', m, n, nrhs, THZTensor_(data)(ra__), lda, THZTensor_(data)(rb__), ldb, THZTensor_(data)(work), lwork, &info); /* printf("lwork = %d,%g\n",lwork,THZTensor_(data)(work)[0]); */ if (info != 0) { THError("Lapack gels : Argument %d : illegal value", -info); } /* clean up */ if (destroya) { if (clonea) { THZTensor_(copy)(ra_,ra__); } THZTensor_(free)(ra__); } if (destroyb) { if (cloneb) { THZTensor_(copy)(rb_,rb__); } THZTensor_(free)(rb__); } THZTensor_(free)(work); } THZ_API void THZTensor_(geev)(THZTensor *re_, THZTensor *rv_, THZTensor *a_, const char *jobvr) { int n, lda, lwork, info, ldvr; THZTensor *work, *wi, *wr, *a; real wkopt; real *rv_data; long i; THArgCheck(a_->nDimension == 2, 3, "A should be 2 dimensional"); THArgCheck(a_->size[0] == a_->size[1], 3,"A should be square"); /* we want to definitely clone */ a = THZTensor_(new)(); THZTensor_(lapackClone)(a,a_,1); n = a->size[0]; lda = n; wi = THZTensor_(new)(); wr = THZTensor_(new)(); THZTensor_(resize2d)(re_,n,2); THZTensor_(resize1d)(wi,n); THZTensor_(resize1d)(wr,n); rv_data = NULL; ldvr = 1; if (*jobvr == 'V') { THZTensor_(resize2d)(rv_,n,n); rv_data = THZTensor_(data)(rv_); ldvr = n; } /* get optimal workspace size */ THZLapack_(geev)('N', jobvr[0], n, THZTensor_(data)(a), lda, THZTensor_(data)(wr), THZTensor_(data)(wi), NULL, 1, rv_data, ldvr, &wkopt, -1, &info); lwork = (int)wkopt; work = THZTensor_(newWithSize1d)(lwork); THZLapack_(geev)('N', jobvr[0], n, THZTensor_(data)(a), lda, THZTensor_(data)(wr), THZTensor_(data)(wi), NULL, 1, rv_data, ldvr, THZTensor_(data)(work), lwork, &info); if (info > 0) { THError(" Lapack geev : Failed to converge. %d off-diagonal elements of an didn't converge to zero",info); } else if (info < 0) { THError("Lapack geev : Argument %d : illegal value", -info); } { real *re_data = THZTensor_(data)(re_); real *wi_data = THZTensor_(data)(wi); real *wr_data = THZTensor_(data)(wr); for (i=0; i<n; i++) { re_data[2*i] = wr_data[i]; re_data[2*i+1] = wi_data[i]; } } if (*jobvr == 'V') { THZTensor_(transpose)(rv_,NULL,0,1); } THZTensor_(free)(a); THZTensor_(free)(wi); THZTensor_(free)(wr); THZTensor_(free)(work); } THZ_API void THZTensor_(syev)(THZTensor *re_, THZTensor *rv_, THZTensor *a, const char *jobz, const char *uplo) { int n, lda, lwork, info; THZTensor *work; real wkopt; THZTensor *rv__; int clonea; int destroy; if (a == NULL) /* possibly destroy the inputs */ { rv__ = THZTensor_(new)(); clonea = THZTensor_(lapackClone)(rv__,rv_,0); destroy = 1; } else /*we want to definitely clone and use ra_ and rb_ as computational space*/ { clonea = THZTensor_(lapackClone)(rv_,a,1); rv__ = rv_; destroy = 0; } THArgCheck(rv__->nDimension == 2, 2, "A should be 2 dimensional"); n = rv__->size[0]; lda = n; THZTensor_(resize1d)(re_,n); /* get optimal workspace size */ THZLapack_(syev)(jobz[0], uplo[0], n, THZTensor_(data)(rv__), lda, THZTensor_(data)(re_), &wkopt, -1, &info); lwork = (int)wkopt; work = THZTensor_(newWithSize1d)(lwork); THZLapack_(syev)(jobz[0], uplo[0], n, THZTensor_(data)(rv__), lda, THZTensor_(data)(re_), THZTensor_(data)(work), lwork, &info); if (info > 0) { THError(" Lapack syev : Failed to converge. %d off-diagonal elements of an didn't converge to zero",info); } else if (info < 0) { THError("Lapack syev : Argument %d : illegal value", -info); } /* clean up */ if (destroy) { if (clonea) { THZTensor_(copy)(rv_,rv__); } THZTensor_(free)(rv__); } THZTensor_(free)(work); } THZ_API void THZTensor_(gesvd)(THZTensor *ru_, THZTensor *rs_, THZTensor *rv_, THZTensor *a, const char* jobu) { THZTensor *ra_ = THZTensor_(new)(); THZTensor_(gesvd2)(ru_, rs_, rv_, ra_, a, jobu); THZTensor_(free)(ra_); } THZ_API void THZTensor_(gesvd2)(THZTensor *ru_, THZTensor *rs_, THZTensor *rv_, THZTensor *ra_, THZTensor *a, const char* jobu) { int k,m, n, lda, ldu, ldvt, lwork, info; THZTensor *work; real wkopt; THZTensor *ra__; int clonea; int destroy; if (a == NULL) /* possibly destroy the inputs */ { ra__ = THZTensor_(new)(); clonea = THZTensor_(lapackClone)(ra__,ra_,0); destroy = 1; } else /*we want to definitely clone */ { clonea = THZTensor_(lapackClone)(ra_,a,1); ra__ = ra_; destroy = 0; } THArgCheck(ra__->nDimension == 2, 2, "A should be 2 dimensional"); m = ra__->size[0]; n = ra__->size[1]; k = (m < n ? m : n); lda = m; ldu = m; ldvt = n; THZTensor_(resize1d)(rs_,k); THZTensor_(resize2d)(rv_,ldvt,n); if (*jobu == 'A') { THZTensor_(resize2d)(ru_,m,ldu); } else { THZTensor_(resize2d)(ru_,k,ldu); } THZTensor_(transpose)(ru_,NULL,0,1); /* we want to return V not VT*/ /*THZTensor_(transpose)(rv_,NULL,0,1);*/ THZLapack_(gesvd)(jobu[0],jobu[0], m,n,THZTensor_(data)(ra__),lda, THZTensor_(data)(rs_), THZTensor_(data)(ru_), ldu, THZTensor_(data)(rv_), ldvt, &wkopt, -1, &info); lwork = (int)wkopt; work = THZTensor_(newWithSize1d)(lwork); THZLapack_(gesvd)(jobu[0],jobu[0], m,n,THZTensor_(data)(ra__),lda, THZTensor_(data)(rs_), THZTensor_(data)(ru_), ldu, THZTensor_(data)(rv_), ldvt, THZTensor_(data)(work),lwork, &info); if (info > 0) { THError(" Lapack gesvd : %d superdiagonals failed to converge.",info); } else if (info < 0) { THError("Lapack gesvd : Argument %d : illegal value", -info); } /* clean up */ if (destroy) { if (clonea) { THZTensor_(copy)(ra_,ra__); } THZTensor_(free)(ra__); } THZTensor_(free)(work); } THZ_API void THZTensor_(getri)(THZTensor *ra_, THZTensor *a) { int m, n, lda, info, lwork; real wkopt; THIntTensor *ipiv; THZTensor *work; THZTensor *ra__; int clonea; int destroy; if (a == NULL) /* possibly destroy the inputs */ { ra__ = THZTensor_(new)(); clonea = THZTensor_(lapackClone)(ra__,ra_,0); destroy = 1; } else /*we want to definitely clone */ { clonea = THZTensor_(lapackClone)(ra_,a,1); ra__ = ra_; destroy = 0; } THArgCheck(ra__->nDimension == 2, 2, "A should be 2 dimensional"); m = ra__->size[0]; n = ra__->size[1]; THArgCheck(m == n, 2, "A should be square"); lda = m; ipiv = THIntTensor_newWithSize1d((long)m); /* Run LU */ THZLapack_(getrf)(n, n, THZTensor_(data)(ra__), lda, THIntTensor_data(ipiv), &info); if (info > 0) { THError("Lapack getrf : U(%d,%d) is 0, U is singular",info, info); } else if (info < 0) { THError("Lapack getrf : Argument %d : illegal value", -info); } /* Run inverse */ THZLapack_(getri)(n, THZTensor_(data)(ra__), lda, THIntTensor_data(ipiv), &wkopt, -1, &info); lwork = (int)wkopt; work = THZTensor_(newWithSize1d)(lwork); THZLapack_(getri)(n, THZTensor_(data)(ra__), lda, THIntTensor_data(ipiv), THZTensor_(data)(work), lwork, &info); if (info > 0) { THError("Lapack getri : U(%d,%d) is 0, U is singular",info, info); } else if (info < 0) { THError("Lapack getri : Argument %d : illegal value", -info); } /* clean up */ if (destroy) { if (clonea) { THZTensor_(copy)(ra_,ra__); } THZTensor_(free)(ra__); } THZTensor_(free)(work); THIntTensor_free(ipiv); } THZ_API void THZTensor_(potrf)(THZTensor *ra_, THZTensor *a) { int n, lda, info; char uplo = 'U'; THZTensor *ra__; int clonea; int destroy; if (a == NULL) /* possibly destroy the inputs */ { ra__ = THZTensor_(new)(); clonea = THZTensor_(lapackClone)(ra__,ra_,0); destroy = 1; } else /*we want to definitely clone */ { clonea = THZTensor_(lapackClone)(ra_,a,1); ra__ = ra_; destroy = 0; } THArgCheck(ra__->nDimension == 2, 2, "A should be 2 dimensional"); THArgCheck(ra__->size[0] == ra__->size[1], 2, "A should be square"); n = ra__->size[0]; lda = n; /* Run Factorization */ THZLapack_(potrf)(uplo, n, THZTensor_(data)(ra__), lda, &info); if (info > 0) { THError("Lapack potrf : A(%d,%d) is 0, A cannot be factorized", info, info); } else if (info < 0) { THError("Lapack potrf : Argument %d : illegal value", -info); } /* Build full upper-triangular matrix */ { real *p = THZTensor_(data)(ra__); long i,j; for (i=0; i<n; i++) { for (j=i+1; j<n; j++) { p[i*n+j] = 0; } } } /* clean up */ if (destroy) { if (clonea) { THZTensor_(copy)(ra_,ra__); } THZTensor_(free)(ra__); } } THZ_API void THZTensor_(potri)(THZTensor *ra_, THZTensor *a) { int n, lda, info; char uplo = 'U'; THZTensor *ra__; int clonea; int destroy; if (a == NULL) /* possibly destroy the inputs */ { ra__ = THZTensor_(new)(); clonea = THZTensor_(lapackClone)(ra__,ra_,0); destroy = 1; } else /*we want to definitely clone */ { clonea = THZTensor_(lapackClone)(ra_,a,1); ra__ = ra_; destroy = 0; } THArgCheck(ra__->nDimension == 2, 2, "A should be 2 dimensional"); THArgCheck(ra__->size[0] == ra__->size[1], 2, "A should be square"); n = ra__->size[0]; lda = n; /* Run Factorization */ THZLapack_(potrf)(uplo, n, THZTensor_(data)(ra__), lda, &info); if (info > 0) { THError("Lapack potrf : A(%d,%d) is 0, A cannot be factorized", info, info); } else if (info < 0) { THError("Lapack potrf : Argument %d : illegal value", -info); } /* Run inverse */ THZLapack_(potri)(uplo, n, THZTensor_(data)(ra__), lda, &info); if (info > 0) { THError("Lapack potrf : A(%d,%d) is 0, A cannot be factorized", info, info); } else if (info < 0) { THError("Lapack potrf : Argument %d : illegal value", -info); } /* Build full matrix */ { real *p = THZTensor_(data)(ra__); long i,j; for (i=0; i<n; i++) { for (j=i+1; j<n; j++) { p[i*n+j] = p[j*n+i]; } } } /* clean up */ if (destroy) { if (clonea) { THZTensor_(copy)(ra_,ra__); } THZTensor_(free)(ra__); } } #endif
2.296875
2
2024-11-18T22:25:10.951244+00:00
2023-07-24T07:48:46
e50743e6ed35be19d85abf7254c2c4c90e272076
{ "blob_id": "e50743e6ed35be19d85abf7254c2c4c90e272076", "branch_name": "refs/heads/master", "committer_date": "2023-07-24T07:48:46", "content_id": "89ed7606107a54f788bb915cb69aa4a9766da16f", "detected_licenses": [ "MIT" ], "directory_id": "71dba066f4baffa86199eae530e32bc0fa8c23e7", "extension": "c", "filename": "ml_set.c", "fork_events_count": 1, "gha_created_at": "2017-12-23T09:02:16", "gha_event_created_at": "2023-08-30T06:22:03", "gha_language": "C", "gha_license_id": "MIT", "github_id": 115183943, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 33696, "license": "MIT", "license_type": "permissive", "path": "/src/ml_set.c", "provenance": "stackv2-0115.json.gz:110647", "repo_name": "wrapl/minilang", "revision_date": "2023-07-24T07:48:46", "revision_id": "7ded18568d6408d773be0da635cd6ce740da06f0", "snapshot_id": "f850b0c65e47e7c57c34bcb11d1edbd184fa778f", "src_encoding": "UTF-8", "star_events_count": 33, "url": "https://raw.githubusercontent.com/wrapl/minilang/7ded18568d6408d773be0da635cd6ce740da06f0/src/ml_set.c", "visit_date": "2023-08-17T08:30:30.210466" }
stackv2
#include "ml_set.h" #include "minilang.h" #include "ml_macros.h" #include <string.h> #include "ml_sequence.h" #include "ml_method.h" #include "ml_object.h" #undef ML_CATEGORY #define ML_CATEGORY "set" ML_TYPE(MLSetT, (MLSequenceT), "set" // A set of values. // Values can be of any type supporting hashing and comparison. // By default, iterating over a set generates the values in the order they were inserted, however this ordering can be changed. ); #ifdef ML_MUTABLES ML_TYPE(MLSetMutableT, (MLSetT), "set::mutable"); #else #define MLSetMutableT MLSetT #endif #ifdef ML_GENERICS static void ml_set_update_generic(ml_set_t *Set, ml_value_t *Value) { if (Set->Type->Type != MLTypeGenericT) { Set->Type = ml_generic_type(2, (ml_type_t *[]){Set->Type, ml_typeof(Value)}); } else { ml_type_t *ValueType0 = ml_typeof(Value); ml_type_t *BaseType = ml_generic_type_args(Set->Type)[0]; ml_type_t *ValueType = ml_generic_type_args(Set->Type)[1]; if (!ml_is_subtype(ValueType0, ValueType)) { ml_type_t *ValueType2 = ml_type_max(ValueType, ValueType0); if (ValueType != ValueType2) { Set->Type = ml_generic_type(2, (ml_type_t *[]){BaseType, ValueType2}); } } } } #endif ML_ENUM2(MLSetOrderT, "set::order", // * :mini:`set::order::Insert` |harr| default ordering; inserted values are put at end, no reordering on access. // * :mini:`set::order::Ascending` |harr| inserted values are kept in ascending order, no reordering on access. // * :mini:`set::order::Descending` |harr| inserted values are kept in descending order, no reordering on access. // * :mini:`set::order::MRU` |harr| inserted values are put at start, accessed values are moved to start. // * :mini:`set::order::LRU` |harr| inserted values are put at end, accessed values are moved to end. "Insert", SET_ORDER_INSERT, "LRU", SET_ORDER_LRU, "MRU", SET_ORDER_MRU, "Ascending", SET_ORDER_ASC, "Descending", SET_ORDER_DESC ); static void ML_TYPED_FN(ml_value_find_all, MLSetT, ml_value_t *Value, void *Data, ml_value_find_fn RefFn) { if (!RefFn(Data, Value, 1)) return; ML_SET_FOREACH(Value, Iter) ml_value_find_all(Iter->Key, Data, RefFn); } ML_TYPE(MLSetNodeT, (), "set::node"); //!internal ml_value_t *ml_set() { ml_set_t *Set = new(ml_set_t); Set->Type = MLSetMutableT; return (ml_value_t *)Set; } ML_METHOD(MLSetT) { //>set // Returns a new set. //$= set() return ml_set(); } static void set_iterate(ml_iter_state_t *State, ml_value_t *Value); static void set_iter_value(ml_iter_state_t *State, ml_value_t *Value) { Value = ml_deref(Value); if (ml_is_error(Value)) ML_CONTINUE(State->Base.Caller, Value); ml_set_insert(State->Values[0], Value); State->Base.run = (void *)set_iterate; return ml_iter_next((ml_state_t *)State, State->Iter); } static void set_iterate(ml_iter_state_t *State, ml_value_t *Value) { if (ml_is_error(Value)) ML_CONTINUE(State->Base.Caller, Value); if (Value == MLNil) ML_CONTINUE(State->Base.Caller, State->Values[0]); State->Base.run = (void *)set_iter_value; return ml_iter_value((ml_state_t *)State, State->Iter = Value); } ML_METHODVX(MLSetT, MLSequenceT) { //<Sequence //>set // Returns a set of all the values produced by :mini:`Sequence`. //$= set("cake") ml_iter_state_t *State = xnew(ml_iter_state_t, 1, ml_value_t *); State->Base.Caller = Caller; State->Base.run = (void *)set_iterate; State->Base.Context = Caller->Context; State->Values[0] = ml_set(); return ml_iterate((ml_state_t *)State, ml_chained(Count, Args)); } ML_METHODVX("grow", MLSetMutableT, MLSequenceT) { //<Set //<Sequence //>set // Adds of all the values produced by :mini:`Sequence` to :mini:`Set` and returns :mini:`Set`. //$= set("cake"):grow("banana") ml_iter_state_t *State = xnew(ml_iter_state_t, 1, ml_value_t *); State->Base.Caller = Caller; State->Base.run = (void *)set_iterate; State->Base.Context = Caller->Context; State->Values[0] = Args[0]; return ml_iterate((ml_state_t *)State, ml_chained(Count - 1, Args + 1)); } extern ml_value_t *CompareMethod; static inline ml_value_t *ml_set_compare(ml_set_t *Set, ml_value_t **Args) { /*ml_method_cached_t *Cached = Set->Cached; if (Cached) { if (Cached->Types[0] != ml_typeof(Args[0])) Cached = NULL; if (Cached->Types[1] != ml_typeof(Args[1])) Cached = NULL; } if (!Cached || !Cached->Callback) { Cached = ml_method_search_cached(NULL, (ml_method_t *)CompareMethod, 2, Args); if (!Cached) return ml_no_method_error((ml_method_t *)CompareMethod, 2, Args); Set->Cached = Cached; } return ml_simple_call(Cached->Callback, 2, Args);*/ return ml_simple_call(CompareMethod, 2, Args); } static ml_set_node_t *ml_set_find_node(ml_set_t *Set, ml_value_t *Key) { ml_set_node_t *Node = Set->Root; long Hash = ml_typeof(Key)->hash(Key, NULL); ml_method_cached_t *Cached = Set->Cached; if (Cached && Cached->Callback) { if (Cached->Types[0] != ml_typeof(Key)) Cached = NULL; } while (Node) { int Compare; if (Hash < Node->Hash) { Compare = -1; } else if (Hash > Node->Hash) { Compare = 1; } else { ml_value_t *Args[2] = {Key, Node->Key}; ml_value_t *Result = ml_set_compare(Set, Args); if (ml_is_error(Result)) return NULL; Compare = ml_integer_value(Result); } if (!Compare) { return Node; } else { Node = Compare < 0 ? Node->Left : Node->Right; } } return NULL; } ml_value_t *ml_set_search(ml_value_t *Set0, ml_value_t *Key) { ml_set_node_t *Node = ml_set_find_node((ml_set_t *)Set0, Key); return Node ? MLSome : MLNil; } ml_value_t *ml_set_search0(ml_value_t *Set0, ml_value_t *Key) { ml_set_node_t *Node = ml_set_find_node((ml_set_t *)Set0, Key); return Node ? MLSome : NULL; } static int ml_set_balance(ml_set_node_t *Node) { int Delta = 0; if (Node->Left) Delta = Node->Left->Depth; if (Node->Right) Delta -= Node->Right->Depth; return Delta; } static void ml_set_update_depth(ml_set_node_t *Node) { int Depth = 0; if (Node->Left) Depth = Node->Left->Depth; if (Node->Right && Depth < Node->Right->Depth) Depth = Node->Right->Depth; Node->Depth = Depth + 1; } static void ml_set_rotate_left(ml_set_node_t **Slot) { ml_set_node_t *Ch = Slot[0]->Right; Slot[0]->Right = Slot[0]->Right->Left; Ch->Left = Slot[0]; ml_set_update_depth(Slot[0]); Slot[0] = Ch; ml_set_update_depth(Slot[0]); } static void ml_set_rotate_right(ml_set_node_t **Slot) { ml_set_node_t *Ch = Slot[0]->Left; Slot[0]->Left = Slot[0]->Left->Right; Ch->Right = Slot[0]; ml_set_update_depth(Slot[0]); Slot[0] = Ch; ml_set_update_depth(Slot[0]); } static void ml_set_rebalance(ml_set_node_t **Slot) { int Delta = ml_set_balance(Slot[0]); if (Delta == 2) { if (ml_set_balance(Slot[0]->Left) < 0) ml_set_rotate_left(&Slot[0]->Left); ml_set_rotate_right(Slot); } else if (Delta == -2) { if (ml_set_balance(Slot[0]->Right) > 0) ml_set_rotate_right(&Slot[0]->Right); ml_set_rotate_left(Slot); } } static void ml_set_insert_before(ml_set_t *Set, ml_set_node_t *Parent, ml_set_node_t *Node) { Node->Next = Parent; Node->Prev = Parent->Prev; if (Parent->Prev) { Parent->Prev->Next = Node; } else { Set->Head = Node; } Parent->Prev = Node; } static void ml_set_insert_after(ml_set_t *Set, ml_set_node_t *Parent, ml_set_node_t *Node) { Node->Prev = Parent; Node->Next = Parent->Next; if (Parent->Next) { Parent->Next->Prev = Node; } else { Set->Tail = Node; } Parent->Next = Node; } static ml_set_node_t *ml_set_node_child(ml_set_t *Set, ml_set_node_t *Parent, long Hash, ml_value_t *Key) { int Compare; if (Hash < Parent->Hash) { Compare = -1; } else if (Hash > Parent->Hash) { Compare = 1; } else { ml_value_t *Args[2] = {Key, Parent->Key}; ml_value_t *Result = ml_set_compare(Set, Args); Compare = ml_integer_value(Result); } if (!Compare) return Parent; ml_set_node_t **Slot = Compare < 0 ? &Parent->Left : &Parent->Right; ml_set_node_t *Node; if (Slot[0]) { Node = ml_set_node_child(Set, Slot[0], Hash, Key); } else { ++Set->Size; Node = Slot[0] = new(ml_set_node_t); Node->Type = MLSetNodeT; Node->Depth = 1; Node->Hash = Hash; Node->Key = Key; switch (Set->Order) { case SET_ORDER_INSERT: case SET_ORDER_LRU: { ml_set_node_t *Prev = Set->Tail; Prev->Next = Node; Node->Prev = Prev; Set->Tail = Node; break; } case SET_ORDER_MRU: { ml_set_node_t *Next = Set->Head; Next->Prev = Node; Node->Next = Next; Set->Head = Node; break; } case SET_ORDER_ASC: { if (Compare < 0) { ml_set_insert_before(Set, Parent, Node); } else { ml_set_insert_after(Set, Parent, Node); } break; } case SET_ORDER_DESC: { if (Compare > 0) { ml_set_insert_before(Set, Parent, Node); } else { ml_set_insert_after(Set, Parent, Node); } break; } } } ml_set_rebalance(Slot); ml_set_update_depth(Slot[0]); return Node; } static ml_set_node_t *ml_set_node(ml_set_t *Set, long Hash, ml_value_t *Key) { ml_set_node_t *Root = Set->Root; if (Root) return ml_set_node_child(Set, Root, Hash, Key); ++Set->Size; ml_set_node_t *Node = Set->Root = new(ml_set_node_t); Node->Type = MLSetNodeT; Set->Head = Set->Tail = Node; Node->Depth = 1; Node->Hash = Hash; Node->Key = Key; return Node; } ml_set_node_t *ml_set_slot(ml_value_t *Set0, ml_value_t *Key) { ml_set_t *Set = (ml_set_t *)Set0; return ml_set_node(Set, ml_typeof(Key)->hash(Key, NULL), Key); } ml_value_t *ml_set_insert(ml_value_t *Set0, ml_value_t *Key) { ml_set_t *Set = (ml_set_t *)Set0; int Size = Set->Size; ml_set_node(Set, ml_typeof(Key)->hash(Key, NULL), Key); #ifdef ML_GENERICS ml_set_update_generic(Set, Key); #endif return Set->Size == Size ? MLSome : MLNil; } static void ml_set_remove_depth_helper(ml_set_node_t *Node) { if (Node) { ml_set_remove_depth_helper(Node->Right); ml_set_update_depth(Node); } } static ml_value_t *ml_set_remove_internal(ml_set_t *Set, ml_set_node_t **Slot, long Hash, ml_value_t *Key) { if (!Slot[0]) return MLNil; ml_set_node_t *Node = Slot[0]; int Compare; if (Hash < Node->Hash) { Compare = -1; } else if (Hash > Node->Hash) { Compare = 1; } else { ml_value_t *Args[2] = {Key, Node->Key}; ml_value_t *Result = ml_set_compare(Set, Args); Compare = ml_integer_value(Result); } ml_value_t *Removed = MLNil; if (!Compare) { --Set->Size; Removed = MLSome; if (Node->Prev) Node->Prev->Next = Node->Next; else Set->Head = Node->Next; if (Node->Next) Node->Next->Prev = Node->Prev; else Set->Tail = Node->Prev; if (Node->Left && Node->Right) { ml_set_node_t **Y = &Node->Left; while (Y[0]->Right) Y = &Y[0]->Right; ml_set_node_t *Node2 = Y[0]; Y[0] = Node2->Left; Node2->Left = Node->Left; Node2->Right = Node->Right; Slot[0] = Node2; ml_set_remove_depth_helper(Node2->Left); } else if (Node->Left) { Slot[0] = Node->Left; } else if (Node->Right) { Slot[0] = Node->Right; } else { Slot[0] = 0; } } else { Removed = ml_set_remove_internal(Set, Compare < 0 ? &Node->Left : &Node->Right, Hash, Key); } if (Slot[0]) { ml_set_update_depth(Slot[0]); ml_set_rebalance(Slot); } return Removed; } ml_value_t *ml_set_delete(ml_value_t *Set0, ml_value_t *Key) { ml_set_t *Set = (ml_set_t *)Set0; return ml_set_remove_internal(Set, &Set->Root, ml_typeof(Key)->hash(Key, NULL), Key); } int ml_set_foreach(ml_value_t *Value, void *Data, int (*callback)(ml_value_t *, void *)) { ml_set_t *Set = (ml_set_t *)Value; for (ml_set_node_t *Node = Set->Head; Node; Node = Node->Next) { if (callback(Node->Key, Data)) return 1; } return 0; } ML_METHOD("precount", MLSetT) { //<Set //>integer // Returns the number of values in :mini:`Set`. //$= set(["A", "B", "C"]):count ml_set_t *Set = (ml_set_t *)Args[0]; return ml_integer(Set->Size); } ML_METHOD("size", MLSetT) { //<Set //>integer // Returns the number of values in :mini:`Set`. //$= set(["A", "B", "C"]):size ml_set_t *Set = (ml_set_t *)Args[0]; return ml_integer(Set->Size); } ML_METHOD("count", MLSetT) { //<Set //>integer // Returns the number of values in :mini:`Set`. //$= set(["A", "B", "C"]):count ml_set_t *Set = (ml_set_t *)Args[0]; return ml_integer(Set->Size); } ML_METHOD("first", MLSetT) { //<Set // Returns the first value in :mini:`Set` or :mini:`nil` if :mini:`Set` is empty. ml_set_t *Set = (ml_set_t *)Args[0]; return Set->Head ? Set->Head->Key : MLNil; } ML_METHOD("last", MLSetT) { //<Set // Returns the last value in :mini:`Set` or :mini:`nil` if :mini:`Set` is empty. ml_set_t *Set = (ml_set_t *)Args[0]; return Set->Tail ? Set->Tail->Key : MLNil; } ML_METHOD("order", MLSetT) { //<Set //>set::order // Returns the current ordering of :mini:`Set`. ml_set_t *Set = (ml_set_t *)Args[0]; return ml_enum_value(MLSetOrderT, Set->Order); } ML_METHOD("order", MLSetMutableT, MLSetOrderT) { //<Set //<Order //>set // Sets the ordering ml_set_t *Set = (ml_set_t *)Args[0]; Set->Order = ml_enum_value_value(Args[1]); return (ml_value_t *)Set; } static void ml_set_move_node_head(ml_set_t *Set, ml_set_node_t *Node) { ml_set_node_t *Prev = Node->Prev; if (Prev) { ml_set_node_t *Next = Node->Next; Prev->Next = Next; if (Next) { Next->Prev = Prev; } else { Set->Tail = Prev; } Node->Next = Set->Head; Node->Prev = NULL; Set->Head->Prev = Node; Set->Head = Node; } } static void ml_set_move_node_tail(ml_set_t *Set, ml_set_node_t *Node) { ml_set_node_t *Next = Node->Next; if (Next) { ml_set_node_t *Prev = Node->Prev; Next->Prev = Prev; if (Prev) { Prev->Next = Next; } else { Set->Head = Next; } Node->Prev = Set->Tail; Node->Next = NULL; Set->Tail->Next = Node; Set->Tail = Node; } } ML_METHOD("[]", MLSetT, MLAnyT) { //<Set //<Value //>some|nil // Returns :mini:`Value` if it is in :mini:`Set`, otherwise returns :mini:`nil`.. //$- let S := set(["A", "B", "C"]) //$= S["A"] //$= S["D"] //$= S ml_set_t *Set = (ml_set_t *)Args[0]; ml_set_node_t *Node = ml_set_find_node(Set, Args[1]); if (!Node) return MLNil; if (Set->Order == SET_ORDER_LRU) { ml_set_move_node_tail(Set, Node); } else if (Set->Order == SET_ORDER_MRU) { ml_set_move_node_head(Set, Node); } return Args[1]; } ML_METHOD("in", MLAnyT, MLSetT) { //<Value //<Set //>any|nil // Returns :mini:`Key` if it is in :mini:`Map`, otherwise return :mini:`nil`. //$- let S := set(["A", "B", "C"]) //$= "A" in S //$= "D" in S ml_set_t *Set = (ml_set_t *)Args[1]; return ml_set_find_node(Set, Args[0]) ? Args[0] : MLNil; } ML_METHOD("empty", MLSetMutableT) { //<Set //>set // Deletes all values from :mini:`Set` and returns it. //$= let S := set(["A", "B", "C"]) //$= S:empty ml_set_t *Set = (ml_set_t *)Args[0]; Set->Root = Set->Head = Set->Tail = NULL; Set->Size = 0; #ifdef ML_GENERICS Set->Type = MLSetMutableT; #endif return (ml_value_t *)Set; } ML_METHOD("pop", MLSetMutableT) { //<Set //>any|nil // Deletes the first value from :mini:`Set` according to its iteration order. Returns the deleted value, or :mini:`nil` if :mini:`Set` is empty. //$- :> Insertion order (default) //$= let S1 := set("cake") //$= S1:pop //$= S1 //$- //$- :> LRU order //$= let S2 := set("cake"):order(set::order::LRU) //$- S2["a"]; S2["e"]; S2["c"]; S2["k"] //$= S2:pop //$= S2 //$- //$- :> MRU order //$= let S3 := set("cake"):order(set::order::MRU) //$- S3["a"]; S3["e"]; S3["c"]; S3["k"] //$= S3:pop //$= S3 ml_set_t *Set = (ml_set_t *)Args[0]; ml_set_node_t *Node = Set->Head; if (!Node) return MLNil; ml_set_delete(Args[0], Node->Key); return Node->Key; } ML_METHOD("pull", MLSetMutableT) { //<Set //>any|nil // Deletes the last value from :mini:`Set` according to its iteration order. Returns the deleted value, or :mini:`nil` if :mini:`Set` is empty. //$- :> Insertion order (default) //$= let S1 := set("cake") //$= S1:pull //$= S1 //$- //$- :> LRU order //$= let S2 := set("cake"):order(set::order::LRU) //$- S2["a"]; S2["e"]; S2["c"]; S2["k"] //$= S2:pull //$= S2 //$- //$- :> MRU order //$= let S3 := set("cake"):order(set::order::MRU) //$- S3["a"]; S3["e"]; S3["c"]; S3["k"] //$= S3:pull //$= S3 ml_set_t *Set = (ml_set_t *)Args[0]; ml_set_node_t *Node = Set->Tail; if (!Node) return MLNil; ml_set_delete(Args[0], Node->Key); return Node->Key; } ML_METHOD("insert", MLSetMutableT, MLAnyT) { //<Set //<Value //>some|nil // Inserts :mini:`Value` into :mini:`Set`. // Returns the previous value associated with :mini:`Key` if any, otherwise :mini:`nil`. //$- let S := set(["A", "B", "C"]) //$= S:insert("A") //$= S:insert("D") //$= S return ml_set_insert(Args[0], Args[1]); } ML_METHODV("push", MLSetMutableT, MLAnyT) { //<Set //<Value //>set // Inserts each :mini:`Value` into :mini:`Set` at the start. //$- let S := set(["A", "B", "C"]) //$= S:push("A") //$= S:push("D") //$= S:push("E", "B") //$= S ml_set_t *Set = (ml_set_t *)Args[0]; for (int I = 1; I < Count; ++I) { ml_value_t *Key = Args[I]; ml_set_node_t *Node = ml_set_node(Set, ml_typeof(Key)->hash(Key, NULL), Key); ml_set_move_node_head(Set, Node); #ifdef ML_GENERICS ml_set_update_generic(Set, Key); #endif } return (ml_value_t *)Set; } ML_METHODV("put", MLSetMutableT, MLAnyT) { //<Set //<Value //>set // Inserts each :mini:`Value` into :mini:`Set` at the end. //$- let S := set(["A", "B", "C"]) //$= S:put("A") //$= S:put("D") //$= S:put("E", "B") //$= S ml_set_t *Set = (ml_set_t *)Args[0]; for (int I = 1; I < Count; ++I) { ml_value_t *Key = Args[I]; ml_set_node_t *Node = ml_set_node(Set, ml_typeof(Key)->hash(Key, NULL), Key); ml_set_move_node_tail(Set, Node); #ifdef ML_GENERICS ml_set_update_generic(Set, Key); #endif } return (ml_value_t *)Set; } ML_METHOD("delete", MLSetMutableT, MLAnyT) { //<Set //<Value //>some|nil // Removes :mini:`Value` from :mini:`Set` and returns it if found, otherwise :mini:`nil`. //$- let S := set(["A", "B", "C"]) //$= S:delete("A") //$= S:delete("D") //$= S ml_value_t *Set = (ml_value_t *)Args[0]; ml_value_t *Key = Args[1]; return ml_set_delete(Set, Key); } ML_METHOD("missing", MLSetMutableT, MLAnyT) { //<Set //<Value //>some|nil // If :mini:`Value` is present in :mini:`Set` then returns :mini:`nil`. Otherwise inserts :mini:`Value` into :mini:`Set` and returns :mini:`some`. //$- let S := set(["A", "B", "C"]) //$= S:missing("A") //$= S:missing("D") //$= S ml_set_t *Set = (ml_set_t *)Args[0]; ml_value_t *Key = Args[1]; int Size = Set->Size; ml_set_node(Set, ml_typeof(Key)->hash(Key, NULL), Key); return Set->Size == Size ? MLNil : MLSome; } typedef struct { ml_type_t *Type; ml_set_node_t *Node; } ml_set_from_t; ML_TYPE(MLSetFromT, (MLSequenceT), "set::from"); //!internal static void ML_TYPED_FN(ml_iterate, MLSetFromT, ml_state_t *Caller, ml_set_from_t *From) { ML_RETURN(From->Node); } ML_METHOD("from", MLSetT, MLAnyT) { //<Set //<Value //>sequence|nil // Returns the subset of :mini:`Set` after :mini:`Value` as a sequence. //$- let S := set(["A", "B", "C", "D", "E"]) //$= set(S:from("C")) //$= set(S:from("F")) ml_set_t *Set = (ml_set_t *)Args[0]; ml_value_t *Key = Args[1]; ml_set_node_t *Node = ml_set_find_node(Set, Key); if (!Node) return MLNil; ml_set_from_t *From = new(ml_set_from_t); From->Type = MLSetFromT; From->Node = Node; return (ml_value_t *)From; } ML_METHOD("append", MLStringBufferT, MLSetT) { //<Buffer //<Set // Appends a representation of :mini:`Set` to :mini:`Buffer`. ml_stringbuffer_t *Buffer = (ml_stringbuffer_t *)Args[0]; ml_stringbuffer_put(Buffer, '{'); ml_set_t *Set = (ml_set_t *)Args[1]; ml_set_node_t *Node = Set->Head; if (Node) { ml_stringbuffer_simple_append(Buffer, Node->Key); while ((Node = Node->Next)) { ml_stringbuffer_write(Buffer, ", ", 2); ml_stringbuffer_simple_append(Buffer, Node->Key); } } ml_stringbuffer_put(Buffer, '}'); return MLSome; } typedef struct ml_set_stringer_t { const char *Seperator; ml_stringbuffer_t *Buffer; int SeperatorLength, First; ml_value_t *Error; } ml_set_stringer_t; static int ml_set_stringer(ml_value_t *Key, ml_set_stringer_t *Stringer) { if (Stringer->First) { Stringer->First = 0; } else { ml_stringbuffer_write(Stringer->Buffer, Stringer->Seperator, Stringer->SeperatorLength); } Stringer->Error = ml_stringbuffer_simple_append(Stringer->Buffer, Key); if (ml_is_error(Stringer->Error)) return 1; return 0; } ML_METHOD("append", MLStringBufferT, MLSetT, MLStringT) { //<Buffer //<Set //<Sep // Appends the values of :mini:`Set` to :mini:`Buffer` with :mini:`Sep` between values. ml_set_stringer_t Stringer[1] = {{ ml_string_value(Args[2]), (ml_stringbuffer_t *)Args[0], ml_string_length(Args[2]), 1 }}; if (ml_set_foreach(Args[1], Stringer, (void *)ml_set_stringer)) return Stringer->Error; return MLSome; } static void ML_TYPED_FN(ml_iter_next, MLSetNodeT, ml_state_t *Caller, ml_set_node_t *Node) { ML_RETURN((ml_value_t *)Node->Next ?: MLNil); } static void ML_TYPED_FN(ml_iter_key, MLSetNodeT, ml_state_t *Caller, ml_set_node_t *Node) { ML_RETURN(Node->Key); } static void ML_TYPED_FN(ml_iter_value, MLSetNodeT, ml_state_t *Caller, ml_set_node_t *Node) { ML_RETURN(Node->Key); } static void ML_TYPED_FN(ml_iterate, MLSetT, ml_state_t *Caller, ml_set_t *Set) { ML_RETURN((ml_value_t *)Set->Head ?: MLNil); } ML_METHOD("+", MLSetT, MLSetT) { //<Set/1 //<Set/2 //>set // Returns a new set combining the values of :mini:`Set/1` and :mini:`Set/2`. //$= let A := set("banana") //$= let B := set("bread") //$= A + B ml_value_t *Set = ml_set(); ML_SET_FOREACH(Args[0], Node) ml_set_insert(Set, Node->Key); ML_SET_FOREACH(Args[1], Node) ml_set_insert(Set, Node->Key); return Set; } ML_METHOD("\\/", MLSetT, MLSetT) { //<Set/1 //<Set/2 //>set // Returns a new set combining the values of :mini:`Set/1` and :mini:`Set/2`. //$= let A := set("banana") //$= let B := set("bread") //$= A \/ B ml_value_t *Set = ml_set(); ML_SET_FOREACH(Args[0], Node) ml_set_insert(Set, Node->Key); ML_SET_FOREACH(Args[1], Node) ml_set_insert(Set, Node->Key); return Set; } ML_METHOD("*", MLSetT, MLSetT) { //<Set/1 //<Set/2 //>set // Returns a new set containing the values of :mini:`Set/1` which are also in :mini:`Set/2`. //$= let A := set("banana") //$= let B := set("bread") //$= A * B ml_value_t *Set = ml_set(); ML_SET_FOREACH(Args[1], Node) { if (ml_set_search0(Args[0], Node->Key)) ml_set_insert(Set, Node->Key); } return Set; } ML_METHOD("/\\", MLSetT, MLSetT) { //<Set/1 //<Set/2 //>set // Returns a new set containing the values of :mini:`Set/1` which are also in :mini:`Set/2`. //$= let A := set("banana") //$= let B := set("bread") //$= A /\ B ml_value_t *Set = ml_set(); ML_SET_FOREACH(Args[1], Node) { if (ml_set_search0(Args[0], Node->Key)) ml_set_insert(Set, Node->Key); } return Set; } ML_METHOD("/", MLSetT, MLSetT) { //<Set/1 //<Set/2 //>set // Returns a new set containing the values of :mini:`Set/1` which are not in :mini:`Set/2`. //$= let A := set("banana") //$= let B := set("bread") //$= A / B ml_value_t *Set = ml_set(); ML_SET_FOREACH(Args[0], Node) { if (!ml_set_search0(Args[1], Node->Key)) ml_set_insert(Set, Node->Key); } return Set; } ML_METHOD("><", MLSetT, MLSetT) { //<Set/1 //<Set/2 //>set // Returns a new set containing the values of :mini:`Set/1` and :mini:`Set/2` that are not in both. //$= let A := set("banana") //$= let B := set("bread") //$= A >< B ml_value_t *Set = ml_set(); ML_SET_FOREACH(Args[0], Node) { if (!ml_set_search0(Args[1], Node->Key)) ml_set_insert(Set, Node->Key); } ML_SET_FOREACH(Args[1], Node) { if (!ml_set_search0(Args[0], Node->Key)) ml_set_insert(Set, Node->Key); } return Set; } ML_METHOD("<=>", MLSetT, MLSetT) { //<Set/1 //<Set/2 //>set // Returns a tuple of :mini:`(Set/1 / Set/2, Set/1 * Set/2, Set/2 / Set/1)`. //$= let A := set("banana") //$= let B := set("bread") //$= A <=> B ml_value_t *Set1 = ml_set(), *Set2 = ml_set(), *Set3 = ml_set(); ML_SET_FOREACH(Args[0], Node) { if (!ml_set_search0(Args[1], Node->Key)) { ml_set_insert(Set1, Node->Key); } else { ml_set_insert(Set2, Node->Key); } } ML_SET_FOREACH(Args[1], Node) { if (!ml_set_search0(Args[0], Node->Key)) ml_set_insert(Set3, Node->Key); } return ml_tuplev(3, Set1, Set2, Set3); } typedef struct { ml_state_t Base; ml_set_t *Set; ml_value_t *Compare; ml_value_t *Args[2]; ml_set_node_t *Head, *Tail; ml_set_node_t *P, *Q; int Count, Size; int InSize, NMerges; int PSize, QSize; } ml_set_sort_state_t; static void ml_set_sort_state_run(ml_set_sort_state_t *State, ml_value_t *Result) { if (Result) goto resume; for (;;) { State->P = State->Head; State->Tail = State->Head = NULL; State->NMerges = 0; while (State->P) { State->NMerges++; State->Q = State->P; State->PSize = 0; for (int I = 0; I < State->InSize; I++) { State->PSize++; State->Q = State->Q->Next; if (!State->Q) break; } State->QSize = State->InSize; while (State->PSize > 0 || (State->QSize > 0 && State->Q)) { ml_set_node_t *E; if (State->PSize == 0) { E = State->Q; State->Q = State->Q->Next; State->QSize--; } else if (State->QSize == 0 || !State->Q) { E = State->P; State->P = State->P->Next; State->PSize--; } else { State->Args[0] = State->P->Key; State->Args[1] = State->Q->Key; return ml_call((ml_state_t *)State, State->Compare, State->Count, State->Args); resume: if (ml_is_error(Result)) { ml_set_node_t *Node = State->P, *Next; if (State->Tail) { State->Tail->Next = Node; } else { State->Head = Node; } Node->Prev = State->Tail; for (int Size = State->PSize; --Size > 0;) { Next = Node->Next; Next->Prev = Node; Node = Next; } Next = State->Q; Node->Next = Next; Next->Prev = Node; Node = Next; while (Node->Next) { Next = Node->Next; Next->Prev = Node; Node = Next; } Node->Next = NULL; State->Tail = Node; goto finished; } else if (Result == MLNil) { E = State->Q; State->Q = State->Q->Next; State->QSize--; } else { E = State->P; State->P = State->P->Next; State->PSize--; } } if (State->Tail) { State->Tail->Next = E; } else { State->Head = E; } E->Prev = State->Tail; State->Tail = E; } State->P = State->Q; } State->Tail->Next = 0; if (State->NMerges <= 1) { Result = (ml_value_t *)State->Set; goto finished; } State->InSize *= 2; } finished: State->Set->Head = State->Head; State->Set->Tail = State->Tail; State->Set->Size = State->Size; ML_CONTINUE(State->Base.Caller, Result); } extern ml_value_t *LessMethod; ML_METHODX("sort", MLSetMutableT) { //<Set //>Set // Sorts the values (changes the iteration order) of :mini:`Set` using :mini:`Value/i < Value/j` and returns :mini:`Set`. //$= let S := set("cake") //$= S:sort if (!ml_set_size(Args[0])) ML_RETURN(Args[0]); ml_set_sort_state_t *State = new(ml_set_sort_state_t); State->Base.Caller = Caller; State->Base.Context = Caller->Context; State->Base.run = (ml_state_fn)ml_set_sort_state_run; ml_set_t *Set = (ml_set_t *)Args[0]; State->Set = Set; State->Count = 2; State->Compare = LessMethod; State->Head = State->Set->Head; State->Size = Set->Size; State->InSize = 1; // TODO: Improve ml_set_sort_state_run so that List is still valid during sort Set->Head = Set->Tail = NULL; Set->Size = 0; return ml_set_sort_state_run(State, NULL); } ML_METHODX("sort", MLSetMutableT, MLFunctionT) { //<Set //<Cmp //>Set // Sorts the values (changes the iteration order) of :mini:`Set` using :mini:`Cmp(Value/i, Value/j)` and returns :mini:`Set` //$= let S := set("cake") //$= S:sort(>) if (!ml_set_size(Args[0])) ML_RETURN(Args[0]); ml_set_sort_state_t *State = new(ml_set_sort_state_t); State->Base.Caller = Caller; State->Base.Context = Caller->Context; State->Base.run = (ml_state_fn)ml_set_sort_state_run; ml_set_t *Set = (ml_set_t *)Args[0]; State->Set = Set; State->Count = 2; State->Compare = Args[1]; State->Head = State->Set->Head; State->Size = Set->Size; State->InSize = 1; // TODO: Improve ml_set_sort_state_run so that List is still valid during sort Set->Head = Set->Tail = NULL; Set->Size = 0; return ml_set_sort_state_run(State, NULL); } ML_METHOD("reverse", MLSetMutableT) { //<Set //>set // Reverses the iteration order of :mini:`Set` in-place and returns it. //$= let S := set("cake") //$= S:reverse ml_set_t *Set = (ml_set_t *)Args[0]; ml_set_node_t *Prev = Set->Head; if (!Prev) return (ml_value_t *)Set; Set->Tail = Prev; ml_set_node_t *Node = Prev->Next; Prev->Next = NULL; while (Node) { ml_set_node_t *Next = Node->Next; Node->Next = Prev; Prev->Prev = Node; Prev = Node; Node = Next; } Prev->Prev = NULL; Set->Head = Prev; return (ml_value_t *)Set; } ML_METHOD("random", MLSetT) { //<List //>any // Returns a random (assignable) node from :mini:`Set`. //$= let S := set("cake") //$= S:random //$= S:random ml_set_t *Set = (ml_set_t *)Args[0]; int Limit = Set->Size; if (Limit <= 0) return MLNil; int Divisor = RAND_MAX / Limit; int Random; do Random = random() / Divisor; while (Random >= Limit); ml_set_node_t *Node = Set->Head; while (--Random >= 0) Node = Node->Next; return Node->Key; } typedef struct { ml_state_t Base; ml_value_t *Visitor, *Dest; ml_set_node_t *Node; ml_value_t *Args[1]; } ml_set_visit_t; static void ml_set_visit_run(ml_set_visit_t *State, ml_value_t *Value) { ml_state_t *Caller = State->Base.Caller; if (ml_is_error(Value)) ML_RETURN(Value); ml_set_node_t *Node = State->Node->Next; if (!Node) ML_RETURN(MLNil); State->Node = Node; State->Args[0] = Node->Key; return ml_call(State, State->Visitor, 1, State->Args); } ML_METHODX("visit", MLVisitorT, MLSetT) { //<Visitor //<Set //>set // Returns a new set contains copies of the elements of :mini:`Set` created using :mini:`Copy`. ml_visitor_t *Visitor = (ml_visitor_t *)Args[0]; ml_set_node_t *Node = ((ml_set_t *)Args[1])->Head; if (!Node) ML_RETURN(MLNil); ml_set_visit_t *State = new(ml_set_visit_t); State->Base.Caller = Caller; State->Base.Context = Caller->Context; State->Base.run = (ml_state_fn)ml_set_visit_run; State->Visitor = (ml_value_t *)Visitor; State->Node = Node; State->Args[0] = Node->Key; return ml_call(State, (ml_value_t *)Visitor, 1, State->Args); } static void ml_set_copy_run(ml_set_visit_t *State, ml_value_t *Value) { ml_state_t *Caller = State->Base.Caller; if (ml_is_error(Value)) ML_RETURN(Value); ml_set_insert(State->Dest, Value); ml_set_node_t *Node = State->Node->Next; if (!Node) ML_RETURN(State->Dest); State->Node = Node; State->Args[0] = Node->Key; return ml_call(State, State->Visitor, 1, State->Args); } ML_METHODX("copy", MLVisitorT, MLSetT) { //<Visitor //<Set //>set // Returns a new set contains copies of the elements of :mini:`Set` created using :mini:`Copy`. ml_visitor_t *Visitor = (ml_visitor_t *)Args[0]; ml_value_t *Dest = ml_set(); inthash_insert(Visitor->Cache, (uintptr_t)Args[1], Dest); ml_set_node_t *Node = ((ml_set_t *)Args[1])->Head; if (!Node) ML_RETURN(Dest); ml_set_visit_t *State = new(ml_set_visit_t); State->Base.Caller = Caller; State->Base.Context = Caller->Context; State->Base.run = (ml_state_fn)ml_set_copy_run; State->Visitor = (ml_value_t *)Visitor; State->Dest = Dest; State->Node = Node; State->Args[0] = Node->Key; return ml_call(State, (ml_value_t *)Visitor, 1, State->Args); } static void ml_set_const_run(ml_set_visit_t *State, ml_value_t *Value) { ml_state_t *Caller = State->Base.Caller; if (ml_is_error(Value)) ML_RETURN(Value); ml_set_insert(State->Dest, Value); ml_set_node_t *Node = State->Node->Next; if (!Node) { #ifdef ML_GENERICS if (State->Dest->Type->Type == MLTypeGenericT) { ml_type_t *TArgs[2]; ml_find_generic_parent(State->Dest->Type, MLSetMutableT, 2, TArgs); TArgs[0] = MLSetT; State->Dest->Type = ml_generic_type(2, TArgs); } else { #endif State->Dest->Type = MLSetT; #ifdef ML_GENERICS } #endif ML_RETURN(State->Dest); } State->Node = Node; State->Args[0] = Node->Key; return ml_call(State, State->Visitor, 1, State->Args); } ML_METHODX("const", MLVisitorT, MLSetT) { //<Visitor //<Set //>set // Returns a new set contains copies of the elements of :mini:`Set` created using :mini:`Visitor`. ml_visitor_t *Visitor = (ml_visitor_t *)Args[0]; ml_value_t *Dest = ml_set(); inthash_insert(Visitor->Cache, (uintptr_t)Args[1], Dest); ml_set_node_t *Node = ((ml_set_t *)Args[1])->Head; if (!Node) ML_RETURN(Dest); ml_set_visit_t *State = new(ml_set_visit_t); State->Base.Caller = Caller; State->Base.Context = Caller->Context; State->Base.run = (ml_state_fn)ml_set_const_run; State->Visitor = (ml_value_t *)Visitor; State->Dest = Dest; State->Node = Node; State->Args[0] = Node->Key; return ml_call(State, (ml_value_t *)Visitor, 1, State->Args); } #ifdef ML_CBOR #include "ml_cbor.h" static void ML_TYPED_FN(ml_cbor_write, MLSetT, ml_cbor_writer_t *Writer, ml_set_t *Set) { ml_cbor_write_tag(Writer, 258); ml_cbor_write_array(Writer, Set->Size); ML_SET_FOREACH(Set, Iter) ml_cbor_write(Writer, Iter->Key); } static ml_value_t *ml_cbor_read_set(ml_cbor_reader_t *Reader, ml_value_t *Value) { if (!ml_is(Value, MLListT)) return ml_error("TagError", "Set requires list"); ml_value_t *Set = ml_set(); ML_SET_FOREACH(Value, Iter) ml_set_insert(Set, Iter->Key); return Set; } #endif void ml_set_init() { #include "ml_set_init.c" stringmap_insert(MLSetT->Exports, "order", MLSetOrderT); stringmap_insert(MLSetT->Exports, "mutable", MLSetMutableT); #ifdef ML_GENERICS ml_type_add_rule(MLSetT, MLSequenceT, ML_TYPE_ARG(1), ML_TYPE_ARG(1), NULL); #ifdef ML_MUTABLES ml_type_add_rule(MLSetMutableT, MLSetT, ML_TYPE_ARG(1), NULL); #endif #endif #ifdef ML_CBOR ml_cbor_default_tag(258, ml_cbor_read_set); #endif }
2.484375
2
2024-11-18T22:25:11.119406+00:00
2017-05-11T15:19:14
e992af7b3a7819411bc4e7f3bbb935e6ad475410
{ "blob_id": "e992af7b3a7819411bc4e7f3bbb935e6ad475410", "branch_name": "refs/heads/master", "committer_date": "2017-05-11T15:19:14", "content_id": "8cc1b6b5e4b1dd60cb6c653a6e8575f7e833bff7", "detected_licenses": [ "MIT" ], "directory_id": "18634178d433cba090737a3ba66c8f2d024158ae", "extension": "h", "filename": "Timer.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": 6941, "license": "MIT", "license_type": "permissive", "path": "/include/Timer.h", "provenance": "stackv2-0115.json.gz:110776", "repo_name": "ajdittmann/Daino", "revision_date": "2017-05-11T15:19:14", "revision_id": "db88f5738aba76fa8a28d7672450e0c5c832b3de", "snapshot_id": "b46b1efcc624182af57f74c5e38e1dafc540216f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ajdittmann/Daino/db88f5738aba76fa8a28d7672450e0c5c832b3de/include/Timer.h", "visit_date": "2020-09-28T23:54:23.992162" }
stackv2
#ifndef __TIMER_H__ #define __TIMER_H__ #include "sys/time.h" void Aux_Error( const char *File, const int Line, const char *Func, const char *Format, ... ); void Aux_Message( FILE *Type, const char *Format, ... ); //------------------------------------------------------------------------------------------------------- // Structure : Timer_t // Description : Data structure for measuring the elapsed time // // Data Member : Status : The status of each timer : (false / true) <--> (stop / ticking) // Time : The variable recording the elapsed time (in microseconds) // WorkingID : The currently working ID of the array "Time" // NTimer : The number of timers // // Method : Timer_t : Constructor // ~Timer_t : Destructor // Start : Start timing // Stop : Stop timing // GetValue : Get the elapsed time recorded in timer (in seconds) // Reset : Reset timer //------------------------------------------------------------------------------------------------------- struct Timer_t { // data members // =================================================================================== bool *Status; ulong *Time; uint WorkingID; uint NTimer; //=================================================================================== // Constructor : Timer_t // Description : Constructor of the structure "Timer_t" // // Note : Allocate and initialize all data member // a. The WorkingID is initialized as "0" // b. The Status is initialized as "false" // c. The timer is initialized as "0" // // Parameter : N : The number of timers to be allocated //=================================================================================== Timer_t( const uint N ) { NTimer = N; WorkingID = 0; Time = new ulong [NTimer]; Status = new bool [NTimer]; for (uint t=0; t<NTimer; t++) { Time [t] = 0; Status[t] = false; } } //=================================================================================== // Destructor : ~Timer_t // Description : Destructor of the structure "Timer_t" // // Note : Release memory //=================================================================================== ~Timer_t() { delete [] Time; delete [] Status; } //=================================================================================== // Method : Start // Description : Start timing and set status as "true" //=================================================================================== void Start() { # ifdef DAINO_DEBUG if ( WorkingID >= NTimer ) Aux_Error( ERROR_INFO, "timer is exhausted !!\n" ); if ( Status[WorkingID] ) Aux_Message( stderr, "WARNING : the timer has already been started (WorkingID = %u) !!\n", WorkingID ); # endif timeval tv; gettimeofday( &tv, NULL ); Time[WorkingID] = tv.tv_sec*1000000 + tv.tv_usec - Time[WorkingID]; Status[WorkingID] = true; } //=================================================================================== // Method : Stop // Description : Stop timing and set status as "false" // // Note : Increase the WorkingID if the input parameter "Next == true" // // Parameter : Next : (true / false) --> (increase / not increase) the WorkingID //=================================================================================== void Stop( const bool Next ) { # ifdef DAINO_DEBUG if ( WorkingID >= NTimer ) Aux_Error( ERROR_INFO, "timer is exhausted !!\n" ); if ( !Status[WorkingID] ) Aux_Message( stderr, "WARNING : the timer has NOT been started (WorkingID = %u) !!\n", WorkingID ); # endif timeval tv; gettimeofday( &tv, NULL ); Time[WorkingID] = tv.tv_sec*1000000 + tv.tv_usec - Time[WorkingID]; Status[WorkingID] = false; if ( Next ) WorkingID++; } //=================================================================================== // Method : GetValue // Description : Get the elapsed time (in seconds) recorded in the timer "TargetID" // // Parameter : TargetID : The ID of the targeted timer //=================================================================================== float GetValue( const uint TargetID ) { # ifdef DAINO_DEBUG if ( TargetID >= NTimer ) Aux_Error( ERROR_INFO, "the queried timer does NOT exist (TargetID = %u, NTimer = %u) !!\n", TargetID, NTimer ); if ( Status[TargetID] ) Aux_Message( stderr, "WARNING : the timer is still ticking (TargetID = %u) !!\n", TargetID ); # endif return Time[TargetID]*1.e-6f; } //=================================================================================== // Method : Reset // Description : Reset all timers and set WorkingID as "0" // // Note : All timing information previously recorded will be lost after // invoking this function //=================================================================================== void Reset() { for (uint t=0; t<NTimer; t++) { # ifdef DAINO_DEBUG if ( Status[t] ) Aux_Message( stderr, "WARNING : resetting a using timer (WorkingID = %u) !!\n", t ); # endif Time[t] = 0; WorkingID = 0; } } }; // struct Timer_t // macro for timing functions #ifdef TIMING # define TIMING_FUNC( call, timer, next ) \ { \ if ( OPT__TIMING_BARRIER ) MPI_Barrier( MPI_COMM_WORLD ); \ timer->Start(); \ call; \ if ( OPT__TIMING_BARRIER ) MPI_Barrier( MPI_COMM_WORLD ); \ timer->Stop( next ); \ } #else # define TIMING_FUNC( call, timer, next ) call #endif // macro for timing solvers #if ( defined TIMING_SOLVER && defined TIMING ) # ifdef GPU # define GPU_SYNC() CUAPI_Synchronize() # else # define GPU_SYNC() # endif # define TIMING_SYNC( call, timer ) \ { \ timer->Start(); \ call; \ GPU_SYNC(); \ timer->Stop( false ); \ } #else # define TIMING_SYNC( call, timer ) call #endif #endif // #ifndef __TIMER_H__
2.765625
3
2024-11-18T22:25:11.201387+00:00
2021-07-18T10:48:14
fd0f17a4ac550d2f50db72f66c85982aad325a04
{ "blob_id": "fd0f17a4ac550d2f50db72f66c85982aad325a04", "branch_name": "refs/heads/master", "committer_date": "2021-07-18T10:48:14", "content_id": "3c0293c33d570bd02d400bbea7fb40b93e56a384", "detected_licenses": [ "MIT" ], "directory_id": "772a6d9500c9f5b46485b3412647d24c09c90bfe", "extension": "c", "filename": "tcp-client.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": 4039, "license": "MIT", "license_type": "permissive", "path": "/tcp_client/tcp-client.c", "provenance": "stackv2-0115.json.gz:110904", "repo_name": "ww117w/code-snippets", "revision_date": "2021-07-18T10:48:14", "revision_id": "b263a1371a7e8cf2d914b756d62ff75d731d069f", "snapshot_id": "0f9316774a7de0313265af883c2f51e477d751c7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ww117w/code-snippets/b263a1371a7e8cf2d914b756d62ff75d731d069f/tcp_client/tcp-client.c", "visit_date": "2023-06-26T00:13:36.445232" }
stackv2
#include <stdio.h> /* for printf() and fprintf() */ #include <sys/socket.h> /* for omnirob_socket(), connect(), send(), and recv() */ #include <arpa/inet.h> /* for omnirob_sockaddr_in and inet_addr() */ #include <stdlib.h> /* for atoi() and exit() */ #include <string.h> /* for memset() */ #include <unistd.h> /* for close() */ #define RCVBUFSIZE 128 /* Size of receive buffer */ #define OMNIROB_IP "192.168.201.50" #define OMNIROB_PORT 56000 int omnirob_sock; /* omnirob_socket descriptor */ struct sockaddr_in omnirob_sock_addr; /* Echo server address */ char *cmd_string; /* String to send to echo server */ char recv_buff[RCVBUFSIZE]; /* Buffer for echo string */ int recv_bytes ; /* Bytes read in single recv() */ int connect_to_omnirob(char* ip, int port) { /* Create a reliable, stream omnirob_socket using TCP */ if ((omnirob_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){ printf("CORE: OMNIROB_IFACE: omnirob_socket creation failed\n"); return -1; } /* Construct the server address structure */ memset(&omnirob_sock_addr, 0, sizeof(omnirob_sock_addr)); /* Zero out structure */ omnirob_sock_addr.sin_family = AF_INET; /* Internet address family */ omnirob_sock_addr.sin_addr.s_addr = inet_addr(ip); /* Server IP address */ omnirob_sock_addr.sin_port = htons(port); /* Server port */ /* Establish the connection to the echo server */ if (connect(omnirob_sock, (struct sockaddr *) &omnirob_sock_addr, sizeof(omnirob_sock_addr)) < 0){ printf("CORE: OMNIROB_IFACE: connection to robot failed\n"); return -2; } return 0; } int read_omnirob_gyro() { const char* cmd = "?Ig\n"; /* Send the interogation command string to the robot */ if (send(omnirob_sock, cmd, strlen(cmd), 0) != strlen(cmd)){ printf("CORE: OMNIROB_IFACE: send failed sent a different number of bytes than expected\n"); return -1; } /* Get the reply */ if ((recv_bytes = recv(omnirob_sock, recv_buff, RCVBUFSIZE - 1, 0)) <= 0){ printf("CORE: OMNIROB_IFACE: receive failed or connection closed prematurely\n"); return -2; } recv_buff[recv_bytes] = '\0'; /* Terminate the string! */ printf("%s", recv_buff); /* Print the echo buffer */ return recv_bytes; } int read_omnirob_compass() { const char* cmd = "?Ic\n"; /* Send the interogation command string to the robot */ if (send(omnirob_sock, cmd, strlen(cmd), 0) != strlen(cmd)){ printf("CORE: OMNIROB_IFACE: send failed sent a different number of bytes than expected\n"); return -1; } /* Get the reply */ if ((recv_bytes = recv(omnirob_sock, recv_buff, RCVBUFSIZE - 1, 0)) <= 0){ printf("CORE: OMNIROB_IFACE: receive failed or connection closed prematurely\n"); return -2; } recv_buff[recv_bytes] = '\0'; /* Terminate the string! */ printf("%s", recv_buff); /* Print the echo buffer */ return recv_bytes; } int read_omnirob_wheels() { const char* cmd = "?Wi\n"; // TODO check what do we need from here /* Send the interogation command string to the robot */ if (send(omnirob_sock, cmd, strlen(cmd), 0) != strlen(cmd)){ printf("CORE: OMNIROB_IFACE: send failed sent a different number of bytes than expected\n"); return -1; } /* Get the reply */ if ((recv_bytes = recv(omnirob_sock, recv_buff, RCVBUFSIZE - 1, 0)) <= 0){ printf("CORE: OMNIROB_IFACE: receive failed or connection closed prematurely\n"); return -2; } recv_buff[recv_bytes] = '\0'; /* Terminate the string! */ printf("%s", recv_buff); /* Print the echo buffer */ return recv_bytes; } int disconnect_from_omnirob() { if(omnirob_sock!=0) close(omnirob_sock); } int main(int argc, char *argv[]) { connect_to_omnirob(OMNIROB_IP, OMNIROB_PORT); read_omnirob_compass(); read_omnirob_gyro(); read_omnirob_wheels(); disconnect_from_omnirob(); return 0; }
2.609375
3
2024-11-18T22:25:12.194881+00:00
2015-03-05T06:06:54
a168286d043967919a2b63de21a7935bdc0c946b
{ "blob_id": "a168286d043967919a2b63de21a7935bdc0c946b", "branch_name": "refs/heads/master", "committer_date": "2015-03-05T06:06:54", "content_id": "86fb036d7add97cd1e077c11856c83d9173e9742", "detected_licenses": [ "MIT" ], "directory_id": "70d0d331cb340fd6b674c575fd45698cda55c9a9", "extension": "h", "filename": "simple_fifo.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 31695092, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5512, "license": "MIT", "license_type": "permissive", "path": "/simple_fifo.h", "provenance": "stackv2-0115.json.gz:111804", "repo_name": "jschmidlapp/c-data-embedded", "revision_date": "2015-03-05T06:06:54", "revision_id": "89f6a1a3296a1b36742c03f20a5e00be146946ea", "snapshot_id": "0018489529ed32634c1b3cf4d980fea35c2324d9", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/jschmidlapp/c-data-embedded/89f6a1a3296a1b36742c03f20a5e00be146946ea/simple_fifo.h", "visit_date": "2021-01-13T16:10:12.864957" }
stackv2
/* * Copyright (c) 2015 Jason Schmidlapp * * 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. */ #ifndef SIMPLE_FIFO_H_ #define SIMPLE_FIFO_H_ /* * A very simple single consumer, single producer FIFO. This should be lockfree, * though two memory barriers may be required (see notes in code below). For * efficiency, two assumptions are made; * * 1. The specified size must be a power of two. * 2. MAXINT-1 must be an even multiple of size. * * The code doesn't do any checking that these conditions are met; bad things will * happen if they aren't. * */ #include <stddef.h> #define SFIFO_Init(name, fifo) SFIFO_Init_##name##_(fifo) #define SFIFO_Get(name, fifo) SFIFO_Get_##name##_(fifo) #define SFIFO_Pop(name, fifo) SFIFO_Pop_##name##_(fifo) #define SFIFO_Push(name, fifo,data) SFIFO_Push_##name##_(fifo, data) #define SFIFO_IsEmpty(name, fifo) SFIFO_IsEmpty_##name##_(fifo) #define SFIFO_IsFull(name, fifo) SFIFO_IsFull_##name##_(fifo) #define SFIFO(name) SFIFO_##name##_t #define MOD2(a,b) (a & (b-1)) #define DECLARE_SIMPLE_FIFO(type, name, size) \ typedef struct { \ size_t produce_count; \ size_t consume_count; \ type buffer[size]; \ } SFIFO_##name##_t; \ \ static inline int SFIFO_Init_##name##_(SFIFO_##name##_t *fifo) \ { \ if (!fifo) \ return -1; \ fifo->produce_count = 0; \ fifo->consume_count = 0; \ return 0; \ } \ \ static inline type SFIFO_Get_##name##_(SFIFO_##name##_t *fifo) \ { \ return fifo->buffer[MOD2(fifo->consume_count, size)]; \ } \ \ static inline type SFIFO_Pop_##name##_(SFIFO_##name##_t *fifo) \ { \ type data = fifo->buffer[MOD2(fifo->consume_count, size)]; \ /* Memory barrier ? */ \ ++fifo->consume_count; \ return data; \ } \ \ static inline void SFIFO_Push_##name##_(SFIFO_##name##_t *fifo, type data) \ { \ fifo->buffer[MOD2(fifo->produce_count, size)] = data; \ /* Memory barrier ? */ \ ++fifo->produce_count; \ } \ \ static inline int SFIFO_IsFull_##name##_(SFIFO_##name##_t *fifo) \ { \ return ((fifo->produce_count - fifo->consume_count) == size); \ } \ \ static inline int SFIFO_IsEmpty_##name##_(SFIFO_##name##_t *fifo) \ { \ return ((fifo->produce_count - fifo->consume_count) == 0); \ } #endif // SIMPLE_FIFO_H_
2.765625
3
2024-11-18T22:25:12.329451+00:00
2019-12-06T07:46:20
a3e3da6be7cfc4fa5583b5c3cafe43943f681af9
{ "blob_id": "a3e3da6be7cfc4fa5583b5c3cafe43943f681af9", "branch_name": "refs/heads/master", "committer_date": "2019-12-06T07:46:20", "content_id": "d3ca4b2e5a3f858f409182d160b475385e87602c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "f874d60e6a9859dcf44f1e4b15b812f99b51ccd5", "extension": "c", "filename": "range.c", "fork_events_count": 0, "gha_created_at": "2019-12-09T16:11:10", "gha_event_created_at": "2019-12-09T16:11:12", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 226912989, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4516, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/runtime/range.c", "provenance": "stackv2-0115.json.gz:112066", "repo_name": "cdosoftei/nanos", "revision_date": "2019-12-06T07:46:20", "revision_id": "e146324e2ffb5c8079aa9c558ecc7323a74642e5", "snapshot_id": "eb84e255215d664c6571b7375d53158fbb8f2396", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/cdosoftei/nanos/e146324e2ffb5c8079aa9c558ecc7323a74642e5/src/runtime/range.c", "visit_date": "2020-09-29T01:22:29.051651" }
stackv2
#include <runtime.h> boolean rangemap_insert(rangemap rm, rmnode n) { list_foreach(&rm->root, l) { rmnode curr = struct_from_list(l, rmnode, l); range i = range_intersection(curr->r, n->r); if (range_span(i)) { /* XXX bark for now until we know we have all potential cases handled... */ msg_warn("attempt to insert %p (%R) but overlap with %p (%R)\n", n, n->r, curr, curr->r); return false; } if (curr->r.start > n->r.start) { list_insert_before(l, &n->l); return true; } } list_insert_before(&rm->root, &n->l); return true; } boolean rangemap_reinsert(rangemap rm, rmnode n, range k) { rangemap_remove_node(rm, n); n->r = k; return rangemap_insert(rm, n); } boolean rangemap_remove_range(rangemap rm, range k) { boolean match = false; list l = list_get_next(&rm->root); while (l && l != &rm->root) { rmnode curr = struct_from_list(l, rmnode, l); list next = list_get_next(l); range i = range_intersection(curr->r, k); /* no intersection */ if (range_empty(i)) { l = next; continue; } match = true; /* complete overlap (delete) */ if (range_equal(curr->r, i)) { rangemap_remove_node(rm, curr); l = next; continue; } /* check for tail trim */ if (curr->r.start < i.start) { /* check for hole */ if (curr->r.end > i.end) { halt("unexpected hole trim: curr %R, key %R\n", curr->r, k); #if 0 /* XXX - I'm not positive that this is the right thing to do; take a closer look at what, if anything, would need benefit from this - plus this would violate any refcounts kept on behalf of opaque value. */ rmnode rn = allocate(rt->h, sizeof(struct rmnode)); rn->r.start = i.end; rn->r.end = curr->r.end; rn->value = curr->value; /* XXX this is perhaps most dubious */ msg_warn("unexpected hole trim: curr %R, key %R\n", curr->r, k); list_insert_after(l, &rn->l); #endif } curr->r.end = i.start; } else if (curr->r.end > i.end) { /* head trim */ curr->r.start = i.end; } l = next; /* valid even if we inserted one */ } return match; } rmnode rangemap_lookup(rangemap rm, u64 point) { list_foreach(&rm->root, i) { rmnode curr = struct_from_list(i, rmnode, l); if (point_in_range(curr->r, point)) return curr; } return INVALID_ADDRESS; } /* return either an exact match or the neighbor to the right */ rmnode rangemap_lookup_at_or_next(rangemap rm, u64 point) { list_foreach(&rm->root, i) { rmnode curr = struct_from_list(i, rmnode, l); if (point_in_range(curr->r, point) || curr->r.start > point) return curr; } return INVALID_ADDRESS; } /* can be called with rh == 0 for true/false match */ boolean rangemap_range_lookup(rangemap rm, range q, rmnode_handler nh) { boolean match = false; list_foreach(&rm->root, i) { rmnode curr = struct_from_list(i, rmnode, l); range i = range_intersection(curr->r, q); if (!range_empty(i)) { match = true; if (nh == 0) /* abort search if match w/o handler */ return true; apply(nh, curr); } } return match; } boolean rangemap_range_find_gaps(rangemap rm, range q, range_handler rh) { boolean match = false; u64 lastedge = q.start; list_foreach(&rm->root, l) { rmnode curr = struct_from_list(l, rmnode, l); u64 edge = curr->r.start; range i = range_intersection(irange(lastedge, edge), q); if (range_span(i)) { match = true; apply(rh, i); } lastedge = curr->r.end; } /* check for a gap between the last node and q.end */ range i = range_intersection(irange(lastedge, q.end), q); if (range_span(i)) { match = true; apply(rh, i); } return match; } rangemap allocate_rangemap(heap h) { rangemap rm = allocate(h, sizeof(struct rangemap)); rm->h = h; list_init(&rm->root); return rm; } void deallocate_rangemap(rangemap r) { }
2.515625
3
2024-11-18T22:25:12.390059+00:00
2021-05-03T21:37:08
767674cf9b9c6133611f0f6263ed1cd04128c6e9
{ "blob_id": "767674cf9b9c6133611f0f6263ed1cd04128c6e9", "branch_name": "refs/heads/main", "committer_date": "2021-05-03T21:37:08", "content_id": "e6ce3d0e069fd334c3943cd2fc723370b70a35a3", "detected_licenses": [ "MIT" ], "directory_id": "0eb854888dfd11a9ad0581b6641816e61fc7747d", "extension": "c", "filename": "sha3_x.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 320690593, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2723, "license": "MIT", "license_type": "permissive", "path": "/sha3_x.c", "provenance": "stackv2-0115.json.gz:112194", "repo_name": "doubleodd/c-do255", "revision_date": "2021-05-03T21:37:08", "revision_id": "4288ecfeb8447de7a6a2cec64afe0feafaa0b2b1", "snapshot_id": "457116d785af487a8382dc1dc6ae51bb6b6af946", "src_encoding": "UTF-8", "star_events_count": 26, "url": "https://raw.githubusercontent.com/doubleodd/c-do255/4288ecfeb8447de7a6a2cec64afe0feafaa0b2b1/sha3_x.c", "visit_date": "2023-04-28T20:34:19.216627" }
stackv2
/* * SHA3 and SHAKE implementation, using an external process_block() * function (for assembly implementations). */ #include <stddef.h> #include <stdint.h> #include <string.h> #include "sha3.h" #define process_block do255_sha3_process_block void process_block(uint64_t *A); /* see sha3.h */ void shake_init(shake_context *sc, unsigned size) { sc->rate = 200 - (size_t)(size >> 2); sc->dptr = 0; memset(sc->A, 0, sizeof sc->A); } /* see sha3.h */ void shake_inject(shake_context *sc, const void *in, size_t len) { size_t dptr, rate; const uint8_t *buf; dptr = sc->dptr; rate = sc->rate; buf = in; while (len > 0) { size_t clen, u; clen = rate - dptr; if (clen > len) { clen = len; } for (u = 0; u < clen; u ++) { size_t v; v = u + dptr; sc->A[v >> 3] ^= (uint64_t)buf[u] << ((v & 7) << 3); } dptr += clen; buf += clen; len -= clen; if (dptr == rate) { process_block(sc->A); dptr = 0; } } sc->dptr = dptr; } /* see sha3.h */ void shake_flip(shake_context *sc) { /* * We apply padding and pre-XOR the value into the state. We * set dptr to the end of the buffer, so that first call to * shake_extract() will process the block. */ unsigned v; v = (unsigned)sc->dptr; sc->A[v >> 3] ^= (uint64_t)0x1F << ((v & 7) << 3); v = (unsigned)(sc->rate - 1); sc->A[v >> 3] ^= (uint64_t)0x80 << ((v & 7) << 3); sc->dptr = sc->rate; } /* see sha3.h */ void shake_extract(shake_context *sc, void *out, size_t len) { size_t dptr, rate; uint8_t *buf; dptr = sc->dptr; rate = sc->rate; buf = out; while (len > 0) { size_t clen; if (dptr == rate) { process_block(sc->A); dptr = 0; } clen = rate - dptr; if (clen > len) { clen = len; } len -= clen; while (clen -- > 0) { *buf ++ = (uint8_t) (sc->A[dptr >> 3] >> ((dptr & 7) << 3)); dptr ++; } } sc->dptr = dptr; } /* see sha3.h */ void sha3_init(sha3_context *sc, unsigned size) { shake_init(sc, size); } /* see sha3.h */ void sha3_update(sha3_context *sc, const void *in, size_t len) { shake_inject(sc, in, len); } /* see sha3.h */ void sha3_close(sha3_context *sc, void *out) { unsigned v; uint8_t *buf; size_t u, len; /* * Apply padding. It differs from the SHAKE padding in that * we append '01', not '1111'. */ v = (unsigned)sc->dptr; sc->A[v >> 3] ^= (uint64_t)0x06 << ((v & 7) << 3); v = (unsigned)(sc->rate - 1); sc->A[v >> 3] ^= (uint64_t)0x80 << ((v & 7) << 3); /* * Process the padded block. */ process_block(sc->A); /* * Write output. Output length (in bytes) is obtained from the rate. */ buf = out; len = (200 - sc->rate) >> 1; for (u = 0; u < len; u ++) { buf[u] = (uint8_t)(sc->A[u >> 3] >> ((u & 7) << 3)); } }
2.96875
3
2024-11-18T22:25:13.455710+00:00
2023-08-17T16:08:06
6ab53d383fe99f3a7d170d653ca231a163b28429
{ "blob_id": "6ab53d383fe99f3a7d170d653ca231a163b28429", "branch_name": "refs/heads/main", "committer_date": "2023-08-17T16:08:06", "content_id": "6c8e0d8fc9dd77596d61eeaad21bec00ab6bd9cb", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "eecd5e4c50d8b78a769bcc2675250576bed34066", "extension": "c", "filename": "daghost.c", "fork_events_count": 169, "gha_created_at": "2013-03-10T20:55:21", "gha_event_created_at": "2023-03-29T11:02:58", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 8691401, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1936, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/dm/impls/da/daghost.c", "provenance": "stackv2-0115.json.gz:113103", "repo_name": "petsc/petsc", "revision_date": "2023-08-17T16:08:06", "revision_id": "9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9", "snapshot_id": "3b1a04fea71858e0292f9fd4d04ea11618c50969", "src_encoding": "UTF-8", "star_events_count": 341, "url": "https://raw.githubusercontent.com/petsc/petsc/9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9/src/dm/impls/da/daghost.c", "visit_date": "2023-08-17T20:51:16.507070" }
stackv2
/* Code for manipulating distributed regular arrays in parallel. */ #include <petsc/private/dmdaimpl.h> /*I "petscdmda.h" I*/ /*@C DMDAGetGhostCorners - Returns the global (x,y,z) indices of the lower left corner and size of the local region, including ghost points. Not Collective Input Parameter: . da - the distributed array Output Parameters: + x - the corner index for the first dimension . y - the corner index for the second dimension (only used in 2D and 3D problems) . z - the corner index for the third dimension (only used in 3D problems) . m - the width in the first dimension . n - the width in the second dimension (only used in 2D and 3D problems) - p - the width in the third dimension (only used in 3D problems) Level: beginner Note: The corner information is independent of the number of degrees of freedom per node set with the `DMDACreateXX()` routine. Thus the x, y, z, and m, n, p can be thought of as coordinates on a logical grid, where each grid point has (potentially) several degrees of freedom. Any of y, z, n, and p can be passed in as NULL if not needed. .seealso: `DM`, `DMDA`, `DMDAGetCorners()`, `DMDACreate1d()`, `DMDACreate2d()`, `DMDACreate3d()`, `DMDAGetOwnershipRanges()`, `DMStagGetGhostCorners()` @*/ PetscErrorCode DMDAGetGhostCorners(DM da, PetscInt *x, PetscInt *y, PetscInt *z, PetscInt *m, PetscInt *n, PetscInt *p) { PetscInt w; DM_DA *dd = (DM_DA *)da->data; PetscFunctionBegin; PetscValidHeaderSpecificType(da, DM_CLASSID, 1, DMDA); /* since the xs, xe ... have all been multiplied by the number of degrees of freedom per cell, w = dd->w, we divide that out before returning.*/ w = dd->w; if (x) *x = dd->Xs / w + dd->xo; if (y) *y = dd->Ys + dd->yo; if (z) *z = dd->Zs + dd->zo; if (m) *m = (dd->Xe - dd->Xs) / w; if (n) *n = (dd->Ye - dd->Ys); if (p) *p = (dd->Ze - dd->Zs); PetscFunctionReturn(PETSC_SUCCESS); }
2.4375
2
2024-11-18T22:25:13.694508+00:00
2019-08-23T14:11:05
7dbbafe08550bf4ea23e5732365ef3f01c7fa793
{ "blob_id": "7dbbafe08550bf4ea23e5732365ef3f01c7fa793", "branch_name": "refs/heads/master", "committer_date": "2019-08-23T14:11:05", "content_id": "34efb1c172b897f8a40b9924d1a05152870fa1b7", "detected_licenses": [ "MIT" ], "directory_id": "edfbbcab98e605b626137a4c0c428be2dd801066", "extension": "c", "filename": "program1.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 190797665, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 713, "license": "MIT", "license_type": "permissive", "path": "/program1.c", "provenance": "stackv2-0115.json.gz:113231", "repo_name": "aarushivohra/my-c-programs", "revision_date": "2019-08-23T14:11:05", "revision_id": "1a264d393a12dd16851b432da6f6527ca306bc41", "snapshot_id": "4fb4cc54f17650581cf03b85ca18b7f976f37e21", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/aarushivohra/my-c-programs/1a264d393a12dd16851b432da6f6527ca306bc41/program1.c", "visit_date": "2022-02-19T10:22:18.707360" }
stackv2
/* Date 19 Aug 2019 Program - 1 performing various arithmatic operations on two numbers */ #include<stdio.h> int main() { float a = 37; float b = 56; float c, d, e; float f; c = a + b; d = a - b; e = a * b; f = a / b; printf("Sum = %f \n", c); printf("Difference = %f \n", d); printf("Multiplication = %f \n", e); printf("Division = %f \n", f); float x,y,z; printf("Enter first number : "); scanf("%f", &x); printf("\nEnter second number : "); scanf("%f", &y); z = x + y; printf("\nSum is %f", z); z = x - y; printf("\nDifference is %f", z); z = x * y; printf("\nMultiplication is %f", z); z = x / y; printf("\nDivision is %f", z); return 0; }
4.125
4
2024-11-18T22:25:13.857350+00:00
2023-08-24T13:58:03
7ea699493f61bbee052704f1444f3044a5b06896
{ "blob_id": "7ea699493f61bbee052704f1444f3044a5b06896", "branch_name": "refs/heads/master", "committer_date": "2023-08-28T13:02:07", "content_id": "c636e85d40ccec90f6a9ab1aa19d878064ac2ed9", "detected_licenses": [ "Apache-2.0" ], "directory_id": "a559e75ad2514230753d5e262a16338493a8093d", "extension": "c", "filename": "aes_encrypt_test.c", "fork_events_count": 55, "gha_created_at": "2018-11-26T08:11:51", "gha_event_created_at": "2023-08-28T13:02:09", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 159133309, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 18153, "license": "Apache-2.0", "license_type": "permissive", "path": "/pkcs11/tests/aes_encrypt_test.c", "provenance": "stackv2-0115.json.gz:113359", "repo_name": "Yubico/yubihsm-shell", "revision_date": "2023-08-24T13:58:03", "revision_id": "eb0034fa7b11492439926324d1d7989b05000922", "snapshot_id": "57f7f6e54a38b2c6562d92d57b91499379856dcd", "src_encoding": "UTF-8", "star_events_count": 78, "url": "https://raw.githubusercontent.com/Yubico/yubihsm-shell/eb0034fa7b11492439926324d1d7989b05000922/pkcs11/tests/aes_encrypt_test.c", "visit_date": "2023-08-29T03:30:18.943483" }
stackv2
/* * Copyright 2021-2022 Yubico AB * * 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. */ #undef NDEBUG #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../pkcs11.h" #include "common.h" #define FAIL(fmt, ...) \ do { \ fprintf(stderr, "%s:%d (%s): " fmt "\n", __FILE__, __LINE__, __func__, \ __VA_ARGS__); \ } while (0) #define nitems(a) (sizeof(a) / sizeof(a[0])) // Disabling automatic formatting so that clang-format does not reflow // the plaintext blocks. Each row corresponds to a whole block. // clang-format off #define PLAINTEXT_LENGTH (4 * 16) static uint8_t plaintext[PLAINTEXT_LENGTH] = "\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96\xe9\x3d\x7e\x11\x73\x93\x17\x2a" "\xae\x2d\x8a\x57\x1e\x03\xac\x9c\x9e\xb7\x6f\xac\x45\xaf\x8e\x51" "\x30\xc8\x1c\x46\xa3\x5c\xe4\x11\xe5\xfb\xc1\x19\x1a\x0a\x52\xef" "\xf6\x9f\x24\x45\xdf\x4f\x9b\x17\xad\x2b\x41\x7b\xe6\x6c\x37\x10"; // clang-format on #define TEST_ECB(key, ptlen, ct) \ { CKM_AES_ECB, key, sizeof(key) - 1, ptlen, ct, sizeof(ct) - 1 } #define TEST_CBC(key, ptlen, ct) \ { CKM_AES_CBC, key, sizeof(key) - 1, ptlen, ct, sizeof(ct) - 1 } #define TEST_CBC_PAD(key, ptlen, ct) \ { CKM_AES_CBC_PAD, key, sizeof(key) - 1, ptlen, ct, sizeof(ct) - 1 } struct test { CK_MECHANISM_TYPE mechanism; uint8_t key[32]; uint8_t keylen; size_t plaintext_len; uint8_t ciphertext[sizeof(plaintext) + 16]; size_t ciphertext_len; }; static uint8_t iv[16] = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"; // CKM_AES_{ECB,CBC} test vectors from NIST. // CKM_AES_CBC_PAD calculated out-of-band. static struct test tests[] = { TEST_ECB("\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", PLAINTEXT_LENGTH, "\x3a\xd7\x7b\xb4\x0d\x7a\x36\x60\xa8\x9e\xca\xf3\x24\x66\xef\x97" "\xf5\xd3\xd5\x85\x03\xb9\x69\x9d\xe7\x85\x89\x5a\x96\xfd\xba\xaf" "\x43\xb1\xcd\x7f\x59\x8e\xce\x23\x88\x1b\x00\xe3\xed\x03\x06\x88" "\x7b\x0c\x78\x5e\x27\xe8\xad\x3f\x82\x23\x20\x71\x04\x72\x5d\xd4"), TEST_ECB("\x8e\x73\xb0\xf7\xda\x0e\x64\x52\xc8\x10\xf3\x2b\x80\x90\x79\xe5" "\x62\xf8\xea\xd2\x52\x2c\x6b\x7b", PLAINTEXT_LENGTH, "\xbd\x33\x4f\x1d\x6e\x45\xf2\x5f\xf7\x12\xa2\x14\x57\x1f\xa5\xcc" "\x97\x41\x04\x84\x6d\x0a\xd3\xad\x77\x34\xec\xb3\xec\xee\x4e\xef" "\xef\x7a\xfd\x22\x70\xe2\xe6\x0a\xdc\xe0\xba\x2f\xac\xe6\x44\x4e" "\x9a\x4b\x41\xba\x73\x8d\x6c\x72\xfb\x16\x69\x16\x03\xc1\x8e\x0e"), TEST_ECB("\x60\x3d\xeb\x10\x15\xca\x71\xbe\x2b\x73\xae\xf0\x85\x7d\x77\x81" "\x1f\x35\x2c\x07\x3b\x61\x08\xd7\x2d\x98\x10\xa3\x09\x14\xdf\xf4", PLAINTEXT_LENGTH, "\xf3\xee\xd1\xbd\xb5\xd2\xa0\x3c\x06\x4b\x5a\x7e\x3d\xb1\x81\xf8" "\x59\x1c\xcb\x10\xd4\x10\xed\x26\xdc\x5b\xa7\x4a\x31\x36\x28\x70" "\xb6\xed\x21\xb9\x9c\xa6\xf4\xf9\xf1\x53\xe7\xb1\xbe\xaf\xed\x1d" "\x23\x30\x4b\x7a\x39\xf9\xf3\xff\x06\x7d\x8d\x8f\x9e\x24\xec\xc7"), TEST_CBC("\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", PLAINTEXT_LENGTH, "\x76\x49\xab\xac\x81\x19\xb2\x46\xce\xe9\x8e\x9b\x12\xe9\x19\x7d" "\x50\x86\xcb\x9b\x50\x72\x19\xee\x95\xdb\x11\x3a\x91\x76\x78\xb2" "\x73\xbe\xd6\xb8\xe3\xc1\x74\x3b\x71\x16\xe6\x9e\x22\x22\x95\x16" "\x3f\xf1\xca\xa1\x68\x1f\xac\x09\x12\x0e\xca\x30\x75\x86\xe1\xa7"), TEST_CBC("\x8e\x73\xb0\xf7\xda\x0e\x64\x52\xc8\x10\xf3\x2b\x80\x90\x79\xe5" "\x62\xf8\xea\xd2\x52\x2c\x6b\x7b", PLAINTEXT_LENGTH, "\x4f\x02\x1d\xb2\x43\xbc\x63\x3d\x71\x78\x18\x3a\x9f\xa0\x71\xe8" "\xb4\xd9\xad\xa9\xad\x7d\xed\xf4\xe5\xe7\x38\x76\x3f\x69\x14\x5a" "\x57\x1b\x24\x20\x12\xfb\x7a\xe0\x7f\xa9\xba\xac\x3d\xf1\x02\xe0" "\x08\xb0\xe2\x79\x88\x59\x88\x81\xd9\x20\xa9\xe6\x4f\x56\x15\xcd"), TEST_CBC("\x60\x3d\xeb\x10\x15\xca\x71\xbe\x2b\x73\xae\xf0\x85\x7d\x77\x81" "\x1f\x35\x2c\x07\x3b\x61\x08\xd7\x2d\x98\x10\xa3\x09\x14\xdf\xf4", PLAINTEXT_LENGTH, "\xf5\x8c\x4c\x04\xd6\xe5\xf1\xba\x77\x9e\xab\xfb\x5f\x7b\xfb\xd6" "\x9c\xfc\x4e\x96\x7e\xdb\x80\x8d\x67\x9f\x77\x7b\xc6\x70\x2c\x7d" "\x39\xf2\x33\x69\xa9\xd9\xba\xcf\xa5\x30\xe2\x63\x04\x23\x14\x61" "\xb2\xeb\x05\xe2\xc3\x9b\xe9\xfc\xda\x6c\x19\x07\x8c\x6a\x9d\x1b"), TEST_CBC_PAD( "\x2b\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c", PLAINTEXT_LENGTH - 15, "\x76\x49\xab\xac\x81\x19\xb2\x46\xce\xe9\x8e\x9b\x12\xe9\x19\x7d" "\x50\x86\xcb\x9b\x50\x72\x19\xee\x95\xdb\x11\x3a\x91\x76\x78\xb2" "\x73\xbe\xd6\xb8\xe3\xc1\x74\x3b\x71\x16\xe6\x9e\x22\x22\x95\x16" "\x29\xe0\x8a\x17\xfd\xdd\xdd\xe8\x6d\xa9\xbc\xaf\x31\xe0\x28\xd8"), TEST_CBC_PAD( "\x8e\x73\xb0\xf7\xda\x0e\x64\x52\xc8\x10\xf3\x2b\x80\x90\x79\xe5" "\x62\xf8\xea\xd2\x52\x2c\x6b\x7b", PLAINTEXT_LENGTH - 1, "\x4f\x02\x1d\xb2\x43\xbc\x63\x3d\x71\x78\x18\x3a\x9f\xa0\x71\xe8" "\xb4\xd9\xad\xa9\xad\x7d\xed\xf4\xe5\xe7\x38\x76\x3f\x69\x14\x5a" "\x57\x1b\x24\x20\x12\xfb\x7a\xe0\x7f\xa9\xba\xac\x3d\xf1\x02\xe0" "\x89\x7e\x29\x85\x3a\x69\x34\xfd\x58\x9f\xc9\x3e\x7a\xf0\x37\x49"), TEST_CBC_PAD( "\x60\x3d\xeb\x10\x15\xca\x71\xbe\x2b\x73\xae\xf0\x85\x7d\x77\x81" "\x1f\x35\x2c\x07\x3b\x61\x08\xd7\x2d\x98\x10\xa3\x09\x14\xdf\xf4", PLAINTEXT_LENGTH, "\xf5\x8c\x4c\x04\xd6\xe5\xf1\xba\x77\x9e\xab\xfb\x5f\x7b\xfb\xd6" "\x9c\xfc\x4e\x96\x7e\xdb\x80\x8d\x67\x9f\x77\x7b\xc6\x70\x2c\x7d" "\x39\xf2\x33\x69\xa9\xd9\xba\xcf\xa5\x30\xe2\x63\x04\x23\x14\x61" "\xb2\xeb\x05\xe2\xc3\x9b\xe9\xfc\xda\x6c\x19\x07\x8c\x6a\x9d\x1b" "\x3f\x46\x17\x96\xd6\xb0\xd6\xb2\xe0\xc2\xa7\x2b\x4d\x80\xe6\x44"), }; static CK_BBOOL g_true = TRUE; static CK_RV create_aes_key(CK_FUNCTION_LIST_PTR p11, CK_SESSION_HANDLE session, CK_BYTE_PTR key, CK_ULONG len, CK_OBJECT_HANDLE *handle) { CK_OBJECT_CLASS class = CKO_SECRET_KEY; CK_KEY_TYPE type = CKK_AES; CK_ATTRIBUTE templ[] = {{CKA_CLASS, &class, sizeof(class)}, {CKA_KEY_TYPE, &type, sizeof(type)}, {CKA_ENCRYPT, &g_true, sizeof(g_true)}, {CKA_DECRYPT, &g_true, sizeof(g_true)}, {CKA_VALUE, key, len}}; return p11->C_CreateObject(session, templ, nitems(templ), handle); } typedef CK_RV (*InitFunc)(CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE); typedef CK_RV (*SingleFunc)(CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, CK_ULONG_PTR); typedef CK_RV (*FinalFunc)(CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR); typedef SingleFunc UpdateFunc; typedef size_t (*CalculateOutputSize)(size_t, size_t); static int do_test_single_part(InitFunc init, SingleFunc single, CK_SESSION_HANDLE session, CK_OBJECT_HANDLE handle, CK_MECHANISM mechanism, const uint8_t *input, size_t inlen, const uint8_t *output, size_t outlen) { uint8_t buffer[PLAINTEXT_LENGTH + 16]; CK_ULONG len; CK_RV rv; if (inlen > sizeof(buffer) || outlen > sizeof(buffer)) { FAIL("%s", "input or expected output data too large"); return -1; } // Initialize the operation. if ((rv = init(session, &mechanism, handle)) != CKR_OK) { FAIL("init failed (rv=0x%lx)", rv); return -1; } memcpy(buffer, input, inlen); // Test querying output size. len = 0; if ((rv = single(session, buffer, inlen, NULL, &len)) != CKR_OK || len < outlen) { FAIL("single size query failed (rv=0x%lx, %lu, %zu)", rv, len, outlen); return -1; } // Test CKR_BUFFER_TOO_SMALL. len = outlen - 1; if ((rv = single(session, buffer, inlen, buffer, &len)) != CKR_BUFFER_TOO_SMALL || len < outlen) { FAIL("single did not return CKR_BUFFER_TOO_SMALL (rv=0x%lx, %lu, %zu)", rv, len, outlen); return -1; } // If the function call was supposed to modify the contents of certain // memory addresses on the host computer, these memory addresses may // have been modified, despite the failure of the function. // PKCS#11 version 2.4; section 5 memcpy(buffer, input, inlen); // Test actual operation. if ((rv = single(session, buffer, inlen, buffer, &len)) != CKR_OK || len != outlen) { FAIL("single failed (rv=0x%lx, %lu, %zu)", rv, len, outlen); return -1; } // Verify expected data. if (memcmp(buffer, output, outlen)) { FAIL("%s", "memcmp failed"); return -1; } return 0; } static int test_single_part(CK_FUNCTION_LIST_PTR p11, CK_SESSION_HANDLE session, CK_OBJECT_HANDLE handle, struct test *test) { CK_MECHANISM mechanism = {test->mechanism, NULL, 0}; if (mechanism.mechanism != CKM_AES_ECB) { mechanism.pParameter = iv; mechanism.ulParameterLen = sizeof(iv); } if (do_test_single_part(p11->C_EncryptInit, p11->C_Encrypt, session, handle, mechanism, plaintext, test->plaintext_len, test->ciphertext, test->ciphertext_len) != 0) { FAIL("%s", "single part encryption failed"); return -1; } if (do_test_single_part(p11->C_DecryptInit, p11->C_Decrypt, session, handle, mechanism, test->ciphertext, test->ciphertext_len, plaintext, test->plaintext_len) != 0) { FAIL("%s", "single part decryption failed"); return -1; } return CKR_OK; } #define BUFFER_OFFSET(b, p) ((size_t)((p) - (b))) /* assumes p >= b*/ static int do_test_multiple_part(InitFunc init, UpdateFunc update, FinalFunc finalize, CalculateOutputSize calc_output_size, CK_SESSION_HANDLE session, CK_OBJECT_HANDLE handle, CK_MECHANISM mechanism, const uint8_t *input, size_t inlen, const uint8_t *output, size_t outlen) { uint8_t buffer[PLAINTEXT_LENGTH + 16]; CK_ULONG len; CK_RV rv; if (inlen > sizeof(buffer) || outlen > sizeof(buffer)) { FAIL("%s", "input or expected output data too large"); return -1; } // Initialize the operation. if ((rv = init(session, &mechanism, handle)) != CKR_OK) { FAIL("init failed (rv=0x%lx)", rv); return -1; } memcpy(buffer, input, inlen); CK_BYTE_PTR cin = buffer, cout = buffer; while (inlen != 0) { CK_ULONG chunksiz = inlen > 3 ? 3 : inlen; // Verify output size. size_t pending = calc_output_size(BUFFER_OFFSET(buffer, cin + chunksiz), BUFFER_OFFSET(buffer, cout)); // Query the output size. len = 0; if ((rv = update(session, cin, chunksiz, NULL, &len)) != CKR_OK || len != pending) { FAIL("update size query failed (rv=0x%lx, %lu, %zu)", rv, len, pending); return -1; } // Check the CKR_BUFFER_TOO_SMALL case. if (len != 0) { CK_ULONG too_small = len - 1; if ((rv = update(session, cin, chunksiz, cout, &too_small)) != CKR_BUFFER_TOO_SMALL || too_small != len) { FAIL("update did not return CKR_BUFFER_TOO_SMALL (rv=0x%lx, %lu, %lu)", rv, too_small, len); return -1; } } // Perform the actual update. len = sizeof(buffer) - BUFFER_OFFSET(buffer, cout); if ((rv = update(session, cin, chunksiz, cout, &len)) != CKR_OK) { FAIL("update failed (rv=0x%lx)", rv); return -1; } cin += chunksiz; cout += len; inlen -= chunksiz; } size_t remain = outlen - BUFFER_OFFSET(buffer, cout); // Check that querying size works. len = 0; if ((rv = finalize(session, NULL, &len)) != CKR_OK || len < remain) { FAIL("finalize size query failed (rv=0x%lx, %lu, %zu)", rv, len, remain); return -1; } // Check the CKR_BUFFER_TOO_SMALL case. if (remain != 0) { CK_ULONG too_small = remain - 1; if ((rv = finalize(session, cout, &too_small)) != CKR_BUFFER_TOO_SMALL || too_small != remain) { FAIL("finalize did not return CKR_BUFFER_TOO_SMALL (rv=0x%lx, %lu, %zu)", rv, too_small, remain); return -1; } } // Finalize the operation. len = sizeof(buffer) - BUFFER_OFFSET(buffer, cout); if ((rv = finalize(session, cout, &len)) != CKR_OK) { FAIL("finalize failed (rv=0x%lx)", rv); return -1; } // Check against the expected ciphertext. cout += len; if (BUFFER_OFFSET(buffer, cout) != outlen) { FAIL("finalize output length does not match (%zu != %zu)", BUFFER_OFFSET(buffer, cout), outlen); return -1; } if (memcmp(buffer, output, outlen)) { FAIL("%s", "memcmp failed"); return -1; } return 0; } static size_t simple_output_size(size_t in, size_t out) { size_t pending = in - out; pending /= 16; pending *= 16; return pending; } static size_t pad_output_size(size_t in, size_t out) { size_t pending = in - out; return pending <= 16 ? 0 : simple_output_size(in, out); } static CK_RV test_multiple_part(CK_FUNCTION_LIST_PTR p11, CK_SESSION_HANDLE session, CK_OBJECT_HANDLE handle, struct test *test) { CK_MECHANISM mechanism = {test->mechanism, NULL, 0}; if (mechanism.mechanism != CKM_AES_ECB) { mechanism.pParameter = iv; mechanism.ulParameterLen = sizeof(iv); } if (do_test_multiple_part(p11->C_EncryptInit, p11->C_EncryptUpdate, p11->C_EncryptFinal, simple_output_size, session, handle, mechanism, plaintext, test->plaintext_len, test->ciphertext, test->ciphertext_len) != 0) { FAIL("%s", "multiple part encryption failed"); return -1; } if (do_test_multiple_part(p11->C_DecryptInit, p11->C_DecryptUpdate, p11->C_DecryptFinal, mechanism.mechanism == CKM_AES_CBC_PAD ? pad_output_size : simple_output_size, session, handle, mechanism, test->ciphertext, test->ciphertext_len, plaintext, test->plaintext_len) != 0) { FAIL("%s", "multiple part decryption failed"); return -1; } return CKR_OK; } static int run_test(CK_FUNCTION_LIST_PTR p11, CK_SESSION_HANDLE session, struct test *test) { CK_OBJECT_HANDLE handle = 0; int rv; if (create_aes_key(p11, session, test->key, test->keylen, &handle) != CKR_OK) { FAIL("%s", "Could not create AES key"); return -1; } if ((rv = test_single_part(p11, session, handle, test)) != 0 || (rv = test_multiple_part(p11, session, handle, test)) != 0) goto end; end: destroy_object(p11, session, handle); return rv; } static CK_RV is_aes_supported(CK_FUNCTION_LIST_PTR p11, CK_SESSION_HANDLE session) { CK_SESSION_INFO info; CK_RV r; if ((r = p11->C_GetSessionInfo(session, &info)) != CKR_OK) { fprintf(stderr, "C_GetSessionInfo (r = %lu)\n", r); return CKR_FUNCTION_FAILED; } CK_MECHANISM_TYPE m[128]; CK_ULONG n = nitems(m); if ((r = p11->C_GetMechanismList(info.slotID, m, &n)) != CKR_OK) { fprintf(stderr, "C_GetMechanismList (r = %lu)\n", r); return CKR_FUNCTION_FAILED; } unsigned int x = 0; for (CK_ULONG i = 0; i < n; i++) { if (m[i] == CKM_AES_ECB) x |= 0x1; else if (m[i] == CKM_AES_CBC) x |= 0x2; else if (m[i] == CKM_AES_CBC_PAD) x |= 0x4; } if ((x >> 1) && (x >> 1) != 0x3) { fprintf(stderr, "CKM_AES_CBC_PAD and CKM_AES_CBC_PAD are toggled together\n"); return CKR_FUNCTION_FAILED; } if (x != 0x7) { fprintf(stderr, "CKM_AES_{ECB,CBC} disabled or unsupported\n"); return CKR_MECHANISM_INVALID; } return CKR_OK; } static const char *mechstr(CK_MECHANISM_TYPE mech) { switch (mech) { case CKM_AES_ECB: return "CKM_AES_ECB"; case CKM_AES_CBC: return "CKM_AES_CBC"; case CKM_AES_CBC_PAD: return "CKM_AES_CBC_PAD"; default: return "unknown"; } } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "usage: /path/to/yubihsm_pkcs11/module\n"); exit(EXIT_FAILURE); } void *handle = open_module(argv[1]); CK_FUNCTION_LIST_PTR p11 = get_function_list(handle); CK_SESSION_HANDLE session = open_session(p11); print_session_state(p11, session); int st = EXIT_SUCCESS; CK_RV rv = is_aes_supported(p11, session); if (rv == CKR_MECHANISM_INVALID) { st = 64; /* arbitrarily chosen */ goto out; } else if (rv != CKR_OK) { st = EXIT_FAILURE; goto out; } for (size_t i = 0; i < nitems(tests); i++) { fprintf(stderr, "Running test %zu (%s, AES%d)... ", i, mechstr(tests[i].mechanism), tests[i].keylen * 8); if (run_test(p11, session, &tests[i]) != 0) { fprintf(stderr, "FAIL\n"); st = EXIT_FAILURE; } else { fprintf(stderr, "OK\n"); } } out: close_session(p11, session); close_module(handle); return st; }
2.15625
2
2024-11-18T22:25:13.959073+00:00
2020-07-01T12:19:34
19034cf8492c10df6b3abe031acadbe4cb2c6e1a
{ "blob_id": "19034cf8492c10df6b3abe031acadbe4cb2c6e1a", "branch_name": "refs/heads/master", "committer_date": "2020-07-01T12:19:34", "content_id": "557608c4fb13e2a6b6bf5571b02a12a83239d40a", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "directory_id": "bbf91cfe87a36779afbc43b5392abc0722363870", "extension": "c", "filename": "utility.c", "fork_events_count": 0, "gha_created_at": "2020-06-06T20:03:26", "gha_event_created_at": "2020-06-06T20:03:26", "gha_language": null, "gha_license_id": "MIT", "github_id": 270090369, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4969, "license": "BSD-3-Clause,MIT", "license_type": "permissive", "path": "/tools/tinyos/c/blip/lib6lowpan/utility.c", "provenance": "stackv2-0115.json.gz:113488", "repo_name": "ioteleman/InternetOfThings", "revision_date": "2020-07-01T12:19:34", "revision_id": "a87c1e2a243d06574d08645f8c5fe82f005c0da3", "snapshot_id": "df9792b2d38527bcd418d976c72fbb60e6ae5ccc", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ioteleman/InternetOfThings/a87c1e2a243d06574d08645f8c5fe82f005c0da3/tools/tinyos/c/blip/lib6lowpan/utility.c", "visit_date": "2022-11-06T06:22:16.304317" }
stackv2
#include <stdint.h> #include <stdint.h> #include <string.h> #include <stdlib.h> #include "lib6lowpan-includes.h" #include "ip.h" #define TO_CHAR(X) (((X) < 10) ? ('0' + (X)) : ('a' + ((X) - 10))) #define CHAR_VAL(X) (((X) >= '0' && (X) <= '9') ? ((X) - '0') : \ (((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : ((X) - 'a' + 10))) void inet_pton6(char *addr, struct in6_addr *dest) { uint16_t cur = 0; char *p = addr; uint8_t block = 0, shift = 0; if (addr == NULL || dest == NULL) return; memset(dest->s6_addr, 0, 16); // first fill in from the front while (*p != '\0') { if (*p != ':') { cur <<= 4; cur |= CHAR_VAL(*p); } else { dest->s6_addr16[block++] = htons(cur); cur = 0; } p++; if (*p == '\0') { dest->s6_addr16[block++] = htons(cur); return; } if (*(p - 1) == ':' && *p == ':') { break; } } // we must have hit a "::" which means we need to start filling in from the end. block = 7; cur = 0; while (*p != '\0') p++; p--; // now pointing at the end of the address string while (p > addr) { if (*p != ':') { cur |= (CHAR_VAL(*p) << shift); shift += 4; } else { dest->s6_addr16[block--] = htons(cur); cur = 0; shift = 0; } p --; if (*(p + 1) == ':' && *p == ':') break; } } int inet_ntop6(struct in6_addr *addr, char *buf, int cnt) { uint16_t block; char *end = buf + cnt; int i, j, compressed = 0; for (j = 0; j < 8; j++) { if (buf > end - 8) goto done; block = ntohs(addr->s6_addr16[j]); for (i = 4; i <= 16; i+=4) { if (block > (0xffff >> i) || (compressed == 2 && i == 16)) { *buf++ = TO_CHAR((block >> (16 - i)) & 0xf); } } if (addr->s6_addr16[j] == 0 && compressed == 0) { *buf++ = ':'; compressed++; } if (addr->s6_addr16[j] != 0 && compressed == 1) compressed++; if (j < 7 && compressed != 1) *buf++ = ':'; } if (compressed == 1) *buf++ = ':'; done: *buf++ = '\0'; return buf - (end - cnt); } uint16_t ieee154_hashaddr(ieee154_addr_t *addr) { if (addr->ieee_mode == IEEE154_ADDR_SHORT) { return addr->i_saddr; } else if (addr->ieee_mode == IEEE154_ADDR_EXT) { uint16_t i, hash = 0, *current = (uint16_t *)addr->i_laddr.data; for (i = 0; i < 4; i++) hash += *current ++; return hash; } else { return 0; } } #ifndef PC uint32_t ntohl(uint32_t i) { uint16_t lo = (uint16_t)i; uint16_t hi = (uint16_t)(i >> 16); lo = (lo << 8) | (lo >> 8); hi = (hi << 8) | (hi >> 8); return (((uint32_t)lo) << 16) | ((uint32_t)hi); } uint8_t *ip_memcpy(uint8_t *dst0, const uint8_t *src0, uint16_t len) { uint8_t *dst = (uint8_t *) dst0; uint8_t *src = (uint8_t *) src0; uint8_t *ret = dst0; for (; len > 0; len--) *dst++ = *src++; return ret; } #endif #ifdef PC char *strip(char *buf) { char *rv; while (isspace(*buf)) buf++; rv = buf; buf += strlen(buf) - 1; while (isspace(*buf)) { *buf = '\0'; buf--; } return rv; } int ieee154_parse(char *in, ieee154_addr_t *out) { int i; long val; char *endp = in; long saddr = strtol(in, &endp, 16); // fprintf(stderr, "ieee154_parse: %s, %c\n", in, *endp); if (*endp == ':') { endp = in; // must be a long address for (i = 0; i < 8; i++) { val = strtol(endp, &endp, 16); out->i_laddr.data[7-i] = val; endp++; } out->ieee_mode = IEEE154_ADDR_EXT; } else { out->i_saddr = htole16(saddr); out->ieee_mode = IEEE154_ADDR_SHORT; } return 0; } int ieee154_print(ieee154_addr_t *in, char *out, size_t cnt) { int i; char *cur = out; switch (in->ieee_mode) { case IEEE154_ADDR_SHORT: snprintf(out, cnt, "IEEE154_ADDR_SHORT: 0x%x", in->i_saddr); break; case IEEE154_ADDR_EXT: cur += snprintf(out, cnt, "IEEE154_ADDR_EXT: "); for (i = 0; i < 8; i++) { cur += snprintf(cur, cnt - (cur - out), "%02x", in->i_laddr.data[i]); if (i < 7) *cur++ = ':'; } break; } return 0; } void fprint_buffer(FILE *fp, uint8_t *buf, int len) { int i; for (i = 0; i < len; i++) { if ((i % 16) == 0 && i > 0) fprintf(fp, "\n"); if (i % 16 == 0) { fprintf(fp, "%i:\t", i); } fprintf(fp, "%02x ", buf[i]); } fprintf(fp, "\n"); } void print_buffer(uint8_t *buf, int len) { fprint_buffer(stdout, buf, len); } void print_buffer_bare(uint8_t *buf, int len) { while (len--) { printf("%02x ", *buf++); } } void scribble(uint8_t *buf, int len) { int i; for (i = 0; i < len; i++) { buf[i] = rand(); } } void iov_print(struct ip_iovec *iov) { struct ip_iovec *cur = iov; while (cur != NULL) { int i; printf("iovec (%p, %i) ", cur, (int)cur->iov_len); for (i = 0; i < cur->iov_len; i++) { printf("%02hhx ", cur->iov_base[i]); } printf("\n"); cur = cur->iov_next; } } #endif
2.546875
3
2024-11-18T22:25:14.047737+00:00
2021-07-24T16:36:21
062f50fba2f5bdd07ee635e236ed3a561d20bb83
{ "blob_id": "062f50fba2f5bdd07ee635e236ed3a561d20bb83", "branch_name": "refs/heads/master", "committer_date": "2021-07-24T16:38:59", "content_id": "259754f1cd39968861f2daf40cdda15def0f2553", "detected_licenses": [ "MIT" ], "directory_id": "5cdeef2599433a0c9ae7c5f3310bfb617a7b513a", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": "2021-05-28T18:43:59", "gha_event_created_at": "2021-06-27T20:27:38", "gha_language": "C", "gha_license_id": null, "github_id": 371790804, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 903, "license": "MIT", "license_type": "permissive", "path": "/server/src/main.c", "provenance": "stackv2-0115.json.gz:113618", "repo_name": "grzes5003/IoT_server", "revision_date": "2021-07-24T16:36:21", "revision_id": "4671d9f2d5bd2ed78c60396c45db50064490e575", "snapshot_id": "0a08d1c030ca635f68db704913a7c3b9a96431a9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/grzes5003/IoT_server/4671d9f2d5bd2ed78c60396c45db50064490e575/server/src/main.c", "visit_date": "2023-06-26T10:53:07.410645" }
stackv2
#include <stdio.h> #include <string.h> #include <errno.h> // #include <unistd.h> #include <stdlib.h> #if _WIN32 #include <winsock2.h> #include <ws2tcpip.h> #pragma comment(lib, "Ws2_32.lib") #pragma comment(lib, "wsock32.lib") #else #include <netinet/in.h> #include <arpa/inet.h> #include <sys/socket.h> #endif #include "server.h" #include "log.h" #define SERV_PORT 50500 #define RCV_BUFFSIZE 10000 int main() { sensor_t *sensor_arr; int servfd = setup_server(SERV_PORT); sensor_arr = (sensor_t*) malloc(sizeof (sensor_t)); if (0 == sensor_arr) { return -1; } sensor_arr->_addr.sin6_family = AF_INET6; sensor_arr->_addr.sin6_addr = in6addr_any; sensor_arr->_addr.sin6_port = htons(5500); sensor_arr->_next= NULL; log_info("Waiting for incoming messages ..."); while (true) { handle_connection(servfd, sensor_arr); } return 0; }
2.265625
2
2024-11-18T22:25:14.273773+00:00
2016-02-05T16:45:49
d7daa5c7ef11c615e762e90d8620ef783190fd31
{ "blob_id": "d7daa5c7ef11c615e762e90d8620ef783190fd31", "branch_name": "refs/heads/master", "committer_date": "2016-02-05T16:45:49", "content_id": "262124327801760c9f725f0c8ab34cdb6b44287f", "detected_licenses": [ "MIT" ], "directory_id": "13f253e94f21f0bee9f1dc2b4416921cb3ceffea", "extension": "c", "filename": "matrix.c", "fork_events_count": 0, "gha_created_at": "2016-02-05T02:44:32", "gha_event_created_at": "2016-02-05T02:44:32", "gha_language": null, "gha_license_id": null, "github_id": 51121660, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4143, "license": "MIT", "license_type": "permissive", "path": "/src/bench/matrix.c", "provenance": "stackv2-0115.json.gz:113879", "repo_name": "criptych/graphene", "revision_date": "2016-02-05T16:45:49", "revision_id": "9838a11de0c698f8841c304fafc7356d96b23363", "snapshot_id": "7f1c9c30bb26ce4a22289ecf5730479f33343f49", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/criptych/graphene/9838a11de0c698f8841c304fafc7356d96b23363/src/bench/matrix.c", "visit_date": "2021-04-12T03:25:13.358303" }
stackv2
#include "config.h" #if defined(HAVE_POSIX_MEMALIGN) && !defined(_XOPEN_SOURCE) #define _XOPEN_SOURCE 600 #endif #if defined(HAVE_MEMALIGN) || defined (_MSC_VER) /* MSVC Builds: Required for _aligned_malloc() and _aligned_free() */ #include <malloc.h> #endif #ifdef _MSC_VER /* On Visual Studio, _aligned_malloc() takes in parameters in inverted * order from aligned_alloc(), but things are more or less the same there * otherwise */ #define aligned_alloc(alignment,size) _aligned_malloc (size, alignment) /* if we _aligned_malloc()'ed, then we must do _align_free() on MSVC */ #define free_aligned(x) _aligned_free (x) #else #define free_aligned(x) free (x) #endif #include <stdlib.h> #include <errno.h> #include <glib.h> #include "graphene-simd4x4f.h" #include "graphene-bench-utils.h" #define N_ROUNDS 819200 typedef struct { graphene_simd4x4f_t *a; graphene_simd4x4f_t *b; graphene_simd4x4f_t *c; graphene_simd4f_t *pa; graphene_simd4f_t *qa; graphene_simd4f_t *ra; } MatrixBench; static gpointer alloc_align (gsize n, gsize size, gsize alignment) { gsize real_size = size * n; gpointer res; #if defined(HAVE_POSIX_MEMALIGN) if (posix_memalign (&res, alignment, real_size) != 0) g_assert_not_reached (); #elif defined(HAVE_ALIGNED_ALLOC) || defined (_MSC_VER) g_assert (real_size % alignment == 0); res = aligned_alloc (alignment, real_size); #elif defined(HAVE_MEMALIGN) res = memalign (alignment, real_size); #endif g_assert (res != NULL); return res; } #define alloc_n_matrix(n) alloc_align((n), sizeof (graphene_simd4x4f_t), 16) #define alloc_n_vec(n) alloc_align((n), sizeof (graphene_simd4f_t), 16) static gpointer matrix_setup (void) { MatrixBench *res = g_new0 (MatrixBench, 1); int i; res->a = alloc_n_matrix (N_ROUNDS); res->b = alloc_n_matrix (N_ROUNDS); res->c = alloc_n_matrix (N_ROUNDS); res->pa = alloc_n_vec (N_ROUNDS); res->qa = alloc_n_vec (N_ROUNDS); res->ra = alloc_n_vec (N_ROUNDS); for (i = 0; i < N_ROUNDS; i++) { graphene_simd4f_t p, q; p = graphene_simd4f_init (i, i, i, i); q = graphene_simd4f_init (N_ROUNDS - i, N_ROUNDS - i, N_ROUNDS - i, N_ROUNDS - i); res->a[i] = graphene_simd4x4f_init (p, p, p, p); res->b[i] = graphene_simd4x4f_init (q, q, q, q); res->pa[i] = graphene_simd4f_init (i, i, 0.f, 0.f); res->qa[i] = graphene_simd4f_init (N_ROUNDS - i, N_ROUNDS - 1, 1.f, 0.f); } return res; } static void matrix_multiply (gpointer data_) { MatrixBench *data = data_; int i; for (i = 0; i < N_ROUNDS; i++) graphene_simd4x4f_matrix_mul (&(data->a[i]), &(data->b[i]), &(data->c[i])); } static void matrix_project (gpointer data_) { MatrixBench *data = data_; int i; for (i = 0; i < N_ROUNDS; i++) { graphene_simd4f_t pback, qback, uback; float t, x, y; graphene_simd4x4f_vec3_mul (&(data->a[i]), &(data->pa[i]), &pback); graphene_simd4x4f_vec3_mul (&(data->a[i]), &(data->qa[i]), &qback); uback = graphene_simd4f_sub (data->pa[i], pback); t = -1.0f * graphene_simd4f_get_z (pback) / graphene_simd4f_get_z (uback); x = graphene_simd4f_get_x (pback) + t * graphene_simd4f_get_x (uback); y = graphene_simd4f_get_y (pback) + t * graphene_simd4f_get_y (uback); data->ra[i] = graphene_simd4f_init (x, y, 0.f, 0.f); } } static void matrix_teardown (gpointer data_) { MatrixBench *data = data_; free_aligned (data->a); free_aligned (data->b); free_aligned (data->c); free_aligned (data->pa); free_aligned (data->qa); free_aligned (data->ra); g_free (data); } int main (int argc, char *argv[]) { graphene_bench_init (&argc, &argv, "implementation", GRAPHENE_SIMD_S, NULL); graphene_bench_set_fixture_setup (matrix_setup); graphene_bench_set_fixture_teardown (matrix_teardown); graphene_bench_set_rounds_per_unit (N_ROUNDS); graphene_bench_add_func ("/simd/4x4f/multiply", matrix_multiply); graphene_bench_add_func ("/simd/4x4f/project", matrix_project); return graphene_bench_run (); }
2.484375
2
2024-11-18T22:25:14.476300+00:00
2022-09-16T12:06:07
789938b69475e701647cdd1078ed8bb9d467bd46
{ "blob_id": "789938b69475e701647cdd1078ed8bb9d467bd46", "branch_name": "refs/heads/master", "committer_date": "2022-09-16T12:06:07", "content_id": "4e8027e3ad1d2213e6b4ba28c542dcf35068b5bc", "detected_licenses": [ "MIT" ], "directory_id": "3b622bd35ba92ba90cf55c4dfd676a739666e4b0", "extension": "c", "filename": "clrmod.c", "fork_events_count": 7, "gha_created_at": "2019-05-15T15:42:02", "gha_event_created_at": "2019-11-27T12:03:04", "gha_language": "C#", "gha_license_id": "MIT", "github_id": 186857163, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1529, "license": "MIT", "license_type": "permissive", "path": "/src/monoclr/clrmod.c", "provenance": "stackv2-0115.json.gz:114137", "repo_name": "henon/pythonnet_netstandard", "revision_date": "2022-09-16T12:06:07", "revision_id": "1b31d32e23f204abaf18f04cd9f71229793e6563", "snapshot_id": "80dfff98c64ee21d309ca49dfa4684afd5f00bf0", "src_encoding": "UTF-8", "star_events_count": 38, "url": "https://raw.githubusercontent.com/henon/pythonnet_netstandard/1b31d32e23f204abaf18f04cd9f71229793e6563/src/monoclr/clrmod.c", "visit_date": "2022-09-21T16:42:55.414569" }
stackv2
#include "pynetclr.h" /* List of functions defined in the module */ static PyMethodDef clr_methods[] = { {NULL, NULL, 0, NULL} /* Sentinel */ }; PyDoc_STRVAR(clr_module_doc, "clr facade module to initialize the CLR. It's later " "replaced by the real clr module. This module has a facade " "attribute to make it distinguishable from the real clr module." ); static PyNet_Args *pn_args; char **environ = NULL; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef clrdef = { PyModuleDef_HEAD_INIT, "clr", /* m_name */ clr_module_doc, /* m_doc */ -1, /* m_size */ clr_methods, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL, /* m_free */ }; #endif static PyObject *_initclr() { PyObject *m; /* Create the module and add the functions */ #if PY_MAJOR_VERSION >= 3 m = PyModule_Create(&clrdef); #else m = Py_InitModule3("clr", clr_methods, clr_module_doc); #endif if (m == NULL) return NULL; PyModule_AddObject(m, "facade", Py_True); Py_INCREF(Py_True); pn_args = PyNet_Init(1); if (pn_args->error) { return NULL; } if (NULL != pn_args->module) return pn_args->module; return m; } #if PY_MAJOR_VERSION >= 3 PyMODINIT_FUNC PyInit_clr(void) { return _initclr(); } #else PyMODINIT_FUNC initclr(void) { _initclr(); } #endif
2.03125
2
2024-11-18T22:25:14.628634+00:00
2015-01-30T21:54:54
b6471b39e69fb9358601dfab7e0a79c078cb1ae9
{ "blob_id": "b6471b39e69fb9358601dfab7e0a79c078cb1ae9", "branch_name": "refs/heads/master", "committer_date": "2015-01-30T21:54:54", "content_id": "c0b189f60380812c7dd08fd152617a7517546af4", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "3f6ad439218378507d1bb242d856530b53b1f14c", "extension": "c", "filename": "main.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 17260042, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 925, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/main.c", "provenance": "stackv2-0115.json.gz:114267", "repo_name": "dkudrow/slice", "revision_date": "2015-01-30T21:54:54", "revision_id": "a7374ecd5c82f58d1ea88b98a67b26d0cdfa7cc4", "snapshot_id": "0725a8f08e9e8645a4cf0c18ba26d28711f97395", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/dkudrow/slice/a7374ecd5c82f58d1ea88b98a67b26d0cdfa7cc4/src/main.c", "visit_date": "2020-04-06T07:00:33.371294" }
stackv2
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * * src/main.c * * Main entry point to Slice OS * * Author: Daniel Kudrow (dkudrow@cs.ucsb.edu) * Date: March 7 2014 * * Copyright (c) 2014, Daniel Kudrow * All rights reserved, see LICENSE.txt for details. * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * */ #define MODULE MAIN #include <emmc.h> #include <framebuffer.h> #include <gpio.h> #include <led.h> #include <log.h> #include <timer.h> #include <util.h> /* * entry point to our operating system */ slice_main() { int i, ret; /* prepare LED pin */ gpio_function_select(16, 1); /* initialize framebuffer */ ret = fb_init(); if (ret != 0) { error_blink(); } /* initialize console */ console_init(); kprintf("Console initialized, welcome to Slice.\n"); /* initialize SD card */ emmc_init(); kprintf("Done.\n"); error_solid(); }
2.1875
2
2024-11-18T22:25:14.698752+00:00
2018-01-14T17:16:56
2662b86e4941614e7f69f043322b6cb7a38dc03e
{ "blob_id": "2662b86e4941614e7f69f043322b6cb7a38dc03e", "branch_name": "refs/heads/master", "committer_date": "2018-01-14T17:16:56", "content_id": "28d3c427c6812c5dc42d4cf46ab7801d592f3bf8", "detected_licenses": [ "MIT" ], "directory_id": "ed82f5f62a34173dc6bc1fffc0cddcc82c09459f", "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": 108433666, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 702, "license": "MIT", "license_type": "permissive", "path": "/Ficha 10/Ex1/main.c", "provenance": "stackv2-0115.json.gz:114395", "repo_name": "MIGMLG/RSI-P2", "revision_date": "2018-01-14T17:16:56", "revision_id": "66a9e856b73cd81211a320703c2f300f46766b42", "snapshot_id": "c66dcea828669bf9c0946f7d75c39206136fb12e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/MIGMLG/RSI-P2/66a9e856b73cd81211a320703c2f300f46766b42/Ficha 10/Ex1/main.c", "visit_date": "2021-05-15T12:54:07.026038" }
stackv2
/* * File: main.c * Author: aluno * * Created on January 4, 2018, 10:36 AM */ #include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { int ch; //abrir ficheiros FILE *ficheiro = fopen("ficheiro.dat", "r"); FILE *ficheiroBackup = fopen("ficheiro.bak", "w"); if (ficheiro != NULL && ficheiroBackup != NULL) { //copiar até ao final do ficheiro while ((ch = getc(ficheiro)) != EOF) { //getc le carater de uma stream putc(ch, ficheiroBackup); } //fechar ficheiros fclose(ficheiro); fclose(ficheiroBackup); printf("Copia Terminada"); puts(""); } return (EXIT_SUCCESS); }
2.78125
3
2024-11-18T22:25:15.680668+00:00
2020-05-14T13:30:03
dac1047001779bc928c2290e98d415f47509eee1
{ "blob_id": "dac1047001779bc928c2290e98d415f47509eee1", "branch_name": "refs/heads/master", "committer_date": "2020-05-14T13:30:03", "content_id": "c8d484360dad8d766795bd8a1aa91ad1487723d0", "detected_licenses": [ "MIT" ], "directory_id": "4048d7ab1cf0c2bd759696f14fe03edf2d59a17e", "extension": "c", "filename": "shell.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 262741673, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5267, "license": "MIT", "license_type": "permissive", "path": "/RTOS/ECShell/shell.c", "provenance": "stackv2-0115.json.gz:115170", "repo_name": "eggcar/ECShell-Demo", "revision_date": "2020-05-14T13:30:03", "revision_id": "465472f3d70649ae0f213b2c82b00ba4aa15ab62", "snapshot_id": "9a58225e72ef0c6440aaa805890fdedf9071c5b7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/eggcar/ECShell-Demo/465472f3d70649ae0f213b2c82b00ba4aa15ab62/RTOS/ECShell/shell.c", "visit_date": "2022-07-14T04:19:02.040659" }
stackv2
/** * @file shell.c * @brief Implementation of the shell object * Import part of linenoise(https://github.com/antirez/linenoise) * @author Eggcar */ /** * MIT License * * Copyright (c) 2020 Eggcar(eggcar at qq.com or eggcar.luan at gmail.com) * * 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 "shell.h" #include "console_codes.h" #include "ec_api.h" #include "ecshell_common.h" #include "ecshell_exec.h" #include "ecshell_exec_def.h" #include "exceptions.h" #include "readline.h" #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <string.h> int user_authentication(char *uname, size_t ulen, char *passwd, size_t plen) { // Test only... if (strcmp(uname, passwd) == 0) { return 0; } else { return -1; } } void display_welcome(ecshell_t *sh) { return; } ecshell_t *ecshell_new(int32_t i_fd, int32_t o_fd, shell_type_t type, uint32_t timeout) { ecshell_t *sh = NULL; if ((i_fd < 0) || (o_fd < 0)) { goto exit; } sh = sh_malloc(sizeof(ecshell_t)); if (sh == NULL) { goto exit; } memset(sh, 0, sizeof(ecshell_t)); sh->stdin_fd = i_fd; sh->stdout_fd = o_fd; sh->echo_mode = 1; sh->shell_status = e_SHELLSTAT_WaitUserLogin; sh->shell_prompt[0] = '\0'; sh->cmd_len = 0; sh->cmd_cursor = 0; sh->history_head = 0; sh->history_tail = 0; sh->history_used = 0; sh->history_offset = 0; sh->timeout_ms = timeout; exit: return sh; } void ecshell_free(ecshell_t *sh) { sh_free(sh); } int shell_run(ecshell_t *sh) { int err; char outbuff[256]; char *_user_name; char *_password; size_t _user_name_len, _password_len; ecshell_env_t exec_env; if (sh == NULL) { err = -EINVAL; goto exit; } if ((sh->stdin_fd < 0) || (sh->stdout_fd < 0)) { err = -EBADF; goto exit; } for (;;) { switch (sh->shell_status) { case e_SHELLSTAT_WaitUserLogin: sh->prompt_len = sprintf(sh->shell_prompt, "User Login:"); err = linenoiseEdit(sh); write(sh->stdout_fd, "\r\n", 2); if (err > 0) { _user_name_len = sh->cmd_len; _user_name = sh_malloc(_user_name_len + 1); memset(_user_name, 0, _user_name_len + 1); if (_user_name == NULL) { err = -ENOMEM; goto exit; } strncpy(_user_name, sh->cmd_line, _user_name_len); _user_name[_user_name_len] = '\0'; sh->shell_status = e_SHELLSTAT_WaitUserAuthen; sh->echo_mask_mode = 1; } break; case e_SHELLSTAT_WaitUserAuthen: sh->prompt_len = sprintf(sh->shell_prompt, "Password:"); err = linenoiseEdit(sh); sh->echo_mask_mode = 0; write(sh->stdout_fd, "\r\n", 2); if (err > 0) { _password_len = sh->cmd_len; _password = sh_malloc(sh->cmd_len + 1); memset(_password, 0, _password_len + 1); if (_password == NULL) { // Clear memory, prevent information leakage. memset(_user_name, 0, _user_name_len); sh_free(_user_name); err = -ENOMEM; goto exit; } strncpy(_password, sh->cmd_line, _password_len); // Clear buffered password as soon as possible. memset(sh->cmd_line, 0, SHELL_LINE_MAXLEN); // Now we have username and password, check it. if (user_authentication(_user_name, _user_name_len, _password, _password_len) == 0) { sh->shell_status = e_SHELLSTAT_NormalCMDLine; display_welcome(sh); } else { sh->shell_status = e_SHELLSTAT_WaitUserLogin; } // Keep user name and free password. memset(_password, 0, _password_len); sh_free(_password); } else { memset(_user_name, 0, _user_name_len); sh_free(_user_name); sh->shell_status = e_SHELLSTAT_WaitUserLogin; } break; case e_SHELLSTAT_NormalCMDLine: sh->prompt_len = sprintf(sh->shell_prompt, "%s@ecshell>", _user_name); err = linenoiseEdit(sh); write(sh->stdout_fd, "\r\n", 2); if (err > 0) { linenoiseHistoryAdd(sh, sh->cmd_line); memcpy(&exec_env, sh, sizeof(exec_env)); sh->shell_status = e_SHELLSTAT_UserProgramIO; ecshell_exec_by_line(sh->cmd_line, &exec_env); sh->shell_status = e_SHELLSTAT_NormalCMDLine; } break; case e_SHELLSTAT_RecvTelnetIAC: // Not implemented yet. May be moved to my modified linenoise processing method later. break; case e_SHELLSTAT_UserProgramIO: default: break; } } exit: return err; }
2.125
2
2024-11-18T22:25:16.575852+00:00
2020-09-05T19:01:28
3b7d50ddc8d84696049f208b54fb663fee764134
{ "blob_id": "3b7d50ddc8d84696049f208b54fb663fee764134", "branch_name": "refs/heads/master", "committer_date": "2020-09-05T19:01:28", "content_id": "063dbc55e2b823d7ea73fe0a2e701fa6f8d15bc5", "detected_licenses": [ "MIT" ], "directory_id": "a04463d849a12ec6f5e82b35989e64218a124a30", "extension": "c", "filename": "input.c", "fork_events_count": 0, "gha_created_at": "2020-07-13T13:17:03", "gha_event_created_at": "2020-08-30T01:43:46", "gha_language": "C", "gha_license_id": "MIT", "github_id": 279307802, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3885, "license": "MIT", "license_type": "permissive", "path": "/compiler/input.c", "provenance": "stackv2-0115.json.gz:115559", "repo_name": "gamesmith-uk/retrolab-engine", "revision_date": "2020-09-05T19:01:28", "revision_id": "176e0ed29eb29c4051741602e2131ef9cf76f543", "snapshot_id": "9f1ba6b29d5d7b648009434b25abf7ce5204d9d4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gamesmith-uk/retrolab-engine/176e0ed29eb29c4051741602e2131ef9cf76f543/compiler/input.c", "visit_date": "2022-12-16T13:20:14.567596" }
stackv2
#define _GNU_SOURCE #include "../global.h" #include "input.h" #include "retrolab.def.h" #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct SourceFile { char* filename; char* source; } SourceFile; typedef struct Input { SourceFile* files; size_t count; } Input; Input* EMSCRIPTEN_KEEPALIVE input_new() { Input* input = calloc(1, sizeof(Input)); return input; } Input* input_new_from_string(const char* text) { Input* input = input_new(); input->count = 2; input->files = calloc(2, sizeof(SourceFile)); input->files[0].filename = strdup("retrolab.def"); input->files[0].source = strdup(retrolab_def); input->files[1].filename = strdup("main.s"); input->files[1].source = strdup(text); return input; } void EMSCRIPTEN_KEEPALIVE input_free(Input* input) { for (size_t i = 0; i < input->count; ++i) { free(input->files[i].filename); free(input->files[i].source); } free(input->files); free(input); } size_t input_file_count(Input* input) { return input->count; } const char* input_filename(Input* input, size_t idx) { return input->files[idx].filename; } const char* input_source(Input* input, size_t idx) { return input->files[idx].source; } size_t EMSCRIPTEN_KEEPALIVE input_add_file(Input* input, const char* filename, const char* source) { size_t i = input->count; input->files = realloc(input->files, (i + 1) * sizeof(SourceFile)); input->files[i].filename = strdup(filename); input->files[i].source = strdup(source); ++input->count; return input->count; } // {{{ precompilation static methods static bool ends_with(const char* s, const char* end) { size_t len_s = strlen(s), len_end = strlen(end); return len_s >= len_end && strcmp(&s[len_s - len_end], end) == 0; } static char* create_input_from_string(Input* input) { char* r = calloc(1, 1); r[0] = '\0'; size_t current_sz = 0; for (size_t i = 0; i < input->count; ++i) { if (!ends_with(input->files[i].filename, ".s") && !ends_with(input->files[i].filename, ".def")) continue; size_t line = 1; char* nxt; char* current = input->files[i].source; do { size_t old_sz = current_sz; nxt = strchrnul(current, '\n'); // find next enter int header_sz = snprintf(NULL, 0, "[$%s$:%zu] ", // calculate header size '[file.s:1] ' input->files[i].filename, line); current_sz += header_sz + (nxt - current) + 1; // header + line + '\n' r = realloc(r, current_sz + 1); // full line + '\0' snprintf(&r[old_sz], current_sz - old_sz + 1, "[$%s$:%zu] %s\n", input->files[i].filename, line, current); ++line; current = nxt + 1; } while (nxt[0] != '\0'); } if (!r) return strdup(""); return r; } static int sort_file_compare(const void* a, const void* b) { const SourceFile *sa = a, *sb = b; bool sa_is_def = ends_with(sa->filename, ".def"), sb_is_def = ends_with(sb->filename, ".def"); if (sa_is_def && !sb_is_def) return -1; else if (!sa_is_def && sb_is_def) return 1; else if (strcmp(sa->filename, "main.s") == 0 || ends_with(sa->filename, "/main.s")) return -1; else if (strcmp(sb->filename, "main.s") == 0 || ends_with(sb->filename, "/main.s")) return 1; return strcmp(sa->filename, sb->filename); } // }}} char* input_precompile(Input* input) { qsort(input->files, input->count, sizeof(SourceFile), sort_file_compare); return create_input_from_string(input); } // vim:st=4:sts=4:sw=4:expandtab:foldmethod=marker
2.546875
3
2024-11-18T22:25:17.630864+00:00
2022-11-25T14:31:40
ed2080d7809093341072599605afd2e41cf79295
{ "blob_id": "ed2080d7809093341072599605afd2e41cf79295", "branch_name": "refs/heads/main", "committer_date": "2022-11-25T14:31:40", "content_id": "934d111c7a1d240a3550087197328324caa7d1c5", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "c6bbd226758134f7057e381234b14ab0e5f19410", "extension": "c", "filename": "input.c", "fork_events_count": 0, "gha_created_at": "2020-06-16T04:28:36", "gha_event_created_at": "2022-11-25T14:31:42", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 272609398, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7128, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/v/input.c", "provenance": "stackv2-0115.json.gz:116203", "repo_name": "kattkieru/Animator-Pro", "revision_date": "2022-11-25T14:31:40", "revision_id": "5a7a58a3386a6430a59b64432d31dc556c56315b", "snapshot_id": "441328d06cae6b7175b0260f4ea1c425b36625e9", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/kattkieru/Animator-Pro/5a7a58a3386a6430a59b64432d31dc556c56315b/src/v/input.c", "visit_date": "2023-08-05T04:34:00.462730" }
stackv2
/* input.c - This is the messy mouse section. Responsible for updating the values in key_in, key_hit, mouse_button, grid_x, grid_y, uzx, uzy, are updated every time c_input is called. Macros are taken care of here by calling the appropriate routines in macro.c. The mouse coordinates are kept in both zoomed (for the paint tools: grid_x, grid_y) and unzoomed (for the menus: uzx, uzy) form. */ #include "jimk.h" #include "blit8_.h" #include "cblock_.h" #include "clipit_.h" #include "fli.h" #include "flicmenu.h" Vip aa_vip; WORD gel_input; WORD firstx, firsty; WORD omouse_button; WORD grid_x, grid_y; WORD uzx,uzy; /* unzoomed xy */ WORD lastx, lasty; WORD mouse_moved; /* mouse not same as last time - x,y or buttons */ WORD key_hit; WORD key_in; WORD mouse_on = 1; WORD reuse; WORD lmouse_x, lmouse_y; char zoomcursor; PLANEPTR brushcursor; extern char inwaittil; static Point hr_buf[HSZ]; static WORD hr_n; void scursor(void); void ccursor(void); static void zoom_bitmap_blit(WORD w, WORD h, WORD sx, WORD sy, PLANEPTR spt, WORD sbpr, WORD dx, WORD dy, WORD color); static void zo_line(int j, PLANEPTR spt, int xs, int xd, int yd, int color); static void unzoom_bitmap_blit(WORD w, WORD h, WORD sx, WORD sy, PLANEPTR spt, WORD sbpr, WORD dx, WORD dy); static void unzo_line(int j, PLANEPTR spt, int xs, int xd, int yd); extern void c_poll_input(void); extern void c_wait_input(void); init_hr() { int i; register Point *p; p = hr_buf; i = HSZ; while (--i >= 0) { p->x = grid_x; p->y = grid_y; p++; } hr_n = 0; } /* update historisis buffer with latest mouse coordinates, and return x/y position after hirstorisis smoothing in grid_x, grid_y */ void next_histrs(void) { extern WORD gel_input; int divs; int i; int n; register Point *p; long x,y; p = hr_buf+hr_n; p->x = grid_x; p->y = grid_y; n = hr_n; hr_n -= 1; if (hr_n < 0) hr_n = HSZ-1; if (gel_input) { x = y = 0; divs = 0; i = HSZ; while (--i>=0) { if (n>=HSZ) n = 0; p = hr_buf+n; n++; x<<=1; y<<=1; divs<<=1; x+= p->x; y+= p->y; divs += 1; } grid_x = (x+divs/2)/divs; grid_y = (y+divs/2)/divs; } } reuse_input() { reuse = 1; } hide_mouse() { mouse_on = 0; } show_mouse() { mouse_on = 1; } #define dcursor() {scursor();ccursor();} get_gridxy() { if (vs.use_grid) { grid_x = ((grid_x - vs.gridx + vs.gridw/2)/vs.gridw*vs.gridw+vs.gridx); grid_y = ((grid_y - vs.gridy + vs.gridh/2)/vs.gridh*vs.gridh+vs.gridy); if (grid_x < 0) grid_x = 0; if (grid_x >= XMAX) grid_x = XMAX-1; if (grid_y < 0) grid_y = 0; if (grid_y >= YMAX) grid_y = YMAX-1; } } check_input() { dcursor(); flip_video(); c_poll_input(); ucursor(); } static vtinput(count, mm) WORD count, mm; { recordall = 0; dcursor(); flip_video(); while (--count >= 0) { mwaits(); c_poll_input(); if ((mm && mouse_moved) || key_hit) break; } ucursor(); recordall = 1; } vsync_input(count) WORD count; { vtinput(count, 1); } timed_input(count) WORD count; { vtinput(count, 0); } wait_input() { recordall = 0; dcursor(); flip_video(); for (;;) { c_wait_input(); if (mouse_moved || key_hit) break; mwaits(); } ucursor(); recordall = 1; } wait_penup() { recordall = 0; dcursor(); flip_video(); for (;;) { if (!PDN) break; mwaits(); c_wait_input(); } ucursor(); recordall = 1; } #ifdef SLUFFED wait_rup() { recordall = 0; dcursor(); flip_video(); for (;;) { if (!RDN) break; mwaits(); c_wait_input(); } ucursor(); recordall = 1; } #endif /* SLUFFED */ wait_click() { clickonly = 1; if (mouse_on) dcursor(); flip_video(); for (;;) { c_wait_input(); mwaits(); if (key_hit || RJSTDN || PJSTDN) break; } clickonly = 0; if (mouse_on) ucursor(); } static char umouse[256]; static WORD sx, sy; void scursor(void) { if (!zoomcursor) { int w = 16; int h = 16; int srcx = uzx-8; int srcy = uzy-8; int dstx = 0; int dsty = 0; if (clipblit2(&w, &h, &srcx, &srcy, vf.w, vf.h, &dstx, &dsty, 16, 16)) { blit8(w, h, srcx, srcy, vf.p, vf.bpr, dstx, dsty, umouse, 16); sx = uzx-8; sy = uzy-8; } } else { sx = uzx/vs.zoomscale + vs.zoomx - 8; sy = uzy/vs.zoomscale + vs.zoomy - 8; } } ucursor() { if (zoomcursor) { unzoom_bitmap_blit(16, 16, 0, 0, white_cursor, 2, sx, sy); unzoom_bitmap_blit(16, 16, 0, 0, black_cursor, 2, sx, sy); if (brushcursor) unzoom_bitmap_blit(16, 16, 0, 0, brushcursor, 2, sx, sy); } else blit8(16,16,0,0,umouse,16, sx,sy,vf.p,vf.bpr); } void ccursor(void) { if (zoomcursor) { if (brushcursor) zoom_bitmap_blit(16, 16, 0, 0, brushcursor, 2, sx, sy, vs.ccolor); zoom_bitmap_blit(16, 16, 0, 0, black_cursor, 2, sx, sy, sblack); zoom_bitmap_blit(16, 16, 0, 0, white_cursor, 2, sx, sy, sbright); } else { if (brushcursor) a1blit(16, 16, 0, 0, brushcursor, 2, sx, sy, vf.p, vf.bpr, vs.ccolor); a1blit(16, 16, 0, 0, black_cursor, 2, sx, sy, vf.p, vf.bpr, sblack); a1blit(16, 16, 0, 0, white_cursor, 2, sx, sy, vf.p, vf.bpr, sbright); } } static void zoom_bitmap_blit(WORD w, WORD h, WORD sx, WORD sy, PLANEPTR spt, WORD sbpr, WORD dx, WORD dy, WORD color) { spt += sy*sbpr; while (--h >= 0) { zo_line(w, spt, sx, dx, dy, color); dy++; spt += sbpr; } } static void zo_line(int j, PLANEPTR spt, int xs, int xd, int yd, int color) { while (--j >= 0) { if (spt[xs>>3] & bmasks[xs&7] ) upd_zoom_dot(xd,yd,color); xs++; xd++; } } static void unzoom_bitmap_blit(WORD w, WORD h, WORD sx, WORD sy, PLANEPTR spt, WORD sbpr, WORD dx, WORD dy) { spt += sy*sbpr; while (--h >= 0) { unzo_line(w, spt, sx, dx, dy); dy++; spt += sbpr; } } static void unzo_line(int j, PLANEPTR spt, int xs, int xd, int yd) { PLANEPTR p; p = zoom_form->p; while (--j >= 0) { if (spt[xs>>3] & bmasks[xs&7] ) upd_zoom_dot(xd,yd,getd(p,xd,yd)); xs++; xd++; } } wait_sync() { wait_novblank(); wait_vblank(); } wait_a_jiffy(j) int j; { long l; l = get80hz()+j; for (;;) { if (get80hz() >= l) break; mwaits(); } } /* wait until a certain time. Return 1 if timed out. Return 0 if they hit a key or right button while waiting. Fairly severly complicated by maintaining macros while this is happening (since may call c_input a variable number of times... */ wait_til(time) long time; { int ok; int odef; ok = 1; inwaittil = 1; /* effectively squelch macro activity */ for (;;) { c_poll_input(); if (RDN || key_hit) { ok = 0; break; } if (time <= get80hz()) { break; } wait_sync(); } inwaittil = 0; /* make macros happen again */ put_macro(0); /* write out last input state into macro file */ if (usemacro) { c_poll_input(); /* read last input state from macro file */ if (RDN || key_hit) { ok = 0; } } return(ok); }
2.21875
2
2024-11-18T22:25:18.030056+00:00
2013-08-17T13:59:22
159ab258e6e5a8930ca1a706cd75b2e402d14115
{ "blob_id": "159ab258e6e5a8930ca1a706cd75b2e402d14115", "branch_name": "refs/heads/master", "committer_date": "2013-08-17T13:59:22", "content_id": "2a1c7beb0b15f803bb04fb28d732ab8efe4b2a1c", "detected_licenses": [ "MIT" ], "directory_id": "e896fff489e393865421db3ad9760233805c9385", "extension": "h", "filename": "trace.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": 1333, "license": "MIT", "license_type": "permissive", "path": "/trace.h", "provenance": "stackv2-0115.json.gz:116592", "repo_name": "Berrrry/itrace-1", "revision_date": "2013-08-17T13:59:22", "revision_id": "774d35add915fb8e03f503fe909ce2bc63be58d7", "snapshot_id": "ae0b2bc81a9fca714f9beaa94ca965527bdbbcf8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Berrrry/itrace-1/774d35add915fb8e03f503fe909ce2bc63be58d7/trace.h", "visit_date": "2018-05-05T09:12:08.147394" }
stackv2
/* * itrace * * Trace specific routines header * */ #ifndef ITRACE_TRACE_H #define ITRACE_TRACE_H #include <sys/types.h> #include <sys/user.h> #include <stdint.h> #define iprintf(fmt, ...) do { if (tracee.flags & QUIET_MODE) break; printf(fmt, ##__VA_ARGS__); } while(0) /* * Possible flags passed to itrace */ typedef enum { SHOW_REGISTERS = 1<<0, /* -r */ SHOW_STACK = 1<<1, /* -s */ SHOW_COMMENTS = 1<<2, /* -C */ SHOW_MAPS = 1<<3, /* -m */ IGNORE_LIBS = 1<<4, /* -i */ SHOW_COUNT = 1<<5, /* -I */ QUIET_MODE = 1<<6 /* -q */ } trace_flags; /* * General information of tracee and argument options */ typedef struct { const char *prog; /* program to start and trace */ char * const *prog_args; /* program arguments */ pid_t pid; /* pid of tracee program */ uintptr_t offset; /* eip offset to start tracing */ unsigned int num_inst; /* Max number of instruction to trace */ int syntax; /* Assembly syntax (0 = at&t, 1 = intel) */ int flags; /* Flags to handle options */ } trace_info; pid_t trace_pid(); pid_t trace_program(); void trace_loop(); extern trace_info tracee; #endif /* ITRACE_TRACE_H */
2.125
2
2024-11-18T22:25:18.163439+00:00
2021-09-25T20:29:37
e822289ff77f00dbdbf06e23189fd8d3eb0f6394
{ "blob_id": "e822289ff77f00dbdbf06e23189fd8d3eb0f6394", "branch_name": "refs/heads/main", "committer_date": "2021-09-25T20:29:37", "content_id": "19882a90db10edbe194fd759dbbcb9e6aa2c253c", "detected_licenses": [ "MIT" ], "directory_id": "9548348a33c31b475cf5d6c2b3020e6a7e14de0c", "extension": "c", "filename": "ListaProva2Exercicio7.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": 1518, "license": "MIT", "license_type": "permissive", "path": "/EXERCICIOS/Respostas_ListaExerciciosProva2-IP_2020-2/ListaExerciciosProva2-IP_2020-2/ListaProva2Exercicio7.c", "provenance": "stackv2-0115.json.gz:116852", "repo_name": "ZeAlysson/Introducao-a-Programacao-em-C", "revision_date": "2021-09-25T20:29:37", "revision_id": "1665db3a0ae337afdaffe3a6fd97c8b9e7c3cf9e", "snapshot_id": "3f4435020725704cf318f8b1134f12e24205daf2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ZeAlysson/Introducao-a-Programacao-em-C/1665db3a0ae337afdaffe3a6fd97c8b9e7c3cf9e/EXERCICIOS/Respostas_ListaExerciciosProva2-IP_2020-2/ListaExerciciosProva2-IP_2020-2/ListaProva2Exercicio7.c", "visit_date": "2023-08-15T14:57:08.265052" }
stackv2
#include <stdio.h> #include <string.h> /* Faça um programa em C que leia uma string e depois leia um valor inteiro entre 1 e 50 (faça um laço de repetição que garante esse valor). O valor inteiro será utilizado como "senha" para "codificar" a string inserida, em uma implementação rudimentar da chamada "shift cypher" (cifra de deslocamento). Some o valor inteiro aos caracteres alfabéticos da String inserida e depois exiba a string. Depois, solicite um outro valor inteiro entre 0 e 50 (também com laço de repetição) e use o novo valor inteiro para "decodificar" a string, decrementando o valor inteiro de cada caractere. Exemplo: String digitada: "Ola mundo" Inteiro digitado: 3 String codificada: "Rod pxqgr" */ int main(void) { char string_codigo[30]; int senha; printf("Digite uma frase: "); gets(string_codigo); do { printf("Digite a senha: "); scanf("%d", &senha); } while((senha<1)||(senha>50)); for (int i = 0; i < strlen(string_codigo); i++) { if ( ((string_codigo[i] >= 65) && (string_codigo[i] <= 90)) || ((string_codigo[i] >= 97) && (string_codigo[i] <= 122)) ) { string_codigo[i] += senha; } } printf("String codificada: %s\n", string_codigo); for (int i = 0; i < strlen(string_codigo); i++) { if (string_codigo[i] != 32) string_codigo[i] -= senha; } printf("String decodificada: %s\n", string_codigo); return 0; }
3.484375
3
2024-11-18T22:25:18.322454+00:00
2015-07-28T10:00:17
80687d12b52e9a8d820c01f8c70f43c9ef731508
{ "blob_id": "80687d12b52e9a8d820c01f8c70f43c9ef731508", "branch_name": "refs/heads/master", "committer_date": "2015-07-28T10:00:17", "content_id": "c37c3f4c4f7df14e5d9db18386ac2530b98a39ac", "detected_licenses": [ "MIT" ], "directory_id": "13eebb17e400baec5696aba530d6f251cb69978c", "extension": "c", "filename": "im-conn.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 39498675, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3247, "license": "MIT", "license_type": "permissive", "path": "/src/im-conn.c", "provenance": "stackv2-0115.json.gz:116982", "repo_name": "tuhuayuan/imcore", "revision_date": "2015-07-28T10:00:17", "revision_id": "f9a4ef57041f78416cb7146be46e3c5a1a902a65", "snapshot_id": "7063c53638004feac60447499f8de21c4b98ff9c", "src_encoding": "GB18030", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tuhuayuan/imcore/f9a4ef57041f78416cb7146be46e3c5a1a902a65/src/im-conn.c", "visit_date": "2021-01-02T08:56:49.018960" }
stackv2
#include "im-inl.h" static void _xmpp_conn_handler(xmpp_conn_t *conn, xmpp_conn_event_t status, const int error, xmpp_stream_error_t *stream_error, void *userdata); static void _im_conn_pre_free(im_conn_t *conn); im_conn_t *im_conn_new(const char *host, const char *username, const char *password, im_conn_state_cb statecb, im_conn_recive_cb msgcb, void *userdate) { im_conn_t *conn = NULL; assert(username && password && statecb && msgcb); if (!username || !password || !statecb || !msgcb) return NULL; bool done = false; // 开始分配内存 do { conn = safe_mem_calloc(sizeof(im_conn_t), NULL); if (!conn) break; conn->signal_thread = im_thread_new(); conn->work_thread = im_thread_new(); if (!conn->signal_thread && !conn->work_thread) break; // xmpp核心工作在信号线程 conn->xmpp_ctx = xmpp_ctx_new(conn->signal_thread, NULL); if (!conn->xmpp_ctx) break; conn->xmpp_conn = xmpp_conn_new(conn->xmpp_ctx); if (!conn->xmpp_conn) break; if (host) { conn->xmpp_host = im_strndup(host, 256); if (!conn->xmpp_host) break; } done = true; } while (0); // 内存分配失败 if (!done && conn) { _im_conn_pre_free(conn); return NULL; } // 内存分配成功, 初始化值 conn->statecb = statecb; conn->msgcb = msgcb; conn->userdata = userdate; // 设置xmpp连接 xmpp_conn_t *xmpp_conn = conn->xmpp_conn; xmpp_conn_set_jid(xmpp_conn, username); xmpp_conn_set_pass(xmpp_conn, password); conn->state = IM_STATE_INIT; return conn; } IMCORE_API int im_conn_open(im_conn_t *conn) { if (conn->state != IM_STATE_INIT) { return -1; } xmpp_connect_client(conn->xmpp_conn, conn->xmpp_host, 5222, _xmpp_conn_handler, conn); // 启动信号线程 im_thread_start(conn->signal_thread, conn); // 启动工作线程 im_thread_start(conn->work_thread, conn); return 0; } static void _im_conn_pre_free(im_conn_t *conn) { } static void _xmpp_conn_handler(xmpp_conn_t *xmpp_conn, xmpp_conn_event_t status, const int error, xmpp_stream_error_t *stream_error, void *userdata) { im_conn_t *conn = (im_conn_t*)userdata; if (status == XMPP_CONN_CONNECT) { // 注册消息<message></message>处理器 xmpp_handler_add(xmpp_conn, msg_text_handler, NULL, "message", NULL, conn); // 注册file消息处理器 xmpp_id_handler_add(xmpp_conn, msg_file_handler, IM_MSG_FILE_ID, conn); // 通知连接成功 conn->statecb(conn, IM_STATE_OPEN, 0, conn->userdata); } else if (status == XMPP_CONN_DISCONNECT) { conn->statecb(conn, IM_STATE_CLOSED, 0, conn->userdata); } else if (status == XMPP_CONN_FAIL) { conn->statecb(conn, IM_STATE_CLOSED, -1, conn->userdata); } }
2.359375
2
2024-11-18T22:25:18.380624+00:00
2020-06-11T02:40:12
0df9b8d2cfb38a2bee4452f4014bac51a94751f0
{ "blob_id": "0df9b8d2cfb38a2bee4452f4014bac51a94751f0", "branch_name": "refs/heads/master", "committer_date": "2020-06-11T02:40:12", "content_id": "a4d8abf09aa30fe449e04b78aa3719e247818c18", "detected_licenses": [ "MIT" ], "directory_id": "4fcd9ea0f6862ef2fe0d2aaf1d812b9d20c1ddcd", "extension": "c", "filename": "ltg.c", "fork_events_count": 0, "gha_created_at": "2020-06-09T00:52:34", "gha_event_created_at": "2020-06-09T00:52:34", "gha_language": null, "gha_license_id": "MIT", "github_id": 270867852, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4087, "license": "MIT", "license_type": "permissive", "path": "/src/exec/ltg.c", "provenance": "stackv2-0115.json.gz:117111", "repo_name": "ReactiveXYZ-Dev/janus", "revision_date": "2020-06-11T02:40:12", "revision_id": "bc240f6e7f0c3f69ad1a39ac215750cf24af83cf", "snapshot_id": "5820857a76ff9a0e9b4e477a7379e30c6cf00852", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ReactiveXYZ-Dev/janus/bc240f6e7f0c3f69ad1a39ac215750cf24af83cf/src/exec/ltg.c", "visit_date": "2022-10-31T09:30:03.220253" }
stackv2
#include <math.h> #include "algo/array.h" #include "config.h" #include "network.h" #include "util/log.h" #include "exec.h" #include "exec/ltg.h" #define TO_LTG(e) struct exec_ltg_t *ltg = (struct exec_ltg_t *)(e); /* Comparison function for sorting critical paths from longest to shortest */ static int _cp_cmp(void const *v1, void const *v2) { struct exec_critical_path_t *t1 = (struct exec_critical_path_t *)v1; struct exec_critical_path_t *t2 = (struct exec_critical_path_t *)v2; bw_t b1 = t1->bandwidth / t1->num_switches; bw_t b2 = t2->bandwidth / t2->num_switches; if (b1 > b2) return -1; else if (b1 < b2) return 1; return 0; } static void _exec_ltg_validate(struct exec_t *exec, struct expr_t const *expr) { TO_LTG(exec); ltg->trace = traffic_matrix_trace_load(400, expr->traffic_test); if (ltg->trace == 0) panic("Couldn't load the traffic matrix file: %s", expr->traffic_test); if (expr->criteria_time == 0) panic_txt("Time criteria not set."); struct traffic_matrix_trace_iter_t *iter = ltg->trace->iter(ltg->trace); ltg->plan = exec_critical_path_analysis(exec, expr, iter, iter->length(iter)); } /* Creates fixed plans by distributing the change as evenly as it can over the * upgrade interval. */ static risk_cost_t _exec_ltg_best_plan_at( struct exec_t *exec, struct expr_t const *expr, trace_time_t at) { TO_LTG(exec); struct exec_critical_path_stats_t *plan = ltg->plan; /* Sort the pods/core change so that the longest critical path comes first */ /* TODO: This is useless in the current iteration of pug, you just spread the * change as evenly as possible so the critical path analysis is close to * useless */ // qsort(plan->paths, plan->num_paths, sizeof(struct exec_critical_path_t), _cp_cmp); */ struct jupiter_located_switch_t **sws = malloc( sizeof(struct jupiter_located_switch_t *) * expr->nlocated_switches); unsigned nsteps = expr->criteria_time->steps; struct mop_t **mops = malloc(sizeof(struct mop_t *) * nsteps); /* TODO: This should somehow use expr->criteria_time->acceptable but right now * it relies on criteria_time->steps */ for (uint32_t i = 0; i < nsteps; ++i) { unsigned idx = 0; for (uint32_t j = 0; j < plan->num_paths; ++j) { int nsws = ceil(((double)plan->paths[j].num_switches)/(double)nsteps); for (uint32_t k = 0; k < nsws; ++k) { sws[idx++] = plan->paths[j].sws[k]; } } mops[i] = jupiter_mop_for(sws, idx); #if DEBUG_MODE char *exp = mops[i]->explain(mops[i], expr->network); info("MOp explanation: %s", exp); free(exp); #endif } risk_cost_t cost = exec_plan_cost(exec, expr, mops, nsteps, at); free(sws); return cost; } static struct exec_output_t * _exec_ltg_runner(struct exec_t *exec, struct expr_t const *expr) { struct exec_output_t *res = malloc(sizeof(struct exec_output_t)); struct exec_result_t result = {0}; res->result = array_create(sizeof(struct exec_result_t), 10); for (uint32_t i = expr->scenario.time_begin; i < expr->scenario.time_end; i += expr->scenario.time_step) { trace_time_t at = i; risk_cost_t actual_cost = _exec_ltg_best_plan_at(exec, expr, at); info("[%4d] Actual cost of the best plan (%02d) is: %4.3f : %4.3f", at, expr->criteria_time->steps, actual_cost, actual_cost); result.cost = actual_cost; result.description = 0; result.num_steps = expr->criteria_time->steps; result.at = i; array_append(res->result, &result); } return res; } static void _exec_ltg_explain(struct exec_t const *exec) { text_block_txt( "LTG (MRC in the paper) divides an upgrade plan over the available\n" "planning intervals. The length of the planning interval is set \n" "through the criteria-time in the .ini file.\n"); } struct exec_t *exec_ltg_create(void) { struct exec_t *exec = malloc(sizeof(struct exec_ltg_t)); exec->net_dp = 0; exec->validate = _exec_ltg_validate; exec->run = _exec_ltg_runner; exec->explain = _exec_ltg_explain; return exec; }
2.125
2
2024-11-18T22:25:18.440511+00:00
2015-06-25T09:14:18
f6be9da9469702f43adc2dbd0370218427838f4f
{ "blob_id": "f6be9da9469702f43adc2dbd0370218427838f4f", "branch_name": "refs/heads/master", "committer_date": "2015-06-25T09:14:18", "content_id": "1b7d4ae29264d278090df8b4d3df3f8fa04ac552", "detected_licenses": [ "MIT" ], "directory_id": "8f276f1359b7a82f5f93041178683465451849c8", "extension": "c", "filename": "vector.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": 723, "license": "MIT", "license_type": "permissive", "path": "/usr/as/vector.c", "provenance": "stackv2-0115.json.gz:117240", "repo_name": "nsauzede/xv6", "revision_date": "2015-06-25T09:14:18", "revision_id": "94d02ecb2b9492365574f2166cf29ce5a170abf5", "snapshot_id": "f5eab1989ce0ef1322680c782197661083f14ff1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nsauzede/xv6/94d02ecb2b9492365574f2166cf29ce5a170abf5/usr/as/vector.c", "visit_date": "2023-03-24T15:40:20.142495" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include "vector.h" #define max(a,b) (a) > (b) ? (a) : (b) Vector * vec_create(int l) { Vector *v = malloc(sizeof(Vector)); if (l != 0) v->body = malloc(sizeof(void *) * l); v->sz = 0; v->nalloc = l; return v; } void * vec_get(Vector *v, int idx) { assert(idx < v->sz); return v->body[idx]; } static void expand(Vector *v, int i) { int n; if (v->sz + i < v->nalloc) { return; } n = v->nalloc + max(v->nalloc, i); v->body = realloc(v->body, n); assert(!v->body); v->nalloc = n; } void vec_push(Vector *v, void *val) { expand(v, 1); v->body[v->sz++] = val; } int vec_lengh(Vector *v) { return v->sz; }
2.9375
3
2024-11-18T22:25:18.503870+00:00
2018-03-17T03:44:37
6859dbb32eb90d15f7c11e27833d382a3f6bfd4a
{ "blob_id": "6859dbb32eb90d15f7c11e27833d382a3f6bfd4a", "branch_name": "refs/heads/master", "committer_date": "2018-03-17T03:44:37", "content_id": "77cf5247d92be2eac84fe4f86481b855cab8ea70", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "bb45db887bc596e949918e8613c62cc1f7cf9e2e", "extension": "c", "filename": "ircman.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 101529078, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1422, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/contrib/ircman.c", "provenance": "stackv2-0115.json.gz:117371", "repo_name": "asterIRC/MERE5", "revision_date": "2018-03-17T03:44:37", "revision_id": "1f5458ec13daf3c90877053dacb9be2bbc694bd1", "snapshot_id": "0bca414a8cd844ebbe5340505339a8768e43f61e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/asterIRC/MERE5/1f5458ec13daf3c90877053dacb9be2bbc694bd1/contrib/ircman.c", "visit_date": "2021-01-20T07:18:07.192964" }
stackv2
/* ircman.c by David N. Welton <davidw@efn.org> */ /* This is free software under the terms of the GNU GPL */ #include <stdio.h> #include <stdlib.h> int main (int argc, char *argv[]) { FILE *fd; FILE *pgr; char *pager; int ch; int boldflag = 0; int revflag = 0; int ulflag = 0; if (argv[1] != NULL) fd = fopen (argv[1], "r"); else { fprintf(stderr, "Usage: %s file\n", argv[0]); exit (1); } if (fd == NULL) { fprintf(stderr, "Could not open %s\n", argv[1]); exit (1); } if(pager = getenv("PAGER")) { pgr = popen(pager, "w"); if (pgr == NULL) { fputs("Danger, will robinson\n", stderr); exit (1); } } else { pgr = stdout; } while((ch = fgetc(fd)) != EOF ) { switch (ch) { case '^V': revflag ^= 1; continue; break; case '^B': boldflag ^= 1; continue; break; case '^_': ulflag ^= 1; continue; break; } if (revflag) { putc(ch,pgr); putc(',pgr); putc(ch,pgr); } else if (boldflag) { putc(ch,pgr); putc(',pgr); putc(ch,pgr); } else if (ulflag) { putc('_',pgr); putc(',pgr); putc(ch,pgr); } else putc(ch,pgr); } close(fd); pclose(pgr); }
2.203125
2
2024-11-18T22:25:18.575071+00:00
2019-01-27T20:07:25
7baadeb6508646f7a962ca7e675af704ed6298f4
{ "blob_id": "7baadeb6508646f7a962ca7e675af704ed6298f4", "branch_name": "refs/heads/master", "committer_date": "2019-01-27T20:46:01", "content_id": "b01fe50b02b5d2f562841c01d9fc304863405738", "detected_licenses": [ "MIT" ], "directory_id": "cd6ab0f034ffbb6535963174a8601f0d792fe42f", "extension": "c", "filename": "pagefault.c", "fork_events_count": 0, "gha_created_at": "2016-09-01T04:02:55", "gha_event_created_at": "2016-09-01T04:02:55", "gha_language": null, "gha_license_id": null, "github_id": 67096747, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1992, "license": "MIT", "license_type": "permissive", "path": "/kernel/pagefault.c", "provenance": "stackv2-0115.json.gz:117501", "repo_name": "cstanfill/silvos", "revision_date": "2019-01-27T20:07:25", "revision_id": "3ced1897043d85c312a5cbafa0f5fefc373a9e75", "snapshot_id": "d4cbe0a8a86761ff0b21f5d1775b997f69d14c37", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cstanfill/silvos/3ced1897043d85c312a5cbafa0f5fefc373a9e75/kernel/pagefault.c", "visit_date": "2020-04-04T21:41:53.287645" }
stackv2
#include "pagefault.h" #include "com.h" #include "ipc.h" #include "memory-map.h" #include "threads.h" #include "util.h" #include <stddef.h> #include <stdint.h> static int check_addr (const void *low, const void *high) { if ((uint64_t)low > (uint64_t)high) { return -1; } if ((uint64_t)high > LOC_USERZONE_TOP) { return -1; } return 0; } jmp_buf for_copying; int is_copying; void pagefault_handler_copy (void) { if (is_copying) { longjmp(for_copying, -1); } } void __attribute__((noreturn)) pagefault_handler_user (uint64_t addr) { if (!running_tcb) { com_printf("Kernel page fault at %p, no running thread! Panic!\n", (void *)addr); panic("Page fault with no running thread!"); } running_tcb->faulting = 1; ipc_msg exception_message = { .addr = running_tcb->handler_thread_id, .r1 = addr, .r2 = running_tcb->saved_registers.status_code, }; call_if_possible(exception_message); com_printf("Unhandled user page fault at %p, running thread is 0x%02X.\n", (void *)addr, running_tcb->thread_id); thread_exit(); } int copy_from_user (void *to, const void *from, size_t count) { const char *f = from; if (check_addr(f, f+count)) { return -1; } is_copying = 1; int res = setjmp(for_copying); if (res == 0) { memcpy(to, from, count); } is_copying = 0; return res; } int copy_to_user (void *to, const void *from, size_t count) { char *t = to; if (check_addr(t, t+count)) { return -1; } is_copying = 1; int res = setjmp(for_copying); if (res == 0) { memcpy(to, from, count); } is_copying = 0; return res; } int copy_string_from_user (void *to, const void *from, size_t max) { const char *f = from; if ((uint64_t)(f + max) > LOC_USERZONE_TOP) { max = LOC_USERZONE_TOP - (uint64_t)f; } if (check_addr(f, f+max)) { return -1; } is_copying = 1; int res = setjmp(for_copying); if (res == 0) { strncpy(to, from, max); } is_copying = 0; return res; }
2.671875
3
2024-11-18T22:25:18.632720+00:00
2020-08-21T07:14:04
47fe4fe7d933625fd28c693b8acf642b9f91cf43
{ "blob_id": "47fe4fe7d933625fd28c693b8acf642b9f91cf43", "branch_name": "refs/heads/master", "committer_date": "2020-08-21T07:14:04", "content_id": "e207012f18dbac5b5afb42e7f9430b7bf5e5abcd", "detected_licenses": [ "Apache-2.0" ], "directory_id": "336875f04df30a4c53528b825140b4fa20822d59", "extension": "c", "filename": "dynreg.c", "fork_events_count": 4, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 269563839, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 32264, "license": "Apache-2.0", "license_type": "permissive", "path": "/SDK/src/dynamic_register/dynreg.c", "provenance": "stackv2-0115.json.gz:117629", "repo_name": "zqd2000/evse-sdk-3.20", "revision_date": "2020-08-21T07:14:04", "revision_id": "eb373ea1345c811514c93f2f901d67b24ab721b6", "snapshot_id": "23c907f7d1585b5d6a0a7ce0adcd3a83e667a9e6", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/zqd2000/evse-sdk-3.20/eb373ea1345c811514c93f2f901d67b24ab721b6/SDK/src/dynamic_register/dynreg.c", "visit_date": "2022-12-04T13:06:16.688428" }
stackv2
/* * Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #include <stdio.h> #include "string.h" #include "infra_state.h" #include "infra_compat.h" #include "infra_types.h" #include "infra_defs.h" #include "infra_string.h" #include "infra_httpc.h" #include "infra_sha256.h" #include "dynreg_internal.h" #include "dynreg_api.h" #ifdef MQTT_DYNAMIC_REGISTER #include "dev_sign_api.h" #include "mqtt_api.h" #endif #define HTTP_RESPONSE_PAYLOAD_LEN (256) #define DYNREG_RANDOM_KEY_LENGTH (15) #define DYNREG_SIGN_LENGTH (65) #define DYNREG_SIGN_METHOD_HMACSHA256 "hmacsha256" typedef struct { char *payload; int payload_len; } dynreg_http_response_t; static int dynamic_register = 0; #if !defined(MQTT_DYNAMIC_REGISTER) static int _parse_string_value(char *payload, int *pos, int *start, int *end) { int idx = 0; for (idx = *pos + 1; idx < strlen(payload); idx++) { if (payload[idx] == '\"') { break; } } *start = *pos + 1; *end = idx - 1; *pos = idx; return 0; } static int _parse_dynreg_value(char *payload, char *key, int *pos, int *start, int *end) { int idx = 0; /* printf("=====%s\n",&payload[*pos]); */ if (memcmp(key, "code", strlen("code")) == 0) { for (idx = *pos; idx < strlen(payload); idx++) { if (payload[idx] < '0' || payload[idx] > '9') { break; } } *start = *pos; *end = idx - 1; *pos = *end; return 0; } else if (memcmp(key, "data", strlen("data")) == 0) { int bracket_cnt = 0; if (payload[*pos] != '{') { return -1; } for (idx = *pos; idx < strlen(payload); idx++) { if (payload[idx] == '{') { bracket_cnt++; } else if (payload[idx] == '}') { bracket_cnt--; } if (bracket_cnt == 0) { break; } } *start = *pos; *end = idx; *pos = *end; return 0; } else { if (payload[*pos] != '\"') { return -1; } return _parse_string_value(payload, pos, start, end); } /* return -1; */ } static int _parse_dynreg_result(char *payload, char *key, int *start, int *end) { int res = 0, idx = 0, pos = 0; for (idx = 0; idx < strlen(payload); idx++) { /* printf("loop start: %s\n",&payload[idx]); */ if (payload[idx] == '\"') { for (pos = idx + 1; pos < strlen(payload); pos++) { if (payload[pos] == '\"') { /* printf("key: %.*s\n",pos - idx - 1, &payload[idx+1]); */ break; } } if (pos == strlen(payload) || payload[pos + 1] != ':') { return -1; } pos += 2; res = _parse_dynreg_value(payload, key, &pos, start, end); if (res == 0 && memcmp(key, &payload[idx + 1], strlen(key)) == 0) { /* printf("value: %.*s\n",*end - *start + 1,&payload[*start]); */ return 0; } idx = pos; } } printf("exit 4\n"); return -1; } static int _calc_dynreg_sign( char product_key[IOTX_PRODUCT_KEY_LEN], char product_secret[IOTX_PRODUCT_SECRET_LEN], char device_name[IOTX_DEVICE_NAME_LEN], char random[DYNREG_RANDOM_KEY_LENGTH + 1], char sign[DYNREG_SIGN_LENGTH]) { int sign_source_len = 0; uint8_t signnum[32]; uint8_t *sign_source = NULL; const char *dynamic_register_sign_fmt = "deviceName%sproductKey%srandom%s"; /* Start Dynamic Register */ memset(random, 0, DYNREG_RANDOM_KEY_LENGTH + 1); memcpy(random, "8Ygb7ULYh53B6OA", strlen("8Ygb7ULYh53B6OA")); dynreg_info("Random Key: %s", random); /* Calculate SHA256 Value */ sign_source_len = strlen(dynamic_register_sign_fmt) + strlen(device_name) + strlen(product_key) + strlen(random) + 1; sign_source = dynreg_malloc(sign_source_len); if (sign_source == NULL) { dynreg_err("Memory Not Enough"); return STATE_SYS_DEPEND_MALLOC; } memset(sign_source, 0, sign_source_len); HAL_Snprintf((char *)sign_source, sign_source_len, dynamic_register_sign_fmt, device_name, product_key, random); utils_hmac_sha256(sign_source, strlen((const char *)sign_source), (uint8_t *)product_secret, strlen(product_secret), signnum); infra_hex2str(signnum, 32, sign); dynreg_free(sign_source); dynreg_info("Sign: %s", sign); return STATE_SUCCESS; } static int _recv_callback(char *ptr, int length, int total_length, void *userdata) { dynreg_http_response_t *response = (dynreg_http_response_t *)userdata; if (strlen(response->payload) + length > response->payload_len) { return -1; } memcpy(response->payload + strlen(response->payload), ptr, length); return length; } static int _fetch_dynreg_http_resp(char *request_payload, char *response_payload, iotx_http_region_types_t region, char device_secret[IOTX_DEVICE_SECRET_LEN]) { int res = 0; const char *domain = NULL; const char *url_format = "http://%s/auth/register/device"; char *url = NULL; int url_len = 0; const char *pub_key = NULL; void *http_handle = NULL; int port = 443; iotx_http_method_t method = IOTX_HTTP_POST; int timeout_ms = 10000; char *header = "Accept: text/xml,text/javascript,text/html,application/json\r\n" "Content-Type: application/x-www-form-urlencoded\r\n"; int http_recv_maxlen = HTTP_RESPONSE_PAYLOAD_LEN; dynreg_http_response_t response; int start = 0, end = 0, data_start = 0, data_end = 0; domain = g_infra_http_domain[region]; if (NULL == domain) { return STATE_USER_INPUT_HTTP_DOMAIN; } url_len = strlen(url_format) + strlen(domain) + 1; url = (char *)dynreg_malloc(url_len); if (NULL == url) { return STATE_SYS_DEPEND_MALLOC; } memset(url, 0, url_len); HAL_Snprintf(url, url_len, url_format, domain); memset(&response, 0, sizeof(dynreg_http_response_t)); response.payload = response_payload; response.payload_len = HTTP_RESPONSE_PAYLOAD_LEN; #ifdef SUPPORT_TLS { //extern const char *iotx_ca_crt; //pub_key = iotx_ca_crt; } #endif http_handle = wrapper_http_init(); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_URL, (void *)url); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_PORT, (void *)&port); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_METHOD, (void *)&method); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_HEADER, (void *)header); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_CERT, (void *)pub_key); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_TIMEOUT, (void *)&timeout_ms); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_RECVCALLBACK, (void *)_recv_callback); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_RECVMAXLEN, (void *)&http_recv_maxlen); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_RECVCONTEXT, (void *)&response); res = wrapper_http_perform(http_handle, request_payload, strlen(request_payload)); wrapper_http_deinit(&http_handle); if (res < STATE_SUCCESS) { dynreg_free(url); return res; } dynreg_free(url); dynreg_info("Http Response Payload: %s", response_payload); _parse_dynreg_result(response_payload, "errorCode", &start, &end); dynreg_info("Dynamic Register errorcode: %.*s", end - start + 1, &response_payload[start]); if (memcmp(&response_payload[start], "200", strlen("200")) != 0) { iotx_state_event(ITE_STATE_HTTP_COMM, STATE_HTTP_DYNREG_FAIL_RESP, &response_payload[start]); return STATE_HTTP_DYNREG_FAIL_RESP; } _parse_dynreg_result(response_payload, "data", &data_start, &data_end); /* dynreg_info("value: %.*s\n",data_end - data_start + 1,&response_payload[data_start]); */ _parse_dynreg_result(&response_payload[data_start + 1], "deviceSecret", &start, &end); dynreg_info("Dynamic Register Device Secret: %.*s", end - start + 1, &response_payload[data_start + 1 + start]); if (end - start + 1 > IOTX_DEVICE_SECRET_LEN) { return STATE_HTTP_DYNREG_INVALID_DS; } memcpy(device_secret, &response_payload[data_start + 1 + start], end - start + 1); return STATE_SUCCESS; } static int _fetch_custom_reg_http_resp(char *request_payload, char *response_payload, iotx_http_region_types_t region, char product_key[IOTX_PRODUCT_KEY_LEN], char device_name[IOTX_DEVICE_NAME_LEN], char device_secret[IOTX_DEVICE_SECRET_LEN]) { int res = 0; const char *domain = NULL; #if defined(PLATFORM_IS_DEBUG) const char *url_format = "http://%s/asset-web-serv-v5.3.0/registerService/getCertificateInfo"; #else const char *url_format = "http://%s/asset-web-api/registerService/getCertificateInfo"; #endif char *url = NULL; int url_len = 0; const char *pub_key = NULL; void *http_handle = NULL; #if defined(PLATFORM_IS_DEBUG) int port = 19843; #else int port = 11901; #endif iotx_http_method_t method = IOTX_HTTP_POST; int timeout_ms = 10000; char *header = "Accept: text/xml,text/javascript,text/html,application/json\r\n" "Content-Type: application/x-www-form-urlencoded\r\n"; int http_recv_maxlen = HTTP_RESPONSE_PAYLOAD_LEN; dynreg_http_response_t response; int start = 0, end = 0, data_start = 0, data_end = 0; domain = g_infra_http_domain[region]; if (NULL == domain) { return STATE_USER_INPUT_HTTP_DOMAIN; } url_len = strlen(url_format) + strlen(domain) + 1; url = (char *)dynreg_malloc(url_len); if (NULL == url) { return STATE_SYS_DEPEND_MALLOC; } memset(url, 0, url_len); HAL_Snprintf(url, url_len, url_format, domain); memset(&response, 0, sizeof(dynreg_http_response_t)); response.payload = response_payload; response.payload_len = HTTP_RESPONSE_PAYLOAD_LEN; #ifdef SUPPORT_TLS { //extern const char *iotx_ca_crt; //pub_key = iotx_ca_crt; } #endif http_handle = wrapper_http_init(); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_URL, (void *)url); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_PORT, (void *)&port); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_METHOD, (void *)&method); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_HEADER, (void *)header); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_CERT, (void *)pub_key); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_TIMEOUT, (void *)&timeout_ms); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_RECVCALLBACK, (void *)_recv_callback); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_RECVMAXLEN, (void *)&http_recv_maxlen); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_RECVCONTEXT, (void *)&response); res = wrapper_http_perform(http_handle, request_payload, strlen(request_payload)); wrapper_http_deinit(&http_handle); if (res < STATE_SUCCESS) { dynreg_free(url); return res; } dynreg_free(url); dynreg_info("Http Response Payload: %s", response_payload); _parse_dynreg_result(response_payload, "code", &start, &end); dynreg_info("Dynamic Register code: %.*s", end - start + 1, &response_payload[start]); if (memcmp(&response_payload[start], "200", strlen("200")) != 0) { iotx_state_event(ITE_STATE_HTTP_COMM, STATE_HTTP_DYNREG_FAIL_RESP, &response_payload[start]); return STATE_HTTP_DYNREG_FAIL_RESP; } _parse_dynreg_result(response_payload, "data", &data_start, &data_end); /* dynreg_info("value: %.*s\n",data_end - data_start + 1,&response_payload[data_start]); */ _parse_dynreg_result(&response_payload[data_start + 1], "productKey", &start, &end); dynreg_info("Dynamic Register Product Key: %.*s", end - start + 1, &response_payload[data_start + 1 + start]); if (end - start + 1 > IOTX_PRODUCT_KEY_LEN) { return STATE_HTTP_DYNREG_INVALID_DS; } memcpy(product_key, &response_payload[data_start + 1 + start], end - start + 1); _parse_dynreg_result(&response_payload[data_start + 1], "deviceName", &start, &end); dynreg_info("Dynamic Register Device Name: %.*s", end - start + 1, &response_payload[data_start + 1 + start]); if (end - start + 1 > IOTX_DEVICE_NAME_LEN) { return STATE_HTTP_DYNREG_INVALID_DS; } memcpy(device_name, &response_payload[data_start + 1 + start], end - start + 1); _parse_dynreg_result(&response_payload[data_start + 1], "deviceSecret", &start, &end); dynreg_info("Dynamic Register Device Secret: %.*s", end - start + 1, &response_payload[data_start + 1 + start]); if (end - start + 1 > IOTX_DEVICE_SECRET_LEN) { return STATE_HTTP_DYNREG_INVALID_DS; } memcpy(device_secret, &response_payload[data_start + 1 + start], end - start + 1); return STATE_SUCCESS; } static int _fetch_get_reg_code_http_resp(char *request_payload, char *response_payload, iotx_http_region_types_t region, char reg_code[IOTX_DEVICE_REG_CODE_LEN]) { int res = 0; const char *domain = NULL; #if defined(PLATFORM_IS_DEBUG) const char *url_format = "http://%s/asset-web-serv-v5.3.0/registerService/getRegisterCode"; #else const char *url_format = "http://%s/asset-web-api/registerService/getRegisterCode"; #endif char *url = NULL; int url_len = 0; const char *pub_key = NULL; void *http_handle = NULL; #if defined(PLATFORM_IS_DEBUG) int port = 19843; #else int port = 11901; #endif iotx_http_method_t method = IOTX_HTTP_POST; int timeout_ms = 10000; char *header = "Accept: text/xml,text/javascript,text/html,application/json\r\n" "Content-Type: application/x-www-form-urlencoded\r\n"; int http_recv_maxlen = HTTP_RESPONSE_PAYLOAD_LEN; dynreg_http_response_t response; int start = 0, end = 0, data_start = 0, data_end = 0; domain = g_infra_http_domain[region]; if (NULL == domain) { return STATE_USER_INPUT_HTTP_DOMAIN; } url_len = strlen(url_format) + strlen(domain) + 1; url = (char *)dynreg_malloc(url_len); if (NULL == url) { return STATE_SYS_DEPEND_MALLOC; } memset(url, 0, url_len); HAL_Snprintf(url, url_len, url_format, domain); memset(&response, 0, sizeof(dynreg_http_response_t)); response.payload = response_payload; response.payload_len = HTTP_RESPONSE_PAYLOAD_LEN; #ifdef SUPPORT_TLS { //extern const char *iotx_ca_crt; //pub_key = iotx_ca_crt; } #endif http_handle = wrapper_http_init(); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_URL, (void *)url); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_PORT, (void *)&port); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_METHOD, (void *)&method); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_HEADER, (void *)header); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_CERT, (void *)pub_key); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_TIMEOUT, (void *)&timeout_ms); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_RECVCALLBACK, (void *)_recv_callback); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_RECVMAXLEN, (void *)&http_recv_maxlen); wrapper_http_setopt(http_handle, IOTX_HTTPOPT_RECVCONTEXT, (void *)&response); res = wrapper_http_perform(http_handle, request_payload, strlen(request_payload)); wrapper_http_deinit(&http_handle); if (res < STATE_SUCCESS) { dynreg_free(url); return res; } dynreg_free(url); dynreg_info("Http Response Payload: %s", response_payload); _parse_dynreg_result(response_payload, "code", &start, &end); dynreg_info("Dynamic Register code: %.*s", end - start + 1, &response_payload[start]); if (memcmp(&response_payload[start], "200", strlen("200")) != 0) { iotx_state_event(ITE_STATE_HTTP_COMM, STATE_HTTP_DYNREG_FAIL_RESP, &response_payload[start]); return STATE_HTTP_DYNREG_FAIL_RESP; } _parse_dynreg_result(response_payload, "data", &data_start, &data_end); /* dynreg_info("value: %.*s\n",data_end - data_start + 1,&response_payload[data_start]); */ _parse_dynreg_result(&response_payload[data_start + 1], "registerCode", &start, &end); dynreg_info("device code get registerCode is: %.*s", end - start + 1, &response_payload[data_start + 1 + start]); if (end - start + 1 > IOTX_DEVICE_REG_CODE_LEN) { return STATE_HTTP_DYNREG_INVALID_DS; } memcpy(reg_code, &response_payload[data_start + 1 + start], end - start + 1); return STATE_SUCCESS; } int32_t _http_dynamic_register(iotx_http_region_types_t region, iotx_dev_meta_info_t *meta) { int res = 0, dynamic_register_request_len = 0; char sign[DYNREG_SIGN_LENGTH] = {0}; char random[DYNREG_RANDOM_KEY_LENGTH + 1] = {0}; const char *dynamic_register_format = "productKey=%s&deviceName=%s&random=%s&sign=%s&signMethod=%s"; char *dynamic_register_request = NULL; char *dynamic_register_response = NULL; if (strlen(meta->product_key) > IOTX_PRODUCT_KEY_LEN) { return STATE_USER_INPUT_PK; } if (strlen(meta->product_secret) > IOTX_PRODUCT_SECRET_LEN) { return STATE_USER_INPUT_PS; } if (strlen(meta->device_name) > IOTX_DEVICE_NAME_LEN) { return STATE_USER_INPUT_DN; } /* Calcute Signature */ res = _calc_dynreg_sign(meta->product_key, meta->product_secret, meta->device_name, random, sign); if (res < STATE_SUCCESS) { return res; } /* Assemble Http Dynamic Register Request Payload */ dynamic_register_request_len = strlen(dynamic_register_format) + strlen(meta->product_key) + strlen(meta->device_name) + strlen(random) + strlen(sign) + strlen(DYNREG_SIGN_METHOD_HMACSHA256) + 1; dynamic_register_request = dynreg_malloc(dynamic_register_request_len); if (dynamic_register_request == NULL) { return STATE_SYS_DEPEND_MALLOC; } memset(dynamic_register_request, 0, dynamic_register_request_len); HAL_Snprintf(dynamic_register_request, dynamic_register_request_len, dynamic_register_format, meta->product_key, meta->device_name, random, sign, DYNREG_SIGN_METHOD_HMACSHA256); dynamic_register_response = dynreg_malloc(HTTP_RESPONSE_PAYLOAD_LEN); if (dynamic_register_response == NULL) { dynreg_free(dynamic_register_request); return STATE_SYS_DEPEND_MALLOC; } memset(dynamic_register_response, 0, HTTP_RESPONSE_PAYLOAD_LEN); /* Send Http Request For Getting Device Secret */ res = _fetch_dynreg_http_resp(dynamic_register_request, dynamic_register_response, region, meta->device_secret); #ifdef INFRA_LOG_NETWORK_PAYLOAD dynreg_dbg("Downstream Payload:"); iotx_facility_json_print(dynamic_register_response, LOG_DEBUG_LEVEL, '<'); #endif dynreg_free(dynamic_register_request); dynreg_free(dynamic_register_response); if (res < STATE_SUCCESS) { return res; } return STATE_SUCCESS; } int32_t _http_custom_register(iotx_http_region_types_t region, iotx_dev_meta_info_t *meta) { int res = 0, custom_register_request_len = 0; //char sign[DYNREG_SIGN_LENGTH] = {0}; //char random[DYNREG_RANDOM_KEY_LENGTH + 1] = {0}; const char *custom_register_format = "deviceCode=%s&registerCode=%s&gunNo=%s"; char *custom_register_request = NULL; char *custom_register_response = NULL; const char *deviceCode = ""; const char *gunNo = ""; if (strlen(meta->device_reg_code) > IOTX_DEVICE_REG_CODE_LEN) { return STATE_USER_INPUT_DR; } custom_register_request_len = strlen(custom_register_format) + strlen(meta->device_reg_code) + strlen(deviceCode) + strlen(gunNo) + 1; custom_register_request = dynreg_malloc(custom_register_request_len); if (custom_register_request == NULL) { return STATE_SYS_DEPEND_MALLOC; } memset(custom_register_request, 0, custom_register_request_len); HAL_Snprintf(custom_register_request, custom_register_request_len, custom_register_format, deviceCode, meta->device_reg_code, gunNo); custom_register_response = dynreg_malloc(HTTP_RESPONSE_PAYLOAD_LEN); if (custom_register_response == NULL) { dynreg_free(custom_register_request); return STATE_SYS_DEPEND_MALLOC; } memset(custom_register_response, 0, HTTP_RESPONSE_PAYLOAD_LEN); /* Send Http Request For Getting Device Secret */ res = _fetch_custom_reg_http_resp(custom_register_request, custom_register_response, region, meta->product_key, meta->device_name, meta->device_secret); #ifdef INFRA_LOG_NETWORK_PAYLOAD dynreg_dbg("Downstream Payload:"); iotx_facility_json_print(custom_register_response, LOG_DEBUG_LEVEL, '<'); #endif dynreg_free(custom_register_request); dynreg_free(custom_register_response); if (res < STATE_SUCCESS) { return res; } return STATE_SUCCESS; } int32_t _http_get_regcode(iotx_http_region_types_t region, iotx_dev_meta_info_t *meta) { int res = 0, custom_register_request_len = 0; //char sign[DYNREG_SIGN_LENGTH] = {0}; //char random[DYNREG_RANDOM_KEY_LENGTH + 1] = {0}; const char *custom_register_format = "deviceCode=%s"; char *custom_register_request = NULL; char *custom_register_response = NULL; const char *deviceCode = "1"; if (strlen(deviceCode) > IOTX_DEVICE_UID_LEN) { return STATE_USER_INPUT_DR; } custom_register_request_len = strlen(custom_register_format) + strlen(meta->device_asset) + 1; custom_register_request = dynreg_malloc(custom_register_request_len); if (custom_register_request == NULL) { return STATE_SYS_DEPEND_MALLOC; } memset(custom_register_request, 0, custom_register_request_len); HAL_Snprintf(custom_register_request, custom_register_request_len, custom_register_format, meta->device_asset); custom_register_response = dynreg_malloc(HTTP_RESPONSE_PAYLOAD_LEN); if (custom_register_response == NULL) { dynreg_free(custom_register_request); return STATE_SYS_DEPEND_MALLOC; } memset(custom_register_response, 0, HTTP_RESPONSE_PAYLOAD_LEN); /* Send Http Request For Getting Device Secret */ //res = _fetch_custom_reg_http_resp(custom_register_request, custom_register_response, region, meta->product_key,meta->device_name,meta->device_secret); res = _fetch_get_reg_code_http_resp(custom_register_request, custom_register_response, region, meta->device_reg_code); #ifdef INFRA_LOG_NETWORK_PAYLOAD dynreg_dbg("Downstream Payload:"); iotx_facility_json_print(custom_register_response, LOG_DEBUG_LEVEL, '<'); #endif dynreg_free(custom_register_request); dynreg_free(custom_register_response); if (res < STATE_SUCCESS) { return res; } return STATE_SUCCESS; } #else static int _mqtt_dynreg_sign_password(iotx_dev_meta_info_t *meta_info, iotx_sign_mqtt_t *signout, char *rand) { char signsource[DEV_SIGN_SOURCE_MAXLEN] = {0}; uint16_t signsource_len = 0; const char sign_fmt[] = "deviceName%sproductKey%srandom%s"; uint8_t sign_hex[32] = {0}; signsource_len = strlen(sign_fmt) + strlen(meta_info->device_name) + 1 + strlen(meta_info->product_key) + strlen(rand) + 1; if (signsource_len >= DEV_SIGN_SOURCE_MAXLEN) { return STATE_MQTT_SIGN_SOURCE_BUF_SHORT; } memset(signsource, 0, signsource_len); memcpy(signsource, "deviceName", strlen("deviceName")); memcpy(signsource + strlen(signsource), meta_info->device_name, strlen(meta_info->device_name)); memcpy(signsource + strlen(signsource), "productKey", strlen("productKey")); memcpy(signsource + strlen(signsource), meta_info->product_key, strlen(meta_info->product_key)); memcpy(signsource + strlen(signsource), "random", strlen("random")); memcpy(signsource + strlen(signsource), rand, strlen(rand)); utils_hmac_sha256((const uint8_t *)signsource, strlen(signsource), (uint8_t *)meta_info->product_secret, strlen(meta_info->product_secret), sign_hex); infra_hex2str(sign_hex, 32, signout->password); return STATE_SUCCESS; } static int32_t _mqtt_dynreg_sign_clientid(iotx_dev_meta_info_t *meta_info, iotx_sign_mqtt_t *signout, char *rand) { const char *clientid1 = "|authType=register,random="; const char *clientid2 = ",signmethod=hmacsha256,securemode=2|"; uint32_t clientid_len = 0; clientid_len = strlen(meta_info->product_key) + 1 + strlen(meta_info->device_name) + strlen(clientid1) + strlen(rand) + strlen(clientid2) + 1; if (clientid_len >= DEV_SIGN_CLIENT_ID_MAXLEN) { return ERROR_DEV_SIGN_CLIENT_ID_TOO_SHORT; } memset(signout->clientid, 0, clientid_len); memcpy(signout->clientid, meta_info->product_key, strlen(meta_info->product_key)); memcpy(signout->clientid + strlen(signout->clientid), ".", strlen(".")); memcpy(signout->clientid + strlen(signout->clientid), meta_info->device_name, strlen(meta_info->device_name)); memcpy(signout->clientid + strlen(signout->clientid), clientid1, strlen(clientid1)); memcpy(signout->clientid + strlen(signout->clientid), rand, strlen(rand)); memcpy(signout->clientid + strlen(signout->clientid), clientid2, strlen(clientid2)); return STATE_SUCCESS; } void _mqtt_dynreg_topic_handle(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg) { int32_t res = 0; char *ds = (char *)pcontext; iotx_mqtt_topic_info_t *topic_info = (iotx_mqtt_topic_info_pt)msg->msg; const char *asterisk = "**********************"; switch (msg->event_type) { case IOTX_MQTT_EVENT_PUBLISH_RECEIVED: { /* print topic name and topic message */ char *device_secret = NULL; uint32_t device_secret_len = 0; if (memcmp(topic_info->ptopic, "/ext/register", strlen("/ext/register"))) { return; } /* parse secret */ res = infra_json_value((char *)topic_info->payload, topic_info->payload_len, "deviceSecret", strlen("deviceSecret"), &device_secret, &device_secret_len); if (res == STATE_SUCCESS) { memcpy(ds, device_secret + 1, device_secret_len - 2); memcpy(device_secret + 1 + 5, asterisk, strlen(asterisk)); dynreg_info("Topic : %.*s", topic_info->topic_len, topic_info->ptopic); dynreg_info("Payload: %.*s", topic_info->payload_len, topic_info->payload); } } break; default: break; } } int32_t _mqtt_dynamic_register(iotx_http_region_types_t region, iotx_dev_meta_info_t *meta) { void *pClient = NULL; iotx_mqtt_param_t mqtt_params; int32_t res = 0; uint32_t length = 0, rand = 0; char rand_str[9] = {0}; iotx_sign_mqtt_t signout; uint64_t timestart = 0, timenow = 0; char device_secret[IOTX_DEVICE_SECRET_LEN + 1] = {0}; memset(&signout, 0, sizeof(iotx_sign_mqtt_t)); /* setup hostname */ if (IOTX_HTTP_REGION_CUSTOM == region) { if (g_infra_mqtt_domain[region] == NULL) { return STATE_USER_INPUT_MQTT_DOMAIN; } length = strlen(g_infra_mqtt_domain[region]) + 1; if (length >= DEV_SIGN_HOSTNAME_MAXLEN) { return STATE_MQTT_SIGN_HOSTNAME_BUF_SHORT; } memset(signout.hostname, 0, DEV_SIGN_HOSTNAME_MAXLEN); memcpy(signout.hostname, g_infra_mqtt_domain[region], strlen(g_infra_mqtt_domain[region])); } else { length = strlen(meta->product_key) + strlen(g_infra_mqtt_domain[region]) + 2; if (length >= DEV_SIGN_HOSTNAME_MAXLEN) { return STATE_MQTT_SIGN_HOSTNAME_BUF_SHORT; } memset(signout.hostname, 0, DEV_SIGN_HOSTNAME_MAXLEN); memcpy(signout.hostname, meta->product_key, strlen(meta->product_key)); memcpy(signout.hostname + strlen(signout.hostname), ".", strlen(".")); memcpy(signout.hostname + strlen(signout.hostname), g_infra_mqtt_domain[region], strlen(g_infra_mqtt_domain[region])); } /* setup port */ signout.port = 443; /* setup username */ length = strlen(meta->device_name) + strlen(meta->product_key) + 2; if (length >= DEV_SIGN_USERNAME_MAXLEN) { return STATE_MQTT_SIGN_USERNAME_BUF_SHORT; } memset(signout.username, 0, DEV_SIGN_USERNAME_MAXLEN); memcpy(signout.username, meta->device_name, strlen(meta->device_name)); memcpy(signout.username + strlen(signout.username), "&", strlen("&")); memcpy(signout.username + strlen(signout.username), meta->product_key, strlen(meta->product_key)); /* password */ rand = HAL_Random(0xffffffff); infra_hex2str((unsigned char *)&rand, 4, rand_str); res = _mqtt_dynreg_sign_password(meta, &signout, rand_str); if (res < 0) { return res; } /* client id */ res = _mqtt_dynreg_sign_clientid(meta, &signout, rand_str); if (res < 0) { return res; } memset(&mqtt_params, 0, sizeof(iotx_mqtt_param_t)); mqtt_params.host = signout.hostname; mqtt_params.port = signout.port; mqtt_params.username = signout.username; mqtt_params.password = signout.password; mqtt_params.client_id = signout.clientid; mqtt_params.request_timeout_ms = 5000; mqtt_params.clean_session = 1; mqtt_params.keepalive_interval_ms = 60000; mqtt_params.read_buf_size = 1000; mqtt_params.write_buf_size = 1000; mqtt_params.handle_event.h_fp = _mqtt_dynreg_topic_handle; mqtt_params.handle_event.pcontext = device_secret; #ifdef SUPPORT_TLS { //extern const char *iotx_ca_crt; //mqtt_params.pub_key = iotx_ca_crt; } #endif pClient = wrapper_mqtt_init(&mqtt_params); if (pClient == NULL) { return STATE_MQTT_WRAPPER_INIT_FAIL; } res = wrapper_mqtt_connect(pClient); if (res < STATE_SUCCESS) { wrapper_mqtt_release(&pClient); return res; } timestart = HAL_UptimeMs(); while (1) { timenow = HAL_UptimeMs(); if (timenow < timestart) { timestart = timenow; } if (timestart - timenow >= MQTT_DYNREG_TIMEOUT_MS) { break; } wrapper_mqtt_yield(pClient, 200); if (strlen(device_secret) > 0) { break; } } if (strlen(device_secret) > 0) { res = STATE_SUCCESS; } else { res = STATE_HTTP_DYNREG_INVALID_DS; } wrapper_mqtt_release(&pClient); memcpy(meta->device_secret, device_secret, strlen(device_secret)); return res; } #endif int32_t IOT_Dynamic_Register(iotx_http_region_types_t region, iotx_dev_meta_info_t *meta) { #ifdef MQTT_DYNAMIC_REGISTER return _mqtt_dynamic_register(region, meta); #else //return _http_dynamic_register(region, meta); return _http_custom_register(region, meta); #endif } //设备唯一码换取注册码 int32_t IOT_Get_Regcode(iotx_http_region_types_t region, iotx_dev_meta_info_t *meta) { #ifdef MQTT_DYNAMIC_REGISTER return _mqtt_dynamic_register(region, meta); #else //return _http_dynamic_register(region, meta); return _http_get_regcode(region, meta); #endif } int IOCTL_FUNC(IOTX_IOCTL_SET_DYNAMIC_REGISTER, void *data) { if (data == NULL) { return FAIL_RETURN; } dynamic_register = *(int *)data; return SUCCESS_RETURN; } int IOCTL_FUNC(IOTX_IOCTL_GET_DYNAMIC_REGISTER, void *data) { if (data == NULL) { return FAIL_RETURN; } *(int *)data = dynamic_register; return SUCCESS_RETURN; }
2.15625
2
2024-11-18T22:25:19.212819+00:00
2020-09-27T11:24:36
354182753d8089241678b011b79d411153d6b1dc
{ "blob_id": "354182753d8089241678b011b79d411153d6b1dc", "branch_name": "refs/heads/master", "committer_date": "2020-09-27T11:24:36", "content_id": "c2fb1c2e6496dd5b2522804c0438ab32d5621023", "detected_licenses": [ "MIT" ], "directory_id": "ed2e817c2ba018b6b281460c5c6aaf8ad7e57088", "extension": "c", "filename": "File Handling - 02 .c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 290419208, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 522, "license": "MIT", "license_type": "permissive", "path": "/File Handling/File Handling - 02 .c", "provenance": "stackv2-0115.json.gz:117888", "repo_name": "Sabin63/C-Programming", "revision_date": "2020-09-27T11:24:36", "revision_id": "a65a52283904d7d5ec24e93c06e5538f5a88a9d3", "snapshot_id": "45cf51f8d8f899a33fd8672a585dc6f83f8778a5", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Sabin63/C-Programming/a65a52283904d7d5ec24e93c06e5538f5a88a9d3/File Handling/File Handling - 02 .c", "visit_date": "2022-12-20T13:25:25.464971" }
stackv2
// Reading from a file #include<stdio.h> int main() { FILE *fptr; int c, stock; char buffer[200],item[10]; float price; /* myfile.txt : Inventory \n 100 Widget 0.29 \n End of List */ fptr = fopen("myfile.txt","r"); fgets(buffer,20,fptr); /* read a line */ printf("%s\n",buffer); fscanf(fptr,"%d %s %f",&stock,item,&price); /* read data */ printf("%d %s %4.2f \n",stock,item,price); while((c = getc(fptr))!=EOF) /* read the rest of the file */ printf("%c",c); fclose(fptr); return 0; }
3.359375
3
2024-11-18T22:25:19.725458+00:00
2023-08-25T19:44:29
417d9112619adcc294b43b52154362f0cbfea298
{ "blob_id": "417d9112619adcc294b43b52154362f0cbfea298", "branch_name": "refs/heads/master", "committer_date": "2023-08-25T19:44:29", "content_id": "bd179a38b421aa83d081e350e026feb4fda262b6", "detected_licenses": [ "Apache-2.0" ], "directory_id": "a4b5d07647547513fbe47f4fd0f8badf08311d72", "extension": "c", "filename": "getline.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 114382891, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1232, "license": "Apache-2.0", "license_type": "permissive", "path": "/misc/c/getline.c", "provenance": "stackv2-0115.json.gz:118147", "repo_name": "bheckel/code", "revision_date": "2023-08-25T19:44:29", "revision_id": "71bf9029eef362c1a84119db17fee983cb4b95cf", "snapshot_id": "cdf9ff1324696e26744f3ce5ecdaadc7a4af1e2d", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/bheckel/code/71bf9029eef362c1a84119db17fee983cb4b95cf/misc/c/getline.c", "visit_date": "2023-09-01T08:51:24.320083" }
stackv2
/***************************************************************************** * Name: getline.c * * Summary: Demo of getting lines of stdin. See fgline.c for getting lines * from a file. * * Adapted: Thu, 11 Jan 2001 15:28:17 (Bob Heckel -- Steve Summit) * Modified: Sun 04 Aug 2002 10:46:58 (Bob Heckel) ***************************************************************************** */ #include <stdio.h> /* Read one line from standard input. * Does not return terminating \n in line. * Returns line length: 0 for empty line, EOF for end-of-file. * * Sample usage: while ( getline(line, MAXLINE ) != EOF ) { ... } * Get similar behavior from: while ( fgets(line, MAXLINE, stdin) ) { ... } */ int mygetline(char line[], int max) { int nch = 0; int c; max = max - 1; /* leave room for '\0' */ while ( (c = getchar()) != EOF ) { if ( c == '\n' ) break; if ( nch < max ) { line[nch] = c; nch = nch + 1; } } if ( c == EOF && nch == 0 ) return EOF; line[nch] = '\0'; return nch; } int main(void) { char line[80]; puts("Ctrl-c to exit."); while ( mygetline(line, 80) != EOF ) { fprintf(stderr,"ok xx%syy\n", line); } return 0; }
3.21875
3
2024-11-18T22:25:20.047410+00:00
2017-12-05T21:55:58
c7cda907e5b4ce3c059882589bfe406991531eb3
{ "blob_id": "c7cda907e5b4ce3c059882589bfe406991531eb3", "branch_name": "refs/heads/master", "committer_date": "2017-12-05T21:55:58", "content_id": "5c3cbb80884a016db026eb4c621126b355edeefe", "detected_licenses": [ "MIT" ], "directory_id": "769f8dc0d8e4703a3beb1b95c4fe441eaa12d9cf", "extension": "c", "filename": "filtragem.c", "fork_events_count": 0, "gha_created_at": "2017-11-08T12:34:26", "gha_event_created_at": "2017-12-05T21:55:59", "gha_language": "C", "gha_license_id": "MIT", "github_id": 109973691, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6173, "license": "MIT", "license_type": "permissive", "path": "/src/filtragem.c", "provenance": "stackv2-0115.json.gz:118406", "repo_name": "LSantos06/ProxyServer", "revision_date": "2017-12-05T21:55:58", "revision_id": "08025eb7fdbf263d8f9ad21e4ace2f26efbee1a1", "snapshot_id": "ba980f70801005bd17e8fc3df3abe063768f2fa1", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/LSantos06/ProxyServer/08025eb7fdbf263d8f9ad21e4ace2f26efbee1a1/src/filtragem.c", "visit_date": "2021-08-23T17:27:22.996985" }
stackv2
#include "../include/filtragem.h" FILE* abrindo_arquivo(char* nome_arquivo){ FILE *fp; fp = fopen(nome_arquivo, "r"); if(fp == NULL){ printf("Erro ao abrir o arquivo \n\n\n"); exit(0); } return fp; } int checkLists(char* nome_arquivo,char * mensagem){ char lista[SIZE_LISTA][MAX_STR]; int i=0, saida = 0; char procurado[strlen(mensagem)]; // zerando a string memset (procurado,'\0',strlen(mensagem)); strcpy (procurado,mensagem); FILE * fp = abrindo_arquivo(nome_arquivo); int aux,cnt=0; while (i<SIZE_LISTA && fgets(lista[i],MAX_STR,fp)!=NULL) { aux = strlen(lista[i])-2; //printf(" %s - %d\n",lista[i],strlen(lista[i])-2); if (strncasecmp(procurado,lista[i],aux)==0) { saida = 1; } i++; } // para ultimo pegar aux = strlen(lista[i-1]); if (strncasecmp(procurado,lista[i-1 ],aux)==0) { saida = 1; } fclose(fp); return saida; } //por enquanto retorna um int para indicar se ta ou nao ta proibido int filtragem_url(char * url) { // pre processamento do host ---- adicionando www. char host_www[500]; char www[504]= "www."; if(strncmp("www.",url,4) != 0) { strcpy(host_www,url); strcat(www,host_www); strcpy(url,www); } // primeiro verifica-se se esta na whiteList int aux_white,aux_black,aux_deny; aux_white = checkLists("whitelist.txt",url); aux_black= checkLists("blacklist.txt",url); // verificando se esta na url os termos proibidos aux_deny = denyterms_request(url); if(aux_white){ //printf("\nWHITE LIST OK --- ENCAMINHAR MENSAGEM %s \n",url); mensagem_log(url,ACCEPT_LOG); return 1; } // verificando se esta na lista negra else if(aux_black){ printf("\nESTA NA BLACK LIST --- REJEITAR MENSAGEM %s \n",url); mensagem_log(url,ERRO_LOG); return 0; }// se nao tiver em nenhuma da lista deve-se procurar por termos proibidos else if (aux_deny){ // se for 1 entao tem termos proibidos na url printf("\n\tdeny terms na URL --- REJEITAR MENSAGEM %s \n",url); mensagem_log(url,DENY_ERRO); return 0; }else{ //printf("\n\tNada %s \n",url); mensagem_log(url,NOT_FILTERED); return 1; } } int denyterms_request(char * request){ char * aux_s = malloc(MAX_STR*sizeof(char)); int * tamanho; tamanho = Length_denyterms(); int i_aux=0,k=0,i=0,j=0,qnt; qnt = tamanho[0]; for(j=1;j<=qnt;j++) { for(i=0;i < strlen(request);i++) { memset (aux_s,'\0',MAX_STR); if((strlen(request)) - i < tamanho[j] ){ break; } for(k=0,i_aux=i;k<tamanho[j];k++ ,i_aux++) { if(request[i_aux] == '+' || request[i_aux] == '-'){ aux_s[k] = ' '; }else{ aux_s[k] = request[i_aux]; } } //printf("%s - %d quita\n",aux_s,strlen(aux_s)); if (checkLists("denyterms.txt",aux_s)) { //printf("\nDENTRO IF \t\t DEBUG == %s /// %d\n",aux_s,tamanho[j]); free(aux_s); free(tamanho); return 1; } } } free(aux_s); free(tamanho); return 0; } int * Length_denyterms(){ // PADRAO INDICE ZERO - CONTEM A QUANTIDADE DE ELEMENTOS // O RESTO SAO OS VALORES FILE * fp = abrindo_arquivo("denyterms.txt"); char lista[SIZE_LISTA][MAX_STR]; int * vetor = malloc(SIZE_LISTA*sizeof(int)); int i=0; int j=1; while (i<SIZE_LISTA && fgets(lista[i],MAX_STR,fp)!=NULL) { vetor[j] = strlen(lista[i])-2; i++;j++; } vetor[0] = i; // para o ultimo termo do denyterms deve-se contar o ultimo elemento buga porcausa do EOF vetor[i]++; /*printf("\n OLA %d ----- %d\n",vetor[0],(strlen(lista[i])-1)); for(j = 0;j <= i; j++){ printf("\n\t\tVetor[%d] = %d",j,vetor[j]); } */ fclose(fp); return vetor; } int denyterms_body(char * body,char *url){ char * aux_s = malloc(MAX_DADO*sizeof(char)); int * tamanho; tamanho = Length_denyterms(); int i_aux=0,k=0,i=0,j=0,qnt; qnt = tamanho[0]; for(j=1;j<=qnt;j++) { for(i=0;i < strlen(body);i++) { memset (aux_s,'\0',MAX_STR); if((strlen(body)) - i < tamanho[j] ){ break; } for(k=0,i_aux=i;k<tamanho[j];k++ ,i_aux++) { aux_s[k] = body[i_aux]; } if (checkLists("denyterms.txt",aux_s)) { //printf("\nDENTRO IF \t\t DEBUG == %s /// %d\n",aux_s,tamanho[j]); mensagem_log_body(url,aux_s); free(aux_s); free(tamanho); return 1; } } } free(aux_s); free(tamanho); return 0; } FILE* abrindo_log(char* nome_arquivo){ FILE *fp; fp = fopen(nome_arquivo, "a+"); if(fp == NULL){ printf("Erro ao abrir/criar o log \n\n\n"); exit(0); } return fp; } void mensagem_log(char * url, int opcao){ // op == ERRO_LOG -> rejeitado // op == ACEPT_LOG (!= 0) -> aceito char * mensagem =(char *) malloc(10*sizeof(char)); char * arquivo =(char *) malloc(30*sizeof(char)); if (opcao == ERRO_LOG){ arquivo= "ErrorLog.txt"; mensagem = "rejeitado - blacklist"; } else if(opcao == DENY_ERRO){ arquivo= "ErrorLog.txt"; mensagem = "rejeitado - denyterms na URL"; } else if(opcao == ACCEPT_LOG){ arquivo= "AcceptLog.txt"; mensagem = "Aceito - whitelist"; } else{ arquivo = "AcceptLog.txt"; mensagem = "aceito - nao filtrado"; } FILE *fp = abrindo_log(arquivo); fprintf(fp,"Data : %s [%s] :: Request foi %s: %s \n",__DATE__,__TIME__ ,mensagem,url); mensagem = NULL; arquivo = NULL; free(mensagem); free(arquivo); fclose(fp); } void mensagem_log_body(char * url, char * dado){ // op == ERRO_LOG -> rejeitado // op == ACEPT_LOG (!= 0) -> aceito // op == DENY_ERRO -> // op == NOT_FILTERED char * mensagem =(char *) malloc(10*sizeof(char)); char * arquivo =(char *) malloc(16*sizeof(char)); arquivo= "ErrorLog.txt"; mensagem = "rejeitado por palavra proibida nos dados"; FILE *fp = abrindo_log(arquivo); fprintf(fp,"Data : %s [%s] :: Request foi %s: %s -> %s\n",__DATE__,__TIME__ ,mensagem,url,dado); mensagem = NULL; arquivo = NULL; free(mensagem); free(arquivo); fclose(fp); }
2.625
3
2024-11-18T22:25:20.127772+00:00
2021-05-24T17:03:31
44f0768406f9589225107a8cd4542b38335fbc09
{ "blob_id": "44f0768406f9589225107a8cd4542b38335fbc09", "branch_name": "refs/heads/main", "committer_date": "2021-05-24T17:03:31", "content_id": "bc201bec67e1141febd73e2ffba80422b476722d", "detected_licenses": [ "MIT" ], "directory_id": "66675b849b26e5e9cc5e34a6ce6ffd2b6708a11a", "extension": "c", "filename": "ex1.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 133545829, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 309, "license": "MIT", "license_type": "permissive", "path": "/Licenciatura (BSc)/Sistemas Operativos I [13]/16'17/aulas/Ficha03/ex1.c", "provenance": "stackv2-0115.json.gz:118537", "repo_name": "LuisRessonha/UEvora", "revision_date": "2021-05-24T17:03:31", "revision_id": "49846b9fa6c48953f97e586b93b1aec2cdac6aea", "snapshot_id": "43ef1969179b964335aaf4d4a0ed4af66460c60a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/LuisRessonha/UEvora/49846b9fa6c48953f97e586b93b1aec2cdac6aea/Licenciatura (BSc)/Sistemas Operativos I [13]/16'17/aulas/Ficha03/ex1.c", "visit_date": "2021-06-05T16:00:50.958899" }
stackv2
#include <math.h> #include <stdio.h> int main(){ int n, i; double sum = 0; printf("Enter a num: "); scanf("%d",&n); // printf("%d",n); for(i=1; i <= n; ++i){ sum += (double)sqrt(i); } printf("O total da soma de todas as raizes ate %d é: %lf", n, sum); return 0; }
3.171875
3
2024-11-18T22:25:20.262551+00:00
2021-10-09T08:45:42
ee71bdb50a4840e3340fc38e69a2ffa58df9702d
{ "blob_id": "ee71bdb50a4840e3340fc38e69a2ffa58df9702d", "branch_name": "refs/heads/main", "committer_date": "2021-10-09T08:45:42", "content_id": "ecfc6e7f07701e79b9c902dc99eca2b8cff5074e", "detected_licenses": [ "Apache-2.0" ], "directory_id": "0d51e5c4518dea4de078fde6be7050c31c307582", "extension": "c", "filename": "lpms.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": 18286, "license": "Apache-2.0", "license_type": "permissive", "path": "/lpms.c", "provenance": "stackv2-0115.json.gz:118793", "repo_name": "zhangsz0516/pms", "revision_date": "2021-10-09T08:45:42", "revision_id": "bc2558c3a6cbe27d3b8ed3b19cf397776592ff88", "snapshot_id": "3cca0ce2ceefc4492e3125b18b28aba40217f91d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/zhangsz0516/pms/bc2558c3a6cbe27d3b8ed3b19cf397776592ff88/lpms.c", "visit_date": "2023-08-21T18:29:22.198437" }
stackv2
/* * Copyright (c) 2006-2021, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2021-10-08 zhangsz the first version */ #include <lpms.h> /* tickless threshold time */ #ifndef LPMS_TICKLESS_THRESHOLD_TIME #define LPMS_TICKLESS_THRESHOLD_TIME 6 #endif /* busy : sleep mode */ #ifndef LPMS_TICKLESS_THRESHOLD_MODE #define LPMS_TICKLESS_THRESHOLD_MODE PM_SLEEP_IDLE #endif /* busy : sleep mode */ #ifndef LPMS_BUSY_SLEEP_MODE #define LPMS_BUSY_SLEEP_MODE PM_SLEEP_NONE #endif /* tickless : deep sleep mode */ #ifndef LPMS_TICKLESS_DEFAULT_MODE #define LPMS_TICKLESS_DEFAULT_MODE PM_SLEEP_LIGHT #endif /* lpms control block */ static lpms_sys_t _pm_sys = { 0 }; /* notify hooks */ #ifdef LPMS_USING_HOOK /* before sleep */ #ifndef LPMS_HOOK_LIST_SLEEP_SIZE #define LPMS_HOOK_LIST_SLEEP_SIZE 4 #endif /* wakeup */ #ifndef LPMS_HOOK_LIST_WAKE_SIZE #define LPMS_HOOK_LIST_WAKE_SIZE 4 #endif /* freqency change */ #ifndef LPMS_HOOK_LIST_FREQ_SIZE #define LPMS_HOOK_LIST_FREQ_SIZE 4 #endif static void (*pm_hook_list_sleep[LPMS_HOOK_LIST_SLEEP_SIZE])(uint8_t mode); static void (*pm_hook_list_wake[LPMS_HOOK_LIST_WAKE_SIZE])(uint8_t mode); static void (*pm_hook_list_freq[LPMS_HOOK_LIST_FREQ_SIZE])(uint8_t mode); /* set sleep hook : before sleep enter */ int32_t lpms_sleep_sethook(void (*hook)(uint8_t mode)) { uint32_t i; uint32_t level; int32_t ret = -LPMS_EFULL; /* disable interrupt */ level = pm_irq_disable(); for (i = 0; i < LPMS_HOOK_LIST_SLEEP_SIZE; i++) { if (pm_hook_list_sleep[i] == NULL) { pm_hook_list_sleep[i] = hook; ret = LPMS_EOK; break; } } /* enable interrupt */ pm_irq_enable(level); return ret; } /* delete sleep hook : before sleep enter */ int32_t lpms_sleep_delhook(void (*hook)(uint8_t mode)) { uint32_t i; uint32_t level; int32_t ret = -LPMS_ENOSYS; /* disable interrupt */ level = pm_irq_disable(); for (i = 0; i < LPMS_HOOK_LIST_SLEEP_SIZE; i++) { if (pm_hook_list_sleep[i] == hook) { pm_hook_list_sleep[i] = NULL; ret = LPMS_EOK; break; } } /* enable interrupt */ pm_irq_enable(level); return ret; } /* set wakeup hook : after sleep exit */ int32_t lpms_wakeup_sethook(void (*hook)(uint8_t mode)) { uint32_t i; uint32_t level; int32_t ret = -LPMS_EFULL; /* disable interrupt */ level = pm_irq_disable(); for (i = 0; i < LPMS_HOOK_LIST_WAKE_SIZE; i++) { if (pm_hook_list_wake[i] == NULL) { pm_hook_list_wake[i] = hook; ret = LPMS_EOK; break; } } /* enable interrupt */ pm_irq_enable(level); return ret; } /* delete wakeup hook : after sleep exit */ int32_t lpms_wakeup_delhook(void (*hook)(uint8_t mode)) { uint32_t i; uint32_t level; int32_t ret = -LPMS_ENOSYS; /* disable interrupt */ level = pm_irq_disable(); for (i = 0; i < LPMS_HOOK_LIST_WAKE_SIZE; i++) { if (pm_hook_list_wake[i] == hook) { pm_hook_list_wake[i] = NULL; ret = LPMS_EOK; break; } } /* enable interrupt */ pm_irq_enable(level); return ret; } /* set freqency change hook : after freqency change exit */ int32_t lpms_freq_sethook(void (*hook)(uint8_t mode)) { uint32_t i; uint32_t level; int32_t ret = -LPMS_EFULL; /* disable interrupt */ level = pm_irq_disable(); for (i = 0; i < LPMS_HOOK_LIST_FREQ_SIZE; i++) { if (pm_hook_list_freq[i] == NULL) { pm_hook_list_freq[i] = hook; ret = LPMS_EOK; break; } } /* enable interrupt */ pm_irq_enable(level); return ret; } /* delete freqency change hook : after freqency change exit */ int32_t lpms_freq_delhook(void (*hook)(uint8_t mode)) { uint32_t i; uint32_t level; int32_t ret = -LPMS_ENOSYS; /* disable interrupt */ level = pm_irq_disable(); for (i = 0; i < LPMS_HOOK_LIST_FREQ_SIZE; i++) { if (pm_hook_list_freq[i] == hook) { pm_hook_list_freq[i] = NULL; ret = LPMS_EOK; break; } } /* enable interrupt */ pm_irq_enable(level); return ret; } /* run sleep notify */ void lpms_notify_sleep(uint8_t mode) { uint32_t i; for (i = 0; i < LPMS_HOOK_LIST_SLEEP_SIZE; i++) { if (pm_hook_list_sleep[i] != NULL) { pm_hook_list_sleep[i](mode); } } } /* run wakeup notify */ void lpms_notify_wakeup(uint8_t mode) { uint32_t i; for (i = 0; i < LPMS_HOOK_LIST_WAKE_SIZE; i++) { if (pm_hook_list_wake[i] != NULL) { pm_hook_list_wake[i](mode); } } } /* run freqency change notify */ void lpms_notify_freq(uint8_t mode) { uint32_t i; for (i = 0; i < LPMS_HOOK_LIST_FREQ_SIZE; i++) { if (pm_hook_list_freq[i] != NULL) { pm_hook_list_freq[i](mode); } } } #endif /* interrupt disable */ uint32_t pm_irq_disable(void) { if (_pm_sys.ops == LPMS_NULL) return 0; if (_pm_sys.ops->irq_disable != LPMS_NULL) return _pm_sys.ops->irq_disable(); return 0; } /* interrupt enable */ void pm_irq_enable(uint32_t level) { if (_pm_sys.ops == LPMS_NULL) return; if (_pm_sys.ops->irq_enable != LPMS_NULL) _pm_sys.ops->irq_enable(level); } /* get os system tick */ static uint32_t pm_get_tick(void) { if (_pm_sys.ops == LPMS_NULL) return 0; if (_pm_sys.ops->systick_get != LPMS_NULL) return _pm_sys.ops->systick_get(); return 0; } /* set os system tick */ static void pm_set_tick(uint32_t ticks) { if (_pm_sys.ops == LPMS_NULL) return; if (_pm_sys.ops->systick_set != LPMS_NULL) _pm_sys.ops->systick_set(ticks); } /* get os system timer next timeout */ static uint32_t pm_next_timeout(void) { if (_pm_sys.ops == LPMS_NULL) return PM_TICK_MAX; if (_pm_sys.ops->systick_next_timeout != LPMS_NULL) return _pm_sys.ops->systick_next_timeout(); return PM_TICK_MAX; } /* get lptimer timer next timeout */ static uint32_t lptimer_next_timeout(void) { if (_pm_sys.ops == LPMS_NULL) return PM_TICK_MAX; if (_pm_sys.ops->lptim_next_timeout != LPMS_NULL) return _pm_sys.ops->lptim_next_timeout(); return PM_TICK_MAX; } /* lptimer start */ static void lptimer_start(uint32_t timeout) { if (_pm_sys.ops == LPMS_NULL) return; if (_pm_sys.ops->lptim_start != LPMS_NULL) _pm_sys.ops->lptim_start(timeout); } /* lptimer stop */ static void lptimer_stop(void) { if (_pm_sys.ops == LPMS_NULL) return; if (_pm_sys.ops->lptim_stop != LPMS_NULL) _pm_sys.ops->lptim_stop(); } /* lptimer get timeout tick */ static uint32_t lptimer_get_timeout(void) { if (_pm_sys.ops == LPMS_NULL) return PM_TICK_MAX; if (_pm_sys.ops->lptim_get_tick != LPMS_NULL) return _pm_sys.ops->lptim_get_tick(); return PM_TICK_MAX; } /* lpms sleep enter */ static void pm_sleep(uint8_t sleep_mode) { if (_pm_sys.ops == LPMS_NULL) return; if (_pm_sys.ops->sleep != LPMS_NULL) _pm_sys.ops->sleep(sleep_mode); } /* lpms change system frequency enter */ void _pm_set_freq(uint8_t freq_mode) { if (_pm_sys.ops == LPMS_NULL) return; if (_pm_sys.ops->set_freq != LPMS_NULL) _pm_sys.ops->set_freq(freq_mode); } /** * This function will let current module work with specified sleep mode. * * @param module_id the pm module id * @param mode the pm sleep mode * * @return none */ void pm_sleep_request(uint16_t module_id, uint8_t mode) { uint32_t level; if (module_id >= PM_MODULE_MAX) { return; } if (mode >= (PM_SLEEP_MODE_MAX - 1)) { return; } level = pm_irq_disable(); _pm_sys.sleep_status[mode][module_id / 32] |= 1 << (module_id % 32); pm_irq_enable(level); } /** * This function will let current module work with PM_SLEEP_IDLE mode. * * @param module_id the pm module id * * @return NULL */ void pm_idle_lock_request(uint16_t module_id) { pm_sleep_request(module_id, PM_SLEEP_IDLE); } /** * When current module don't work, release requested sleep mode. * * @param module_id the pm module id * @param mode the pm sleep mode * * @return NULL */ void pm_sleep_release(uint16_t module_id, uint8_t mode) { uint32_t level; if (module_id >= PM_MODULE_MAX) { return; } if (mode >= (PM_SLEEP_MODE_MAX - 1)) { return; } level = pm_irq_disable(); _pm_sys.sleep_status[mode][module_id / 32] &= ~(1 << (module_id % 32)); pm_irq_enable(level); } /** * The specified module release the requested PM_SLEEP_IDLE mode * * @param module_id the pm module id * * @return none */ void pm_idle_lock_release(uint16_t module_id) { pm_sleep_release(module_id, PM_SLEEP_IDLE); } /** * select frequency mode from frequency request * * @param none * * @return frequency mode */ uint8_t select_freq_mode(void) { uint8_t index; uint16_t len; for (index = 0; index < PM_FREQ_MODE_MAX -1; index++) { for (len = 0; len < ((PM_MODULE_MAX + 31) / 32); len++) { if (_pm_sys.freq_status[index][len] != 0x00) return index; } } return PM_FREQ_LOW; /* default frequency mode */ } /** * This function will let current module work with specified frequency mode. * * @param module_id the pm module id * @param mode the pm frequency mode * * @return none */ void pm_freq_request(uint16_t module_id, uint8_t mode) { uint32_t level; if (module_id >= PM_MODULE_MAX) { return; } if (mode >= (PM_FREQ_MODE_MAX - 1)) { return; } level = pm_irq_disable(); _pm_sys.freq_status[mode][module_id / 32] |= 1 << (module_id % 32); if (mode < _pm_sys.freq_mode) /* request high freq? */ { _pm_set_freq(mode); /* if request high freq, do it */ _pm_sys.freq_mode = mode; /* update current freq_mode */ } pm_irq_enable(level); } /** * The pm module release the requested frequency mode. * * @param module_id the pm module id * @param mode the pm frequency mode * * @return none */ void pm_freq_release(uint16_t module_id, uint8_t mode) { uint32_t level; if (module_id >= PM_MODULE_MAX) { return; } if (mode >= (PM_FREQ_MODE_MAX - 1)) { return; } level = pm_irq_disable(); _pm_sys.freq_status[mode][module_id / 32] &= ~(1 << (module_id % 32)); _pm_sys.freq_flag = 0x01; /* change freq delay in idle thread */ pm_irq_enable(level); } /** * Set pm module in busy mode. * * @param module_id the pm module id * @param ticks the max busy time * * @return none */ void pm_busy_set(uint16_t module_id, uint32_t ticks) { uint32_t level; if (module_id >= PM_BUSY_MODULE_MAX) { return; } if ((ticks < 1) || (ticks >= PM_TICK_MAX / 2)) { return; } level = pm_irq_disable(); _pm_sys.timeout[module_id] = pm_get_tick() + ticks; pm_irq_enable(level); } /** * Clear pm module busy status. * * @param module_id the pm module id * * @return none */ void pm_busy_clear(uint16_t module_id) { uint32_t level; if (module_id >= PM_BUSY_MODULE_MAX) { return; } level = pm_irq_disable(); _pm_sys.timeout[module_id] = 0; pm_irq_enable(level); } /** * select sleep mode from sleep request * * @param none * * @return sleep mode */ static uint8_t select_sleep_mode(void) { uint8_t index; uint16_t len; for (index = 0; index < PM_SLEEP_MODE_MAX -1; index++) { for (len = 0; len < ((PM_MODULE_MAX + 31) / 32); len++) { if (_pm_sys.sleep_status[index][len] != 0x00) return index; } } return PM_SLEEP_DEEP; /* default sleep mode */ } /** * get current sleep mode * * @param none * * @return sleep mode */ uint8_t pm_get_sleep_mode(void) { return _pm_sys.sleep_mode; } /** * get current frequency mode * * @param none * * @return frequency mode */ uint8_t pm_get_freq_mode(void) { return _pm_sys.freq_mode; } /** * get current busy status * * @param none * * @return busy or idle */ static uint8_t pm_check_busy(void) { uint32_t index = 0; for (index = 0; index < PM_BUSY_MODULE_MAX; index++) { if (_pm_sys.timeout[index] > pm_get_tick()) { return PM_FLAG_BUSY; /* busy */ } } return PM_FLAG_IDLE; /* default idle */ } /** * print current module sleep request list * * @param none * * @return none */ void pm_sleep_mode_dump(void) { #ifdef LPMS_USING_DEBUG uint8_t index; uint16_t len; PM_PRINT("+-------------+--------------+\n"); PM_PRINT("| Sleep Mode | Value |\n"); PM_PRINT("+-------------+--------------+\n"); for (index = 0; index < PM_SLEEP_MODE_MAX -1; index++) { for (len = 0; len < ((PM_MODULE_MAX + 31) / 32); len++) { PM_PRINT("| Mode[%d] : %d | 0x%08x |\n", index, len, _pm_sys.sleep_status[index][len]); } } PM_PRINT("+-------------+--------------+\n"); #endif } /** * print current module frequency request list * * @param none * * @return none */ void pm_freq_mode_dump(void) { #ifdef LPMS_USING_DEBUG uint8_t index; uint16_t len; PM_PRINT("+-------------+--------------+\n"); PM_PRINT("| Freq Mode | Value |\n"); PM_PRINT("+-------------+--------------+\n"); for (index = 0; index < PM_FREQ_MODE_MAX -1; index++) { for (len = 0; len < ((PM_MODULE_MAX + 31) / 32); len++) { PM_PRINT("| Mode[%d] : %d | 0x%08x |\n", index, len, _pm_sys.freq_status[index][len]); } } PM_PRINT("+-------------+--------------+\n"); #endif } /** * print current module busy status list * * @param none * * @return none */ void pm_busy_mode_dump(void) { #ifdef LPMS_USING_DEBUG uint32_t index = 0; PM_PRINT("+-------------+--------------+\n"); PM_PRINT("| module_id | remain ticks |\n"); PM_PRINT("+-------------+--------------+\n"); for (index = 0; index < PM_BUSY_MODULE_MAX; index++) { if (_pm_sys.timeout[index] > pm_get_tick()) { PM_PRINT("| %3d | 0x%08x |\n", index, _pm_sys.timeout[index] - pm_get_tick()); } } PM_PRINT("+-------------+--------------+\n"); #endif } /** * pms init * * @param ops the pms ops for power management * @param freq_mode the system startup frequency mode * * @return none */ void lpms_init(const struct lpms_ops *ops, uint8_t freq_mode) { if (_pm_sys.init_flag) return; _pm_sys.init_flag = 0x01; _pm_sys.enable_flag = 0x00; /* 默认不工作 */ _pm_sys.sleep_mode = PM_SLEEP_DEEP; _pm_sys.freq_mode = freq_mode; _pm_sys.ops = ops; } /** * enable pms * * @param none * * @return none */ void lpms_enable(void) { _pm_sys.enable_flag = 0x01; } /** * disable pms * * @param none * * @return none */ void lpms_disable(void) { _pm_sys.enable_flag = 0x00; } /** * return the pms enable status * * @param none * * @return none */ uint8_t pm_is_enabled(void) { return _pm_sys.enable_flag; } /** * run frequency mode logic * * @param none * * @return none */ static void pm_freq_handle(void) { uint8_t freq_mode; if (_pm_sys.freq_flag == 0x01) { _pm_sys.freq_flag = 0x00; freq_mode = select_freq_mode(); /* need frequency change */ if (freq_mode != _pm_sys.freq_mode) { _pm_set_freq(freq_mode); _pm_sys.freq_mode = freq_mode; /* if have freq notify */ LPMS_HOOK_CALL(lpms_notify_freq, (_pm_sys.freq_mode)); } } } /** * run sleep tickless mode logic * * @param none * * @return none */ void pm_run_tickless(void) { uint32_t level; uint32_t timeout_tick = 0; uint32_t delta_tick = 0; uint8_t lptim_flag = 0x00; uint8_t sleep_mode = PM_SLEEP_DEEP; /* pms enable? */ if (!pm_is_enabled()) return; level = pm_irq_disable(); /* judge sleep mode from module request */ _pm_sys.sleep_mode = select_sleep_mode(); /* check module busy status */ if (pm_check_busy() == PM_FLAG_BUSY) { sleep_mode = LPMS_BUSY_SLEEP_MODE; if (sleep_mode < _pm_sys.sleep_mode) { _pm_sys.sleep_mode = sleep_mode; /* judge the highest sleep mode */ } } /* tickless threshold check */ timeout_tick = pm_next_timeout(); /* system-timer timeout */ timeout_tick -= pm_get_tick(); if (timeout_tick <= LPMS_TICKLESS_THRESHOLD_TIME) { sleep_mode = LPMS_TICKLESS_THRESHOLD_MODE; if (sleep_mode < _pm_sys.sleep_mode) { _pm_sys.sleep_mode = sleep_mode; } } /* can enter deepsleep? */ if (_pm_sys.sleep_mode >= LPMS_TICKLESS_DEFAULT_MODE) { timeout_tick = lptimer_next_timeout(); timeout_tick -= pm_get_tick(); lptimer_start(timeout_tick); lptim_flag = 0x01; } /* before sleep notify, if needed */ LPMS_HOOK_CALL(lpms_notify_sleep, (_pm_sys.sleep_mode)); /* sleep enter */ pm_sleep(_pm_sys.sleep_mode); /* wakeup notify, if needed */ LPMS_HOOK_CALL(lpms_notify_wakeup, (_pm_sys.sleep_mode)); /* system tick compensation */ if (_pm_sys.sleep_mode >= LPMS_TICKLESS_DEFAULT_MODE) { if (lptim_flag == 0x01) { delta_tick = lptimer_get_timeout(); lptimer_stop(); /* stop lptimer */ pm_set_tick(pm_get_tick() + delta_tick); /* tick compensation */ lptim_flag = 0x00; } } /* run freq logic */ pm_freq_handle(); pm_irq_enable(level); }
2.15625
2
2024-11-18T22:25:20.932380+00:00
2019-10-16T09:34:49
9f4adc73101bf5f762062ac34e4ccf427ac11e99
{ "blob_id": "9f4adc73101bf5f762062ac34e4ccf427ac11e99", "branch_name": "refs/heads/master", "committer_date": "2019-10-16T09:34:49", "content_id": "9b819756ab216c04e875a9aef823ad87eb611d84", "detected_licenses": [ "MIT-Modern-Variant", "ISC" ], "directory_id": "8eeb4dc93d55619b20eba6b4fede07294240a856", "extension": "c", "filename": "resdest.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 211876836, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 785, "license": "MIT-Modern-Variant,ISC", "license_type": "permissive", "path": "/src/spice3/src/lib/dev/res/resdest.c", "provenance": "stackv2-0115.json.gz:119308", "repo_name": "space-tudelft/cacd", "revision_date": "2019-10-16T09:34:49", "revision_id": "8837293bb2c97edad986cf36ad8efe75387d9171", "snapshot_id": "d7863c84e461726efeb0f5b52066eb70d02e6699", "src_encoding": "UTF-8", "star_events_count": 11, "url": "https://raw.githubusercontent.com/space-tudelft/cacd/8837293bb2c97edad986cf36ad8efe75387d9171/src/spice3/src/lib/dev/res/resdest.c", "visit_date": "2020-08-03T20:37:02.033704" }
stackv2
/********** Copyright 1990 Regents of the University of California. All rights reserved. Author: 1985 Thomas L. Quarles **********/ #include "spice.h" #include <stdio.h> #include "util.h" #include "resdefs.h" void RESdestroy(inModel) GENmodel **inModel; { RESmodel **model = (RESmodel **)inModel; RESinstance *here; RESinstance *prev = NULL; RESmodel *mod = *model; RESmodel *oldmod = NULL; for( ; mod ; mod = mod->RESnextModel) { if(oldmod) FREE(oldmod); oldmod = mod; prev = (RESinstance *)NULL; for(here = mod->RESinstances ; here ; here = here->RESnextInstance) { if(prev) FREE(prev); prev = here; } if(prev) FREE(prev); } if(oldmod) FREE(oldmod); *model = NULL; }
2.03125
2
2024-11-18T22:25:21.102779+00:00
2015-10-06T18:56:54
c0b1222f21c39280f50864f292f6331e9d89c95a
{ "blob_id": "c0b1222f21c39280f50864f292f6331e9d89c95a", "branch_name": "refs/heads/master", "committer_date": "2015-10-06T18:56:54", "content_id": "12a9ea7a6ee0ece99375d87c7fa0fa01ebb7eb7b", "detected_licenses": [ "Apache-2.0" ], "directory_id": "5b3da96163680f93c84b13087421fa4288a52694", "extension": "h", "filename": "stack.h", "fork_events_count": 0, "gha_created_at": "2015-10-01T13:44:34", "gha_event_created_at": "2015-10-01T13:44:35", "gha_language": null, "gha_license_id": null, "github_id": 43498737, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3892, "license": "Apache-2.0", "license_type": "permissive", "path": "/clib/stack.h", "provenance": "stackv2-0115.json.gz:119568", "repo_name": "eddiejames/ffs", "revision_date": "2015-10-06T18:56:54", "revision_id": "b7a54030035068010de32311c265f4173d5308ff", "snapshot_id": "4f955cf1ff7839c8f17a485e37ee12ba3549ffba", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/eddiejames/ffs/b7a54030035068010de32311c265f4173d5308ff/clib/stack.h", "visit_date": "2021-01-17T01:12:05.810690" }
stackv2
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: clib/stack.h $ */ /* */ /* OpenPOWER FFS Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /*! * @file stack.h * @brief stack container * @details * A stack is a data structure (container) used for collecting a sequence of elements. * stack allow for efficient insertion, removal and retreival of elements. * * @details For example, * @code * #include <clib/stack.h> * #include <clib/stack_iter.h> * * int main(const int argc, const char * argv[]) { * typedef struct { * stack_node_t node; * int i; * float f; * } data_t; * * slab_t s; * slab_init(&s, sizeof(data_t), 0); * * stack_t a; * stack_init(&a); * * int i; * for (i=0; i<10; i++) { * data_t * d = (data_t *)slab_alloc(&s); * * d->i = i; * d->f = (float)i; * * stack_add_tail(&l, &d->node); * } * * data_t * d; * stack_for_each(&l, d, node) { * printf("i: %d f: %f\n", d->i, d->f); * } * * stack_dump(&l, stdout); * slab_delete(&s); * * return 0; * } * @endcode * @author Shaun Wetzstein <shaun@us.ibm.com> * @date 2010-2011 */ #ifndef __STACK_H__ #define __STACK_H__ #include "list.h" #include "type.h" typedef list stack; typedef list_node stack_node; #define stack_init(s) list_init((list *)(s)) #define stack_push(s,n) list_add_tail((list *)(s),(n)) #define stack_pop(s) list_remove_tail((list *)(s)) #define stack_empty(s) list_empty((list *)(s)) #define stack_dump(s,o) list_dump((list *)(s),(o)) #define stack_entry(n, t, m) list_entry((n),(t),(m)) #define stack_top(s) list_head((list *)(s)) #define stack_bottom(s) list_tail((list *)(s)) #define stack_for_each(s, i, m) \ for (i = container_of_var(s->node.next, i, m); \ &i->m != &(s)->node; \ i = container_of_var(i->m.next, i, m)) #define stack_for_each_safe(s, i, n, m) \ for (i = container_of_var((s)->node.next, i, m), \ n = container_of_var(i->m.next, i, m); \ &i->m != &(s)->node; \ i = n, n = container_of_var(i->m.next, i, m)) #endif /* __STACK_H__ */
2.25
2
2024-11-18T22:25:21.173710+00:00
2020-05-16T12:45:07
3c832cae7bf807b80ab7373a73e0af3af06b560a
{ "blob_id": "3c832cae7bf807b80ab7373a73e0af3af06b560a", "branch_name": "refs/heads/master", "committer_date": "2020-05-16T12:45:07", "content_id": "459d9e0c20255ec2f8f4a0757d852e65a0d5c10e", "detected_licenses": [ "MIT" ], "directory_id": "256635720b151219c83089c1a9dae925bb2a6339", "extension": "c", "filename": "server.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 264431615, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4903, "license": "MIT", "license_type": "permissive", "path": "/cherokee/src/server.c", "provenance": "stackv2-0115.json.gz:119698", "repo_name": "TASnomad/etna-oss-projects", "revision_date": "2020-05-16T12:45:07", "revision_id": "fbd252e5c0f38c4a3c086e61c1e2b22178cb9c67", "snapshot_id": "fa2edc67b9376a8e7c71839d84e7460509c29dfc", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/TASnomad/etna-oss-projects/fbd252e5c0f38c4a3c086e61c1e2b22178cb9c67/cherokee/src/server.c", "visit_date": "2022-07-31T05:34:22.346062" }
stackv2
#include <stdio.h> #include <stdlib.h> #include "server.h" #include "io.h" #include "cherokee.h" #include "my_integer.h" #include "http.h" #include "response.h" #include "syntax.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> int create_server_socket(int port) { struct sockaddr_in srv; int opts; int fd; opts = 1; srv.sin_family = AF_INET; srv.sin_addr.s_addr = INADDR_ANY; srv.sin_port = htons(port); fd = socket(AF_INET, SOCK_STREAM, 0); if (fd < 0) { perror("create_server_socket socket:"); return (fd); } if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opts, sizeof(socklen_t)) < 0) { perror("create_server_socket cant set SO_REUSEADDR flags:"); } if (bind(fd, (struct sockaddr *) &srv, sizeof(srv)) < 0) { perror("create_server_socket bind:"); close(fd); return (-1); } if (listen(fd, SOMAXCONN) < 0) { perror("create_server_socket listen:"); close(fd); return (-1); } return (fd); } /* t_string read_file(char *filename) { int fd; off_t size; t_string buf; int count; fd = open(filename, 0); if (fd == -1) { perror("open()"); return (NULL); } size = filesize(fd); if ((buf = malloc(sizeof(*buf) * (size + 1))) == 0) { perror("malloc()"); return (NULL); } count = read(fd, buf, size); buf[count] = 0; return (buf); } t_response *defaultHandle(t_request *request) { int fd; t_response *response; t_string document_root; t_string server_path; response = init_response(); document_root = read_file(DOCUMENT_ROOT_CONF); if (!document_root) { printf("Fail to read conf file %s\n", DOCUMENT_ROOT_CONF); return (NULL); } if (!response) { printf("Fail to init memory"); return (NULL); } if (strcmp(request->path, "/") == 0) { printf("%s\n", request->path); free(request->path); request->path = strdup("/index.html"); printf("after\n"); } server_path = (t_string)malloc((sizeof(char) * (strlen(document_root) + strlen(request->path) + 1))); if (!server_path) { internal_error(response); return (response); } strcpy(server_path, document_root); strcpy(server_path + strlen(document_root), request->path); fd = open(server_path, O_RDWR); if (fd > 0) { success(response); response->file_fd = fd; } else { not_found(response); } return (response); } */ char *pathname(char *request_path, char *document_root) { char *server_path; server_path = (t_string)malloc((sizeof(char) * (strlen(document_root) + strlen(request_path) + 1))); if (!server_path) { return (NULL); } strcpy(server_path, document_root); strcpy(server_path + strlen(document_root), request_path); return (server_path); } /* t_response *handle(char *protocol) { t_request *request; t_http_lexemes lexemes; t_response *response; lexemes = parse_request(protocol); if (!lexemes) { printf("fail to parse request\n"); return (NULL); } request = lexeme_to_request(lexemes); if (!request) { printf("get object request\n"); delete_list_exec_action(lexemes, &remove_lexeme); return (NULL); } response = defaultHandle(request); delete_list_exec_action(lexemes, &remove_lexeme); delete_request(request); if (!response) { printf("fail to create response\n"); return (NULL); } return (response); } */ void s_send(t_integer *fd, t_response *response) { #if defined EXPERIMENT /*size = filesize(response->file_fd);*/ if (fd->value > -1) cherokee_sendfile(response, fd->value); #else t_string str; str = toResponseString(response); send(fd->value, str, strlen(str), 0); free(str); if (fd->value != -1) { //sendfile(fd->value, response->file_fd, &offset, size); int offset; char buf[1024]; offset = 0; while ((offset = read(response->file_fd, buf, 1024)) > 0) { buf[offset] = 0; send(fd->value, buf, offset, 0); } if (offset == -1) { perror("read()"); } } #endif /* !EXPERIMENT */ close(response->file_fd); } /* void handle_request(void *data) { char buff[BUFSIZE]; int rsize; t_integer *fd; t_response *response; fd = (t_integer *)data; rsize = recv(fd->value, buff, BUFSIZE, 0); if (rsize <= 0) { perror("handle_request() recv:"); close(fd->value); free(fd); return; } response = handle(buff); if (!response) { close(fd->value); free(fd); return; } s_send(fd, response); delete_response(response); close(fd->value); free(fd); } void routingHandle(t_request *request) { printf("%p\n", request); } void launch_server(int fd) { int client_fd; struct sockaddr_in client_addr; socklen_t size; char *IP = NULL; while (1) { client_fd = accept(fd, (struct sockaddr *) &client_addr, &size); if (client_fd < 0) { perror("launch_server accept:"); continue; } IP = inet_ntoa(client_addr.sin_addr); if (IP) { printf("Got new connection from : %s\n", IP); } //handle_request(&client_fd); close(client_fd); } } */
2.28125
2
2024-11-18T22:25:21.585037+00:00
2018-04-28T14:50:19
565d5264da209df0e84e564df4de164721b05a74
{ "blob_id": "565d5264da209df0e84e564df4de164721b05a74", "branch_name": "refs/heads/master", "committer_date": "2018-04-28T14:50:19", "content_id": "85dcde098e241cd149345926020d1a7ddb575967", "detected_licenses": [ "MIT" ], "directory_id": "695055eb5962f4051c537044701622346332ac13", "extension": "c", "filename": "gen2_save_test.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 64138873, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7792, "license": "MIT", "license_type": "permissive", "path": "/testing/unit-tests/gen2_save_test.c", "provenance": "stackv2-0115.json.gz:119826", "repo_name": "ncorgan/pksav", "revision_date": "2018-04-28T14:50:19", "revision_id": "76b9af65bc239acf42d65ed981af85fbdbacd00d", "snapshot_id": "591258b86be1a99f9dedb01f8d55319b1490d7a0", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/ncorgan/pksav/76b9af65bc239acf42d65ed981af85fbdbacd00d/testing/unit-tests/gen2_save_test.c", "visit_date": "2021-12-01T03:13:23.004603" }
stackv2
/* * Copyright (c) 2017 Nicholas Corgan (n.corgan@gmail.com) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #include "c_test_common.h" #include "test-utils.h" #include <pksav/config.h> #include <pksav/gen2/save.h> #include <stdio.h> #include <string.h> // TODO: replace when size is moved to header #define GEN2_SAVE_SIZE 0x8000 /* * We don't care about the result of the function itself. As the buffer * is randomized, it will likely be false. This function is to make sure * running it on invalid input doesn't crash. */ static void pksav_buffer_is_gen2_save_on_random_buffer_test() { uint8_t buffer[GEN2_SAVE_SIZE] = {0}; for(size_t run_index = 0; run_index < 1000; ++run_index) { randomize_buffer(buffer, sizeof(buffer)); bool is_buffer_gen2_save = false; (void)pksav_buffer_is_gen2_save( buffer, sizeof(buffer), false, // crystal &is_buffer_gen2_save ); (void)pksav_buffer_is_gen2_save( buffer, sizeof(buffer), true, // crystal &is_buffer_gen2_save ); } } static void pksav_buffer_is_gen2_save_test( const char* subdir, const char* save_name, bool crystal ) { TEST_ASSERT_NOT_NULL(subdir); TEST_ASSERT_NOT_NULL(save_name); static char filepath[256]; static uint8_t save_buffer[GEN2_SAVE_SIZE]; pksav_error_t error = PKSAV_ERROR_NONE; char* pksav_test_saves = getenv("PKSAV_TEST_SAVES"); if(!pksav_test_saves) { TEST_FAIL_MESSAGE("Failed to get test save directory."); } snprintf( filepath, sizeof(filepath), "%s%s%s%s%s", pksav_test_saves, FS_SEPARATOR, subdir, FS_SEPARATOR, save_name ); if(read_file_into_buffer(filepath, save_buffer, GEN2_SAVE_SIZE)) { TEST_FAIL_MESSAGE("Failed to read save into buffer."); } bool is_buffer_gen2_save = false; error = pksav_buffer_is_gen2_save( save_buffer, GEN2_SAVE_SIZE, crystal, &is_buffer_gen2_save ); TEST_ASSERT_EQUAL(PKSAV_ERROR_NONE, error); TEST_ASSERT_TRUE(is_buffer_gen2_save); } static void pksav_file_is_gen2_save_test( const char* subdir, const char* save_name, bool crystal ) { TEST_ASSERT_NOT_NULL(subdir); TEST_ASSERT_NOT_NULL(save_name); static char filepath[256]; pksav_error_t error = PKSAV_ERROR_NONE; char* pksav_test_saves = getenv("PKSAV_TEST_SAVES"); if(!pksav_test_saves) { TEST_FAIL_MESSAGE("Failed to get test save directory."); } snprintf( filepath, sizeof(filepath), "%s%s%s%s%s", pksav_test_saves, FS_SEPARATOR, subdir, FS_SEPARATOR, save_name ); bool is_file_gen2_save = false; error = pksav_file_is_gen2_save( filepath, crystal, &is_file_gen2_save ); TEST_ASSERT_EQUAL(PKSAV_ERROR_NONE, error); TEST_ASSERT_TRUE(is_file_gen2_save); } static void gen2_save_load_and_save_match_test( const char* subdir, const char* save_name, bool crystal ) { TEST_ASSERT_NOT_NULL(subdir); TEST_ASSERT_NOT_NULL(save_name); static char original_filepath[256]; static char tmp_save_filepath[256]; pksav_gen2_save_t gen2_save; pksav_error_t error = PKSAV_ERROR_NONE; char* pksav_test_saves = getenv("PKSAV_TEST_SAVES"); if(!pksav_test_saves) { TEST_FAIL_MESSAGE("Failed to get test save directory."); } snprintf( original_filepath, sizeof(original_filepath), "%s%s%s%s%s", pksav_test_saves, FS_SEPARATOR, subdir, FS_SEPARATOR, save_name ); snprintf( tmp_save_filepath, sizeof(tmp_save_filepath), "%s%spksav_%d_%s", get_tmp_dir(), FS_SEPARATOR, get_pid(), save_name ); error = pksav_gen2_save_load( original_filepath, &gen2_save ); TEST_ASSERT_EQUAL(PKSAV_ERROR_NONE, error); TEST_ASSERT_EQUAL((crystal ? PKSAV_GEN2_CRYSTAL : PKSAV_GEN2_GS), gen2_save.gen2_game); error = pksav_gen2_save_save( tmp_save_filepath, &gen2_save ); TEST_ASSERT_EQUAL(PKSAV_ERROR_NONE, error); /* * Files may differ if one of the checksums was not set, which happen for some reason. So * just see if we can load the saved file and compare the saves by field. */ pksav_gen2_save_t tmp_save; error = pksav_gen2_save_load( tmp_save_filepath, &tmp_save ); TEST_ASSERT_EQUAL(PKSAV_ERROR_NONE, error); TEST_ASSERT_EQUAL(gen2_save.gen2_game, tmp_save.gen2_game); TEST_ASSERT_EQUAL(0, memcmp(gen2_save.pokemon_party, tmp_save.pokemon_party, sizeof(*gen2_save.pokemon_party)) ); TEST_ASSERT_EQUAL(*gen2_save.current_pokemon_box_num, *tmp_save.current_pokemon_box_num); for(int i = 0; i < 14; ++i) { TEST_ASSERT_EQUAL(0, memcmp(gen2_save.pokemon_boxes[i], tmp_save.pokemon_boxes[i], sizeof(*gen2_save.pokemon_boxes[i])) ); } TEST_ASSERT_EQUAL(0, memcmp(gen2_save.pokemon_box_names, tmp_save.pokemon_box_names, sizeof(*gen2_save.pokemon_box_names)) ); TEST_ASSERT_EQUAL(0, memcmp(gen2_save.item_bag, tmp_save.item_bag, sizeof(*gen2_save.item_bag)) ); TEST_ASSERT_EQUAL(0, memcmp(gen2_save.item_pc, tmp_save.item_pc, sizeof(*gen2_save.item_pc)) ); TEST_ASSERT_EQUAL(0, memcmp(gen2_save.trainer_name, tmp_save.trainer_name, 7) ); TEST_ASSERT_EQUAL(*gen2_save.trainer_id, *tmp_save.trainer_id); if(crystal) { TEST_ASSERT_EQUAL(*gen2_save.trainer_gender, *tmp_save.trainer_gender); } TEST_ASSERT_EQUAL(0, memcmp(gen2_save.money, tmp_save.money, 3) ); TEST_ASSERT_EQUAL(0, memcmp(gen2_save.rival_name, tmp_save.rival_name, 7) ); TEST_ASSERT_EQUAL(*gen2_save.daylight_savings, *tmp_save.daylight_savings); TEST_ASSERT_EQUAL(0, memcmp(gen2_save.time_played, tmp_save.time_played, sizeof(*gen2_save.time_played)) ); error = pksav_gen2_save_free(&tmp_save); TEST_ASSERT_EQUAL(PKSAV_ERROR_NONE, error); error = pksav_gen2_save_free(&gen2_save); TEST_ASSERT_EQUAL(PKSAV_ERROR_NONE, error); if(delete_file(tmp_save_filepath)) { TEST_FAIL_MESSAGE("Failed to clean up temp file."); } } static void pksav_buffer_is_gold_save_test() { pksav_buffer_is_gen2_save_test("gold_silver", "pokemon_gold.sav", false); } static void pksav_file_is_gold_save_test() { pksav_file_is_gen2_save_test("gold_silver", "pokemon_gold.sav", false); } static void gold_save_load_and_save_match_test() { gen2_save_load_and_save_match_test("gold_silver", "pokemon_gold.sav", false); } static void pksav_buffer_is_crystal_save_test() { pksav_buffer_is_gen2_save_test("crystal", "pokemon_crystal.sav", true); } static void pksav_file_is_crystal_save_test() { pksav_file_is_gen2_save_test("crystal", "pokemon_crystal.sav", true); } static void crystal_save_load_and_save_match_test() { gen2_save_load_and_save_match_test("crystal", "pokemon_crystal.sav", true); } PKSAV_TEST_MAIN( PKSAV_TEST(pksav_buffer_is_gen2_save_on_random_buffer_test) PKSAV_TEST(pksav_buffer_is_gold_save_test) PKSAV_TEST(pksav_file_is_gold_save_test) PKSAV_TEST(gold_save_load_and_save_match_test) PKSAV_TEST(pksav_buffer_is_crystal_save_test) PKSAV_TEST(pksav_file_is_crystal_save_test) PKSAV_TEST(crystal_save_load_and_save_match_test) )
2.21875
2
2024-11-18T22:25:21.653606+00:00
2017-06-19T10:51:21
d356bef72da8551fb1ce1f12f7321cd6b6261eb1
{ "blob_id": "d356bef72da8551fb1ce1f12f7321cd6b6261eb1", "branch_name": "refs/heads/master", "committer_date": "2017-06-19T10:57:23", "content_id": "0eec89f9839d31b6246383784e91f834de2904d3", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "4dd3497a17ce271afc7ba0ac078f1d818012179d", "extension": "c", "filename": "producer_bench.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 52731688, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 998, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/bench/src/producer_bench.c", "provenance": "stackv2-0115.json.gz:119955", "repo_name": "rbruggem/mqlog", "revision_date": "2017-06-19T10:51:21", "revision_id": "caf5761ebcc529cb9473ec74d053e7db9175d515", "snapshot_id": "5f6889a91e37de60817bb5baf43b4fa553fb3397", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/rbruggem/mqlog/caf5761ebcc529cb9473ec74d053e7db9175d515/bench/src/producer_bench.c", "visit_date": "2021-06-18T01:43:12.243502" }
stackv2
#include "bench_util.h" #include <stdlib.h> #include <mqlog.h> #include <util.h> int producer_bench(size_t segment_size, size_t num, size_t size) { unsigned char* block = random_block(size); if (!block) { return -1; } const char* dir = "/tmp/producer_bench"; delete_directory(dir); mqlog_t* lg = NULL; int rc = mqlog_open(&lg, dir, segment_size, 0); if (rc != 0) { return -1; } struct timespec tsr, tsb, tse; if (clock_gettime(CLOCK_REALTIME, &tsb) < 0) { return -1; } for (size_t i = 0; i < num; ++i) { const ssize_t written = mqlog_write(lg, block, size); if ((size_t)written != size) { return -1; } } if (clock_gettime(CLOCK_REALTIME, &tse) < 0) { return -1; } tsr.tv_sec = tse.tv_sec - tsb.tv_sec; tsr.tv_nsec = tse.tv_nsec - tsb.tv_nsec; print_report(__func__, tsr, num, num * size); mqlog_close(lg); free(block); return 0; }
2.5
2
2024-11-18T22:25:21.865455+00:00
2014-10-30T18:32:35
e02b9ea4bb49d73bed5b1fdc659e32bb3566e881
{ "blob_id": "e02b9ea4bb49d73bed5b1fdc659e32bb3566e881", "branch_name": "refs/heads/develop", "committer_date": "2014-10-30T18:32:35", "content_id": "b2cca9a06d5d4074748a6d64deeedcd1af1e7dc9", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "aeef4d7bab4ca441fbecc2823815e9f94cb4563b", "extension": "h", "filename": "lists.h", "fork_events_count": 90, "gha_created_at": "2013-01-15T00:02:23", "gha_event_created_at": "2014-10-30T18:32:35", "gha_language": "C++", "gha_license_id": null, "github_id": 7615342, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3259, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/codelib/tools/lists/lists.h", "provenance": "stackv2-0115.json.gz:120212", "repo_name": "FreeFalcon/freefalcon-central", "revision_date": "2014-10-30T18:32:35", "revision_id": "c28d807183ab447ef6a801068aa3769527d55deb", "snapshot_id": "8fc80b6d82eab44ce314a39860e6ee8e6f5ee71a", "src_encoding": "UTF-8", "star_events_count": 133, "url": "https://raw.githubusercontent.com/FreeFalcon/freefalcon-central/c28d807183ab447ef6a801068aa3769527d55deb/src/codelib/tools/lists/lists.h", "visit_date": "2021-01-23T20:49:45.844619" }
stackv2
/* ---------------------------------------------------- LISTS.H ---------------------------------------------------- Written by Kevin Ray (c) 1994 Spectrum Holobyte. ---------------------------------------------------- */ #if not defined(__LISTS_H_INCLUDED) # define __LISTS_H_INCLUDED 1 #include "omni.h" /* Get our configuration */ /* ----------------------------------- Configuration Options ----------------------------------- */ #ifndef USE_LIST_ALLOCATIONS /* should the list allocs be globbed into a pre-alloc'd table ? */ # define USE_LIST_ALLOCATIONS YES #endif #ifndef USE_THREAD_SAFE /* should the list library be multithread approved ? */ # define USE_THREAD_SAFE YES #endif /* ---------------------------------- Build as a DLL ? ---------------------------------- */ #ifdef _DLL_VERSION # define LST_EXPORT CFUNC __declspec (dllexport) #else # define LST_EXPORT CFUNC #endif /* ---------------------------------- For convenient type coercion ---------------------------------- */ #define LIST_APPEND(a,b) ListAppend( (LIST*)(a), (void*)(b) ) #define LIST_APPEND_END(a,b) ListAppendEnd( (LIST*)(a), (void*)(b) ) #define LIST_APPEND_SECOND(a,b) ListAppendSecond( (LIST*)(a),(void*)(b) ) #define LIST_CATENATE(a,b) ListCatenate( (LIST*)(a),(LIST*)(b) ) #define LIST_DESTROY(a,b) ListDestroy( (LIST*)(a), b ) #define LIST_NTH(a,b) ListNth( (LIST*)(a), (int)(b) ) #define LIST_COUNT(a) ListCount( (LIST*)(a) ) #define LIST_WHERE(a,b) ListWhere( (LIST*)(a), (void*)(b) ) #define LIST_REMOVE(a,b) ListRemove( (LIST*)(a), (void*)(b) ) #define LIST_FIND(a,b) ListFind( (LIST*)(a), (void*)(b) ) #define LIST_SEARCH(a,b,c) ListSearch( (LIST*)(a), (void*)(b), c ) #define LIST_DUP(a) ListDup( (LIST*)(a) ) #define LIST_SORT(a, fn) ListSort( (LIST**)(a), fn ) /* -------------------------------------------------- All singly linked lists have this structure -------------------------------------------------- */ typedef struct LIST { void * node; /* pointer to node data */ void * user; /* pointer to user data */ struct LIST * next; /* next list node */ } LIST; #if( USE_LIST_ALLOCATIONS ) LST_EXPORT void ListValidate(void); LST_EXPORT void ListGlobalFree(void); #endif /* USE_LIST_ALLOCATIONS */ LST_EXPORT LIST * ListAppend(LIST * list, void * node); LST_EXPORT LIST * ListAppendEnd(LIST * list, void * node); LST_EXPORT LIST * ListAppendSecond(LIST * list, void * node); LST_EXPORT LIST * ListCatenate(LIST * l1, LIST * l2); LST_EXPORT LIST * ListNth(LIST * list, int n); LST_EXPORT int ListCount(LIST * list); LST_EXPORT LIST * ListRemove(LIST * list, void * node); LST_EXPORT LIST * ListFind(LIST * list, void * node); LST_EXPORT void ListDestroy(LIST * list, PFV destructor); LST_EXPORT int ListWhere(LIST * list, void * node); LST_EXPORT LIST * ListSearch(LIST * list, void * node, PFI func_ptr); LST_EXPORT LIST * ListDup(LIST * list); LST_EXPORT LIST * ListSort(LIST ** list, PFI func_ptr); #endif /* __LISTS_H_INCLUDED */
2.234375
2
2024-11-18T22:25:22.016139+00:00
2021-03-23T05:51:31
e0d36e71f696c171743a260ca33cd66784adc7ce
{ "blob_id": "e0d36e71f696c171743a260ca33cd66784adc7ce", "branch_name": "refs/heads/master", "committer_date": "2021-03-23T05:51:31", "content_id": "0df29674a84dff558cff2caee61bfd9d44e5c1f9", "detected_licenses": [ "MIT" ], "directory_id": "53fa5359864d818647fad14d4be8c65e44a611b6", "extension": "h", "filename": "win32_kernel.h", "fork_events_count": 6, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 162519934, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9376, "license": "MIT", "license_type": "permissive", "path": "/code/win32_kernel.h", "provenance": "stackv2-0115.json.gz:120341", "repo_name": "ALEXMORF/cray", "revision_date": "2021-03-23T05:51:31", "revision_id": "ebf61b37ccde690081648f3408c6c5963bdd43c6", "snapshot_id": "4b7447465255f4f04e5f841ca1cb7655c847abbb", "src_encoding": "UTF-8", "star_events_count": 38, "url": "https://raw.githubusercontent.com/ALEXMORF/cray/ebf61b37ccde690081648f3408c6c5963bdd43c6/code/win32_kernel.h", "visit_date": "2021-06-13T19:17:32.987484" }
stackv2
u64 Win32GetPerformanceFrequency() { LARGE_INTEGER Result = {}; QueryPerformanceFrequency(&Result); return Result.QuadPart; } u64 Win32GetPerformanceCounter() { LARGE_INTEGER Result = {}; QueryPerformanceCounter(&Result); return Result.QuadPart; } inline f32 Win32GetTimeElapsedInMS(u64 BeginCounter, u64 EndCounter) { f32 Result = (f32)(EndCounter - BeginCounter) / (f32)Win32GetPerformanceFrequency(); Result *= 1000.0f; return Result; } struct win32_window_dimension { int Width, Height; }; inline win32_window_dimension Win32GetWindowDimension(HWND Window) { win32_window_dimension Result = {}; RECT ClientRect; GetClientRect(Window, &ClientRect); Result.Width = ClientRect.right - ClientRect.left; Result.Height = ClientRect.bottom - ClientRect.top; return Result; } //NOTE(chen): RECT Is in screen-coordinate inline RECT Win32GetClientRect(HWND Window) { RECT Result = {}; GetWindowRect(Window, &Result); POINT ClientUpperLeft = {Result.left, Result.top}; POINT ClientLowerRight = {Result.right, Result.bottom}; ScreenToClient(Window, &ClientUpperLeft); ScreenToClient(Window, &ClientLowerRight); i32 SideBorderSize = -ClientUpperLeft.x; i32 TopBorderSize = -ClientUpperLeft.y; Result.left += SideBorderSize; Result.top += TopBorderSize; Result.right += SideBorderSize; Result.bottom += SideBorderSize; return Result; } void * Win32AllocateMemory(size_t MemorySize) { return VirtualAlloc(0, MemorySize, MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE); } char * Win32ReadFileToMemory(char *Filename, u64 *MemorySize) { char *Result = 0; HANDLE FileHandle = CreateFile(Filename, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0); if (FileHandle != INVALID_HANDLE_VALUE) { LARGE_INTEGER FileSize = {}; GetFileSizeEx(FileHandle, &FileSize); *MemorySize = (size_t)FileSize.QuadPart; Result = (char *)VirtualAlloc(0, (size_t)FileSize.QuadPart, MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE); DWORD NumberOfBytesRead; if (ReadFile(FileHandle, Result, (DWORD)FileSize.QuadPart, &NumberOfBytesRead, 0)) { //NOTE(chen): succeeds } else { //NOTE(chen): failed to read file, reset memory to ground zero *MemorySize = 0; VirtualFree(Result, 0, MEM_RELEASE); } CloseHandle(FileHandle); } return Result; } void Win32FreeFileMemory(void *Memory) { VirtualFree(Memory, 0, MEM_RELEASE); } global_variable WINDOWPLACEMENT GlobalWindowPosition; internal void Win32ToggleFullscreen(HWND Window) { DWORD Style = GetWindowLong(Window, GWL_STYLE); if (Style & WS_OVERLAPPEDWINDOW) { MONITORINFO mi = { sizeof(mi) }; if (GetWindowPlacement(Window, &GlobalWindowPosition) && GetMonitorInfo(MonitorFromWindow(Window, MONITOR_DEFAULTTOPRIMARY), &mi)) { SetWindowLong(Window, GWL_STYLE, Style & ~WS_OVERLAPPEDWINDOW); SetWindowPos(Window, HWND_TOP, mi.rcMonitor.left, mi.rcMonitor.top, mi.rcMonitor.right - mi.rcMonitor.left, mi.rcMonitor.bottom - mi.rcMonitor.top, SWP_NOOWNERZORDER | SWP_FRAMECHANGED); } } else { SetWindowLong(Window, GWL_STYLE, Style | WS_OVERLAPPEDWINDOW); SetWindowPlacement(Window, &GlobalWindowPosition); SetWindowPos(Window, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED); } } internal HWND Win32CreateWindow(HINSTANCE InstanceHandle, i32 WindowWidth, i32 WindowHeight, char *WindowName, char *WindowClassName, WNDPROC WindowProcedure) { WNDCLASS WindowClass = {}; WindowClass.style = CS_OWNDC|CS_VREDRAW|CS_HREDRAW; WindowClass.lpfnWndProc = WindowProcedure; WindowClass.hInstance = InstanceHandle; WindowClass.hCursor = LoadCursor(0, IDC_ARROW); WindowClass.lpszClassName = WindowClassName; RegisterClass(&WindowClass); DWORD WindowStyle = WS_VISIBLE|WS_OVERLAPPEDWINDOW; //find right window size RECT WindowSize = {}; { HDC ScreenDeviceContext = GetWindowDC(0); int ScreenWidth = GetDeviceCaps(ScreenDeviceContext, HORZRES); int ScreenHeight = GetDeviceCaps(ScreenDeviceContext, VERTRES); int WindowLeft = (ScreenWidth - WindowWidth) / 2; int WindowTop = (ScreenHeight - WindowHeight) / 2; WindowSize = {WindowLeft, WindowTop, WindowLeft + WindowWidth, WindowTop + WindowHeight}; AdjustWindowRect(&WindowSize, WindowStyle, FALSE); ReleaseDC(0, ScreenDeviceContext); } HWND Window = CreateWindow( WindowClassName, WindowName, WindowStyle, WindowSize.left, WindowSize.top, WindowSize.right - WindowSize.left, WindowSize.bottom - WindowSize.top, 0, 0, InstanceHandle, 0); return Window; } internal void Win32BlitBufferToScreen(HDC WindowDC, void *Buffer, int Width, int Height) { BITMAPINFO BitmapInfo = {}; BitmapInfo.bmiHeader.biSize = sizeof(BitmapInfo.bmiHeader); BitmapInfo.bmiHeader.biWidth = Width; BitmapInfo.bmiHeader.biHeight = Height; BitmapInfo.bmiHeader.biPlanes = 1; BitmapInfo.bmiHeader.biBitCount = 32; BitmapInfo.bmiHeader.biCompression = BI_RGB; StretchDIBits(WindowDC, 0, 0, Width, Height, 0, 0, Width, Height, Buffer, &BitmapInfo, DIB_RGB_COLORS, SRCCOPY); } /* void * Win32GetOpenglFunction(char *FunctionName) { void *Result = 0; Result = (void *)wglGetProcAddress(FunctionName); if (Result == 0 || (Result == (void *)0x1) || (Result == (void *)0x2) || (Result == (void *)0x3) || (Result == (void *)-1)) { HMODULE OpenglLibrary = LoadLibraryA("opengl32.dll"); Result = (void *)GetProcAddress(OpenglLibrary, FunctionName); FreeLibrary(OpenglLibrary); } return Result; } //WGL extension tokens #define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091 #define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092 #define WGL_CONTEXT_LAYER_PLANE_ARB 0x2093 #define WGL_CONTEXT_FLAGS_ARB 0x2094 #define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126 #define WGL_CONTEXT_DEBUG_BIT_ARB 0x0001 #define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x0002 #define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001 #define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002 #define ERROR_INVALID_VERSION_ARB 0x2095 #define ERROR_INVALID_PROFILE_ARB 0x2096 #define WGL_SAMPLE_BUFFERS_ARB 0x2041 #define WGL_SAMPLES_ARB 0x2042 typedef BOOL WINAPI wgl_swap_interval_ext(int Interval); typedef HGLRC WINAPI wgl_create_context_attribs_arb(HDC hDC, HGLRC hshareContext, const int *attribList); //NOTE(chen): disable warning 4706 #pragma warning(push) #pragma warning(disable: 4706) internal b32 Win32InitializeOpengl(HDC WindowDC, int MajorVersion, int MinorVersion) { PIXELFORMATDESCRIPTOR DesiredPixelFormat = {}; DesiredPixelFormat.nSize = sizeof(PIXELFORMATDESCRIPTOR); DesiredPixelFormat.nVersion = 1; DesiredPixelFormat.dwFlags = PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER; DesiredPixelFormat.iPixelType = PFD_TYPE_RGBA; DesiredPixelFormat.cColorBits = 32; DesiredPixelFormat.cStencilBits = 8; int SuggestedPixelFormatIndex = ChoosePixelFormat(WindowDC, &DesiredPixelFormat); PIXELFORMATDESCRIPTOR SuggestedPixelFormat; DescribePixelFormat(WindowDC, SuggestedPixelFormatIndex, sizeof(PIXELFORMATDESCRIPTOR), &SuggestedPixelFormat); SetPixelFormat(WindowDC, SuggestedPixelFormatIndex, &SuggestedPixelFormat); HGLRC Win32RenderContext = wglCreateContext(WindowDC); if (!wglMakeCurrent(WindowDC, Win32RenderContext)) { ASSERT(!"Failed to make opengl 1.0 context current"); } //NOTE(Chen): Probably the extensions u wanna get, but I comment it out here #if 0 wglSwapInterval = (wgl_swap_interval_ext *)wglGetProcAddress("wglSwapIntervalEXT"); ASSERT(wglSwapInterval); #endif wgl_create_context_attribs_arb *wglCreateContextAttribsARB = (wgl_create_context_attribs_arb *)wglGetProcAddress("wglCreateContextAttribsARB"); ASSERT(wglCreateContextAttribsARB); //unblind current context wglMakeCurrent(WindowDC, 0); wglDeleteContext(Win32RenderContext); //make a new render context i32 AttributeList[] = { WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_DEBUG_BIT_ARB, WGL_CONTEXT_MAJOR_VERSION_ARB, MajorVersion, WGL_CONTEXT_MINOR_VERSION_ARB, MinorVersion, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, 0, }; Win32RenderContext = wglCreateContextAttribsARB(WindowDC, 0, AttributeList); if (Win32RenderContext) { if (wglMakeCurrent(WindowDC, Win32RenderContext) == TRUE) { return true; } } return false; } #pragma warning(pop) */
2.0625
2
2024-11-18T22:25:23.339785+00:00
2019-11-08T21:32:40
508db148ee741c8662feb7a2ed115a25a9300849
{ "blob_id": "508db148ee741c8662feb7a2ed115a25a9300849", "branch_name": "refs/heads/master", "committer_date": "2019-11-08T21:32:40", "content_id": "0e65f82ab618d1eca4ee3a7b4f26262478076fbc", "detected_licenses": [ "MIT" ], "directory_id": "e00b0a31da188a2902966a3ac896483f60e4cb9d", "extension": "c", "filename": "sQueue.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 218452892, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2411, "license": "MIT", "license_type": "permissive", "path": "/queue/sQueue.c", "provenance": "stackv2-0115.json.gz:121119", "repo_name": "aaryan6789/_cSpace", "revision_date": "2019-11-08T21:32:40", "revision_id": "64274c3bec98f5dc2848041e907b6083b1129577", "snapshot_id": "1665f5a731179e34d6b684ed1e70cfefd041a16e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/aaryan6789/_cSpace/64274c3bec98f5dc2848041e907b6083b1129577/queue/sQueue.c", "visit_date": "2020-08-30T18:05:17.577728" }
stackv2
/* * sQueue.c * * Created on: Feb 22, 2018 * Author: hsahu */ #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <errno.h> #include "sQueue.h" struct sQueue* createSQ() { struct sQueue *sq = (struct sQueue *)malloc(sizeof(struct sQueue)); sq->stack1 = NULL; sq->stack2 = NULL; return sq; } /** sPush - push an item on to the stack (Stack by linked List) */ void sPush(struct sNode** top_ref, int key){ struct sNode *nsNode = (struct sNode*)malloc(sizeof(struct sNode)); nsNode->data = key; nsNode->next = (*top_ref); // Link the old sNode to the new sNode (*top_ref) = nsNode; // new sNode will become the new Top pointer return; } /** sPop - Pop an item from the Stack (Stack by linked List )*/ int sPop(struct sNode** top_ref) { int pop; struct sNode* top; if(*top_ref == NULL){ printf("Stack is Empty\n"); return INT_MIN; } else{ // Get the top node top = *top_ref; pop = top->data; // Link the new top Node *top_ref = top->next; free(top); printf("Pop from Stack = %d \n", pop); return pop; } } /** * sEnqueue - Enqueue an element in the sQueue (Queue by stacks) * Enqueue the coming element by pushing it on Stack 1. */ void sEnqueue(struct sQueue* sq, int key){ sPush(&sq->stack1, key); printf("Enqueue %d on sQueue\n", key); return; } /** * sDequeue - Dequeue an element from the sQueue (Queue by Stacks) * 1. Push all the elements from Stack 1 to Stack 2 * 2. Pop the first element of Stack 2 to return the dequeued item. */ void sDequeue(struct sQueue* sq){ /* If both the Stacks are Empty then return */ if (sq->stack1 == NULL && sq->stack2 == NULL){ printf("sQueue is Empty. Nothing to sDequeue.\n"); return; } /* Push elements from stack1 to stack2 only when stack2 is empty */ if (sq->stack2 == NULL){ // Check if Stack2 is empty while(sq->stack1 != NULL){ // Push all elements from stack1 to stack2 int pop1 = sPop(&sq->stack1); sPush(&sq->stack2, pop1); } } /* Pop an element from stack2 and dequeue it*/ int pop = sPop(&sq->stack2); printf("Dequeue item from sQueue = %d\n", pop); } // void printSQueue(struct sQueue *sq) { // struct sNode* temp = sq->front; // while(temp != NULL) { // printf("%d ",temp->data); // temp = temp->next; // } // printf("\n"); // }
4.03125
4
2024-11-18T22:25:23.556578+00:00
2018-11-25T18:23:26
b3616ecda284773b9208de9d805893e111381d50
{ "blob_id": "b3616ecda284773b9208de9d805893e111381d50", "branch_name": "refs/heads/master", "committer_date": "2018-11-25T18:23:26", "content_id": "65304cd4f5b8319f85c8dbcb50a97b6ca5abac88", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "0d5a82724cf2aed3a33c2732fcbcb14630950651", "extension": "c", "filename": "debugnet.c", "fork_events_count": 5, "gha_created_at": "2018-11-25T18:17:34", "gha_event_created_at": "2019-03-16T12:06:55", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 159060889, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1083, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/debugnet.c", "provenance": "stackv2-0115.json.gz:121247", "repo_name": "orbisdev/ps4sh", "revision_date": "2018-11-25T18:23:26", "revision_id": "ba5ffd413b730d7ee26e6553128f5c4219c1f53c", "snapshot_id": "a41fc128358f32a979340b8a446bd2394832df42", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/orbisdev/ps4sh/ba5ffd413b730d7ee26e6553128f5c4219c1f53c/src/debugnet.c", "visit_date": "2020-04-08T05:27:09.317192" }
stackv2
#include "rl_common.h" #include "debugnet.h" #include <stdarg.h> void debugNetPrintf_(const char* fmt, ...) { char buffer[0x800]; va_list arg; va_start(arg, fmt); vsnprintf(buffer, sizeof(buffer), fmt, arg); va_end(arg); write_log_line(buffer); fflush(stdout); } /** * Log Level printf for debugnet library * * @par Example: * @code * debugNetPrintf(INFO,"This is a test\n"); * @endcode * * @param level - NONE,INFO,ERROR or DEBUG */ int logLevel=DEBUG; void debugNetPrintf(int level, char* format, ...) { char msgbuf[0x800]; va_list args; if (level>logLevel) return; va_start(args, format); vsnprintf(msgbuf,2048, format, args); msgbuf[2047] = 0; va_end(args); switch(level) { case INFO: debugNetPrintf_("[HOST][INFO]: [PS4SH] %s",msgbuf); break; case ERROR: debugNetPrintf_("[HOST][ERROR]: [PS4SH] %s",msgbuf); break; case DEBUG: debugNetPrintf_("[HOST][DEBUG]: [PS4SH] %s",msgbuf); break; case NONE: break; default: debugNetPrintf_("%s",msgbuf); } }
2.5625
3
2024-11-18T22:25:23.647097+00:00
2021-11-23T06:38:56
d200f2910a65918f06eeeef7512cd01291476554
{ "blob_id": "d200f2910a65918f06eeeef7512cd01291476554", "branch_name": "refs/heads/master", "committer_date": "2021-11-23T06:38:56", "content_id": "7be4ef6d27c88b778c161e3a0ede1556c033fdef", "detected_licenses": [ "MIT" ], "directory_id": "9f43eca612dd000200ae6a0669709d769c209042", "extension": "h", "filename": "iOS 跳转网页的四种方法.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 77913363, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4591, "license": "MIT", "license_type": "permissive", "path": "/LSProjectTool/File/iOS 跳转网页的四种方法.h", "provenance": "stackv2-0115.json.gz:121376", "repo_name": "Link-Start/Tools", "revision_date": "2021-11-23T06:38:56", "revision_id": "cd66663d2d38247a66fe12d3d088c5d4ea1ba293", "snapshot_id": "24970586d9fd32dccd28f8445b61a0cdde9eaff0", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Link-Start/Tools/cd66663d2d38247a66fe12d3d088c5d4ea1ba293/LSProjectTool/File/iOS 跳转网页的四种方法.h", "visit_date": "2021-12-04T01:08:56.678078" }
stackv2
// // iOS 跳转网页的四种方法.h // LSProjectTool // // Created by 刘晓龙 on 2021/6/24. // Copyright © 2021 Link-Start. All rights reserved. // #ifndef iOS___________h #define iOS___________h iOS 跳转网页的四种方法 跳转界面 push 展示网页 1.Safari : openURL:自带很多功能 (进度条,刷新,前进,倒退..)就是打开了一个浏览器,跳出自己的应用 2.UIWebView: 没有功能,在当前应用中打开网页,自己去实现某些功能,但不能实现进度条功能(有些软件做了假进度条,故意卡到70%不动,加载完成前秒到100%) 3.SFSafariViewController: iOS9+ 专门用来展示网页 需求:既想要在当前应用展示网页,又想要safari功能 需要导入#import <SafariServices/SafariServices.h>框架 #pragma mark - UICollectionViewDelegate - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{ // 小盒子的点击事件 BQLog(@"%@",indexPath); // 跳转界面 push 展示网页 /* 1.Safari openURL:自带很多功能 (进度条,刷新,前进,倒退..)就是打开了一个浏览器,跳出自己的应用 2.UIWebView:没有功能,在当前应用中打开网页,自己去实现某些功能,但不能实现进度条功能 3.SFSafariViewController:iOS9+ 专门用来展示网页 需求:既想要在当前应用展示网页,又想要safari功能 需要导入#import <SafariServices/SafariServices.h>框架 4.WKWebView:iOS8+ (UIWebView升级版本)添加功能:1)监听进度条 2)缓存 */ BQSquareItem *item = self.squareItems[indexPath.row]; if (![item.url containsString:@"http"]) { return; } SFSafariViewController *safariVc = [[SFSafariViewController alloc] initWithURL:[NSURL URLWithString:item.url]]; // safariVc.delegate = self; // self.navigationController.navigationBarHidden = YES; // [self.navigationController pushViewController:safariVc animated:YES]; [self presentViewController:safariVc animated:YES completion:nil]; // 推荐使用modal自动处理 而不是push } 4.WKWebView: iOS8+ (UIWebView升级版本)添加功能:1)监听进度条 2)缓存 需要手动导入WebKit框架 编译器默认不会导入 - (void)viewDidLoad { [super viewDidLoad]; // 添加WebView WKWebView *webView = [[WKWebView alloc] init]; _webView = webView; [self.contentView addSubview:webView]; // 加载网页 NSURLRequest *request = [NSURLRequest requestWithURL:self.url]; [webView loadRequest:request]; // KVO监听属性改变 /* KVO使用: addObserver:观察者 forKeyPath:观察webview哪个属性 options:NSKeyValueObservingOptionNew观察新值改变 注意点:对象销毁前 一定要记得移除 -dealloc */ [webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:nil]; [webView addObserver:self forKeyPath:@"canGoForward" options:NSKeyValueObservingOptionNew context:nil]; [webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil]; // 进度条 [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil]; } - (void)viewDidLayoutSubviews{ [super viewDidLayoutSubviews]; _webView.frame = self.contentView.bounds; } #pragma mark - KVO // 只要观察者有新值改变就会调用 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{ self.backItem.enabled = self.webView.canGoBack; self.forwardItem.enabled = self.webView.canGoForward; self.title = self.webView.title; self.progressView.progress = self.webView.estimatedProgress; self.progressView.hidden = self.webView.estimatedProgress>=1; } - (void)dealloc { [self.webView removeObserver:self forKeyPath:@"canGoBack"]; [self.webView removeObserver:self forKeyPath:@"canGoForward"]; [self.webView removeObserver:self forKeyPath:@"title"]; [self.webView removeObserver:self forKeyPath:@"estimatedProgress"]; } #pragma mark - 按钮的点击事件 - (IBAction)goBack:(id)sender { // 回退 [self.webView goBack]; } - (IBAction)goForward:(id)sender { // 前进 [self.webView goForward]; } - (IBAction)reload:(id)sender { //刷新 [self.webView reload]; } #endif /* iOS___________h */
2.03125
2
2024-11-18T22:25:23.712583+00:00
2015-07-04T07:40:16
a619f14d3c8c48cb2a0fb0e033545621fe9b7905
{ "blob_id": "a619f14d3c8c48cb2a0fb0e033545621fe9b7905", "branch_name": "refs/heads/master", "committer_date": "2015-07-04T07:40:16", "content_id": "885bf7a30ebc8fa48eb60071c21a0c7337b0b416", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "11cbf2c204255f982315600f7a03cf3fc285b62c", "extension": "c", "filename": "UnitTestMessages_copied.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 38526092, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2657, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/solutions/PX4/source_gen/PX4/Commander/UnitTestMessages_copied.c", "provenance": "stackv2-0115.json.gz:121504", "repo_name": "jgoppert/px4mbeddr", "revision_date": "2015-07-04T07:40:16", "revision_id": "b13c7b020fdca63d4757300662ae9463d59e54f9", "snapshot_id": "d8c72991fb04bfd6a0833d7efd5869c5a7412431", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/jgoppert/px4mbeddr/b13c7b020fdca63d4757300662ae9463d59e54f9/solutions/PX4/source_gen/PX4/Commander/UnitTestMessages_copied.c", "visit_date": "2016-09-06T12:02:52.316272" }
stackv2
#include "UnitTestMessages_copied.h" #include <stdio.h> /* * Message Reporting Function */ void UnitTestMessages_copied____testing_FAILED(int8_t testID, char *loc) { printf("$$FAILED: ***FAILED*** ("); printf("testID=%i",(((int8_t)(testID)))); printf(" @loc %s \n",loc);; } /* * Message Reporting Function */ void UnitTestMessages_copied____testing_FAILED_DOUBLE(int8_t testID, double act, char *loc) { printf("$$FAILED_DOUBLE: ***FAILED*** ("); printf("testID=%i",(((int8_t)(testID)))); printf(", act=%lf",(((double)(act)))); printf(" @loc %s \n",loc);; } /* * Message Reporting Function */ void UnitTestMessages_copied____testing_FAILED_DOUBLE_DOUBLE(int8_t testID, double act, char *op, double exp, char *loc) { printf("$$FAILED_DOUBLE_DOUBLE: ***FAILED*** ("); printf("testID=%i",(((int8_t)(testID)))); printf(", act=%lf",(((double)(act)))); printf(", op=%s",(((char *)(op)))); printf(", exp=%lf",(((double)(exp)))); printf(" @loc %s \n",loc);; } /* * Message Reporting Function */ void UnitTestMessages_copied____testing_FAILED_DOUBLE_STR(int8_t testID, double act, char *exp, char *loc) { printf("$$FAILED_DOUBLE_STR: ***FAILED*** ("); printf("testID=%i",(((int8_t)(testID)))); printf(", act=%lf",(((double)(act)))); printf(", exp=%s",(((char *)(exp)))); printf(" @loc %s \n",loc);; } /* * Message Reporting Function */ void UnitTestMessages_copied____testing_FAILED_INT(int8_t testID, int32_t act, char *loc) { printf("$$FAILED_INT: ***FAILED*** ("); printf("testID=%i",(((int8_t)(testID)))); printf(", act=%i",(((int32_t)(act)))); printf(" @loc %s \n",loc);; } /* * Message Reporting Function */ void UnitTestMessages_copied____testing_FAILED_INT_INT(int8_t testID, int32_t act, char *op, int32_t exp, char *loc) { printf("$$FAILED_INT_INT: ***FAILED*** ("); printf("testID=%i",(((int8_t)(testID)))); printf(", act=%i",(((int32_t)(act)))); printf(", op=%s",(((char *)(op)))); printf(", exp=%i",(((int32_t)(exp)))); printf(" @loc %s \n",loc);; } /* * Message Reporting Function */ void UnitTestMessages_copied____testing_FAILED_INT_STR(int8_t testID, int32_t act, char *exp, char *loc) { printf("$$FAILED_INT_STR: ***FAILED*** ("); printf("testID=%i",(((int8_t)(testID)))); printf(", act=%i",(((int32_t)(act)))); printf(", exp=%s",(((char *)(exp)))); printf(" @loc %s \n",loc);; } /* * Message Reporting Function */ void UnitTestMessages_copied____testing_runningTest(char *loc) { printf("$$runningTest: running test ("); printf(" @loc %s \n",loc);; }
2.109375
2
2024-11-18T22:25:24.213373+00:00
2014-11-04T23:15:22
c9ea0b9cc7f3dbab4d3dfa58e4390f1b5fcd463c
{ "blob_id": "c9ea0b9cc7f3dbab4d3dfa58e4390f1b5fcd463c", "branch_name": "refs/heads/master", "committer_date": "2014-11-04T23:15:22", "content_id": "0d6ed261432da03b3fca05f2d05cd717ae04cebc", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "70214efa2467f6c567b805dc923c0d288bf92733", "extension": "c", "filename": "fdtest.c", "fork_events_count": 5, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 26249164, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7272, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/tao/interface/fdtest.c", "provenance": "stackv2-0115.json.gz:121763", "repo_name": "OpenCMISS-Dependencies/petsc", "revision_date": "2014-11-04T23:15:22", "revision_id": "5334b1442d9dabf795f2fdda92d0f565f35ff948", "snapshot_id": "0684cd59bb9bddb6be03f27f2e9c183ad476b208", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/OpenCMISS-Dependencies/petsc/5334b1442d9dabf795f2fdda92d0f565f35ff948/src/tao/interface/fdtest.c", "visit_date": "2021-01-17T10:08:25.370917" }
stackv2
#include <petsc-private/taoimpl.h> /*I "petsctao.h" I*/ typedef struct { PetscBool check_gradient; PetscBool check_hessian; PetscBool complete_print; } Tao_Test; /* TaoSolve_Test - Tests whether a hand computed Hessian matches one compute via finite differences. */ #undef __FUNCT__ #define __FUNCT__ "TaoSolve_Test" PetscErrorCode TaoSolve_Test(Tao tao) { Mat A = tao->hessian,B; Vec x = tao->solution,g1,g2; PetscErrorCode ierr; PetscInt i; PetscReal nrm,gnorm,hcnorm,fdnorm; MPI_Comm comm; Tao_Test *fd = (Tao_Test*)tao->data; PetscFunctionBegin; comm = ((PetscObject)tao)->comm; if (fd->check_gradient) { ierr = VecDuplicate(x,&g1);CHKERRQ(ierr); ierr = VecDuplicate(x,&g2);CHKERRQ(ierr); ierr = PetscPrintf(comm,"Testing hand-coded gradient (hc) against finite difference gradient (fd), if the ratio ||fd - hc|| / ||hc|| is\n");CHKERRQ(ierr); ierr = PetscPrintf(comm,"0 (1.e-8), the hand-coded gradient is probably correct.\n");CHKERRQ(ierr); if (!fd->complete_print) { ierr = PetscPrintf(comm,"Run with -tao_test_display to show difference\n");CHKERRQ(ierr); ierr = PetscPrintf(comm,"between hand-coded and finite difference gradient.\n");CHKERRQ(ierr); } for (i=0; i<3; i++) { if (i == 1) {ierr = VecSet(x,-1.0);CHKERRQ(ierr);} else if (i == 2) {ierr = VecSet(x,1.0);CHKERRQ(ierr);} /* Compute both version of gradient */ ierr = TaoComputeGradient(tao,x,g1);CHKERRQ(ierr); ierr = TaoDefaultComputeGradient(tao,x,g2,NULL);CHKERRQ(ierr); if (fd->complete_print) { MPI_Comm gcomm; PetscViewer viewer; ierr = PetscPrintf(comm,"Finite difference gradient\n");CHKERRQ(ierr); ierr = PetscObjectGetComm((PetscObject)g2,&gcomm);CHKERRQ(ierr); ierr = PetscViewerASCIIGetStdout(gcomm,&viewer);CHKERRQ(ierr); ierr = VecView(g2,viewer);CHKERRQ(ierr); ierr = PetscPrintf(comm,"Hand-coded gradient\n");CHKERRQ(ierr); ierr = PetscObjectGetComm((PetscObject)g1,&gcomm);CHKERRQ(ierr); ierr = PetscViewerASCIIGetStdout(gcomm,&viewer);CHKERRQ(ierr); ierr = VecView(g1,viewer);CHKERRQ(ierr); ierr = PetscPrintf(comm,"\n");CHKERRQ(ierr); } ierr = VecAXPY(g2,-1.0,g1);CHKERRQ(ierr); ierr = VecNorm(g1,NORM_2,&hcnorm);CHKERRQ(ierr); ierr = VecNorm(g2,NORM_2,&fdnorm);CHKERRQ(ierr); if (!hcnorm) hcnorm=1.0e-20; ierr = PetscPrintf(comm,"ratio ||fd-hc||/||hc|| = %g, difference ||fd-hc|| = %g\n", (double)(fdnorm/hcnorm), (double)fdnorm);CHKERRQ(ierr); } ierr = VecDestroy(&g1);CHKERRQ(ierr); ierr = VecDestroy(&g2);CHKERRQ(ierr); } if (fd->check_hessian) { if (A != tao->hessian_pre) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Cannot test with alternative preconditioner"); ierr = PetscPrintf(comm,"Testing hand-coded Hessian (hc) against finite difference Hessian (fd). If the ratio is\n");CHKERRQ(ierr); ierr = PetscPrintf(comm,"O (1.e-8), the hand-coded Hessian is probably correct.\n");CHKERRQ(ierr); if (!fd->complete_print) { ierr = PetscPrintf(comm,"Run with -tao_test_display to show difference\n");CHKERRQ(ierr); ierr = PetscPrintf(comm,"of hand-coded and finite difference Hessian.\n");CHKERRQ(ierr); } for (i=0;i<3;i++) { /* compute both versions of Hessian */ ierr = TaoComputeHessian(tao,x,A,A);CHKERRQ(ierr); if (!i) {ierr = MatConvert(A,MATSAME,MAT_INITIAL_MATRIX,&B);CHKERRQ(ierr);} ierr = TaoDefaultComputeHessian(tao,x,B,B,tao->user_hessP);CHKERRQ(ierr); if (fd->complete_print) { MPI_Comm bcomm; PetscViewer viewer; ierr = PetscPrintf(comm,"Finite difference Hessian\n");CHKERRQ(ierr); ierr = PetscObjectGetComm((PetscObject)B,&bcomm);CHKERRQ(ierr); ierr = PetscViewerASCIIGetStdout(bcomm,&viewer);CHKERRQ(ierr); ierr = MatView(B,viewer);CHKERRQ(ierr); } /* compare */ ierr = MatAYPX(B,-1.0,A,DIFFERENT_NONZERO_PATTERN);CHKERRQ(ierr); ierr = MatNorm(B,NORM_FROBENIUS,&nrm);CHKERRQ(ierr); ierr = MatNorm(A,NORM_FROBENIUS,&gnorm);CHKERRQ(ierr); if (fd->complete_print) { MPI_Comm hcomm; PetscViewer viewer; ierr = PetscPrintf(comm,"Hand-coded Hessian\n");CHKERRQ(ierr); ierr = PetscObjectGetComm((PetscObject)B,&hcomm);CHKERRQ(ierr); ierr = PetscViewerASCIIGetStdout(hcomm,&viewer);CHKERRQ(ierr); ierr = MatView(A,viewer);CHKERRQ(ierr); ierr = PetscPrintf(comm,"Hand-coded minus finite difference Hessian\n");CHKERRQ(ierr); ierr = MatView(B,viewer);CHKERRQ(ierr); } if (!gnorm) gnorm = 1.0e-20; ierr = PetscPrintf(comm,"ratio ||fd-hc||/||hc|| = %g, difference ||fd-hc|| = %g\n",(double)(nrm/gnorm),(double)nrm);CHKERRQ(ierr); } ierr = MatDestroy(&B);CHKERRQ(ierr); } tao->reason = TAO_CONVERGED_USER; PetscFunctionReturn(0); } /* ------------------------------------------------------------ */ #undef __FUNCT__ #define __FUNCT__ "TaoDestroy_Test" PetscErrorCode TaoDestroy_Test(Tao tao) { PetscErrorCode ierr; PetscFunctionBegin; ierr = PetscFree(tao->data);CHKERRQ(ierr); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "TaoSetFromOptions_Test" static PetscErrorCode TaoSetFromOptions_Test(Tao tao) { Tao_Test *fd = (Tao_Test *)tao->data; PetscErrorCode ierr; PetscFunctionBegin; ierr = PetscOptionsHead("Hand-coded Hessian tester options");CHKERRQ(ierr); ierr = PetscOptionsBool("-tao_test_display","Display difference between hand-coded and finite difference Hessians","None",fd->complete_print,&fd->complete_print,NULL);CHKERRQ(ierr); ierr = PetscOptionsBool("-tao_test_gradient","Test Hand-coded gradient against finite-difference gradient","None",fd->check_gradient,&fd->check_gradient,NULL);CHKERRQ(ierr); ierr = PetscOptionsBool("-tao_test_hessian","Test Hand-coded hessian against finite-difference hessian","None",fd->check_hessian,&fd->check_hessian,NULL);CHKERRQ(ierr); if (fd->check_gradient == PETSC_FALSE && fd->check_hessian == PETSC_FALSE) { fd->check_gradient = PETSC_TRUE; } ierr = PetscOptionsTail();CHKERRQ(ierr); PetscFunctionReturn(0); } /* ------------------------------------------------------------ */ /*C FD_TEST - Test hand-coded Hessian against finite difference Hessian Options Database: . -tao_test_display Display difference between approximate and hand-coded Hessian Level: intermediate .seealso: TaoCreate(), TaoSetType() */ EXTERN_C_BEGIN #undef __FUNCT__ #define __FUNCT__ "TaoCreate_Test" PetscErrorCode TaoCreate_Test(Tao tao) { Tao_Test *fd; PetscErrorCode ierr; PetscFunctionBegin; tao->ops->setup = 0; tao->ops->solve = TaoSolve_Test; tao->ops->destroy = TaoDestroy_Test; tao->ops->setfromoptions = TaoSetFromOptions_Test; tao->ops->view = 0; ierr = PetscNewLog(tao,&fd);CHKERRQ(ierr); tao->data = (void*)fd; fd->complete_print = PETSC_FALSE; fd->check_gradient = PETSC_TRUE; fd->check_hessian = PETSC_FALSE; PetscFunctionReturn(0); } EXTERN_C_END
2.1875
2
2024-11-18T22:25:24.291328+00:00
2020-02-10T21:47:42
aa9a4af6725acf368f13c48e8f1dcf810d9ee799
{ "blob_id": "aa9a4af6725acf368f13c48e8f1dcf810d9ee799", "branch_name": "refs/heads/master", "committer_date": "2020-02-10T21:47:42", "content_id": "37ce48126c7cd31b24b5aeafd6d421fbd68787cc", "detected_licenses": [ "MIT" ], "directory_id": "e69dae40c6396c904026a9dcbf441e9f5941597e", "extension": "c", "filename": "handlers.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 87200128, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2277, "license": "MIT", "license_type": "permissive", "path": "/C/GTK/handlers.c", "provenance": "stackv2-0115.json.gz:121893", "repo_name": "PysKa-Ratzinger/rcomp1617pluto", "revision_date": "2020-02-10T21:47:42", "revision_id": "99e73239f1bd1bfd34f41c29659bf9ef33573aa5", "snapshot_id": "db44328b2108f56f2c2249b0a54cb012ade2215e", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/PysKa-Ratzinger/rcomp1617pluto/99e73239f1bd1bfd34f41c29659bf9ef33573aa5/C/GTK/handlers.c", "visit_date": "2021-01-19T00:41:26.307443" }
stackv2
#include "header.h" /*Closes App*/ void close_app(UNUSED, AppWidgets *app){ g_free(app); //Code Before closing comes here... (cleanup) gtk_main_quit(); } /*Show FolderPicker Window + close Start Window*/ void gtk_widget_showPicker(UNUSED, AppWidgets *app){ gtk_widget_destroy(app->Start); gtk_widget_show(app->folderPicker); } /*Show FolderPicker Window + close Start Window*/ void gtk_widget_showPicker_again(UNUSED, AppWidgets *app){ gtk_widget_hide(app->selectNick); gtk_widget_show(app->folderPicker); } /*Action when NEXT from FilePicker is clicked*/ void folder_set(UNUSED, AppWidgets *app){ /*GET FOLDER:*/ gchar *folder = gtk_file_chooser_get_uri ((GtkFileChooser*)app->folderButton); if(folder != NULL){ printf("-------\nCHOSEN FOLDER: %s\n--------", folder); /** * WHAT TO DO WITH FOLDER? * * */ //avança... gtk_widget_show(app->selectNick); gtk_widget_hide(app->folderPicker); }//else do nothing g_free (folder); } void finish(UNUSED, AppWidgets *app){ const gchar* nickname = gtk_entry_get_text((GtkEntry *) app->nickBox); printf("\n-------\nUSERNAME: %s\n-------\n", nickname); g_free((gpointer* )nickname); gtk_main_quit(); printf("\n---------\nApp closed\n---------\n"); } /* Show the About box */ void help_about(UNUSED, AppWidgets *app){ gtk_widget_hide(app->Start); gtk_widget_show(app->HelpAboutDialog); } /*Close About box*/ void closeHelpAbout(UNUSED, AppWidgets* app){ gtk_widget_hide(app->HelpAboutDialog); gtk_widget_show(app->Start); } /*Show team info from About Dialog*/ void show_team(UNUSED, AppWidgets* app){ gtk_widget_show(app->theTeam); } /*Show team info from license Dialog*/ void show_team2(UNUSED, AppWidgets* app){ gtk_widget_hide(app->licenseWindow); gtk_widget_show(app->theTeam); } /*Shows License from About Dialog*/ void show_license(UNUSED, AppWidgets* app){ gtk_widget_show(app->licenseWindow); } /*Shows License from license Dialog*/ void show_license2(UNUSED, AppWidgets* app){ gtk_widget_show(app->licenseWindow); gtk_widget_hide(app->theTeam); } void close_license(UNUSED, AppWidgets* app){ gtk_widget_hide(app->licenseWindow); } /*Closes team info*/ void closeTheTeam(UNUSED, AppWidgets* app){ gtk_widget_hide(app->theTeam); }
2.046875
2
2024-11-18T22:25:24.533450+00:00
2020-08-27T23:19:18
7fe4a53f2c418e4696752a8b9a02673b7ce233de
{ "blob_id": "7fe4a53f2c418e4696752a8b9a02673b7ce233de", "branch_name": "refs/heads/master", "committer_date": "2020-08-27T23:19:18", "content_id": "579eb8d18aeddb5e5f6b0363a33f439d00d51474", "detected_licenses": [ "MIT" ], "directory_id": "f8d14654c35bd4a33ea4ce7dfa5d1937e4f6f284", "extension": "c", "filename": "4-puts.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 238567022, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 234, "license": "MIT", "license_type": "permissive", "path": "/0x00-hello_world/4-puts.c", "provenance": "stackv2-0115.json.gz:122023", "repo_name": "jfbm74/holbertonschool-low_level_programming", "revision_date": "2020-08-27T23:19:18", "revision_id": "9cedaff870af333af5df085cdd776d43f48634d2", "snapshot_id": "b2734369e97d7c2290bf6ad34c8d1e7c88fb93fd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jfbm74/holbertonschool-low_level_programming/9cedaff870af333af5df085cdd776d43f48634d2/0x00-hello_world/4-puts.c", "visit_date": "2020-12-29T10:06:29.349223" }
stackv2
#include <stdio.h> /** * main - runs the all the code * * Description: Run puts and print statement * Return: Return 0 to exit function */ int main(void) { puts("\"Programming is like building a multilingual puzzle"); return (0); }
2.578125
3
2024-11-18T22:25:24.873033+00:00
2021-06-09T15:19:32
fa836f85cac0581f84af02e44bc7469699b3975f
{ "blob_id": "fa836f85cac0581f84af02e44bc7469699b3975f", "branch_name": "refs/heads/main", "committer_date": "2021-06-09T15:19:32", "content_id": "9968ba6611e30652f1f0c4b2465c671b46a755de", "detected_licenses": [ "MIT" ], "directory_id": "4f517624577db8776979d5bb1816add7bea41190", "extension": "c", "filename": "photon.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 374425236, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1724, "license": "MIT", "license_type": "permissive", "path": "/block2/2-PhotonGas/Source/photon.c", "provenance": "stackv2-0115.json.gz:122408", "repo_name": "Amin-Debabeche/advanced_comput", "revision_date": "2021-06-09T15:19:32", "revision_id": "17175765c5c3d6079e48dc88d8e0a11435e7ec8a", "snapshot_id": "e479290ce47a3f7efa17d70c3b2588a6ad273f75", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Amin-Debabeche/advanced_comput/17175765c5c3d6079e48dc88d8e0a11435e7ec8a/block2/2-PhotonGas/Source/photon.c", "visit_date": "2023-05-31T06:41:53.817447" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include "ran_uniform.h" #define CycleMultiplication 1000 int main(void) { int NumberOfCycles,NumberOfInitializationSteps,New,Old,i,j; double Beta,Sum,Count; // initialize the random number generator with the system time InitializeRandomNumberGenerator(time(0l)); // read the input parameters printf("How many cycles (x %d)? ",CycleMultiplication); fscanf(stdin,"%d",&NumberOfCycles); printf("How many initialization cycles (x %d)? ",CycleMultiplication); fscanf(stdin,"%d",&NumberOfInitializationSteps); if(NumberOfInitializationSteps>=NumberOfCycles) { printf("Initialisation must be shorter than the run!\n"); exit(0); } printf("Beta*epsilon ? (Example: 1.0"); fscanf(stdin,"%lf",&Beta); New=1; Old=1; Sum=0.0; Count=0.0; // Loop Over All Cycles for(i=0;i<NumberOfCycles;i++) { for(j=0;j<CycleMultiplication;j++) { // start modification if (RandomNumber()<0.5) New =Old+((int)(RandomNumber()*5)); else New=Old-((int)(RandomNumber()*5)); if (New<0) New=0; // end modification // accept or reject if(RandomNumber()<exp(-Beta*(New-Old))) { Old=New; } // calculate average occupancy result if(i>NumberOfInitializationSteps) { Sum+=Old; Count+=1.0; } } } // write the final result printf( "\nResults:\n" ); printf("Average Value : %lf\n",Sum/Count); printf("Theoretical Value : %lf\n",1.0/(exp(Beta)-1.0)); printf("Relative Error : %lf\n",fabs((exp(Beta)-1.0)*((Sum/Count) - (1.0/(exp(Beta)-1.0))))); return 0; }
3
3
2024-11-18T22:25:24.943043+00:00
2020-09-14T12:38:01
eed48fd03199efcc467f5bc944e12a72dd806f4f
{ "blob_id": "eed48fd03199efcc467f5bc944e12a72dd806f4f", "branch_name": "refs/heads/master", "committer_date": "2020-09-14T12:38:01", "content_id": "2b442c8a0fbf0d3d48aca8330dc87ed088def68b", "detected_licenses": [ "MIT" ], "directory_id": "21da312b3484ffa2890b3318c35a64251aa303e9", "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": 67823039, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5634, "license": "MIT", "license_type": "permissive", "path": "/src/double/helpers.c", "provenance": "stackv2-0115.json.gz:122536", "repo_name": "mathigatti/orga2-tp", "revision_date": "2020-09-14T12:38:01", "revision_id": "3e8dfb8f97672c3bec06987899929da79528d119", "snapshot_id": "eccfa607a350a2b135a7f1dd676d07a783005cd3", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/mathigatti/orga2-tp/3e8dfb8f97672c3bec06987899929da79528d119/src/double/helpers.c", "visit_date": "2021-03-22T01:29:34.957208" }
stackv2
#include "helpers.h" Images* trainSetReader() { printf("Loading training set...\n"); char buffer[150]; char *record,*line; Images* Img = (Images*) malloc(sizeof(Images)); Img->mat = (double*) malloc(IMGS_NUM * IMG_SIZE * sizeof(double)); Img->res = (int*) malloc(IMGS_NUM * sizeof(double)); Img->size = IMGS_NUM; FILE *fstream = fopen("data/train_set.txt","r"); if(fstream == NULL) { printf("\n file opening failed "); return NULL ; } for(int i = 0; i<IMGS_NUM; i++){ for(int j = 0; j<IMG_SIZE; j++){ line=fgets(buffer,sizeof(buffer),fstream); record = strtok(line,"\n"); Img->mat[i * IMG_SIZE + j] = atof(record); record = strtok(NULL,"\n"); } line=fgets(buffer,sizeof(buffer),fstream); record = strtok(line,"\n"); Img->res[i] = atoi(record); record = strtok(NULL,"\n"); } fclose(fstream); return Img; } Images* testSetReader() { printf("Loading test set...\n"); char buffer[150]; char *record,*line; Images* Img = (Images*) malloc(sizeof(Images)); Img->mat = (double*) malloc(TEST_IMGS_NUM * IMG_SIZE * sizeof(double)); Img->res = (int*) malloc(TEST_IMGS_NUM * sizeof(double)); Img->size = TEST_IMGS_NUM; FILE *fstream = fopen("data/test_set.txt","r"); if(fstream == NULL) { printf("\n file opening failed "); return NULL ; } for(int i = 0; i<TEST_IMGS_NUM; i++){ for(int j = 0; j<IMG_SIZE; j++){ line=fgets(buffer,sizeof(buffer),fstream); record = strtok(line,"\n"); Img->mat[i * IMG_SIZE + j] = atof(record); record = strtok(NULL,"\n"); } line=fgets(buffer,sizeof(buffer),fstream); record = strtok(line,"\n"); Img->res[i] = atoi(record); record = strtok(NULL,"\n"); } fclose(fstream); return Img; } double* loadTestImage(double* matrix, const char* inputImage) { printf("Loading test image...\n"); char buffer[150]; char *record,*line; FILE *fstream = fopen(inputImage,"r"); if(fstream == NULL) { printf("\n file opening failed\n"); return NULL ; } for(int j = 0; j<IMG_SIZE; j++){ line=fgets(buffer,sizeof(buffer),fstream); record = strtok(line,"\n"); matrix[j] = atof(record); } fclose(fstream); } void imagesDestructor(Images* imgs) { free(imgs->mat); free(imgs->res); free(imgs); } void random_shuffle(Images* batch) { size_t n = batch->size; if (n > 1) { size_t i; for (i = 0; i < n - 1; i++) { size_t j = i + rand() / (RAND_MAX / (n - i) + 1); // We permute the rows of batch.mat double temp_pixel; for(uint k = 0; k < 784; k++) { temp_pixel = batch->mat[j * 784 + k]; batch->mat[j * 784 + k] = batch->mat[i * 784 + k]; batch->mat[i * 784 + k] = temp_pixel; } // Finally, let's permute the targets int temp_res = batch->res[j]; batch->res[j] = batch->res[i]; batch->res[i] = temp_res; } } } void printImg(double* img) { for(uint i = 0; i < 28; i++) { for(uint j = 0; j < 28; j++) { if(img[i * 28 + j] >= 0.45) { printf("O"); } else { printf(" "); } } printf("\n"); } } void printMatrix(double* matrix, int n, int m) { for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { printf("%.3f ", matrix[i * m + j]); } printf("\n"); } } double sigmoid(double number){ /*The sigmoid function.*/ return 1/(1 + exp(-number)); } double sigmoid_prime(double number){ double sig = sigmoid(number); return sig * (1 - sig); } // A Implementar en ASM int max_arg(double* vector, uint n) { int maxIndex = 0; double maxValue = vector[maxIndex]; for(int i = 1; i < n; i++){ if(maxValue < vector[i]) { maxIndex = i; maxValue = vector[i]; } } return maxIndex; } void transpose(double* matrix, uint n, uint m, double* output){ /* NOTA: n y m no tienen que coincidir forzosamente con la cantidad de filas y columnas real de matrix. Por ejemplo, si matrix es pxm con n < p, output sera la matriz que tenga por columnas las primeras n filas de matrix. Esto es util a la hora de usar mini batches. */ for(uint i = 0; i < n; i++) { for (int j = 0; j < m; j++) { output[j * n + i] = matrix[i * m + j]; } } } void sigmoid_v(double* matrix, uint n, uint m, double* output){ /*The sigmoid function.*/ for(uint i = 0; i < n; i++){ for(uint j = 0; j < m; j++) { output[i * m + j] = sigmoid(matrix[i * m + j]); } } } void sigmoid_prime_v(double* matrix, uint n, uint m, double* output){ double sig; double minusOneSig; for(uint i = 0; i < n; i++){ for(uint j = 0; j < m; j++){ sig = sigmoid(matrix[i * m + j]); minusOneSig = 1 - sig; output[i * m + j] = minusOneSig * sig; } } } void randomVector(uint size, double* vector, uint randMax){ for (uint i = 0; i < size; i++){ vector[i] = (double) rand() / RAND_MAX; } } void randomMatrix(double* matrix, uint n, uint m){ for (uint i = 0; i < n; i++){ for (uint j = 0; j < m; j++){ matrix[i * m + j] = (double) rand() / RAND_MAX; } } } void compress(double* matrix, uint n, uint m, double* output) { // output.length() = n for (int i = 0; i < n; i++) { output[i] = 0.0; for (int j = 0; j < m; j++) { output[i] += matrix[i * m + j]; } } } void mat_plus_vec(double* matrix, double* vector, uint n, uint m, double* output){ // |vector| == n for(int i = 0; i < n; i++){ double val = vector[i]; for (int j = 0; j < m; j++) { output[i * m + j] = val + matrix[i * m + j]; } } }
2.578125
3
2024-11-18T22:25:25.678406+00:00
2016-04-18T01:10:56
bbf8aed0ee1168ade109c3c5049fec0fe9aee20d
{ "blob_id": "bbf8aed0ee1168ade109c3c5049fec0fe9aee20d", "branch_name": "refs/heads/master", "committer_date": "2016-04-18T01:10:56", "content_id": "9275f4c7b49c5a106e1dd6dca4b9bad98e9a6bca", "detected_licenses": [ "MIT" ], "directory_id": "0d4334535ee13461160fa94ec16fab2e73e36eef", "extension": "c", "filename": "map.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 55247785, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1941, "license": "MIT", "license_type": "permissive", "path": "/src/map.c", "provenance": "stackv2-0115.json.gz:122929", "repo_name": "astery/the-garden", "revision_date": "2016-04-18T01:10:56", "revision_id": "996cd310649f36c1ea547c5aa8fac78254157325", "snapshot_id": "8a2227ce4b6385ec55f8c3a4492abf996127d3c4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/astery/the-garden/996cd310649f36c1ea547c5aa8fac78254157325/src/map.c", "visit_date": "2021-01-10T13:57:07.354302" }
stackv2
/* * map.c * * Created on: Apr 6, 2016 * Author: astery */ #include "map.h" #include <stdlib.h> #include "colors.h" #include "position.h" void Map_Init(Map *map) { int i, j; Tile *tile; for (i=0; i < MAP_SIZE; i++) { for (j=0; j < MAP_SIZE; j++) { tile = &map->tiles[i][j]; // TODO: Tile_Init tile->pos.x = i; tile->pos.y = j; tile->items_count = 0; tile->default_item.tile = tile; tile->default_item.type = NONE; } } map->border.type = WALL; } void Map_AppendFromItemTypeArray(Map *map, MapSlice slice) { int i, j; Tile *tile; for (i=0; i < MAP_SIZE; i++) { for (j=0; j < MAP_SIZE; j++) { TileItemType type = slice.tiles[j][i]; if (type == NONE) { continue; } tile = &map->tiles[i][j]; TileItem *item = &tile->items[tile->items_count]; item->type = type; item->tile = tile; tile->items_count++; } } } void Map_Render(Map *map, SDL_Renderer *renderer) { SDL_SetRenderDrawColor(renderer, 0xf, 0xf, 0xf, 0xf); SDL_RenderClear(renderer); int i, j; for (i=0; i < MAP_SIZE; i++) { for (j=0; j < MAP_SIZE; j++) { Tile_Render(&map->tiles[i][j], renderer); } } return; } TileItem* Map_GetTopItemAtPos(Map *map, Position pos) { if (!Position_IsInMapBoundaries(&pos, map)) { return &map->border; } Tile *tile = &map->tiles[pos.x][pos.y]; return Tile_GetTopItem(tile); } bool Map_IsWallAtPos(Map *map, Position pos) { if (!Position_IsInMapBoundaries(&pos, map)) { return true; } TileItem *item = Map_GetTopItemAtPos(map, pos); return item->type == WALL; } int Map_GetFrontWallDistance(Map *map, Position *pos, Orientation orient) { int dist = 0; Position p_next = *pos; do { dist++; p_next = Position_NextToOrientation(&p_next, orient); // TODO: traverse all TileItem *item = Map_GetTopItemAtPos(map, p_next); if (item->type == WALL) { return dist; } } while (Position_IsInMapBoundaries(&p_next, map)); return dist; }
2.984375
3
2024-11-18T22:25:25.846342+00:00
2017-12-14T03:13:06
3d4f5c253a0e448cbcf5443ac57f1a941133c573
{ "blob_id": "3d4f5c253a0e448cbcf5443ac57f1a941133c573", "branch_name": "refs/heads/master", "committer_date": "2017-12-14T03:13:06", "content_id": "9c2a1cd07da6bdf943ea1d8f79da92bb484a7679", "detected_licenses": [ "MIT" ], "directory_id": "1924644bc1c87e947544b6a930b15d1ddc00be57", "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": 113690152, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 175, "license": "MIT", "license_type": "permissive", "path": "/9-dec/9_gv2.c/main.c", "provenance": "stackv2-0115.json.gz:123059", "repo_name": "kasiriveni/c-examples", "revision_date": "2017-12-14T03:13:06", "revision_id": "79f1c302d8069e17dae342739420602bb58315f8", "snapshot_id": "f3824879d55987bfed73239d65d3692227a449f2", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/kasiriveni/c-examples/79f1c302d8069e17dae342739420602bb58315f8/9-dec/9_gv2.c/main.c", "visit_date": "2021-05-06T16:21:51.221273" }
stackv2
// a program on both local and global variable has same names #include <stdio.h> int g = 20; int main () { int g = 10; printf ("value of g = %d\n", g); return 0; }
2.765625
3
2024-11-18T22:25:26.219015+00:00
2016-09-25T16:01:02
b93efef10b91b589eb55e850bfddb2b12ec7ded2
{ "blob_id": "b93efef10b91b589eb55e850bfddb2b12ec7ded2", "branch_name": "refs/heads/master", "committer_date": "2016-09-25T16:01:02", "content_id": "20e5a8d6274a66cd51d80f30fe1bf4d7fc2fb9d8", "detected_licenses": [ "MIT" ], "directory_id": "cf13a282ff6ae8949f71b21fff50a6d0768da59c", "extension": "c", "filename": "plsa.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 68613883, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13780, "license": "MIT", "license_type": "permissive", "path": "/plsa.c", "provenance": "stackv2-0115.json.gz:123322", "repo_name": "hsnaves/JusBrasil", "revision_date": "2016-09-25T16:01:02", "revision_id": "96685985948b0e9bdb5deaa4d670506e6342eb6b", "snapshot_id": "bb4fee52aeecd131e28cc17a751330e62f061d77", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/hsnaves/JusBrasil/96685985948b0e9bdb5deaa4d670506e6342eb6b/plsa.c", "visit_date": "2020-12-25T22:47:34.208662" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "plsa.h" #include "args.h" #include "docinfo.h" #include "utils.h" #include "random.h" void plsa_reset(plsa *pl) { pl->dt = NULL; pl->dt2 = NULL; pl->tw = NULL; pl->tw2 = NULL; pl->top = NULL; } int plsa_initialize(plsa *pl) { plsa_reset(pl); pl->likelihood = 1; pl->old_likelihood = 1; return TRUE; } static void plsa_cleanup_tables(plsa *pl) { if (pl->dt) { free(pl->dt); pl->dt = NULL; } if (pl->dt2) { free(pl->dt2); pl->dt2 = NULL; } if (pl->tw) { free(pl->tw); pl->tw = NULL; } if (pl->tw2) { free(pl->tw2); pl->tw2 = NULL; } } static void plsa_cleanup_temporary(plsa *pl) { if (pl->top) { free(pl->top); pl->top = NULL; } } void plsa_cleanup(plsa *pl) { plsa_cleanup_tables(pl); plsa_cleanup_temporary(pl); } static void plsa_initialize_random(plsa *pl, int retrain_dt) { unsigned int i, j, k, pos; double sum; for (i = 0; i < pl->num_documents; i++) { sum = 0; for (j = 0; j < pl->num_topics; j++) { pos = i * pl->num_topics + j; pl->dt[pos] = -log(genrand_real1()); sum += pl->dt[pos]; } for (j = 0; j < pl->num_topics; j++) { pos = i * pl->num_topics + j; pl->dt[pos] /= sum; } } if (retrain_dt) return; for (j = 0; j < pl->num_topics; j++) { sum = 0; for (k = 0; k < pl->num_words; k++) { pos = j * pl->num_words + k; pl->tw[pos] = -log(genrand_real1()); sum += pl->tw[pos]; } for (k = 0; k < pl->num_words; k++) { pos = j * pl->num_words + k; pl->tw[pos] /= sum; } } } static double plsa_iteration(plsa *pl, const docinfo *doc, int update_dt, int update_tw) { unsigned pos, pos2; unsigned int i, j, k, l, num_wordstats; double dotprod, val, sum, likelihood, total_weight; docinfo_wordstats *wordstats; docinfo_document *document; size_t size; if (update_dt) { size = pl->num_documents * pl->num_topics * sizeof(double); memset(pl->dt2, 0, size); } if (update_tw) { size = pl->num_topics * pl->num_words * sizeof(double); memset(pl->tw2, 0, size); } likelihood = 0; total_weight = 0; num_wordstats = docinfo_num_wordstats(doc); for (l = 0; l < num_wordstats; l++) { wordstats = docinfo_get_wordstats(doc, l + 1); k = wordstats->document - 1; i = wordstats->word - 1; document = docinfo_get_document(doc, wordstats->document); dotprod = 0; for (j = 0; j < pl->num_topics; j++) { pos = k * pl->num_topics + j; pos2 = j * pl->num_words + i; dotprod += pl->dt[pos] * pl->tw[pos2]; } likelihood += wordstats->count * log(dotprod); total_weight += wordstats->count; for (j = 0; j < pl->num_topics; j++) { pos = k * pl->num_topics + j; pos2 = j * pl->num_words + i; val = wordstats->count * pl->dt[pos] * pl->tw[pos2] / dotprod; if (update_dt) pl->dt2[pos] += val / document->word_count; if (update_tw) pl->tw2[pos2] += val; } } if (update_tw) { for (j = 0; j < pl->num_topics; j++) { sum = 0; for (i = 0; i < pl->num_words; i++) { pos2 = j * pl->num_words + i; sum += pl->tw2[pos2]; } for (i = 0; i < pl->num_words; i++) { pos2 = j * pl->num_words + i; pl->tw2[pos2] /= sum; } } } return likelihood / total_weight; } static int plsa_allocate_tables(plsa *pl, unsigned int num_words, unsigned int num_documents, unsigned int num_topics) { size_t size; if (pl->num_documents != num_documents || pl->num_topics != num_topics) { if (pl->dt) { free(pl->dt); pl->dt = NULL; } if (pl->dt2) { free(pl->dt2); pl->dt2 = NULL; } } if (pl->num_topics != num_topics || pl->num_words != num_words) { if (pl->tw) { free(pl->tw); pl->tw = NULL; } if (pl->tw2) { free(pl->tw2); pl->tw2 = NULL; } } pl->num_documents = num_documents; pl->num_words = num_words; pl->num_topics = num_topics; size = pl->num_documents * num_topics * sizeof(double); if (!pl->dt) { pl->dt = (double *) xmalloc(size); if (!pl->dt) return FALSE; } if (!pl->dt2) { pl->dt2 = (double *) xmalloc(size); if (!pl->dt2) return FALSE; } size = num_topics * pl->num_words * sizeof(double); if (!pl->tw) { pl->tw = (double *) xmalloc(size); if (!pl->tw) return FALSE; } if (!pl->tw2) { pl->tw2 = (double *) xmalloc(size); if (!pl->tw2) return FALSE; } return TRUE; } int plsa_train(plsa *pl, const docinfo *doc, unsigned int num_topics, unsigned int max_iterations, double tol, int retrain_dt, const char *plsa_filename) { unsigned int iter; double *temp; if (!plsa_allocate_tables(pl, docinfo_num_different_words(doc), docinfo_num_documents(doc), num_topics)) return FALSE; if (retrain_dt) { pl->likelihood = 1; pl->old_likelihood = 1; } if (pl->likelihood >= 0) plsa_initialize_random(pl, retrain_dt); else if (fabs(pl->likelihood - pl->old_likelihood) < tol) { return TRUE; } printf("Running PLSA on data...\n"); for (iter = 0; iter < max_iterations; iter++) { pl->old_likelihood = pl->likelihood; pl->likelihood = plsa_iteration(pl, doc, TRUE, !retrain_dt); printf("Iteration %d: likelihood = %g\n", iter + 1, pl->likelihood); temp = pl->dt; pl->dt = pl->dt2; pl->dt2 = temp; if (!retrain_dt) { temp = pl->tw; pl->tw = pl->tw2; pl->tw2 = temp; if ((iter % 10) == 9 && plsa_filename) { printf("Saving temporary PLSA `%s'...\n", plsa_filename); if (!plsa_save_easy(pl, plsa_filename)) return FALSE; } } if (pl->old_likelihood < 0 && fabs(pl->likelihood - pl->old_likelihood) < tol) { break; } } if (plsa_filename) { printf("Saving PLSA `%s'...\n", plsa_filename); if (!plsa_save_easy(pl, plsa_filename)) { return FALSE; } } return TRUE; } static int cmp_topmost(const void *p1, const void *p2, void *arg) { const plsa_topmost *t1 = (const plsa_topmost *) p1; const plsa_topmost *t2 = (const plsa_topmost *) p2; if (t1->val < t2->val) return 1; if (t1->val > t2->val) return -1; return 0; } static int plsa_allocate_temporary(plsa *pl) { size_t size; plsa_cleanup_temporary(pl); size = MAX(pl->num_words, pl->num_topics) * sizeof(plsa_topmost); pl->top = (plsa_topmost *) xmalloc(size); if (!pl->top) return FALSE; return TRUE; } int plsa_print_topics(plsa *pl, const docinfo *doc, unsigned top_words) { unsigned int j, l; const char *token; if (!plsa_allocate_temporary(pl)) return FALSE; top_words = MIN(top_words, pl->num_words); printf("Summary of topics:\n\n"); for (l = 0; l < pl->num_topics; l++) { for (j = 0; j < pl->num_words; j++) { pl->top[j].idx = j; pl->top[j].val = pl->tw[l * pl->num_words + j]; } xsort(pl->top, pl->num_words, sizeof(plsa_topmost), &cmp_topmost, NULL); printf("\nTopic %d:\n", l + 1); for (j = 0; j < top_words; j++) { token = docinfo_get_word(doc, pl->top[j].idx + 1); printf("%s: %g\n", token, pl->top[j].val); } } printf("\n\n"); return TRUE; } int plsa_print_documents(plsa *pl, const docinfo *doc, unsigned top_topics) { unsigned int i, j, l; if (!plsa_allocate_temporary(pl)) return FALSE; top_topics = MIN(top_topics, pl->num_topics); for (i = 0; i < pl->num_documents; i++) { docinfo_document *document; printf("Document %u:\n", i + 1); document = docinfo_get_document(doc, i + 1); for (j = 0; j < document->word_count; j++) { printf("%s ", docinfo_get_word_in_doc(doc, document, j + 1)); } printf("\n"); for (l = 0; l < pl->num_topics; l++) { pl->top[l].idx = l; pl->top[l].val = pl->dt[i * pl->num_topics + l]; } xsort(pl->top, pl->num_topics, sizeof(plsa_topmost), &cmp_topmost, NULL); for (l = 0; l < top_topics; l++) { printf("%u: %.4f, ", pl->top[l].idx + 1, pl->top[l].val); } printf("\n\n"); } return TRUE; } int plsa_save(const plsa *pl, FILE *fp) { unsigned int nmemb; if (fwrite(&pl->num_words, sizeof(unsigned int), 1, fp) != 1) return FALSE; if (fwrite(&pl->num_documents, sizeof(unsigned int), 1, fp) != 1) return FALSE; if (fwrite(&pl->num_topics, sizeof(unsigned int), 1, fp) != 1) return FALSE; if (fwrite(&pl->likelihood, sizeof(double), 1, fp) != 1) return FALSE; if (fwrite(&pl->old_likelihood, sizeof(double), 1, fp) != 1) return FALSE; nmemb = pl->num_documents * pl->num_topics; if (fwrite(pl->dt, sizeof(double), nmemb, fp) != nmemb) return FALSE; nmemb = pl->num_topics * pl->num_words; if (fwrite(pl->tw, sizeof(double), nmemb, fp) != nmemb) return FALSE; return TRUE; } int plsa_save_easy(const plsa *pl, const char *filename) { FILE *fp; int ret; fp = fopen(filename, "wb"); if (!fp) { error("could not open `%s' for writing", filename); return FALSE; } ret = plsa_save(pl, fp); fclose(fp); return ret; } int plsa_load(plsa *pl, FILE *fp) { unsigned int nmemb, num_words, num_documents, num_topics; plsa_reset(pl); if (!plsa_initialize(pl)) return FALSE; if (fread(&num_words, sizeof(unsigned int), 1, fp) != 1) return FALSE; if (fread(&num_documents, sizeof(unsigned int), 1, fp) != 1) return FALSE; if (fread(&num_topics, sizeof(unsigned int), 1, fp) != 1) return FALSE; if (fread(&pl->likelihood, sizeof(double), 1, fp) != 1) return FALSE; if (fread(&pl->old_likelihood, sizeof(double), 1, fp) != 1) return FALSE; if (!plsa_allocate_tables(pl, num_words, num_documents, num_topics)) goto error_load; nmemb = pl->num_documents * pl->num_topics; if (fread(pl->dt, sizeof(double), nmemb, fp) != nmemb) goto error_load; nmemb = pl->num_topics * pl->num_words; if (fread(pl->tw, sizeof(double), nmemb, fp) != nmemb) goto error_load; return TRUE; error_load: error("could not load PLSA"); plsa_cleanup(pl); return FALSE; } int plsa_load_easy(plsa *pl, const char *filename) { FILE *fp; int ret; fp = fopen(filename, "rb"); if (!fp) { error("could not open `%s' for reading", filename); return FALSE; } ret = plsa_load(pl, fp); fclose(fp); return ret; } int plsa_build_cached(plsa *pl, const char *plsa_file, const docinfo *doc, unsigned int num_topics, unsigned int max_iter, double tol) { FILE *fp = NULL; int ret; plsa_reset(pl); if (plsa_file) fp = fopen(plsa_file, "rb"); if (fp) { printf("Loading PLSA `%s'...\n", plsa_file); ret = plsa_load(pl, fp); fclose(fp); if (!ret) return FALSE; } else { if (!plsa_initialize(pl)) return FALSE; } if (!plsa_train(pl, doc, num_topics, max_iter, tol, FALSE, plsa_file)) { plsa_cleanup(pl); return FALSE; } return TRUE; } static int do_main(const char *docinfo_file, const char *training_file, const char *ignore_file, const char *plsa_file, unsigned int num_topics, unsigned int max_iter, double tol, unsigned int top_words, const char *test_file, unsigned int top_topics) { docinfo doc; plsa pl; docinfo_reset(&doc); plsa_reset(&pl); if (!docinfo_build_cached(&doc, docinfo_file, training_file, ignore_file)) goto error_main; if (!plsa_build_cached(&pl, plsa_file, &doc, num_topics, max_iter, tol)) goto error_main; if (top_words > 0) { if (!plsa_print_topics(&pl, &doc, top_words)) goto error_main; } if (test_file) { docinfo_clear(&doc, TRUE); if (!docinfo_process_file(&doc, test_file, FALSE)) goto error_main; if (!plsa_train(&pl, &doc, num_topics, max_iter, tol, TRUE, NULL)) goto error_main; if (top_topics > 0) { if (!plsa_print_documents(&pl, &doc, top_topics)) goto error_main; } } docinfo_cleanup(&doc); plsa_cleanup(&pl); return TRUE; error_main: docinfo_cleanup(&doc); plsa_cleanup(&pl); return FALSE; } int main(int argc, char **argv) { char *docinfo_file, *plsa_file; char *training_file, *ignore_file; char *test_file; unsigned int top_words, top_topics; unsigned int num_topics, max_iter; double tol; option opts[] = { { "-d", NULL, ARGTYPE_FILE, "specify the DOCINFO file" }, { "-t", NULL, ARGTYPE_FILE, "specify the training file" }, { "-i", NULL, ARGTYPE_FILE, "specify the ignore file" }, { "-p", NULL, ARGTYPE_FILE, "specify the PLSA file" }, { "-q", NULL, ARGTYPE_UINT, "the number of topics" }, { "-m", NULL, ARGTYPE_UINT, "the maximum number of iterations" }, { "-e", NULL, ARGTYPE_DBL, "the tolerance for convergence" }, { "-w", NULL, ARGTYPE_UINT, "the number of words per topic" }, { "-y", NULL, ARGTYPE_FILE, "specify the test file" }, { "-z", NULL, ARGTYPE_UINT, "the number of topics per document" }, { "--help", NULL, ARGTYPE_NONE, "print this help" }, }; unsigned int num_opts; int ret; #if 1 setvbuf(stdout, 0, _IONBF, 0); setvbuf(stderr, 0, _IONBF, 0); #endif opts[0].ptr = &docinfo_file; opts[1].ptr = &training_file; opts[2].ptr = &ignore_file; opts[3].ptr = &plsa_file; opts[4].ptr = &num_topics; opts[5].ptr = &max_iter; opts[6].ptr = &tol; opts[7].ptr = &top_words; opts[8].ptr = &test_file; opts[9].ptr = &top_topics; genrand_randomize(); docinfo_file = NULL; plsa_file = NULL; training_file = NULL; ignore_file = NULL; test_file = NULL; top_words = 0; top_topics = 0; num_topics = 0; max_iter = 0; tol = 0; num_opts = sizeof(opts) / sizeof(option); if (argc == 1) { print_help(argv[0], opts, num_opts); return 0; } ret = process_args(argc, argv, opts, num_opts); if (ret <= 0) return ret; if (!do_main(docinfo_file, training_file, ignore_file, plsa_file, num_topics, max_iter, tol, top_words, test_file, top_topics)) return -1; return 0; }
2.1875
2
2024-11-18T22:25:26.409577+00:00
2016-02-20T09:59:41
0c1ce7fe91d3b80c0087c60d320e3cf8a1f98d66
{ "blob_id": "0c1ce7fe91d3b80c0087c60d320e3cf8a1f98d66", "branch_name": "refs/heads/master", "committer_date": "2016-02-20T09:59:41", "content_id": "2bb7066e1be43f58db4692a42bf6729c88504ad7", "detected_licenses": [ "Apache-2.0" ], "directory_id": "34ace2ca7bde7ca3489c886c25a46090cdf607cd", "extension": "c", "filename": "parser.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 52146992, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1792, "license": "Apache-2.0", "license_type": "permissive", "path": "/parser.c", "provenance": "stackv2-0115.json.gz:123581", "repo_name": "I-Valchev/easy-lang", "revision_date": "2016-02-20T09:59:41", "revision_id": "ac0a31bb193646e79b21aa6e907c353dac7069bf", "snapshot_id": "540529bde65fb859c726a27a138ff01bcb5c943a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/I-Valchev/easy-lang/ac0a31bb193646e79b21aa6e907c353dac7069bf/parser.c", "visit_date": "2021-01-10T17:46:58.721564" }
stackv2
#include <stdlib.h> #include "lex.h" #include "error.h" #include "parser.h" #include <stdio.h> static Expression* new_expression(void){ return (Expression *) malloc (sizeof(Expression)); } static void free_expression(Expression *expr) {free((void*) expr);} static int Parse_operator(Operator *oper_p); static int Parse_expression(Expression **expr_p, FILE* source_file); static int Parse_operator(Operator *oper){ if(Token.class == '+'){ *oper = '+'; return 1; } if(Token.class == '*'){ *oper = '*'; return 1; } return 0; } static int Parse_expression(Expression **expr_p, FILE* source_file){ Expression *expr = *expr_p = new_expression(); if(Token.class == DIGIT){ expr->type = 'D'; expr->value = Token.repr - '0'; }else if(Token.class == '('){ expr->type = 'P'; get_next_token(source_file); if(!Parse_expression(&expr->left, source_file)){ Error("Missing expression"); } if(!Parse_operator(&expr->oper)){ Error("Missing operator"); } get_next_token(source_file); if(!Parse_expression(&expr->right, source_file)){ Error("Missing expression"); } if(Token.class != ')'){ Error("Missing )"); } }else{ free_expression(expr); return 0; } get_next_token(source_file); return 1; } FILE* open_source_file(char* filename){ FILE* file = fopen(filename, "r"); return file; } int Parse_program(AST_node **icode_p, char* source_file_name){ Expression *expr; FILE* source_file = open_source_file(source_file_name); get_next_token(source_file); if(Parse_expression(&expr, source_file)){ if(Token.class == EoF){ Error("Garbage after end of program"); } *icode_p = expr; return 1; } fclose(source_file); return 0; }
2.796875
3
2024-11-18T22:25:27.807551+00:00
2016-12-31T14:07:42
4b835be1e70faad037440dc9d9af20194e7666d3
{ "blob_id": "4b835be1e70faad037440dc9d9af20194e7666d3", "branch_name": "refs/heads/master", "committer_date": "2016-12-31T14:07:42", "content_id": "1e3a9c4ad155356b3b90ba2b89f018150f544d89", "detected_licenses": [ "ISC" ], "directory_id": "f7feafd121a2aa60a37d2f7cd67924f8508a3f9d", "extension": "c", "filename": "header-test.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": 3912, "license": "ISC", "license_type": "permissive", "path": "/test/header-test.c", "provenance": "stackv2-0115.json.gz:123972", "repo_name": "wuli133144/molch", "revision_date": "2016-12-31T14:07:42", "revision_id": "21d50d396478f623fbf9147a4069c77cc2e16314", "snapshot_id": "3f81aad50be1257cd46e3a1c6e03f086694e0285", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/wuli133144/molch/21d50d396478f623fbf9147a4069c77cc2e16314/test/header-test.c", "visit_date": "2021-01-19T05:50:42.019233" }
stackv2
/* * Molch, an implementation of the axolotl ratchet based on libsodium * * ISC License * * Copyright (C) 2015-2016 1984not Security GmbH * Author: Max Bruckner (FSMaxB) * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <stdio.h> #include <stdlib.h> #include <sodium.h> #include "../lib/header.h" #include "utils.h" #include "tracing.h" int main(void) { //create buffers buffer_t *our_public_ephemeral_key = buffer_create_on_heap(crypto_box_PUBLICKEYBYTES, crypto_box_PUBLICKEYBYTES); buffer_t *header = NULL; buffer_t *extracted_public_ephemeral_key = buffer_create_on_heap(crypto_box_PUBLICKEYBYTES, crypto_box_PUBLICKEYBYTES); return_status status = return_status_init(); if (sodium_init() == -1) { throw(INIT_ERROR, "Failed to initialize libsodium."); } int status_int; //create ephemeral key status_int = buffer_fill_random(our_public_ephemeral_key, our_public_ephemeral_key->content_length); if (status_int != 0) { throw(KEYGENERATION_FAILED, "Failed to create our public ephemeral."); } printf("Our public ephemeral key (%zu Bytes):\n", our_public_ephemeral_key->content_length); print_hex(our_public_ephemeral_key); //message numbers uint32_t message_number = 2; uint32_t previous_message_number = 10; printf("Message number: %u\n", message_number); printf("Previous message number: %u\n", previous_message_number); putchar('\n'); //create the header status = header_construct( &header, our_public_ephemeral_key, message_number, previous_message_number); throw_on_error(CREATION_ERROR, "Failed to create header."); //print the header printf("Header (%zu Bytes):\n", header->content_length); print_hex(header); putchar('\n'); //get data back out of the header again uint32_t extracted_message_number; uint32_t extracted_previous_message_number; status = header_extract( extracted_public_ephemeral_key, &extracted_message_number, &extracted_previous_message_number, header); throw_on_error(DATA_FETCH_ERROR, "Failed to extract data from header."); printf("Extracted public ephemeral key (%zu Bytes):\n", extracted_public_ephemeral_key->content_length); print_hex(extracted_public_ephemeral_key); printf("Extracted message number: %u\n", extracted_message_number); printf("Extracted previous message number: %u\n", extracted_previous_message_number); putchar('\n'); //compare them if (buffer_compare(our_public_ephemeral_key, extracted_public_ephemeral_key) != 0) { throw(INVALID_VALUE, "Public ephemeral keys don't match."); } printf("Public ephemeral keys match.\n"); if (message_number != extracted_message_number) { throw(INVALID_VALUE, "Message number doesn't match."); } printf("Message numbers match.\n"); if (previous_message_number != extracted_previous_message_number) { throw(INVALID_VALUE, "Previous message number doesn't match."); } printf("Previous message numbers match.\n"); cleanup: buffer_destroy_from_heap_and_null_if_valid(our_public_ephemeral_key); buffer_destroy_from_heap_and_null_if_valid(extracted_public_ephemeral_key); buffer_destroy_from_heap_and_null_if_valid(header); on_error { print_errors(&status); return_status_destroy_errors(&status); } return status.status; }
2.40625
2
2024-11-18T22:25:27.974492+00:00
2022-01-09T22:46:26
b11e7f078193c348b6db5df1221fd0dbaafdeba2
{ "blob_id": "b11e7f078193c348b6db5df1221fd0dbaafdeba2", "branch_name": "refs/heads/master", "committer_date": "2022-01-09T22:46:26", "content_id": "f3671e36f5bedf25539ab281199867efe9fc3396", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "c4492c7ceacd029604dac6f71a797ea7cb81562c", "extension": "c", "filename": "spf.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 61708143, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3300, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/spf.c", "provenance": "stackv2-0115.json.gz:124231", "repo_name": "tipss/c2016", "revision_date": "2022-01-09T22:46:26", "revision_id": "cca715e7ba7dea4f1c68d7890b725f5a6265f344", "snapshot_id": "71a890910d451f756b391cfa0678b8646d55dc2b", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/tipss/c2016/cca715e7ba7dea4f1c68d7890b725f5a6265f344/spf.c", "visit_date": "2022-01-28T02:20:18.844144" }
stackv2
#include <stdio.h> #include <stdlib.h> #define V 9 #define INT_MAX 0xffffff void printSolution(int dist[], int n) { printf("Vertex Distance from Source\n"); for (int i = 0; i < V; i++) printf("%d \t\t %d\n", i, dist[i]); } /* return -1 : No more node left MIN-HEAP : Find a vertex, which is at a minimum distance from soure */ int min_vertex_index(int sptSet[], int dist[]) { int min = INT_MAX; int index = -1; for (int i = 0; i< V; i++) { if (sptSet[i] == 0 && dist[i] < min) { min = dist[i]; index = i; } } printf("Return Vertex %d with min-distance %d\n", index, min); return (index); } /* * 1. PATH : sptSet[] : Hold vertices that are already part of Shortest Path Tree * 2. TENT : distance[]: Minimum distance from a single source Vertix to this node found * 3. Initialize distance[] to INFINITI for all vertices, except for the source vertice(Val Zero) * 4. Find index of vertex, whose distance is minimum from the 'distance[] using min_key API, * 5. Add this vertex to sptSet[] by setting it to 1/TRUE. * 6. Find all its adjacent vertices using supplied Graph[current-vertex][i] * 7. Update the distance of those adjacent vertices into distance[],if vertex is not in sptSet[]. * 8. Continue, until there are no more index with min-distance */ /* Given adjacency graph in two dimensional array, find shortest path tree from given source */ /* * Add parent list , next hops can be tracked TBD * Note: It is similar to greedy BFS(Breadth First Search), where a Queue is used * In Other words: * It mainly uses priority-queue(min-heap), where in a list is used as underlying struct * to store different vertices ordered by distance, root node representing min-distance at all time. * * This is used in Link State protocols like IS-IS and OSPF to compute shortest distrance * from root(self) to all other vertices(nodes) in the network. */ void dijkstra(int G[V][V], int source_index) { int dist[V] = {0}; int sptSet[V] = {0}; int u=0; //Rows int v=0; //Columns for(int i=0;i<V;i++){ dist[i]= INT_MAX; } dist[source_index] = 0; for(int count = 0; count < V; count++) { //Get a index for vertex with min-distance from source //which is not already in the PATH list(sptSet). u = min_vertex_index(sptSet, dist); if (u == -1) { printf("Exit Dijkstra(no more vertices to add\n"); } sptSet[u]= 1; //Find all the adjacent nodes for this vertex in u, using supplied graph G for(int v = 0; v < V; v++) { if((sptSet[v] == 1 || G[u][v] == 0 || dist[u] == INT_MAX) { continue; } if(dist[v] > (dist[u]+ G[u][v])) { dist[v] = dist[u] + G[u][v]; } }//End of for loop }//End of for loop printSolution(dist,V); } // driver program to test above function int main(int argc, char *argv[]) { /* Let us create the example graph discussed above */ int graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0}, {4, 0, 8, 0, 0, 0, 0, 11, 0}, {0, 8, 0, 7, 0, 4, 0, 0, 2}, {0, 0, 7, 0, 9, 14, 0, 0, 0}, {0, 0, 0, 9, 0, 10, 0, 0, 0}, {0, 0, 4, 14, 10, 0, 2, 0, 0}, {0, 0, 0, 0, 0, 2, 0, 1, 6}, {8, 11, 0, 0, 0, 0, 1, 0, 7}, {0, 0, 2, 0, 0, 0, 6, 7, 0} }; dijkstra(graph, 0); return 0; }
3.359375
3
2024-11-18T22:25:28.038498+00:00
2020-01-17T22:27:57
7e9fde05650a7a157fbf61cbcb3f5602083c8fe4
{ "blob_id": "7e9fde05650a7a157fbf61cbcb3f5602083c8fe4", "branch_name": "refs/heads/master", "committer_date": "2020-01-17T22:27:57", "content_id": "e09044c35eade40ab4a1d1e3f50fc058c21efa4c", "detected_licenses": [], "directory_id": "102493c818b3f67bd2034d7de673653881f25280", "extension": "c", "filename": "sleep.c", "fork_events_count": 0, "gha_created_at": "2019-04-18T02:23:51", "gha_event_created_at": "2019-11-14T12:09:25", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 182001519, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4642, "license": "", "license_type": "permissive", "path": "/source/ti/posix/freertos/sleep.c", "provenance": "stackv2-0115.json.gz:124359", "repo_name": "ArakniD/simplelink_msp432p4_sdk", "revision_date": "2020-01-17T22:27:57", "revision_id": "002fd4866284891e0b9b1a8d917a74334d39a997", "snapshot_id": "4fb9eb53f5d98a5afd86bdd2ab49882d1c3a0db1", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/ArakniD/simplelink_msp432p4_sdk/002fd4866284891e0b9b1a8d917a74334d39a997/source/ti/posix/freertos/sleep.c", "visit_date": "2020-05-15T01:12:51.507318" }
stackv2
/* * Copyright (c) 2016-2019 Texas Instruments Incorporated - http://www.ti.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * 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. * * * Neither the name of Texas Instruments Incorporated nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ /* * ======== sleep.c ======== */ #include <errno.h> #include <time.h> #include <unistd.h> #include <FreeRTOS.h> #include <task.h> /* number of microseconds per tick */ #define TICK_PERIOD_USECS (1000000L / configTICK_RATE_HZ) /* The maximum number of ticks before the tick count rolls over. We use * 0xFFFFFFFF instead of 0x100000000 to avoid 64-bit math. */ #define MAX_TICKS 0xFFFFFFFFL #define TICKS_PER_SEC (1000000L / TICK_PERIOD_USECS) /* integral number of seconds in a period of MAX_TICKS */ #define MAX_SECONDS (MAX_TICKS / TICKS_PER_SEC) /* * ======== nanosleep ======== */ int nanosleep(const struct timespec *rqtp, struct timespec *rmtp) { TickType_t ticks; /* max interval to avoid tick count overflow */ if (rqtp->tv_sec >= MAX_SECONDS) { errno = EINVAL; return (-1); } if ((rqtp->tv_nsec < 0) || (rqtp->tv_nsec >= 1000000000)) { errno = EINVAL; return (-1); } if ((rqtp->tv_sec == 0) && (rqtp->tv_nsec == 0)) { return (0); } ticks = rqtp->tv_sec * (1000000 / TICK_PERIOD_USECS); /* compute ceiling value */ ticks += (rqtp->tv_nsec + TICK_PERIOD_USECS * 1000 - 1) / (TICK_PERIOD_USECS * 1000); /* Add one tick to ensure the timeout is not less than the * amount of time requested. The clock may be about to tick, * and that counts as one tick even though the amount of time * until this tick is less than a full tick period. */ ticks++; /* suspend for the requested time interval */ vTaskDelay(ticks); /* If the rmtp argument is non-NULL, the structure referenced * by it should contain the amount of time remaining in the * interval. Signals are not supported, therefore, this will * always be zero. Caution: the rqtp and rmtp arguments may * point to the same object. */ if (rmtp != NULL) { rmtp->tv_sec = 0; rmtp->tv_nsec = 0; } return (0); } /* * ======== sleep ======== */ unsigned sleep(unsigned seconds) { TickType_t xDelay; unsigned long secs; /* at least 32-bit */ unsigned max_secs, rval; /* native size, might be 16-bit */ max_secs = MAX_SECONDS; if (seconds < max_secs) { secs = seconds; rval = 0; } else { secs = max_secs; rval = seconds - max_secs; } /* compute requested ticks */ xDelay = secs * configTICK_RATE_HZ; /* must add one tick to ensure a full duration of requested ticks */ vTaskDelay(xDelay + 1); return (rval); } /* * ======== usleep ======== */ int usleep(useconds_t usec) { TickType_t xDelay; /* usec must be less than 1000000 */ if (usec >= 1000000) { errno = EINVAL; return (-1); } /* take the ceiling */ xDelay = (usec + TICK_PERIOD_USECS - 1) / TICK_PERIOD_USECS; /* must add one tick to ensure a full duration of xDelay ticks */ vTaskDelay(xDelay + 1); return (0); }
2.390625
2
2024-11-18T22:25:29.481863+00:00
2023-08-30T12:41:33
e0e5bc0c7d24e2b9818af4b6b6b4e235501cc963
{ "blob_id": "e0e5bc0c7d24e2b9818af4b6b6b4e235501cc963", "branch_name": "refs/heads/master", "committer_date": "2023-08-30T12:41:33", "content_id": "e606fbcebd281c5b64659d133ba56271573fc66b", "detected_licenses": [ "MIT" ], "directory_id": "4aa3252c05a22ac52587758f98ff7b020c54c659", "extension": "h", "filename": "token.h", "fork_events_count": 6, "gha_created_at": "2022-05-04T19:38:16", "gha_event_created_at": "2023-08-20T15:23:53", "gha_language": "C", "gha_license_id": "MIT", "github_id": 488721422, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2870, "license": "MIT", "license_type": "permissive", "path": "/core/inc/token.h", "provenance": "stackv2-0115.json.gz:124489", "repo_name": "crocguy0688/CrocDE-BRender", "revision_date": "2023-08-30T12:41:33", "revision_id": "92001ec8059f452c0a89fff438a05cef277ab846", "snapshot_id": "cf922481c0205006f767400ff482c4f0501dc9e9", "src_encoding": "UTF-8", "star_events_count": 43, "url": "https://raw.githubusercontent.com/crocguy0688/CrocDE-BRender/92001ec8059f452c0a89fff438a05cef277ab846/core/inc/token.h", "visit_date": "2023-09-01T15:42:46.477576" }
stackv2
/* * Copyright (c) 1992,1993-1995 Argonaut Technologies Limited. All rights reserved. * * $Id: token.h 1.2 1998/09/21 14:53:14 johng Exp $ * $Locker: $ * */ #ifndef _TOKEN_H_ #define _TOKEN_H_ #ifndef BR_TOKEN_ENUM #define BR_TOKEN_ENUM 1 #endif /* * Tokens are unique 32 bit numbers that are assoicated with a name * and a value type. * */ #if !BR_TOKEN_ENUM typedef br_uint_32 br_token; #endif /* * 0 is reserved to indicate NULL tokens */ #ifdef __cplusplus #define BR_NULL_TOKEN ((const br_token)0) #else #define BR_NULL_TOKEN 0 #endif /* * Maximum length (including terminating '\0') of an string value */ #define BR_MAX_IDENTIFIER 64 /* * Predefined token values */ #include "pretok.h" /* * Make some macros for setting token types in terms of scalar */ #define BRT_AS_SCALAR(tok) BRT_AS_FLOAT(tok) #define BRT_AS_MATRIX23_SCALAR(tok) BRT_AS_MATRIX23_FLOAT(tok) #define BRT_AS_MATRIX34_SCALAR(tok) BRT_AS_MATRIX34_FLOAT(tok) #define BRT_AS_MATRIX4_SCALAR(tok) BRT_AS_MATRIX4_FLOAT(tok) #define BRT_AS_VECTOR2_SCALAR(tok) BRT_AS_VECTOR2_FLOAT(tok) #define BRT_AS_VECTOR3_SCALAR(tok) BRT_AS_VECTOR3_FLOAT(tok) #define BRT_AS_VECTOR4_SCALAR(tok) BRT_AS_VECTOR4_FLOAT(tok) typedef union br_value_tag { void *p; br_intptr_t pi; br_uintptr_t pu; br_boolean b; br_token t; br_int_8 i8; br_uint_8 u8; br_int_16 i16; br_uint_16 u16; br_int_32 i32; br_uint_32 u32; br_int_64 i64; br_uint_64 u64; br_fixed_ls x; br_float f; br_scalar s; br_angle a; br_colour rgb; struct br_object *o; void *h; br_vector2 *v2; br_vector3 *v3; br_vector4 *v4; br_vector2_i *v2_i; br_vector3_i *v3_i; br_vector4_i *v4_i; br_vector2_x *v2_x; br_vector3_x *v3_x; br_vector4_x *v4_x; br_vector2_f *v2_f; br_vector3_f *v3_f; br_vector4_f *v4_f; br_matrix23 *m23; br_matrix34 *m34; br_matrix4 *m4; br_matrix23_x *m23_x; br_matrix34_x *m34_x; br_matrix4_x *m4_x; br_matrix23_f *m23_f; br_matrix34_f *m34_f; br_matrix4_f *m4_f; char *str; const char *cstr; struct br_object **ol; br_token *tl; void **pl; struct br_token_value *tvl; } br_value; /* * Token value pair */ typedef struct br_token_value { br_token t; br_value v; } br_token_value; #endif
2.0625
2
2024-11-18T22:25:29.700067+00:00
2020-05-04T16:31:54
f1d14e2c2d2a5ede41b6ebf9666263fe0af33226
{ "blob_id": "f1d14e2c2d2a5ede41b6ebf9666263fe0af33226", "branch_name": "refs/heads/master", "committer_date": "2020-05-04T16:31:54", "content_id": "62bfe395fa05ea2f85259a9413d5d53a82d01471", "detected_licenses": [ "MIT" ], "directory_id": "e388dc46e41d78403f4e7481eb3fd52f640bd20e", "extension": "c", "filename": "ex1.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 58293385, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 653, "license": "MIT", "license_type": "permissive", "path": "/sr01/td4/ex1.c", "provenance": "stackv2-0115.json.gz:124751", "repo_name": "roddehugo/utc", "revision_date": "2020-05-04T16:31:54", "revision_id": "1f81e64c13eed562b95ed67faedca24f0e583492", "snapshot_id": "4ef822c019cb4a00775bdde6b908e258cd6ac1a5", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/roddehugo/utc/1f81e64c13eed562b95ed67faedca24f0e583492/sr01/td4/ex1.c", "visit_date": "2021-06-02T02:01:33.907859" }
stackv2
#include <stdio.h> #include <string.h> int main() { int i,nbMaj,nbMin,nbBlanc,nbAutre; i=nbMaj=nbMin=nbBlanc=nbAutre=0; char chaine[100]; fgets(chaine,100,stdin); while (chaine[i] != '\0') { if (chaine[i]>='A' && chaine[i]<='Z') nbMaj++; else if (chaine[i]>='a' && chaine[i]<='z') nbMin++; else if (chaine[i]==' ') nbBlanc++; else nbAutre++; i++; } printf("Longueur de la chaine : %d\n Nombre de majuscule :%d\n Nombre de miniscule :%d\n Nombre d'espace :%d\n Nombre d'autres caractères :%d\n",i-1,nbMaj,nbMin,nbBlanc,nbAutre-1); return 0; }
3.140625
3
2024-11-18T22:25:29.903710+00:00
2019-09-28T16:05:36
fa9d01c7c22b07a4140944137bbb4c6f3daaba28
{ "blob_id": "fa9d01c7c22b07a4140944137bbb4c6f3daaba28", "branch_name": "refs/heads/master", "committer_date": "2019-09-28T16:05:36", "content_id": "ec1f648ba5e203b3d9f7bab20e83d7780387c68c", "detected_licenses": [ "MIT" ], "directory_id": "a51a1af9a66078c0a5ce5c4077075a5979e89849", "extension": "c", "filename": "terminates1.c", "fork_events_count": 1, "gha_created_at": "2019-08-23T08:48:48", "gha_event_created_at": "2019-09-28T16:19:32", "gha_language": "C", "gha_license_id": "MIT", "github_id": 203960782, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1559, "license": "MIT", "license_type": "permissive", "path": "/src/asm/terminates1.c", "provenance": "stackv2-0115.json.gz:125007", "repo_name": "gloomikon/Corewar", "revision_date": "2019-09-28T16:05:36", "revision_id": "60bf18e824140abdc6c44e9e23fe22d307fc6ef0", "snapshot_id": "769b45406ea5303a2e2b2bffd3301e645f057bdb", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/gloomikon/Corewar/60bf18e824140abdc6c44e9e23fe22d307fc6ef0/src/asm/terminates1.c", "visit_date": "2020-07-09T11:46:18.119002" }
stackv2
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* terminates1.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mzhurba <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/09/10 16:41:27 by mzhurba #+# #+# */ /* Updated: 2019/09/27 19:41:22 by ozhadaie ### ########.fr */ /* */ /* ************************************************************************** */ #include "asm.h" void terminate_invalid_argument(t_inst *inst, int arg_num, t_entity *entity) { char *str; str = ft_str_tolower(g_class[entity->class]); ft_printf("Invalid parameter %d type %s for instruction \"%s\"\n", arg_num, str, inst->name); ft_strdel(&str); exit(1); } void terminate_label(t_label *label) { ft_printf("No such label %s while attempting to dereference token " "[TOKEN][%03d:%03d] DIRECT_LABEL \"%:%s\"\n", label->name, label->mentions->row, label->mentions->col, label->name); exit(1); } void terminate_invalid_parameter_count(t_inst *inst) { ft_printf("Invalid parameter count for instruction %s\n", inst->name); exit(1); }
2.203125
2
2024-11-18T22:25:30.017671+00:00
2019-11-13T01:49:47
061aa7be1973160f4ca469664876e48beed0e93e
{ "blob_id": "061aa7be1973160f4ca469664876e48beed0e93e", "branch_name": "refs/heads/master", "committer_date": "2019-11-13T01:49:47", "content_id": "0f2c6259e40c3d48c14352d0203bc15ffecd9a40", "detected_licenses": [ "MIT" ], "directory_id": "5b2d402406d0d789b9d19ce3c7fb3c581293a5d3", "extension": "h", "filename": "exception_level.h", "fork_events_count": 0, "gha_created_at": "2019-10-12T01:51:20", "gha_event_created_at": "2019-11-13T01:49:49", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 214558599, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2036, "license": "MIT", "license_type": "permissive", "path": "/scapula_os/include/exception_level.h", "provenance": "stackv2-0115.json.gz:125137", "repo_name": "fengjixuchui/scapula", "revision_date": "2019-11-13T01:49:47", "revision_id": "0ca411d8571622a6f7411bf423c3b662030e550b", "snapshot_id": "3ca78558d1be5173ff9587f345f970f902402db7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fengjixuchui/scapula/0ca411d8571622a6f7411bf423c3b662030e550b/scapula_os/include/exception_level.h", "visit_date": "2020-08-11T11:35:05.806802" }
stackv2
#ifndef SCAPULA_OS_EXCEPTION_LEVEL_H #define SCAPULA_OS_EXCEPTION_LEVEL_H #include <stdint.h> // get_current_el // // Get the current exception level that Scapula OS is currently exceuting at // Software components should read the current exception level through this // function because hardware has no way of reporting when the current exception // level is EL0 // // @return The current exception level (0 = EL0, 1 = EL1, 2 = EL2, 3 = EL3) uint32_t get_current_el(void); // set_current_el // // Sets the current exception level that Scapula OS is currently exceuting // at. This function should generally be used only by interrupt and exception // handlers as a means to indicate to software that the current exception level // has changed. This function does NOT change the hardware exception level. // // @param new_el The new exception level that Scapula OS is currently // running at (0 = EL0, 1 = EL1, 2 = EL2, 3 = EL3, other values undefined) void set_current_el(uint32_t new_el); // switch_to_el // // Change the current exception level (EL) to a new one. Upon returning, the // exception level will be changed to target_el, preserving the current stack, // link register, and general purpose registers // // @param target_el The target exception level to switch to // Valid values: 0 (EL0), 1 (EL1), 2 (EL2), 3 (EL3) // // Usage: // SCAPULA_PRINT("This will print from EL2"); // switch_to_el(1); // SCAPULA_PRINT("This will print from EL1"); void switch_to_el(uint32_t target_el); // get_exception_counter // // Returns the number of synchronous exceptions that have occurred since the // last time the Scapula OS exception counter was cleared. // // @return The number of exceptions that have occurred uint64_t get_exception_counter(void); // reset_exception_counter // // Reset the Scapula OS exception counter to 0 void reset_exception_counter(void); // increment_exception_counter // // Adds an exception occurrence to the exception counter void increment_exception_counter(void); #endif
2.6875
3
2024-11-18T22:25:30.562340+00:00
2021-06-04T17:07:57
480d04ac99db8894ff180ed7565b91b3ed288490
{ "blob_id": "480d04ac99db8894ff180ed7565b91b3ed288490", "branch_name": "refs/heads/master", "committer_date": "2021-06-04T17:07:57", "content_id": "84adbcf806b276d8d0dcf6bbd92fb50d55d940a0", "detected_licenses": [ "Unlicense" ], "directory_id": "362838cfb39d9c0240688bf613530abbc8a28947", "extension": "c", "filename": "rt_jtoc_utilits.c", "fork_events_count": 3, "gha_created_at": "2019-09-29T20:00:37", "gha_event_created_at": "2019-10-12T16:47:16", "gha_language": "C", "gha_license_id": null, "github_id": 211718871, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3267, "license": "Unlicense", "license_type": "permissive", "path": "/srcs/rt_jtoc/rt_jtoc_utilits.c", "provenance": "stackv2-0115.json.gz:125786", "repo_name": "dolovnyak/rt_indi", "revision_date": "2021-06-04T17:07:57", "revision_id": "def722cd81a9163ba8b531fb4d651b316cfa1190", "snapshot_id": "ac144ccf8427e8ba8d9d2ba0b1f632b2f2cfcb29", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/dolovnyak/rt_indi/def722cd81a9163ba8b531fb4d651b316cfa1190/srcs/rt_jtoc/rt_jtoc_utilits.c", "visit_date": "2021-06-18T13:34:55.539508" }
stackv2
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* rt_jtoc_utilits.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rkeli <rkeli@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/06 17:18:34 by rkeli #+# #+# */ /* Updated: 2019/10/06 17:20:25 by rkeli ### ########.fr */ /* */ /* ************************************************************************** */ #include "rt.h" int rt_jtoc_sdl_log_error(const char *p, const int id) { printf("%s ----> ERROR <---- %s\n", KRED, KNRM); printf("INCORRECT: %s%s%s%s%s\n", p, id < 0 ? "" : " IN ID = ", KGRN, id < 0 ? "" : ft_itoa(id), KNRM); return (FUNCTION_FAILURE); } int rt_jtoc_get_objects_num_in_arr(unsigned int *objects_num, t_jnode *n) { t_jnode *tmp; if (n == NULL) return (FUNCTION_SUCCESS); if (n->type != array) return (rt_jtoc_sdl_log_error("TYPE IS NOT ARRAY", -1)); tmp = n->down; while (tmp) { if (tmp->type != object) return (rt_jtoc_sdl_log_error("TYPE IS NOT OBJECT", -1)); (*objects_num)++; tmp = tmp->right; } return (FUNCTION_SUCCESS); } int rt_jtoc_get_float2(cl_float2 *vec, t_jnode *n) { t_jnode *tmp; if (!(tmp = jtoc_node_get_by_path(n, "x")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("X ERROR", -1)); vec->x = jtoc_get_float(tmp); if (!(tmp = jtoc_node_get_by_path(n, "y")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("Y ERROR", -1)); vec->y = jtoc_get_float(tmp); return (FUNCTION_SUCCESS); } int rt_jtoc_get_float3(cl_float3 *vec, t_jnode *n) { t_jnode *tmp; if (!(tmp = jtoc_node_get_by_path(n, "x")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("X ERROR", -1)); vec->x = jtoc_get_float(tmp); if (!(tmp = jtoc_node_get_by_path(n, "y")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("Y ERROR", -1)); vec->y = jtoc_get_float(tmp); if (!(tmp = jtoc_node_get_by_path(n, "z")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("Z ERROR", -1)); vec->z = jtoc_get_float(tmp); return (FUNCTION_SUCCESS); } int rt_jtoc_get_float4(cl_float4 *vec, t_jnode *n) { t_jnode *tmp; if (!(tmp = jtoc_node_get_by_path(n, "x")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("X ERROR", -1)); vec->x = jtoc_get_float(tmp); if (!(tmp = jtoc_node_get_by_path(n, "y")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("Y ERROR", -1)); vec->y = jtoc_get_float(tmp); if (!(tmp = jtoc_node_get_by_path(n, "z")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("Z ERROR", -1)); vec->z = jtoc_get_float(tmp); if (!(tmp = jtoc_node_get_by_path(n, "w")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("W ERROR", -1)); vec->w = jtoc_get_float(tmp); return (FUNCTION_SUCCESS); }
2.265625
2
2024-11-18T22:25:31.973855+00:00
2017-06-16T09:11:02
8b8c9295d1b85d22a9d3fc0241476ab790025fd6
{ "blob_id": "8b8c9295d1b85d22a9d3fc0241476ab790025fd6", "branch_name": "refs/heads/master", "committer_date": "2017-06-16T09:11:02", "content_id": "56d18a3ad825ca4ad8677cf218d7e40a382ecd75", "detected_licenses": [ "ISC" ], "directory_id": "81355ff0719b6577a32a2c7f31d8fd2bca7767cf", "extension": "c", "filename": "linker.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": 18685, "license": "ISC", "license_type": "permissive", "path": "/linker.c", "provenance": "stackv2-0115.json.gz:126565", "repo_name": "mfalconi/kwebapp", "revision_date": "2017-06-16T09:11:02", "revision_id": "bae443c58768c71a29e13993d043e95dbb8ec3ec", "snapshot_id": "c4f005060c112aa2492d411ffc273a0002162b4f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mfalconi/kwebapp/bae443c58768c71a29e13993d043e95dbb8ec3ec/linker.c", "visit_date": "2021-01-25T01:08:05.652696" }
stackv2
/* $Id$ */ /* * Copyright (c) 2017 Kristaps Dzonsons <kristaps@bsd.lv> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "config.h" #include <sys/queue.h> #include <assert.h> #if HAVE_ERR # include <err.h> #endif #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "extern.h" /* * Check that a given row identifier is valid. * The rules are that only one row identifier can exist on a structure * and that it must happen on a native type. */ static int checkrowid(const struct field *f, int hasrowid) { if (hasrowid) { warnx("%s.%s: multiple rowids on " "structure", f->parent->name, f->name); return(0); } if (FTYPE_STRUCT == f->type) { warnx("%s.%s: rowid on non-native field" "type", f->parent->name, f->name); return(0); } return(1); } /* * Reference rules: we can't reference from or to a struct, nor can the * target and source be of a different type. */ static int checktargettype(const struct ref *ref) { /* Our actual reference objects may not be structs. */ if (FTYPE_STRUCT == ref->target->type || FTYPE_STRUCT == ref->source->type) { warnx("%s.%s: referencing a struct", ref->parent->parent->name, ref->parent->name); return(0); } /* Our reference objects must have equivalent types. */ if (ref->source->type != ref->target->type) { warnx("%s.%s: referencing a different type", ref->parent->parent->name, ref->parent->name); return(0); } if ( ! (FIELD_ROWID & ref->target->flags)) warnx("%s.%s: referenced target %s.%s is not " "a unique field", ref->parent->parent->name, ref->parent->name, ref->target->parent->name, ref->target->name); return(1); } /* * When we're parsing a structure's reference, we need to create the * referring information to the source field, which is the actual * reference itself. * Return zero on failure, non-zero on success. */ static int linkref(struct ref *ref) { assert(NULL != ref->parent); assert(NULL != ref->source); assert(NULL != ref->target); if (FTYPE_STRUCT != ref->parent->type) return(1); /* * If our source field is already a reference, make sure it * points to the same thing we point to. * Otherwise, it's an error. */ if (NULL != ref->source->ref && (strcasecmp(ref->tfield, ref->source->ref->tfield) || strcasecmp(ref->tstrct, ref->source->ref->tstrct))) { warnx("%s.%s: redeclaration of reference", ref->parent->parent->name, ref->parent->name); return(0); } else if (NULL != ref->source->ref) return(1); /* Make sure that the target is a rowid and not null. */ if ( ! (FIELD_ROWID & ref->target->flags)) { warnx("%s.%s: target is not a rowid", ref->target->parent->name, ref->target->name); return(0); } else if (FIELD_NULL & ref->target->flags) { warnx("%s.%s: target can't be null", ref->target->parent->name, ref->target->name); return(0); } /* Create linkage. */ ref->source->ref = calloc(1, sizeof(struct ref)); if (NULL == ref->source->ref) err(EXIT_FAILURE, NULL); ref->source->ref->parent = ref->source; ref->source->ref->source = ref->source; ref->source->ref->target = ref->target; ref->source->ref->sfield = strdup(ref->sfield); ref->source->ref->tfield = strdup(ref->tfield); ref->source->ref->tstrct = strdup(ref->tstrct); if (NULL == ref->source->ref->sfield || NULL == ref->source->ref->tfield || NULL == ref->source->ref->tstrct) err(EXIT_FAILURE, NULL); return(1); } /* * Check the source field (case insensitive). * Return zero on failure, non-zero on success. * On success, this sets the "source" field for the referrent. */ static int resolve_field_source(struct ref *ref, struct strct *s) { struct field *f; if (NULL != ref->source) return(1); assert(NULL == ref->source); assert(NULL == ref->target); TAILQ_FOREACH(f, &s->fq, entries) { if (strcasecmp(f->name, ref->sfield)) continue; ref->source = f; return(1); } warnx("%s:%zu%zu: unknown reference target", ref->parent->pos.fname, ref->parent->pos.line, ref->parent->pos.column); return(0); } /* * Check that the target structure and field exist (case insensitive). * Return zero on failure, non-zero on success. * On success, this sets the "target" field for the referrent. */ static int resolve_field_target(struct ref *ref, struct strctq *q) { struct strct *p; struct field *f; if (NULL != ref->target) return(1); assert(NULL != ref->source); assert(NULL == ref->target); TAILQ_FOREACH(p, q, entries) { if (strcasecmp(p->name, ref->tstrct)) continue; TAILQ_FOREACH(f, &p->fq, entries) { if (strcasecmp(f->name, ref->tfield)) continue; ref->target = f; return(1); } } warnx("%s:%zu%zu: unknown reference target", ref->parent->pos.fname, ref->parent->pos.line, ref->parent->pos.column); return(0); } /* * Resolve an enumeration. * This returns zero if the resolution fails, non-zero otherwise. * In the success case, it sets the enumeration link. */ static int resolve_field_enum(struct eref *ref, struct enmq *q) { struct enm *e; TAILQ_FOREACH(e, q, entries) if (0 == strcasecmp(e->name, ref->ename)) { ref->enm = e; return(1); } warnx("%s:%zu:%zu: unknown enum reference", ref->parent->pos.fname, ref->parent->pos.line, ref->parent->pos.column); return(0); } /* * Recursively check for... recursion. * Returns zero if the reference is recursive, non-zero otherwise. */ static int check_recursive(struct ref *ref, const struct strct *check) { struct field *f; struct strct *p; assert(NULL != ref); if ((p = ref->target->parent) == check) return(0); TAILQ_FOREACH(f, &p->fq, entries) if (FTYPE_STRUCT == f->type) if ( ! check_recursive(f->ref, check)) return(0); return(1); } /* * Recursively annotate our height from each node. * We only do this for FTYPE_STRUCT objects. */ static void annotate(struct ref *ref, size_t height, size_t colour) { struct field *f; struct strct *p; p = ref->target->parent; if (p->colour == colour) return; p->colour = colour; p->height += height; TAILQ_FOREACH(f, &p->fq, entries) if (FTYPE_STRUCT == f->type) annotate(f->ref, height + 1, colour); } /* * Resolve a specific update reference by looking it up in our parent * structure. * Return zero on failure, non-zero on success. */ static int resolve_uref(struct uref *ref, int crq) { struct field *f; const char *type; type = UP_MODIFY == ref->parent->type ? "update" : "delete"; assert(NULL == ref->field); assert(NULL != ref->parent); TAILQ_FOREACH(f, &ref->parent->parent->fq, entries) if (0 == strcasecmp(f->name, ref->name)) break; if (NULL == (ref->field = f)) warnx("%s:%zu:%zu: %s term not found", ref->pos.fname, ref->pos.line, ref->pos.column, type); else if (FTYPE_STRUCT == f->type) warnx("%s:%zu:%zu: %s term is a struct", ref->pos.fname, ref->pos.line, ref->pos.column, type); else if (crq && FTYPE_PASSWORD == f->type) warnx("%s:%zu:%zu: %s constraint is a password", ref->pos.fname, ref->pos.line, ref->pos.column, type); else return(1); return(0); } /* * Make sure that our constraint operator is consistent with the type * named in the constraint. * Returns zero on failure, non-zero on success. * (For the time being, this always returns non-zero.) */ static int check_updatetype(struct update *up) { struct uref *ref; TAILQ_FOREACH(ref, &up->crq, entries) if ((OPTYPE_NOTNULL == ref->op || OPTYPE_ISNULL == ref->op) && ! (FIELD_NULL & ref->field->flags)) warnx("%s:%zu:%zu: null operator " "on field that's never null", ref->pos.fname, ref->pos.line, ref->pos.column); return(1); } /* * Make sure that our modification type is numeric. * (Text-based modifications with "add" or "sub" or otherwise don't * really make sense. */ static int check_modtype(const struct uref *ref) { assert(MODTYPE__MAX != ref->mod); if (MODTYPE_SET == ref->mod || FTYPE_EPOCH == ref->field->type || FTYPE_INT == ref->field->type || FTYPE_REAL == ref->field->type) return(1); warnx("%s:%zu:%zu: update modification on " "invalid field type (not numeric)", ref->pos.fname, ref->pos.line, ref->pos.column); return(0); } /* * Resolve all of the fields managed by struct update. * These are all local to the current structure. * (This is a constraint of SQL.) * Return zero on failure, non-zero on success. */ static int resolve_update(struct update *up) { struct uref *ref; /* Will always be empty for UPT_DELETE. */ TAILQ_FOREACH(ref, &up->mrq, entries) { if ( ! resolve_uref(ref, 0)) return(0); if ( ! check_modtype(ref)) return(0); } TAILQ_FOREACH(ref, &up->crq, entries) if ( ! resolve_uref(ref, 1)) return(0); return(1); } /* * Recursively follow the chain of references in a search target, * finding out whether it's well-formed in the process. * Returns zero on failure, non-zero on success. */ static int resolve_sref(struct sref *ref, struct strct *s) { struct field *f; TAILQ_FOREACH(f, &s->fq, entries) if (0 == strcasecmp(f->name, ref->name)) break; /* Did we find the field in our structure? */ if (NULL == (ref->field = f)) { warnx("%s:%zu:%zu: search term not found", ref->pos.fname, ref->pos.line, ref->pos.column); return(0); } /* * If we're following a chain, we must have a "struct" type; * otherwise, we must have a native type. */ if (NULL == TAILQ_NEXT(ref, entries)) { if (FTYPE_STRUCT != f->type) return(1); warnx("%s:%zu:%zu: search term leaf field " "is a struct", ref->pos.fname, ref->pos.line, ref->pos.column); return(0); } else if (FTYPE_STRUCT != f->type) { warnx("%s:%zu:%zu: search term node field " "is not a struct", ref->pos.fname, ref->pos.line, ref->pos.column); return(0); } /* Follow the chain of our reference. */ ref = TAILQ_NEXT(ref, entries); return(resolve_sref(ref, f->ref->target->parent)); } /* * Sort by reverse height. */ static int parse_cmp(const void *a1, const void *a2) { const struct strct *p1 = *(const struct strct **)a1, *p2 = *(const struct strct **)a2; return((ssize_t)p1->height - (ssize_t)p2->height); } /* * Recursively create the list of all possible search prefixes we're * going to see in this structure. * This consists of all "parent.child" chains of structure that descend * from the given "orig" original structure. * FIXME: artificially limited to 26 entries. */ static void resolve_aliases(struct strct *orig, struct strct *p, size_t *offs, const struct alias *prior) { struct field *f; struct alias *a; int c; TAILQ_FOREACH(f, &p->fq, entries) { if (FTYPE_STRUCT != f->type) continue; assert(NULL != f->ref); a = calloc(1, sizeof(struct alias)); if (NULL == a) err(EXIT_FAILURE, NULL); if (NULL != prior) { c = asprintf(&a->name, "%s.%s", prior->name, f->name); if (c < 0) err(EXIT_FAILURE, NULL); } else a->name = strdup(f->name); if (NULL == a->name) err(EXIT_FAILURE, NULL); assert(*offs < 26); c = asprintf(&a->alias, "_%c", (char)*offs + 97); if (c < 0) err(EXIT_FAILURE, NULL); (*offs)++; TAILQ_INSERT_TAIL(&orig->aq, a, entries); resolve_aliases(orig, f->ref->target->parent, offs, a); } } /* * Check to see that our search type (e.g., list or iterate) is * consistent with the fields that we're searching for. * In other words, running an iterator search on a unique row isn't * generally useful. * Also warn if null-sensitive operators (isnull, notnull) will be run * on non-null fields. * Return zero on failure, non-zero on success. */ static int check_searchtype(const struct strct *p) { const struct search *srch; const struct sent *sent; const struct sref *sr; TAILQ_FOREACH(srch, &p->sq, entries) { if (SEARCH_IS_UNIQUE & srch->flags && STYPE_SEARCH != srch->type) warnx("%s:%zu:%zu: multiple-result search " "on a unique field", srch->pos.fname, srch->pos.line, srch->pos.column); if ( ! (SEARCH_IS_UNIQUE & srch->flags) && STYPE_SEARCH == srch->type) warnx("%s:%zu:%zu: single-result search " "on a non-unique field", srch->pos.fname, srch->pos.line, srch->pos.column); TAILQ_FOREACH(sent, &srch->sntq, entries) { sr = TAILQ_LAST(&sent->srq, srefq); if ((OPTYPE_NOTNULL == sent->op || OPTYPE_ISNULL == sent->op) && ! (FIELD_NULL & sr->field->flags)) warnx("%s:%zu:%zu: null operator " "on field that's never null", sent->pos.fname, sent->pos.line, sent->pos.column); /* * FIXME: we should (in theory) allow for the * unary types and equality binary types. * But for now, mandate equality. */ if (OPTYPE_EQUAL != sent->op && FTYPE_PASSWORD == sr->field->type) { warnx("%s:%zu:%zu: password field " "only processes equality", sent->pos.fname, sent->pos.line, sent->pos.column); return(0); } } } return(1); } /* * Resolve the chain of search terms. * To do so, descend into each set of search terms for the structure and * resolve the fields. * Also set whether we have row identifiers within the search expansion. */ static int resolve_search(struct search *srch) { struct sent *sent; struct sref *ref; struct alias *a; struct strct *p; p = srch->parent; TAILQ_FOREACH(sent, &srch->sntq, entries) { ref = TAILQ_FIRST(&sent->srq); if ( ! resolve_sref(ref, p)) return(0); ref = TAILQ_LAST(&sent->srq, srefq); if (FIELD_ROWID & ref->field->flags || FIELD_UNIQUE & ref->field->flags) { sent->flags |= SENT_IS_UNIQUE; srch->flags |= SEARCH_IS_UNIQUE; } if (NULL == sent->name) continue; /* * Look up our alias name. * Our resolve_sref() function above * makes sure that the reference exists, * so just assert on lack of finding. */ TAILQ_FOREACH(a, &p->aq, entries) if (0 == strcasecmp(a->name, sent->name)) break; assert(NULL != a); sent->alias = a; } return(1); } static int check_unique(const struct unique *u) { const struct nref *n; TAILQ_FOREACH(n, &u->nq, entries) { if (FTYPE_STRUCT != n->field->type) continue; warnx("%s:%zu:%zu: field not a native type", n->pos.fname, n->pos.line, n->pos.column); return(0); } return(1); } /* * Resolve the chain of unique fields. * These are all in the local structure. */ static int resolve_unique(struct unique *u) { struct nref *n; struct field *f; TAILQ_FOREACH(n, &u->nq, entries) { TAILQ_FOREACH(f, &u->parent->fq, entries) if (0 == strcasecmp(f->name, n->name)) break; if (NULL != (n->field = f)) continue; warnx("%s:%zu:%zu: field not found", n->pos.fname, n->pos.line, n->pos.column); return(0); } return(1); } int parse_link(struct config *cfg) { struct update *u; struct strct *p; struct strct **pa; struct field *f; struct unique *n; struct search *srch; size_t colour = 1, sz = 0, i = 0, hasrowid = 0; /* * First, establish linkage between nodes. * While here, check for duplicate rowids. */ TAILQ_FOREACH(p, &cfg->sq, entries) { hasrowid = 0; TAILQ_FOREACH(f, &p->fq, entries) { if (FIELD_ROWID & f->flags) if ( ! checkrowid(f, hasrowid++)) return(0); if (NULL != f->ref && (! resolve_field_source(f->ref, p) || ! resolve_field_target(f->ref, &cfg->sq) || ! linkref(f->ref) || ! checktargettype(f->ref))) return(0); if (NULL != f->eref && ! resolve_field_enum(f->eref, &cfg->eq)) return(0); } TAILQ_FOREACH(u, &p->uq, entries) if ( ! resolve_update(u) || ! check_updatetype(u)) return(0); TAILQ_FOREACH(u, &p->dq, entries) if ( ! resolve_update(u) || ! check_updatetype(u)) return(0); } /* Check for reference recursion. */ TAILQ_FOREACH(p, &cfg->sq, entries) TAILQ_FOREACH(f, &p->fq, entries) if (FTYPE_STRUCT == f->type) { if (check_recursive(f->ref, p)) continue; warnx("%s:%zu:%zu: recursive " "reference", f->pos.fname, f->pos.line, f->pos.column); return(0); } /* * Now follow and order all outbound links for structs. * From the get-go, we don't descend into structures that we've * already coloured. * This establishes a "height" that we'll use when ordering our * structures in the header file. */ TAILQ_FOREACH(p, &cfg->sq, entries) { sz++; if (p->colour) continue; TAILQ_FOREACH(f, &p->fq, entries) if (FTYPE_STRUCT == f->type) { p->colour = colour; annotate(f->ref, 1, colour); } colour++; } assert(sz > 0); /* * Next, create unique names for all joins within a structure. * We do this by creating a list of all search patterns (e.g., * user.name and user.company.name, which assumes two structures * "user" and "company", the first pointing into the second, * both of which contain "name"). */ i = 0; TAILQ_FOREACH(p, &cfg->sq, entries) resolve_aliases(p, p, &i, NULL); /* Resolve search terms. */ TAILQ_FOREACH(p, &cfg->sq, entries) TAILQ_FOREACH(srch, &p->sq, entries) if ( ! resolve_search(srch)) return(0); TAILQ_FOREACH(p, &cfg->sq, entries) TAILQ_FOREACH(n, &p->nq, entries) if ( ! resolve_unique(n) || ! check_unique(n)) return(0); /* See if our search type is wonky. */ TAILQ_FOREACH(p, &cfg->sq, entries) if ( ! check_searchtype(p)) return(0); /* * Copy the list into a temporary array. * Then sort the list by reverse-height. * Finally, re-create the list from the sorted elements. */ if (NULL == (pa = calloc(sz, sizeof(struct strct *)))) err(EXIT_FAILURE, NULL); i = 0; while (NULL != (p = TAILQ_FIRST(&cfg->sq))) { TAILQ_REMOVE(&cfg->sq, p, entries); assert(i < sz); pa[i++] = p; } assert(i == sz); qsort(pa, sz, sizeof(struct strct *), parse_cmp); for (i = 0; i < sz; i++) TAILQ_INSERT_HEAD(&cfg->sq, pa[i], entries); free(pa); return(1); }
2.28125
2
2024-11-18T22:25:32.257805+00:00
2019-05-06T01:44:53
a98222cddd25b8469db84d095cfce9874866b64d
{ "blob_id": "a98222cddd25b8469db84d095cfce9874866b64d", "branch_name": "refs/heads/master", "committer_date": "2019-05-06T01:44:53", "content_id": "cf09a2e1e3d1d33c020c43b8885c93e8ef9f3645", "detected_licenses": [ "MIT" ], "directory_id": "b7e920541e6cef12da3a1f5d53acf49543e61cfb", "extension": "c", "filename": "servo_motor_control_with_pot.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": 7088, "license": "MIT", "license_type": "permissive", "path": "/servo_motor_control_with_pot.c", "provenance": "stackv2-0115.json.gz:126954", "repo_name": "mkollayan/Elegoo_Mega_2560", "revision_date": "2019-05-06T01:44:53", "revision_id": "2c158de67adf4e897f726646ec878b5de737494c", "snapshot_id": "6f333be86feca7697efa04886ec7093402d26ee8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mkollayan/Elegoo_Mega_2560/2c158de67adf4e897f726646ec878b5de737494c/servo_motor_control_with_pot.c", "visit_date": "2023-04-02T08:29:08.408727" }
stackv2
//Copyright (c) 2017 Pratik M Tambe <enthusiasticgeek@gmail.com> #include <avr/io.h> #include <avr/interrupt.h> #include <util/delay.h> #include <stdint.h> // http://www.electroschematics.com/10053/avr-adc/ //Benn Thomsen has a good article on this. This is the basis for the following program. See below. // Reference: https://bennthomsen.wordpress.com/arduino/peripherals/analogue-input/ //Atmega 2560 has 10-bit successive approximation type ADC @ 15kS/s sampling rate. //ADC modes: Single Conversion, Triggered Conversion, Free Running (We use the last one here) /* From Atmega2560 datasheet ADC Prescaler: 7-bit Selected using ADPS0, ADPS1, ADPS2 (2, 4, 16, 32, 64 and 128) - ADC frequency between 50KHz to 200KHz (> 10 bit resolution) ADC Channels: The ADC in Atmega2560 PDIP package has 16 channels, allows you to take samples from 16 different pins ADC Registers: Register provides the communication link between CPU and the ADC. You can configure the ADC according to your need using these registers. The ADC has 3 registers only: ADC Multiplexer Selection Register – ADMUX: For selecting the reference voltage and the input channel ADC Control and Status Register A – ADCSRA: It has the status of ADC and is also used to control it The ADC Data Register – ADCL and ADCH: Final result of the conversion is stored here AVCC: This pin supplies power to ADC. AVCC must not differ more than ± 0.3V from Vcc AREF: Another pin which can optionally be used as an external voltage reference pin. Voltage Resolution:This is the smallest voltage increment which can be measured. For 10 bit ADC, there can be 1024 different voltages (for an 8 bit ADC, there can be 256 different voltages) */ //Connect VCC to 330 Ohms to +ve end of LED and -ve end of LED to pin 5 of Arduino //Connect VCC to 330 Ohms to +ve end of LED and -ve end of LED to pin 4 of Arduino //Connect 10K Ohms POTENTIOMETER's center to A7 pin on ADC port of Arduino. One side of POT to to GND. Remaining side of POT to +5V. Connect ARef to +5V and Capacitor 0.1 microFarad between GND and +5V. //Connect pin 6 on Arduino to orange wire on servo, red wire on servo to +5V and brown wire on servo to GND. /* From Atmega2560 datasheet freq OCnx = F_CPU / (PRESCALAR * (1 + TOP)) where TOP = ICRn in our case for mode 14 fast PWM e.g. to create 50 Hz pulse as required by SG90 servo motor 50 = 16 MHz / ( 64 * (1 + ICRn)) (16 MHz / ( 50 * 64 )) - 1 = ICRn ICRn = 4999 */ static unsigned long positions[8] = {150, 200, 250, 312, 375, 438, 500, 562}; static unsigned long division(unsigned long dividend, unsigned long divisor) { return (dividend + (divisor/2)) / divisor; } int main(void) { //SG90 servo needs 50 Hz or 20 milliseconds pulse /* Weight: 9 g Dimension: 22.2 x 11.8 x 31 mm approx. Stall torque: 1.8 kgf-cm Operating speed: 0.1 s/60 degree Operating voltage: 4.8 V (~5V) Dead band width: 10 μs Temperature range: 0 ºC – 55 ºC Leads: PWM (Orange), Vcc (Red), Ground (Brown) PWM Period: 20 milliseconds duty cycle varies between 1 and 2 ms Position -90 (1 milliseconds/20 milliseconds -> 5% duty cycle) - left position Position 0 (1.5 milliseconds/20 milliseconds -> 7.5% duty cycle) - middle position Position +90 (2 milliseconds/20 milliseconds -> 10% duty cycle) - right position */ unsigned long timer_frequency; unsigned long desired_frequency = 50; // 50 Hz const unsigned long prescalar = 64; //Set PORTE to OUTPUT LED DDRE |= _BV(DDE3); //Set the output port E pin 3 to 0 (LOW) state PORTE &= ~_BV(PORTE3); //Set PORTG to OUTPUT LED DDRG |= _BV(DDG5); //Set the output port G pin 5 to 0 (LOW) state PORTG &= ~_BV(PORTG5); // Initial PORT //Set PORTH to OUTPUT DDRH |= _BV(DDH3); //Set the output port H pin 3 to 0 (LOW) state PORTH &= ~_BV(PORTH3); //Set up ADC ADCSRA = (1<<ADEN) | (1<<ADPS2) | (1<<ADPS0); //Clear Interrupts cli(); ADCSRA |= (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0); // Set ADC -> prescaler to 128 - 125KHz sample rate @ 16MHz ADCSRB |= (0 << ADTS2) | (0 << ADTS1) | (0 << ADTS0); // Set ADC -> Free Running Mode ADMUX |= (0 << REFS1)| (1 << REFS0); // Set ADC reference to AVCC //ADMUX |= (0 << REFS1)| (0 << REFS0); //AREF, Internal VREF turned off //ADMUX |= (1 << ADLAR); // Left adjust ADC result to allow easy 8 bit ADMUX |= (0 << ADLAR); // Default - right adjust ADC result to allow easy 8 bit ADCSRA |= (1 << ADEN); // Enable ADC ADCSRA |= (1 << ADIE); // Enable ADC Interrupt ADMUX |= (1 << MUX2)| (1 << MUX1) |(1 << MUX0); // using ADC7 pin timer_frequency = division(F_CPU, prescalar); ICR4 = division(timer_frequency, desired_frequency) - 1; // Initial TIMER4 Fast PWM // Fast PWM Frequency = fclk / (N * TOP), Where N is the Prescaler TCCR4A |= 1<<WGM41 | 0<<WGM40; // Fast PWM - Mode 14 with 16 Bit timer TCCR4B |= 1<<WGM43 | 1<<WGM42; // Fast PWM - Mode 14 with 16 Bit timer //Clear OC4A on compare match, set OC4A at BOTTOM (non-inverting mode) TCCR4A |= 1<<COM4A1 | 0<<COM4A0; // Used 64 Prescaler TCCR4B |= 0<<CS12 | 1<<CS11 | 1<<CS10; //Divide by 64 (We are using 16 MHz external Crystal) //Set Interrupts sei(); while (1) { ADCSRA |= (1<<ADSC); // Start conversion //Instead of logic below for waiting for conversion we wait for ADC conversion complete interrupt //while (ADCSRA & (1<<ADSC)); // wait for conversion to complete } return 0; } ISR(ADC_vect){ //Clear interrupt cli(); //ADCW stores the value unsigned int adc_value = ADCW; // max ADCW value is 2^10 = 1024 hence half of it. if (adc_value < 512) { PORTE |= _BV(PORTE3); // Turn on LED1 PORTG &= ~_BV(PORTG5); // Turn off LED2 } else { PORTE &= ~_BV(PORTE3); // Turn off LED1 PORTG |= _BV(PORTG5); // Turn on LED2 } // We vary the duty cycle between 3% and 11% @5V -> To move from 0 degrees to 180 degrees if(adc_value > 0 && adc_value <= 128){ OCR4A = positions[0]; _delay_ms(500); } else if(adc_value > 128 && adc_value <= 256 ){ OCR4A = positions[1]; _delay_ms(500); } else if(adc_value > 256 && adc_value <= 384 ){ OCR4A = positions[2]; _delay_ms(500); } else if(adc_value > 384 && adc_value <= 512 ){ OCR4A = positions[3]; _delay_ms(500); } else if(adc_value > 512 && adc_value <= 640 ){ OCR4A = positions[4]; _delay_ms(500); } else if(adc_value > 640 && adc_value <= 768 ){ OCR4A = positions[5]; _delay_ms(500); } else if(adc_value > 768 && adc_value <= 896 ){ OCR4A = positions[6]; _delay_ms(500); } else if(adc_value > 896 && adc_value <= 1024 ){ OCR4A = positions[7]; _delay_ms(500); } else { OCR4A = positions[0]; _delay_ms(500); } //Set interrupt sei(); }
2.765625
3
2024-11-18T22:25:32.343043+00:00
2021-03-12T15:06:29
1216c005926cc74d88d5e1a67d8605aab53cff1d
{ "blob_id": "1216c005926cc74d88d5e1a67d8605aab53cff1d", "branch_name": "refs/heads/master", "committer_date": "2021-03-12T15:06:29", "content_id": "2922cc9aabf28d455d4e4c402c6f11fe13521cc4", "detected_licenses": [ "Apache-2.0" ], "directory_id": "00a90405e5185b898ca8cb39082906a2cee5ccc3", "extension": "c", "filename": "lock.c", "fork_events_count": 0, "gha_created_at": "2015-06-09T21:29:22", "gha_event_created_at": "2021-03-12T15:06:29", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 37159492, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4105, "license": "Apache-2.0", "license_type": "permissive", "path": "/cpvmm/vmm/utils/lock.c", "provenance": "stackv2-0115.json.gz:127083", "repo_name": "jethrogb/cloudproxy", "revision_date": "2021-03-12T15:06:29", "revision_id": "fcf90a62bf09c4ecc9812117d065954be8a08da5", "snapshot_id": "1c20a4670e8ed74c32f7d7ff0fca60f8e8ef181f", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/jethrogb/cloudproxy/fcf90a62bf09c4ecc9812117d065954be8a08da5/cpvmm/vmm/utils/lock.c", "visit_date": "2021-07-14T12:54:54.105912" }
stackv2
/* * Copyright (c) 2013 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "libc.h" #include "hw_includes.h" #include "lock.h" #include "ipc.h" #include "vmm_dbg.h" #include "file_codes.h" #define VMM_DEADLOOP() VMM_DEADLOOP_LOG(LOCK_C) #define VMM_ASSERT(__condition) VMM_ASSERT_LOG(LOCK_C, __condition) #define VMM_ASSERT_NOLOCK(__condition) VMM_ASSERT_NOLOCK_LOG(LOCK_C, __condition) // lock_try_acquire - returns TRUE if lock was acquired and FALSE if not BOOLEAN lock_try_acquire(VMM_LOCK* lock); void lock_acquire(VMM_LOCK* lock) { (void)lock; CPU_ID this_cpu_id = hw_cpu_id(); if (! lock) { return; // error } while (FALSE == lock_try_acquire(lock)) { VMM_ASSERT_NOLOCK(lock->owner_cpu_id != this_cpu_id); hw_pause(); } lock->owner_cpu_id = this_cpu_id; } void interruptible_lock_acquire(VMM_LOCK* lock) { (void)lock; CPU_ID this_cpu_id = hw_cpu_id(); BOOLEAN ipc_processed = FALSE; if (!lock) { return; // error } while (FALSE == lock_try_acquire(lock)) { ipc_processed = ipc_process_one_ipc(); if(FALSE == ipc_processed) { hw_pause(); } } lock->owner_cpu_id = this_cpu_id; } void lock_release(VMM_LOCK* lock) { (void)lock; if (!lock) { return; // error } lock->owner_cpu_id = (CPU_ID)-1; #if 0 hw_interlocked_assign((INT32 volatile *)(&(lock->uint32_lock)), 0); #else lock->uint32_lock= 0; #endif } BOOLEAN lock_try_acquire(VMM_LOCK* lock) { (void)lock; UINT32 expected_value = 0, current_value; UINT32 new_value = 1; if (!lock) { return FALSE; // error } current_value = hw_interlocked_compare_exchange((INT32 volatile *)(&(lock->uint32_lock)), expected_value, new_value); return (current_value == expected_value); } void lock_initialize(VMM_LOCK* lock) { (void)lock; lock_release( lock ); } void lock_initialize_read_write_lock(VMM_READ_WRITE_LOCK* lock) { (void)lock; lock_initialize(&lock->lock); lock->readers = 0; } void lock_acquire_readlock(VMM_READ_WRITE_LOCK* lock) { (void)lock; lock_acquire(&lock->lock); hw_interlocked_increment((INT32*)(&lock->readers)); lock_release(&lock->lock); } void interruptible_lock_acquire_readlock(VMM_READ_WRITE_LOCK* lock) { (void)lock; interruptible_lock_acquire(&lock->lock); hw_interlocked_increment((INT32*)(&lock->readers)); lock_release(&lock->lock); } void lock_release_readlock( VMM_READ_WRITE_LOCK * lock ) { (void)lock; hw_interlocked_decrement((INT32*)(&lock->readers)); } void lock_acquire_writelock(VMM_READ_WRITE_LOCK * lock) { (void)lock; lock_acquire(&lock->lock); // wait until readers == 0 while(lock->readers) { hw_pause(); } } void interruptible_lock_acquire_writelock(VMM_READ_WRITE_LOCK * lock) { (void)lock; BOOLEAN ipc_processed = FALSE; interruptible_lock_acquire(&lock->lock); // wait until readers == 0 while(lock->readers) { ipc_processed = ipc_process_one_ipc(); if(FALSE == ipc_processed) { hw_pause(); } } } void lock_release_writelock(VMM_READ_WRITE_LOCK* lock) { (void)lock; lock_release(&lock->lock); } VMM_DEBUG_CODE( void lock_print( VMM_LOCK* lock ) { (void)lock; #if 0 // lock print VMM_LOG(mask_anonymous, level_trace,"lock %p: value=%d, owner=%d\r\n", lock, lock->uint32_lock, lock->owner_cpu_id); #endif } )
2.234375
2
2024-11-18T22:25:32.420124+00:00
2021-04-28T18:36:30
8e1cfc219ebfa7976886c662b7af9cd9d14c865c
{ "blob_id": "8e1cfc219ebfa7976886c662b7af9cd9d14c865c", "branch_name": "refs/heads/main", "committer_date": "2021-04-28T18:36:30", "content_id": "44519b5ce81bd12b33bd1937575ff94f2af6b4cc", "detected_licenses": [ "MIT" ], "directory_id": "bfa82074cbe9d4f83356087dda364ea5cb127ee2", "extension": "c", "filename": "hw2-p1.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 331356521, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1591, "license": "MIT", "license_type": "permissive", "path": "/hw2-p1.c", "provenance": "stackv2-0115.json.gz:127211", "repo_name": "ykzzyk/DataStructureAlgorithm", "revision_date": "2021-04-28T18:36:30", "revision_id": "75e4e03996d009ba12356e40ee87bc879c609642", "snapshot_id": "4aa70ed9c94c13bfab54132a2afd1c768c8eb7a8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ykzzyk/DataStructureAlgorithm/75e4e03996d009ba12356e40ee87bc879c609642/hw2-p1.c", "visit_date": "2023-04-17T05:38:09.904759" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> // Create a union type union integer { char c; short s; int i; long b; }; // main function int main(){ union integer INT; printf("Enter a character: "); scanf("%c", &INT.c); printf("'%c' printed as a character is %c\n", INT.c, INT.c); printf("'%c' printed as a short integer is %hi\n", INT.c, INT.s); printf("'%c' printed as an integer is %d\n", INT.c, INT.i); printf("'%c' printed as a long integer is %ld\n", INT.c, INT.b); printf("\nEnter a short integer: "); scanf("%hi", &INT.s); printf("'%hi' printed as a character is %c\n", INT.s, INT.c); printf("'%hi' printed as a short integer is %hi\n", INT.s, INT.s); printf("'%hi' printed as an integer is %d\n", INT.s, INT.i); printf("'%hi' printed as a long integer is %ld\n", INT.s, INT.b); printf("\nEnter an integer: "); scanf("%d", &INT.i); printf("'%d' printed as a character is %c\n", INT.i, INT.c); printf("'%d' printed as a short integer is %hi\n", INT.i, INT.s); printf("'%d' printed as an integer is %d\n", INT.i, INT.i); printf("'%d' printed as a long integer is %ld\n", INT.i, INT.b); printf("\nEnter a long integer: "); scanf("%ld", &INT.b); printf("'%ld' printed as a character is %c\n", INT.b, INT.c); printf("'%ld' printed as a short integer is %hi\n", INT.b, INT.s); printf("'%ld' printed as an integer is %d\n", INT.b, INT.i); printf("'%ld' printed as a long integer is %ld\n", INT.b, INT.b); return 0; }
3.953125
4
2024-11-18T22:25:32.582575+00:00
2021-04-14T01:40:00
bc1d280853e09c9534fea3eb27c32d747d99948e
{ "blob_id": "bc1d280853e09c9534fea3eb27c32d747d99948e", "branch_name": "refs/heads/main", "committer_date": "2021-04-14T01:40:00", "content_id": "553bc7cb0655797e54d4ce1b07830eb07edb5caf", "detected_licenses": [ "MIT" ], "directory_id": "af582fa4f2283deda4ad20fc20dd37dc54b23d96", "extension": "c", "filename": "ft_strmapi.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": 1249, "license": "MIT", "license_type": "permissive", "path": "/sources/ft_strmapi.c", "provenance": "stackv2-0115.json.gz:127469", "repo_name": "Bortize/ft_libft", "revision_date": "2021-04-14T01:40:00", "revision_id": "a3cc8e3ce7ac4803309fd0486ae51593cdbe5cb2", "snapshot_id": "7cd0867832dac44c4417688ff1a5368d5f049ed3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Bortize/ft_libft/a3cc8e3ce7ac4803309fd0486ae51593cdbe5cb2/sources/ft_strmapi.c", "visit_date": "2023-04-05T08:56:29.753215" }
stackv2
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strmapi.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lpaulo-m <lpaulo-m@student.42sp.org.br> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/02/06 23:09:36 by lpaulo-m #+# #+# */ /* Updated: 2021/03/25 20:02:49 by lpaulo-m ### ########.fr */ /* */ /* ************************************************************************** */ #include <libft.h> /* ** Returns an allocated string with each char modified by f. */ char *ft_strmapi(char const *s, char (*f)(unsigned int, char)) { char *map_start; char *map; map_start = ft_strdup(s); if (map_start == NULL) return (NULL); map = map_start; while (*map) { *map = f(map - map_start, *map); map++; } return (map_start); }
2.640625
3
2024-11-18T22:25:32.898288+00:00
2016-10-16T21:30:20
d99d6b028682ce33d9847de490c1cf3ea63018fd
{ "blob_id": "d99d6b028682ce33d9847de490c1cf3ea63018fd", "branch_name": "refs/heads/master", "committer_date": "2016-10-16T21:30:20", "content_id": "19f060ba22dfc76ca45301ac7252f198061e036e", "detected_licenses": [ "MIT" ], "directory_id": "b46abaa87f21e589819d2638cccdf5173aed95c1", "extension": "c", "filename": "ar_mngt.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 71078113, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1681, "license": "MIT", "license_type": "permissive", "path": "/src_nm/ar_mngt.c", "provenance": "stackv2-0115.json.gz:127856", "repo_name": "KASOGIT/nmobjdump", "revision_date": "2016-10-16T21:30:20", "revision_id": "047153c9908708dc2c755ba9e4d8e03ee72c14da", "snapshot_id": "b5e7ad90f026ba03091bfb996352f89cb697f7d8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/KASOGIT/nmobjdump/047153c9908708dc2c755ba9e4d8e03ee72c14da/src_nm/ar_mngt.c", "visit_date": "2021-05-04T05:54:05.501931" }
stackv2
/* ** ar_mngt.c for in /home/soto_a/nmobjdump/src_nm ** ** Made by adam soto ** Login <soto_a@epitech.net> ** ** Started on Fri Feb 26 23:13:28 2016 adam soto ** Last update Sun Feb 28 15:27:48 2016 */ #include "my_nm.h" char *get_elf_name(char *name, char *s_tab_name) { char *get_name; int i; i = 0; get_name = strdup(name); if (strncmp(name, "/", 1) == 0) { free(get_name); get_name = strdup(s_tab_name + atoi(name + 1)); } while (get_name[i] != '/') i++; get_name[i] = '\0'; return (get_name); } void act_data_ar(void *ptr, char *name, int i, char *s_tab_name) { char *get_name; Elf64_Ehdr *elf_hdr; get_name = get_elf_name(name, s_tab_name); elf_hdr = (Elf64_Ehdr *)(ptr + i + sizeof(struct ar_hdr)); if (check_elf_fmt(elf_hdr->e_ident)) { printf("\n%s:\n", get_name); get_elf_data_and_act(ptr + i + sizeof(struct ar_hdr), elf_hdr); } else fprintf(stderr, "/usr/bin/objdump: %s: File format not recognized\n", name); free(get_name); } void parse_ar_file_and_act(void *data_load, int fd) { struct ar_hdr *ar_hdrs; char *s_tab_name; int i; char nb[11]; char name[17]; void *ptr; ptr = (data_load + SARMAG); i = 0; while (i < get_filesize(fd) - 8) { ar_hdrs = (ptr + i); memset(nb, 0, 11); memset(name, 0, 17); strncpy(nb, ar_hdrs->ar_size, 11); strncpy(name, ar_hdrs->ar_name, 17); if (i != 0) { if (strncmp(name, "//", 2) == 0) s_tab_name = (char *)(ptr + i + sizeof(struct ar_hdr)); else act_data_ar(ptr, name, i, s_tab_name); } i += sizeof(struct ar_hdr) + atoi(nb); } }
2.40625
2
2024-11-18T22:25:33.110904+00:00
2018-07-03T16:12:12
11e16849414d48762755246d28dede369fa76657
{ "blob_id": "11e16849414d48762755246d28dede369fa76657", "branch_name": "refs/heads/master", "committer_date": "2018-07-03T16:12:12", "content_id": "73cdaa734d9dd1e20540e408a93a6b3e465fdc3f", "detected_licenses": [ "BSD-3-Clause", "NCSA", "MIT" ], "directory_id": "144fdeec6dec6ed22e702f8902f94d77ba0d6059", "extension": "c", "filename": "polymorphic-native-function-pointers1.c", "fork_events_count": 1, "gha_created_at": "2016-09-01T07:06:28", "gha_event_created_at": "2016-09-01T07:06:28", "gha_language": null, "gha_license_id": null, "github_id": 67107046, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 618, "license": "BSD-3-Clause,NCSA,MIT", "license_type": "permissive", "path": "/tests/com.oracle.truffle.llvm.tests.sulong/c/polymorphic-native-function-pointers1.c", "provenance": "stackv2-0115.json.gz:128113", "repo_name": "pointhi/sulong", "revision_date": "2018-07-03T16:12:12", "revision_id": "5446c54d360f486f9e97590af5f466cf1f5cd1f7", "snapshot_id": "cb9dc61f54a113e988911f1e3654d6e5792c2859", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/pointhi/sulong/5446c54d360f486f9e97590af5f466cf1f5cd1f7/tests/com.oracle.truffle.llvm.tests.sulong/c/polymorphic-native-function-pointers1.c", "visit_date": "2021-01-16T22:17:36.966183" }
stackv2
#include <stdio.h> #include <math.h> typedef double (*test_type)(double); #define SIZE 4 test_type getFunction(int i) { int val = i % SIZE; switch (val) { case 0: return &log2; case 1: return &floor; case 2: return &fabs; case 3: return &ceil; } return 0; } int callFunction() { double val; int i; test_type func; double currentVal = 2342; for (i = 0; i < 1000; i++) { currentVal = getFunction(i)(currentVal) > 4353423; } return currentVal; } int main() { int i; int sum = 0; for (i = 0; i < 1000; i++) { sum += callFunction(); } return sum == 0; }
2.953125
3
2024-11-18T22:25:33.531945+00:00
2018-04-23T21:23:41
081b43b6f6ab912a26d853a8cd8bd27e6547193a
{ "blob_id": "081b43b6f6ab912a26d853a8cd8bd27e6547193a", "branch_name": "refs/heads/develop", "committer_date": "2018-04-23T21:23:41", "content_id": "70b0b542548226c75afe681ae8e8e34b4027cf34", "detected_licenses": [ "BSL-1.0" ], "directory_id": "d8860eb725a51fd0ef814bebfb8abaa8a807996d", "extension": "c", "filename": "outhtml.c", "fork_events_count": 0, "gha_created_at": "2013-12-31T23:10:07", "gha_event_created_at": "2018-04-23T21:52:16", "gha_language": "C", "gha_license_id": null, "github_id": 15558048, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9659, "license": "BSL-1.0", "license_type": "permissive", "path": "/kmlfuncs/source/outhtml.c", "provenance": "stackv2-0115.json.gz:128759", "repo_name": "mlbrock/MlbDevOld", "revision_date": "2018-04-23T21:23:41", "revision_id": "d31005dbe8ec05f59557e189e7194ee952ab64ff", "snapshot_id": "31c9809c8cbf8a2066c139d712a5ff0f758bbc39", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mlbrock/MlbDevOld/d31005dbe8ec05f59557e189e7194ee952ab64ff/kmlfuncs/source/outhtml.c", "visit_date": "2021-01-20T03:53:21.763387" }
stackv2
/* *********************************************************************** */ /* *********************************************************************** */ /* Keyword Matching Logic (KMLFUNCS) Program Module */ /* *********************************************************************** */ /* File Name : %M% File Version : %I% Last Extracted : %D% %T% Last Updated : %E% %U% File Description : Outputs matched string in HTML format. Revision History : 1998-03-19 --- Creation. Michael L. Brock Copyright Michael L. Brock 1998 - 2018. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ /* *********************************************************************** */ /* *********************************************************************** */ /* *********************************************************************** */ /* Necessary include files . . . */ /* *********************************************************************** */ #include <string.h> #include "kmlfunci.h" /* *********************************************************************** */ /* *********************************************************************** */ /* *********************************************************************** */ /* Function prototypes for static functions . . . */ /* *********************************************************************** */ COMPAT_FN_DECL_STATIC(void KML_EmitHTML, (const char *in_ptr, unsigned int in_length, unsigned int tab_setting, unsigned int *current_col, STR_FUNC_TYPE_fprintf output_function, void *output_control)); /* *********************************************************************** */ /* *********************************************************************** */ #ifndef NARGS void KML_OutputHTML(KML_CONTROL *control_ptr, const char *file_name, unsigned int tab_setting, const char *in_string, STR_FUNC_TYPE_fprintf output_function, void *output_control) #else void KML_OutputHTML(control_ptr, file_name, tab_setting, in_string, output_function, output_control) KML_CONTROL *control_ptr; const char *file_name; unsigned int tab_setting; const char *in_string; STR_FUNC_TYPE_fprintf output_function; void *output_control; #endif /* #ifndef NARGS */ { unsigned int current_col = 0; const char *in_ptr; unsigned int in_length; unsigned int tmp_length; const KML_MATCH *match_ptr; const KML_MATCH *old_match_ptr; const char *leading_text; const char *trailing_text; STR_EMIT_SetDefaults(&output_function, &output_control); (*output_function)(output_control, "<HTML>\n"); (*output_function)(output_control, "<HEAD>\n"); if ((file_name != NULL) && *file_name) { (*output_function)(output_control, "<TITLE>"); KML_EmitHTML(file_name, strlen(file_name), tab_setting, &current_col, output_function, output_control); (*output_function)(output_control, "</TITLE>\n"); } (*output_function)(output_control, "</HEAD>\n"); (*output_function)(output_control, "<BODY>\n"); (*output_function)(output_control, "<PRE WIDTH=80>"); in_ptr = in_string; in_length = strlen(in_string); match_ptr = control_ptr->match_list; current_col = 0; while (*in_ptr) { if (match_ptr == NULL) { KML_EmitHTML(in_ptr, in_length, tab_setting, &current_col, output_function, output_control); break; } else if (in_ptr < match_ptr->ptr) { KML_EmitHTML(in_ptr, tmp_length = ((unsigned int) (match_ptr->ptr - in_ptr)), tab_setting, &current_col, output_function, output_control); in_ptr += tmp_length; in_length -= tmp_length; } else { switch (match_ptr->type) { case KML_TYPE_STRING : leading_text = "<FONT COLOR=#0000FF>"; trailing_text = "<FONT COLOR=#000000>"; break; case KML_TYPE_COMMENT : leading_text = "<FONT COLOR=#000080><I>"; trailing_text = "</I><FONT COLOR=#000000>"; break; case KML_TYPE_KEYWORD : leading_text = "<B>"; trailing_text = "</B>"; break; case KML_TYPE_SYMBOL : leading_text = ""; trailing_text = ""; break; case KML_TYPE_BLOCK : leading_text = ""; trailing_text = ""; break; case KML_TYPE_NAME : leading_text = ""; trailing_text = ""; break; case KML_TYPE_NUMBER : leading_text = ""; trailing_text = ""; break; case KML_TYPE_OPERATOR : leading_text = ""; trailing_text = ""; break; default : leading_text = ""; trailing_text = ""; break; } (*output_function)(output_control, "%s", leading_text); KML_EmitHTML(match_ptr->ptr, match_ptr->length, tab_setting, &current_col, output_function, output_control); (*output_function)(output_control, "%s", trailing_text); in_ptr += match_ptr->length; in_length -= match_ptr->length; old_match_ptr = match_ptr; /* Just in case matches are contained within other matches. */ while ((match_ptr == old_match_ptr) || ((match_ptr != NULL) && (match_ptr->ptr < (old_match_ptr->ptr + old_match_ptr->length)))) match_ptr = (match_ptr < (control_ptr->match_list + (control_ptr->match_count - 1))) ? (match_ptr + 1) : NULL; } } (*output_function)(output_control, "</PRE>\n"); (*output_function)(output_control, "</BODY>\n"); (*output_function)(output_control, "</HTML>\n"); } /* *********************************************************************** */ /* *********************************************************************** */ #ifndef NARGS static void KML_EmitHTML(const char *in_ptr, unsigned int in_length, unsigned int tab_setting, unsigned int *current_col, STR_FUNC_TYPE_fprintf output_function, void *output_control) #else static void KML_EmitHTML(in_ptr, in_length, tab_setting, current_col, output_function, output_control) const char *in_ptr; unsigned int in_length; unsigned int tab_setting; unsigned int *current_col; STR_FUNC_TYPE_fprintf output_function; void *output_control; #endif /* #ifndef NARGS */ { unsigned int space_count; while (*in_ptr && in_length) { if (*in_ptr == '\"') { (*output_function)(output_control, "&quot;"); (*current_col)++; } else if (*in_ptr == '&') { (*output_function)(output_control, "&amp;"); (*current_col)++; } else if (*in_ptr == '<') { (*output_function)(output_control, "&lt;"); (*current_col)++; } else if (*in_ptr == '>') { (*output_function)(output_control, "&gt;"); (*current_col)++; } else if (*in_ptr == '\t') { if (tab_setting) { space_count = tab_setting - (*current_col % tab_setting); *current_col += space_count; while (space_count--) (*output_function)(output_control, " "); } } else if ((*in_ptr == '\n') || (*in_ptr == '\r')) { if ((*in_ptr == '\r') && ((in_length > 1) && (*(in_ptr + 1) == '\n'))) { in_ptr++; in_length--; } *current_col = 0; (*output_function)(output_control, "\n"); } else { (*output_function)(output_control, "%c", *in_ptr); (*current_col)++; } in_ptr++; in_length--; } } /* *********************************************************************** */ #ifdef TEST_MAIN #include <stdio.h> #include <stdlib.h> COMPAT_FN_DECL(int main, (int argc, char **argv)); #ifndef NARGS int main(int argc, char **argv) #else int main(argc, argv) int argc; char **argv; #endif /* #ifndef NARGS */ { int return_code; unsigned int count_1; KML_CONTROL control_data; const KML_DOMAIN *domain_ptr; const char *file_type; char *file_buffer; char error_text[KMLFUNCS_MAX_ERROR_TEXT]; fprintf(stderr, "Test routine for 'KML_OutputHTML()'\n"); fprintf(stderr, "---- ------- --- ------------------\n\n"); if (argc == 1) { sprintf(error_text, "USAGE:\n %s <source-file> [<source-file> ...]", argv[0]); return_code = KMLFUNCS_BAD_ARGS_FAILURE; } else if ((return_code = KML_TEST_InitializeControl(&control_data, error_text)) == KMLFUNCS_SUCCESS) { for (count_1 = 1; count_1 < ((unsigned int) argc); count_1++) { if (((file_type = strrchr(argv[count_1], '.')) != NULL) && *file_type) fprintf(stderr, "File: %s (using extension '%s')", argv[count_1], ++file_type); else fprintf(stderr, "File: %s (no extension, using '%s')", argv[count_1], file_type = "c"); if ((domain_ptr = KML_FIND_ControlDomainByType(&control_data, file_type)) == NULL) fprintf(stderr, ": Unable to locate a domain for file extension '%s'.", file_type); else fprintf(stderr, ": Found domain name '%s', description '%s'.\n", domain_ptr->domain_name, domain_ptr->domain_description); if ((return_code = KML_TFREAD_ReadFileBuffer(argv[count_1], NULL, &file_buffer, error_text)) != KMLFUNCS_SUCCESS) break; if ((domain_ptr != NULL) && ((return_code = KML_MatchAll(&control_data, domain_ptr, file_buffer, KML_TYPE_STRING | KML_TYPE_COMMENT | KML_TYPE_KEYWORD, error_text)) != KMLFUNCS_SUCCESS)) break; KML_OutputHTML(&control_data, argv[count_1], 3, file_buffer, NULL, NULL); free(file_buffer); KML_ClearMatchList(&control_data); } KML_FREE_Control(&control_data); } if (return_code != KMLFUNCS_SUCCESS) fprintf(stderr, "\n\nERROR: %s\n", error_text); return(return_code); } #endif /* #ifdef TEST_MAIN */
2.296875
2
2024-11-18T22:25:34.015078+00:00
2017-01-09T10:21:29
ff0fcdcdbce49a1c5d969898ce2fd9334044056a
{ "blob_id": "ff0fcdcdbce49a1c5d969898ce2fd9334044056a", "branch_name": "refs/heads/master", "committer_date": "2017-01-09T10:21:29", "content_id": "5fb80acdd8443e2184203195cbb9fffc1d3f32a9", "detected_licenses": [ "MIT" ], "directory_id": "56240fc4712d9d2b3147d9281c0f4cb5ccae216c", "extension": "c", "filename": "bitlevel.c", "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": 500, "license": "MIT", "license_type": "permissive", "path": "/src/bitlevel.c", "provenance": "stackv2-0115.json.gz:129147", "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/src/bitlevel.c", "visit_date": "2021-01-17T19:57:42.723444" }
stackv2
#include <stdlib.h> #include <stdio.h> int main(void) { unsigned int x = 10; unsigned int y = 1; unsigned int result; result = x & y; printf("x & y = %d\n", result ); result = x | y; printf("x | y = %d\n", result ); result = x ^ y; printf("x ^ y = %d\n", result ); //right shift 1 is equivalent of dividing by 2 result = x >> 1; printf("x >> 1 = %d\n",result ); //left shift 1 is equivalent of multiplying by 2 result = y << 1; printf("y << 1 = %d\n",result ); }
3.234375
3
2024-11-18T22:25:34.096853+00:00
2015-03-17T12:40:55
08bfc18afdaf0690136c3295b699974fbdf7be56
{ "blob_id": "08bfc18afdaf0690136c3295b699974fbdf7be56", "branch_name": "refs/heads/master", "committer_date": "2015-03-17T12:40:55", "content_id": "43e2a190daf36e9b2c912f675d1d31e0f689f058", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "06782f75f5157d1e5359c77e1424f4be0941a0ba", "extension": "c", "filename": "sortedVector.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 32392336, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1678, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/sortedVector.c", "provenance": "stackv2-0115.json.gz:129276", "repo_name": "jobtalle/sortedVector", "revision_date": "2015-03-17T12:40:55", "revision_id": "565c74a57c195b3dec2794c4f9fb7105a2a5edee", "snapshot_id": "d8e279e3ee3aedffc3711ed051d1518c62c9d33e", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/jobtalle/sortedVector/565c74a57c195b3dec2794c4f9fb7105a2a5edee/sortedVector.c", "visit_date": "2020-09-13T10:18:33.190816" }
stackv2
#include <stdlib.h> #include <string.h> #include "sortedVector.h" void sortedVectorCreate(sortedVector *vector) { vector->size = 0; vector->capacity = SORTED_VECTOR_INITIAL_CAPACITY; vector->elements = malloc(sizeof(sortedVectorType)*vector->capacity); } void sortedVectorFree(sortedVector *vector) { free(vector->elements); } void sortedVectorAddUnique(sortedVector *vector, sortedVectorType element) { unsigned int index = sortedVectorIndex(vector, element); if(vector->elements[index - 1] == element) return; vector->size++; if(vector->size == vector->capacity) { vector->capacity <<= 1; vector->elements = realloc(vector->elements, sizeof(sortedVectorType)*vector->capacity); } if(index != vector->size - 1) { memmove(&vector->elements[index + 1], &vector->elements[index], (vector->size - index - 1) * sizeof(sortedVectorType)); } vector->elements[index] = element; } void sortedVectorRemove(sortedVector *vector, sortedVectorType element) { unsigned int index = sortedVectorIndex(vector, element) - 1; if(vector->elements[index] == element) { memmove(&vector->elements[index], &vector->elements[index + 1], (vector->size - index - 1) * sizeof(sortedVectorType)); vector->size--; } } unsigned int sortedVectorIndex(sortedVector *vector, sortedVectorType element) { int first, last, middle; if(vector->size == 0) return 0; first = 0; last = vector->size - 1; middle = last >> 1; while(first <= last) { if(vector->elements[middle] < element) { first = middle + 1; } else if(vector->elements[middle] == element) { break; } else { last = middle - 1; } middle = (first + last) >> 1; } return middle + 1; }
3.125
3
2024-11-18T22:25:34.136189+00:00
2016-08-29T08:50:50
482a134c96ab7a70d9f8d3faf870a2733bdba005
{ "blob_id": "482a134c96ab7a70d9f8d3faf870a2733bdba005", "branch_name": "refs/heads/master", "committer_date": "2016-08-29T08:50:50", "content_id": "d83c63a134ac57e9dede0203000274c71833b6e0", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "6f8403b5398b55b34f3be5cbdde3446a179c9c1d", "extension": "c", "filename": "usbmuxd.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 66826523, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4358, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/usbmuxd/usbmuxd/usbmuxd.c", "provenance": "stackv2-0115.json.gz:129404", "repo_name": "com3611923/IOSManageLib", "revision_date": "2016-08-29T08:50:50", "revision_id": "b4d7fbadcc83d2cd3d1a707dd7fbc6f71a941636", "snapshot_id": "a005dabd632bd7b9c2009b4aa939f5e332b61da6", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/com3611923/IOSManageLib/b4d7fbadcc83d2cd3d1a707dd7fbc6f71a941636/usbmuxd/usbmuxd/usbmuxd.c", "visit_date": "2020-12-01T18:49:43.013909" }
stackv2
// // usbmuxd.c // usbmuxd // // Created by Samantha Marshall on 1/25/14. // Copyright (c) 2014 Samantha Marshall. All rights reserved. // #ifndef usbmuxd_usbmuxd_c #define usbmuxd_usbmuxd_c #include "usbmuxd.h" #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> static char *sdm_usbmuxd_path = "/var/run/sdm_usbmuxd"; USBMuxAgentRef MuxAgent; USBMuxAgentRef USBMuxAgentCreate() { USBMuxAgentRef agent = (USBMuxAgentRef)calloc(1, sizeof(struct USBMuxAgentClass)); agent->socket = -1; agent->isActive = false; agent->socketQueue = dispatch_queue_create("com.samdmarshall.sdm_usbmux.socketQueue", NULL); return agent; } uint32_t SDM_USBMux_SocketCreate() { unlink(sdm_usbmuxd_path); struct sockaddr_un local; uint32_t sock = socket(AF_UNIX, SOCK_STREAM, 0x0); if (sock != -1) { local.sun_family = AF_UNIX; strcpy(local.sun_path, sdm_usbmuxd_path); unlink(local.sun_path); socklen_t len = (socklen_t)strlen(local.sun_path) + sizeof(local.sun_family); if (bind(sock, (struct sockaddr *)&local, len) == -1) { perror("bind"); exit(1); } if (listen(sock, 0x5) == -1) { perror("listen"); exit(1); } } return sock; } void USBMuxSend(uint32_t sock, struct USBMuxPacket *packet) { CFDataRef xmlData = CFPropertyListCreateXMLData(kCFAllocatorDefault, packet->payload); char *buffer = (char *)CFDataGetBytePtr(xmlData); ssize_t result = send(sock, &packet->body, sizeof(struct USBMuxPacketBody), 0x0); if (result == sizeof(struct USBMuxPacketBody)) { if (packet->body.length > result) { ssize_t payloadSize = packet->body.length - result; ssize_t remainder = payloadSize; while (remainder) { result = send(sock, &buffer[payloadSize-remainder], sizeof(char), 0x0); if (result != sizeof(char)) { break; } remainder -= result; } } } CFSafeRelease(xmlData); } void USBMuxReceive(uint32_t sock, struct USBMuxPacket *packet) { ssize_t result = recv(sock, &packet->body, sizeof(struct USBMuxPacketBody), 0x0); if (result == sizeof(struct USBMuxPacketBody)) { ssize_t payloadSize = packet->body.length - result; if (payloadSize) { char *buffer = calloc(0x1, payloadSize); ssize_t remainder = payloadSize; while (remainder) { result = recv(sock, &buffer[payloadSize-remainder], sizeof(char), 0x0); if (result != sizeof(char)) { break; } remainder -= result; } CFDataRef xmlData = CFDataCreate(kCFAllocatorDefault, (UInt8 *)buffer, payloadSize); packet->payload = CFPropertyListCreateFromXMLData(kCFAllocatorDefault, xmlData, kCFPropertyListImmutable, NULL); Safe(free,buffer); CFSafeRelease(xmlData); } } } void StartMux() { MuxAgent = USBMuxAgentCreate(); if (MuxAgent) { MuxAgent->socket = SDM_USBMux_SocketCreate(); MuxAgent->socketSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, MuxAgent->socket, 0x0, MuxAgent->socketQueue); dispatch_source_set_event_handler(MuxAgent->socketSource, ^{ struct USBMuxPacket *packet = (struct USBMuxPacket *)calloc(0x1, sizeof(struct USBMuxPacket)); USBMuxReceive(MuxAgent->socket, packet); if (CFPropertyListIsValid(packet->payload, kCFPropertyListXMLFormat_v1_0)) { if (CFDictionaryContainsKey(packet->payload, CFSTR("MessageType"))) { CFStringRef type = CFDictionaryGetValue(packet->payload, CFSTR("MessageType")); if (CFStringCompare(type, USBMuxPacketMessage[kUSBMuxPacketResultType], 0x0) == 0x0) { } else if (CFStringCompare(type, USBMuxPacketMessage[kUSBMuxPacketAttachType], 0x0) == 0x0) { } else if (CFStringCompare(type, USBMuxPacketMessage[kUSBMuxPacketDetachType], 0x0) == 0x0) { } } else { if (CFDictionaryContainsKey(packet->payload, CFSTR("Logs"))) { } else if (CFDictionaryContainsKey(packet->payload, CFSTR("DeviceList"))) { } else if (CFDictionaryContainsKey(packet->payload, CFSTR("ListenerList"))) { } else { } } } else { printf("socketSourceEventHandler: failed to decodeCFPropertyList from packet payload\n"); } }); dispatch_source_set_cancel_handler(MuxAgent->socketSource, ^{ printf("socketSourceEventCancelHandler: source canceled\n"); }); dispatch_resume(MuxAgent->socketSource); //sub_d8b5(); CFRunLoopRun(); } } #endif
2.140625
2
2024-11-18T22:25:34.204939+00:00
2023-08-13T13:58:07
7dce91b50a5fe0f92a1e2f176d1e5185160abb1d
{ "blob_id": "7dce91b50a5fe0f92a1e2f176d1e5185160abb1d", "branch_name": "refs/heads/master", "committer_date": "2023-08-13T13:58:07", "content_id": "e7a9109731d178b0c1f97cf09e39c97e62c48b78", "detected_licenses": [ "CC0-1.0" ], "directory_id": "7e4eccee4ba976b6694cd944fea75e7835cd1a4b", "extension": "c", "filename": "test_csp_sm.c", "fork_events_count": 0, "gha_created_at": "2016-03-24T19:11:14", "gha_event_created_at": "2022-06-06T19:18:26", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 54667633, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3574, "license": "CC0-1.0", "license_type": "permissive", "path": "/linux/test_csp_sm.c", "provenance": "stackv2-0115.json.gz:129536", "repo_name": "zwizwa/uc_tools", "revision_date": "2023-08-13T13:58:07", "revision_id": "20df6f91a2082424b498e384583d7f403ff8bf16", "snapshot_id": "fc16d39722d5f30164dad524cd86f1aec230f2f4", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/zwizwa/uc_tools/20df6f91a2082424b498e384583d7f403ff8bf16/linux/test_csp_sm.c", "visit_date": "2023-08-18T20:45:09.789340" }
stackv2
/* Test the interaction of sm.h based state machines and the csp scheduler. This is done using two tasks: a counter, implemented as a single loop a processor, implemented as a loop making two calls to a submachine, with the submachine performing the csp blocking read. A change was made to separate the idea of CSP task and continuation. The csp scheduler does not care about continuations of the individual tasks, but the select macro does rely on computed goto to set the next pointer. This has been separated by providing two arguments: abstract continuation (the thing that has the next pointer) and concrete task struct. To allow sub-tasks to perform CSP functions, they need a pointer to the task struct. */ #include "macros.h" #include "sm_csp.h" /* COUNT TASK */ struct count { struct csp_task task; /* Task ends in a 0-length event array for which we provide * storage here. */ struct csp_evt evt[1]; /* It is our responsibility to represent the continuation. */ void *next; int count; int chan; }; csp_status_t count_tick(struct count *s) { SM_RESUME(s); for(;;) { LOG("count: %d -> ", s->count); CSP_SND(&(s->task), s, s->chan, s->count); s->count++; } } void count_init(struct count *s, int chan) { memset(s,0,sizeof(*s)); s->task.resume = (csp_resume_f)count_tick; s->chan = chan; } /* PROC TASK + SUB*/ struct procsub { // struct csp_task task; /* Task ends in a 0-length event array for which we provide * storage here. */ // struct csp_evt evt[1]; /* It is our responsibility to represent the continuation. */ void *next; int chan; int loops; int count; /* If the subtask wants to wait on events, it needs a reference to the task structure. Use a wrapper to keep the shape of the macros. FIXME: chean up that interface. */ struct csp_task *task; }; csp_status_t procsub_tick(struct procsub *s) { SM_RESUME(s); while (s->loops--) { CSP_RCV(s->task, s, s->chan, s->count); LOG("procsub: %d %d\n", s->count, s->loops); } LOG("\n"); SM_HALT(s); } void procsub_init(struct procsub *s, struct csp_task *task, int loops) { memset(s,0,sizeof(*s)); s->loops = loops; s->task = task; } struct proc { struct csp_task task; /* Task ends in a 0-length event array for which we provide * storage here. */ struct csp_evt evt[1]; /* It is our responsibility to represent the continuation. */ void *next; int loops; int chan; union { struct procsub procsub; } sub; }; csp_status_t proc_tick(struct proc *s) { SM_RESUME(s); while(s->loops--) { SM_SUB_HALT(s, procsub, &s->task, 3); SM_SUB_HALT(s, procsub, &s->task, 2); } halt: SM_HALT(s); } void proc_init(struct proc *s, int chan) { memset(s,0,sizeof(*s)); s->task.resume = (csp_resume_f)proc_tick; s->chan = chan; s->loops = 4; } /* SETUP */ void test1(struct csp_scheduler *s) { struct count c; struct proc p; SM_CSP_START(s, &c.task, count, &c, 0 /* chan */); SM_CSP_START(s, &p.task, proc, &p, 0 /* chan */); csp_schedule(s); LOG("\n"); } int main(int argc, char **argv) { /* Sizes don't matter much for tests. Just make sure they are large enough. FIXME: create some functionality to compute storage parameters from application. */ int nb_c2e = 20; int nb_c = 20; csp_with_scheduler(nb_c2e, nb_c, test1); return 0; }
3.09375
3
2024-11-18T22:25:34.699328+00:00
2022-04-06T18:13:11
116a171ef6fc1cf9ca2d89aecce74b7c2c5d888b
{ "blob_id": "116a171ef6fc1cf9ca2d89aecce74b7c2c5d888b", "branch_name": "refs/heads/master", "committer_date": "2022-04-06T18:13:11", "content_id": "4be5d886315c43009574063a130e3f8f8a7dcfb1", "detected_licenses": [ "Apache-2.0" ], "directory_id": "aaee792bb1bab2839b39cb89d30799578e56d36e", "extension": "c", "filename": "wdns-hex-driver.c", "fork_events_count": 8, "gha_created_at": "2013-11-30T20:43:45", "gha_event_created_at": "2023-09-06T15:36:33", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 14828058, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1644, "license": "Apache-2.0", "license_type": "permissive", "path": "/examples/wdns-hex-driver.c", "provenance": "stackv2-0115.json.gz:129794", "repo_name": "farsightsec/wdns", "revision_date": "2022-04-06T18:13:11", "revision_id": "00741508d2e22ac1904d674ee6131383890c097b", "snapshot_id": "2ddce23290f6c8efa8b9d5d0c0ea6b8c77e3f0f7", "src_encoding": "UTF-8", "star_events_count": 14, "url": "https://raw.githubusercontent.com/farsightsec/wdns/00741508d2e22ac1904d674ee6131383890c097b/examples/wdns-hex-driver.c", "visit_date": "2023-09-03T15:32:08.890521" }
stackv2
#include "private.h" #include <wdns.h> extern bool loadfunc(uint8_t *data, size_t len); extern bool testfunc(void); extern void freefunc(void); static bool hex_to_int(char hex, uint8_t *val) { if (islower((unsigned char) hex)) hex = toupper((unsigned char) hex); switch (hex) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': *val = (hex - '0'); return (true); case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': *val = (hex - 55); return (true); default: printf("hex_to_int() failed\n"); return (false); } } static bool hex_decode(const char *hex, uint8_t **raw, size_t *len) { size_t hexlen = strlen(hex); uint8_t *p; if (hexlen == 0 || (hexlen % 2) != 0) return (false); *len = hexlen / 2; p = *raw = malloc(*len); if (*raw == NULL) return (false); while (hexlen != 0) { uint8_t val[2]; if (!hex_to_int(*hex, &val[0])) goto err; hex++; if (!hex_to_int(*hex, &val[1])) goto err; hex++; *p = (val[0] << 4) | val[1]; p++; hexlen -= 2; } return (true); err: free(*raw); return (false); } int main(int argc, char **argv) { size_t rawlen; uint8_t *rawdata; if (argc != 2) { fprintf(stderr, "Usage: %s <HEXDATA>\n", argv[0]); return (EXIT_FAILURE); } if (!hex_decode(argv[1], &rawdata, &rawlen)) { fprintf(stderr, "Error: unable to decode hex\n"); return (EXIT_FAILURE); } if (loadfunc(rawdata, rawlen)) { testfunc(); freefunc(); } else { free(rawdata); fprintf(stderr, "Error: load function failed\n"); return (EXIT_FAILURE); } free(rawdata); return (EXIT_SUCCESS); }
2.84375
3
2024-11-18T22:25:34.817126+00:00
2019-06-03T03:13:43
10fcca5992158dd9c49e290f22a3fc1ac9df226d
{ "blob_id": "10fcca5992158dd9c49e290f22a3fc1ac9df226d", "branch_name": "refs/heads/master", "committer_date": "2019-06-03T03:13:43", "content_id": "1dcb9f5aa3c45da7a26cf8d92aa3952d8af5ef08", "detected_licenses": [ "MIT" ], "directory_id": "4306b991ff12fc02b93ee759b75a1ef0913d3288", "extension": "c", "filename": "genProcess.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 80803761, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4724, "license": "MIT", "license_type": "permissive", "path": "/genProcess.c", "provenance": "stackv2-0115.json.gz:130056", "repo_name": "Zhuzxlab/LW-FQZip2", "revision_date": "2019-06-03T03:13:43", "revision_id": "04da905cd672952fe5385739c7e7247cd292b43e", "snapshot_id": "41219ed5a8f85b2586adeedc3f10faf48a011c97", "src_encoding": "UTF-8", "star_events_count": 9, "url": "https://raw.githubusercontent.com/Zhuzxlab/LW-FQZip2/04da905cd672952fe5385739c7e7247cd292b43e/genProcess.c", "visit_date": "2021-01-09T05:37:03.637765" }
stackv2
//load the genome file to memery and get the index of PreKey! #include "head.h" //#define INFINITY 0x7fffffff char *file_name=NULL, *gen_buf=NULL; int **Indexarray=NULL, *IndexarrayNum=NULL, *InitarraySize=NULL; //store the IndexPosition int isfasta(char * p) { int len, i; len=strlen(p); for(i=len-1; *(p+i)!='.'; i--); if( !stringcmp(p+i, ".fasta") || !stringcmp(p+i, ".fa") ) return 1; else return 0; } void AddIndexWord(unsigned int Key, int Posi) //Link or array { //Link /*struct IndexLink *p; p=(struct IndexLink *) malloc( sizeof(struct IndexLink) ); p->Posi=posi; p->Next=*(IndexData+Key)->Next; *(IndexData+Key)->Next=p; return *(IndexData+Key);*/ //array } char * getIndex(int NumberP, int *IndexP, char *buf) //get the Index via Hashtable { int i, j, KeyP, PreKeyLength, IndexHashLength; unsigned int HashWord=0; PreKeyLength=strlen(IndexPreKey); IndexHashLength=_pow(4,HashStrlen); InitarraySize=(int*)calloc( IndexHashLength,sizeof(int) ); IndexarrayNum=(int*)calloc( IndexHashLength,sizeof(int) ); Indexarray=(int **) calloc( IndexHashLength,sizeof(int*)); for(i=0; i<IndexHashLength; i++) { *(InitarraySize+i)=100; *(Indexarray+i)=(int *) calloc( *(InitarraySize+i), sizeof(int) ); } for(i=0; i<NumberP; i++) { KeyP=*(IndexP+i); for(j=0; j<HashStrlen; j++) //hashStrlen=8 HashWord=base_hash( *(buf+KeyP+j),HashWord ); *(*(Indexarray+HashWord)+ *(IndexarrayNum+HashWord) )= KeyP; //posi is point to the next char of "PreKey" *(IndexarrayNum+HashWord)+=1; if( *(IndexarrayNum+HashWord)==*(InitarraySize+HashWord) ) //request more memory { *(InitarraySize+HashWord) += 100; *(Indexarray+HashWord)=(int *)realloc( *(Indexarray+HashWord), sizeof(int)*(*(InitarraySize+HashWord)) ); } HashWord=0; } return buf; } size_t InitsrcFile(FILE *fp) { char firstch, str[2048]; size_t genome_size=0; int size; fseek(fp,0,SEEK_END); genome_size=ftell(fp); //get file size fseek(fp,0,SEEK_SET); if( (firstch=fgetc(fp))=='>' ) //if there is a title { title=(char *)calloc( 4096,sizeof(char) ); fscanf(fp,"%s",title); fgets(str,2048,fp); } //printf("%s\n",*title ); //test title size=sizeof(char); fseek(fp, -size, SEEK_CUR); //back a char return genome_size; } //load genome to genBaseBuf & getIndex char * genProcess(char *genFileName, char *BaseBuf, char *PreKey) { FILE *srcFile, *outFile; size_t genSize=0; long int i=0, j=0, base_count=0, readtemp; long int Key_offset,offset, PreKeyLength, IndexPosi_count, InitIndexPosi_count; char basech, PreKeyEndchar; //open file srcFile=fopen(genFileName,"rb"); if(!srcFile) { printf("error input genome file :%s\n",genFileName); return NULL; } //read file genSize=InitsrcFile(srcFile); if(genSize>0) { gen_buf=(char *)malloc(genSize); BaseBuf=(char *) calloc( genSize, sizeof(char) ); if(!gen_buf || ! BaseBuf) { printf("lack of memory to load the genomes!\n"); return NULL; } readtemp=fread(gen_buf,sizeof(char),genSize,srcFile); //if readtemp < genSize ERROR } else { printf("error genome file size\nMax Genome Size :4G\n"); return NULL; } //test readtemp & genSize BaseBuf=BaseBuf+5; //the start is 5 zero! for mapping PreKeyLength=strlen(PreKey); PreKeyEndchar=Caps(*(PreKey+PreKeyLength-1)); Key_offset=PreKeyLength-2; offset=2; IndexPosi_count=0; InitIndexPosi_count=128*1024; IndexPosition=(int*)calloc( InitIndexPosi_count, sizeof(int) ); for(j=0; j<readtemp; j++) { if( ( basech=Caps(*(gen_buf+j)) )>64 ) //del the LF { *(BaseBuf+base_count)=basech; base_count++; //record base //get index depend on PreKey if( basech == PreKeyEndchar ) //request PreKeyLength>1 { while( *(BaseBuf+base_count-offset)==*(PreKey+PreKeyLength-offset) ) { if(PreKeyLength-offset==0) { *(IndexPosition+IndexPosi_count)=base_count; //+1 means the next char of "CG..." IndexPosi_count++; if(IndexPosi_count==InitIndexPosi_count) //request more memory { InitIndexPosi_count+=InitIndexPosi_count; IndexPosition=(int*)realloc(IndexPosition, InitIndexPosi_count*sizeof(int)); } break; } offset++; } offset=2; } } } while( *(IndexPosition+IndexPosi_count-1) > base_count-20 ) IndexPosi_count--; //delete the last //record the information of struct Ind BaseCount = base_count; //base_num[0]=0 IndexPosiCount = IndexPosi_count; //HashStrlen = 8; //8 or 10 14 strcpy( IndexPreKey , PreKey ); fclose(srcFile); if(gen_buf!=NULL) { free(gen_buf); gen_buf=NULL; } //get index from IndexPosition BaseBuf=getIndex(IndexPosi_count, IndexPosition, BaseBuf); return BaseBuf; }
2.484375
2
2024-11-18T22:25:34.919502+00:00
2019-07-09T15:46:04
b0bce9bf65f534544057f39042e5f153268056d5
{ "blob_id": "b0bce9bf65f534544057f39042e5f153268056d5", "branch_name": "refs/heads/master", "committer_date": "2019-07-09T15:46:04", "content_id": "a7dc19b38e8cf0771ebf3bdc66a62a8b9aa0c41b", "detected_licenses": [ "MIT" ], "directory_id": "f2916122ee02817233b22ca6205081bc56d3a46a", "extension": "h", "filename": "malloc.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 163726636, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 230, "license": "MIT", "license_type": "permissive", "path": "/include/malloc.h", "provenance": "stackv2-0115.json.gz:130184", "repo_name": "archibate/h2os", "revision_date": "2019-07-09T15:46:04", "revision_id": "04bf2a16519969eeb605ec97d8cb04d16da93ee9", "snapshot_id": "04315e5176fe5bece84be1832da7f91b3786a4a6", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/archibate/h2os/04bf2a16519969eeb605ec97d8cb04d16da93ee9/include/malloc.h", "visit_date": "2020-04-14T07:59:01.498942" }
stackv2
#pragma once #include <inttypes.h> void *malloc(size_t size); void *zalloc(size_t size); void *calloc(size_t nmemb, size_t size); void *amalloc(size_t len, size_t align); void *realloc(void *p, size_t size); void free(void *p);
2.078125
2
2024-11-18T22:25:38.297070+00:00
2019-03-28T19:14:22
e074237321a0a2739660071659c52798345494c8
{ "blob_id": "e074237321a0a2739660071659c52798345494c8", "branch_name": "refs/heads/master", "committer_date": "2019-03-28T19:14:22", "content_id": "9daee47ff4d2041bc455a37cfbd47dfa36810326", "detected_licenses": [ "MIT" ], "directory_id": "325749aab317529bf8ee3b1926f07e056eed5a44", "extension": "c", "filename": "csmsavetxt.c", "fork_events_count": 2, "gha_created_at": "2017-11-19T17:15:27", "gha_event_created_at": "2018-11-29T13:07:39", "gha_language": "C", "gha_license_id": "MIT", "github_id": 111315769, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8668, "license": "MIT", "license_type": "permissive", "path": "/rGWB/csmsavetxt.c", "provenance": "stackv2-0115.json.gz:130577", "repo_name": "mfernba/rGWB", "revision_date": "2019-03-28T19:14:22", "revision_id": "346de75519b1752c1ac9bea8ad7e5526096506ca", "snapshot_id": "249d32bb8f1ca764f6b27a2e4d811bb5846fcff7", "src_encoding": "UTF-8", "star_events_count": 12, "url": "https://raw.githubusercontent.com/mfernba/rGWB/346de75519b1752c1ac9bea8ad7e5526096506ca/rGWB/csmsavetxt.c", "visit_date": "2021-07-04T16:02:16.555187" }
stackv2
// // csmsavetxt.c // rGWB // // Created by Manuel Fernández on 1/11/18. // Copyright © 2018 Manuel Fernández. All rights reserved. // #include "csmsavetxt.h" #include "csmsave.h" #include "csmstring.inl" #ifdef RGWB_STANDALONE_DISTRIBUTABLE #include "csmassert.inl" #include "csmmem.inl" #else #include "cyassert.h" #include "cypespy.h" #include "cypeio.h" #include "cypetxt.h" #include "standarc.h" #define fflush f_lc_fflush #define fopen lc_fopen #define fclose lc_fclose #define fprintf ctxt_printf #endif enum i_mode_t { i_MODE_WRITE, i_MODE_READ }; struct csmsavetxt_t { FILE *file_descriptor; enum i_mode_t mode; }; #define i_STRING_BUFFER_SIZE (1024 * 1024) // ---------------------------------------------------------------------------------------------------- CONSTRUCTOR(static struct csmsavetxt_t *, i_new, (FILE **file_descriptor, enum i_mode_t mode)) { struct csmsavetxt_t *csmsave; csmsave = MALLOC(struct csmsavetxt_t); csmsave->file_descriptor = ASSIGN_POINTER_PP_NOT_NULL(file_descriptor, FILE); csmsave->mode = mode; return csmsave; } // ---------------------------------------------------------------------------------------------------- static void i_free(struct csmsavetxt_t **csmsave) { assert_no_null(csmsave); assert_no_null(*csmsave); assert_no_null((*csmsave)->file_descriptor); (void)fflush((*csmsave)->file_descriptor); fclose((*csmsave)->file_descriptor); (*csmsave)->file_descriptor = NULL; FREE_PP(csmsave, struct csmsavetxt_t); } // ---------------------------------------------------------------------------------------------------- static void i_write_bool(const struct csmsavetxt_t *csmsave, CSMBOOL value) { assert_no_null(csmsave); assert(csmsave->mode == i_MODE_WRITE); fprintf(csmsave->file_descriptor, "%hu\n", value); } // ---------------------------------------------------------------------------------------------------- static void i_write_ushort(const struct csmsavetxt_t *csmsave, unsigned short value) { assert_no_null(csmsave); assert(csmsave->mode == i_MODE_WRITE); fprintf(csmsave->file_descriptor, "%hu\n", value); } // ---------------------------------------------------------------------------------------------------- static void i_write_uchar(const struct csmsavetxt_t *csmsave, unsigned char value) { assert_no_null(csmsave); assert(csmsave->mode == i_MODE_WRITE); fprintf(csmsave->file_descriptor, "%hhu\n", value); } // ---------------------------------------------------------------------------------------------------- static void i_write_ulong(const struct csmsavetxt_t *csmsave, unsigned long value) { assert_no_null(csmsave); assert(csmsave->mode == i_MODE_WRITE); fprintf(csmsave->file_descriptor, "%lu\n", value); } // ---------------------------------------------------------------------------------------------------- static void i_write_double(const struct csmsavetxt_t *csmsave, double value) { assert_no_null(csmsave); assert(csmsave->mode == i_MODE_WRITE); fprintf(csmsave->file_descriptor, "%.17lf\n", value); } // ---------------------------------------------------------------------------------------------------- static void i_write_float(const struct csmsavetxt_t *csmsave, float value) { assert_no_null(csmsave); assert(csmsave->mode == i_MODE_WRITE); fprintf(csmsave->file_descriptor, "%.9f\n", value); } // ---------------------------------------------------------------------------------------------------- static void i_write_string(const struct csmsavetxt_t *csmsave, const char *value) { assert_no_null(csmsave); assert(csmsave->mode == i_MODE_WRITE); fprintf(csmsave->file_descriptor, "%s\n", value); } // ---------------------------------------------------------------------------------------------------- static CSMBOOL i_read_bool(const struct csmsavetxt_t *csmsave) { unsigned short value; int readed; assert_no_null(csmsave); readed = fscanf(csmsave->file_descriptor, "%hu\n", &value); assert(readed == 1); assert(value == 0 || value == 1); return (CSMBOOL)value; } // ---------------------------------------------------------------------------------------------------- static unsigned char i_read_uchar(const struct csmsavetxt_t *csmsave) { unsigned char value; int readed; assert_no_null(csmsave); readed = fscanf(csmsave->file_descriptor, "%hhu", &value); assert(readed == 1); assert(value < 255); return (unsigned char)value; } // ---------------------------------------------------------------------------------------------------- static unsigned short i_read_ushort(const struct csmsavetxt_t *csmsave) { unsigned short value; int readed; assert_no_null(csmsave); readed = fscanf(csmsave->file_descriptor, "%hu\n", &value); assert(readed == 1); return (CSMBOOL)value; } // ---------------------------------------------------------------------------------------------------- static unsigned long i_read_ulong(const struct csmsavetxt_t *csmsave) { unsigned long value; int readed; assert_no_null(csmsave); readed = fscanf(csmsave->file_descriptor, "%lu\n", &value); assert(readed == 1); return value; } // ---------------------------------------------------------------------------------------------------- static double i_read_double(const struct csmsavetxt_t *csmsave) { double value; int readed; assert_no_null(csmsave); readed = fscanf(csmsave->file_descriptor, "%lf\n", &value); assert(readed == 1); return value; } // ---------------------------------------------------------------------------------------------------- static float i_read_float(const struct csmsavetxt_t *csmsave) { float value; int readed; assert_no_null(csmsave); readed = fscanf(csmsave->file_descriptor, "%f\n", &value); assert(readed == 1); return value; } // ---------------------------------------------------------------------------------------------------- CONSTRUCTOR(static char *, i_read_string, (const struct csmsavetxt_t *csmsave)) { int readed; char value[i_STRING_BUFFER_SIZE]; assert_no_null(csmsave); assert(csmsave->mode == i_MODE_READ); readed = fscanf(csmsave->file_descriptor, "%s\n", value); assert(readed == 1); return csmstring_duplicate(value); } // ---------------------------------------------------------------------------------------------------- CONSTRUCTOR(static struct csmsave_t *, i_new_csmsave, (struct csmsavetxt_t **csmsavetxt)) { return csmsave_new( csmsavetxt, csmsavetxt_t, i_free, i_write_bool, i_write_uchar, i_write_ushort, i_write_ulong, i_write_double, i_write_float, i_write_string, i_read_bool, i_read_uchar, i_read_ushort, i_read_ulong, i_read_double, i_read_float, i_read_string, i_write_string, i_read_string); } // ---------------------------------------------------------------------------------------------------- struct csmsave_t *csmsavetxt_new_file_writer(const char *file_path) { FILE *file_descriptor; enum i_mode_t mode; struct csmsavetxt_t *csmsavetxt; file_descriptor = fopen(file_path, "wt"); assert_no_null(file_descriptor); mode = i_MODE_WRITE; csmsavetxt = i_new(&file_descriptor, mode); return i_new_csmsave(&csmsavetxt); } // ---------------------------------------------------------------------------------------------------- struct csmsave_t *csmsavetxt_new_file_reader(const char *file_path) { FILE *file_descriptor; enum i_mode_t mode; struct csmsavetxt_t *csmsavetxt; file_descriptor = fopen(file_path, "rt"); assert_no_null(file_descriptor); mode = i_MODE_READ; csmsavetxt = i_new(&file_descriptor, mode); return i_new_csmsave(&csmsavetxt); }
2.484375
2
2024-11-18T22:25:38.422367+00:00
2021-02-14T20:58:56
fcd58d2cfbb9c09297205a43a18686a618bf8310
{ "blob_id": "fcd58d2cfbb9c09297205a43a18686a618bf8310", "branch_name": "refs/heads/master", "committer_date": "2021-02-14T20:58:56", "content_id": "7a00856570495048d35a741cb1de0ffdc95fbebf", "detected_licenses": [ "MIT" ], "directory_id": "a69d1330f160a42a89ea78ce4b1a494a68ffeeaa", "extension": "c", "filename": "source_code_.c", "fork_events_count": 0, "gha_created_at": "2019-10-04T18:38:46", "gha_event_created_at": "2019-10-04T19:04:03", "gha_language": null, "gha_license_id": "MIT", "github_id": 212880607, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 506, "license": "MIT", "license_type": "permissive", "path": "/DS18B20 Water Proof Temperature Sensor/source_code_.c", "provenance": "stackv2-0115.json.gz:130706", "repo_name": "amadou-olabi/Arduino-Test-Codes", "revision_date": "2021-02-14T20:58:56", "revision_id": "4a8274c3cd6a25502695a48016a3cfe15f7ff385", "snapshot_id": "c7e55872a4dfaf3f001ea76faa14f8261c9cae5b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/amadou-olabi/Arduino-Test-Codes/4a8274c3cd6a25502695a48016a3cfe15f7ff385/DS18B20 Water Proof Temperature Sensor/source_code_.c", "visit_date": "2021-06-25T23:29:53.309831" }
stackv2
#include "OneWire.h" #include "DallasTemperature.h" #define ONE_WIRE_BUS 5 OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensors(&oneWire); float Celcius=0; float Fahrenheit=0; void setup(void) { Serial.begin(9600); sensors.begin(); } void loop(void) { sensors.requestTemperatures(); Celcius=sensors.getTempCByIndex(0); Fahrenheit=sensors.toFahrenheit(Celcius); Serial.print(" C "); Serial.print(Celcius); Serial.print(" F "); Serial.println(Fahrenheit); delay(1000); }
2.375
2
2024-11-18T22:25:38.653157+00:00
2017-06-16T16:35:56
1f9455062275da5d277c0c3a4d245fe053b28a5d
{ "blob_id": "1f9455062275da5d277c0c3a4d245fe053b28a5d", "branch_name": "refs/heads/master", "committer_date": "2017-06-16T16:35:56", "content_id": "db7100e2d875e5c015a703ddb5d64195a1f94f8a", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "0d3e96843f84f7981dcbec2062cae002232228f9", "extension": "c", "filename": "ice_parameters.c", "fork_events_count": 0, "gha_created_at": "2017-06-22T10:54:21", "gha_event_created_at": "2017-06-22T10:54:21", "gha_language": null, "gha_license_id": null, "github_id": 95105880, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2877, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/librawrtc/ice_parameters.c", "provenance": "stackv2-0115.json.gz:130964", "repo_name": "fippo/rawrtc", "revision_date": "2017-06-16T16:35:56", "revision_id": "929766ab1e15c4ce266a68d7b54cb2269ad6512c", "snapshot_id": "69406640c5ea6c2b8fc9785ba97ee019b572219c", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/fippo/rawrtc/929766ab1e15c4ce266a68d7b54cb2269ad6512c/src/librawrtc/ice_parameters.c", "visit_date": "2021-01-13T05:36:16.326091" }
stackv2
#include <rawrtc.h> #include "ice_parameters.h" /* * Destructor for an existing ICE parameters instance. */ static void rawrtc_ice_parameters_destroy( void* const arg ) { struct rawrtc_ice_parameters* const parameters = arg; // Un-reference mem_deref(parameters->username_fragment); mem_deref(parameters->password); } /* * Create a new ICE parameters instance. */ enum rawrtc_code rawrtc_ice_parameters_create( struct rawrtc_ice_parameters** const parametersp, // de-referenced char* const username_fragment, // copied char* const password, // copied bool const ice_lite ) { struct rawrtc_ice_parameters* parameters; enum rawrtc_code error; // Check arguments if (!parametersp || !username_fragment || !password) { return RAWRTC_CODE_INVALID_ARGUMENT; } // Allocate parameters = mem_zalloc(sizeof(*parameters), rawrtc_ice_parameters_destroy); if (!parameters) { return RAWRTC_CODE_NO_MEMORY; } // Set fields/copy error = rawrtc_strdup(&parameters->username_fragment, username_fragment); if (error) { goto out; } error = rawrtc_strdup(&parameters->password, password); if (error) { goto out; } parameters->ice_lite = ice_lite; out: if (error) { mem_deref(parameters); } else { // Set pointer *parametersp = parameters; } return error; } /* * Get the ICE parameter's username fragment value. * `*username_fragmentp` must be unreferenced. */ enum rawrtc_code rawrtc_ice_parameters_get_username_fragment( char** const username_fragmentp, // de-referenced struct rawrtc_ice_parameters* const parameters ) { // Check arguments if (!username_fragmentp || !parameters) { return RAWRTC_CODE_INVALID_ARGUMENT; } // Set pointer (and reference) *username_fragmentp = mem_ref(parameters->username_fragment); return RAWRTC_CODE_SUCCESS; } /* * Get the ICE parameter's password value. * `*passwordp` must be unreferenced. */ enum rawrtc_code rawrtc_ice_parameters_get_password( char** const passwordp, // de-referenced struct rawrtc_ice_parameters* const parameters ) { // Check arguments if (!passwordp || !parameters) { return RAWRTC_CODE_INVALID_ARGUMENT; } // Set pointer (and reference) *passwordp = mem_ref(parameters->password); return RAWRTC_CODE_SUCCESS; } /* * Get the ICE parameter's ICE lite value. */ enum rawrtc_code rawrtc_ice_parameters_get_ice_lite( bool* const ice_litep, // de-referenced struct rawrtc_ice_parameters* const parameters ) { // Check arguments if (!ice_litep || !parameters) { return RAWRTC_CODE_INVALID_ARGUMENT; } // Set value *ice_litep = parameters->ice_lite; return RAWRTC_CODE_SUCCESS; }
2.625
3
2024-11-18T22:25:39.220993+00:00
2019-04-23T06:53:09
3bbcee2e3e17a576f24d3665ea3cfebfb056d908
{ "blob_id": "3bbcee2e3e17a576f24d3665ea3cfebfb056d908", "branch_name": "refs/heads/master", "committer_date": "2019-04-23T06:53:09", "content_id": "21e71458a2c3cc34d816ecddba402e7ffdd90b89", "detected_licenses": [ "MIT" ], "directory_id": "c73420f06038e6ac9b7ca84a5d292264425a62d6", "extension": "c", "filename": "ft_term_utils.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": 2180, "license": "MIT", "license_type": "permissive", "path": "/src/keyboard/ft_term_utils.c", "provenance": "stackv2-0115.json.gz:131351", "repo_name": "chenlilong84/21sh", "revision_date": "2019-04-23T06:53:09", "revision_id": "e6b09f761718a92fae3a3b6f5ef2926640575865", "snapshot_id": "5c8be2e2b653fbf14961aef4fe714bf5a847a508", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/chenlilong84/21sh/e6b09f761718a92fae3a3b6f5ef2926640575865/src/keyboard/ft_term_utils.c", "visit_date": "2020-06-02T19:33:45.833810" }
stackv2
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_term_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: julekgwa <julekgwa@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/12/19 12:52:55 by julekgwa #+# #+# */ /* Updated: 2017/01/03 09:59:08 by julekgwa ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" int ft_myputchar(int c) { return (write(2, &c, 1)); } void ft_create_stack(t_stack *stack, char **envp) { t_search *search; char *path; char **split; search = (t_search *)malloc(sizeof(t_search) + 1); ft_memset(stack->list, 0, 4096); ft_memset(&stack->hash, 0, sizeof(t_hash *) * MAX_HASH); path = ft_get_env("$PATH", envp); split = ft_strsplit(path, ':'); ft_hash_table_bin(stack->hash, split); search->results = ""; search->prev_match = ""; search->fail = 0; stack->search = search; stack->ctrl_r = 0; stack->count = -1; stack->success = 0; stack->envp = envp; stack->paste = ""; stack->top = -1; stack->capacity = 4096; freecopy(split); } void ft_push(t_stack *stack, char *hist) { if (stack->top == stack->capacity - 1) return ; stack->list[++stack->top] = hist; stack->count = stack->top + 1; } void ft_display_cmd(char *cmd, int pos) { int i; i = 0; while (cmd[i]) { if (i == pos - 1) { tputs(tgetstr("so", NULL), 1, ft_myputchar); ft_putchar(cmd[i]); tputs(tgetstr("se", NULL), 1, ft_myputchar); } else ft_putchar(cmd[i]); i++; } } int ft_in_array(char **av, int len, char *needle) { int i; i = 0; while (i < len) { if (ft_strequ(av[i], needle)) return (1); i++; } return (0); }
2.59375
3
2024-11-18T22:25:39.291317+00:00
2021-01-05T02:01:30
0a3b83246da14f5d8834a0a4b5c40c08d66b3ce3
{ "blob_id": "0a3b83246da14f5d8834a0a4b5c40c08d66b3ce3", "branch_name": "refs/heads/master", "committer_date": "2021-01-05T02:01:30", "content_id": "a4d15a912456a8745c98d4296bbbb4eb46a4945e", "detected_licenses": [ "MIT" ], "directory_id": "609059bfbb21ecc1f109c2480925cd8aa23d998a", "extension": "h", "filename": "lcd.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": 614, "license": "MIT", "license_type": "permissive", "path": "/src/lcd.h", "provenance": "stackv2-0115.json.gz:131481", "repo_name": "JooHyeonKim/IronMan_MoodLight", "revision_date": "2021-01-05T02:01:30", "revision_id": "c2f44b93bd7dbb86325dbdcf0b02f29dbe041ba0", "snapshot_id": "ae06adec9dbfc26efa6b180e60a3ea77f0042b01", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/JooHyeonKim/IronMan_MoodLight/c2f44b93bd7dbb86325dbdcf0b02f29dbe041ba0/src/lcd.h", "visit_date": "2023-07-24T12:27:59.508770" }
stackv2
#ifndef __LCD_H__ #define __LCD_H__ #include <Arduino.h> #include <LiquidCrystal_I2C.h> LiquidCrystal_I2C lcd(PCF8574_ADDR_A21_A11_A01, 16, 2); //lcd 객체 선언 int lcdflag = 0; void UpdateLCDbyRegister(){ int Register = digitalRead(A0); if(lcdflag == 0 && Register == 1) lcd.begin(); if(Register == 0){ lcdflag = 0; }else{ lcdflag = 1; } } void printGestureRunning(){ lcd.setCursor(0, 0); lcd.print("Gesture Running"); lcd.setCursor(15, 0); } void printBluetoothOkay(){ lcd.setCursor(0, 0); lcd.print("Bluetooth Okay. "); lcd.setCursor(15, 0); } #endif
2.28125
2
2024-11-18T22:25:39.524033+00:00
2019-06-15T11:02:49
2d6b2825c6493585723e6ca429d55b7be1d4d754
{ "blob_id": "2d6b2825c6493585723e6ca429d55b7be1d4d754", "branch_name": "refs/heads/master", "committer_date": "2019-06-15T11:36:58", "content_id": "56100ea84be66664fe420c6fdcfbd6ee57545776", "detected_licenses": [ "MIT" ], "directory_id": "c8390b31f98d53e4b1b95b554d3816b3fd7cb5b6", "extension": "c", "filename": "helpers.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 137112374, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 428, "license": "MIT", "license_type": "permissive", "path": "/sandBox/05_interrupts/src/utils/common/helpers.c", "provenance": "stackv2-0115.json.gz:131869", "repo_name": "ragu-manjegowda/vivitsa", "revision_date": "2019-06-15T11:02:49", "revision_id": "1bc8c03d66b24ee12af33266ac86d0b29c9b2e77", "snapshot_id": "a228cb952d2429c673544f4b6a0b1900750e96e8", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/ragu-manjegowda/vivitsa/1bc8c03d66b24ee12af33266ac86d0b29c9b2e77/sandBox/05_interrupts/src/utils/common/helpers.c", "visit_date": "2021-07-16T00:23:35.918206" }
stackv2
#include "helpers.h" void integer_to_string(s8int *buffer, u32int number) { if (number == 0) { buffer[1] = '0'; return; } u32int temp_number = number; s8int buffer_rev[10] = " "; u32int i = 0; while (temp_number > 0) { buffer_rev[i] = '0' + (temp_number % 10); temp_number /= 10; i++; } u32int j = 0; while (i > 0) { buffer[i--] = buffer_rev[j++]; } buffer[i] = buffer_rev[j]; }
2.765625
3
2024-11-18T22:25:39.588058+00:00
2021-09-06T04:35:18
1a2e1cc361169f3cf766a7d5b07caecab61ee1f7
{ "blob_id": "1a2e1cc361169f3cf766a7d5b07caecab61ee1f7", "branch_name": "refs/heads/main", "committer_date": "2021-09-06T04:35:18", "content_id": "7025d95e3966384032f4ad82741bea38aea385e3", "detected_licenses": [ "MIT" ], "directory_id": "2e5625b4c29b81b60953fe57e47c3986a7154b5a", "extension": "c", "filename": "sram.c", "fork_events_count": 0, "gha_created_at": "2021-09-03T14:25:17", "gha_event_created_at": "2021-09-03T15:07:04", "gha_language": "C", "gha_license_id": null, "github_id": 402796504, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1408, "license": "MIT", "license_type": "permissive", "path": "/src/sram/sram.c", "provenance": "stackv2-0115.json.gz:132001", "repo_name": "Ellen7ions/GeminiSim", "revision_date": "2021-09-06T04:35:18", "revision_id": "7adeedf71e0f3616293a0d97c08734d5923e993b", "snapshot_id": "e1bbd822dc8c984b0bbfe74f7246c2d11896a34a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Ellen7ions/GeminiSim/7adeedf71e0f3616293a0d97c08734d5923e993b/src/sram/sram.c", "visit_date": "2023-07-24T13:14:49.433356" }
stackv2
// // Created by Ellen7ions on 2021/9/3. // #include "stdlib.h" #include "stdio.h" #include "sram.h" SRAM *get_inst_sram(const char *filename) { SRAM *inst_sram = (SRAM *) malloc(sizeof(SRAM)); init_inst_sram(inst_sram, filename); return inst_sram; } SRAM *get_data_sram(const char *filename) { SRAM *inst_sram = (SRAM *) malloc(sizeof(SRAM)); init_data_sram(inst_sram, filename); return inst_sram; } void init_sram(SRAM *sram, const char *filename, const char *mode) { sram->file = fopen(filename, mode); } void init_inst_sram(SRAM *sram, const char *filename) { init_sram(sram, filename, "rb"); } void init_data_sram(SRAM *sram, const char *filename) { init_sram(sram, filename, "rb+"); } uint32_t sram_read(SRAM *sram, uint32_t addr) { uint32_t result; uint32_t _addr = addr & 0xfc; rewind(sram->file); fseek(sram->file, _addr, SEEK_SET); fread(&result, sizeof(result), 1, sram->file); return result; } void sram_write(SRAM *sram, uint32_t addr, uint32_t wdata) { uint32_t _addr = addr & 0xfc; rewind(sram->file); fseek(sram->file, _addr, SEEK_CUR); fwrite(&wdata, sizeof(wdata), 1, sram->file); } void sram_top(SRAM *sram, Bus *bus) { if (bus->en) { if (bus->wen) { sram_write(sram, bus->addr, bus->wdata); } else { bus->rdata = sram_read(sram, bus->addr); } } }
2.296875
2
2024-11-18T22:25:40.045290+00:00
2019-03-23T01:35:07
7c5083bcbc507d9aa73ee9ddfb90cfcb32918b5d
{ "blob_id": "7c5083bcbc507d9aa73ee9ddfb90cfcb32918b5d", "branch_name": "refs/heads/master", "committer_date": "2019-03-23T01:35:07", "content_id": "0d970ae829fb49f3279edb8e41e7a16383115b15", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "df33f1348277ef3bacda73a99c3fcfa8269e73e4", "extension": "c", "filename": "module.c", "fork_events_count": 2, "gha_created_at": "2017-05-22T04:19:02", "gha_event_created_at": "2018-08-14T20:02:24", "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 92010746, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7852, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/tools/pscript/module.c", "provenance": "stackv2-0115.json.gz:132653", "repo_name": "38/plumber", "revision_date": "2019-03-23T01:35:07", "revision_id": "30fead11cddd6352025dcac0c16065172744c0f9", "snapshot_id": "ab0153ed1b34fffd45c7db20f4e5535158ada0bc", "src_encoding": "UTF-8", "star_events_count": 40, "url": "https://raw.githubusercontent.com/38/plumber/30fead11cddd6352025dcac0c16065172744c0f9/tools/pscript/module.c", "visit_date": "2021-01-21T18:05:51.981562" }
stackv2
/** * Copyright (C) 2017, Hao Hou * Copyright (C) 2017, Feng Liu **/ #include <unistd.h> #include <stdint.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <sys/stat.h> #include <errno.h> #include <constants.h> #include <error.h> #include <utils/hash/murmurhash3.h> #include <pss.h> #include <module.h> typedef struct _loaded_module_t { uint64_t hash[2]; pss_bytecode_module_t* module; struct _loaded_module_t* next; } _loaded_module_t; static _loaded_module_t* _modules = NULL; static char const* const* _search_path = NULL; int module_set_search_path(char const* const* paths) { if(NULL == paths) ERROR_RETURN_LOG(int, "Invalid arguments"); _search_path = paths; return 0; } static time_t _get_file_ts(const char* path, off_t* size) { struct stat st; if(stat(path, &st) < 0) return ERROR_CODE(time_t); if(NULL != size) *size = st.st_size; return st.st_ctime; } static inline void _add_module_to_list(pss_bytecode_module_t* m, uint64_t hash[2]) { _loaded_module_t* module = (_loaded_module_t*)malloc(sizeof(*module)); if(NULL == module) { LOG_ERROR_ERRNO("Cannot allocate memory for the new module node"); return; } module->hash[0] = hash[0]; module->hash[1] = hash[1]; module->module = m; module->next = _modules; _modules = module; } static pss_bytecode_module_t* _try_load_module_from_buffer(const char* file, const char* code, uint32_t code_size, uint32_t debug, uint32_t repl) { pss_comp_lex_t* lexer = NULL; pss_bytecode_module_t* module = NULL; pss_comp_error_t* err = NULL; if(NULL == (lexer = pss_comp_lex_new(file, code, code_size))) ERROR_LOG_GOTO(_ERR, "Cannot create lexer"); if(NULL == (module = pss_bytecode_module_new())) ERROR_LOG_GOTO(_ERR, "Cannot create module instance"); pss_comp_option_t opt = { .lexer = lexer, .module = module, .debug = (debug != 0), .repl = (repl != 0) }; if(ERROR_CODE(int) == pss_comp_compile(&opt, &err)) ERROR_LOG_GOTO(_ERR, "Can not compile the source code"); if(ERROR_CODE(int) == pss_comp_lex_free(lexer)) LOG_WARNING("Cannot dispose the lexer instance"); return module; _ERR: if(NULL != err) { const pss_comp_error_t* this; for(this = err; NULL != this; this = this->next) fprintf(stderr, "%s:%u:%u:error: %s\n", this->filename, this->line + 1, this->column + 1, this->message); pss_comp_free_error(err); } if(NULL != lexer) pss_comp_lex_free(lexer); if(NULL != module) pss_bytecode_module_free(module); return NULL; } pss_bytecode_module_t* module_from_buffer(const char* code, uint32_t code_size, uint32_t debug, uint32_t repl) { pss_bytecode_module_t* module = NULL; if(NULL == (module = _try_load_module_from_buffer("<stdin>", code, code_size, debug, repl))) return NULL; uint64_t hash[2] = {0, 0}; _add_module_to_list(module, hash); return module; } static int _try_load_module(const char* source_path, const char* compiled_path, int load_compiled, int dump_compiled, int debug, pss_bytecode_module_t** ret) { off_t source_sz = 0; time_t source_ts = source_path == NULL ? ERROR_CODE(time_t) : _get_file_ts(source_path, &source_sz); time_t compiled_ts = compiled_path == NULL ? ERROR_CODE(time_t) : _get_file_ts(compiled_path, NULL); if(load_compiled && ERROR_CODE(time_t) != compiled_ts && (source_ts == ERROR_CODE(time_t) || compiled_ts > source_ts)) { LOG_DEBUG("Found compiled PSS module at %s", compiled_path); if(NULL == (*ret = pss_bytecode_module_load(compiled_path))) ERROR_RETURN_LOG(int, "Cannot alod module from file %s", compiled_path); return 1; } else if(ERROR_CODE(time_t) != source_ts) { LOG_DEBUG("Found PSS module source at %s", source_path); pss_bytecode_module_t* module = NULL; char* code = (char*)malloc((size_t)(source_sz + 1)); FILE* fp = NULL; if(NULL == code) ERROR_LOG_ERRNO_GOTO(ERR, "Cannot allocate memory for code"); code[source_sz] = 0; fp = fopen(source_path, "r"); if(NULL == fp) ERROR_LOG_ERRNO_GOTO(ERR, "Cannot open the source code file"); if(source_sz != 0 && fread(code, (size_t)source_sz, 1, fp) != 1) ERROR_LOG_ERRNO_GOTO(ERR, "Cannot read file"); if(fclose(fp) < 0) ERROR_LOG_ERRNO_GOTO(ERR, "Cannot close file"); else fp = NULL; if(NULL == (module = _try_load_module_from_buffer(source_path, code, (unsigned)(source_sz + 1), (uint32_t)debug, 0))) goto ERR; free(code); if(compiled_path != NULL && dump_compiled && ERROR_CODE(int) == pss_bytecode_module_dump(module, compiled_path)) LOG_WARNING("Cannot dump the compiled module to file"); *ret = module; return 1; ERR: if(NULL != fp) fclose(fp); if(NULL != code) free(code); return ERROR_CODE(int); } return 0; } static inline void _compute_hash(const char* str, uint64_t* hash) { size_t len = strlen(str); murmurhash3_128(str, len, 0x1234567u, hash); } static inline int _is_previously_loaded(const char* source_path) { uint64_t hash[2]; _compute_hash(source_path, hash); const _loaded_module_t* ptr; for(ptr = _modules; NULL != ptr && (ptr->hash[0] != hash[0] || ptr->hash[1] != hash[1]); ptr = ptr->next); return (ptr != NULL); } pss_bytecode_module_t* module_from_file(const char* name, int load_compiled, int dump_compiled, int debug, const char* compiled_output) { if(NULL == name) ERROR_PTR_RETURN_LOG("Invalid arguments"); uint32_t i; pss_bytecode_module_t* ret; uint64_t hash[2] = {}; for(i = 0; _search_path != NULL && _search_path[i] != NULL; i ++) { char module_name[PATH_MAX]; char source_path[PATH_MAX]; char compiled_path[PATH_MAX]; size_t len = strlen(name); if(len > 4 && 0 == strcmp(name + len - 4, ".pss")) len -= 4; else { /* Try to load the fullpath and do not dump the psm if the filename is not end with pss */ snprintf(source_path, sizeof(source_path), "%s/%s", _search_path[i], name); _compute_hash(source_path, hash); int rc = _try_load_module(source_path, NULL, 0, 0, debug, &ret); if(ERROR_CODE(int) == rc) ERROR_PTR_RETURN_LOG("Cannot load module"); if(rc == 1) goto FOUND; } /* If not found, then we need try to find the compiled */ memcpy(module_name, name, len); module_name[len] = 0; snprintf(source_path, sizeof(source_path), "%s/%s.pss", _search_path[i], module_name); if(compiled_output == NULL) snprintf(compiled_path, sizeof(compiled_path), "%s/%s.psm", _search_path[i], module_name); else snprintf(compiled_path, sizeof(compiled_path), "%s", compiled_output); _compute_hash(source_path, hash); int rc = _try_load_module(source_path, compiled_path, load_compiled, dump_compiled, debug, &ret); if(ERROR_CODE(int) == rc) ERROR_PTR_RETURN_LOG("Cannot load module"); if(rc == 1) goto FOUND; } ERROR_PTR_RETURN_LOG("Cannot found the script"); FOUND: _add_module_to_list(ret, hash); return ret; } int module_is_loaded(const char* name) { if(NULL == name) ERROR_RETURN_LOG(int, "Invalid arguments"); uint32_t i; for(i = 0; _search_path != NULL && _search_path[i] != NULL; i ++) { char module_name[PATH_MAX]; char source_path[PATH_MAX]; size_t len = strlen(name); if(len > 4 && 0 == strcmp(name + len - 4, ".pss")) len -= 4; else { /* Try to load the fullpath and do not dump the psm if the filename is not end with pss */ snprintf(source_path, sizeof(source_path), "%s/%s", _search_path[i], name); if(_is_previously_loaded(source_path)) return 1; } memcpy(module_name, name, len); module_name[len] = 0; snprintf(source_path, sizeof(source_path), "%s/%s.pss", _search_path[i], module_name); if(_is_previously_loaded(source_path)) return 1; } return 0; } int module_unload_all() { int rc = 0; _loaded_module_t* ptr; for(ptr = _modules; ptr != NULL;) { _loaded_module_t* this = ptr; ptr = ptr->next; if(ERROR_CODE(int) == pss_bytecode_module_free(this->module)) rc = ERROR_CODE(int); free(this); } return rc; }
2.546875
3
2024-11-18T22:25:40.110912+00:00
2021-03-23T08:58:30
f1cbebcedba9a15337529beee8c9b636b8dbd093
{ "blob_id": "f1cbebcedba9a15337529beee8c9b636b8dbd093", "branch_name": "refs/heads/main", "committer_date": "2021-03-23T08:58:30", "content_id": "c0853a42029e8cc1c76cf95e19a5031712630bb8", "detected_licenses": [ "MIT" ], "directory_id": "218fbb0029c65465e96811c72fc10aa444c271ef", "extension": "c", "filename": "remove_quoted_str.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 330643941, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2876, "license": "MIT", "license_type": "permissive", "path": "/srcs/command_read/remove_quoted_str.c", "provenance": "stackv2-0115.json.gz:132782", "repo_name": "EnapsTer/Minishell", "revision_date": "2021-03-23T08:58:30", "revision_id": "46c8a3cb6e1d1f7a53493930db231c13c3b37efc", "snapshot_id": "e69dbeb31ce1da6bf1cca73b92d95d58f0b75648", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/EnapsTer/Minishell/46c8a3cb6e1d1f7a53493930db231c13c3b37efc/srcs/command_read/remove_quoted_str.c", "visit_date": "2023-03-16T09:12:14.300238" }
stackv2
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* remove_quoted_str.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: nscarab <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/06 17:59:10 by nscarab #+# #+# */ /* Updated: 2021/03/16 17:56:57 by nscarab ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include "start.h" #include <libft.h> static void handle_single_quote(int *quote_flag, int *strlen, char **out) { if (*quote_flag == 1 && *quote_flag != 2) *quote_flag = 0; else if (*quote_flag != 2) { if (out) (*out)[*strlen] = '\r'; *strlen = *strlen + 1; *quote_flag = 1; } } static void handle_double_quote(int *quote_flag, int *strlen, char **out) { if (*quote_flag == 2 && *quote_flag != 1) *quote_flag = 0; else if (*quote_flag != 1) { if (out) (*out)[*strlen] = '\r'; *strlen = *strlen + 1; *quote_flag = 2; } } static void get_final_str(char *str, char **out) { int i; int strlen; int quote_flag; i = 0; strlen = 0; quote_flag = 0; while (str[i]) { if (str[i] == '\'' && (quote_flag == 1 || !is_mirrored(str, i))) handle_single_quote(&quote_flag, &strlen, out); else if (str[i] == '"' && !is_mirrored(str, i)) handle_double_quote(&quote_flag, &strlen, out); else if (quote_flag > 0) ; else (*out)[strlen++] = str[i]; i++; } (*out)[strlen] = '\0'; } static int get_final_strlen(char *str) { int i; int strlen; int quote_flag; i = 0; strlen = 0; quote_flag = 0; while (str[i]) { if (str[i] == '\'' && (quote_flag == 1 || !is_mirrored(str, i))) handle_single_quote(&quote_flag, &strlen, NULL); else if (str[i] == '"' && !is_mirrored(str, i)) handle_double_quote(&quote_flag, &strlen, NULL); else if (quote_flag > 0) ; else strlen++; i++; } if (quote_flag > 0) return (-1); return (strlen); } char *remove_quoted_str(char *str, t_env **env, int *continue_flag) { char *out; int strlen; if (!str || str[0] == '\0') { out = ft_strdup(""); return (out); } strlen = get_final_strlen(str); if (strlen == -1) { print_syntax_error("open quotes", env, continue_flag); return (NULL); } if (!(out = (char*)malloc(sizeof(char) * (strlen + 1)))) { *continue_flag = MALLOC_ERROR; return (NULL); } get_final_str(str, &out); return (out); }
2.734375
3
2024-11-18T22:25:40.287992+00:00
2022-11-28T21:01:03
c994111afdf719a296ff9d440b6edbd43b6517f8
{ "blob_id": "c994111afdf719a296ff9d440b6edbd43b6517f8", "branch_name": "refs/heads/master", "committer_date": "2022-11-28T21:01:03", "content_id": "dc64798e8903d8f4fe62a413c3892a4a38d5d419", "detected_licenses": [ "MIT" ], "directory_id": "82751ca8cd84cf2b2fbac850e33c162e9ec77960", "extension": "h", "filename": "example1.h", "fork_events_count": 0, "gha_created_at": "2020-04-13T21:11:30", "gha_event_created_at": "2020-04-13T21:11:31", "gha_language": null, "gha_license_id": "MIT", "github_id": 255442610, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2310, "license": "MIT", "license_type": "permissive", "path": "/fish/mbed/LPCExpress/robotic_fish_6/MODDMA/example1.h", "provenance": "stackv2-0115.json.gz:133041", "repo_name": "arizonat/softroboticfish7", "revision_date": "2022-11-28T21:01:03", "revision_id": "777fd37ff817e131106392a85f65c700198b0197", "snapshot_id": "c4b1b3a866d42c04f7785088010ba0d6a173dc79", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/arizonat/softroboticfish7/777fd37ff817e131106392a85f65c700198b0197/fish/mbed/LPCExpress/robotic_fish_6/MODDMA/example1.h", "visit_date": "2022-12-13T02:59:16.290695" }
stackv2
#include "mbed.h" #include "MODDMA.h" #include "MODSERIAL.h" DigitalOut led1(LED1); DigitalOut led2(LED2); DigitalOut led3(LED3); DigitalOut led4(LED4); MODDMA dma; MODSERIAL pc(USBTX, USBRX); // Function prototypes for IRQ callbacks. // See definitions following main() below. void dmaTCCallback(void); void dmaERRCallback(void); void TC0_callback(void); void ERR0_callback(void); int main() { char s[] = "**DMA** ABCDEFGHIJKLMNOPQRSTUVWXYZ **DMA**"; pc.baud(PC_BAUD); dma.attach_tc( &dmaTCCallback ); dma.attach_err( &dmaERRCallback ); MODDMA_Config *config = new MODDMA_Config; config ->channelNum ( MODDMA::Channel_0 ) ->srcMemAddr ( (uint32_t) &s ) ->dstMemAddr ( 0 ) ->transferSize ( sizeof(s) ) ->transferType ( MODDMA::m2p ) ->transferWidth ( 0 ) ->srcConn ( 0 ) ->dstConn ( MODDMA::UART0_Tx ) ->dmaLLI ( 0 ) ->attach_tc ( &TC0_callback ) ->attach_err ( &ERR0_callback ) ; // config end // Setup the configuration. dma.Setup(config); //dma.Enable( MODDMA::Channel_0 ); //dma.Enable( config->channelNum() ); dma.Enable( config ); while (1) { led1 = !led1; wait(0.25); } } // Main controller TC IRQ callback void dmaTCCallback(void) { led2 = 1; } // Main controller ERR IRQ callback void dmaERRCallback(void) { error("Oh no! My Mbed exploded! :( Only kidding, find the problem"); } // Configuration callback on TC void TC0_callback(void) { MODDMA_Config *config = dma.getConfig(); dma.haltAndWaitChannelComplete( (MODDMA::CHANNELS)config->channelNum()); dma.Disable( (MODDMA::CHANNELS)config->channelNum() ); // Configurations have two IRQ callbacks for TC and Err so you // know which you are processing. However, if you want to use // a single callback function you can tell what type of IRQ // is being processed thus:- if (dma.irqType() == MODDMA::TcIrq) { led3 = 1; dma.clearTcIrq(); } if (dma.irqType() == MODDMA::ErrIrq) { led4 = 1; dma.clearErrIrq(); } } // Configuration cakllback on Error void ERR0_callback(void) { error("Oh no! My Mbed exploded! :( Only kidding, find the problem"); }
2.640625
3
2024-11-18T22:25:40.853600+00:00
2020-08-08T13:53:03
8f6d50ecd364f8147373303244f289925911f103
{ "blob_id": "8f6d50ecd364f8147373303244f289925911f103", "branch_name": "refs/heads/master", "committer_date": "2020-08-08T13:53:03", "content_id": "69db9815492334c34ff1dd764ae1e6f787c95cab", "detected_licenses": [ "MIT" ], "directory_id": "ac7cfc5e41f300f737539211e7bf579d57fee409", "extension": "c", "filename": "alloc.c", "fork_events_count": 0, "gha_created_at": "2020-08-20T03:07:41", "gha_event_created_at": "2020-08-20T03:07:41", "gha_language": null, "gha_license_id": "MIT", "github_id": 288893200, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3089, "license": "MIT", "license_type": "permissive", "path": "/src/rcheevos/alloc.c", "provenance": "stackv2-0115.json.gz:133692", "repo_name": "miagui/rcheevos", "revision_date": "2020-08-08T13:53:03", "revision_id": "203fc282d542a058241f3c5a28a2d0ca15e628cb", "snapshot_id": "e2fd8818f95f3d0e0b07b0797d5b09ee26bc0f19", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/miagui/rcheevos/203fc282d542a058241f3c5a28a2d0ca15e628cb/src/rcheevos/alloc.c", "visit_date": "2022-12-26T00:58:05.144192" }
stackv2
#include "internal.h" #include <stdlib.h> #include <string.h> void* rc_alloc(void* pointer, int* offset, int size, int alignment, rc_scratch_t* scratch) { void* ptr; *offset = (*offset + alignment - 1) & ~(alignment - 1); if (pointer != 0) { ptr = (void*)((char*)pointer + *offset); } else if (scratch != 0) { ptr = &scratch->obj; } else { ptr = 0; } *offset += size; return ptr; } char* rc_alloc_str(rc_parse_state_t* parse, const char* text, int length) { char* ptr; ptr = (char*)rc_alloc(parse->buffer, &parse->offset, length + 1, RC_ALIGNOF(char), 0); if (ptr) { memcpy(ptr, text, length); ptr[length] = '\0'; } return ptr; } void rc_init_parse_state(rc_parse_state_t* parse, void* buffer, lua_State* L, int funcs_ndx) { parse->offset = 0; parse->L = L; parse->funcs_ndx = funcs_ndx; parse->buffer = buffer; parse->scratch.memref = parse->scratch.memref_buffer; parse->scratch.memref_size = sizeof(parse->scratch.memref_buffer) / sizeof(parse->scratch.memref_buffer[0]); parse->scratch.memref_count = 0; parse->first_memref = 0; parse->measured_target = 0; } void rc_destroy_parse_state(rc_parse_state_t* parse) { if (parse->scratch.memref != parse->scratch.memref_buffer) free(parse->scratch.memref); } const char* rc_error_str(int ret) { switch (ret) { case RC_OK: return "OK"; case RC_INVALID_LUA_OPERAND: return "Invalid Lua operand"; case RC_INVALID_MEMORY_OPERAND: return "Invalid memory operand"; case RC_INVALID_CONST_OPERAND: return "Invalid constant operand"; case RC_INVALID_FP_OPERAND: return "Invalid floating-point operand"; case RC_INVALID_CONDITION_TYPE: return "Invalid condition type"; case RC_INVALID_OPERATOR: return "Invalid operator"; case RC_INVALID_REQUIRED_HITS: return "Invalid required hits"; case RC_DUPLICATED_START: return "Duplicated start condition"; case RC_DUPLICATED_CANCEL: return "Duplicated cancel condition"; case RC_DUPLICATED_SUBMIT: return "Duplicated submit condition"; case RC_DUPLICATED_VALUE: return "Duplicated value expression"; case RC_DUPLICATED_PROGRESS: return "Duplicated progress expression"; case RC_MISSING_START: return "Missing start condition"; case RC_MISSING_CANCEL: return "Missing cancel condition"; case RC_MISSING_SUBMIT: return "Missing submit condition"; case RC_MISSING_VALUE: return "Missing value expression"; case RC_INVALID_LBOARD_FIELD: return "Invalid field in leaderboard"; case RC_MISSING_DISPLAY_STRING: return "Missing display string"; case RC_OUT_OF_MEMORY: return "Out of memory"; case RC_INVALID_VALUE_FLAG: return "Invalid flag in value expression"; case RC_MISSING_VALUE_MEASURED: return "Missing measured flag in value expression"; case RC_MULTIPLE_MEASURED: return "Multiple measured targets"; case RC_INVALID_MEASURED_TARGET: return "Invalid measured target"; case RC_INVALID_COMPARISON: return "Invalid comparison"; case RC_INVALID_STATE: return "Invalid state"; default: return "Unknown error"; } }
2.265625
2
2024-11-18T22:25:40.903754+00:00
2020-06-08T08:14:40
9260d25b4ce9506e80fdf670a8505615c86d68d7
{ "blob_id": "9260d25b4ce9506e80fdf670a8505615c86d68d7", "branch_name": "refs/heads/master", "committer_date": "2020-06-08T08:14:40", "content_id": "027b20eebcce3f9d58a39702d4f41a9df8be9b09", "detected_licenses": [ "MIT" ], "directory_id": "a5356472796a32f233ad35b85055e15213e46c64", "extension": "c", "filename": "environment.c", "fork_events_count": 0, "gha_created_at": "2020-03-28T20:55:56", "gha_event_created_at": "2020-04-15T13:26:41", "gha_language": "C", "gha_license_id": "MIT", "github_id": 250891768, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1268, "license": "MIT", "license_type": "permissive", "path": "/src/environment.c", "provenance": "stackv2-0115.json.gz:133821", "repo_name": "celltec/Creatures", "revision_date": "2020-06-08T08:14:40", "revision_id": "6ff21b2d03e737477c688fc35e06c5982a82835f", "snapshot_id": "b60b731106727d7048547b67b976af75f3f16e0d", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/celltec/Creatures/6ff21b2d03e737477c688fc35e06c5982a82835f/src/environment.c", "visit_date": "2022-10-13T17:04:16.904862" }
stackv2
#include "chipmunk/chipmunk.h" #include "sokol.h" #include "free.h" #include "environment.h" Environment* NewEnvironment(void) { return (Environment*)cpcalloc(1, sizeof(Environment)); } void InitEnvironment(Environment* environment) { /* Create new space and set properties */ cpSpace* space = cpSpaceNew(); cpSpaceSetDamping(space, 0.0); /* Bodies shouldn't retain their velocity */ cpSpaceSetCollisionBias(space, 0.0); /* Push apart overlapping bodies very fast */ /* Parse URL or command line arguments */ if (sargs_exists("seed")) { environment->seed = atoi(sargs_value("seed")); } else { environment->seed = (int)stm_now(); } srand(environment->seed); environment->space = space; environment->creatures = NewList(); environment->view = (View*)cpcalloc(1, sizeof(View)); environment->mouse = (Mouse*)cpcalloc(1, sizeof(Mouse)); environment->timeStep = 1.0 / 60.0; /* For 60 Hz */ /* Zoom in the beginning */ environment->view->scale = 0.01; environment->view->targetScale = 0.3; } void DestroyEnvironment(Environment* environment) { FreeAllChildren(environment->space); cpSpaceFree(environment->space); Delete(environment->creatures); cpfree(environment->view); cpfree(environment->mouse); cpfree(environment); }
2.359375
2
2024-11-18T22:25:41.319910+00:00
2021-10-31T05:46:00
7e99e12c525fd145c6adc01381b7a56b01081c1d
{ "blob_id": "7e99e12c525fd145c6adc01381b7a56b01081c1d", "branch_name": "refs/heads/master", "committer_date": "2021-10-31T05:46:00", "content_id": "5d69ac5f81ec5de396e7662f9b6202923cd5b057", "detected_licenses": [ "MIT" ], "directory_id": "9eac48c3beb78b984c918d86ae72954a73253e0c", "extension": "c", "filename": "enqueue_using_linked_list.c", "fork_events_count": 0, "gha_created_at": "2021-10-31T05:46:20", "gha_event_created_at": "2021-10-31T05:49:11", "gha_language": null, "gha_license_id": "MIT", "github_id": 423064440, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1098, "license": "MIT", "license_type": "permissive", "path": "/Yogesh Gaur/implement_in_c/Queue/enqueue_using_linked_list.c", "provenance": "stackv2-0115.json.gz:134213", "repo_name": "herambchaudhari4121/Hacktoberfest-KIIT-2021", "revision_date": "2021-10-31T05:46:00", "revision_id": "dd62a26c519abb786c7116c8ad6bf891451246e8", "snapshot_id": "2986f8c82bd795c606a880b0f68f17c68816b11f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/herambchaudhari4121/Hacktoberfest-KIIT-2021/dd62a26c519abb786c7116c8ad6bf891451246e8/Yogesh Gaur/implement_in_c/Queue/enqueue_using_linked_list.c", "visit_date": "2023-08-19T19:16:34.123637" }
stackv2
#include <stdio.h> #include <stdlib.h> struct queue { int value; struct queue *next; } * front, *rear, *temp, *fr; void enqueue(int data) { if (rear == NULL) { rear = (struct queue *)malloc(sizeof(struct queue)); rear->next = NULL; rear->value = data; front = rear; } else { temp = (struct queue *)malloc(sizeof(struct queue)); rear->next = temp; temp->value = data; temp->next = NULL; rear = temp; } } void traverse_queue() { fr = front; if ((fr == NULL) && (rear == NULL)) { printf("Queue is empty"); return; } while (fr != rear) { printf("%d ", fr->value); fr = fr->next; } if (fr == rear) printf("%d", fr->value); } int main() { int size, elem; printf("Enter the size of the Queue : \n"); scanf("%d", &size); for (int i = 0; i < size; i++) { printf("Enter the Element :\n"); scanf("%d", &elem); enqueue(elem); } printf("Queue is : \n"); traverse_queue(); }
3.9375
4
2024-11-18T22:25:41.475212+00:00
2020-04-12T08:27:17
6a374bab6472789712f31b2b0d0dc8bbc9e21b52
{ "blob_id": "6a374bab6472789712f31b2b0d0dc8bbc9e21b52", "branch_name": "refs/heads/master", "committer_date": "2020-04-12T08:27:17", "content_id": "b18e519964cbb8e91faf5d0c86337bbfd367b336", "detected_licenses": [ "MIT" ], "directory_id": "e9333c8d76b584e5da8fae9dbf937d851c80e887", "extension": "h", "filename": "circular_buff.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 223780127, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 641, "license": "MIT", "license_type": "permissive", "path": "/firmware/TWIP/src/misc/circular_buff.h", "provenance": "stackv2-0115.json.gz:134342", "repo_name": "mihainicolae80/Robot_Inverted_Pendulum", "revision_date": "2020-04-12T08:27:17", "revision_id": "f366ea89748abe886969d35e725a6f0ca7c860e3", "snapshot_id": "f9389c3b7ffffea327b61d499229a2fa2f2cb323", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mihainicolae80/Robot_Inverted_Pendulum/f366ea89748abe886969d35e725a6f0ca7c860e3/firmware/TWIP/src/misc/circular_buff.h", "visit_date": "2020-09-16T13:10:25.790816" }
stackv2
/* * circular_buff.h * * Created: 3/21/2019 5:50:45 PM * Author: mihai */ #ifndef CIRCULAR_BUFF_H_ #define CIRCULAR_BUFF_H_ #include <stdint.h> #include "config/conf_circ_buff.h" #ifndef NULL #define NULL ((void*)0) #endif struct circ_buff_t { uint8_t data[CIRC_BUFF_CAPACITY]; uint8_t size; uint8_t head, tail; }; /* Initialize circular buffer DS */ void circ_buff_init(struct circ_buff_t *buff); /* Add byte to circular buffer */ void circ_buff_put(struct circ_buff_t *buff, uint8_t data); /* Remove and return a byte from circular buffer */ uint8_t circ_buff_get(struct circ_buff_t *buff); #endif /* CIRCULAR_BUFF_H_ */
2.15625
2
2024-11-18T22:25:41.546320+00:00
2021-10-25T14:55:25
8b9f1b76eb6374b1a1fdd89d381253e852c0b0aa
{ "blob_id": "8b9f1b76eb6374b1a1fdd89d381253e852c0b0aa", "branch_name": "refs/heads/master", "committer_date": "2021-10-25T14:55:25", "content_id": "944f7e7099541303c78dbcaaa91303e0f9596110", "detected_licenses": [ "MIT" ], "directory_id": "6a1c028ac0ee25b982ee3aaedaeb77f4b3c427e3", "extension": "c", "filename": "stats.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": 739, "license": "MIT", "license_type": "permissive", "path": "/stats.c", "provenance": "stackv2-0115.json.gz:134470", "repo_name": "clean-code-craft-tcq-2/sense-c-PraveenaJayakumar", "revision_date": "2021-10-25T14:55:25", "revision_id": "c475bf2226e84f6f91dea10675e5c9c2482fa797", "snapshot_id": "e7300d5c725e1034568fb3097a1182cdd45a67cd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/clean-code-craft-tcq-2/sense-c-PraveenaJayakumar/c475bf2226e84f6f91dea10675e5c9c2482fa797/stats.c", "visit_date": "2023-08-25T18:05:13.820002" }
stackv2
#include "stats.h" #include "math.h" struct Stats compute_statistics(const float* numberset, int setlength) { struct Stats s; s.average = 0; s.min = 0; s.max = 0; float sum = 0.0; if((numberset == NULL) || (setlength == 0) || (numberset == 0)) { s.average = NAN; s.min = NAN; s.max = NAN; } else { s.min = numberset[0]; s.max = numberset[0]; for(int i = 0;i<setlength;i++) { if(s.min > numberset[i]) { s.min = numberset[i]; } if(s.max < numberset[i]) { s.max = numberset[i]; } sum += numberset[i]; } s.average = sum / setlength; } return s; }
2.59375
3
2024-11-18T22:25:41.746226+00:00
2020-10-29T12:55:51
6feebace55cbf5170e10345d2820feee3d9c372c
{ "blob_id": "6feebace55cbf5170e10345d2820feee3d9c372c", "branch_name": "refs/heads/master", "committer_date": "2020-10-29T12:55:51", "content_id": "eef37a09e62811d76d8b4363688fd20b08a83419", "detected_licenses": [ "MIT" ], "directory_id": "fb1be179b7dbffff127b0e0088e2c097b7af1735", "extension": "c", "filename": "benchoverride_user.c", "fork_events_count": 0, "gha_created_at": "2020-10-15T04:28:50", "gha_event_created_at": "2020-10-29T12:55:53", "gha_language": "C", "gha_license_id": null, "github_id": 304209797, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7295, "license": "MIT", "license_type": "permissive", "path": "/datafilter/benchoverride_user.c", "provenance": "stackv2-0115.json.gz:134732", "repo_name": "giuliafrascaria/ebpf-data-filter", "revision_date": "2020-10-29T12:55:51", "revision_id": "d52f844eab95d995cff251a1ff6be16759eab0f5", "snapshot_id": "61813d0baf10fb9a89c796a458bd0b54192f663e", "src_encoding": "UTF-8", "star_events_count": 19, "url": "https://raw.githubusercontent.com/giuliafrascaria/ebpf-data-filter/d52f844eab95d995cff251a1ff6be16759eab0f5/datafilter/benchoverride_user.c", "visit_date": "2023-01-02T02:01:10.119831" }
stackv2
// SPDX-License-Identifier: GPL-2.0 #define _GNU_SOURCE #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <sched.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <linux/bpf.h> #include <locale.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/wait.h> #include <time.h> #include <bpf.h> #include "bpf_load.h" #include <fcntl.h> #define ITERATIONS 1000 #define MAX_ITER 10000 #define READ_SIZE 4096 //file is now 32*4kb = 131072 262144 1mb=1048576 4mb= 4194304 2mb=2097152 #define MAX_READ 4096 #define EXEC_1 0 #define EXEC_2 1 int main(int argc, char **argv) { char filename[256]; int ret; snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]); //printf("eBPF file to be loaded is : %s \n", filename); if (load_bpf_file(filename)) { printf("%s", bpf_log_buf); return 1; } char * expected = "42"; char * flag = "deadbeef"; int ret1, ret2; struct timespec tp1, tp2; clockid_t clk_id1, clk_id2; clk_id1 = CLOCK_MONOTONIC; clk_id2 = CLOCK_MONOTONIC; int override_count = 0; int partial_override_count = 0; int exec_count = 0; if (argc != 2) { printf("usage: ./override_exec n\nn: number of batched of iteration. every batch is 1000\n"); return 1; } int i; i = atoi(argv[1]); int readsize = READ_SIZE; int iter = ITERATIONS * i; __u32 key = 0; __u64 counter = 0; if (bpf_map_update_elem(map_fd[1], &key, &counter, BPF_ANY) != 0) { fprintf(stderr, "map_update failed: %s\n", strerror(errno)); return 1; } if(EXEC_1) { while (readsize <= MAX_READ) { char * buf = malloc(readsize + 1); printf("buffer on user side = %lu\n", (unsigned long) buf); __u32 key = 0; if (bpf_map_update_elem(map_fd[0], &key, &buf, BPF_ANY) != 0) { fprintf(stderr, "map_update failed: %s\n", strerror(errno)); return 1; } for (int i = 0; i < ITERATIONS; i++) { char * rand = malloc(readsize + 1); int src = open("/dev/urandom", O_RDONLY); ssize_t randbytes = read(src, rand, readsize); close(src); int fd = open("file", O_WRONLY | O_TRUNC); if (fd == -1) { printf("error open file\n"); exit(EXIT_FAILURE); } int bytes = write(fd, flag, sizeof(flag)); if (bytes == -1) { printf("error write file\n"); exit(EXIT_FAILURE); } bytes = write(fd, rand, readsize ); if (bytes == -1) { printf("error write file\n"); exit(EXIT_FAILURE); } free(rand); //fsync(fd); close(fd); //int fd = open("4kB", O_RDONLY); fd = open("file", O_RDONLY); if (fd == -1) { printf("error open file 2\n"); exit(EXIT_FAILURE); } ssize_t readbytes = read(fd, buf, readsize); if ( strncmp(buf, expected, 2) == 0) { override_count = override_count + 1; } else { exec_count = exec_count + 1; } fsync(fd); close(fd); memset(buf, 0, readsize + 1); } printf("---------------------------------------------------------\nrand size : %d\nsuccess: %d\nfailed: %d\n---------------------------------------------------------\n", readsize, override_count, exec_count); override_count = 0; exec_count = 0; readsize = readsize * 2; free(buf); } } override_count = 0; partial_override_count = 0; exec_count = 0; readsize = READ_SIZE; if(EXEC_2) { //while (readsize <= MAX_READ) //while (iter <= MAX_ITER) //{ char * buf = malloc(readsize + 1); //char * buf = mmap(NULL, 4095, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); //printf("buffer on user side = %lu\n", (unsigned long) buf); __u32 key = 0; if (bpf_map_update_elem(map_fd[0], &key, &buf, BPF_ANY) != 0) { fprintf(stderr, "map_update failed: %s\n", strerror(errno)); return 1; } int fd = open("randfile", O_RDONLY); if (fd == -1) { printf("error open file 2\n"); exit(EXIT_FAILURE); } for (int i = 0; i < iter; i++) { //int posix_fadvise(int fd, off_t offset, off_t len, int advice); //posix_fadvise(fd, 0, 4096, POSIX_FADV_DONTNEED); //ssize_t readahead(int fd, off64_t offset, size_t count); readahead(fd, 0, 524288000); memset(buf, 0, readsize + 1); ret1 = clock_gettime(clk_id1, &tp1); ssize_t readbytes = read(fd, buf, readsize); ret2 = clock_gettime(clk_id2, &tp2); printf("time: %ld\n", tp2.tv_nsec- tp1.tv_nsec); if ( strncmp(buf, expected, 2) == 0) { /*if(strcmp(buf + 2, "a") == 0) { partial_override_count += 1; }*/ //successful complete return override override_count = override_count + 1; //printf("read %s\n", buf); } else { exec_count = exec_count + 1; //printf("fail %d\n", i); } //close(fd); //fsync(fd); memset(buf, 0, readsize + 1); } close(fd); //printf("---------------------------------------------------------\nknown size : %d\nsuccess: %d\npartial: %d\nfail: %d\n---------------------------------------------------------\n", readsize, override_count, partial_override_count, exec_count); printf("%d, %d, %d, %d\n", iter, override_count, exec_count, iter*readsize); override_count = 0; partial_override_count = 0; exec_count = 0; //readsize = readsize * 2; //iter = iter + 250; //sleep(5); free(buf); //} } //printf("execution override success: %d\nExecution override failed: %d\n", override_count, exec_count); unsigned long count; bpf_map_lookup_elem(map_fd[1], &key, &count); //printf("kprobe executed %lu times\n", count); return 0; }
2
2