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-18T20:13:09.095273+00:00
2023-08-13T07:00:15
ab49f79c973e5b035d1084fd0330c8363e8a2830
{ "blob_id": "ab49f79c973e5b035d1084fd0330c8363e8a2830", "branch_name": "refs/heads/master", "committer_date": "2023-08-13T07:00:15", "content_id": "5c692a83024b7a7add135a97b3d54bf9802ae441", "detected_licenses": [ "MIT" ], "directory_id": "2266eb133fc3121daf0aa7f4560626b46b94afe0", "extension": "c", "filename": "tree_hole.c", "fork_events_count": 49, "gha_created_at": "2017-11-28T03:05:14", "gha_event_created_at": "2023-02-01T03:42:14", "gha_language": "C", "gha_license_id": "MIT", "github_id": 112278568, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1292, "license": "MIT", "license_type": "permissive", "path": "/d/wanjiegu/tree_hole.c", "provenance": "stackv2-0049.json.gz:176782", "repo_name": "oiuv/mud", "revision_date": "2023-08-13T07:00:15", "revision_id": "e9ff076724472256b9b4bd88c148d6bf71dc3c02", "snapshot_id": "6fbabebc7b784279fdfae06d164f5aecaa44ad90", "src_encoding": "UTF-8", "star_events_count": 99, "url": "https://raw.githubusercontent.com/oiuv/mud/e9ff076724472256b9b4bd88c148d6bf71dc3c02/d/wanjiegu/tree_hole.c", "visit_date": "2023-08-18T20:18:37.848801" }
stackv2
// Room: /t/wanjiegu/tree_hole.c inherit ROOM; void create() { set("short", "树洞"); set("long", @LONG 树洞内非常狭窄,光线黑暗,地上铺满是枯草。洞的墙上有一 只大蜘蛛正在编织一个蜘蛛网。 LONG ); set("exits", ([ /* sizeof() == 1 */ "out" : __DIR__"entrance", ])); set("no_clean_up", 0); set("item_desc", ([ /* sizeof() == 2 */ "枯草":"一堆枯草,里面有一个大铁环(ring)。\n", "grass":"一堆枯草,里面有一个大铁环(ring)。\n", ])); setup(); } void init() { add_action("do_pull","pull"); } int do_pull(string arg) { if( !arg ) return 0; if( arg != "大铁环" && arg != "ring" ) return 0; if( arg == "大铁环" || arg == "ring" ) { message_vision("$N用劲拉起大铁环,拎起一块木板,下面露出一洞。\n", this_player() ); set("exits/enter", __DIR__"tunnel1"); call_out("close_passage", 10); return 1; } } void close_passage() { // object room; if( !query("exits/enter") ) return; delete("exits/enter"); message("vision","木板晃了晃,将下面的洞口盖住了。\n", this_object() ); }
2.203125
2
2024-11-18T20:13:09.246554+00:00
2019-04-10T10:55:21
f07d513155de58c5330d7e76c80248a81e9367cf
{ "blob_id": "f07d513155de58c5330d7e76c80248a81e9367cf", "branch_name": "refs/heads/master", "committer_date": "2019-04-10T10:55:21", "content_id": "62b1c80da2aea09072083f3c33f5521280cc9b5a", "detected_licenses": [ "Apache-2.0" ], "directory_id": "86cf2ccaa0625027335da0214a28f4d01dcbd932", "extension": "c", "filename": "UInt32.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": 1531, "license": "Apache-2.0", "license_type": "permissive", "path": "/IL2C.Runtime/src/System/UInt32.c", "provenance": "stackv2-0049.json.gz:176911", "repo_name": "FrostyFeng/IL2C", "revision_date": "2019-04-10T10:55:21", "revision_id": "d3a3c3d27f8e775b9dcaa8dcad0576ff2887d0ef", "snapshot_id": "f74728682c68e505879b41dbd9091ccb5f83bc72", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/FrostyFeng/IL2C/d3a3c3d27f8e775b9dcaa8dcad0576ff2887d0ef/IL2C.Runtime/src/System/UInt32.c", "visit_date": "2020-05-18T00:03:00.324160" }
stackv2
#include "il2c_private.h" ///////////////////////////////////////////////////////////// // System.UInt32 System_String* System_UInt32_ToString(uint32_t* this__) { il2c_assert(this__ != NULL); wchar_t buffer[14]; il2c_u32tow(*this__, buffer, 10); return il2c_new_string(buffer); } int32_t System_UInt32_GetHashCode(uint32_t* this__) { il2c_assert(this__ != NULL); return (int32_t)*this__; } bool System_UInt32_Equals(uint32_t* this__, uint32_t obj) { il2c_assert(this__ != NULL); return *this__ == obj; } bool System_UInt32_Equals_1(uint32_t* this__, System_Object* obj) { il2c_assert(this__ != NULL); if (obj == NULL) { return false; } uint32_t rhs = *il2c_unbox(obj, System_UInt32); return *this__ == rhs; } bool System_UInt32_TryParse(System_String* s, uint32_t* result) { // TODO: NullReferenceException il2c_assert(s != NULL); il2c_assert(result != NULL); il2c_assert(s->string_body__ != NULL); wchar_t* endPtr; *result = il2c_wtou32(s->string_body__, &endPtr, 10); return ((s->string_body__ != endPtr) && (il2c_errno == 0)) ? true : false; } ///////////////////////////////////////////////// // VTable and runtime type info declarations IL2C_DECLARE_TRAMPOLINE_VFUNC_FOR_VALUE_TYPE(System_UInt32); IL2C_DECLARE_TRAMPOLINE_VTABLE_FOR_VALUE_TYPE(System_UInt32); IL2C_RUNTIME_TYPE_BEGIN(System_UInt32, "System.UInt32", IL2C_TYPE_UNSIGNED_INTEGER, sizeof(System_UInt32), System_ValueType, 0, 0) IL2C_RUNTIME_TYPE_END();
2.28125
2
2024-11-18T20:13:09.482022+00:00
2021-12-31T09:23:38
e2b3203967ce39404cb2e56443600efcbf600fc6
{ "blob_id": "e2b3203967ce39404cb2e56443600efcbf600fc6", "branch_name": "refs/heads/master", "committer_date": "2021-12-31T09:23:38", "content_id": "19433d273d9a9bdb7b2db2c422acad432a0da01d", "detected_licenses": [ "MIT" ], "directory_id": "af9eabdb2ac240f9f2a2f3e92e6bc9044069362e", "extension": "c", "filename": "k_task.c", "fork_events_count": 609, "gha_created_at": "2019-10-19T13:25:30", "gha_event_created_at": "2019-12-15T10:41:08", "gha_language": "Verilog", "gha_license_id": "MIT", "github_id": 216210370, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 25913, "license": "MIT", "license_type": "permissive", "path": "/sdk/csi_kernel/rhino/core/k_task.c", "provenance": "stackv2-0049.json.gz:177168", "repo_name": "T-head-Semi/wujian100_open", "revision_date": "2021-12-31T09:23:38", "revision_id": "83e297583bb3454b688f9f27d6bc20ff3276ad32", "snapshot_id": "9926f118867a08283004759d09af6631db2e92cf", "src_encoding": "UTF-8", "star_events_count": 1846, "url": "https://raw.githubusercontent.com/T-head-Semi/wujian100_open/83e297583bb3454b688f9f27d6bc20ff3276ad32/sdk/csi_kernel/rhino/core/k_task.c", "visit_date": "2022-07-27T05:13:57.608880" }
stackv2
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <k_api.h> static kstat_t task_create(ktask_t *task, const name_t *name, void *arg, uint8_t prio, tick_t ticks, cpu_stack_t *stack_buf, size_t stack_size, task_entry_t entry, uint8_t autorun, uint8_t mm_alloc_flag, uint8_t cpu_num, uint8_t cpu_binded) { CPSR_ALLOC(); cpu_stack_t *tmp; NULL_PARA_CHK(task); NULL_PARA_CHK(name); NULL_PARA_CHK(entry); NULL_PARA_CHK(stack_buf); if (stack_size == 0u) { return RHINO_TASK_INV_STACK_SIZE; } if (prio >= RHINO_CONFIG_PRI_MAX) { return RHINO_BEYOND_MAX_PRI; } RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); /* idle task is only allowed to create once */ if (prio == RHINO_IDLE_PRI) { if (g_idle_task_spawned[cpu_num] > 0u) { RHINO_CRITICAL_EXIT(); return RHINO_IDLE_TASK_EXIST; } g_idle_task_spawned[cpu_num] = 1u; } RHINO_CRITICAL_EXIT(); memset(task, 0, sizeof(ktask_t)); #if (RHINO_CONFIG_SCHED_RR > 0) if (ticks > 0u) { task->time_total = ticks; } else { task->time_total = RHINO_CONFIG_TIME_SLICE_DEFAULT; } task->time_slice = task->time_total; task->sched_policy = KSCHED_RR; #endif if (autorun > 0u) { task->task_state = K_RDY; } else { task->task_state = K_SUSPENDED; task->suspend_count = 1u; } /* init all the stack element to 0 */ task->task_stack_base = stack_buf; tmp = stack_buf; memset(tmp, 0, stack_size * sizeof(cpu_stack_t)); task->task_name = name; task->prio = prio; task->b_prio = prio; task->stack_size = stack_size; task->mm_alloc_flag = mm_alloc_flag; task->cpu_num = cpu_num; cpu_binded = cpu_binded; #if (RHINO_CONFIG_CPU_NUM > 1) task->cpu_binded = cpu_binded; #endif #if (RHINO_CONFIG_TASK_STACK_OVF_CHECK > 0) #if (RHINO_CONFIG_CPU_STACK_DOWN > 0) tmp = task->task_stack_base; *tmp = RHINO_TASK_STACK_OVF_MAGIC; #else tmp = (cpu_stack_t *)(task->task_stack_base) + task->stack_size - 1u; *tmp = RHINO_TASK_STACK_OVF_MAGIC; #endif #endif task->task_stack = cpu_task_stack_init(stack_buf, stack_size, arg, entry); #if (RHINO_CONFIG_USER_HOOK > 0) krhino_task_create_hook(task); #endif TRACE_TASK_CREATE(task); RHINO_CRITICAL_ENTER(); #if (RHINO_CONFIG_SYSTEM_STATS > 0) klist_insert(&(g_kobj_list.task_head), &task->task_stats_item); #endif if (autorun > 0u) { ready_list_add_tail(&g_ready_queue, task); /* if system is not start,not call core_sched */ if (g_sys_stat == RHINO_RUNNING) { RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } } RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } kstat_t krhino_task_create(ktask_t *task, const name_t *name, void *arg, uint8_t prio, tick_t ticks, cpu_stack_t *stack_buf, size_t stack_size, task_entry_t entry, uint8_t autorun) { return task_create(task, name, arg, prio, ticks, stack_buf, stack_size, entry, autorun, K_OBJ_STATIC_ALLOC, 0, 0); } #if (RHINO_CONFIG_CPU_NUM > 1) kstat_t krhino_task_cpu_create(ktask_t *task, const name_t *name, void *arg, uint8_t prio, tick_t ticks, cpu_stack_t *stack_buf, size_t stack_size, task_entry_t entry, uint8_t cpu_num, uint8_t autorun) { return task_create(task, name, arg, prio, ticks, stack_buf, stack_size, entry, autorun, K_OBJ_STATIC_ALLOC, cpu_num, 1); } kstat_t krhino_task_cpu_bind(ktask_t *task, uint8_t cpu_num) { CPSR_ALLOC(); ktask_t *task_cur; RHINO_CRITICAL_ENTER(); task_cur = g_active_task[cpu_cur_get()]; if (task != task_cur) { RHINO_CRITICAL_EXIT(); return RHINO_INV_PARAM; } task->cpu_num = cpu_num; task->cpu_binded = 1u; RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } kstat_t krhino_task_cpu_unbind(ktask_t *task) { CPSR_ALLOC(); ktask_t *task_cur; RHINO_CRITICAL_ENTER(); task_cur = g_active_task[cpu_cur_get()]; if (task != task_cur) { RHINO_CRITICAL_EXIT(); return RHINO_INV_PARAM; } task->cpu_binded = 0u; RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } #endif #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) kstat_t task_dyn_create(ktask_t **task, const name_t *name, void *arg, uint8_t pri, tick_t ticks, size_t stack, task_entry_t entry, uint8_t cpu_num, uint8_t cpu_binded, uint8_t autorun) { kstat_t ret; cpu_stack_t *task_stack; ktask_t *task_obj; NULL_PARA_CHK(task); if (stack == 0) { return RHINO_INV_PARAM; } task_stack = krhino_mm_alloc(stack * sizeof(cpu_stack_t) + sizeof(ktask_t), __builtin_return_address(0)); if (task_stack == NULL) { return RHINO_NO_MEM; } task_obj = (ktask_t*)((uint8_t*)task_stack + stack * sizeof(cpu_stack_t)); // task_obj = krhino_mm_alloc(sizeof(ktask_t) + stack * sizeof(cpu_stack_t), __builtin_return_address(0)); // if (task_obj == NULL) { // // krhino_mm_free(task_stack); // return RHINO_NO_MEM; // } *task = task_obj; ret = task_create(task_obj, name, arg, pri, ticks, task_stack, stack, entry, autorun, K_OBJ_DYN_ALLOC, cpu_num, cpu_binded); if ((ret != RHINO_SUCCESS) && (ret != RHINO_STOPPED)) { krhino_mm_free(task_stack); // krhino_mm_free(task_obj); *task = NULL; return ret; } return ret; } kstat_t krhino_task_dyn_create(ktask_t **task, const name_t *name, void *arg, uint8_t pri, tick_t ticks, size_t stack, task_entry_t entry, uint8_t autorun) { return task_dyn_create(task, name, arg, pri, ticks, stack, entry, 0, 0, autorun); } #if (RHINO_CONFIG_CPU_NUM > 1) kstat_t krhino_task_cpu_dyn_create(ktask_t **task, const name_t *name, void *arg, uint8_t pri, tick_t ticks, size_t stack, task_entry_t entry, uint8_t cpu_num, uint8_t autorun) { return task_dyn_create(task, name, arg, pri, ticks, stack, entry, cpu_num, 1, autorun); } #endif #endif kstat_t krhino_task_sleep(tick_t ticks) { CPSR_ALLOC(); uint8_t cur_cpu_num; kstat_t ret; if (ticks == 0u) { return RHINO_INV_PARAM; } RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); cur_cpu_num = cpu_cur_get(); /* system is locked so task can not be blocked just return immediately */ if (g_sched_lock[cur_cpu_num] > 0u) { RHINO_CRITICAL_EXIT(); return RHINO_SCHED_DISABLE; } g_active_task[cur_cpu_num]->task_state = K_SLEEP; tick_list_insert(g_active_task[cur_cpu_num], ticks); ready_list_rm(&g_ready_queue, g_active_task[cur_cpu_num]); TRACE_TASK_SLEEP(g_active_task[cur_cpu_num], ticks); RHINO_CRITICAL_EXIT_SCHED(); RHINO_CPU_INTRPT_DISABLE(); /* is task timeout normally after sleep */ ret = pend_state_end_proc(g_active_task[cpu_cur_get()]); RHINO_CPU_INTRPT_ENABLE(); return ret; } kstat_t krhino_task_yield(void) { CPSR_ALLOC(); /* make current task to the end of ready list */ RHINO_CRITICAL_ENTER(); ready_list_head_to_tail(&g_ready_queue, g_active_task[cpu_cur_get()]); RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } ktask_t *krhino_cur_task_get(void) { CPSR_ALLOC(); ktask_t *task; RHINO_CRITICAL_ENTER(); task = g_active_task[cpu_cur_get()]; RHINO_CRITICAL_EXIT(); return task; } kstat_t task_suspend(ktask_t *task) { CPSR_ALLOC(); uint8_t cur_cpu_num; RHINO_CRITICAL_ENTER(); cur_cpu_num = cpu_cur_get(); #if (RHINO_CONFIG_CPU_NUM > 1) if (task->cpu_num != cur_cpu_num) { if (task->cur_exc == 1) { RHINO_CRITICAL_EXIT(); return RHINO_TRY_AGAIN; } } #endif if (task == g_active_task[cur_cpu_num]) { if (g_sched_lock[cur_cpu_num] > 0u) { RHINO_CRITICAL_EXIT(); return RHINO_SCHED_DISABLE; } } switch (task->task_state) { case K_RDY: task->suspend_count = 1u; task->task_state = K_SUSPENDED; ready_list_rm(&g_ready_queue, task); break; case K_SLEEP: task->suspend_count = 1u; task->task_state = K_SLEEP_SUSPENDED; break; case K_PEND: task->suspend_count = 1u; task->task_state = K_PEND_SUSPENDED; break; case K_SUSPENDED: case K_SLEEP_SUSPENDED: case K_PEND_SUSPENDED: if (task->suspend_count == (suspend_nested_t)-1) { RHINO_CRITICAL_EXIT(); return RHINO_SUSPENDED_COUNT_OVF; } task->suspend_count++; break; case K_SEED: default: RHINO_CRITICAL_EXIT(); return RHINO_INV_TASK_STATE; } TRACE_TASK_SUSPEND(g_active_task[cur_cpu_num], task); RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } kstat_t krhino_task_suspend(ktask_t *task) { if (task == NULL) { return RHINO_NULL_PTR; } if (task->prio == RHINO_IDLE_PRI) { return RHINO_TASK_SUSPEND_NOT_ALLOWED; } return task_suspend(task); } kstat_t task_resume(ktask_t *task) { CPSR_ALLOC(); RHINO_CRITICAL_ENTER(); switch (task->task_state) { case K_RDY: case K_SLEEP: case K_PEND: RHINO_CRITICAL_EXIT(); return RHINO_TASK_NOT_SUSPENDED; case K_SUSPENDED: task->suspend_count--; if (task->suspend_count == 0u) { /* Make task ready */ task->task_state = K_RDY; ready_list_add(&g_ready_queue, task); } break; case K_SLEEP_SUSPENDED: task->suspend_count--; if (task->suspend_count == 0u) { task->task_state = K_SLEEP; } break; case K_PEND_SUSPENDED: task->suspend_count--; if (task->suspend_count == 0u) { task->task_state = K_PEND; } break; case K_SEED: default: RHINO_CRITICAL_EXIT(); return RHINO_INV_TASK_STATE; } TRACE_TASK_RESUME(g_active_task[cpu_cur_get()], task); RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } kstat_t krhino_task_resume(ktask_t *task) { NULL_PARA_CHK(task); return task_resume(task); } kstat_t krhino_task_stack_min_free(ktask_t *task, size_t *free) { cpu_stack_t *task_stack; size_t free_stk = 0; NULL_PARA_CHK(task); NULL_PARA_CHK(free); if (task->task_state == K_DELETED) { return RHINO_INV_TASK_STATE; } #if (RHINO_CONFIG_CPU_STACK_DOWN > 0) task_stack = task->task_stack_base + 1u; while (*task_stack++ == 0u) { free_stk++; } #else task_stack = (cpu_stack_t *)(task->task_stack_base) + task->stack_size - 2u; while (*task_stack-- == 0u) { free_stk++; } #endif *free = free_stk; return RHINO_SUCCESS; } #if (RHINO_CONFIG_TASK_STACK_CUR_CHECK > 0) kstat_t krhino_task_stack_cur_free(ktask_t *task, size_t *free) { CPSR_ALLOC(); size_t sp = 0; RHINO_CRITICAL_ENTER(); if (task == NULL || task == g_active_task[cpu_cur_get()]) { task = g_active_task[cpu_cur_get()]; sp = soc_get_cur_sp(); } else { sp = (size_t)task->task_stack; } if (sp == 0) { RHINO_CRITICAL_EXIT(); k_err_proc(RHINO_SYS_SP_ERR); return RHINO_SYS_SP_ERR; } if ((size_t)(task->task_stack_base + task->stack_size) < sp) { RHINO_CRITICAL_EXIT(); k_err_proc(RHINO_TASK_STACK_OVF); return RHINO_TASK_STACK_OVF; } *free = ((size_t)(task->task_stack_base + task->stack_size) - sp) / sizeof( cpu_stack_t); RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } #endif #if (RHINO_CONFIG_TASK_PRI_CHG > 0) kstat_t task_pri_change(ktask_t *task, uint8_t new_pri) { uint8_t old_pri; kmutex_t *mutex_tmp; ktask_t *mutex_task; do { if (task->prio != new_pri) { switch (task->task_state) { case K_RDY: ready_list_rm(&g_ready_queue, task); task->prio = new_pri; if (task == g_active_task[cpu_cur_get()]) { ready_list_add_head(&g_ready_queue, task); } else { ready_list_add_tail(&g_ready_queue, task); } task = NULL; break; case K_SLEEP: case K_SUSPENDED: case K_SLEEP_SUSPENDED: /* set new task prio */ task->prio = new_pri; task = NULL; break; case K_PEND: case K_PEND_SUSPENDED: old_pri = task->prio; task->prio = new_pri; pend_list_reorder(task); if (task->blk_obj->obj_type == RHINO_MUTEX_OBJ_TYPE) { mutex_tmp = (kmutex_t *)(task->blk_obj); mutex_task = mutex_tmp->mutex_task; if (mutex_task->prio > task->prio) { /* since the highest prio of the lock wait task became higher, raise the lock get task prio higher */ task = mutex_task; } else if (mutex_task->prio == old_pri) { /* find suitable tcb prio */ new_pri = mutex_pri_look(mutex_task, 0); if (new_pri != mutex_task->prio) { /* Change prio of lock get task */ task = mutex_task; } else { task = NULL; } } else { task = NULL; } } else { task = NULL; } break; default: k_err_proc(RHINO_INV_TASK_STATE); return RHINO_INV_TASK_STATE; } } else { task = NULL; } } while (task != NULL); return RHINO_SUCCESS; } kstat_t krhino_task_pri_change(ktask_t *task, uint8_t pri, uint8_t *old_pri) { CPSR_ALLOC(); uint8_t pri_limit; kstat_t error; NULL_PARA_CHK(task); NULL_PARA_CHK(old_pri); /* idle task is not allowed to change prio */ if (task->prio >= RHINO_IDLE_PRI) { return RHINO_PRI_CHG_NOT_ALLOWED; } /* not allowed change to idle prio */ if (pri >= RHINO_IDLE_PRI) { return RHINO_PRI_CHG_NOT_ALLOWED; } /* deleted task is not allowed to change prio */ if (task->task_state == K_DELETED) { return RHINO_INV_TASK_STATE; } RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); /* limit the prio change by mutex at task prio change */ pri_limit = mutex_pri_limit(task, pri); task->b_prio = pri; /* new pripority may change here */ pri = pri_limit; *old_pri = task->prio; error = task_pri_change(task, pri); if (error != RHINO_SUCCESS) { RHINO_CRITICAL_EXIT(); return error; } TRACE_TASK_PRI_CHANGE(g_active_task[cpu_cur_get()], task, pri); RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } #endif #if (RHINO_CONFIG_TASK_WAIT_ABORT > 0) kstat_t krhino_task_wait_abort(ktask_t *task) { CPSR_ALLOC(); NULL_PARA_CHK(task); RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); switch (task->task_state) { case K_RDY: break; case K_SUSPENDED: /* change to ready state */ task->task_state = K_RDY; ready_list_add(&g_ready_queue, task); break; case K_SLEEP: case K_SLEEP_SUSPENDED: /* change to ready state */ tick_list_rm(task); ready_list_add(&g_ready_queue, task); task->task_state = K_RDY; task->blk_state = BLK_ABORT; break; case K_PEND_SUSPENDED: case K_PEND: /* remove task on the tick list because task is woken up */ tick_list_rm(task); /* remove task on the block list because task is woken up */ klist_rm(&task->task_list); /* add to the ready list again */ ready_list_add(&g_ready_queue, task); task->task_state = K_RDY; task->blk_state = BLK_ABORT; mutex_task_pri_reset(task); task->blk_obj = NULL; break; default: RHINO_CRITICAL_EXIT(); return RHINO_INV_TASK_STATE; } #if (RHINO_CONFIG_USER_HOOK > 0) krhino_task_abort_hook(task); #endif TRACE_TASK_WAIT_ABORT(g_active_task[cpu_cur_get()], task); RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } #endif #if (RHINO_CONFIG_TASK_DEL > 0) static void task_mutex_free(ktask_t *task) { kmutex_t *mutex; kmutex_t *next_mutex; ktask_t *next_task; klist_t *blk_list_head; next_mutex = task->mutex_list; while ((mutex = next_mutex) != NULL) { next_mutex = mutex->mutex_list; blk_list_head = &mutex->blk_obj.blk_list; if (!is_klist_empty(blk_list_head)) { next_task = krhino_list_entry(blk_list_head->next, ktask_t, task_list); /* wakeup wait task */ pend_task_wakeup(next_task); /* change mutex get task */ mutex->mutex_task = next_task; mutex->mutex_list = next_task->mutex_list; next_task->mutex_list = mutex; } else { /* no wait task */ mutex->mutex_task = NULL; } } } kstat_t krhino_task_del(ktask_t *task) { CPSR_ALLOC(); uint8_t cur_cpu_num; #if (RHINO_CONFIG_USER_HOOK > 0) res_free_t *res_free; #endif RHINO_CRITICAL_ENTER(); cur_cpu_num = cpu_cur_get(); INTRPT_NESTED_LEVEL_CHK(); if (task == NULL) { task = g_active_task[cur_cpu_num]; } if (task->prio == RHINO_IDLE_PRI) { return RHINO_TASK_DEL_NOT_ALLOWED; } if (task->mm_alloc_flag != K_OBJ_STATIC_ALLOC) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_DEL_ERR; } #if (RHINO_CONFIG_CPU_NUM > 1) if (task->cpu_num != cur_cpu_num) { if (task->cur_exc == 1) { RHINO_CRITICAL_EXIT(); return RHINO_TRY_AGAIN; } } #endif if (task == g_active_task[cpu_cur_get()]) { if (g_sched_lock[cpu_cur_get()] > 0u) { RHINO_CRITICAL_EXIT(); return RHINO_SCHED_DISABLE; } } /* free all the mutex which task hold */ task_mutex_free(task); switch (task->task_state) { case K_RDY: ready_list_rm(&g_ready_queue, task); task->task_state = K_DELETED; break; case K_SUSPENDED: task->task_state = K_DELETED; break; case K_SLEEP: case K_SLEEP_SUSPENDED: tick_list_rm(task); task->task_state = K_DELETED; break; case K_PEND: case K_PEND_SUSPENDED: tick_list_rm(task); klist_rm(&task->task_list); task->task_state = K_DELETED; mutex_task_pri_reset(task); break; default: RHINO_CRITICAL_EXIT(); return RHINO_INV_TASK_STATE; } #if (RHINO_CONFIG_SYSTEM_STATS > 0) klist_rm(&task->task_stats_item); #endif TRACE_TASK_DEL(g_active_task[cur_cpu_num], task); #if (RHINO_CONFIG_USER_HOOK > 0) #if (RHINO_CONFIG_CPU_STACK_DOWN > 0) res_free = (res_free_t *)(task->task_stack_base + 1u); #else res_free = (res_free_t *)(task->task_stack_base + task->stack_size - (sizeof(res_free_t) / sizeof(cpu_stack_t)) - 1u); #endif res_free->cnt = 0; krhino_task_del_hook(task, res_free); #endif RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) kstat_t krhino_task_dyn_del(ktask_t *task) { CPSR_ALLOC(); kstat_t ret; uint8_t cur_cpu_num; res_free_t *res_free; RHINO_CRITICAL_ENTER(); cur_cpu_num = cpu_cur_get(); INTRPT_NESTED_LEVEL_CHK(); if (task == NULL) { task = g_active_task[cur_cpu_num]; } if (task->prio == RHINO_IDLE_PRI) { RHINO_CRITICAL_EXIT(); return RHINO_TASK_DEL_NOT_ALLOWED; } if (task->mm_alloc_flag != K_OBJ_DYN_ALLOC) { RHINO_CRITICAL_EXIT(); return RHINO_KOBJ_DEL_ERR; } #if (RHINO_CONFIG_CPU_NUM > 1) if (task->cpu_num != cur_cpu_num) { if (task->cur_exc == 1) { RHINO_CRITICAL_EXIT(); return RHINO_TRY_AGAIN; } } #endif if (task == g_active_task[cpu_cur_get()]) { if (g_sched_lock[cpu_cur_get()] > 0u) { RHINO_CRITICAL_EXIT(); return RHINO_SCHED_DISABLE; } } if (task->task_state == K_DELETED) { RHINO_CRITICAL_EXIT(); return RHINO_INV_TASK_STATE; } #if (RHINO_CONFIG_CPU_STACK_DOWN > 0) res_free = (res_free_t *)(task->task_stack_base + 1u); #else res_free = (res_free_t *)(task->task_stack_base + task->stack_size - (sizeof(res_free_t) / sizeof(cpu_stack_t)) - 1u); #endif g_sched_lock[cpu_cur_get()]++; klist_insert(&g_res_list, &res_free->res_list); res_free->res[0] = task->task_stack_base; // res_free->res[0] = task; res_free->cnt = 1; ret = krhino_sem_give(&g_res_sem); g_sched_lock[cpu_cur_get()]--; if (ret != RHINO_SUCCESS) { RHINO_CRITICAL_EXIT(); k_err_proc(RHINO_SYS_SP_ERR); return ret; } /* free all the mutex which task hold */ task_mutex_free(task); switch (task->task_state) { case K_RDY: ready_list_rm(&g_ready_queue, task); task->task_state = K_DELETED; break; case K_SUSPENDED: task->task_state = K_DELETED; break; case K_SLEEP: case K_SLEEP_SUSPENDED: tick_list_rm(task); task->task_state = K_DELETED; break; case K_PEND: case K_PEND_SUSPENDED: tick_list_rm(task); klist_rm(&task->task_list); task->task_state = K_DELETED; mutex_task_pri_reset(task); break; case K_SEED: default: break; } #if (RHINO_CONFIG_SYSTEM_STATS > 0) klist_rm(&task->task_stats_item); #endif TRACE_TASK_DEL(g_active_task[cpu_cur_get()], task); #if (RHINO_CONFIG_USER_HOOK > 0) krhino_task_del_hook(task, res_free); #endif RHINO_CRITICAL_EXIT_SCHED(); return RHINO_SUCCESS; } #endif #endif #if (RHINO_CONFIG_SCHED_RR > 0) kstat_t krhino_task_time_slice_set(ktask_t *task, size_t slice) { CPSR_ALLOC(); NULL_PARA_CHK(task); RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); if (slice > 0u) { /* assign the new time slice */ task->time_total = slice; } else { /* assign the default time slice */ task->time_total = RHINO_CONFIG_TIME_SLICE_DEFAULT; } task->time_slice = task->time_total; RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } kstat_t krhino_sched_policy_set(ktask_t *task, uint8_t policy) { CPSR_ALLOC(); NULL_PARA_CHK(task); if ((policy != KSCHED_FIFO) && (policy != KSCHED_RR)) { return RHINO_INV_SCHED_WAY; } RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); task->sched_policy = policy; RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } kstat_t krhino_sched_policy_get(ktask_t *task, uint8_t *policy) { CPSR_ALLOC(); NULL_PARA_CHK(task); NULL_PARA_CHK(policy); RHINO_CRITICAL_ENTER(); INTRPT_NESTED_LEVEL_CHK(); *policy = task->sched_policy; RHINO_CRITICAL_EXIT(); return RHINO_SUCCESS; } #endif #if (RHINO_CONFIG_TASK_INFO > 0) kstat_t krhino_task_info_set(ktask_t *task, size_t idx, void *info) { CPSR_ALLOC(); NULL_PARA_CHK(task); if (idx >= RHINO_CONFIG_TASK_INFO_NUM) { return RHINO_INV_PARAM; } RHINO_CPU_INTRPT_DISABLE(); task->user_info[idx] = info; RHINO_CPU_INTRPT_ENABLE(); return RHINO_SUCCESS; } kstat_t krhino_task_info_get(ktask_t *task, size_t idx, void **info) { NULL_PARA_CHK(task); NULL_PARA_CHK(info); if (idx >= RHINO_CONFIG_TASK_INFO_NUM) { return RHINO_INV_PARAM; } *info = task->user_info[idx]; return RHINO_SUCCESS; } #endif void krhino_task_deathbed(void) { #if (RHINO_CONFIG_TASK_DEL > 0) ktask_t *task; task = krhino_cur_task_get(); if (task->mm_alloc_flag == K_OBJ_DYN_ALLOC) { /* del my self*/ #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) krhino_task_dyn_del(NULL); #endif } else { krhino_task_del(NULL); } #else while (1) { krhino_task_sleep(RHINO_CONFIG_TICKS_PER_SECOND * 10); } #endif }
2.046875
2
2024-11-18T20:13:46.821423+00:00
2015-05-15T08:06:17
1a9a15d984e12a80cc93a15a3a7cf7b7d1f9f212
{ "blob_id": "1a9a15d984e12a80cc93a15a3a7cf7b7d1f9f212", "branch_name": "refs/heads/master", "committer_date": "2015-05-15T08:06:17", "content_id": "bef6b35d8738b63e9995292383b638be3ff16b31", "detected_licenses": [ "NCSA" ], "directory_id": "0703984183ca342d0277787ae4e26ec137fd48ca", "extension": "c", "filename": "test_strcmp.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": 332, "license": "NCSA", "license_type": "permissive", "path": "/klee/examples/string/test_strcmp.c", "provenance": "stackv2-0049.json.gz:177812", "repo_name": "fanyao/kleestr", "revision_date": "2015-05-15T08:06:17", "revision_id": "8be333655856f0e8132455acb150228f0ce2b482", "snapshot_id": "1bd37980003ffd2e76cca54764b1a24fdb9e9198", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fanyao/kleestr/8be333655856f0e8132455acb150228f0ce2b482/klee/examples/string/test_strcmp.c", "visit_date": "2021-01-15T20:13:24.467420" }
stackv2
/* * test_concat.c * * Created on: Apr 22, 2015 * Author: zehranaz */ #include <klee/klee.h> #include <string.h> #include <stdlib.h> int main () { char *left; char *right; left = malloc(3); b = malloc(5); klee_make_symbolic(left, 3, "left"); klee_make_symbolic(b, 5, "b"); int c = strcmp(left, b); return 0; }
2.3125
2
2024-11-18T20:13:46.926444+00:00
2018-12-31T09:04:22
1546f562175f45b50e0ed4bc24258e769e67ca11
{ "blob_id": "1546f562175f45b50e0ed4bc24258e769e67ca11", "branch_name": "refs/heads/master", "committer_date": "2018-12-31T09:04:22", "content_id": "411f685eef9a0382ffa87e961de9528ddcd0585b", "detected_licenses": [ "MIT" ], "directory_id": "7bbdaa4582e1bb4cbe87de9c805ef62d6de4e4a6", "extension": "c", "filename": "client.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 159173807, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 779, "license": "MIT", "license_type": "permissive", "path": "/1/client.c", "provenance": "stackv2-0049.json.gz:177940", "repo_name": "hwfhc/server", "revision_date": "2018-12-31T09:04:22", "revision_id": "9880674287c04ea27e6c49350a7abc39dc7e1d75", "snapshot_id": "60435650c8f19520424976b4f1009904ffe596b5", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/hwfhc/server/9880674287c04ea27e6c49350a7abc39dc7e1d75/1/client.c", "visit_date": "2020-04-08T08:18:11.827124" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <arpa/inet.h> int main(int argc, char *argv[]) { int fd; struct sockaddr_in serv_addr; char buf[16]; fd = socket(AF_INET, SOCK_STREAM, 0); if(fd < 0){ printf("socket error\n"); return -1; } bzero(&serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(8080); inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr); connect(fd, (struct sockaddr*)&serv_addr, sizeof(struct sockaddr)); read(fd,buf,16); write(1,buf,16); close(fd); return 0; }
2.71875
3
2024-11-18T20:13:47.125075+00:00
2019-07-03T01:45:08
1615ed529d7947edef0ff76c509efbee1b4e00f1
{ "blob_id": "1615ed529d7947edef0ff76c509efbee1b4e00f1", "branch_name": "refs/heads/master", "committer_date": "2019-07-03T01:45:08", "content_id": "e8a11ce7aff679c079187ef23e4e62a70f611d20", "detected_licenses": [ "0BSD" ], "directory_id": "920d047648af2b743b3c6e7cdce3b733a9e559fb", "extension": "c", "filename": "sh.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 195602853, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13938, "license": "0BSD", "license_type": "permissive", "path": "/toys/pending/sh.c", "provenance": "stackv2-0049.json.gz:178196", "repo_name": "michalgr/platform_external_toybox", "revision_date": "2019-07-03T01:45:08", "revision_id": "be2958ac07e917ecb7c74d2c76d4fb7324af5da4", "snapshot_id": "73dbda79b370d645fdd56b36c8204c3178370608", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/michalgr/platform_external_toybox/be2958ac07e917ecb7c74d2c76d4fb7324af5da4/toys/pending/sh.c", "visit_date": "2020-06-16T14:07:15.984803" }
stackv2
/* sh.c - toybox shell * * Copyright 2006 Rob Landley <[email protected]> * * The POSIX-2008/SUSv4 spec for this is at: * http://opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html * and http://opengroup.org/onlinepubs/9699919799/utilities/sh.html * * The first link describes the following shell builtins: * * break colon continue dot eval exec exit export readonly return set shift * times trap unset * * The second link (the utilities directory) also contains specs for the * following shell builtins: * * alias bg cd command fc fg getopts hash jobs kill read type ulimit * umask unalias wait * * Things like the bash man page are good to read too. USE_SH(NEWTOY(cd, NULL, TOYFLAG_NOFORK)) USE_SH(NEWTOY(exit, NULL, TOYFLAG_NOFORK)) USE_SH(NEWTOY(sh, "c:i", TOYFLAG_BIN)) USE_SH(OLDTOY(toysh, sh, TOYFLAG_BIN)) // Login lies in argv[0], so add some aliases to catch that USE_SH(OLDTOY(-sh, sh, 0)) USE_SH(OLDTOY(-toysh, sh, 0)) config SH bool "sh (toysh)" default n help usage: sh [-c command] [script] Command shell. Runs a shell script, or reads input interactively and responds to it. -c command line to execute -i interactive mode (default when STDIN is a tty) # These are here for the help text, they're not selectable and control nothing config CD bool default n depends on SH help usage: cd [-PL] [path] Change current directory. With no arguments, go $HOME. -P Physical path: resolve symlinks in path -L Local path: .. trims directories off $PWD (default) config EXIT bool default n depends on SH help usage: exit [status] Exit shell. If no return value supplied on command line, use value of most recent command, or 0 if none. */ #define FOR_sh #include "toys.h" GLOBALS( char *command; long lineno; // parse scratch space struct double_list *parse; // Running jobs. struct sh_job { struct sh_job *next, *prev; unsigned jobno; // Every pipeline has at least one set of arguments or it's Not A Thing struct sh_arg { char **v; unsigned long c; } pipeline; // null terminated array of running processes in pipeline struct sh_process { struct string_list *delete; // expanded strings int pid, exit; // status? Stopped? Exited? char *end; struct sh_arg arg; } *procs, *proc; } *jobs, *job; unsigned jobcnt; ) void cd_main(void) { char *dest = *toys.optargs ? *toys.optargs : getenv("HOME"); xchdir(dest ? dest : "/"); } void exit_main(void) { exit(*toys.optargs ? atoi(*toys.optargs) : 0); } // Print prompt, parsing escapes static void do_prompt(char *prompt) { char *s, c, cc; if (!prompt) prompt = "\\$ "; while (*prompt) { c = *(prompt++); if (c=='!') { if (*prompt=='!') prompt++; else { printf("%ld", TT.lineno); continue; } } else if (c=='\\') { int i = 0; cc = *(prompt++); if (!cc) goto down; // \nnn \dD{}hHjlstT@AuvVwW!#$ // Ignore bash's "nonprintable" hack; query our cursor position instead. if (cc=='[' || cc==']') continue; else if (cc=='$') putchar(getuid() ? '$' : '#'); else if (cc=='h' || cc=='H') { *toybuf = 0; gethostname(toybuf, sizeof(toybuf)-1); if (cc=='h' && (s = strchr(toybuf, '.'))) *s = 0; fputs(toybuf, stdout); } else if (cc=='s') fputs(getbasename(*toys.argv), stdout); else { if (!(c = unescape(cc))) { c = '\\'; prompt--; } i++; } if (!i) continue; } down: putchar(c); } fflush(stdout); } // Execute the commands in a pipeline static void run_command(struct sh_process *pp) { struct toy_list *tl = toy_find(*pp->arg.v); // Is this command a builtin that should run in this process? if (tl && (tl->flags & TOYFLAG_NOFORK)) { struct toy_context temp; sigjmp_buf rebound; // This fakes lots of what toybox_main() does. memcpy(&temp, &toys, sizeof(struct toy_context)); memset(&toys, 0, sizeof(struct toy_context)); if (!sigsetjmp(rebound, 1)) { toys.rebound = &rebound; toy_init(tl, pp->arg.v); tl->toy_main(); } pp->exit = toys.exitval; if (toys.optargs != toys.argv+1) free(toys.optargs); if (toys.old_umask) umask(toys.old_umask); memcpy(&toys, &temp, sizeof(struct toy_context)); } else { int pipe[2]; pipe[0] = 0; pipe[1] = 1; if (-1 == (pp->pid = xpopen_both(pp->arg.v, pipe))) perror_msg("%s: vfork", *pp->arg.v); else pp->exit = xpclose_both(pp->pid, 0); } return; } // todo: ${name:?error} causes an error/abort here (syntax_err longjmp?) static void expand_arg(struct sh_arg *arg, char *new) { if (!(arg->c&32)) arg->v = xrealloc(arg->v, sizeof(void *)*(arg->c+33)); arg->v[arg->c++] = new; arg->v[arg->c] = 0; } // like error_msg() but exit from shell scripts void syntax_err(char *msg, ...) { va_list va; va_start(va, msg); verror_msg(msg, 0, va); va_end(va); if (*toys.optargs) xexit(); } // Parse one word from the command line, appending one or more argv[] entries // to struct command. Handles environment variable substitution and // substrings. Returns pointer to next used byte, or NULL if it // hit an ending token. // caller eats leading spaces // parse next word from command line. Returns end, or 0 if need continuation static char *parse_word(char *start) { int i, quote = 0; char *end = start, *s; // find end of string while (*end) { i = 0; // Handle quote contexts if (quote) { // end quote, skip quoted chars if (*end == toybuf[quote-1]) quote--, end++; else if (toybuf[quote-1] == '"' && *end == '`') toybuf[quote++] = *end++; else if (toybuf[quote-1] == '\'' || isspace(*end)) end++; else i++; } else { if (isspace(*end)) break; // start quote if (strchr("\"'`", *end)) toybuf[quote++] = *end++; else if (strstart(&end, "<(") || strstart(&end,">(")) toybuf[quote++]=')'; else if (*end==')') return end+(end==start); else { // control chars for (s = end; strchr(";|&<>(", *s); s++); if (s != end) return (end == start) ? s : end; i++; } } // loop if we already handled a symbol if (!i) continue; // Things the same unquoted or in double quotes // backslash escapes if (*end == '\\') { if (!end[1]) return 0; end += 2; } else if (*end == '$') { // barf if we're near overloading quote stack (nesting ridiculously deep) if (quote>4000) { syntax_err("tilt"); return (void *)1; } end++; if (strstart(&end, "((")) { // all we care about here are parentheses matching and then ending )) for (i = 0;;) { if (!*end) return 0; if (!i && strstart(&end, "))")) break; if (*end == '(') i++; else if (*end == ')') i--; } } else if (-1 != (i = stridx("({[", *end))) { toybuf[quote++] = ")}]"[i]; end++; } } else end++; } return quote ? 0 : end; } // Consume a line of shell script and do what it says. Returns 0 if finished, // pointer to start of unused part of line if it needs another line of input. static char *parse_line(char *line, struct double_list **pipeline) { char *start = line, *end, *s, *ex, *add; struct sh_arg *arg = 0; struct double_list *pl, *expect = 0; unsigned i, paren = 0; // Resume appending to last pipeline's last argument list if (*pipeline) arg = (void *)(*pipeline)->prev->data; if (arg) for (i = 0; i<arg->c; i++) { if (!strcmp(arg->v[i], "(")) paren++; else if (!strcmp(arg->v[i], ")")) paren--; } // Loop handling each word for (;;) { // Skip leading whitespace/comment while (isspace(*start)) ++start; if (*start=='#') { while (*start && *start != '\n') start++; continue; } // Parse next word and detect continuation/overflow. if ((end = parse_word(start)) == (void *)1) return 0; if (!end) return start; // Extend pipeline and argv[], handle EOL if (!arg) dlist_add(pipeline, (void *)(arg = xzalloc(sizeof(struct sh_arg)))); if (!(31&arg->c)) arg->v = xrealloc(arg->v, (32+arg->c)*sizeof(void *)); if (end == start) { arg->v[arg->c] = 0; break; } // Save argument (strdup) and check if it's special s = arg->v[arg->c] = xstrndup(start, end-start); if (!strcmp(s, "(")) paren++; else if (!strcmp(s, ")") && !paren--) syntax_err("bad %s", s); if (paren || !strchr(";|&", *start)) arg->c++; else { if (!arg->c) { syntax_err("bad %s", arg->v[arg->c]); goto flush; } arg = 0; } start = end; } // We parsed to the end of the line, which ended a pipeline. // Now handle flow control commands, which can also need more lines. // array of command lines separated by | and such // Note: don't preparse past ; because environment variables differ // Check for flow control continuations end = 0; for (pl = *pipeline; pl ; pl = (pl->next == *pipeline) ? 0 : pl->next) { arg = (void *)pl->data; if (!arg->c) continue; add = 0; // parse flow control statements in this command line for (i = 0; ; i++) { ex = expect ? expect->prev->data : 0; s = arg->v[i]; // push word to expect to end this block, and expect a command first if (add) { dlist_add(&expect, add); dlist_add(&expect, add = 0); } // end of statement? if (i == arg->c) break; // When waiting for { it must be next symbol, but can be on a new line. if (ex && !strcmp(ex, "{") && (strcmp(s, "{") || (!i && end))) { syntax_err("need {"); goto flush; } if (!strcmp(s, "if")) add = "then"; else if (!strcmp(s, "for") || !strcmp(s, "select") || !strcmp(s, "while") || !strcmp(s, "until")) add = "do"; else if (!strcmp(s, "case")) add = "esac"; else if (!strcmp(s, "{")) add = "}"; else if (!strcmp(s, "[[")) add = "]]"; // function NAME () [nl] { [nl] body ; } // Why can you to declare functions inside other functions? else if (arg->c>i+1 && !strcmp(arg->v[i+1], "(")) goto funky; else if (!strcmp(s, "function")) { i++; funky: // At this point we can only have a function: barf if it's invalid if (arg->c<i+3 || !strcmp(arg->v[i+1], "(") || !strcmp(arg->v[i+2], ")")) { syntax_err("bad function ()"); goto flush; } dlist_add(&expect, "}"); dlist_add(&expect, 0); dlist_add(&expect, "{"); // Expecting NULL will take any otherwise unrecognized word } else if (expect && !ex) { free(dlist_pop(&expect)); continue; // If we expect nothing and didn't just start a new flow control block, // rest of statement is a command and arguments, so stop now } else if (!ex) break; if (add) continue; // If we got here we expect a word to end this block: is this it? if (!strcmp(arg->v[i], ex)) { free(dlist_pop(&expect)); // can't "if | then" or "while && do", only ; or newline works if (end && !strcmp(end, ";")) { syntax_err("bad %s", end); goto flush; } // if it's a multipart block, what comes next? if (!strcmp(s, "do")) ex = "done"; else if (!strcmp(s, "then")) add = "fi\0A"; // fi could have elif, which queues a then. } else if (!strcmp(ex, "fi")) { if (!strcmp(s, "elif")) { free(dlist_pop(&expect)); add = "then"; // catch duplicate else while we're here } else if (!strcmp(s, "else")) { if (ex[3] != 'A') { syntax_err("2 else"); goto flush; } free(dlist_pop(&expect)); add = "fi\0B"; } } } // Record how the previous stanza ended: ; | & ;; || && ;& ;;& |& NULL end = arg->v[arg->c]; } // Do we need more lines to finish a flow control statement? if (expect || paren) { llist_traverse(expect, free); return start; } // iterate through the commands running each one for (pl = *pipeline; pl ; pl = (pl->next == *pipeline) ? 0 : pl->next) { struct sh_process *pp = xzalloc(sizeof(struct sh_process)); for (i = 0; i<((struct sh_arg *)pl->data)->c; i++) expand_arg(&pp->arg, ((struct sh_arg *)pl->data)->v[i]); run_command(pp); } flush: while ((pl = dlist_pop(pipeline))) { arg = (void *)pl->data; free(pl); for (i = 0; i<arg->c; i++) free(arg->v[i]); free(arg->v); free(arg); } *pipeline = 0; return 0; } void sh_main(void) { FILE *f = 0; char *command = 0, *old = 0; struct double_list *scratch = 0; // Set up signal handlers and grab control of this tty. if (isatty(0)) toys.optflags |= FLAG_i; if (*toys.optargs) f = xfopen(*toys.optargs, "r"); if (TT.command) command = parse_line(TT.command, &scratch); else for (;;) { char *new = 0; size_t linelen = 0; // Prompt and read line if (!f) { char *s = getenv(command ? "PS2" : "PS1"); if (!s) s = command ? "> " : (getpid() ? "\\$ " : "# "); do_prompt(s); } if (1 > getline(&new, &linelen, f ? f : stdin)) break; if (f) TT.lineno++; // Append to unused portion of previous line if any if (command) { command = xmprintf("%s%s", command, new); free(old); free(new); old = command; } else { free(old); old = new; } // returns 0 if line consumed, command if it needs more data command = parse_line(old, &scratch); } if (command) error_exit("unfinished line"); toys.exitval = f && ferror(f); }
2.21875
2
2024-11-18T20:14:19.865674+00:00
2023-07-21T03:43:38
f3e0c6aa80029be3120b0727ee97cf8be4a0e202
{ "blob_id": "f3e0c6aa80029be3120b0727ee97cf8be4a0e202", "branch_name": "refs/heads/master", "committer_date": "2023-07-21T03:43:38", "content_id": "c3c783859f5fc11f45151cb984161dc6bfc72bf2", "detected_licenses": [ "Apache-2.0" ], "directory_id": "f24b1897637ac30dbc6fc7d839cfe7cce47fd36d", "extension": "h", "filename": "ops_ref.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 236031479, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2449, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/ops_ref.h", "provenance": "stackv2-0049.json.gz:178839", "repo_name": "mikeagun/concat", "revision_date": "2023-07-21T03:43:38", "revision_id": "dd5cbd78c148bfebf013c1e0c7b57d8e483bff1b", "snapshot_id": "5a3ea4511a1d63888faecfc58e02688408653048", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mikeagun/concat/dd5cbd78c148bfebf013c1e0c7b57d8e483bff1b/src/ops_ref.h", "visit_date": "2023-08-08T12:52:50.386474" }
stackv2
//Copyright (C) 2020 D. Michael Agun // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. #ifndef __OPS_REF_H__ #define __OPS_REF_H__ 1 #include "vmstate.h" //TODO: review and determine minimum comprehensive operator set err_t ops_ref_init(vm_t *vm); vm_op_handler _op_ref; //A ref -- ref(A) vm_op_handler _op_deref; //ref(A) -- A vm_op_handler _op_refswap; //ref(A) B -- ref(B) A vm_op_handler _op_guard; //ref(x) [A] guard -- lock(ref(x)) x A unlock(ref(x)) vm_op_handler _op_guard_sig; //ref(x) [A] guard.sig -- lock(ref(x)) x A signal(ref(x)) unlock(ref(x)) vm_op_handler _op_guard_bcast; //ref(x) [A] guard.bcast -- lock(ref(x)) x A bcast (ref(x)) unlock(ref(x)) vm_op_handler _op_guard_waitwhile; //ref(x) [prewait] [postwait] guard.waitwhile -- lock x [prewait] (ref() [prewait] [postwait]) waitwhile_ unlock vm_op_handler _op_guard_sigwaitwhile; //ref(x) [prewait] [postwait] guard.waitwhile -- lock x [prewait] signal (ref() [prewait] [postwait]) waitwhile_ unlock vm_op_handler _op_waitwhile_; //x bool (ref() [prewait] [postwait]) waitwhile_ -- x postwait ref() OR wait x (ref() [prewait] [postwait]) waitwhile_ vm_op_handler _op_sigwaitwhile_; //x bool (ref() [prewait] [postwait]) waitwhile_ -- x postwait ref() OR wait x (ref() [prewait] [postwait]) waitwhile_ vm_op_handler _op_unguard_catch; //internal: continuation handler to ensure refs get unlocked on exception vm_op_handler _op_unguard; //internal: unlock reference vm_op_handler _op_unguard_sig; //internal: signal and unlock reference vm_op_handler _op_unguard_bcast; //internal: broadcast and unlock reference vm_op_handler _op_signal; //ref{A} -- ref{A} signal one thread waiting on this ref vm_op_handler _op_broadcast; //ref{A} -- ref{A} signal all threads waiting on this ref vm_op_handler _op_wait; //ref{A} -- ref{A} locks, waits for a signal, unlocks -- you probably want guard.waitwhile instead #endif
2.375
2
2024-11-18T20:14:25.396488+00:00
2020-09-13T06:08:15
3a2c30e47417c52f31a1b0a44e29ae40644fe23a
{ "blob_id": "3a2c30e47417c52f31a1b0a44e29ae40644fe23a", "branch_name": "refs/heads/master", "committer_date": "2020-09-13T06:08:15", "content_id": "48abc00ae3c4fc6740a3f3f388e7cccdb2fcdf9e", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause" ], "directory_id": "965fc6765aa08f98d53daa78dfc0d80489683dbd", "extension": "c", "filename": "dump.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 295089455, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3924, "license": "BSD-2-Clause,BSD-3-Clause", "license_type": "permissive", "path": "/src/dump.c", "provenance": "stackv2-0049.json.gz:179482", "repo_name": "lastweek/source-tcpstat", "revision_date": "2020-09-13T06:08:15", "revision_id": "f2a4e55d5d58ba93050996e30e0412cfd6e930c4", "snapshot_id": "fd719f0c369f1cfe22bf796ba49a4252a193a147", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lastweek/source-tcpstat/f2a4e55d5d58ba93050996e30e0412cfd6e930c4/src/dump.c", "visit_date": "2022-12-09T18:06:06.109222" }
stackv2
/* * Copyright (c) 2000 Paul Herman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. * * $Id: dump.c,v 1.14 2002/09/18 21:00:29 pherman Exp $ */ /********************************************************** * Example of how to use the library included * with this program **********************************************************/ #include "packetdump.h" /* GLOBALS */ char filterexpr[BUF_SIZ] = ""; int get_tcp_flags = 0; int what_to_show = 0; int packet_number = 0; void my_hook(packet_data *pd, void **args) { printf("PACKET NUMBER: %d\n", ++packet_number); print_packet(pd, what_to_show); printf("-------------------\n"); } /* * process_file() takes the output of tcpdump, saves packets, and displays * statistics */ void process_file(char *fname, u_int unused) { get_dump_data(fname, filterexpr, get_tcp_flags, -1.0, my_hook, NULL); } int parse_show_types(char *in) { int ret = 0; while (*in) { if (*in == 'b' || *in == 'a' ) ret |= PP_SHOW_BASICINFO; if (*in == 'l' || *in == 'a' ) ret |= PP_SHOW_LINKLAYER; if (*in == 'i' || *in == 'a' ) ret |= PP_SHOW_IPHEADER; if (*in == 'c' || *in == 'a' ) ret |= PP_SHOW_PACKETCONTENT; if (*in == 't' || *in == 'a' ) ret |= PP_SHOW_TCPHEADER | PP_SHOW_UDPHEADER | PP_SHOW_ICMPHEADER; in++; } return ret; } #define USAGE \ "Usage: %s [-?hls] [-f filter expr] [-r file] [-s letters] \ \n -?, -h - display this help \ \n -f filter expr - filter expression to pass to tcpdump \ \n -l - include link layer in packet size calc \ \n -r file - file to read data from \ \n -s letters - what to show from packet, where letters is any of: \ \n a - everything \ \n b - basic info \ \n l - link info \ \n i - IP info \ \n t - TCP/UDP/ICMP info \ \n c - packet content \ \n" int Usage(int r, char *prog) { fprintf(stderr, USAGE, my_basename(prog)); return r; } void error(char *s) { fprintf(stderr, "error: %s\n", s); Usage(-1, "packetdump"); exit(-1); } int main(int argc, char **argv) { char filename[BUF_SIZ]; int ch; *filename = 0; while ( (ch = getopt(argc, argv, "h?lf:r:s:")) != -1) { switch(ch) { case 'h': case '?': return Usage(1, argv[0]); break; case 'l': get_tcp_flags |= GET_TCPD_COUNT_LINKSIZE; break; case 'f': strncpy(filterexpr, optarg, BUF_SIZ); break; case 'r': strncpy(filename, optarg, BUF_SIZ); break; case 's': what_to_show |= parse_show_types(optarg); break; default: return Usage(1, argv[0]); break; } } if (*filename == 0) error("must specify filename"); process_file(filename, 0); return 0; }
2.328125
2
2024-11-18T20:14:25.726870+00:00
2023-07-31T08:26:14
36f989455e378bec263d437bd2b6d7eff98a0efd
{ "blob_id": "36f989455e378bec263d437bd2b6d7eff98a0efd", "branch_name": "refs/heads/develop", "committer_date": "2023-08-11T07:38:17", "content_id": "8721a5031a33620e0fb80b65a183d9afe1b20914", "detected_licenses": [], "directory_id": "693bd39eb66eade67997bc608fe84e76e66eeec2", "extension": "c", "filename": "mpp_trie_test.c", "fork_events_count": 79, "gha_created_at": "2016-10-17T01:13:37", "gha_event_created_at": "2023-03-08T09:44:01", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 71088248, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2406, "license": "", "license_type": "permissive", "path": "/mpp/base/test/mpp_trie_test.c", "provenance": "stackv2-0049.json.gz:179739", "repo_name": "HermanChen/mpp", "revision_date": "2023-07-31T08:26:14", "revision_id": "0af9b5becc76c4685831214808e124e65543297b", "snapshot_id": "6a1751777b120b764f86e0f34975231054a3c262", "src_encoding": "UTF-8", "star_events_count": 139, "url": "https://raw.githubusercontent.com/HermanChen/mpp/0af9b5becc76c4685831214808e124e65543297b/mpp/base/test/mpp_trie_test.c", "visit_date": "2023-08-17T07:17:49.489974" }
stackv2
/* * Copyright 2015 Rockchip Electronics Co. LTD * * 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. */ #define MODULE_TAG "mpp_trie_test" #include <string.h> #include "mpp_log.h" #include "mpp_mem.h" #include "mpp_time.h" #include "mpp_common.h" #include "mpp_trie.h" typedef void *(*TestProc)(void *); typedef struct TestAction_t { const char *name; void *ctx; TestProc proc; } TestAction; void *print_opt(void *ctx) { RK_U8 **str = (RK_U8 **)ctx; if (str && *str) mpp_log("get option %s\n", *str); return NULL; } TestAction test_info[] = { { "rc:mode", &test_info[0], print_opt}, { "rc:bps_target", &test_info[1], print_opt}, { "rc:bps_max", &test_info[2], print_opt}, { "rc:bps_min", &test_info[3], print_opt}, }; const char *test_str[] = { "rc:mode", "rc:bps_target", "rc:bps_max", }; int main() { MppTrie trie = NULL; void *info = NULL; RK_U32 i; RK_S64 end = 0; RK_S64 start = 0; RK_S32 info_cnt = MPP_ARRAY_ELEMS(test_info); RK_S32 node_cnt = 100; mpp_trie_init(&trie, node_cnt, info_cnt); start = mpp_time(); mpp_trie_add_info(trie, &test_info[0].name); mpp_trie_add_info(trie, &test_info[1].name); mpp_trie_add_info(trie, &test_info[2].name); mpp_trie_add_info(trie, &test_info[3].name); end = mpp_time(); mpp_log("add act time %lld us\n", end - start); for (i = 0; i < MPP_ARRAY_ELEMS(test_str); i++) { start = mpp_time(); info = mpp_trie_get_info(trie, test_str[i]); end = mpp_time(); if (info) { TestAction *act = (TestAction *)info; if (act && act->proc) { act->proc(act->ctx); mpp_log("search time %lld us\n", end - start); } } } mpp_trie_deinit(trie); return 0; }
2.25
2
2024-11-18T20:14:25.811890+00:00
2023-02-16T18:40:06
63f90e5654258fb556344976dc4cf70b34d348c2
{ "blob_id": "63f90e5654258fb556344976dc4cf70b34d348c2", "branch_name": "refs/heads/main", "committer_date": "2023-02-16T18:40:06", "content_id": "a25c53b261187e5458bc1d3126f3fb331f770874", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "fb6245383e7e7d53ab94b6eb2bb09469db466c58", "extension": "h", "filename": "alrm.h", "fork_events_count": 28, "gha_created_at": "2011-10-28T20:21:39", "gha_event_created_at": "2022-12-28T22:03:54", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 2667699, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2658, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/misc/alrm.h", "provenance": "stackv2-0049.json.gz:179868", "repo_name": "Unidata/LDM", "revision_date": "2023-02-16T18:40:06", "revision_id": "293344411b1a4fe35bd0e9c1eda8614a6d201d51", "snapshot_id": "99122b6e1fef032af263972be3b56eb83d3074fd", "src_encoding": "UTF-8", "star_events_count": 33, "url": "https://raw.githubusercontent.com/Unidata/LDM/293344411b1a4fe35bd0e9c1eda8614a6d201d51/misc/alrm.h", "visit_date": "2023-09-03T01:06:51.376173" }
stackv2
/** * Careful alarm interface * * Copyright 2020, University Corporation for Atmospheric Research. All rights * reserved. * * See file COPYRIGHT in the top-level source-directory for copying and * redistribution conditions. */ #ifndef ALRM_H #define ALRM_H #include <unistd.h> #include <signal.h> #include <setjmp.h> /* * Implement a signal function with known, desired characteristics. -Stevens */ #if defined(__STDC__) typedef void Sigfunc(int) ; #else typedef void Sigfunc() ; #endif /** * Sets an alarm. * * @param[in] seconds Amount of time to wait until SIGALRM is generated * @retval 0 Success */ void alarm_set(const unsigned seconds); /** * Dismisses any potential or pending alarm. Does nothing if `alarm_set()` * wasn't previously called. */ void alarm_dismiss(); /** * Indicates if a SIGALRM was generated after the last call to `alarm_set()`. * * @retval 1 SIGALRM was generated * @retval 0 SIGALRM was not generated */ int alarm_generated(); /* * Glenn's original stuff with some additions and modifications: * -- SRE 2020-10-10 */ // The following must be visible to SET_ALARM(): extern volatile sig_atomic_t alrm_validJmpbuf; // `alrm_jumpbuf` is valid? extern sigjmp_buf alrm_jumpbuf; extern Sigfunc* alrm_savHandler; extern void alrm_init(); // Ensures module is initialized /** * Sets a signal handler. * * @param[in] signo Signal number * @param[in] handler Signal handler * @return Previous signal handler */ Sigfunc* alrm_mysignal(int signo, Sigfunc *handler); /** * SIGALRM handler for SET_ALARM(). * * @param[in] sig SIGALRM */ void alrm_handler(int sig); /** * Sets an alarm. * * @param[in] seconds Time until SIGALRM is generated * @param[in] jumplabel `goto` label to jump to upon SIGALRM delivery */ #define SET_ALARM(seconds, jumplabel) \ { \ alrm_init(); \ if (sigsetjmp(alrm_jumpbuf, 1)) { \ /* \ * SIGALRM handler called siglongjmp(). Can't happen inside \ * alrm_clear(). \ */ \ if (alrm_savHandler != SIG_ERR) { \ (void)alrm_mysignal(SIGALRM, alrm_savHandler); \ alrm_savHandler = SIG_ERR; \ } \ goto jumplabel; \ } \ /* else, first time, we set the jmp env */ \ alrm_validJmpbuf = 1; \ \ alrm_savHandler = alrm_mysignal(SIGALRM, alrm_handler); \ if (alrm_savHandler == SIG_ERR) { \ alrm_validJmpbuf = 0; \ } else { \ (void)alarm((unsigned)(seconds)); \ } \ } /** * Dismisses any potential or pending alarm. Safe to call even when SET_ALARM() * has not been called */ void alrm_clear(); #define CLR_ALARM() alrm_clear() #endif /* ALRM_H */
2.484375
2
2024-11-18T20:14:28.545229+00:00
2021-04-13T08:58:17
a2602e0531db86aaaf56ca7a61cbd1752be18e20
{ "blob_id": "a2602e0531db86aaaf56ca7a61cbd1752be18e20", "branch_name": "refs/heads/master", "committer_date": "2021-04-13T08:58:17", "content_id": "883b99079e815692f2920fcc55dad961dbc23eba", "detected_licenses": [ "MIT" ], "directory_id": "e5e7add4d441c885fe3f90f17d842d793bd97750", "extension": "c", "filename": "spsa.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 266304463, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2751, "license": "MIT", "license_type": "permissive", "path": "/spsa.c", "provenance": "stackv2-0049.json.gz:180257", "repo_name": "vdbergh/spsa_simul", "revision_date": "2021-04-13T08:58:17", "revision_id": "66f45e8daf51bf1258d9aab27b91540803411b8b", "snapshot_id": "31dcec81f2cc627a4f725d813fd465cef2ff1d85", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/vdbergh/spsa_simul/66f45e8daf51bf1258d9aab27b91540803411b8b/spsa.c", "visit_date": "2023-04-14T22:36:13.402831" }
stackv2
#include "spsa_sim.h" void spsa_disp(spsa_t *s){ printf("~~~~~~~design~~~~~~~ \n"); printf("num_params =%d\n",s->num_params); printf("confidence =%f\n",s->confidence); printf("draw_ratio =%f\n",s->draw_ratio); printf("precision =%f\n",s->precision); printf("c_ratio =%f\n",s->c_ratio); printf("lambda_ratio =%f\n",s->lambda_ratio); printf("start_elo =%f\n",s->start_elo); printf("bounds =%d\n",s->bounds); printf("~~~~~~~computed~~~~~~~ \n"); printf("r =%f\n",s->r); params_disp("c =",s->num_params,&(s->c)); printf("num_games =%d\n",s->num_games); } void spsa_init(spsa_t *s){ s->num_params=0; s->confidence=0.95; s->draw_ratio=0.61; s->precision=0.5; s->c_ratio=1.0/6.0; s->lambda_ratio=3; s->bounds=0; /* do not respect bounds by default */ s->start_elo=2; s->r=0; s->num_games=0; for(int i=0;i<MAX_PARAMS;i++){ s->c[i]=0; } } void spsa_lambda(spsa_t *s, lf_t *est_lf, params_t *lambda){ for(int j=0;j<s->num_params;j++){ double H_diag=-2*est_lf->elos[j]/pow((est_lf->maxima[j]-est_lf->minima[j])/2,2); (*lambda)[j]=-C/(2*s->r*pow(s->c[j],2)*H_diag); } } void spsa_compute(spsa_t *s, lf_t *est_lf, int heuristic){ double chi2=gsl_cdf_chisq_Pinv(s->confidence, est_lf->num_params); params_t lambda; int ng; s->num_params=est_lf->num_params; for(int j=0;j<s->num_params;j++){ s->c[j]=s->c_ratio*(est_lf->maxima[j]-est_lf->minima[j]); } if(heuristic==OPTIONS_HEURISTIC_LAMBDA_RATIO){ s->r=s->precision/(C*chi2*(1-s->draw_ratio)/8); s->num_games=0; spsa_lambda(s,est_lf,&lambda); for(int j=0;j<s->num_params;j++){ ng=(int)(s->lambda_ratio*lambda[j]+0.5); if(ng>s->num_games){ s->num_games=ng; } } }else if(heuristic==OPTIONS_HEURISTIC_OPTIMUM){ double r_,t_; optimum_r_t(s, est_lf, &r_, &t_); s->r=r_; s->num_games=(int)(t_+0.5); }else{ assert(0); } } void spsa_elo_estimate(spsa_t *s, lf_t *lf, params_t *p0, double t, double *fixed, double *noise, double *asymp){ sos_t sos, sos_asymp; double fixed_, noise_; sos_from_lf_spsa(&sos, lf, s, p0, t); sos_from_lf_spsa(&sos_asymp, lf, s, p0, INFINITY); sos_expected(&sos,&fixed_,&noise_); *fixed=-fixed_; *noise=-noise_; sos_expected(&sos_asymp,&fixed_,&noise_); *asymp=-noise_; } double spsa_success_estimate(spsa_t *s, lf_t *lf, params_t *p0, double t){ sos_t sos; sos_from_lf_spsa(&sos, lf, s, p0, t); return sos_cdf(&sos,s->precision); } double spsa_percentile(spsa_t *s, lf_t *lf, params_t *p0, double t, double p){ sos_t sos; sos_from_lf_spsa(&sos, lf, s, p0, t); return -sos_ppf(&sos,p); }
2.203125
2
2024-11-18T20:14:28.633867+00:00
2021-07-24T22:22:38
5d90b466b2e1a8372d512bdd23230a14a75e4cb1
{ "blob_id": "5d90b466b2e1a8372d512bdd23230a14a75e4cb1", "branch_name": "refs/heads/main", "committer_date": "2021-07-24T22:22:38", "content_id": "2f71ec6887549308b95cb8a74ba3b3e22478cfde", "detected_licenses": [ "MIT" ], "directory_id": "6c039ab0efbc0fc6f215c16a1b9b89c1c8c2706f", "extension": "c", "filename": "Untitled-1.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 389211770, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1620, "license": "MIT", "license_type": "permissive", "path": "/user/Untitled-1.c", "provenance": "stackv2-0049.json.gz:180386", "repo_name": "DorCarmi94/OS-Scheduling", "revision_date": "2021-07-24T22:22:38", "revision_id": "84439d2453954984c68b2516ad53ea32b6ab46c4", "snapshot_id": "26dbc0e2fa400e5ea6a5061cfadf1e207048afa3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/DorCarmi94/OS-Scheduling/84439d2453954984c68b2516ad53ea32b6ab46c4/user/Untitled-1.c", "visit_date": "2023-06-24T15:32:28.077699" }
stackv2
//Run the requested working directory //if(ecmd->argv[0] == 0) //exit(1); //exec(ecmd->argv[0], ecmd->argv); ///If didn't work, run the directories specified by PATH file read(path_fd, &buffer, buf_size); char* ptr = buffer; char* dots_ptr; while((dots_ptr = strchr(ptr, ':'))){ *dots_ptr = '\0'; exec(ptr, ecmd->argv); ptr = dots_ptr + 1; } fprintf(2, "exec %s failed\n", ecmd->argv[0]); break; //backup ecmd = (struct execcmd*)cmd; if(ecmd->argv[0] == 0) exit(1); exec(ecmd->argv[0], ecmd->argv); int path_fd; char buffer[buf_size]; char* str; path_fd= open("/path",O_RDWR); if(path_fd<0) { path_fd=open("/path",O_CREATE|O_RDWR); str= "/:/user/:"; write(path_fd,str,strlen(str)); } char* ptr = buffer; read(path_fd, ptr, buf_size); char* dots_ptr; while((dots_ptr = strchr(ptr, ':'))){ *dots_ptr = '\0'; int length = strlen(ptr); char cpy[length]; strcpy(cpy, ptr); ecmd->argv[0] = cpy; exec(ecmd->argv[0], ecmd->argv); ptr = dots_ptr + 1; } fprintf(2, "exec %s failed\n", ecmd->argv[0]); //fucking working int path_fd=3; char buffer[2000]; char* str;="hellpo"; buffer[0]='1'; if(ecmd->argv[0] == 0) exit(1); exec(ecmd->argv[0], ecmd->argv); //buffer[0]='c'; //path_fd= open("/path",O_RDWR); fprintf(2,"%d",path_fd); fprintf(2,"%c",buffer[0]); fprintf(2,"%s",str); //*buffer="hello"; break;
2.453125
2
2024-11-18T20:14:29.110657+00:00
2023-08-04T02:52:06
99a6255666b8483d42e8ecc539b2db0320bb97c3
{ "blob_id": "99a6255666b8483d42e8ecc539b2db0320bb97c3", "branch_name": "refs/heads/main", "committer_date": "2023-08-04T02:52:06", "content_id": "37f7d09dc83bc9377ccb0369d90e3ed33f9f732c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c641636e184c0ec1dcc7b851bad678c898cdd05d", "extension": "c", "filename": "graph.c", "fork_events_count": 341, "gha_created_at": "2019-06-11T03:23:28", "gha_event_created_at": "2023-08-04T02:52:07", "gha_language": "Python", "gha_license_id": "Apache-2.0", "github_id": 191286408, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7879, "license": "Apache-2.0", "license_type": "permissive", "path": "/pgl/third_party/metis/libmetis/graph.c", "provenance": "stackv2-0049.json.gz:180645", "repo_name": "PaddlePaddle/PGL", "revision_date": "2023-08-04T02:52:06", "revision_id": "7a55649d46d7ad93de31eb9b3ebf71b82d1fcffb", "snapshot_id": "d8f0a82854a141bee1afdddd9a77bdd723c83ed8", "src_encoding": "UTF-8", "star_events_count": 1719, "url": "https://raw.githubusercontent.com/PaddlePaddle/PGL/7a55649d46d7ad93de31eb9b3ebf71b82d1fcffb/pgl/third_party/metis/libmetis/graph.c", "visit_date": "2023-08-17T10:33:02.425526" }
stackv2
/** \file \brief Functions that deal with setting up the graphs for METIS. \date Started 7/25/1997 \author George \author Copyright 1997-2009, Regents of the University of Minnesota \version\verbatim $Id: graph.c 10513 2011-07-07 22:06:03Z karypis $ \endverbatim */ #include "metislib.h" /*************************************************************************/ /*! This function sets up the graph from the user input */ /*************************************************************************/ graph_t *SetupGraph(ctrl_t *ctrl, idx_t nvtxs, idx_t ncon, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *vsize, idx_t *adjwgt) { idx_t i, j, k, sum; real_t *nvwgt; graph_t *graph; /* allocate the graph and fill in the fields */ graph = CreateGraph(); graph->nvtxs = nvtxs; graph->nedges = xadj[nvtxs]; graph->ncon = ncon; graph->xadj = xadj; graph->free_xadj = 0; graph->adjncy = adjncy; graph->free_adjncy = 0; /* setup the vertex weights */ if (vwgt) { graph->vwgt = vwgt; graph->free_vwgt = 0; } else { vwgt = graph->vwgt = ismalloc(ncon*nvtxs, 1, "SetupGraph: vwgt"); } graph->tvwgt = imalloc(ncon, "SetupGraph: tvwgts"); graph->invtvwgt = rmalloc(ncon, "SetupGraph: invtvwgts"); for (i=0; i<ncon; i++) { graph->tvwgt[i] = isum(nvtxs, vwgt+i, ncon); graph->invtvwgt[i] = 1.0/(graph->tvwgt[i] > 0 ? graph->tvwgt[i] : 1); } if (ctrl->objtype == METIS_OBJTYPE_VOL) { /* Setup the vsize */ if (vsize) { graph->vsize = vsize; graph->free_vsize = 0; } else { vsize = graph->vsize = ismalloc(nvtxs, 1, "SetupGraph: vsize"); } /* Allocate memory for edge weights and initialize them to the sum of the vsize */ adjwgt = graph->adjwgt = imalloc(graph->nedges, "SetupGraph: adjwgt"); for (i=0; i<nvtxs; i++) { for (j=xadj[i]; j<xadj[i+1]; j++) adjwgt[j] = 1+vsize[i]+vsize[adjncy[j]]; } } else { /* For edgecut minimization */ /* setup the edge weights */ if (adjwgt) { graph->adjwgt = adjwgt; graph->free_adjwgt = 0; } else { adjwgt = graph->adjwgt = ismalloc(graph->nedges, 1, "SetupGraph: adjwgt"); } } /* setup various derived info */ SetupGraph_tvwgt(graph); if (ctrl->optype == METIS_OP_PMETIS || ctrl->optype == METIS_OP_OMETIS) SetupGraph_label(graph); ASSERT(CheckGraph(graph, ctrl->numflag, 1)); return graph; } /*************************************************************************/ /*! Set's up the tvwgt/invtvwgt info */ /*************************************************************************/ void SetupGraph_tvwgt(graph_t *graph) { idx_t i; if (graph->tvwgt == NULL) graph->tvwgt = imalloc(graph->ncon, "SetupGraph_tvwgt: tvwgt"); if (graph->invtvwgt == NULL) graph->invtvwgt = rmalloc(graph->ncon, "SetupGraph_tvwgt: invtvwgt"); for (i=0; i<graph->ncon; i++) { graph->tvwgt[i] = isum(graph->nvtxs, graph->vwgt+i, graph->ncon); graph->invtvwgt[i] = 1.0/(graph->tvwgt[i] > 0 ? graph->tvwgt[i] : 1); } } /*************************************************************************/ /*! Set's up the label info */ /*************************************************************************/ void SetupGraph_label(graph_t *graph) { idx_t i; if (graph->label == NULL) graph->label = imalloc(graph->nvtxs, "SetupGraph_label: label"); for (i=0; i<graph->nvtxs; i++) graph->label[i] = i; } /*************************************************************************/ /*! Setup the various arrays for the splitted graph */ /*************************************************************************/ graph_t *SetupSplitGraph(graph_t *graph, idx_t snvtxs, idx_t snedges) { graph_t *sgraph; sgraph = CreateGraph(); sgraph->nvtxs = snvtxs; sgraph->nedges = snedges; sgraph->ncon = graph->ncon; /* Allocate memory for the splitted graph */ sgraph->xadj = imalloc(snvtxs+1, "SetupSplitGraph: xadj"); sgraph->vwgt = imalloc(sgraph->ncon*snvtxs, "SetupSplitGraph: vwgt"); sgraph->adjncy = imalloc(snedges, "SetupSplitGraph: adjncy"); sgraph->adjwgt = imalloc(snedges, "SetupSplitGraph: adjwgt"); sgraph->label = imalloc(snvtxs, "SetupSplitGraph: label"); sgraph->tvwgt = imalloc(sgraph->ncon, "SetupSplitGraph: tvwgt"); sgraph->invtvwgt = rmalloc(sgraph->ncon, "SetupSplitGraph: invtvwgt"); if (graph->vsize) sgraph->vsize = imalloc(snvtxs, "SetupSplitGraph: vsize"); return sgraph; } /*************************************************************************/ /*! This function creates and initializes a graph_t data structure */ /*************************************************************************/ graph_t *CreateGraph(void) { graph_t *graph; graph = (graph_t *)gk_malloc(sizeof(graph_t), "CreateGraph: graph"); InitGraph(graph); return graph; } /*************************************************************************/ /*! This function initializes a graph_t data structure */ /*************************************************************************/ void InitGraph(graph_t *graph) { memset((void *)graph, 0, sizeof(graph_t)); /* graph size constants */ graph->nvtxs = -1; graph->nedges = -1; graph->ncon = -1; graph->mincut = -1; graph->minvol = -1; graph->nbnd = -1; /* memory for the graph structure */ graph->xadj = NULL; graph->vwgt = NULL; graph->vsize = NULL; graph->adjncy = NULL; graph->adjwgt = NULL; graph->label = NULL; graph->cmap = NULL; graph->tvwgt = NULL; graph->invtvwgt = NULL; /* by default these are set to true, but the can be explicitly changed afterwards */ graph->free_xadj = 1; graph->free_vwgt = 1; graph->free_vsize = 1; graph->free_adjncy = 1; graph->free_adjwgt = 1; /* memory for the partition/refinement structure */ graph->where = NULL; graph->pwgts = NULL; graph->id = NULL; graph->ed = NULL; graph->bndptr = NULL; graph->bndind = NULL; graph->nrinfo = NULL; graph->ckrinfo = NULL; graph->vkrinfo = NULL; /* linked-list structure */ graph->coarser = NULL; graph->finer = NULL; } /*************************************************************************/ /*! This function frees the refinement/partition memory stored in a graph */ /*************************************************************************/ void FreeRData(graph_t *graph) { /* The following is for the -minconn and -contig to work properly in the vol-refinement routines */ if ((void *)graph->ckrinfo == (void *)graph->vkrinfo) graph->ckrinfo = NULL; /* free partition/refinement structure */ gk_free((void **)&graph->where, &graph->pwgts, &graph->id, &graph->ed, &graph->bndptr, &graph->bndind, &graph->nrinfo, &graph->ckrinfo, &graph->vkrinfo, LTERM); } /*************************************************************************/ /*! This function deallocates any memory stored in a graph */ /*************************************************************************/ void FreeGraph(graph_t **r_graph) { graph_t *graph; graph = *r_graph; /* free graph structure */ if (graph->free_xadj) gk_free((void **)&graph->xadj, LTERM); if (graph->free_vwgt) gk_free((void **)&graph->vwgt, LTERM); if (graph->free_vsize) gk_free((void **)&graph->vsize, LTERM); if (graph->free_adjncy) gk_free((void **)&graph->adjncy, LTERM); if (graph->free_adjwgt) gk_free((void **)&graph->adjwgt, LTERM); /* free partition/refinement structure */ FreeRData(graph); gk_free((void **)&graph->tvwgt, &graph->invtvwgt, &graph->label, &graph->cmap, &graph, LTERM); *r_graph = NULL; }
2.5625
3
2024-11-18T20:14:29.344473+00:00
2014-05-22T04:05:09
4dba59ff2756bce4d468993ee76c482c29e2554b
{ "blob_id": "4dba59ff2756bce4d468993ee76c482c29e2554b", "branch_name": "refs/heads/master", "committer_date": "2014-05-22T04:05:09", "content_id": "296a927f072c6e8d490aa22000646cfe7c163e18", "detected_licenses": [ "Apache-2.0" ], "directory_id": "a67a242a5a264b8c4d119c8d02422c9f7b4bd84e", "extension": "c", "filename": "paging.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 17102645, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2274, "license": "Apache-2.0", "license_type": "permissive", "path": "/kernel/src/paging.c", "provenance": "stackv2-0049.json.gz:180774", "repo_name": "sjrct/frosk-current", "revision_date": "2014-05-22T04:05:09", "revision_id": "88ebd51f78fc596c955824a6a6eb83d7ecf2718f", "snapshot_id": "c76697788fabc277566e7fe5137b5376f6c0120e", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/sjrct/frosk-current/88ebd51f78fc596c955824a6a6eb83d7ecf2718f/kernel/src/paging.c", "visit_date": "2023-06-22T04:25:44.421548" }
stackv2
// // kernel/src/paging.c // #include <util.h> #include <common.h> #include "asm.h" #include "debug.h" #include "paging.h" #include "memory/pages.h" #define ERROR_PRESENT 0x01 #define ERROR_WRITE 0x02 #define ERROR_USER 0x04 #define ERROR_RESERVED 0x08 #define ERROR_EXECUTE 0x10 #define PG_SWP_ENT (PM_L1_LOC + PG_SWP_LOC / 0x200) static ulong get_entry(ulong addr, ulong tbl, int shf) { #ifdef __ARCH_X86_64 #define LSHIFT 3 #else #define LSHIFT 2 #endif return tbl + (((addr >> shf) << LSHIFT) & 0xfff); #undef LSHIFT } static void down(ulong addr, ulong tbl, int shift) { long i; ulong entry = get_entry(addr, tbl, shift); ulong v = atq(entry); if (!(v & 1)) { v = alloc_pgs(PAGE_SIZE, PHYS_PAGES) | 7; atq(entry) = v; atq(PG_SWP_ENT) = v; invlpg(PG_SWP_LOC); for (i = 0; i < PAGE_SIZE; i++) atb(PG_SWP_LOC + i) = 0; } else { atq(PG_SWP_ENT) = v; invlpg(PG_SWP_LOC); } } void pageto(ulong virt, ulong value) { assert(!(virt % PAGE_SIZE)); invlpg(virt); #ifdef __ARCH_X86_64 if (virt >= HIGH_HALF_BOT) { virt -= NON_CANON_SIZE; } down(virt, PM_L4_LOC, 39); down(virt, PG_SWP_LOC, 30); down(virt, PG_SWP_LOC, 21); #else down(virt, PM_L2_LOC, 22); #endif atq(get_entry(virt, PG_SWP_LOC, 12)) = value; } ulong getpage(ulong virt) { assert(!(virt % PAGE_SIZE)); invlpg(virt); #ifdef __ARCH_X86_64 if (virt >= HIGH_HALF_BOT) { virt -= NON_CANON_SIZE; } down(virt, PM_L4_LOC, 39); down(virt, PG_SWP_LOC, 30); down(virt, PG_SWP_LOC, 21); #else down(virt, PM_L2_LOC, 22); #endif return get_entry(virt, PG_SWP_LOC, 12); } void page_fault(ulong error, ulong cr2) { dputs("asdfaskdflaj\n"); for(;;); /*region * heap; region * stack; kprintf("cr2 = %p\n", cr2); if (error & ERROR_PRESENT) { fatal("Page protection fault (%x) at %p", error, cr2); } if (~error & ERROR_USER) { fatal("Kernel page fault (%x) at %p", error, cr2); } assert(~error & ERROR_PRESENT); heap = cur_thrd->parent->code; stack = cur_thrd->stack; cr2 = floor(cr2, PAGE_SIZE); if (!assure(stack, cr2, 7) && !assure(heap, cr2, 7)) { if (cr2 < LOW_HALF_TOP / 2) { // presume heap grow(heap, cr2); assure(heap, cr2, 7); } else { // presume stack grow(stack, cr2); assure(stack, cr2, 7); } } */ }
2.578125
3
2024-11-18T20:14:29.510333+00:00
2021-05-26T12:31:02
5aac8dd77969b844525b53a0dada6016fbd7ac76
{ "blob_id": "5aac8dd77969b844525b53a0dada6016fbd7ac76", "branch_name": "refs/heads/master", "committer_date": "2021-05-26T12:31:02", "content_id": "a760d747501dd01172be6b48aaea1888d6b4c457", "detected_licenses": [ "ISC" ], "directory_id": "61851bbf54b29b3b2502ca71acd864c7c2cdcc82", "extension": "h", "filename": "util.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 80364798, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 686, "license": "ISC", "license_type": "permissive", "path": "/uemu/src/util.h", "provenance": "stackv2-0049.json.gz:181031", "repo_name": "kukrimate/libefi", "revision_date": "2021-05-26T12:31:02", "revision_id": "53f623dbb518a3e86e25a6d398dd34ef06fe09ba", "snapshot_id": "d8aba8d95af7443a7ee2f79c2c83c7795ae12042", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/kukrimate/libefi/53f623dbb518a3e86e25a6d398dd34ef06fe09ba/uemu/src/util.h", "visit_date": "2023-05-08T14:46:40.781773" }
stackv2
// // Utility functions for EFI data structures // #ifndef UTIL_H #define UTIL_H // // Calculate the size of an array // #define ARRAY_SIZE(x) (sizeof(x) / sizeof(*x)) // // Compare two EFI strings // efi_ssize efi_strcmp(efi_ch16 *str1, efi_ch16 *str2); // // Compute the number of characters (excluding the NUL-terminator) in an EFI string // efi_size efi_strlen(efi_ch16 *str); // // Compute the size of an EFI string (including the NUL-terminator) in bytes // efi_size efi_strsize(efi_ch16 *str); // // Convert an EFI string to an ASCII string // char *efi_to_ascii(efi_ch16 *str); // // Convert an EFI GUID to an ASCII string // char *guid_to_ascii(efi_guid *guid); #endif
2.375
2
2024-11-18T20:14:29.621808+00:00
2022-05-11T19:12:04
a9ef4db0801991b6009b6cda67fc2b577df10cf0
{ "blob_id": "a9ef4db0801991b6009b6cda67fc2b577df10cf0", "branch_name": "refs/heads/master", "committer_date": "2022-05-11T19:12:04", "content_id": "e588359d1d70737fe52c4d4f9bf3fe427a885717", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "8fd935d0bcf03a176dc1c042602e731aab016f43", "extension": "c", "filename": "flann_example.c", "fork_events_count": 124, "gha_created_at": "2019-06-16T21:43:54", "gha_event_created_at": "2022-04-27T23:52:53", "gha_language": "C++", "gha_license_id": "BSD-3-Clause", "github_id": 192239549, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2374, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/libvis/third_party/flann/examples/flann_example.c", "provenance": "stackv2-0049.json.gz:181160", "repo_name": "ETH3D/badslam", "revision_date": "2022-05-11T19:12:04", "revision_id": "c66bdc841658cc04f9feae229c746b32f4284102", "snapshot_id": "9ce088d96672ee5385f721928d3e6536778e1574", "src_encoding": "UTF-8", "star_events_count": 691, "url": "https://raw.githubusercontent.com/ETH3D/badslam/c66bdc841658cc04f9feae229c746b32f4284102/libvis/third_party/flann/examples/flann_example.c", "visit_date": "2022-07-08T05:39:08.983448" }
stackv2
#include <flann/flann.h> #include <stdio.h> #include <stdlib.h> float* read_points(const char* filename, int rows, int cols) { float* data; float *p; FILE* fin; int i,j; fin = fopen(filename,"r"); if (!fin) { printf("Cannot open input file.\n"); exit(1); } data = (float*) malloc(rows*cols*sizeof(float)); if (!data) { printf("Cannot allocate memory.\n"); exit(1); } p = data; for (i=0;i<rows;++i) { for (j=0;j<cols;++j) { fscanf(fin,"%g ",p); p++; } } fclose(fin); return data; } void write_results(const char* filename, int *data, int rows, int cols) { FILE* fout; int* p; int i,j; fout = fopen(filename,"w"); if (!fout) { printf("Cannot open output file.\n"); exit(1); } p = data; for (i=0;i<rows;++i) { for (j=0;j<cols;++j) { fprintf(fout,"%d ",*p); p++; } fprintf(fout,"\n"); } fclose(fout); } int main(int argc, char** argv) { float* dataset; float* testset; int nn; int* result; float* dists; struct FLANNParameters p; float speedup; flann_index_t index_id; int rows = 9000; int cols = 128; int tcount = 1000; /* * The files dataset.dat and testset.dat can be downloaded from: * http://people.cs.ubc.ca/~mariusm/uploads/FLANN/datasets/dataset.dat * http://people.cs.ubc.ca/~mariusm/uploads/FLANN/datasets/testset.dat */ printf("Reading input data file.\n"); dataset = read_points("dataset.dat", rows, cols); printf("Reading test data file.\n"); testset = read_points("testset.dat", tcount, cols); nn = 3; result = (int*) malloc(tcount*nn*sizeof(int)); dists = (float*) malloc(tcount*nn*sizeof(float)); p = DEFAULT_FLANN_PARAMETERS; p.algorithm = FLANN_INDEX_KDTREE; p.trees = 8; p.log_level = FLANN_LOG_INFO; p.checks = 64; printf("Computing index.\n"); index_id = flann_build_index(dataset, rows, cols, &speedup, &p); flann_find_nearest_neighbors_index(index_id, testset, tcount, result, dists, nn, &p); write_results("results.dat",result, tcount, nn); flann_free_index(index_id, &p); free(dataset); free(testset); free(result); free(dists); return 0; }
2.671875
3
2024-11-18T20:14:30.368179+00:00
2020-12-13T11:20:32
5fbbff7a3cb7aad258026cde249c8e2f7b4ceedc
{ "blob_id": "5fbbff7a3cb7aad258026cde249c8e2f7b4ceedc", "branch_name": "refs/heads/master", "committer_date": "2020-12-13T11:20:32", "content_id": "7fd300545d77bb9d8bc6b39921ccfce248ec6d91", "detected_licenses": [ "MIT" ], "directory_id": "349933bfd961e1c5857e9f8aac078db4d0da7226", "extension": "c", "filename": "ft_processor.c", "fork_events_count": 0, "gha_created_at": "2020-07-02T15:13:40", "gha_event_created_at": "2020-12-13T11:20:34", "gha_language": "C", "gha_license_id": null, "github_id": 276678540, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1623, "license": "MIT", "license_type": "permissive", "path": "/processor/ft_processor.c", "provenance": "stackv2-0049.json.gz:182060", "repo_name": "k-allard/printf_implementation", "revision_date": "2020-12-13T11:20:32", "revision_id": "93c934c06cafe82cf77af1cad6cace88a2c83429", "snapshot_id": "f75d6aee184eb07e1723b76c7a9822dc1990f140", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/k-allard/printf_implementation/93c934c06cafe82cf77af1cad6cace88a2c83429/processor/ft_processor.c", "visit_date": "2023-02-03T00:32:55.509066" }
stackv2
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_processor.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kallard <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/07/11 11:05:00 by kallard #+# #+# */ /* Updated: 2020/07/18 13:41:41 by kallard ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/ft_processor.h" t_ok ft_processor(va_list *argptr, t_format *argformat, int *count) { if (argformat->type == d || argformat->type == i) return (ft_int_type(argptr, argformat, count)); if (argformat->type == s) return (ft_string_type(argptr, argformat, count)); if (argformat->type == percent) return (ft_percent_type(argformat, count)); if (argformat->type == c) return (ft_char_type(argptr, argformat, count)); if (argformat->type == u) return (ft_un_int_type(argptr, argformat, count)); if (argformat->type == x || argformat->type == X) return (ft_un_xx_type(argptr, argformat, count)); if (argformat->type == p) return (ft_pointer_type(argptr, argformat, count)); return (ERROR); }
2.1875
2
2024-11-18T20:14:31.239065+00:00
2016-02-24T06:00:26
7d411444f2437e10de55d1553196a0f440ea23fb
{ "blob_id": "7d411444f2437e10de55d1553196a0f440ea23fb", "branch_name": "refs/heads/master", "committer_date": "2016-02-24T06:00:26", "content_id": "d30a166904bacc6e97cff7f41cc42115a5bfdfea", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "cdf41df24c29b0766ab22ac537a0e6350c3643ee", "extension": "c", "filename": "phonebook_opt.c", "fork_events_count": 2, "gha_created_at": "2015-10-01T03:05:11", "gha_event_created_at": "2016-04-01T07:27:35", "gha_language": "C", "gha_license_id": null, "github_id": 43475712, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2329, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/phonebook_opt.c", "provenance": "stackv2-0049.json.gz:182446", "repo_name": "tony0620emma/phonebook", "revision_date": "2016-02-24T06:00:26", "revision_id": "cc14efa7a12b84a9979f656d4bf8338d98b13e9d", "snapshot_id": "05b25ed6fc1ea304a281fb8712ac4e923a7c11ac", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/tony0620emma/phonebook/cc14efa7a12b84a9979f656d4bf8338d98b13e9d/phonebook_opt.c", "visit_date": "2020-12-11T04:03:03.370929" }
stackv2
#include <stdlib.h> #include <string.h> #include <math.h> #include "phonebook_opt.h" HashTable *createHashTable(int size) { if (size < 1) return NULL; HashTable *ht = malloc(sizeof(HashTable)); ht->size = size; ht->storage = calloc(size, sizeof(entry *)); return ht; } void freeHashTable(HashTable *ht) { int i = 0; for (i = 0; i < ht->size; i++) { entry *cur; if ((cur = ht->storage[i])) { do { entry *e = cur; cur = e->pNext; free(e); } while (cur); } } free(ht->storage); free(ht); } int *getHashKey(char *s, int size, int *key) { if (!s) return NULL; int hash, i, val; for (hash = 0, i = 0, val = 1; *s != '\0'; i++, s++) { hash = (hash<<4) ^ (hash>>28) ^ *s; val = val * 31 + (*s - 'a'); } /* index 0 for the key * index 1 for the value * so we don't need strcpy */ key[0] = abs(hash % size); key[1] = val; return key; } char *valuetoName(int val, char *Name) { int c, i = 0; while (val != 1) { c = val % 31; val = (val - c) / 31; Name[i++] = c + 'a'; } Name[i] = '\0'; int j = 0, temp; for (j = 0, --i; i > j; i--, j++) { temp = Name[i]; Name[i] = Name[j]; Name[j] = temp; } return Name; } entry *findName(HashTable *ht, char lastName[]) { int *key = malloc(sizeof(int) * 2); key = getHashKey(lastName, ht->size, key); if (key[0] == -1) return NULL; entry *e; if ((e = ht->storage[key[0]])) { do { if (key[1] == e->lastNameValue) { free(key); return e; } e = e->pNext; } while (e); } return NULL; } entry *append(HashTable *ht, char lastName[], int *key) { key = getHashKey(lastName, ht->size, key); if (key[0] == -1) return NULL; entry *e; if (ht->storage[key[0]]) { e = malloc(sizeof(entry)); e->lastNameValue = key[1]; e->pNext = ht->storage[key[0]]; ht->storage[key[0]] = e; return e; } else { e = malloc(sizeof(entry)); e->lastNameValue = key[1]; e->pNext = NULL; ht->storage[key[0]] = e; return e; } }
3.03125
3
2024-11-18T18:58:18.199657+00:00
2019-12-09T14:50:56
b1df2877d86f21bc0493db355995ca6f9614b153
{ "blob_id": "b1df2877d86f21bc0493db355995ca6f9614b153", "branch_name": "refs/heads/master", "committer_date": "2019-12-09T14:50:56", "content_id": "431e3cba7e629ec00790e15a4a4c8f1f9b87e508", "detected_licenses": [ "MIT" ], "directory_id": "2369613cde60ae9106fa90d2c662b8e77cbc6eb6", "extension": "h", "filename": "aux.h", "fork_events_count": 0, "gha_created_at": "2019-12-09T14:49:01", "gha_event_created_at": "2019-12-09T14:49:02", "gha_language": null, "gha_license_id": "MIT", "github_id": 226895610, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1202, "license": "MIT", "license_type": "permissive", "path": "/src/aux.h", "provenance": "stackv2-0052.json.gz:207357", "repo_name": "gnyman/snidump", "revision_date": "2019-12-09T14:50:56", "revision_id": "e6b2f9027bb8110889706f8fac0e0ec3801eb716", "snapshot_id": "fc6275d4f861c4a1ddc629a2bf325ecdb367b66f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gnyman/snidump/e6b2f9027bb8110889706f8fac0e0ec3801eb716/src/aux.h", "visit_date": "2020-09-28T23:50:05.449449" }
stackv2
#ifndef __AUX_H__ #define __AUX_H__ /* kontaxis 2015-10-31 */ #include <string.h> #include <limits.h> struct read_bytes_ctx { /* Buffer holding data to be read. */ void *in; /* MUST be set to the exact number of bytes available in the 'in' buffer * BEFORE the first call to read_bytes() is moade. */ size_t read_bytes_available; }; /* * Copies exactly 'must_read_bytes' bytes from 'ctx->in' to 'out' or fails. * * If 'out' is NULL nothing is copied but the read_bytes_available variable * is incremented by must_read_bytes bytes. * * Returns number of bytes copied. * - 'must_read_bytes' bytes indicate success. * - 0 bytes indicate failure. */ size_t read_bytes(struct read_bytes_ctx *ctx, void *out, size_t must_read_bytes) { if (!ctx) { return 0; } if (ctx->read_bytes_available < must_read_bytes) { return 0; } /* Reading must_read_bytes will cause an address overflow. */ if (~((size_t)0x0) - (size_t) ctx->in < must_read_bytes) { return 0; } if (out != NULL) { memcpy(out, ctx->in, must_read_bytes); } ctx->in = ((uint8_t *) ctx->in) + must_read_bytes; ctx->read_bytes_available -= must_read_bytes; return must_read_bytes; } #endif
2.890625
3
2024-11-18T18:58:18.319821+00:00
2012-08-16T17:20:14
6a5c620dd66ef2862f8b82e370c8fff21799c3a9
{ "blob_id": "6a5c620dd66ef2862f8b82e370c8fff21799c3a9", "branch_name": "refs/heads/master", "committer_date": "2012-08-16T17:20:14", "content_id": "1d8fe36dce19cc1c027089f981502c4b935ca73f", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "a1e9ed98b785919ac763e405b8cdf9d2ba13398b", "extension": "c", "filename": "pwm.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 5253179, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11074, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/libMU_Demos/libMU/pwm/pwm.c", "provenance": "stackv2-0052.json.gz:207486", "repo_name": "josulf/Morsee", "revision_date": "2012-08-16T17:20:14", "revision_id": "969238df220cde895662640ddf70966933e6aeed", "snapshot_id": "9680c90692b237ac6725d253e7dbb8c7aa03bf17", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/josulf/Morsee/969238df220cde895662640ddf70966933e6aeed/libMU_Demos/libMU/pwm/pwm.c", "visit_date": "2020-04-06T03:39:45.151513" }
stackv2
/** * @addtogroup libMU_PWM * Library for easy access to the serial port * @{ ******************************************************************** * @author Eñaut Muxika <emuxika at mondragon dot edu> * @date 2011/7/10 * @copyright BSDL ******************************************************************** */ #include <inc/hw_types.h> // New data types #include <inc/hw_memmap.h> // Peripheral memory map #include <driverlib/sysctl.h> // System control functions #include <driverlib/gpio.h> // General Purpose IO functions #include <driverlib/pwm.h> // Pulse Width Modulation functions #include <libMU/pwm.h> /** * Configuration constants * pins - PF0/PWM0 (led), PG1/PWM1 (sound), PB0/PWM2, * PB1/PWM3, PE1/PWM4 (button), PE2/PWM5 (button) */ typedef struct _pwmc_t { uint32_t sysctl_periph, gpio_port, gpio_pin, gen_code, gen_bit, out_code, out_bit; } pwmc_t; static const pwmc_t PWMC[ LIBMU_PWM_5 + 1 ] = { { SYSCTL_PERIPH_GPIOF, GPIO_PORTF_BASE, GPIO_PIN_0, PWM_GEN_0, PWM_GEN_0_BIT, PWM_OUT_0, PWM_OUT_0_BIT }, { SYSCTL_PERIPH_GPIOG, GPIO_PORTG_BASE, GPIO_PIN_1, PWM_GEN_0, PWM_GEN_0_BIT, PWM_OUT_1, PWM_OUT_1_BIT }, { SYSCTL_PERIPH_GPIOB, GPIO_PORTB_BASE, GPIO_PIN_0, PWM_GEN_1, PWM_GEN_1_BIT, PWM_OUT_2, PWM_OUT_2_BIT }, { SYSCTL_PERIPH_GPIOB, GPIO_PORTB_BASE, GPIO_PIN_1, PWM_GEN_1, PWM_GEN_1_BIT, PWM_OUT_3, PWM_OUT_3_BIT }, { SYSCTL_PERIPH_GPIOE, GPIO_PORTE_BASE, GPIO_PIN_1, PWM_GEN_2, PWM_GEN_2_BIT, PWM_OUT_4, PWM_OUT_4_BIT }, { SYSCTL_PERIPH_GPIOE, GPIO_PORTE_BASE, GPIO_PIN_2, PWM_GEN_2, PWM_GEN_2_BIT, PWM_OUT_5, PWM_OUT_5_BIT } }; /** * PWM generator input frequency */ static uint32_t libMU_PWM_Freq; /** * Set-up PWM output * @param outputID Output identifier (single output) * @param freq Desired PWM frequency * @return 1 if error, 0 if ok * @note * The CPU frequency must be set before calling this function * Careful with specific outputs: * - PWM0 is connected to LED0 * - PWM1 is connected to the buzzer * - PWM4 is connected to up button input (Shortcircuit risk!!!) * - PWM5 is connected to down button input (Shortcircuit risk!!!) */ int libMU_PWM_InitializeOutput( libMU_PWM_Constants_t outputID, uint32_t freq ) { uint32_t cpu_freq = SysCtlClockGet(); uint32_t count = cpu_freq / freq; uint32_t div, div_code; for( div = 0; count > 0xFFFF; div++ ) count >>= 1; switch( div ) { case 0: div_code = SYSCTL_PWMDIV_1; break; case 1: div_code = SYSCTL_PWMDIV_2; break; case 2: div_code = SYSCTL_PWMDIV_4; break; case 3: div_code = SYSCTL_PWMDIV_8; break; case 4: div_code = SYSCTL_PWMDIV_16; break; case 5: div_code = SYSCTL_PWMDIV_32; break; case 6: div_code = SYSCTL_PWMDIV_64; break; default: return 1; // This frequency can not obtained } libMU_PWM_Freq = cpu_freq / (1<<div); switch( outputID ) { case LIBMU_PWM_0: SysCtlPWMClockSet ( div_code ); // Set the PWM clock to the system clock SysCtlPeripheralEnable ( SYSCTL_PERIPH_PWM ); // Enable PWM peripheral SysCtlPeripheralEnable ( SYSCTL_PERIPH_GPIOF );// Enable port for PWM pins & assign pins GPIOPinTypePWM ( GPIO_PORTF_BASE, GPIO_PIN_0 ); PWMGenConfigure ( PWM_BASE, PWM_GEN_0, PWM_GEN_MODE_DOWN ); //PWMSyncUpdate ( PWM_BASE, PWM_GEN_0_BIT ); PWMGenPeriodSet ( PWM_BASE, PWM_GEN_0, count ); PWMPulseWidthSet( PWM_BASE, PWM_OUT_0, (count>>1) );// Duty cycle %50 PWMOutputState ( PWM_BASE, PWM_OUT_0_BIT, true ); // Enable PWM0/PF0 PWMGenEnable ( PWM_BASE, PWM_GEN_0 ); // Enables PWM0 counter return 0; } if( outputID > LIBMU_PWM_5 ) return 1; SysCtlPeripheralEnable ( SYSCTL_PERIPH_PWM ); // Enable PWM peripheral SysCtlPWMClockSet ( div_code ); // Set the PWM clock to the system clock SysCtlPeripheralEnable ( PWMC[outputID].sysctl_periph );// Enable port for PWM pins GPIOPinTypePWM ( PWMC[outputID].gpio_port, PWMC[outputID].gpio_pin ); PWMGenConfigure ( PWM_BASE, PWMC[outputID].gen_code, PWM_GEN_MODE_DOWN ); //PWMSyncUpdate ( PWM_BASE, PWMC[outputID].gen_bit ); // Force PWM updates when counter reaches 0 PWMGenPeriodSet ( PWM_BASE, PWMC[outputID].gen_code, count ); PWMPulseWidthSet( PWM_BASE, PWMC[outputID].out_code, (count>>1) ); // Duty cycle %50 PWMOutputState ( PWM_BASE, PWMC[outputID].out_bit, true ); PWMGenEnable ( PWM_BASE, PWMC[outputID].gen_code ); // PWMSyncTimeBase ( PWM_BASE, PWM_GEN_0_BIT | PWM_GEN_1_BIT | PWM_GEN_2_BIT ); return 0; } /** * Set-up PWM output for chopper control with deadbands * @param groupId Output group identifier (single output) * @param freq Desired PWM frequency * @param deadband Required deadband time in ns * @return 1 if error, 0 if ok * @note * The CPU frequency must be set before calling this function * Careful with specific outputs: * - PWM_GRP_01 is connected to LED0 and Buzzer * - PWM_GRP_45 is connected to the up/down button inputs (Shortcircuit risk!!!) * - The generated deadband is between the two outputs of the group * - The maximum deadband is 4095*Tpwm; */ int libMU_PWM_InitializeChopperOutput( libMU_PWM_Constants_t groupId, uint32_t freq, uint32_t deadband ) { uint32_t cpu_freq = SysCtlClockGet(); uint32_t count = cpu_freq / freq; uint32_t pwm_freq, div, div_code; for( div = 0; count > 0xFFFF; div++ ) count >>= 1; switch( div ) { case 0: div_code = SYSCTL_PWMDIV_1; break; case 1: div_code = SYSCTL_PWMDIV_2; break; case 2: div_code = SYSCTL_PWMDIV_4; break; case 3: div_code = SYSCTL_PWMDIV_8; break; case 4: div_code = SYSCTL_PWMDIV_16; break; case 5: div_code = SYSCTL_PWMDIV_32; break; case 6: div_code = SYSCTL_PWMDIV_64; break; default: return 1; // This frequency can not obtained } pwm_freq = cpu_freq / (1<<div); libMU_PWM_Freq = cpu_freq / (1<<div); deadband = ((uint64_t)deadband * (uint64_t)pwm_freq) / 1000000000ull; // Convert microseconds to PWM clock ticks if( deadband >= 4096 ) { for(;;); // Error, it can not generate this dead band size } SysCtlPeripheralEnable ( SYSCTL_PERIPH_PWM ); // Enable PWM peripheral SysCtlPWMClockSet ( div_code ); // Set the PWM clock to the system clock switch( groupId ) { case LIBMU_PWM_GRP_01: SysCtlPeripheralEnable ( PWMC[0].sysctl_periph );// Enable port for PWM pins SysCtlPeripheralEnable ( PWMC[1].sysctl_periph );// Enable port for PWM pins GPIOPinTypePWM ( PWMC[0].gpio_port, PWMC[0].gpio_pin ); GPIOPinTypePWM ( PWMC[1].gpio_port, PWMC[1].gpio_pin ); PWMGenConfigure ( PWM_BASE, PWMC[0].gen_code, PWM_GEN_MODE_DOWN ); //PWMSyncUpdate ( PWM_BASE, PWMC[0].gen_bit ); // Force PWM updates when counter reaches 0 PWMGenPeriodSet ( PWM_BASE, PWMC[0].gen_code, count ); PWMPulseWidthSet( PWM_BASE, PWMC[0].out_code, (count>>1) ); // Duty cycle %50 PWMPulseWidthSet( PWM_BASE, PWMC[1].out_code, (count>>1) ); // Duty cycle %50 PWMOutputState ( PWM_BASE, PWMC[0].out_bit, true ); PWMOutputState ( PWM_BASE, PWMC[1].out_bit, true ); PWMDeadBandEnable(PWM_BASE, PWMC[0].gen_code, deadband, deadband ); PWMGenEnable ( PWM_BASE, PWMC[0].gen_code ); return 0; case LIBMU_PWM_GRP_23: SysCtlPeripheralEnable ( PWMC[2].sysctl_periph );// Enable port for PWM pins SysCtlPeripheralEnable ( PWMC[3].sysctl_periph );// Enable port for PWM pins GPIOPinTypePWM ( PWMC[2].gpio_port, PWMC[2].gpio_pin ); GPIOPinTypePWM ( PWMC[3].gpio_port, PWMC[3].gpio_pin ); PWMGenConfigure ( PWM_BASE, PWMC[2].gen_code, PWM_GEN_MODE_DOWN ); //PWMSyncUpdate ( PWM_BASE, PWMC[2].gen_bit ); // Force PWM updates when counter reaches 0 PWMGenPeriodSet ( PWM_BASE, PWMC[2].gen_code, count ); PWMPulseWidthSet( PWM_BASE, PWMC[2].out_code, (count>>1) ); // Duty cycle %50 PWMPulseWidthSet( PWM_BASE, PWMC[3].out_code, (count>>1) ); // Duty cycle %50 PWMOutputState ( PWM_BASE, PWMC[2].out_bit, true ); PWMOutputState ( PWM_BASE, PWMC[3].out_bit, true ); PWMDeadBandEnable(PWM_BASE, PWMC[2].gen_code, deadband, deadband ); PWMGenEnable ( PWM_BASE, PWMC[2].gen_code ); return 0; case LIBMU_PWM_GRP_45: SysCtlPeripheralEnable ( PWMC[4].sysctl_periph );// Enable port for PWM pins SysCtlPeripheralEnable ( PWMC[5].sysctl_periph );// Enable port for PWM pins GPIOPinTypePWM ( PWMC[4].gpio_port, PWMC[4].gpio_pin ); GPIOPinTypePWM ( PWMC[5].gpio_port, PWMC[5].gpio_pin ); PWMGenConfigure ( PWM_BASE, PWMC[4].gen_code, PWM_GEN_MODE_DOWN ); //PWMSyncUpdate ( PWM_BASE, PWMC[4].gen_bit ); // Force PWM updates when counter reaches 0 PWMGenPeriodSet ( PWM_BASE, PWMC[4].gen_code, count ); PWMPulseWidthSet( PWM_BASE, PWMC[4].out_code, (count>>1) ); // Duty cycle %50 PWMPulseWidthSet( PWM_BASE, PWMC[5].out_code, (count>>1) ); // Duty cycle %50 PWMOutputState ( PWM_BASE, PWMC[4].out_bit, true ); PWMOutputState ( PWM_BASE, PWMC[5].out_bit, true ); PWMDeadBandEnable(PWM_BASE, PWMC[4].gen_code, deadband, deadband ); PWMGenEnable ( PWM_BASE, PWMC[4].gen_code ); return 0; } PWMSyncTimeBase ( PWM_BASE, PWM_GEN_0_BIT | PWM_GEN_1_BIT | PWM_GEN_2_BIT ); return 1; } /** * Set-up PWM output pulse width * @param outId Output identifier (single output) * @param pulsewidth In hundreds of a percentage: 0 -> 0.00%, 10000 -> 100.00%, 4567 -> 45.67% * @note * The resolution may be better or worse than 0.1% depending on cpu and pwm frequency */ void libMU_PWM_SetPulseWidth( libMU_PWM_Constants_t outId, uint32_t pulsewidth ) { pulsewidth = ( pulsewidth * PWMGenPeriodGet( PWM_BASE, PWMC[outId].gen_code ) ) / 10000; if( pulsewidth == 0 ) pulsewidth = 1; PWMPulseWidthSet( PWM_BASE, PWMC[outId].out_code, pulsewidth ); } /** * Set-up PWM output frequency * @param outId Output identifier (single output) * @param freq In Hz * @note * The resolution may be quite bad */ void libMU_PWM_SetFrequency( libMU_PWM_Constants_t outId, uint32_t freq ) { uint32_t period = libMU_PWM_Freq / freq; PWMGenPeriodSet( PWM_BASE, PWMC[outId].gen_code, period ); } /** * Get PWM generator period in internal ticks * @param outId Output identifier (single output) * @return PWM Generator period */ uint32_t libMU_PWM_GetPeriodIU( libMU_PWM_Constants_t outId ) { return PWMGenPeriodGet( PWM_BASE, PWMC[outId].gen_code ); } /** * Get PWM output pulse width in internal ticks * @param outId Output identifier (single output) * @return PWM pulse width */ uint32_t libMU_PWM_GetPulseWidthIU( libMU_PWM_Constants_t outId ) { return PWMPulseWidthGet( PWM_BASE, PWMC[outId].out_code ); } /** * Disable PWM output * @param outId Output identifier (single output) */ void libMU_PWM_OutputDisable( libMU_PWM_Constants_t outId ) { PWMOutputState( PWM_BASE, PWMC[outId].gen_code, false ); } /** * Enable PWM output * @param outId Output identifier (single output) */ void libMU_PWM_OutputEnable( libMU_PWM_Constants_t outId ) { PWMOutputState( PWM_BASE, PWMC[outId].gen_code, true ); } /** * @} */
2.546875
3
2024-11-18T18:58:18.415977+00:00
2016-03-07T06:09:42
a8e732dcff5c0f7c1cd7ebbcf73d4837dc7b9e0c
{ "blob_id": "a8e732dcff5c0f7c1cd7ebbcf73d4837dc7b9e0c", "branch_name": "refs/heads/master", "committer_date": "2016-03-07T06:09:42", "content_id": "9814974a7d4e181012128e4243c8129af740b8a4", "detected_licenses": [ "Apache-2.0" ], "directory_id": "fd254058ca64486706ee0238ecd526c4edef9f0b", "extension": "c", "filename": "ecalloc.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": 5475, "license": "Apache-2.0", "license_type": "permissive", "path": "/ecalloc.c", "provenance": "stackv2-0052.json.gz:207615", "repo_name": "mkvoya/cocytus", "revision_date": "2016-03-07T06:09:42", "revision_id": "63efa53280a112373ee3b6f4757e82b9fd18dd68", "snapshot_id": "819f07a84f01d2f0019995cb583e8e68c57e1b26", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mkvoya/cocytus/63efa53280a112373ee3b6f4757e82b9fd18dd68/ecalloc.c", "visit_date": "2021-05-31T05:02:29.140528" }
stackv2
/* * The code is part of the Cocytus project * * Copyright (C) 2016 Institute of Parallel and Distributed Systems (IPADS), Shanghai Jiao Tong University * All rights reserved. * * 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. * * For more about this software, visit: http://ipads.se.sjtu.edu.cn/pub/projects/cocytus * */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <inttypes.h> #include "const.h" #include "ecalloc.h" static void move_item(void *item, struct avlnode *src, struct avlnode *des) { ((struct ecalloc_header *)item)->node = des; return; } static int32_t addr_compare(void *l, void *r) { uint64_t left = ((struct ecalloc_header *)l)->addr; uint64_t right = ((struct ecalloc_header *)r)->addr; if (left < right) { return -1; } else if (left == right) { return 0; } else { return 1; } } static int32_t size_compare(void *l, void *r) { uint64_t left = ((struct ecalloc_header*)l)->size; uint64_t right = ((struct ecalloc_header *)r)->size; if (left < right) { return -1; } else if (left == right) { return 0; } else { return 1; } } void ecalloc_init(struct ecalloc *ecalloc, uint64_t size) { struct ecalloc_header *header; avl_init(&ecalloc->free_tree, size_compare, move_item); avl_init(&ecalloc->used_tree, addr_compare, move_item); ecalloc->size = size; ecalloc->used = 0; header = safe_malloc(sizeof(struct ecalloc_header)); header->addr = 0; header->size = size; header->flag = 0; header->prev = NULL; header->next = NULL; header->node = avl_insert(&ecalloc->free_tree, header); pthread_mutex_init(&ecalloc->mutex, NULL); } void ec_free(struct ecalloc *ecalloc, ADDR addr) { struct ecalloc_header *header; struct ecalloc_header tmp; pthread_mutex_lock(&ecalloc->mutex); // find in used tree, free the node tmp.addr = addr; header = avl_remove(&ecalloc->used_tree, (void *)&tmp); if (!header) { printf("free a wrong addr %ld\n", addr); exit(-1); } else { ecalloc->used -= header->size; header->flag &= ~USING; } /* Combine neighbor behind */ while (1) { struct ecalloc_header *next = header->next; /* If the next is in using, break */ if (!next || next->flag & USING) break; assert(next->addr == header->addr + header->size); /* combine the two */ header->size += next->size; header->next = next->next; if (header->next) header->next->prev = header; /* clean the next */ avl_remove_node(&ecalloc->free_tree, next->node); free(next); } /* Combine neighbor front */ while (1) { struct ecalloc_header *prev = header->prev; /* If the next is in using, break */ if (!prev || prev->flag & USING) break; assert(prev->addr + prev->size == header->addr); /* combine the two */ header->size += prev->size; header->addr = prev->addr; header->prev = prev->prev; if (header->prev) header->prev->next = header; /* clean the next */ avl_remove_node(&ecalloc->free_tree, prev->node); free(prev); } header->node = avl_insert(&ecalloc->free_tree, header); pthread_mutex_unlock(&ecalloc->mutex); } // return 0 if check is passed int ec_check(struct ecalloc *ecalloc, ADDR addr, uint64_t size) { struct avlnode *node; struct ecalloc_header *header; struct ecalloc_header tmp; tmp.addr = addr; node = avl_search(&ecalloc->used_tree, (void *)&tmp); if (!node) return -1; header = node->item; if (!header) { return -1; } else { if ((header->flag & USING) == 0) return -2; //if (header->size != size) return -3; } return 0; } ADDR ec_alloc(struct ecalloc *ecalloc, uint64_t size) { ADDR ret; struct avlnode *node; struct ecalloc_header *header, *newer; struct ecalloc_header tmp; pthread_mutex_lock(&ecalloc->mutex); size = (size + 15) & (~15); ret = -1; /** * Find the node containing enough space. */ tmp.size = size; node = avl_search_close(&ecalloc->free_tree, (void *)&tmp); if (!node) { perror("ec_alloc has no enough space"); exit(-1); } header = (struct ecalloc_header *)node->item; if (header->size < size && node->next) { node = node->next; header = (struct ecalloc_header *)node->item; } if (header->size < size) { perror("ec_alloc has no enough space"); exit(-1); } else { ret = header->addr; ecalloc->used += size; } /** * Split the node into used and free */ avl_remove_node(&ecalloc->free_tree, node); if (header->size > size) { newer = safe_malloc(sizeof(struct ecalloc_header)); newer->addr = header->addr; newer->size = size; newer->flag = USING; newer->node = avl_insert(&ecalloc->used_tree, newer); newer->next = header; newer->prev = header->prev; if (newer->prev) { newer->prev->next = newer; } header->prev = newer; header->addr += size; header->size -= size; header->node = avl_insert(&ecalloc->free_tree, header); } else { header->flag = USING; header->node = avl_insert(&ecalloc->used_tree, header); } pthread_mutex_unlock(&ecalloc->mutex); return ret; }
2.5
2
2024-11-18T18:58:23.479607+00:00
2020-12-17T13:39:26
9e5a4bf16629f2a84a173321fe359cc7aaf32ac9
{ "blob_id": "9e5a4bf16629f2a84a173321fe359cc7aaf32ac9", "branch_name": "refs/heads/master", "committer_date": "2020-12-17T13:39:26", "content_id": "37b1fcbdc0634a872d406560ff1ebe525528d88c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "77af3b8dc0fccec2ca9ca215bd6c3e3cd6e9aaff", "extension": "c", "filename": "step1-wait-hello.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": 587, "license": "Apache-2.0", "license_type": "permissive", "path": "/flash/src/isp/drivers/step1-wait-hello.c", "provenance": "stackv2-0052.json.gz:207744", "repo_name": "cincui/k210-sd-dump", "revision_date": "2020-12-17T13:39:26", "revision_id": "365306746ae43fa966e023ad9d385c4bf71af9a5", "snapshot_id": "d083b33fd855e1eec76f69cb6db1ef5326ecb58e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cincui/k210-sd-dump/365306746ae43fa966e023ad9d385c4bf71af9a5/flash/src/isp/drivers/step1-wait-hello.c", "visit_date": "2023-01-30T22:33:18.125041" }
stackv2
volatile uint8_t lock_step1 = 1; #define JSON_TYPE_1 ("{\"type\":1,\"hello\":\"this is fast flash isp.\"}\n") static void core0_step1_wait_hello() { char* hello = repeat_malloc(JSON_TYPE_1); while (lock_step1) { repeat_printf(hello, JSON_TYPE_1); msleep(10); if (gpiohs_get_pin(PIN_BOOT) == GPIO_PV_HIGH) { lock_step1 = 0; } } } static void core1_step1_blink_led() { while (lock_step1) { gpiohs_set_pin(PIN_LED, GPIO_PV_LOW); msleep(120); gpiohs_set_pin(PIN_LED, GPIO_PV_HIGH); msleep(600); } gpiohs_set_pin(PIN_LED, GPIO_PV_HIGH); }
2.21875
2
2024-11-18T18:58:59.349638+00:00
2016-03-03T23:57:04
38c46b5d25bbe7a49707c371554ecedd4d5694f6
{ "blob_id": "38c46b5d25bbe7a49707c371554ecedd4d5694f6", "branch_name": "refs/heads/master", "committer_date": "2016-03-03T23:57:04", "content_id": "455860cf8ea7d52831e5984602a489d7dc1e1b27", "detected_licenses": [ "MIT" ], "directory_id": "481f7e4c28473e4c753394867e366b8601d3a2c6", "extension": "h", "filename": "stm32f030xx_uart_print.h", "fork_events_count": 0, "gha_created_at": "2019-06-09T13:47:58", "gha_event_created_at": "2019-06-09T13:47:58", "gha_language": null, "gha_license_id": "MIT", "github_id": 191011965, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2645, "license": "MIT", "license_type": "permissive", "path": "/UART/stm32f030xx_uart_print.h", "provenance": "stackv2-0052.json.gz:207872", "repo_name": "bluetronics-India/STM32F0-3", "revision_date": "2016-03-03T23:57:04", "revision_id": "eb8d60339d159a813ee086abc052efbb16b83ab8", "snapshot_id": "4674cc0bfcf5006db2b5952eeb049643bc7d3969", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/bluetronics-India/STM32F0-3/eb8d60339d159a813ee086abc052efbb16b83ab8/UART/stm32f030xx_uart_print.h", "visit_date": "2020-06-02T02:52:03.873261" }
stackv2
/* =============================================================================== ##### STM32F030XX-discovery board: UART specific communication ##### header file =============================================================================== * @date 4-Jan-2015 * @author Domen Jurkovic */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F030XX_UART_PRINT_H #define __STM32F030XX_UART_PRINT_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include <stm32f0xx.h> #include <stm32f0xx_usart.h> #include <stm32f0xx_rcc.h> #include <stm32f0xx_gpio.h> #include <stm32f0xx_exti.h> #include <stm32f0xx_syscfg.h> #include <stm32f0xx_misc.h> #include <stdio.h> #include <stdbool.h> #include <stdint.h> #include <string.h> #include <math.h> #include "stm32f0xx_gpio_init.h" //uint8_t base: #define DEC 10 #define BIN 2 #define HEX 16 #define OCT 8 /****************************************************************************************/ /* COMMUNICATION FUNCTIONS - change in .c file accordingly to your HW */ /****************************************************************************************/ // initialize UART void UART_Init(void); /* If RX interrupt is used, call void USARTx_IRQHandler(){ while(USART_GetITStatus(USARTx, USART_IT_RXNE) != RESET){ // Received characters added to fifo USART_ClearITPendingBit(USARTx, USART_IT_RXNE); received_data = USART_ReceiveData(USART1); // Receive the character } } */ uint32_t _send_byte(uint8_t byte); uint8_t _receive_byte(void); /****************************************************************************************/ /* PRINT/WRITE FUNCTIONS */ /****************************************************************************************/ //print WITHOUT new line and carriage return void printString(char *data); //send/print string overserial. void printNumber(int32_t number, uint8_t base); //send/print SINGED/UNSIGNED int32_t number void printFloat(double number); //print WITH new line and carriage return void printStringLn(char *data); //send/print string. void printNumberLn(int32_t number, uint8_t base); //send/print SINGED/UNSIGNED number. void printLn(void); //print new line and carriage return void printFloatLn(double number); //send raw data, any type. void writeData(void *data, uint8_t dataSize); //"private" function. Can be used if needed. void printUnsignedNumber(uint32_t n, uint8_t base); //send/print UNSIGNED uint32_t. #ifdef __cplusplus } #endif #endif /* __STM32F030XX_UART_PRINT_H */
2.3125
2
2024-11-18T18:58:59.596986+00:00
2021-01-19T00:51:09
d63f38375420b8fd9b6ee8815360013ea866d494
{ "blob_id": "d63f38375420b8fd9b6ee8815360013ea866d494", "branch_name": "refs/heads/master", "committer_date": "2021-01-19T00:51:09", "content_id": "238a9a9880010fcaa3f44072d198be114fcab764", "detected_licenses": [ "MIT" ], "directory_id": "55809aac9b4ed91acf4e6b17982496afcf7bee9e", "extension": "c", "filename": "a5.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 330823480, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8267, "license": "MIT", "license_type": "permissive", "path": "/a5.c", "provenance": "stackv2-0052.json.gz:208002", "repo_name": "LorandMezei/RGB-Color-Selector", "revision_date": "2021-01-19T00:51:09", "revision_id": "6f3ed4742974f1abd462ad9d2d1a18e573b8f9b8", "snapshot_id": "322b4f51b6d679d01b706351016e374a7616344d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/LorandMezei/RGB-Color-Selector/6f3ed4742974f1abd462ad9d2d1a18e573b8f9b8/a5.c", "visit_date": "2023-02-22T03:59:00.068642" }
stackv2
#include <msp430.h> #include <libemb/conio/conio.h> #include <libemb/serial/serial.h> #include "colors.h" // colors array #include "dtc.h" /****** * * CONSTANTS * ******/ // large number of data structures should be here // use `const` keyword //=================================== DIGIT 1 =========================================== //DLD1B1D* const char digit1_pattern1[] = { 0b00001000, 0b00001001, 0b00001000 }; const char digit1_pattern2[] = { 0b10101101, 0b00000100, 0b00000101 }; //***L**L* //R G B //======================================================================================= //=================================== DIGIT 2/3 ========================================= //DLD1B1D* const char digits23_pattern1[] = { 0b00001001, 0b00001001, 0b00001000, 0b00001000, 0b00001000, 0b00001000, 0b00001000, 0b00001001, 0b00001000, 0b00001000, 0b00001000, 0b00001000, 0b00001001, 0b00001000, 0b00001000, 0b00001000 }; const char digits23_pattern2[] = { 0b00000000, 0b11100001, 0b10001000, 0b11000000, 0b01100001, 0b01000100, 0b00000100, 0b11100000, 0b00000000, 0b01000000, 0b00100000, 0b00000101, 0b00001100, 0b10000001, 0b00001100, 0b00101100 }; //***L**L* // 0 1 2 3 4 5 6 7 8 9 A B C D E F //======================================================================================= /****** * * GLOBALS * ******/ // counters can go here //====================================== char cursor = 0; // which digit is it on // For choosing which led to change brightness for. int color_counter = 0; // For printing color to screen. int print_counter = 0; int red_print = 0; int green_print = 0; int blue_print = 0; int color_math = 0; //====================================== /******l * * INITIALIZATION * ******/ int main(void) { //--------------- DEFAULT --------------------- /* WIZARD WORDS ***************************/ WDTCTL = WDTPW | WDTHOLD; // Disable Watchdog BCSCTL1 = CALBC1_1MHZ; // Run @ 1MHz DCOCTL = CALDCO_1MHZ; //--------------------------------------------- //----------------- GPIO ----------------------- // pin initialization P1DIR = BIT7|BIT5|BIT1|BIT0; P2DIR = -1; P1OUT = BIT7|BIT5|BIT1; P2OUT = 0; // Use P2.6 and P2.7 as GPIO P2SEL &= ~(BIT6|BIT7); P2SEL2 &= ~(BIT6|BIT7); //--------------------------------------------- //------------ PRINTING ------------ // Call to allow printing to console serial_init(9600); // Set P1.1 back to regular GPIO P1SEL &= ~BIT1; P1SEL2 &= ~BIT1; //---------------------------------- //---------------- TIMER A0 ------------------- // timer 0 initialization TA0CTL = TASSEL_2|ID_0|MC_1; TA0CCTL0 = CCIE; TA0CCR0 = 1024; TA0CCTL1 = OUTMOD_7; P2SEL |= BIT1; P2SEL |= BIT4; P1SEL |= BIT6; //--------------------------------------------- //---------------- TIMER A1 ------------------- // timer 1 initialization TA1CTL = TASSEL_2|ID_3|MC_1; TA1CCTL0 = CCIE; TA1CCR0 = 1024; TA1CCTL1 = OUTMOD_7; TA1CCTL2 = OUTMOD_7; //--------------------------------------------- //------------ BUTTON INTERRUPT ------------ // Execute once, button stuff // // For old boards P1DIR = ~BIT3;//mov.b #~BIT3, &P1DIR P1REN = BIT3;//mov.b #BIT3, &P1REN P1OUT = BIT3;//mov.b #BIT3, &P1OUT // For interrupts P1IE |= BIT3;//bis.b #BIT3, &P1IE ; OR P1IES |= BIT3;//bis.b #BIT3, &P1IES P1IFG &= ~BIT3;//bic.b #BIT3, &P1IFG ; clear //------------------------------------------ //------------ ADC10CTL POTENTIOMETER ---------------------- initialize_dtc(INCH_4, &TA0CCR1); // or &TA1CCR1 or &TA1CCR2 // value in potentiometer is stored in TA0CCR1 // the brightness will be changed by the call to initialize_dtc() //---------------------------------------------------------- /****** * * MAIN LOOP (THERE ISN'T ONE) * ******/ //---------------- SLEEP-- -------------------- // go to sleep with interrupts enabled __bis_SR_register(LPM1_bits|GIE); //--------------------------------------------- // Do not put code past here // never return return 0; } /****** * * INTERRUPTS * ******/ #pragma vector=TIMER0_A0_VECTOR __interrupt void timer0 (void) // Timer Interrupt for the Display { //-------------------------- Potentiometer value changing -------------------------- // Turn potentiometer 10 bit value to 8 bit value int potentiometer_to_8bit; // potentiometer value in 8 bits // Potentiometer value for red led if (color_counter == 0) { potentiometer_to_8bit = TA0CCR1 >> 2; } // Potentiometer value for green led else if (color_counter == 1) { potentiometer_to_8bit = TA1CCR1 >> 2; } // Potentiometer value for blue led else if (color_counter == 2) { potentiometer_to_8bit = TA1CCR2 >> 2; } int bottom_4bit = potentiometer_to_8bit & 0b1111; // Mask to get 4 digits on right int top_4bit = potentiometer_to_8bit >> 4; // Right shift to get 4 digits on left //---------------------------------------------------------------------------------- //--------------- Turn off digits in 7-segment ----------------- // 1.) Turn off all digits P1OUT &= ~(BIT7|BIT5|BIT1); // bic.b BIT7|BIT5|BIT1 //-------------------------------------------------------------- //---------- Choose digit value in 7-segment -------------- // 2.) Configure segment pins for correct pattern. // If digit 1 if (cursor == 0) { P1OUT = digit1_pattern1[color_counter]; P2OUT = digit1_pattern2[color_counter]; } // If digit 2 else if (cursor == 1) { P1OUT = digits23_pattern1[top_4bit]; P2OUT = digits23_pattern2[top_4bit]; } // If digit 3 else { P1OUT = digits23_pattern1[bottom_4bit]; P2OUT = digits23_pattern2[bottom_4bit]; } //--------------------------------------------------------- //--------- Choose which digit is on in 7-segment ---------- // 3.) Turn on next digit (only 1 digit is on at a time) if (cursor == 0) { P1OUT |= BIT1; // bis.b BIT7 (P1.7) 3rd digit } else if (cursor == 1) { P1OUT |= BIT5; // bis.b BIT5 (P1.5) 2nd digit } else { P1OUT |= BIT7; // bis.b BIT1 (P1.1) 1st digit } //---------------------------------------------------------- //-------- Update digit counter --------- // move ahead cursor for next time cursor++; cursor %= 3; //--------------------------------------- //------------ Print color to console --------------- if (print_counter == 1000) { color_math = (blue_print << 6) + (green_print << 3) + red_print; cio_printf("%s\n\r", colors[color_math]); } print_counter++; // Print every 1 seconds. if (print_counter > 1000) { print_counter = 0; } //--------------------------------------------------- // 4.) leave the interrupt } #pragma vector=TIMER1_A0_VECTOR __interrupt void timer1 (void) // Timer interrupt for printing the color to the screen { //-------------------------------- // RED LED if (color_counter == 0) { red_print = TA0CCR1 >> 7; // Turn 10 bit to 3 bit } // GREEN LED else if (color_counter == 1) { green_print = TA1CCR1 >> 7; // Turn 10 bit to 3 bit } // BLUE LED else if (color_counter == 2) { blue_print = TA1CCR2 >> 7; } //--------------------------------- } #pragma vector=PORT1_VECTOR __interrupt void button (void) // Button Interrupt { //------------------------ color_counter++; if (color_counter > 2) { color_counter = 0; } //------------------------ //--------------------------------------- // Change red led if (color_counter == 0) { initialize_dtc(INCH_4, &TA0CCR1); } // Change green led else if (color_counter == 1) { initialize_dtc(INCH_4, &TA1CCR1); } // Change blue led else if (color_counter == 2) { initialize_dtc(INCH_4, &TA1CCR2); } //--------------------------------------- //------------------------------------------------------- // button debounce routine while (!(BIT3 & P1IN)) {} // is finger off of button yet? __delay_cycles(32000); // wait 32ms P1IFG &= ~BIT3; // clear interrupt flag //------------------------------------------------------- }
2.421875
2
2024-11-18T18:58:59.660574+00:00
2017-01-24T09:44:16
0f3fc26178bf10b45dc9950f39d9a51421a3e59b
{ "blob_id": "0f3fc26178bf10b45dc9950f39d9a51421a3e59b", "branch_name": "refs/heads/master", "committer_date": "2017-01-24T09:44:16", "content_id": "d19b82e2a925c34b7d42738a0116bfdcfdc9ab81", "detected_licenses": [ "MIT" ], "directory_id": "0c3f4042cddefcc67ab0c170fa69250ea6cd373b", "extension": "c", "filename": "http.c", "fork_events_count": 0, "gha_created_at": "2017-01-26T02:56:28", "gha_event_created_at": "2017-01-26T02:56:28", "gha_language": null, "gha_license_id": null, "github_id": 80080919, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3481, "license": "MIT", "license_type": "permissive", "path": "/source/http.c", "provenance": "stackv2-0052.json.gz:208131", "repo_name": "SirComet/PKSV", "revision_date": "2017-01-24T09:44:16", "revision_id": "90660ae7fa83f3b668f4ac700f4c016537926341", "snapshot_id": "a0b8d9300d939c1f7073b56ab74e1af5e58a486b", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/SirComet/PKSV/90660ae7fa83f3b668f4ac700f4c016537926341/source/http.c", "visit_date": "2021-01-11T16:25:24.611184" }
stackv2
/* This file is part of PKSV > MIT License > Copyright (c) 2016/17 Bernardo Giordano > > 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 <stdlib.h> #include <stdio.h> #include <string.h> #include <3ds.h> #include "http.h" #include "graphic.h" Result downloadFile(char* url, char* path) { httpcInit(0); httpcContext context; u32 statuscode = 0; u32 contentsize = 0; u8 *buf; if (httpcOpenContext(&context, HTTPC_METHOD_GET, url, 0)) { infoDisp("Failed to open http context!"); return -1; } if (httpcAddRequestHeaderField(&context, "User-Agent", "PKSV")) { infoDisp("Failed to add a request header field!"); return -1; } if (httpcSetSSLOpt(&context, SSLCOPT_DisableVerify)) { infoDisp("Failed to set SSLOpt!"); return -1; } httpcAddRequestHeaderField(&context, "Connection", "Keep-Alive"); if (httpcBeginRequest(&context)) { infoDisp("Failed to begin a http request!"); return -1; } if (httpcGetResponseStatusCode(&context, &statuscode)) { infoDisp("Failed to receive a status code!"); httpcCloseContext(&context); return -1; } if (statuscode != 200) { if (statuscode >= 300 && statuscode < 400) { char newUrl[1024]; if (httpcGetResponseHeader(&context, (char*)"Location", newUrl, 1024)) { infoDisp("Redirection failed!"); return -1; } httpcCloseContext(&context); downloadFile(newUrl, path); return -1; } else { infoDisp("Redirection failed!"); httpcCloseContext(&context); return -1; } } if (httpcGetDownloadSizeState(&context, NULL, &contentsize)) { infoDisp("Failed to receive download size!"); httpcCloseContext(&context); return -1; } buf = (u8*)malloc(contentsize); if (buf == NULL) { free(buf); infoDisp("Failed to alloc memory!"); return -1; } memset(buf, 0, contentsize); if (httpcDownloadData(&context, buf, contentsize, NULL)) { free(buf); infoDisp("Failed to download file!"); httpcCloseContext(&context); return -1; } remove(path); FILE *fptr = fopen(path, "wb"); fwrite(buf, 1, contentsize, fptr); fclose(fptr); free(buf); httpcCloseContext(&context); httpcExit(); return 0; }
2.109375
2
2024-11-18T18:58:59.757157+00:00
2018-07-25T16:16:39
36c582522a829fa179f16410048d7c77754fbdfc
{ "blob_id": "36c582522a829fa179f16410048d7c77754fbdfc", "branch_name": "refs/heads/master", "committer_date": "2018-07-25T16:16:39", "content_id": "66fcdf9e1a9cdfd2ecd0fd91163e70ba8ba87393", "detected_licenses": [ "MIT" ], "directory_id": "2908554e58449bc16be9d846022c77325714399d", "extension": "c", "filename": "rct_client.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 142314535, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1717, "license": "MIT", "license_type": "permissive", "path": "/rct_client.c", "provenance": "stackv2-0052.json.gz:208261", "repo_name": "bryandario8/RCT", "revision_date": "2018-07-25T16:16:39", "revision_id": "72d5f6b193da54927a479a08e8b04dfebc32d2e3", "snapshot_id": "c81557e309bc7f74496e8581c72c51fb36fd4045", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bryandario8/RCT/72d5f6b193da54927a479a08e8b04dfebc32d2e3/rct_client.c", "visit_date": "2020-03-24T00:55:36.088881" }
stackv2
/* * This is sample code generated by rpcgen. * These are only templates and you can use them * as a guideline for developing your own functions. */ #include "rct.h" #include <time.h> void rct_servicio_1(char *host, char *nombre, char *mensaje) { CLIENT *clnt; int *result_1; char * obtener_id_1_arg; long *result_2; char *bindate_1_arg; char * *result_3; char * obtener_respuesta_1_arg; struct tm *tm; char fecha_hora[100]; #ifndef DEBUG clnt = clnt_create (host, RCT_SERVICIO, RCT_VERS, "udp"); if (clnt == NULL) { clnt_pcreateerror (host); exit (1); } #endif /* DEBUG */ obtener_id_1_arg = nombre; result_1 = obtener_id_1(&obtener_id_1_arg, clnt); if (result_1 == (int *) NULL) { clnt_perror (clnt, "call failed"); } else { printf("Id: %d\n", *result_1 ); } //*bindate_1_arg = NULL; result_2 = bindate_1((void*)&bindate_1_arg, clnt); if (result_2 == (long *) NULL) { clnt_perror (clnt, "call failed"); } else { //Hace la conversión del time_t generado en el servidor tm = localtime(result_2); strftime(fecha_hora, 100, "%d/%m/%Y %H:%M:%S %z", tm); // formato: dia/mes/año hora/minutos/segundos uso_horario printf("Fecha de envío: %s\n", fecha_hora ); } obtener_respuesta_1_arg = mensaje; result_3 = obtener_respuesta_1(&obtener_respuesta_1_arg, clnt); if (result_3 == (char **) NULL) { clnt_perror (clnt, "call failed"); } else { printf("Mensaje: %s\n", *result_3 ); } #ifndef DEBUG clnt_destroy (clnt); #endif /* DEBUG */ } int main (int argc, char *argv[]) { char *host; if (argc < 4) { printf ("usage: %s server_host nombre mensaje\n", argv[0]); exit (1); } host = argv[1]; rct_servicio_1 (host, argv[2], argv[3]); exit (0); }
2.796875
3
2024-11-18T18:58:59.850416+00:00
2014-08-22T23:00:04
4634dd3fe7e4c0350aaec07b6312c4315cfb4ad9
{ "blob_id": "4634dd3fe7e4c0350aaec07b6312c4315cfb4ad9", "branch_name": "refs/heads/master", "committer_date": "2014-08-22T23:00:04", "content_id": "40f7668aa1822a535dc1d203d1cc470c8ffcef92", "detected_licenses": [ "Zlib" ], "directory_id": "3b9a6aabfa5490346a6275f085b1e76008f814ae", "extension": "c", "filename": "particles.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": 5376, "license": "Zlib", "license_type": "permissive", "path": "/particles.c", "provenance": "stackv2-0052.json.gz:208390", "repo_name": "kevinmel2000/particles-3DS", "revision_date": "2014-08-22T23:00:04", "revision_id": "e2526d5f2e795fcd3e5f720a6d6df066ea87c81e", "snapshot_id": "e482f5e9a2ed90e92e4ad42ca1006d5979f8132a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kevinmel2000/particles-3DS/e2526d5f2e795fcd3e5f720a6d6df066ea87c81e/particles.c", "visit_date": "2021-01-18T12:48:35.574121" }
stackv2
/* 3DS Particle Demo Copyright (C) 2014 Joseph LoManto This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "particles.h" #include "LCD.h" #include <ctr/svc.h> #include "HIDex.h" #include <math.h> #include <stdlib.h> #include "draw.h" Particle particles[MAX_PARTICLES]; ParticleProperties particleProperties = { {80.0f,120.0f}, 0, 1, 255,255,255, 1, }; Vector gravityForce = {0.0f,-0.08f}; extern u8* gspHeap; void init_all_particles() { int i; for(i = 0; i < MAX_PARTICLES; i++) { restart_particle(&particles[i]); } } void update_particle(Particle* p,u8 paused) { if(p->lifetime > 0) { //reduce lifetime p->lifetime--; //apply gravity if(particleProperties.gravity) vec_add(&p->speed,&p->speed,&gravityForce); //move particle vec_add(&p->pos,&p->pos,&p->speed); } else if(!paused) { //restart when lifetime == 0 restart_particle(p); } } void draw_particle(Particle* p) { if(p->lifetime == 0) return; //draw particle int x,y,size; x = (int)p->pos.x; y = (int)p->pos.y; size = particleProperties.size; y = MAIN_SCREEN_HEIGHT-y; if(x<0 || y<0 || x+size>=MAIN_SCREEN_WIDTH || y+size>=MAIN_SCREEN_HEIGHT) return; draw_fillrect( x, y ,x+size-1, y+size-1, particleProperties.r, particleProperties.g, particleProperties.b, gspHeap); } void restart_particle(Particle* p) { p->lifetime = (rand() % 100) + 1; float x,y; x = particleProperties.pos.x + rand()%16; y = particleProperties.pos.y + rand()%16; vec_set(&p->pos,x,y); float ct,st; float theta = particleProperties.dir + (float)(rand() % 100)/100 - 0.5f; ct = cosf(theta)*4; st = sinf(theta)*4; vec_set(&p->speed,ct,st); } void update_all_particles(vu8* paused) { int i; for(i = 0; i < MAX_PARTICLES; i++) { update_particle(&particles[i],*paused); draw_particle(&particles[i]); } } /*static void update_all_particles_maybe_draw(vu8* dontrestart) { int i; for(i = 0; i < MAX_PARTICLES; i++) { update_particle(&particles[i]); draw_particle(&particles[i]); } }*/ void draw_all_particles() { int i; for(i = 0; i < MAX_PARTICLES; i++) { draw_particle(&particles[i]); } } u32 ptStack[THREAD_STACKSIZE]; vThread pThread; void init_thread(vThread* t) { t->thread = 0; t->request_pause = 0; t->is_paused = 0; t->request_exit = 0; t->is_exitted = 0; } Result create_particles_thread() { init_thread(&pThread); return svc_createThread( (Handle*)&pThread.thread, particles_thread, (u32)&pThread, &ptStack[THREAD_STACKSIZE], 0x3f, ~1 ); } void particles_thread(u32 info) { vThread* pt = (vThread*)info; while(1) { if(pt->request_exit) { pt->is_exitted = 1; svc_exitThread(); return; } else { if(pt->request_pause) { pt->is_paused = 1; } else { pt->is_paused = 0; } update_all_particles(&pt->request_pause); svc_sleepThread(1000); } } } static void particle_properties_update_move() { //move particle source u32 pad = REG_PAD_STATE; if(pad & PAD_LEFT) { particleProperties.pos.x -= PARTICLE_SOURCE_SPEED; } if(pad & PAD_RIGHT) { particleProperties.pos.x += PARTICLE_SOURCE_SPEED; } if(pad & PAD_DOWN) { particleProperties.pos.y -= PARTICLE_SOURCE_SPEED; } if(pad & PAD_UP) { particleProperties.pos.y += PARTICLE_SOURCE_SPEED; } } static void particle_properties_update_direction() { vCirclePadInfo* cpad = REG_CPAD_INFO; float distance = sqrt((float)(cpad->x*cpad->x + cpad->y*cpad->y)); if(distance >= 48) { float direction = atan2f((float)cpad->y/distance,(float)cpad->x/distance); particleProperties.dir = direction; } } static u32 prevpad = 0; static void particle_properties_update_size() { u32 pad = REG_PAD_STATE; if((pad & PAD_A) && !(prevpad & PAD_A)) { particleProperties.size++; } if((pad & PAD_B) && !(prevpad & PAD_B)) { particleProperties.size--; } if(particleProperties.size < 1) particleProperties.size = 1; else if(particleProperties.size > 64) particleProperties.size = 64; } static void particle_properties_update_gravity() { u32 pad = REG_PAD_STATE; if((pad & PAD_X) && !(prevpad & PAD_X)) { particleProperties.gravity ^= 1; } } static void particle_properties_update_toggle_paused() { u32 pad = REG_PAD_STATE; if((pad & PAD_START) && !(prevpad & PAD_START)) { pThread.request_pause ^= 1; } } void particle_properties_update() { particle_properties_update_move(); particle_properties_update_direction(); particle_properties_update_size(); particle_properties_update_gravity(); particle_properties_update_toggle_paused(); prevpad = REG_PAD_STATE; }
2.515625
3
2024-11-18T19:34:54.489683+00:00
2023-07-26T12:59:16
99161fd00738c134d2c5cae4766eec101d6c9219
{ "blob_id": "99161fd00738c134d2c5cae4766eec101d6c9219", "branch_name": "refs/heads/master", "committer_date": "2023-07-26T12:59:16", "content_id": "5eedb29f86da7813be977bf63d87acb05623aad4", "detected_licenses": [ "MIT" ], "directory_id": "d9921707bc5a8c4f5fafc9788e8a8b1d1a41088e", "extension": "c", "filename": "track.c", "fork_events_count": 7, "gha_created_at": "2013-06-29T14:43:13", "gha_event_created_at": "2017-09-02T14:18:52", "gha_language": "C", "gha_license_id": null, "github_id": 11053920, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 665, "license": "MIT", "license_type": "permissive", "path": "/test/track.c", "provenance": "stackv2-0054.json.gz:101", "repo_name": "detomon/BlipKit", "revision_date": "2023-07-26T12:59:16", "revision_id": "ee14dcdef20ec1f76c0e9230d50dfe7e912200b5", "snapshot_id": "960b9759281ac2978e7d21594aa3592fcf9562ae", "src_encoding": "UTF-8", "star_events_count": 30, "url": "https://raw.githubusercontent.com/detomon/BlipKit/ee14dcdef20ec1f76c0e9230d50dfe7e912200b5/test/track.c", "visit_date": "2023-08-13T11:21:16.265604" }
stackv2
#include "test.h" int main (int argc, char const * argv []) { BKInt res; BKTrack * track = INVALID_PTR; // check for allocation res = BKTrackAlloc (& track, BK_SQUARE); assert (res == 0); assert (track != INVALID_PTR && track != NULL); BKDispose (track); // check for init values res = BKTrackAlloc (& track, -345876); assert (track -> waveform == 0); // check for allocation BKContext * ctx = INVALID_PTR; res = BKContextAlloc (& ctx, 2, 44100); assert (res == 0); res = BKTrackAttach (track, ctx); assert (res == 0); BKTrackDetach (track); assert (track -> unit.ctx == NULL); BKDispose (track); BKDispose (ctx); return 0; }
2.203125
2
2024-11-18T19:34:54.538779+00:00
2022-04-02T14:14:48
8a590fdf3c8bd7acc95fb83066888cd8b0a04771
{ "blob_id": "8a590fdf3c8bd7acc95fb83066888cd8b0a04771", "branch_name": "refs/heads/master", "committer_date": "2022-04-02T14:14:48", "content_id": "0cb5b100b3747071f62767381c5abc650297e705", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause" ], "directory_id": "3d88508d70d060ded2b0747bf5d9bc0e000339e8", "extension": "c", "filename": "tc_signal.c", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 168486342, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 774, "license": "BSD-2-Clause,BSD-3-Clause", "license_type": "permissive", "path": "/reading-code-of-nginx-1.9.2-master/nginx-1.9.2/高并发测试工具/tcpburn-master/tcpburn-master/src/core/tc_signal.c", "provenance": "stackv2-0054.json.gz:229", "repo_name": "zengrixi/architecture", "revision_date": "2022-04-02T14:14:48", "revision_id": "b9f40240e79df3ec93e98b6a4b00e84f01dd21f9", "snapshot_id": "2820f99b6fcda2f2beb328a458ca52558a320f3a", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/zengrixi/architecture/b9f40240e79df3ec93e98b6a4b00e84f01dd21f9/reading-code-of-nginx-1.9.2-master/nginx-1.9.2/高并发测试工具/tcpburn-master/tcpburn-master/src/core/tc_signal.c", "visit_date": "2022-04-26T06:26:26.294615" }
stackv2
 #include <xcopy.h> int sigignore(int sig) { struct sigaction sa; sa.sa_handler = SIG_IGN; sa.sa_flags = 0; if (sigemptyset(&sa.sa_mask) == -1 || sigaction(sig, &sa, 0) == -1) { return -1; } return 0; } int set_signal_handler(signal_t *signals) { int status; signal_t *sig; struct sigaction sa; for (sig = signals; sig->signo != 0; sig++) { memset(&sa, 0, sizeof(sa)); sa.sa_handler = sig->handler; sa.sa_flags = sig->flags; sigemptyset(&sa.sa_mask); status = sigaction(sig->signo, &sa, NULL); if (status < 0) { tc_log_info(LOG_ERR, errno, "sigaction(%s) failed", sig->signame); return -1; } } return 0; }
2.484375
2
2024-11-18T19:34:56.169826+00:00
2021-01-04T16:27:58
c13cfcc992929f4916c8441f467b36d92ae76c28
{ "blob_id": "c13cfcc992929f4916c8441f467b36d92ae76c28", "branch_name": "refs/heads/master", "committer_date": "2021-01-04T16:27:58", "content_id": "f6826e4cfabf132d3b05cab664e79cf8468be79c", "detected_licenses": [ "MIT" ], "directory_id": "0d7caef3f04c62d53ebd51902ecfd16c3fe8d17b", "extension": "c", "filename": "mouse.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 173937877, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2418, "license": "MIT", "license_type": "permissive", "path": "/projeto/src/mouse.c", "provenance": "stackv2-0054.json.gz:614", "repo_name": "TitoGrine/LCOM_Project", "revision_date": "2021-01-04T16:27:58", "revision_id": "59ac34d6476faf26afec7406840a83be38e9a722", "snapshot_id": "fbdbdb7c562eb8e9392b1e88811595175ce4cf3b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/TitoGrine/LCOM_Project/59ac34d6476faf26afec7406840a83be38e9a722/projeto/src/mouse.c", "visit_date": "2023-02-12T18:39:46.077965" }
stackv2
#include <lcom/lcf.h> #include "keyboard.h" #include "mouse.h" #include "MACROS.h" int hook_id_mouse = 3; uint8_t data; bool error_flag_mouse; static bool right_button = false; static bool left_button = false; static bool middle_button = false; bool x_sign = false; bool y_sign = false; // Stores mouse event information struct packet packet_data; uint8_t packet_size = 0; int(mouse_subscribe_int)(uint8_t *bit_no) { *bit_no = hook_id_mouse; sys_irqsetpolicy(MOUSE_IRQ, IRQ_REENABLE | IRQ_EXCLUSIVE, &hook_id_mouse); return 0; } int(mouse_unsubscribe_int)() { sys_irqrmpolicy(&hook_id_mouse); return 0; } void(mouse_ih)() { uint32_t status_register; sys_inb(STAT_REG, &status_register); if ((status_register & ST_PARITY) || (status_register & ST_TIMEOUT)) error_flag_mouse = true; else error_flag_mouse = false; if (status_register & ST_OBF) { uint32_t output; sys_inb(OUT_BUF, &output); data = (uint8_t) output; } if (!error_flag_mouse) { if (packet_size == 0 && (data & BIT(3))) { packet_data.bytes[packet_size] = data; packet_data.y_ov = data & Y_OVF; packet_data.x_ov = data & X_OVF; if (data & Y_SIGNAL) y_sign = true; else y_sign = false; if (data & X_SIGNAL) x_sign = true; else x_sign = false; packet_data.mb = data & MMB; middle_button = packet_data.mb; packet_data.rb = data & RMB; right_button = packet_data.rb; packet_data.lb = data & LMB; left_button = packet_data.lb; packet_size++; } else if (packet_size == 1) { packet_data.bytes[packet_size] = data; if (x_sign) packet_data.delta_x = 0xFF00 | data; else packet_data.delta_x = data; packet_size++; } else if (packet_size == 2) { packet_data.bytes[packet_size] = data; if (y_sign) packet_data.delta_y = 0xFF00 | data; else packet_data.delta_y = data; packet_size = 0; } } } int(mouse_cmd)(uint8_t command) { uint32_t status; do { kbc_cmd(WRITE_BYTE_MOUSE, &command, false); tickdelay(micros_to_ticks(DELAY)); while (1) { sys_inb(STAT_REG, &status); if (status & ST_OBF) { sys_inb(OUT_BUF, &status); break; } tickdelay(micros_to_ticks(DELAY)); } } while (status != ACK); return 0; }
2.390625
2
2024-11-18T19:34:56.556222+00:00
2020-07-10T22:15:50
cbc4c9828aaf225b001bd8929a41360894d2b443
{ "blob_id": "cbc4c9828aaf225b001bd8929a41360894d2b443", "branch_name": "refs/heads/master", "committer_date": "2020-07-10T22:15:50", "content_id": "85d56f1c61002d2a2823dc685ec511e3af96b3e2", "detected_licenses": [ "Unlicense" ], "directory_id": "c37f3e818676aa2b8e43611a291ac16cb0df84d6", "extension": "c", "filename": "e1-7_print_EOF.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 264082113, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 114, "license": "Unlicense", "license_type": "permissive", "path": "/e1-7_print_EOF.c", "provenance": "stackv2-0054.json.gz:871", "repo_name": "kevinrichey/knrcex", "revision_date": "2020-07-10T22:15:50", "revision_id": "7b15393d9ffe3663b1b518745ff15209a5f2ca2f", "snapshot_id": "5d18db07c696d2d9b464e46f3b50bf3dc10ae27d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kevinrichey/knrcex/7b15393d9ffe3663b1b518745ff15209a5f2ca2f/e1-7_print_EOF.c", "visit_date": "2022-11-16T01:57:48.948220" }
stackv2
#include <stdio.h> int main(int argv, char *argc[]) { int c = EOF; printf("int EOF = %d\n", c); return 0; }
2.1875
2
2024-11-18T19:34:56.849011+00:00
2020-09-12T21:06:08
4cab22a3b140411e0d1d846e8b4ec48cb7914c7c
{ "blob_id": "4cab22a3b140411e0d1d846e8b4ec48cb7914c7c", "branch_name": "refs/heads/master", "committer_date": "2020-09-12T21:06:08", "content_id": "871673c7becf37052556c040da4fef5056bbae27", "detected_licenses": [ "MIT" ], "directory_id": "17562281063b2c5d32ac87bd9848f1ce7b612874", "extension": "c", "filename": "mx_main2.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 240107276, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1043, "license": "MIT", "license_type": "permissive", "path": "/src/main/mx_main2.c", "provenance": "stackv2-0054.json.gz:1127", "repo_name": "Vladddd46/ush", "revision_date": "2020-09-12T21:06:08", "revision_id": "2eb131525afd7df5deac73366db5d6c554ba1088", "snapshot_id": "da2e516d2308c6a4e451925ca61fc5b39db9a1b4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Vladddd46/ush/2eb131525afd7df5deac73366db5d6c554ba1088/src/main/mx_main2.c", "visit_date": "2021-01-03T14:27:42.062374" }
stackv2
#include "ush.h" static void free_list(t_parsed_blocks **list) { t_parsed_blocks *tmp = *list; t_parsed_blocks *free_node; while(tmp) { free(tmp->separator); mx_arr_freesher(tmp->cmd_expr); free_node = tmp; tmp = tmp->next; free(free_node); } } void mx_main2(char *cmd, t_proc **proc_list, t_local_env **local_env) { t_parsed_blocks *list = mx_expression_parse(cmd); t_parsed_blocks *tmp = list; int status = 1; // This loop is needed to implement && and || while(tmp) { mx_input_preprocessing(tmp->cmd_expr, proc_list, local_env); status = mx_execute(tmp->cmd_expr, &proc_list[0], local_env); if (status == 1) { while(tmp) { if(tmp->separator) { if (mx_strcmp(tmp->separator, "&&") == 0) break; } tmp = tmp->next; } } if (tmp) tmp = tmp -> next; } free_list(&list); }
2.3125
2
2024-11-18T19:34:56.915086+00:00
2018-01-15T13:35:38
956eeff5018f968e90b95a3cc9a2c7301402c5b0
{ "blob_id": "956eeff5018f968e90b95a3cc9a2c7301402c5b0", "branch_name": "refs/heads/master", "committer_date": "2018-01-15T13:35:38", "content_id": "32bf15b9f8ab891b893d5305ce0da3f02563dc67", "detected_licenses": [ "MIT" ], "directory_id": "29a6629b61bb15eeab197d67b680410495ca7588", "extension": "c", "filename": "initialize.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 117549213, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1093, "license": "MIT", "license_type": "permissive", "path": "/src/initialize.c", "provenance": "stackv2-0054.json.gz:1255", "repo_name": "BillowBone/my_runner_2017", "revision_date": "2018-01-15T13:35:38", "revision_id": "444010d9d718698a00848c83e0e0a55c158536bd", "snapshot_id": "3cdb8e21a8908236254ce6ff17747c8f466c15c3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/BillowBone/my_runner_2017/444010d9d718698a00848c83e0e0a55c158536bd/src/initialize.c", "visit_date": "2021-05-12T00:59:25.064056" }
stackv2
/* ** EPITECH PROJECT, 2018 ** initialize.c ** File description: ** Function that initialize each vector of each object */ #include "../include/include.h" void initialize(object* obj, int nb) { obj->vector.x = nb * 640; obj->vector.y = 420; obj->x = nb * 640; obj->y = 420; } void initialize_sky(object* obj, int nb) { obj->vector.x = nb * 799; obj->vector.y = 0; obj->x = nb * 799; obj->y = 0; } void initialize_all(object* obj, object* obj2, object* obj3, object* obj4) { initialize(obj, 0); initialize(obj2, 1); initialize(obj3, 2); initialize(obj4, 3); } void initialize_sky_all(object* obj, object* obj2, object* obj3, object* obj4) { initialize_sky(obj, 0); initialize_sky(obj2, 1); initialize_sky(obj3, 2); initialize_sky(obj4, 3); } void initializer(sky skies, ground grounds, vege vegies, Time *time) { initialize_sky_all(skies.sky, skies.sky2, skies.sky3, skies.sky4); initialize_all(grounds.ground, grounds.ground2, grounds.ground3, grounds.ground4); initialize_all(vegies.vege, vegies.vege2, vegies.vege3, vegies.vege4); time->clock = sfClock_create(); }
2.546875
3
2024-11-18T19:34:57.142722+00:00
2014-05-28T16:34:00
5e80a5e6a716064719a257f12f54f33662e925a2
{ "blob_id": "5e80a5e6a716064719a257f12f54f33662e925a2", "branch_name": "refs/heads/master", "committer_date": "2014-05-28T16:34:00", "content_id": "8178111495d9e213be9b51f9375982041b49aa1f", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "6be1ed0d3ab9ff56cb583eba533329613ab49a1e", "extension": "c", "filename": "semaphore.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 242160695, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6397, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/kernelmode/kernel/process/semaphore.c", "provenance": "stackv2-0054.json.gz:1641", "repo_name": "slackner/ibnos", "revision_date": "2014-05-28T16:34:00", "revision_id": "756d1e0aa3ac253d3da82d908248f0a168719cdc", "snapshot_id": "bd1d04bb36b8d9e9ed31ceb869b4f3aa64442950", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/slackner/ibnos/756d1e0aa3ac253d3da82d908248f0a168719cdc/kernelmode/kernel/process/semaphore.c", "visit_date": "2021-01-08T22:29:11.749047" }
stackv2
/* * Copyright (c) 2014, Michael Müller * Copyright (c) 2014, Sebastian Lackner * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <process/semaphore.h> #include <process/object.h> #include <memory/allocator.h> #include <util/list.h> #include <util/util.h> /** \addtogroup Semaphores * @{ * Implementation of Semaphores */ static void __semaphoreDestroy(struct object *obj); static void __semaphoreShutdown(struct object *obj, UNUSED uint32_t mode); static int32_t __semaphoreGetStatus(struct object *obj, UNUSED uint32_t mode); static struct linkedList *__semaphoreWait(struct object *obj, UNUSED uint32_t mode, uint32_t *result); static void __semaphoreSignal(struct object *obj, UNUSED uint32_t result); static const struct objectFunctions semaphoreFunctions = { __semaphoreDestroy, NULL, /* getMinHandle */ __semaphoreShutdown, __semaphoreGetStatus, __semaphoreWait, __semaphoreSignal, NULL, /* write */ NULL, /* read */ NULL, /* insert */ NULL, /* remove */ }; /** * @brief Creates a new kernel semaphore object * @details This function allocates and returns the memory for a new kernel semaphore * object, which can for example be used for synchronization between multiple * threads. * * @param value Initial value of the semaphore object * @return Pointer to the new kernel semaphore object */ struct semaphore *semaphoreCreate(uint32_t value) { struct semaphore *s; /* allocate some new memory */ if (!(s = heapAlloc(sizeof(*s)))) return NULL; /* initialize general object info */ __objectInit(&s->obj, &semaphoreFunctions); ll_init(&s->waiters); s->value = value; return s; } /** * @brief Destructor for kernel semaphore objects * * @param obj Pointer to the kernel semaphore object */ static void __semaphoreDestroy(struct object *obj) { struct semaphore *s = objectContainer(obj, struct semaphore, &semaphoreFunctions); /* release other threads if the user destroys the object before they return */ queueWakeup(&s->waiters, true, -1); assert(ll_empty(&s->waiters)); /* release semaphore memory */ s->obj.functions = NULL; heapFree(s); } /** * @brief Aborts all pending wait operations * @details This function allows to abort all pending wait operations on the given * kernel semaphore object. All waiting threads will return (-1), similar as if * the object was destroyed. * * @param obj Pointer to the kernel semaphore object * @param mode not used */ static void __semaphoreShutdown(struct object *obj, UNUSED uint32_t mode) { struct semaphore *s = objectContainer(obj, struct semaphore, &semaphoreFunctions); queueWakeup(&s->waiters, true, -1); } /** * @brief Queries the current value of the kernel semaphore object * @details This function returns the current value of the kernel semaphore object. * It is not safe to rely on the result of this function in a multithreading * environment where other threads could modify the counter in the meantime. * * @param obj Pointer to the kernel semaphore object * @param mode not used * * @return Current counter of the semaphore object */ static int32_t __semaphoreGetStatus(struct object *obj, UNUSED uint32_t mode) { struct semaphore *s = objectContainer(obj, struct semaphore, &semaphoreFunctions); return s->value; } /** * @brief Performs a semaphore wait operation * @details This function will try to decrement the counter of the semaphore object. * If this is possible the function will return immediately, whereas the result * represents the new counter of the semaphore. It is not safe to rely on the * result of this function in a multithreading environment, where other threads * could also modify the counter in the meantime. If the counter is already zero * and cannot be decremented, the operation is blocking till another thread * increments it with a semaphore signal operation. * * @param obj Pointer to the kernel semaphore object * @param mode not used * @param result Will be filled out with the result code if the operation doesn't block * @return NULL if the operation returns immediately, otherwise a pointer to a wait queue linked list */ static struct linkedList *__semaphoreWait(struct object *obj, UNUSED uint32_t mode, uint32_t *result) { struct semaphore *s = objectContainer(obj, struct semaphore, &semaphoreFunctions); if (s->value == 0) return &s->waiters; *result = --s->value; return NULL; } /** * @brief Performs a semaphore signal operation * @details If there are no threads waiting for the semaphore this function will * increment the semaphore counter by one. Otherwise one of the waiting * threads will wake up with a result value of 0, as the semaphore counter * hasn't changed its value. * * @param obj Pointer to the kernel semaphore object * @param result not used */ static void __semaphoreSignal(struct object *obj, UNUSED uint32_t result) { struct semaphore *s = objectContainer(obj, struct semaphore, &semaphoreFunctions); if (ll_empty(&s->waiters)) s->value++; else { assert(s->value == 0); queueWakeup(&s->waiters, false, 0); } } /** * @} */
2.59375
3
2024-11-18T19:34:57.301532+00:00
2009-03-07T09:58:27
3762ecc09df1420afa20cb9da2572c557740aa09
{ "blob_id": "3762ecc09df1420afa20cb9da2572c557740aa09", "branch_name": "refs/heads/master", "committer_date": "2009-03-07T09:58:27", "content_id": "b52de2445f8be173a3b2488ddea3b7374d355535", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "f5e274afe121ff86721e17a1f84ec6ec3243114d", "extension": "c", "filename": "random.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 145107, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2491, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/packages/random/random.c", "provenance": "stackv2-0054.json.gz:1898", "repo_name": "elq/torch5", "revision_date": "2009-03-07T09:58:27", "revision_id": "5965bd6410f8ca7e87c6bc9531aaf46e10ed281e", "snapshot_id": "7b0009f64e247ce95adfe1567704ffd8a4862b61", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/elq/torch5/5965bd6410f8ca7e87c6bc9531aaf46e10ed281e/packages/random/random.c", "visit_date": "2020-05-17T01:56:46.913867" }
stackv2
#include "luaT.h" #include "TH.h" static int random_seed(lua_State *L) { lua_pushnumber(L, THRandom_seed()); return 1; } static int random_manualSeed(lua_State *L) { long seed = luaL_checklong(L, 1); THRandom_manualSeed(seed); return 0; } static int random_initialSeed(lua_State *L) { lua_pushnumber(L, THRandom_initialSeed()); return 1; } static int random_random(lua_State *L) { lua_pushnumber(L, THRandom_random()); return 1; } static int random_uniform(lua_State *L) { double a = luaL_optnumber(L, 1, 0); double b = luaL_optnumber(L, 2, 1); lua_pushnumber(L, THRandom_uniform(a, b)); return 1; } static int random_normal(lua_State *L) { double a = luaL_optnumber(L, 1, 0); double b = luaL_optnumber(L, 2, 1); luaL_argcheck(L, b > 0, 2, "positive number required"); lua_pushnumber(L, THRandom_normal(a, b)); return 1; } static int random_exponential(lua_State *L) { double lambda = luaL_checknumber(L, 1); lua_pushnumber(L, THRandom_exponential(lambda)); return 1; } static int random_cauchy(lua_State *L) { double median = luaL_optnumber(L, 1, 0); double sigma = luaL_optnumber(L, 2, 1); lua_pushnumber(L, THRandom_cauchy(median, sigma)); return 1; } static int random_logNormal(lua_State *L) { double mean = luaL_checknumber(L, 1); double stdv = luaL_checknumber(L, 2); luaL_argcheck(L, stdv > 0, 2, "positive number required"); lua_pushnumber(L, THRandom_logNormal(mean, stdv)); return 1; } static int random_geometric(lua_State *L) { double p = luaL_checknumber(L, 1); luaL_argcheck(L, p > 0 && p < 1, 2, "must be > 0 and < 1"); lua_pushnumber(L, THRandom_geometric(p)); return 1; } static int random_bernoulli(lua_State *L) { double p = luaL_optnumber(L, 1, 0.5); luaL_argcheck(L, p > 0 && p < 1, 2, "must be > 0 and < 1"); lua_pushnumber(L, THRandom_bernoulli(p)); return 1; } static const struct luaL_Reg random__ [] = { {"seed", random_seed}, {"manualSeed", random_manualSeed}, {"initialSeed", random_initialSeed}, {"random", random_random}, {"uniform", random_uniform}, {"normal", random_normal}, {"exponential", random_exponential}, {"cauchy", random_cauchy}, {"logNormal", random_logNormal}, {"geometric", random_geometric}, {"bernoulli", random_bernoulli}, {NULL, NULL} }; DLL_EXPORT int luaopen_librandom(lua_State *L) { lua_newtable(L); lua_pushvalue(L, -1); lua_setfield(L, LUA_GLOBALSINDEX, "random"); luaL_register(L, NULL, random__); return 1; }
2.125
2
2024-11-18T19:34:57.560816+00:00
2020-09-27T02:37:49
db5ff1b3065ecdfa511b67d2a8a47a133913de0b
{ "blob_id": "db5ff1b3065ecdfa511b67d2a8a47a133913de0b", "branch_name": "refs/heads/master", "committer_date": "2020-09-27T02:37:49", "content_id": "bae877f169bf188172db356175ffeb828a5025d2", "detected_licenses": [ "MIT" ], "directory_id": "7e9e5206fe900441ca7634ff581f63d03d0ea9fd", "extension": "c", "filename": "simulacao.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 295295229, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3069, "license": "MIT", "license_type": "permissive", "path": "/simulacao.c", "provenance": "stackv2-0054.json.gz:2284", "repo_name": "tonnycordeiro/CastawaysGame", "revision_date": "2020-09-27T02:37:49", "revision_id": "9335c4c52854708d6fc2ab44dd86e36fe074c364", "snapshot_id": "8cb7cc93d40e915470895932453beb8b85df36e2", "src_encoding": "ISO-8859-1", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tonnycordeiro/CastawaysGame/9335c4c52854708d6fc2ab44dd86e36fe074c364/simulacao.c", "visit_date": "2022-12-24T14:34:04.087159" }
stackv2
/* Nome e nº USP Cirillo Ribeiro Ferreira - 6431200 Matheus de Lima Barbosa - 5968663 Tonny Costa Cordeiro - 6539839 */ /* Arquivo da funcao que gerencia toda a simulacao do oceano */ #include <stdlib.h> #include <stdio.h> #include <time.h> #include <sys/time.h> #include "simulacao.h" void simular(double frequencia, int velocidade, unsigned int semente) { int i; ptr_marcaBarreiras ptrBarreiras; representacao oceano; passageiros *ps; bote *b1, *b2; recifes *rs; navio *navio; struct timespec t; struct timeval t_inicial, t_final; inicializarSimulacao(&oceano, &ps, &b1, &b2, &rs, &navio, &ptrBarreiras); /*todo: teste:*/ /*imprimeRepresentacaoBarreiras(ptrBarreiras);*/ for(i = 0; i < TEMPO_SIMULACAO; i++) { t.tv_sec = 0.0; t.tv_nsec = 100000000.0; /* Guarda o tempo de início da geração do quadro */ gettimeofday(&t_inicial, NULL); interacaoSimulacao(oceano, ps, b1, b2, navio, frequencia, velocidade, semente,ptrBarreiras);/*, */ definirVisualRepresentacao(oceano, ps, rs, b1, b2, navio); imprimirRepresentacao(oceano); PRINT_INFO_TELA(ps); /* Guarda o tempo de término da geração do quadro */ gettimeofday(&t_final, NULL); /* Desconta o tempo gasto no processamento do quadro no tempo que a execução deverá ficar 'dormindo', tornando a simulação mais real. */ t.tv_nsec -= (t_final.tv_usec - t_inicial.tv_usec) * 1000; nanosleep(&t, NULL); } destruirSimulacao(oceano, ps, b1, b2, rs, navio); } void inicializarSimulacao(representacao *oceano, passageiros **ps, bote **b1, bote **b2, recifes **rs, navio **n, ptr_marcaBarreiras *ptrBarreiras) { *ptrBarreiras = inicializarMarcacaoDasBarreiras(); *oceano = inicializarRepresentacao(); *ps = inicializarPassageiros( MAX_PASSAGEIROS_TELA ); *b1 = inicializarBote(); *b2 = inicializarBote(); *rs = inicializarRecifes(); *n = inicializarNavio(*ptrBarreiras); } void destruirSimulacao(representacao oceano, passageiros *ps, bote *b1, bote *b2, recifes *rs, navio *nav) { /* Destrói os botes */ destruirBote(b1); destruirBote(b2); /* Destrói os recifes */ destruirRecifes(rs); /* Destrói o navio */ destruirNavio(nav); destruirPassageiros(ps); destruirRepresentacao(oceano); } void interacaoSimulacao(representacao oceano, passageiros *ps, bote *b1, bote *b2, navio *n, double frequencia, int velocidade, unsigned int semente, ptr_marcaBarreiras ptrBarreiras) { calcularDirecaoPassageiros(ps); eliminarPassageiros(ps); calcularPassageirosResgatados(ps, b1); calcularPassageirosResgatados(ps, b2); criarPassageiros(ps, frequencia, velocidade, semente,ptrBarreiras); calcularColisaoPassageiros(ps); calcularColisaoNavio(ps, n); /*calcularColisaoComBarreira(ps,ptrBarreiras);*/ eliminarPassageiros(ps); atualizarTempoPassageiros(ps); }
2.703125
3
2024-11-18T19:34:57.984813+00:00
2018-05-28T08:36:34
2fb7204139031511dcbc164ffc98d909f4715ca0
{ "blob_id": "2fb7204139031511dcbc164ffc98d909f4715ca0", "branch_name": "refs/heads/master", "committer_date": "2018-05-28T08:36:34", "content_id": "c332b69cde5b0e4947f232876f96cac66032bbfd", "detected_licenses": [ "MIT" ], "directory_id": "5d2f6c05e7f67dda7212a12462524bbd13b7d242", "extension": "c", "filename": "integrals_de.c", "fork_events_count": 0, "gha_created_at": "2016-07-09T14:00:30", "gha_event_created_at": "2016-07-09T14:00:30", "gha_language": null, "gha_license_id": null, "github_id": 62952034, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5660, "license": "MIT", "license_type": "permissive", "path": "/arb/integrals_de.c", "provenance": "stackv2-0054.json.gz:2540", "repo_name": "christianneurohr/hcperiods", "revision_date": "2018-05-28T08:36:34", "revision_id": "668eb388d9fbf67af16f215e36acc900a2f61436", "snapshot_id": "7c05ba329971f41cdbe400c74e4f4aca7b9de062", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/christianneurohr/hcperiods/668eb388d9fbf67af16f215e36acc900a2f61436/arb/integrals_de.c", "visit_date": "2021-03-31T02:19:54.076678" }
stackv2
/****************************************************************************** Copyright (C) 2016 Pascal Molin ******************************************************************************/ #include "abel_jacobi.h" void de_integrals_precomp(acb_ptr res, acb_srcptr u, slong d1, slong d, sec_t c, const de_int_t de, int flag, slong prec) { slong l; arb_t x; acb_t y, wy, wyx; acb_ptr z; void (*mth_root_pol) (acb_t y, acb_srcptr u, slong d1, slong d, const arb_t x, acb_srcptr z, slong m, slong prec); arb_init(x); acb_init(y); acb_init(wy); acb_init(wyx); z = _acb_vec_init(c.m); _acb_vec_unit_roots(z, c.m, c.m, prec); #if DEBUG flint_printf("\nde integral, d1=%ld, d=%ld, prec=%ld\n", d1, d, prec); #endif mth_root_pol = &mth_root_pol_prod; if (prec > 1000 && d > 5) mth_root_pol = &mth_root_pol_turn; if (flag & AJ_ROOT_DEF) mth_root_pol = &mth_root_pol_def; else if (flag & AJ_ROOT_PROD) mth_root_pol = &mth_root_pol_prod; else if (flag & AJ_ROOT_TURN) mth_root_pol = &mth_root_pol_turn; /* compute integral */ _acb_vec_zero(res, c.g); for (l = 0; l < de->n; l++) { slong j; acb_ptr r; /* compute 1/y(x) */ mth_root_pol(y, u, d1, d, de->x + l, z, c.m, prec); acb_set_arb(wy, de->ch2m + l); acb_div(y, wy, y, prec); /* all differentials for x */ if (c.j1 > 1) { acb_pow_ui(wy, y, c.j1, prec); acb_mul_arb(wy, wy, de->dx + l, prec); } else acb_mul_arb(wy, y, de->dx + l, prec); for (r = res, j = 0; j < c.nj; j++) { if (j) acb_mul(wy, wy, y, prec); acb_set(wyx, wy); acb_vec_add_geom_arb(r, c.ni[j], wyx, de->x + l, prec); r += c.ni[j]; } #if DEBUG > 2 flint_printf("\nl = %ld, res = ", l); _acb_vec_printd(res, c.g, 30, "\n"); #endif if (l == 0) continue; /* now on -x */ arb_neg(x, de->x + l); mth_root_pol(y, u, d1, d, x, z, c.m, prec); acb_set_arb(wy, de->ch2m + l); acb_div(y, wy, y, prec); if (c.j1 > 1) { acb_pow_ui(wy, y, c.j1, prec); acb_mul_arb(wy, wy, de->dx + l, prec); } else acb_mul_arb(wy, y, de->dx + l, prec); for (r = res, j = 0; j < c.nj; j++) { if (j) acb_mul(wy, wy, y, prec); acb_set(wyx, wy); acb_vec_sub_geom_arb(r, c.ni[j], wyx, de->x + l, prec); r += c.ni[j]; } } _acb_vec_scalar_mul_arb(res, res, c.g, de->factor, prec); #if DEBUG > 1 flint_printf("\nend integration "); _acb_vec_printd(res, c.g, 30, "\n"); #endif arb_clear(x); acb_clear(y); acb_clear(wy); acb_clear(wyx); _acb_vec_clear(z, c.m); } void de_integrals(acb_ptr res, acb_srcptr u, slong d1, slong d, sec_t c, int flag, slong prec) { slong n; arf_t h, l; mag_t e; de_int_t de; arf_init(h); arf_init(l); mag_init(e); n = de_params(e, h, l, u, d, 0, c.n - 1, c.j1, c.m, prec); de_int_init(de, h, l, n, e, c.m, prec); de_integrals_precomp(res, u, d1, d, c, de, flag, prec); de_int_clear(de); arf_clear(h); arf_clear(l); mag_clear(e); } void integrals_edge_de(acb_ptr res, ydata_t ye, sec_t c, de_int_t de, int flag, slong prec) { slong n; arf_t h, l; mag_t e; arf_init(h); arf_init(l); mag_init(e); if (!de->n || !(flag & AJ_DE_SAME)) { n = de_params(e, h, l, ye->u, c.n - 2, 0., c.n - 1, c.j1, c.m, prec); if (!de->n || (de->n - n) * (c.n + c.g) > n) { #if DEBUG flint_printf("\nprecomputed DE, n = %ld, h = %lf, prec=%ld\n", n, arf_get_d(h, ARF_RND_NEAR), prec); #endif de_int_clear(de); de_int_init(de, h, l, n, e, c.m, prec); } } de_integrals_precomp(res, ye->u, ye->n1, c.n - 2, c, de, flag, prec); if (!mag_is_zero(de->e)) _acb_vec_add_error_mag(res, c.g, de->e); integrals_edge_factors(res, ye->ba2, ye->ab, ye->c, c, prec); arf_clear(h); arf_clear(l); mag_clear(e); } void integrals_tree_de(acb_mat_t integrals, sec_t c, const tree_t tree, int flag, slong prec) { slong l; comp_t * t; de_int_t de; t = flint_malloc(tree->n * sizeof(comp_t)); for (l = 0; l < tree->n; l++) t[l].k = l, t[l].r = tree->e[l].r; qsort(t, tree->n, sizeof(comp_t), (int(*)(const void*,const void*))comp_cmp); de->n = 0; for (l = 0; l < tree->n; l++) { slong k = t[l].k; integrals_edge_de(integrals->rows[k], tree->data + k, c, de, flag, prec); } de_int_clear(de); flint_free(t); #if DEBUG > 1 flint_printf("\ntree integrals\n"); acb_mat_printd(integrals, 30); #endif } void integral_d2(acb_ptr res, ydata_t ye, sec_t c, slong prec) { slong j; fmpq_t h, jm; arb_t g; acb_ptr p = res; arb_init(g); fmpq_init(h); fmpq_set_si(h, 1, 2); fmpq_init(jm); _acb_vec_zero(p, c.g); for (j = c.g ; j > 0; j--, p++) { arb_ptr r = acb_realref(p); arb_const_sqrt_pi(r, prec); fmpq_set_si(jm, j, c.m); arb_gamma_fmpq(g, jm, prec); arb_mul(r, r, g, prec); fmpq_add(jm, jm, h); arb_gamma_fmpq(g, jm, prec); arb_div(r, r, g, prec); } fmpq_clear(jm); fmpq_clear(h); arb_clear(g); integrals_edge_factors(res, ye->ba2, ye->ab, ye->c, c, prec); }
2.1875
2
2024-11-18T19:34:58.162791+00:00
2017-08-08T19:10:28
39c02bf6135aecb8e173ecc56376b328c27b2e6d
{ "blob_id": "39c02bf6135aecb8e173ecc56376b328c27b2e6d", "branch_name": "refs/heads/master", "committer_date": "2017-08-08T19:10:28", "content_id": "cfd3ce4b470d4ecf965755b6a14bd3815d798eac", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "directory_id": "61fa27eacf7046473994dc861aaa957d85b1b680", "extension": "c", "filename": "socketlib.c", "fork_events_count": 4, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 99728123, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6845, "license": "BSD-3-Clause,MIT", "license_type": "permissive", "path": "/usr/src/libsocket/socketlib.c", "provenance": "stackv2-0054.json.gz:2669", "repo_name": "SCSLaboratory/BearOS", "revision_date": "2017-08-08T19:10:28", "revision_id": "81428604e0b7869606413872e1d3fc896256490a", "snapshot_id": "2a20b5cb737ac7dec32561d40760e7d1ebc33555", "src_encoding": "UTF-8", "star_events_count": 26, "url": "https://raw.githubusercontent.com/SCSLaboratory/BearOS/81428604e0b7869606413872e1d3fc896256490a/usr/src/libsocket/socketlib.c", "visit_date": "2021-01-15T16:52:59.963257" }
stackv2
/* Copyright <2017> <Scaleable and Concurrent Systems Lab; Thayer School of Engineering at Dartmouth College> 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. */ /* * This file contains all of the core helper functions * to support sockets */ #include <stdio.h> /* printf */ #include <stdint.h> /* uint32_t, uint16_t, uint8_t */ #include <ctype.h> /* isdigit, isxdigit, islower, isspace */ #include <netinet/in.h> #include <arpa/inet.h> #define ip4_addr_get_u32(src_ipaddr) ((src_ipaddr)->s_addr) #define ip4_addr_set_u32(dest_ipaddr, src_u32) ((dest_ipaddr)->s_addr = (src_u32)) /** * Convert an uint16_t from host- to network byte order. * * @param n uint16_t in host byte order * @return n in network byte order */ uint16_t htons(uint16_t n) { return ((n & 0xff) << 8) | ((n & 0xff00) >> 8); } /** * Convert an uint16_t from network- to host byte order. * * @param n uint16_t in network byte order * @return n in host byte order */ uint16_t ntohs(uint16_t n) { return htons(n); } /** * Convert an uint32_t from host- to network byte order. * * @param n uint32_t in host byte order * @return n in network byte order */ uint32_t htonl(uint32_t n) { return ((n & 0xff) << 24) | ((n & 0xff00) << 8) | ((n & 0xff0000UL) >> 8) | ((n & 0xff000000UL) >> 24); } /** * Convert an uint32_t from network- to host byte order. * * @param n uint32_t in network byte order * @return n in host byte order */ uint32_t ntohl(uint32_t n) { return htonl(n); } /** * Ascii internet address interpretation routine. * The value returned is in network order. * * @param cp IP address in ascii represenation (e.g. "127.0.0.1") * @return ip address in network order */ uint32_t inet_addr(const char *cp) { struct in_addr val; if (inet_aton(cp, &val)) { return ip4_addr_get_u32(&val); } return (INADDR_NONE); } /** * Check whether "cp" is a valid ascii representation * of an Internet address and convert to a binary address. * Returns 1 if the address is valid, 0 if not. * This replaces inet_addr, the return value from which * cannot distinguish between failure and a local broadcast address. * * @param cp IP address in ascii represenation (e.g. "127.0.0.1") * @param addr pointer to which to save the ip address in network order * @return 1 if cp could be converted to addr, 0 on failure */ int inet_aton(const char *cp, struct in_addr *addr) { uint32_t val; uint8_t base; char c; uint32_t parts[4]; uint32_t *pp = parts; c = *cp; for (;;) { /* * Collect number up to ``.''. * Values are specified as for C: * 0x=hex, 0=octal, 1-9=decimal. */ if (!isdigit(c)) return (0); val = 0; base = 10; if (c == '0') { c = *++cp; if (c == 'x' || c == 'X') { base = 16; c = *++cp; } else base = 8; } for (;;) { if (isdigit(c)) { val = (val * base) + (int)(c - '0'); c = *++cp; } else if (base == 16 && isxdigit(c)) { val = (val << 4) | (int)(c + 10 - (islower(c) ? 'a' : 'A')); c = *++cp; } else break; } if (c == '.') { /* * Internet format: * a.b.c.d * a.b.c (with c treated as 16 bits) * a.b (with b treated as 24 bits) */ if (pp >= parts + 3) { return (0); } *pp++ = val; c = *++cp; } else break; } /* * Check for trailing characters. */ if (c != '\0' && !isspace(c)) { return (0); } /* * Concoct the address according to * the number of parts specified. */ switch (pp - parts + 1) { case 0: return (0); /* initial nondigit */ case 1: /* a -- 32 bits */ break; case 2: /* a.b -- 8.24 bits */ if (val > 0xffffffUL) { return (0); } val |= parts[0] << 24; break; case 3: /* a.b.c -- 8.8.16 bits */ if (val > 0xffff) { return (0); } val |= (parts[0] << 24) | (parts[1] << 16); break; case 4: /* a.b.c.d -- 8.8.8.8 bits */ if (val > 0xff) { return (0); } val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8); break; default: printf("socketlib: inet_aton unhandled class\n"); break; } if (addr) { ip4_addr_set_u32(addr, htonl(val)); } return (1); } #define MAXBUF 16 /** * Convert numeric IP address into decimal dotted ASCII representation. * returns ptr to static buffer; not reentrant! * * @param addr ip address in network order to convert * @return pointer to a global static (!) buffer that holds the ASCII * represenation of addr */ char *inet_ntoa(struct in_addr addr) { char *inet_ntoa_r(struct in_addr *addr, char *buf, int buflen); static char str[MAXBUF]; return inet_ntoa_r(&addr, str, MAXBUF); } /** * Same as inet_ntoa, but reentrant since a user-supplied buffer is used. * * @param addr ip address in network order to convert * @param buf target buffer where the string is stored * @param buflen length of buf * @return either pointer to buf which now holds the ASCII * representation of addr or NULL if buf was too small */ char *inet_ntoa_r(struct in_addr *addr, char *buf, int buflen) { uint32_t s_addr; char inv[3]; char *rp; uint8_t *ap; uint8_t rem; uint8_t n; uint8_t i; int len = 0; s_addr = ip4_addr_get_u32(addr); rp = buf; ap = (uint8_t *)&s_addr; for(n = 0; n < 4; n++) { i = 0; do { rem = *ap % (uint8_t)10; *ap /= (uint8_t)10; inv[i++] = '0' + rem; } while(*ap); while(i--) { if (len++ >= buflen) { return NULL; } *rp++ = inv[i]; } if (len++ >= buflen) { return NULL; } *rp++ = '.'; ap++; } *--rp = 0; return buf; }
2.734375
3
2024-11-18T19:34:58.908388+00:00
2013-12-18T19:26:13
ecc0e5086b1dcce5199b67dabba7d527b8069861
{ "blob_id": "ecc0e5086b1dcce5199b67dabba7d527b8069861", "branch_name": "refs/heads/master", "committer_date": "2013-12-18T19:26:13", "content_id": "cb09723f753b1fca8107d0e4a8e17ee0d0a5b56f", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "504e8516fb1ab146503ad29844bea62f11af269c", "extension": "h", "filename": "ia64_defns.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": 2933, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/lockfree-lib-bsd/ia64_defns.h", "provenance": "stackv2-0054.json.gz:3184", "repo_name": "nmldiegues/stamp-rtm", "revision_date": "2013-12-18T19:26:13", "revision_id": "9690799d6de9f544e430e4dbfa6a0d04e53f5615", "snapshot_id": "d88458317edd8e4fb52350caf0e8589d68d72ea7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nmldiegues/stamp-rtm/9690799d6de9f544e430e4dbfa6a0d04e53f5615/lockfree-lib-bsd/ia64_defns.h", "visit_date": "2020-12-24T15:22:47.243306" }
stackv2
#ifndef __IA64_DEFNS_H__ #define __IA64_DEFNS_H__ #include <pthread.h> #include <sched.h> #ifndef IA64 #define IA64 #endif #define CACHE_LINE_SIZE 64 /* * I. Compare-and-swap. */ #define CAS32(_a, _o, _n) \ ({ /*__typeof__(_o) __o = _o; */ \ /* __asm__ __volatile__("mov ar.ccv=%0 ;;" :: "rO" (_o)); */ \ /* __asm__ __volatile__("cmpxchg4.acq %0=%1,%2,ar.ccv ;; " */ \ /* : "=r" (__o), "=m" (*(_a)) */ \ /* : "r"(_n)); */ \ /* __o; */ \ __sync_val_compare_and_swap(_a,_o,_n); \ }) #define CAS64(_a, _o, _n) \ ({ /*__typeof__(_o) __o = _o; */ \ /*__asm__ __volatile__("mov ar.ccv=%0 ;;" :: "rO" (_o)); */ \ /*__asm__ __volatile__("cmpxchg8.acq %0=%1,%2,ar.ccv ;; " */ \ /* : "=r" (__o), "=m" (*(_a)) */ \ /* : "r"(_n)); */ \ /*__o; */ \ __sync_val_compare_and_swap(_a,_o,_n); \ }) #define FAS32(_a, _n) \ ({ __typeof__(_n) __o; \ __asm__ __volatile__("xchg4 %0=%1,%2 ;; " \ : "=r" (__o), "=m" (*(_a)) \ : "r"(_n)); \ __o; \ }) #define FAS64(_a, _n) \ ({ \ /*__typeof__(_n) __o; */ \ /* __asm__ __volatile__("xchg8 %0=%1,%2 ;; " */ \ /* : "=r" (__o), "=m" (*(_a)) */ \ /* : "r"(_n)); */ \ /*__o; */ \ __typeof__(_n) __o; \ __asm__ __volatile__("xchgq %0,%1" \ :"=r" (__o) \ :"m" (*(_a)), "0" (__o) \ :"memory"); \ __o; \ }) #define CAS(_x,_o,_n) ((sizeof (*_x) == 4)?CAS32(_x,_o,_n):CAS64(_x,_o,_n)) #define FAS(_x,_n) ((sizeof (*_x) == 4)?FAS32(_x,_n) :FAS64(_x,_n)) /* Update Integer location, return Old value. */ #define CASIO CAS #define FASIO FAS /* Update Pointer location, return Old value. */ #define CASPO CAS64 #define FASPO FAS64 /* Update 32/64-bit location, return Old value. */ #define CAS32O CAS32 #define CAS64O CAS64 /* * II. Memory barriers. * WMB(): All preceding write operations must commit before any later writes. * RMB(): All preceding read operations must commit before any later reads. * MB(): All preceding memory accesses must commit before any later accesses. * * If the compiler does not observe these barriers (but any sane compiler * will!), then VOLATILE should be defined as 'volatile'. */ #define MB() __sync_synchronize() /*__asm__ __volatile__ (";; mf ;; " : : : "memory")*/ #define WMB() MB() #define RMB() MB() #define VOLATILE volatile /* * III. Cycle counter access. */ typedef unsigned long long tick_t; #define RDTICK() \ ({ tick_t __t; __asm__ __volatile__ ("rdtsc" : "=A" (__t)); __t; }) /* * IV. Types. */ typedef unsigned char _u8; typedef unsigned short _u16; typedef unsigned int _u32; typedef unsigned long long _u64; #endif /* __IA64_DEFNS_H__ */
2.296875
2
2024-11-18T19:34:59.024428+00:00
2022-06-03T22:32:35
f6598949deada14007799fc3749537438a9fa378
{ "blob_id": "f6598949deada14007799fc3749537438a9fa378", "branch_name": "refs/heads/master", "committer_date": "2022-06-03T22:49:26", "content_id": "e60d375c86bac836ee8fa50d0564d82ea0871025", "detected_licenses": [ "Apache-2.0", "curl" ], "directory_id": "b7061e3f678190e1e40be7d3e1151b1c278dfaa2", "extension": "c", "filename": "test_v1beta1_group_subject.c", "fork_events_count": 0, "gha_created_at": "2020-03-23T05:00:49", "gha_event_created_at": "2022-06-03T22:56:11", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 249339642, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1734, "license": "Apache-2.0,curl", "license_type": "permissive", "path": "/kubernetes/unit-test/test_v1beta1_group_subject.c", "provenance": "stackv2-0054.json.gz:3312", "repo_name": "brendandburns/c", "revision_date": "2022-06-03T22:32:35", "revision_id": "6be8eca36e73be0d6a8c752e0b2b9e3f36eb6143", "snapshot_id": "967147816092bf88cfb9b5369465de52a599fd28", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/brendandburns/c/6be8eca36e73be0d6a8c752e0b2b9e3f36eb6143/kubernetes/unit-test/test_v1beta1_group_subject.c", "visit_date": "2022-07-10T05:22:49.165574" }
stackv2
#ifndef v1beta1_group_subject_TEST #define v1beta1_group_subject_TEST // the following is to include only the main from the first c file #ifndef TEST_MAIN #define TEST_MAIN #define v1beta1_group_subject_MAIN #endif // TEST_MAIN #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdbool.h> #include "../external/cJSON.h" #include "../model/v1beta1_group_subject.h" v1beta1_group_subject_t* instantiate_v1beta1_group_subject(int include_optional); v1beta1_group_subject_t* instantiate_v1beta1_group_subject(int include_optional) { v1beta1_group_subject_t* v1beta1_group_subject = NULL; if (include_optional) { v1beta1_group_subject = v1beta1_group_subject_create( "0" ); } else { v1beta1_group_subject = v1beta1_group_subject_create( "0" ); } return v1beta1_group_subject; } #ifdef v1beta1_group_subject_MAIN void test_v1beta1_group_subject(int include_optional) { v1beta1_group_subject_t* v1beta1_group_subject_1 = instantiate_v1beta1_group_subject(include_optional); cJSON* jsonv1beta1_group_subject_1 = v1beta1_group_subject_convertToJSON(v1beta1_group_subject_1); printf("v1beta1_group_subject :\n%s\n", cJSON_Print(jsonv1beta1_group_subject_1)); v1beta1_group_subject_t* v1beta1_group_subject_2 = v1beta1_group_subject_parseFromJSON(jsonv1beta1_group_subject_1); cJSON* jsonv1beta1_group_subject_2 = v1beta1_group_subject_convertToJSON(v1beta1_group_subject_2); printf("repeating v1beta1_group_subject:\n%s\n", cJSON_Print(jsonv1beta1_group_subject_2)); } int main() { test_v1beta1_group_subject(1); test_v1beta1_group_subject(0); printf("Hello world \n"); return 0; } #endif // v1beta1_group_subject_MAIN #endif // v1beta1_group_subject_TEST
2.609375
3
2024-11-18T19:34:59.450420+00:00
2017-06-16T17:47:27
a8f69a042e0ea0d3ed2b0e1168143f0a54688442
{ "blob_id": "a8f69a042e0ea0d3ed2b0e1168143f0a54688442", "branch_name": "refs/heads/master", "committer_date": "2017-06-16T17:47:27", "content_id": "46c6b4f9df53dde744179cf505310927e1de9e60", "detected_licenses": [ "MIT" ], "directory_id": "1efca1de7b080da2af29bfb2ceb9f2346e1beccc", "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": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4643, "license": "MIT", "license_type": "permissive", "path": "/src/server.c", "provenance": "stackv2-0054.json.gz:3440", "repo_name": "otbr/kaplar", "revision_date": "2017-06-16T17:47:27", "revision_id": "c2af77ba82588ed5b9bf6de748d6e1efcff0f6a2", "snapshot_id": "b70a56a7bba0d2a9dcd1b37f32b94f29033f7e45", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/otbr/kaplar/c2af77ba82588ed5b9bf6de748d6e1efcff0f6a2/src/server.c", "visit_date": "2020-03-26T20:50:28.806301" }
stackv2
#include "server.h" #include "network.h" #include "message.h" #include "thread.h" #include "log.h" #include "scheduler.h" #include "connection.h" #include <stddef.h> #define SERVICE_OPEN 0x00 #define SERVICE_CLOSED 0x01 #define SERVICE_MAX_REOPENS 16 struct service{ long port; long flags; long reopens; struct socket *sock; struct protocol *protocol_list; }; #define MAX_SERVICES 4 static struct service services[MAX_SERVICES]; static long service_count = 0; static long running = 0; static void service_reopen(struct service *service); static void service_on_accept(struct socket *sock, int error, int bytes_transfered, void *udata) { struct service *service = udata; // reopen service in case of error if(error != 0){ LOG_ERROR("service_on_accept: operation failed (error = %d)", error); net_close(sock); if((service->flags & SERVICE_CLOSED) == 0){ LOG_ERROR("service_on_accept: fatal socket error! re-opening service"); service_reopen(service); return; } } // if service is closing, close it's socket and return // interrupting the accept chain if((service->flags & SERVICE_CLOSED) != 0){ net_close(service->sock); service->sock = NULL; return; } // create new connection connection_accept(sock, service->protocol_list); // chain next accept if(net_async_accept(service->sock, service_on_accept, service) != 0){ LOG_ERROR("service_on_accept: failed to chain next accept! trying to re-open service"); service_reopen(service); } } static void service_reopen(struct service *service) { if(service->sock != NULL) net_close(service->sock); if(service->reopens >= SERVICE_MAX_REOPENS){ LOG_ERROR("service_reopen: maximum number of reopens reached (%d)", SERVICE_MAX_REOPENS); service->flags |= SERVICE_CLOSED; return; } service->sock = net_server_socket(service->port); if(service->sock == NULL){ LOG_ERROR("service_reopen: failed to create service socket on port %d", service->port); return; } if(net_async_accept(service->sock, service_on_accept, service) != 0){ LOG_ERROR("service_reopen: failed to restart accept chain on service port %d", service->port); net_close(service->sock); service->sock = NULL; } } void server_run() { struct service *service; struct protocol *proto; // initialize services for(int i = 0; i < service_count; i++){ service = &services[i]; // check that port is valid if(service->port <= 0){ LOG_ERROR("server_run: service with invalid port %d", service->port); continue; } // initialize protocol internals for(proto = service->protocol_list; proto != NULL; proto = proto->next) proto->init(); // create service socket service->sock = net_server_socket(service->port); if(service->sock == NULL){ LOG_ERROR("server_run: failed to start service on port %d", service->port); continue; } // start accept chain if(net_async_accept(service->sock, service_on_accept, service) != 0){ LOG_ERROR("server_run: failed to start accept chain on service port %d", service->port); net_close(service->sock); service->sock = NULL; } } // network loop running = 1; while(running != 0){ // net_work returning -1 means the net interface // is no longer usable and needs to be shutdown if(net_work() == -1) running = 0; } // close services for(int i = 0; i < service_count; i++){ service = &services[i]; // close service socket service->flags |= SERVICE_CLOSED; if(service->sock != NULL) net_close(service->sock); // shutdown protocol internals for(proto = service->protocol_list; proto != NULL; proto = proto->next) proto->shutdown(); } } void server_stop() { running = 0; } void server_add_protocol(int port, struct protocol *protocol) { int i; struct service *service; if(running != 0){ LOG_ERROR("server_add_protocol: server already running"); return; } service = NULL; for(i = 0; i < service_count; i++){ if(services[i].port == port){ service = &services[i]; break; } } if(service == NULL){ if(service_count >= MAX_SERVICES){ LOG_ERROR("server_add_protocol: reached maximum number of services %d", MAX_SERVICES); return; } service = &services[service_count]; service->port = port; service->protocol_list = protocol; service_count++; } else{ if(service->protocol_list->flags & PROTOCOL_SENDS_FIRST || protocol->flags & PROTOCOL_SENDS_FIRST){ LOG_ERROR("server_add_protocol: protocols \"%s\" and \"%s\" cannot use the same port", service->protocol_list->name, protocol->name); return; } protocol->next = service->protocol_list; service->protocol_list = protocol; } }
2.59375
3
2024-11-18T19:34:59.677990+00:00
2016-01-28T20:21:36
8eca5df70bd638e90a8d2f14bffe56a5a140081a
{ "blob_id": "8eca5df70bd638e90a8d2f14bffe56a5a140081a", "branch_name": "refs/heads/master", "committer_date": "2016-01-28T20:21:36", "content_id": "811832c3dd1dfa0447da2b7db12be7b1b97159f5", "detected_licenses": [ "MIT" ], "directory_id": "b10441cad720818486c262348effbfd456229941", "extension": "c", "filename": "nanomsg_timing.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 50998633, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3773, "license": "MIT", "license_type": "permissive", "path": "/test/nanomsg_timing.c", "provenance": "stackv2-0054.json.gz:3825", "repo_name": "lalazari/nanomsg-transport-ofi", "revision_date": "2016-01-28T20:21:36", "revision_id": "57b9dd288b1f297334233095cd6b7c212243e699", "snapshot_id": "1500f0d738adb0ee0f1051352fecd5380cc777ad", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lalazari/nanomsg-transport-ofi/57b9dd288b1f297334233095cd6b7c212243e699/test/nanomsg_timing.c", "visit_date": "2020-04-07T08:48:31.981142" }
stackv2
/** * NanoMsg libFabric Transport - Shared Functions * Copyright (c) 2015 Ioannis Charalampidis * * 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 <unistd.h> #include <assert.h> #include <libc.h> #include <stdio.h> #include <time.h> #include <sys/time.h> #include <nanomsg/nn.h> #include <nanomsg/pair.h> /* Platform-specific customisations */ #ifdef __APPLE__ #include "../src/transports/ofi/platf/osx.h" /* (Implementation in libfabric) */ #endif #define MSG_LEN 10240 #define ITERATIONS 10000 #define DIRECTION_IN 0 #define DIRECTION_OUT 1 #define NODE0 "node0" #define NODE1 "node1" const char msg_buffer[MSG_LEN]; /** * shamelessly stolen from fabtests shared.c * precision fixed to us */ int64_t get_elapsed(const struct timespec *b, const struct timespec *a) { int64_t elapsed; elapsed = (a->tv_sec - b->tv_sec) * 1000 * 1000 * 1000; elapsed += a->tv_nsec - b->tv_nsec; return elapsed / 1000; // microseconds } /** */ int run_tests( int sock, int direction ) { char *buf = NULL; struct timespec t0, t1; int iterations = ITERATIONS; int sz_n, i; // When sending, start counting before transmittion if (direction == DIRECTION_OUT) clock_gettime(CLOCK_MONOTONIC, &t0); // Exchange messages for (i=0; i<iterations; i++) { // Send or receive if (direction == DIRECTION_OUT) { // Send message sz_n = nn_send (sock, msg_buffer, MSG_LEN, 0); assert( sz_n == MSG_LEN ); } else { // Receive message sz_n = nn_recv (sock, &buf, NN_MSG, 0); assert( sz_n == MSG_LEN ); nn_freemsg (buf); // When receiving, start counting after first receive if (i == 0) clock_gettime(CLOCK_MONOTONIC, &t0); } } // Calculate overall lattency clock_gettime(CLOCK_MONOTONIC, &t1); printf("TIM: Time per message: %8.2f us\n", get_elapsed(&t0, &t1)/i/2.0); return 0; } /** * Firtst node */ int node0 (const char *url) { int sock = nn_socket (AF_SP, NN_PAIR); assert (sock >= 0); assert (nn_bind (sock, url) >= 0); printf("TIM: I will be receiving\n"); run_tests(sock, DIRECTION_IN); nn_shutdown (sock, 0); return 0; } /** * Second node */ int node1 (const char *url) { int sock = nn_socket (AF_SP, NN_PAIR); assert (sock >= 0); assert (nn_connect (sock, url) >= 0); printf("TIM: I will be sending\n"); run_tests(sock, DIRECTION_OUT); nn_shutdown (sock, 0); return 0; } /** * Entry point */ int main (const int argc, const char **argv) { if (strncmp (NODE0, argv[1], strlen (NODE0)) == 0 && argc > 1) return node0 (argv[2]); else if (strncmp (NODE1, argv[1], strlen (NODE1)) == 0 && argc > 1) return node1 (argv[2]); else { fprintf (stderr, "Usage: pair %s|%s <URL> <ARG> ...\n", NODE0, NODE1); return 1; } return 0; }
2.359375
2
2024-11-18T19:35:00.399018+00:00
2020-05-31T11:53:11
c5972618a84b8bde32a4dd7d8cb0819fcf763d9f
{ "blob_id": "c5972618a84b8bde32a4dd7d8cb0819fcf763d9f", "branch_name": "refs/heads/master", "committer_date": "2020-05-31T11:53:11", "content_id": "c69c6c154aedc0abd8dcd26d47680b54f6a3968f", "detected_licenses": [ "MIT" ], "directory_id": "504195662c63d281827ce3449ec453ea500cbf22", "extension": "c", "filename": "filter_ip.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 254323760, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1895, "license": "MIT", "license_type": "permissive", "path": "/source/filter_ip.c", "provenance": "stackv2-0054.json.gz:3954", "repo_name": "Cheney0114/firewall-based-on-netfilter", "revision_date": "2020-05-31T11:53:11", "revision_id": "aa29db8cdd342534f6cd2a5a8175b571c00bd021", "snapshot_id": "727ce57b0655f67b780fd0d7ce1f2c3201edb685", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/Cheney0114/firewall-based-on-netfilter/aa29db8cdd342534f6cd2a5a8175b571c00bd021/source/filter_ip.c", "visit_date": "2021-06-02T10:28:15.887585" }
stackv2
#ifndef __KERNEL__ #define __KERNEL__ #endif #ifndef MODULE #define MODULE #endif #include <linux/module.h> #include <linux/kernel.h> #include <linux/skbuff.h> #include <net/tcp.h> #include <linux/netdevice.h> #include <linux/netfilter.h> #include <linux/netfilter_ipv4.h> #include <linux/inet.h> //by llh //#include <linux/netfilter.h> //by llh /*struct that is used for register hook*/ static struct nf_hook_ops nfho; /* definition of hook function */ unsigned int hook_func(unsigned int hooknum, //where to put the filter struct sk_buff *skb, const struct net_device *in, const struct net_device *out, int (*okfn)(struct sk_buff *)) { struct sk_buff *pskb=skb; struct iphdr *ip_header = ip_hdr(pskb); /* printk("package from %d.%d.%d.%d\n",ip_header->saddr&0x000000FF, (ip_header->saddr&0x0000FF00)>>8, (ip_header->saddr&0x00FF0000)>>16, (ip_header->saddr&0xFF000000)>>24);*/ if((ip_header->saddr/*nh.iph->saddr by llh*/)==in_aton("192.168.0.103")) //check the source { printk("<0>""A Packet from 192.168.0.103: DROP\n"); return NF_DROP; } else { return NF_ACCEPT; } } /* module initial function */ int init_module() { /* init the struct */ nfho.hook = (nf_hookfn *)hook_func; /* hook function */ nfho.hooknum = NF_INET_PRE_ROUTING;/*NF_IP_PRE_ROUTING;by llh the hook point */ nfho.pf = PF_INET; /* potocol family */ nfho.priority = NF_IP_PRI_FIRST; /* priority */ nf_register_hook(&nfho); /* register the hook */ return 0; } /* module clean function */ void cleanup_module() { nf_unregister_hook(&nfho); printk("<0>""exit!\n"); } MODULE_LICENSE("GPL"); MODULE_AUTHOR("llh");
2.1875
2
2024-11-18T19:35:00.581465+00:00
2018-01-16T19:07:35
1971a8b461897d65e99f14ccedb01f79052ba2e6
{ "blob_id": "1971a8b461897d65e99f14ccedb01f79052ba2e6", "branch_name": "refs/heads/master", "committer_date": "2018-01-16T19:07:35", "content_id": "4378721fdf4e4f97f7c2774b16b9ac8a0362b7e7", "detected_licenses": [ "Unlicense" ], "directory_id": "8978ad70030b2904dfccb934af2e306484b33480", "extension": "h", "filename": "musl.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": 8100, "license": "Unlicense", "license_type": "permissive", "path": "/musl.h", "provenance": "stackv2-0054.json.gz:4210", "repo_name": "xlar54/musl", "revision_date": "2018-01-16T19:07:35", "revision_id": "e4145cf5cc851e9a87a7c2178020eb36ec0802c7", "snapshot_id": "45429a5453365ad327754dc788a19c9a2c509456", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/xlar54/musl/e4145cf5cc851e9a87a7c2178020eb36ec0802c7/musl.h", "visit_date": "2022-01-15T13:49:39.851274" }
stackv2
/* * Musl: A silly scripting language. * This file allows you to embed the Musl interpreter into * your own applications. * *2 API *# {*Musl*} provides an API through which it can be embedded into *# other applications in order to provide a scripting interface.\n *# About terminology:\n *{ ** The {/interpreter/} is contained in the {{struct ~~musl}}. *# It is created with the {{~~mu_create()}} function. ** A {/script/} is a string of text containing Musl code that *# is evaluated by {{~~mu_run()}} on an interpreter. ** The interpreter contains {/variables/}. Multiple scripts can *# be executed on the same interpreter (through multiple calls *# to {{~~mu_run()}}) in which case they will have access to the *# same variables.\n ** The term {/"external function"/} is used to describe a function *# written in C that matches the {{~~mu_func}} prototype and is *# registered with the interpreter through {{~~mu_add_func()}} *# so that it can be called from scripts. *} *# For more information: *{ ** See {{main.c}} for an example of how to add Musl to your applications. ** See {{musl.c}} for details about the implementation of the API. *} */ #ifndef MUSL_H #define MUSL_H /* Version number: */ #define MUSL_VERSION 0.1234 #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /*@ struct ##musl *# The {*Musl*} structure that contains the state of the interpreter.\n *# It is created with {{~~mu_create()}}.\n *# A script is run on the interpreter with {{~~mu_run()}}.\n *# The structure is destroyed with {{~~mu_cleanup()}}. */ struct musl; /*@ char *##mu_readfile(const char *fname) *# Helper function to read an entire file into memory. *# The returned pointer should be {{free()}}'d when no loger in use. */ char *mu_readfile(const char *fname); /*@ struct musl *##mu_create() *# Creates a {{~~musl}} interpreter structure.\n *# Use {{~~mu_run()}} to execute a script against the new interpreter.\n *# Use {{~~mu_cleanup()}} to deallocate it's memory when it is no longer in use.\n *# It will return {{NULL}} if a {{malloc()}} failed. */ struct musl *mu_create(); /*@ void ##mu_cleanup(struct musl *m) *# Deallocates an interpreter. */ void mu_cleanup(struct musl *m); /*@ int ##mu_run(struct musl *m, const char *script) *# Runs a script through an interpreter structure.\n *# Returns 0 if the script contains errors, in which *# case {{~~mu_error_msg()}} can be used to retrieve a *# description of the error, and {{~~mu_error_text()}} can *# be used to retrieve the text in the script where *# the error occured. */ int mu_run(struct musl *m, const char *script); /*@ int ##mu_gosub(struct musl *m, const char *label) *# Executes a subroutine in a script from an external *# function.\n *# The purpose of this function is to allow some *# sort of callback mechanism (musl calls C calls musl).\n *# Note that it must only be called from some external *# function (see {{~~mu_func}}), since only {{~~mu_run()}} knows *# about the labels of subroutines.\n *# It returns 1 on success and 0 on failure, in which *# case the external function should clean up and then *# call {{~~mu_throw()}} to terminate the script. */ int mu_gosub(struct musl *m, const char *label); /*@ void ##mu_halt(struct musl *m) *# Stops the interpreter.\n *# If you call this from an external function, *# the interpreter will behave as if it reached *# an END statement. */ void mu_halt(struct musl *m); /*@ enum ##mu_ptype {mu_int, mu_str} *# Type of function parameter/return value. *# See {{~~mu_par}}'s {{type}} field. */ enum mu_ptype {mu_int, mu_str}; /*@ struct ##mu_par *# Function parameter/return type structure. *[ *# struct mu_par { *# enum mu_ptype type; *# union { *# int i; *# char *s; *# } v; *# } *] */ struct mu_par { enum mu_ptype type; union { int i; char *s; } v; }; /*@ typedef struct mu_par (*##mu_func)(struct musl *m, int argc, struct mu_par argv[]) *# Prototype for external functions that are added through {{~~mu_add_func()}}. *{ ** {{m}} is the interpreter. You can use it as a parameter to other API funtions. ** {{argc}} is the number of parameters - the number of elements in the {{argv}} array. ** {{argv}} is the parameters to the function. *} */ typedef struct mu_par (*mu_func)(struct musl *m, int argc, struct mu_par argv[]); /*@ int ##mu_add_func(struct musl *m, const char *name, mu_func fun) *# Adds a {{~~mu_func}} function {{fun}} named {{name}} to the interpreter.\n *# Existing functions are replaced.\n *# Returns 0 on failure. */ int mu_add_func(struct musl *m, const char *name, mu_func fun); /*@ void ##mu_throw(struct musl *m, const char *msg, ...) *# Reports errors that happen in external functions. *N Only call it from within external functions. *# Don't call it from anywhere else because it uses *# {{longjmp()}} to return to the {{~~mu_run()}}. */ void mu_throw(struct musl *m, const char *msg, ...); /*@ const char *##mu_error_msg(struct musl *m) *# Retrieves a text description of errors that occured. */ const char *mu_error_msg(struct musl *m); /*@ const char *##mu_error_text(struct musl *m) *# Retrieves the text in the script where the *# last error occured. */ const char *mu_error_text(struct musl *m); /*@ int ##mu_cur_line(struct musl *m) *# Returns the current line number (actual line, not the label) *# in the script where the interpreter was last executing.\n *# The memory to which the {{script}} parameter of {{~~mu_run()}} *# points should still be valid, because it is used internally. */ int mu_cur_line(struct musl *m); /*@ int ##mu_par_int(struct musl *m, int n) *# Gets the {{n}}'th parameter of a function as a number.\n *# Only call it from {{~~mu_func()}} external functions because *# it uses {{~~mu_throw()}} on errors. */ int mu_par_int(struct musl *m, int n, int argc, struct mu_par argv[]); /*@ const char *##mu_par_str(struct musl *m, int n) *# Gets the {{n}}'th parameter of a function as a string.\n *# Only call it from {{~~mu_func()}} external functions because *# it uses {{~~mu_throw()}} on errors. */ const char *mu_par_str(struct musl *m, int n, int argc, struct mu_par argv[]); /*@ int ##mu_set_int(struct musl *m, const char *name, int num) *# Sets the value of a numeric variable.\n *# Returns 0 on failure. */ int mu_set_int(struct musl *m, const char *name, int num); /*@ int ##mu_get_int(struct musl *m, const char *name) *# Gets the value of a numeric variable. */ int mu_get_int(struct musl *m, const char *name); /*@ int ##mu_set_str(struct musl *m, const char *name, const char *val) *# Sets the value of a variable to a string.\n *# Returns 0 on failure. */ int mu_set_str(struct musl *m, const char *name, const char *val); /*@ const char *##mu_get_str(struct musl *m, const char *name) *# Retrieves the value of a variable as a string.\n *# Returns {{NULL}} on if the value does not exist. */ const char *mu_get_str(struct musl *m, const char *name); /*@ int ##mu_has_var(struct musl *m, const char *name) *# Returns 1 if the variable {{name}} is defined in the *# interpreter, 0 otherwise. */ int mu_has_var(struct musl *m, const char *name); /*@ void ##mu_set_data(struct musl *m, void *data) *# Stores arbitrary user data in the musl structure *# that can later be retrieved with {{~~mu_get_data()}} */ void mu_set_data(struct musl *m, void *data); /*@ void *##mu_get_data(struct musl *m) *# Retrieves user data from the musl structure *# that was previously stored with {{~~mu_set_data()}} */ void *mu_get_data(struct musl *m); /*@ void ##mu_dump(struct musl *m, FILE *f) *# Dumps the contents of the interpreter's variables to the file {{f}}.\n *# This is useful for debugging purposes. */ void mu_dump(struct musl *m, FILE *f); /*@ int ##mu_valid_id(const char *id) *# Returns 1 if {{id}} is a valid Musl identifier, *# otherwise it returns 0. */ int mu_valid_id(const char *id); #if defined(__cplusplus) || defined(c_plusplus) } /* extern "C" */ #endif #endif /* MUSL_H */
2.59375
3
2024-11-18T19:35:00.652530+00:00
2020-02-27T14:51:48
9e3cebd5c5b2997454606382baf8f416aea250a6
{ "blob_id": "9e3cebd5c5b2997454606382baf8f416aea250a6", "branch_name": "refs/heads/master", "committer_date": "2020-02-27T14:51:48", "content_id": "3732df2ef736fb803b4bdfeec69eab0813b5f80d", "detected_licenses": [ "Apache-2.0" ], "directory_id": "d4c74a8001451840f3efb87f15856cdb9d5e9eb6", "extension": "c", "filename": "conv1d_sw.c", "fork_events_count": 0, "gha_created_at": "2020-01-23T14:39:58", "gha_event_created_at": "2020-01-23T14:39:59", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 235814026, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1911, "license": "Apache-2.0", "license_type": "permissive", "path": "/examples/native/mbed/test_driver_gap9/test_FILTER/conv1d_sw.c", "provenance": "stackv2-0054.json.gz:4338", "repo_name": "danieldennett/gap_sdk", "revision_date": "2020-02-27T14:51:48", "revision_id": "5667c899025a3a152dbf91e5c18e5b3e422d4ea6", "snapshot_id": "3e4b4d187f03a28a761b08aed36a5e6a06f48e8d", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/danieldennett/gap_sdk/5667c899025a3a152dbf91e5c18e5b3e422d4ea6/examples/native/mbed/test_driver_gap9/test_FILTER/conv1d_sw.c", "visit_date": "2020-12-19T19:17:40.083131" }
stackv2
#include "conv1d_sw.h" void conv1d_uint16(uint16_t *data,uint16_t *result,uint16_t *kernel,uint32_t data_size, uint32_t kernel_size) { uint16_t acc; uint32_t num_windows = data_size - kernel_size + 1; for(uint32_t i=0;i<num_windows;i++) { acc=0; //printf("Window %d/%d\n",i,num_windows); for(uint32_t j=0;j<kernel_size;j++) { acc=acc+data[i+j]*kernel[j]; } result[i]=acc; } } void conv1d_int16(short int *data,short int *result,short int *kernel,uint32_t data_size, uint32_t kernel_size) { short int acc; uint32_t num_windows = data_size - kernel_size + 1; for(uint32_t i=0;i<num_windows;i++) { acc=0; for(uint32_t j=0;j<kernel_size;j++) { acc=acc+data[i+j]*kernel[j]; } result[i]=acc; } } void conv1d_uint32(uint32_t *data,uint32_t *result,uint32_t *kernel,uint32_t data_size, uint32_t kernel_size) { uint32_t acc; uint32_t num_windows = data_size - kernel_size + 1; for(uint32_t i=0;i<num_windows;i++) { acc=0; for(uint32_t j=0;j<kernel_size;j++) { acc=acc+data[i+j]*kernel[j]; } result[i]=acc; } } void conv1d_int32(int *data,int *result,int *kernel,uint32_t data_size, uint32_t kernel_size) { int acc; uint32_t num_windows = data_size - kernel_size + 1; for(uint32_t i=0;i<num_windows;i++) { acc=0; for(uint32_t j=0;j<kernel_size;j++) { acc=acc+data[i+j]*kernel[j]; } result[i]=acc; } } void vect_AxREGpB_uint16(uint16_t *vect_a,uint16_t *vect_b,uint16_t reg0,uint16_t *result,uint16_t size) { for(uint32_t i=0;i<size;i++) { result[i]=reg0*vect_a[i]+vect_b[i]; } } void vect_ApB_uint16(uint16_t *vect_a,uint16_t *vect_b,uint16_t *result,uint16_t size) { for(uint32_t i=0;i<size;i++) { result[i]=vect_a[i]+vect_b[i]; } }
2.34375
2
2024-11-18T19:35:00.733237+00:00
2022-06-03T22:32:35
527a6b7ec2e1ac0f47e0c4483ed69fde7743b293
{ "blob_id": "527a6b7ec2e1ac0f47e0c4483ed69fde7743b293", "branch_name": "refs/heads/master", "committer_date": "2022-06-03T22:49:26", "content_id": "1fd60fd32a8f8bec6ca75878957c236bf42d0a4d", "detected_licenses": [ "Apache-2.0", "curl" ], "directory_id": "b7061e3f678190e1e40be7d3e1151b1c278dfaa2", "extension": "c", "filename": "v2beta2_horizontal_pod_autoscaler_behavior.c", "fork_events_count": 0, "gha_created_at": "2020-03-23T05:00:49", "gha_event_created_at": "2022-06-03T22:56:11", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 249339642, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4576, "license": "Apache-2.0,curl", "license_type": "permissive", "path": "/kubernetes/model/v2beta2_horizontal_pod_autoscaler_behavior.c", "provenance": "stackv2-0054.json.gz:4466", "repo_name": "brendandburns/c", "revision_date": "2022-06-03T22:32:35", "revision_id": "6be8eca36e73be0d6a8c752e0b2b9e3f36eb6143", "snapshot_id": "967147816092bf88cfb9b5369465de52a599fd28", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/brendandburns/c/6be8eca36e73be0d6a8c752e0b2b9e3f36eb6143/kubernetes/model/v2beta2_horizontal_pod_autoscaler_behavior.c", "visit_date": "2022-07-10T05:22:49.165574" }
stackv2
#include <stdlib.h> #include <string.h> #include <stdio.h> #include "v2beta2_horizontal_pod_autoscaler_behavior.h" v2beta2_horizontal_pod_autoscaler_behavior_t *v2beta2_horizontal_pod_autoscaler_behavior_create( v2beta2_hpa_scaling_rules_t *scale_down, v2beta2_hpa_scaling_rules_t *scale_up ) { v2beta2_horizontal_pod_autoscaler_behavior_t *v2beta2_horizontal_pod_autoscaler_behavior_local_var = malloc(sizeof(v2beta2_horizontal_pod_autoscaler_behavior_t)); if (!v2beta2_horizontal_pod_autoscaler_behavior_local_var) { return NULL; } v2beta2_horizontal_pod_autoscaler_behavior_local_var->scale_down = scale_down; v2beta2_horizontal_pod_autoscaler_behavior_local_var->scale_up = scale_up; return v2beta2_horizontal_pod_autoscaler_behavior_local_var; } void v2beta2_horizontal_pod_autoscaler_behavior_free(v2beta2_horizontal_pod_autoscaler_behavior_t *v2beta2_horizontal_pod_autoscaler_behavior) { if(NULL == v2beta2_horizontal_pod_autoscaler_behavior){ return ; } listEntry_t *listEntry; if (v2beta2_horizontal_pod_autoscaler_behavior->scale_down) { v2beta2_hpa_scaling_rules_free(v2beta2_horizontal_pod_autoscaler_behavior->scale_down); v2beta2_horizontal_pod_autoscaler_behavior->scale_down = NULL; } if (v2beta2_horizontal_pod_autoscaler_behavior->scale_up) { v2beta2_hpa_scaling_rules_free(v2beta2_horizontal_pod_autoscaler_behavior->scale_up); v2beta2_horizontal_pod_autoscaler_behavior->scale_up = NULL; } free(v2beta2_horizontal_pod_autoscaler_behavior); } cJSON *v2beta2_horizontal_pod_autoscaler_behavior_convertToJSON(v2beta2_horizontal_pod_autoscaler_behavior_t *v2beta2_horizontal_pod_autoscaler_behavior) { cJSON *item = cJSON_CreateObject(); // v2beta2_horizontal_pod_autoscaler_behavior->scale_down if(v2beta2_horizontal_pod_autoscaler_behavior->scale_down) { cJSON *scale_down_local_JSON = v2beta2_hpa_scaling_rules_convertToJSON(v2beta2_horizontal_pod_autoscaler_behavior->scale_down); if(scale_down_local_JSON == NULL) { goto fail; //model } cJSON_AddItemToObject(item, "scaleDown", scale_down_local_JSON); if(item->child == NULL) { goto fail; } } // v2beta2_horizontal_pod_autoscaler_behavior->scale_up if(v2beta2_horizontal_pod_autoscaler_behavior->scale_up) { cJSON *scale_up_local_JSON = v2beta2_hpa_scaling_rules_convertToJSON(v2beta2_horizontal_pod_autoscaler_behavior->scale_up); if(scale_up_local_JSON == NULL) { goto fail; //model } cJSON_AddItemToObject(item, "scaleUp", scale_up_local_JSON); if(item->child == NULL) { goto fail; } } return item; fail: if (item) { cJSON_Delete(item); } return NULL; } v2beta2_horizontal_pod_autoscaler_behavior_t *v2beta2_horizontal_pod_autoscaler_behavior_parseFromJSON(cJSON *v2beta2_horizontal_pod_autoscaler_behaviorJSON){ v2beta2_horizontal_pod_autoscaler_behavior_t *v2beta2_horizontal_pod_autoscaler_behavior_local_var = NULL; // define the local variable for v2beta2_horizontal_pod_autoscaler_behavior->scale_down v2beta2_hpa_scaling_rules_t *scale_down_local_nonprim = NULL; // define the local variable for v2beta2_horizontal_pod_autoscaler_behavior->scale_up v2beta2_hpa_scaling_rules_t *scale_up_local_nonprim = NULL; // v2beta2_horizontal_pod_autoscaler_behavior->scale_down cJSON *scale_down = cJSON_GetObjectItemCaseSensitive(v2beta2_horizontal_pod_autoscaler_behaviorJSON, "scaleDown"); if (scale_down) { scale_down_local_nonprim = v2beta2_hpa_scaling_rules_parseFromJSON(scale_down); //nonprimitive } // v2beta2_horizontal_pod_autoscaler_behavior->scale_up cJSON *scale_up = cJSON_GetObjectItemCaseSensitive(v2beta2_horizontal_pod_autoscaler_behaviorJSON, "scaleUp"); if (scale_up) { scale_up_local_nonprim = v2beta2_hpa_scaling_rules_parseFromJSON(scale_up); //nonprimitive } v2beta2_horizontal_pod_autoscaler_behavior_local_var = v2beta2_horizontal_pod_autoscaler_behavior_create ( scale_down ? scale_down_local_nonprim : NULL, scale_up ? scale_up_local_nonprim : NULL ); return v2beta2_horizontal_pod_autoscaler_behavior_local_var; end: if (scale_down_local_nonprim) { v2beta2_hpa_scaling_rules_free(scale_down_local_nonprim); scale_down_local_nonprim = NULL; } if (scale_up_local_nonprim) { v2beta2_hpa_scaling_rules_free(scale_up_local_nonprim); scale_up_local_nonprim = NULL; } return NULL; }
2.03125
2
2024-11-18T19:35:00.897989+00:00
2023-09-02T14:55:31
d7c8bf5327321fa02c111fdbf31ddd77c0859223
{ "blob_id": "d7c8bf5327321fa02c111fdbf31ddd77c0859223", "branch_name": "refs/heads/master", "committer_date": "2023-09-02T14:55:31", "content_id": "18fc91d135d63da4c7e128b26c9250ce2aaba398", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "8838eb997879add5759b6dfb23f9a646464e53ca", "extension": "c", "filename": "write.c", "fork_events_count": 325, "gha_created_at": "2015-03-29T15:27:48", "gha_event_created_at": "2023-09-14T16:58:34", "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 33078138, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 21191, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/fs/driver/jffs2/write.c", "provenance": "stackv2-0054.json.gz:4723", "repo_name": "embox/embox", "revision_date": "2023-09-02T14:55:31", "revision_id": "98e3c06e33f3fdac10a29c069c20775568e0a6d1", "snapshot_id": "d6aacec876978522f01cdc4b8de37a668c6f4c80", "src_encoding": "UTF-8", "star_events_count": 1087, "url": "https://raw.githubusercontent.com/embox/embox/98e3c06e33f3fdac10a29c069c20775568e0a6d1/src/fs/driver/jffs2/write.c", "visit_date": "2023-09-04T03:02:20.165042" }
stackv2
/* * JFFS2 -- Journalling Flash File System, Version 2. * * Copyright (C) 2001-2003 Red Hat, Inc. * * Created by David Woodhouse <[email protected]> * * For licensing information, see the file 'LICENCE' in this directory. * * $Id: write.c,v 1.94 2005/07/20 15:50:51 dedekind Exp $ * */ #include <linux/kernel.h> #include <linux/fs.h> #include <linux/crc32.h> #include <linux/slab.h> #include <linux/pagemap.h> #include <linux/mtd/mtd.h> #include "nodelist.h" #include "compr.h" int jffs2_do_new_inode(struct jffs2_sb_info *c, struct jffs2_inode_info *f, uint32_t mode, struct jffs2_raw_inode *ri) { struct jffs2_inode_cache *ic; ic = jffs2_alloc_inode_cache(); if (!ic) { return -ENOMEM; } memset(ic, 0, sizeof(*ic)); f->inocache = ic; f->inocache->nlink = 1; f->inocache->nodes = (struct jffs2_raw_node_ref *)f->inocache; f->inocache->state = INO_STATE_PRESENT; jffs2_add_ino_cache(c, f->inocache); D1(printk( "jffs2_do_new_inode(): Assigned ino# %d\n", f->inocache->ino)); ri->ino = cpu_to_je32(f->inocache->ino); ri->magic = cpu_to_je16(JFFS2_MAGIC_BITMASK); ri->nodetype = cpu_to_je16(JFFS2_NODETYPE_INODE); ri->totlen = cpu_to_je32(PAD(sizeof(*ri))); ri->hdr_crc = cpu_to_je32(crc32(0, ri, sizeof(struct jffs2_unknown_node)-4)); ri->mode = cpu_to_jemode(mode); f->highest_version = 1; ri->version = cpu_to_je32(f->highest_version); return 0; } /** * jffs2_write_dnode - given a raw_inode, allocate a full_dnode for it, * write it to the flash, link it into the existing inode/fragment list */ struct jffs2_full_dnode *jffs2_write_dnode(struct jffs2_sb_info *c, struct jffs2_inode_info *f, struct jffs2_raw_inode *ri, const unsigned char *data, uint32_t datalen, uint32_t flash_ofs, int alloc_mode) { struct jffs2_raw_node_ref *raw; struct jffs2_full_dnode *fn; size_t retlen; struct iovec vecs[2]; int ret; uint32_t dummy; struct jffs2_eraseblock *jeb; int retried = 0; unsigned long cnt = 2; D1( if(je32_to_cpu(ri->hdr_crc) != crc32(0, ri, sizeof(struct jffs2_unknown_node)-4)) { printk(KERN_CRIT "Eep. CRC not correct in jffs2_write_dnode()\n"); BUG(); } ); vecs[0].iov_base = ri; vecs[0].iov_len = sizeof(*ri); vecs[1].iov_base = (unsigned char *)data; vecs[1].iov_len = datalen; jffs2_dbg_prewrite_paranoia_check(c, flash_ofs, vecs[0].iov_len + vecs[1].iov_len); if (je32_to_cpu(ri->totlen) != sizeof(*ri) + datalen) { printk(KERN_WARNING "jffs2_write_dnode: ri->totlen (0x%08x) != sizeof(*ri) (0x%08zx) + datalen (0x%08x)\n", je32_to_cpu(ri->totlen), sizeof(*ri), datalen); } raw = jffs2_alloc_raw_node_ref(); if (!raw) { return ERR_PTR(-ENOMEM); } fn = jffs2_alloc_full_dnode(); if (!fn) { jffs2_free_raw_node_ref(raw); return ERR_PTR(-ENOMEM); } fn->ofs = je32_to_cpu(ri->offset); fn->size = je32_to_cpu(ri->dsize); fn->frags = 0; /* check number of valid vecs */ if (!datalen || !data) { cnt = 1; } retry: fn->raw = raw; raw->flash_offset = flash_ofs; raw->__totlen = PAD(sizeof(*ri)+datalen); raw->next_phys = NULL; if ((alloc_mode!=ALLOC_GC) && (je32_to_cpu(ri->version) < f->highest_version)) { BUG_ON(!retried); D1(printk( "jffs2_write_dnode : dnode_version %d, " "highest version %d -> updating dnode\n", je32_to_cpu(ri->version), f->highest_version)); ri->version = cpu_to_je32(++f->highest_version); ri->node_crc = cpu_to_je32(crc32(0, ri, sizeof(*ri)-8)); } ret = jffs2_flash_writev(c, vecs, cnt, flash_ofs, &retlen, (alloc_mode==ALLOC_GC)?0:f->inocache->ino); if (ret || (retlen != sizeof(*ri) + datalen)) { printk(KERN_NOTICE "Write of %zd bytes at 0x%08x failed. returned %d, retlen %zd\n", sizeof(*ri)+datalen, flash_ofs, ret, retlen); /* Mark the space as dirtied */ if (retlen) { /* Doesn't belong to any inode */ raw->next_in_ino = NULL; /* Don't change raw->size to match retlen. We may have * written the node header already, and only the data will * seem corrupted, in which case the scan would skip over * any node we write before the original intended end of * this node */ raw->flash_offset |= REF_OBSOLETE; jffs2_add_physical_node_ref(c, raw); jffs2_mark_node_obsolete(c, raw); } else { printk(KERN_NOTICE "Not marking the space at 0x%08x as dirty because the flash driver returned retlen zero\n", raw->flash_offset); jffs2_free_raw_node_ref(raw); } if (!retried && alloc_mode != ALLOC_NORETRY && (raw = jffs2_alloc_raw_node_ref())) { /* Try to reallocate space and retry */ jeb = &c->blocks[flash_ofs / c->sector_size]; retried = 1; D1(printk( "Retrying failed write.\n")); jffs2_dbg_acct_sanity_check(c,jeb); jffs2_dbg_acct_paranoia_check(c, jeb); if (alloc_mode == ALLOC_GC) { ret = jffs2_reserve_space_gc(c, sizeof(*ri) + datalen, &flash_ofs, &dummy); } else { /* Locking pain */ up(&f->sem); jffs2_complete_reservation(c); ret = jffs2_reserve_space(c, sizeof(*ri) + datalen, &flash_ofs, &dummy, alloc_mode); down(&f->sem); } if (!ret) { D1(printk( "Allocated space at 0x%08x to retry failed write.\n", flash_ofs)); jffs2_dbg_acct_sanity_check(c,jeb); jffs2_dbg_acct_paranoia_check(c, jeb); goto retry; } D1(printk( "Failed to allocate space to retry failed write: %d!\n", ret)); jffs2_free_raw_node_ref(raw); } /* Release the full_dnode which is now useless, and return */ jffs2_free_full_dnode(fn); return ERR_PTR(ret?ret:-EIO); } /* Mark the space used */ /* If node covers at least a whole page, or if it starts at the beginning of a page and runs to the end of the file, or if it's a hole node, mark it REF_PRISTINE, else REF_NORMAL. */ if ((je32_to_cpu(ri->dsize) >= PAGE_CACHE_SIZE) || ( ((je32_to_cpu(ri->offset)&(PAGE_CACHE_SIZE-1))==0) && (je32_to_cpu(ri->dsize)+je32_to_cpu(ri->offset) == je32_to_cpu(ri->isize)))) { raw->flash_offset |= REF_PRISTINE; } else { raw->flash_offset |= REF_NORMAL; } jffs2_add_physical_node_ref(c, raw); /* Link into per-inode list */ spin_lock(&c->erase_completion_lock); raw->next_in_ino = f->inocache->nodes; f->inocache->nodes = raw; spin_unlock(&c->erase_completion_lock); D1(printk( "jffs2_write_dnode wrote node at 0x%08x(%d) with dsize 0x%x, csize 0x%x, node_crc 0x%08x, data_crc 0x%08x, totlen 0x%08x\n", flash_ofs, ref_flags(raw), je32_to_cpu(ri->dsize), je32_to_cpu(ri->csize), je32_to_cpu(ri->node_crc), je32_to_cpu(ri->data_crc), je32_to_cpu(ri->totlen))); if (retried) { jffs2_dbg_acct_sanity_check(c,NULL); } return fn; } struct jffs2_full_dirent *jffs2_write_dirent(struct jffs2_sb_info *c, struct jffs2_inode_info *f, struct jffs2_raw_dirent *rd, const unsigned char *name, uint32_t namelen, uint32_t flash_ofs, int alloc_mode) { struct jffs2_raw_node_ref *raw; struct jffs2_full_dirent *fd; size_t retlen; struct iovec vecs[2]; int retried = 0; int ret; D1(printk( "jffs2_write_dirent(ino #%u, name at *0x%p \"%s\"->ino #%u, name_crc 0x%08x)\n", je32_to_cpu(rd->pino), name, name, je32_to_cpu(rd->ino), je32_to_cpu(rd->name_crc))); D1( if(je32_to_cpu(rd->hdr_crc) != crc32(0, rd, sizeof(struct jffs2_unknown_node)-4)) { printk(KERN_CRIT "Eep. CRC not correct in jffs2_write_dirent()\n"); BUG(); } ); vecs[0].iov_base = rd; vecs[0].iov_len = sizeof(*rd); vecs[1].iov_base = (unsigned char *)name; vecs[1].iov_len = namelen; jffs2_dbg_prewrite_paranoia_check(c, flash_ofs, vecs[0].iov_len + vecs[1].iov_len); raw = jffs2_alloc_raw_node_ref(); if (!raw) { return ERR_PTR(-ENOMEM); } fd = jffs2_alloc_full_dirent(namelen+1); if (!fd) { jffs2_free_raw_node_ref(raw); return ERR_PTR(-ENOMEM); } fd->version = je32_to_cpu(rd->version); fd->ino = je32_to_cpu(rd->ino); fd->nhash = full_name_hash(name, strlen((const char *) name)); fd->type = rd->type; memcpy(fd->name, name, namelen); fd->name[namelen]=0; retry: fd->raw = raw; raw->flash_offset = flash_ofs; raw->__totlen = PAD(sizeof(*rd)+namelen); raw->next_phys = NULL; if ((alloc_mode!=ALLOC_GC) && (je32_to_cpu(rd->version) < f->highest_version)) { BUG_ON(!retried); D1(printk( "jffs2_write_dirent : dirent_version %d, " "highest version %d -> updating dirent\n", je32_to_cpu(rd->version), f->highest_version)); rd->version = cpu_to_je32(++f->highest_version); fd->version = je32_to_cpu(rd->version); rd->node_crc = cpu_to_je32(crc32(0, rd, sizeof(*rd)-8)); } ret = jffs2_flash_writev(c, vecs, 2, flash_ofs, &retlen, (alloc_mode==ALLOC_GC)?0:je32_to_cpu(rd->pino)); if (ret || (retlen != sizeof(*rd) + namelen)) { printk(KERN_NOTICE "Write of %zd bytes at 0x%08x failed. returned %d, retlen %zd\n", sizeof(*rd)+namelen, flash_ofs, ret, retlen); /* Mark the space as dirtied */ if (retlen) { raw->next_in_ino = NULL; raw->flash_offset |= REF_OBSOLETE; jffs2_add_physical_node_ref(c, raw); jffs2_mark_node_obsolete(c, raw); } else { printk(KERN_NOTICE "Not marking the space at 0x%08x as dirty because the flash driver returned retlen zero\n", raw->flash_offset); jffs2_free_raw_node_ref(raw); } if (!retried && (raw = jffs2_alloc_raw_node_ref())) { /* Try to reallocate space and retry */ uint32_t dummy; struct jffs2_eraseblock *jeb = &c->blocks[flash_ofs / c->sector_size]; retried = 1; D1(printk( "Retrying failed write.\n")); jffs2_dbg_acct_sanity_check(c,jeb); jffs2_dbg_acct_paranoia_check(c, jeb); if (alloc_mode == ALLOC_GC) { ret = jffs2_reserve_space_gc(c, sizeof(*rd) + namelen, &flash_ofs, &dummy); } else { /* Locking pain */ up(&f->sem); jffs2_complete_reservation(c); ret = jffs2_reserve_space(c, sizeof(*rd) + namelen, &flash_ofs, &dummy, alloc_mode); down(&f->sem); } if (!ret) { D1(printk( "Allocated space at 0x%08x to retry failed write.\n", flash_ofs)); jffs2_dbg_acct_sanity_check(c,jeb); jffs2_dbg_acct_paranoia_check(c, jeb); goto retry; } D1(printk( "Failed to allocate space to retry failed write: %d!\n", ret)); jffs2_free_raw_node_ref(raw); } /* Release the full_dnode which is now useless, and return */ jffs2_free_full_dirent(fd); return ERR_PTR(ret?ret:-EIO); } /* Mark the space used */ raw->flash_offset |= REF_PRISTINE; jffs2_add_physical_node_ref(c, raw); spin_lock(&c->erase_completion_lock); raw->next_in_ino = f->inocache->nodes; f->inocache->nodes = raw; spin_unlock(&c->erase_completion_lock); if (retried) { jffs2_dbg_acct_sanity_check(c,NULL); } return fd; } /** * The OS-specific code fills in the metadata in the jffs2_raw_inode for us, so that * we don't have to go digging in struct inode or its equivalent. It should set: * mode, uid, gid, (starting)isize, atime, ctime, mtime */ int jffs2_write_inode_range(struct jffs2_sb_info *c, struct jffs2_inode_info *f, struct jffs2_raw_inode *ri, unsigned char *buf, uint32_t offset, uint32_t writelen, uint32_t *retlen) { int ret = 0; uint32_t writtenlen = 0; D1(printk( "jffs2_write_inode_range(): Ino #%u, ofs 0x%x, len 0x%x\n", f->inocache->ino, offset, writelen)); while(writelen) { struct jffs2_full_dnode *fn; unsigned char *comprbuf = NULL; uint16_t comprtype = JFFS2_COMPR_NONE; uint32_t phys_ofs, alloclen; uint32_t datalen, cdatalen; int retried = 0; retry: D2(printk( "jffs2_commit_write() loop: 0x%x to write to 0x%x\n", writelen, offset)); ret = jffs2_reserve_space(c, sizeof(*ri) + JFFS2_MIN_DATA_LEN, &phys_ofs, &alloclen, ALLOC_NORMAL); if (ret) { D1(printk( "jffs2_reserve_space returned %d\n", ret)); break; } down(&f->sem); datalen = min_t(uint32_t, writelen, PAGE_CACHE_SIZE - (offset & (PAGE_CACHE_SIZE-1))); cdatalen = min_t(uint32_t, alloclen - sizeof(*ri), datalen); comprtype = jffs2_compress(c, f, buf, &comprbuf, &datalen, &cdatalen); ri->magic = cpu_to_je16(JFFS2_MAGIC_BITMASK); ri->nodetype = cpu_to_je16(JFFS2_NODETYPE_INODE); ri->totlen = cpu_to_je32(sizeof(*ri) + cdatalen); ri->hdr_crc = cpu_to_je32(crc32(0, ri, sizeof(struct jffs2_unknown_node)-4)); ri->ino = cpu_to_je32(f->inocache->ino); ri->version = cpu_to_je32(++f->highest_version); ri->isize = cpu_to_je32(max(je32_to_cpu(ri->isize), offset + datalen)); ri->offset = cpu_to_je32(offset); ri->csize = cpu_to_je32(cdatalen); ri->dsize = cpu_to_je32(datalen); ri->compr = comprtype & 0xff; ri->usercompr = (comprtype >> 8 ) & 0xff; ri->node_crc = cpu_to_je32(crc32(0, ri, sizeof(*ri)-8)); ri->data_crc = cpu_to_je32(crc32(0, comprbuf, cdatalen)); fn = jffs2_write_dnode(c, f, ri, comprbuf, cdatalen, phys_ofs, ALLOC_NORETRY); jffs2_free_comprbuf(comprbuf, buf); if (IS_ERR(fn)) { ret = PTR_ERR(fn); up(&f->sem); jffs2_complete_reservation(c); if (!retried) { /* Write error to be retried */ retried = 1; D1(printk( "Retrying node write in jffs2_write_inode_range()\n")); goto retry; } break; } ret = jffs2_add_full_dnode_to_inode(c, f, fn); if (f->metadata) { jffs2_mark_node_obsolete(c, f->metadata->raw); jffs2_free_full_dnode(f->metadata); f->metadata = NULL; } if (ret) { /* Eep */ D1(printk( "Eep. add_full_dnode_to_inode() failed in commit_write, returned %d\n", ret)); jffs2_mark_node_obsolete(c, fn->raw); jffs2_free_full_dnode(fn); up(&f->sem); jffs2_complete_reservation(c); break; } up(&f->sem); jffs2_complete_reservation(c); if (!datalen) { printk(KERN_WARNING "Eep. We didn't actually write any data in jffs2_write_inode_range()\n"); ret = -EIO; break; } D1(printk( "increasing writtenlen by %d\n", datalen)); writtenlen += datalen; offset += datalen; writelen -= datalen; buf += datalen; } *retlen = writtenlen; return ret; } int jffs2_do_create(struct jffs2_sb_info *c, struct jffs2_inode_info *dir_f, struct jffs2_inode_info *f, struct jffs2_raw_inode *ri, const char *name, int namelen) { struct jffs2_raw_dirent *rd; struct jffs2_full_dnode *fn; struct jffs2_full_dirent *fd; uint32_t alloclen, phys_ofs; int ret; /* Try to reserve enough space for both node and dirent. * Just the node will do for now, though */ ret = jffs2_reserve_space(c, sizeof(*ri), &phys_ofs, &alloclen, ALLOC_NORMAL); D1(printk( "jffs2_do_create(): reserved 0x%x bytes\n", alloclen)); if (ret) { up(&f->sem); return ret; } ri->data_crc = cpu_to_je32(0); ri->node_crc = cpu_to_je32(crc32(0, ri, sizeof(*ri)-8)); fn = jffs2_write_dnode(c, f, ri, NULL, 0, phys_ofs, ALLOC_NORMAL); D1(printk( "jffs2_do_create created file with mode 0x%x\n", jemode_to_cpu(ri->mode))); if (IS_ERR(fn)) { D1(printk( "jffs2_write_dnode() failed\n")); /* Eeek. Wave bye bye */ up(&f->sem); jffs2_complete_reservation(c); return PTR_ERR(fn); } /* No data here. Only a metadata node, which will be * obsoleted by the first data write */ f->metadata = fn; up(&f->sem); jffs2_complete_reservation(c); ret = jffs2_reserve_space(c, sizeof(*rd) + namelen, &phys_ofs, &alloclen, ALLOC_NORMAL); if (ret) { /* Eep. */ D1(printk( "jffs2_reserve_space() for dirent failed\n")); return ret; } rd = jffs2_alloc_raw_dirent(); if (!rd) { /* Argh. Now we treat it like a normal delete */ jffs2_complete_reservation(c); return -ENOMEM; } down(&dir_f->sem); rd->magic = cpu_to_je16(JFFS2_MAGIC_BITMASK); rd->nodetype = cpu_to_je16(JFFS2_NODETYPE_DIRENT); rd->totlen = cpu_to_je32(sizeof(*rd) + namelen); rd->hdr_crc = cpu_to_je32(crc32(0, rd, sizeof(struct jffs2_unknown_node)-4)); rd->pino = cpu_to_je32(dir_f->inocache->ino); rd->version = cpu_to_je32(++dir_f->highest_version); rd->ino = ri->ino; rd->mctime = ri->ctime; rd->nsize = namelen; rd->type = DT_REG; rd->node_crc = cpu_to_je32(crc32(0, rd, sizeof(*rd)-8)); rd->name_crc = cpu_to_je32(crc32(0, name, namelen)); fd = jffs2_write_dirent(c, dir_f, rd, (const unsigned char *) name, namelen, phys_ofs, ALLOC_NORMAL); jffs2_free_raw_dirent(rd); if (IS_ERR(fd)) { /* dirent failed to write. Delete the inode normally * as if it were the final unlink() */ jffs2_complete_reservation(c); up(&dir_f->sem); return PTR_ERR(fd); } /* Link the fd into the inode's list, obsoleting an old one if necessary. */ jffs2_add_fd_to_list(c, fd, &dir_f->dents); jffs2_complete_reservation(c); up(&dir_f->sem); return 0; } int jffs2_do_unlink(struct jffs2_sb_info *c, struct jffs2_inode_info *dir_f, const char *name, int namelen, struct jffs2_inode_info *dead_f) { struct jffs2_raw_dirent *rd; struct jffs2_full_dirent *fd; uint32_t alloclen, phys_ofs; int ret; if (1 /* alternative branch needs testing */ || !jffs2_can_mark_obsolete(c)) { /* We can't mark stuff obsolete on the medium. * We need to write a deletion dirent */ rd = jffs2_alloc_raw_dirent(); if (!rd) { return -ENOMEM; } ret = jffs2_reserve_space(c, sizeof(*rd) + namelen, &phys_ofs, &alloclen, ALLOC_DELETION); if (ret) { jffs2_free_raw_dirent(rd); return ret; } down(&dir_f->sem); /* Build a deletion node */ rd->magic = cpu_to_je16(JFFS2_MAGIC_BITMASK); rd->nodetype = cpu_to_je16(JFFS2_NODETYPE_DIRENT); rd->totlen = cpu_to_je32(sizeof(*rd) + namelen); rd->hdr_crc = cpu_to_je32(crc32(0, rd, sizeof(struct jffs2_unknown_node)-4)); rd->pino = cpu_to_je32(dir_f->inocache->ino); rd->version = cpu_to_je32(++dir_f->highest_version); rd->ino = cpu_to_je32(0); rd->mctime = cpu_to_je32(get_seconds()); rd->nsize = namelen; rd->type = DT_UNKNOWN; rd->node_crc = cpu_to_je32(crc32(0, rd, sizeof(*rd)-8)); rd->name_crc = cpu_to_je32(crc32(0, name, namelen)); fd = jffs2_write_dirent(c, dir_f, rd, (const unsigned char *) name, namelen, phys_ofs, ALLOC_DELETION); jffs2_free_raw_dirent(rd); if (IS_ERR(fd)) { jffs2_complete_reservation(c); up(&dir_f->sem); return PTR_ERR(fd); } /* File it. This will mark the old one obsolete. */ jffs2_add_fd_to_list(c, fd, &dir_f->dents); up(&dir_f->sem); } else { struct jffs2_full_dirent **prev = &dir_f->dents; uint32_t nhash = full_name_hash((const unsigned char *) name, namelen); down(&dir_f->sem); while ((*prev) && (*prev)->nhash <= nhash) { if ((*prev)->nhash == nhash && !memcmp((*prev)->name, name, namelen) && !(*prev)->name[namelen]) { struct jffs2_full_dirent *this = *prev; D1(printk( "Marking old dirent node (ino #%u) @%08x obsolete\n", this->ino, ref_offset(this->raw))); *prev = this->next; jffs2_mark_node_obsolete(c, (this->raw)); jffs2_free_full_dirent(this); break; } prev = &((*prev)->next); } up(&dir_f->sem); } /* dead_f is NULL if this was a rename not a real unlink */ /* Also catch the !f->inocache case, where there was a dirent pointing to an inode which didn't exist. */ if (dead_f && dead_f->inocache) { down(&dead_f->sem); if (S_ISDIR(OFNI_EDONI_2SFFJ(dead_f)->i_mode)) { while (dead_f->dents) { /* There can be only deleted ones */ fd = dead_f->dents; dead_f->dents = fd->next; if (fd->ino) { printk(KERN_WARNING "Deleting inode #%u with active dentry \"%s\"->ino #%u\n", dead_f->inocache->ino, fd->name, fd->ino); } else { D1(printk( "Removing deletion dirent for \"%s\" from dir ino #%u\n", fd->name, dead_f->inocache->ino)); } jffs2_mark_node_obsolete(c, fd->raw); jffs2_free_full_dirent(fd); } } dead_f->inocache->nlink--; /* NB: Caller must set inode nlink if appropriate */ up(&dead_f->sem); } jffs2_complete_reservation(c); return 0; } int jffs2_do_link (struct jffs2_sb_info *c, struct jffs2_inode_info *dir_f, uint32_t ino, uint8_t type, const char *name, int namelen) { struct jffs2_raw_dirent *rd; struct jffs2_full_dirent *fd; uint32_t alloclen, phys_ofs; int ret; rd = jffs2_alloc_raw_dirent(); if (!rd) return -ENOMEM; ret = jffs2_reserve_space(c, sizeof(*rd) + namelen, &phys_ofs, &alloclen, ALLOC_NORMAL); if (ret) { jffs2_free_raw_dirent(rd); return ret; } down(&dir_f->sem); /* Build a deletion node */ rd->magic = cpu_to_je16(JFFS2_MAGIC_BITMASK); rd->nodetype = cpu_to_je16(JFFS2_NODETYPE_DIRENT); rd->totlen = cpu_to_je32(sizeof(*rd) + namelen); rd->hdr_crc = cpu_to_je32(crc32(0, rd, sizeof(struct jffs2_unknown_node) - 4)); rd->pino = cpu_to_je32(dir_f->inocache->ino); rd->version = cpu_to_je32(++dir_f->highest_version); rd->ino = cpu_to_je32(ino); rd->mctime = cpu_to_je32(get_seconds()); rd->nsize = namelen; rd->type = type; rd->node_crc = cpu_to_je32(crc32(0, rd, sizeof(*rd)-8)); rd->name_crc = cpu_to_je32(crc32(0, name, namelen)); fd = jffs2_write_dirent(c, dir_f, rd, (const unsigned char *) name, namelen, phys_ofs, ALLOC_NORMAL); jffs2_free_raw_dirent(rd); if (IS_ERR(fd)) { jffs2_complete_reservation(c); up(&dir_f->sem); return PTR_ERR(fd); } /* File it. This will mark the old one obsolete. */ jffs2_add_fd_to_list(c, fd, &dir_f->dents); jffs2_complete_reservation(c); up(&dir_f->sem); return 0; }
2.265625
2
2024-11-18T19:35:01.323006+00:00
2021-04-30T16:16:36
f84d075a2e43e62f5ce816be910b18adf9c5533b
{ "blob_id": "f84d075a2e43e62f5ce816be910b18adf9c5533b", "branch_name": "refs/heads/main", "committer_date": "2021-04-30T16:16:36", "content_id": "86fc8a5be56aa54b3354cda64f8f4a3c46c374f1", "detected_licenses": [ "MIT" ], "directory_id": "77c4f8e008007cc25a433c968ee5cadbb03e2293", "extension": "c", "filename": "SerialCommunicationUART.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": 795, "license": "MIT", "license_type": "permissive", "path": "/src/SerialCommunicationUART.c", "provenance": "stackv2-0054.json.gz:5238", "repo_name": "Atulsingh20/embedded_systems_project_256889", "revision_date": "2021-04-30T16:16:36", "revision_id": "41abac120611cb811ee4b446124e56b36f21d697", "snapshot_id": "9091a3aa817a0cb30ee857fe983ce999f1e8f904", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Atulsingh20/embedded_systems_project_256889/41abac120611cb811ee4b446124e56b36f21d697/src/SerialCommunicationUART.c", "visit_date": "2023-04-21T02:23:00.327326" }
stackv2
/** * @file SerialCommunicationUART.c * @author Hemanth A ([email protected]) * @brief A file where serial communication functions are implemented * @version 0.1 * @date 2021-04-29 * * @copyright Copyright (c) 2021 * */ #include <avr/io.h> #include "SerialCommunicationUART.h" /** * @brief A program to initialize the UART serial communication * * @param ubrr_value */ void UARTinit(uint16_t ubrr_value){ UBRR0L = ubrr_value; UBRR0H = (ubrr_value>>8)&(0x00ff); UART_CHARACTER_SIZE; // 8 bit size of data UART_ENABLED; //enable rx and tx of uart with interrupts } /** * @brief A function to write characters to send it to other UART port * * @param data */ void UARTwritecharacter(char data){ while(UART_DATA_NOT_WRITTEN){ } UDR0 = data; }
2.578125
3
2024-11-18T19:35:02.302719+00:00
2018-07-11T22:41:35
33b68ada173313525565a6bbee45c9a81ad52759
{ "blob_id": "33b68ada173313525565a6bbee45c9a81ad52759", "branch_name": "refs/heads/master", "committer_date": "2018-07-11T22:41:35", "content_id": "7b7b05639945c586db7603dd6c59ff9fe0e51624", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "e9091a83528203502f294452f1a2aee73f662338", "extension": "c", "filename": "misc.c", "fork_events_count": 15, "gha_created_at": "2009-11-24T15:06:20", "gha_event_created_at": "2022-12-28T09:30:05", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 383937, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11287, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/misc.c", "provenance": "stackv2-0054.json.gz:5880", "repo_name": "bearded/ruby-ldap", "revision_date": "2018-07-11T22:41:35", "revision_id": "3cfab0fd05c9fdf4c92c60d52457a6dadad4c8c0", "snapshot_id": "6433f1a3c617b9f76b00e3e44f70a36cbe18d290", "src_encoding": "UTF-8", "star_events_count": 26, "url": "https://raw.githubusercontent.com/bearded/ruby-ldap/3cfab0fd05c9fdf4c92c60d52457a6dadad4c8c0/misc.c", "visit_date": "2023-05-26T22:01:24.001431" }
stackv2
/* -*- C -*- * $Id: misc.c,v 1.11 2006/07/03 22:54:52 ianmacd Exp $ */ #include "ruby.h" #include "rbldap.h" VALUE rb_sLDAP_APIInfo; VALUE rb_cLDAP_Control; #ifdef LDAP_OPT_API_INFO VALUE rb_ldap_apiinfo_new (LDAPAPIInfo * info) { VALUE info_version, api_version, protocol_version; VALUE extensions, vendor_name, vendor_version; int i; info_version = INT2NUM (info->ldapai_info_version); api_version = INT2NUM (info->ldapai_api_version); protocol_version = INT2NUM (info->ldapai_protocol_version); vendor_version = INT2NUM (info->ldapai_vendor_version); vendor_name = rb_tainted_str_new2 (info->ldapai_vendor_name); extensions = rb_ary_new (); for (i = 0; info->ldapai_extensions[i]; i++) { rb_ary_push (extensions, rb_tainted_str_new2 (info->ldapai_extensions[i])); } return rb_struct_new (rb_sLDAP_APIInfo, info_version, api_version, protocol_version, extensions, vendor_name, vendor_version, 0); } LDAPAPIInfo * rb_ldap_get_apiinfo (VALUE data) { LDAPAPIInfo *info; VALUE r_extensions; int len, i; char **c_extensions; if (data == Qnil) return NULL; info = ALLOC_N (LDAPAPIInfo, 1); info->ldapai_info_version = FIX2INT (rb_struct_getmember (data, rb_intern ("info_version"))); info->ldapai_api_version = FIX2INT (rb_struct_getmember (data, rb_intern ("api_version"))); info->ldapai_protocol_version = FIX2INT (rb_struct_getmember (data, rb_intern ("protocol_version"))); r_extensions = rb_struct_getmember (data, rb_intern ("extensions")); len = RARRAY_LEN (r_extensions); c_extensions = ALLOCA_N (char *, len); for (i = 0; i <= len - 1; i++) { VALUE str = RARRAY_PTR (r_extensions)[i]; RB_LDAP_SET_STR (c_extensions[i], str); } info->ldapai_extensions = c_extensions; RB_LDAP_SET_STR (info->ldapai_vendor_name, rb_struct_getmember (data, rb_intern ("vendor_name"))); info->ldapai_vendor_version = FIX2INT (rb_struct_getmember (data, rb_intern ("vendor_version"))); return info; } #endif /* LDAP_OPT_API_INFO */ #ifdef HAVE_LDAPCONTROL static void rb_ldap_control_free (LDAPControl * ctl) { if (ctl) { if (ctl->ldctl_value.bv_val) xfree (ctl->ldctl_value.bv_val); if (ctl->ldctl_oid) xfree (ctl->ldctl_oid); xfree (ctl); } } VALUE rb_ldap_control_new (LDAPControl * ctl) { if (!ctl) return Qnil; else return Data_Wrap_Struct (rb_cLDAP_Control, 0, rb_ldap_control_free, ctl); } /* Identical to rb_ldap_control_new, but does not define a routine with which to free memory. This should be called only by rb_ldap_parse_result(). */ VALUE rb_ldap_control_new2 (LDAPControl * ctl) { if (!ctl) return Qnil; else return Data_Wrap_Struct (rb_cLDAP_Control, 0, 0, ctl); } /* This is called by #initialize_copy and is using for duping/cloning. */ VALUE rb_ldap_control_copy (VALUE copy, VALUE orig) { LDAPControl *orig_ctl, *copy_ctl; Data_Get_Struct (orig, LDAPControl, orig_ctl); Data_Get_Struct (copy, LDAPControl, copy_ctl); memcpy (copy_ctl, orig_ctl, (size_t) sizeof (LDAPControl)); return copy; } static VALUE rb_ldap_control_s_allocate (VALUE klass) { LDAPControl *ctl; ctl = ALLOC_N (LDAPControl, 1); ctl->ldctl_value.bv_val = NULL; ctl->ldctl_value.bv_len = 0; ctl->ldctl_oid = NULL; ctl->ldctl_iscritical = 0; return Data_Wrap_Struct (klass, 0, rb_ldap_control_free, ctl); } #if RUBY_VERSION_CODE < 170 static VALUE rb_ldap_control_s_new (int argc, VALUE argv[], VALUE klass) { VALUE obj; obj = rb_ldap_control_s_allocate (klass); rb_obj_call_init (obj, argc, argv); return obj; } #endif static VALUE rb_ldap_control_set_value (VALUE self, VALUE val) { LDAPControl *ctl; Data_Get_Struct (self, LDAPControl, ctl); if (ctl->ldctl_value.bv_val) free (ctl->ldctl_value.bv_val); if (val == Qnil) { ctl->ldctl_value.bv_val = NULL; ctl->ldctl_value.bv_len = 0; } else { RB_LDAP_SET_STR (ctl->ldctl_value.bv_val, val); ctl->ldctl_value.bv_len = RSTRING_LEN (val); } return val; } static VALUE rb_ldap_control_get_value (VALUE self) { LDAPControl *ctl; VALUE val; Data_Get_Struct (self, LDAPControl, ctl); if (ctl->ldctl_value.bv_len == 0 || ctl->ldctl_value.bv_val == NULL) { val = Qnil; } else { val = rb_tainted_str_new (ctl->ldctl_value.bv_val, ctl->ldctl_value.bv_len); } return val; } /* * Document-method: value * * call-seq: * ctrl.value => String or nil * * Return the value of the control. */ /* * Document-method: value= * * call-seq: * ctrl.value=(val) => val * * Set the value of the control. */ static VALUE rb_ldap_control_value (int argc, VALUE argv[], VALUE self) { VALUE val; if (rb_scan_args (argc, argv, "01", &val) == 1) val = rb_ldap_control_set_value (self, val); else val = rb_ldap_control_get_value (self); return val; } static VALUE rb_ldap_control_set_oid (VALUE self, VALUE val) { LDAPControl *ctl; Data_Get_Struct (self, LDAPControl, ctl); if (ctl->ldctl_oid) free (ctl->ldctl_oid); if (val == Qnil) { ctl->ldctl_oid = NULL; } else { RB_LDAP_SET_STR (ctl->ldctl_oid, val); } return val; } static VALUE rb_ldap_control_get_oid (VALUE self) { LDAPControl *ctl; VALUE val; Data_Get_Struct (self, LDAPControl, ctl); if (ctl->ldctl_oid == NULL) { val = Qnil; } else { val = rb_tainted_str_new2 (ctl->ldctl_oid); } return val; } /* * Document-method: oid * * call-seq: * ctrl.oid => String or nil * * Return the OID of the control. */ /* * Document-method: oid= * * call-seq: * ctrl.oid=(oid) => oid * * Set the OID of the control. */ static VALUE rb_ldap_control_oid (int argc, VALUE argv[], VALUE self) { VALUE val; LDAPControl *ctl; Data_Get_Struct (self, LDAPControl, ctl); if (rb_scan_args (argc, argv, "01", &val) == 1) { val = rb_ldap_control_set_oid (self, val); } else { val = rb_ldap_control_get_oid (self); } return val; } static VALUE rb_ldap_control_set_critical (VALUE self, VALUE val) { LDAPControl *ctl; Data_Get_Struct (self, LDAPControl, ctl); ctl->ldctl_iscritical = (val == Qtrue) ? 1 : 0; return val; } static VALUE rb_ldap_control_get_critical (VALUE self) { LDAPControl *ctl; VALUE val; Data_Get_Struct (self, LDAPControl, ctl); val = ctl->ldctl_iscritical ? Qtrue : Qfalse; return val; } /* * Document-method: critical * * call-seq: * ctrl.critical => true or false * ctrl.critical? => true or false * ctrl.iscritical => true or false * * Return the criticality of the control. */ /* * Document-method: critical= * * call-seq: * ctrl.critical=(val) => val * ctrl.iscritical=(val) => val * * Set the criticality of the control. +val+ should be *true* or *false*. */ static VALUE rb_ldap_control_critical (int argc, VALUE argv[], VALUE self) { VALUE val; LDAPControl *ctl; Data_Get_Struct (self, LDAPControl, ctl); if (rb_scan_args (argc, argv, "01", &val) == 1) { val = rb_ldap_control_set_critical (self, val); } else { val = rb_ldap_control_get_critical (self); } return val; } /* * Document-method: new * * call-seq: * LDAP::Control.new(oid, value, criticality) => LDAP::Control * * Create a new LDAP::Control. +oid+ is the OID of the control, +value+ is the * value to be assigned to the control, and +criticality+ is the criticality * of the control, which should be *true* or *false*. */ static VALUE rb_ldap_control_initialize (int argc, VALUE argv[], VALUE self) { VALUE oid, value, critical; switch (rb_scan_args (argc, argv, "03", &oid, &value, &critical)) { case 3: rb_ldap_control_set_critical (self, critical); case 2: rb_ldap_control_set_value (self, value); case 1: rb_ldap_control_set_oid (self, oid); default: break; } return Qnil; } /* * call-seq: * ctrl.inspect => String * * Produce a concise representation of the control. */ static VALUE rb_ldap_control_inspect (VALUE self) { VALUE str; str = rb_tainted_str_new2 ("#<"); rb_str_cat2 (str, rb_class2name (CLASS_OF (self))); rb_str_cat2 (str, " oid="); rb_str_concat (str, rb_inspect (rb_ldap_control_get_oid (self))); rb_str_cat2 (str, " value="); rb_str_concat (str, rb_inspect (rb_ldap_control_get_value (self))); rb_str_cat2 (str, " iscritical="); rb_str_concat (str, rb_inspect (rb_ldap_control_get_critical (self))); rb_str_cat2 (str, ">"); return str; } VALUE rb_ldap_controls_new (LDAPControl ** ctrls) { int i; VALUE ary; if (!ctrls) return Qnil; ary = rb_ary_new (); for (i = 0; ctrls[i]; i++) rb_ary_push (ary, rb_ldap_control_new (ctrls[i])); return ary; } LDAPControl * rb_ldap_get_control (VALUE obj) { LDAPControl *ctl; if (obj == Qnil) { return NULL; } else { Data_Get_Struct (obj, LDAPControl, ctl); return ctl; } } LDAPControl ** rb_ldap_get_controls (VALUE data) { LDAPControl **ctls; int len, i; if (data == Qnil) return NULL; Check_Type (data, T_ARRAY); len = RARRAY_LEN (data); ctls = ALLOC_N (LDAPControl *, len + 1); for (i = 0; i < len; i++) { ctls[i] = rb_ldap_get_control (rb_ary_entry (data, i)); } ctls[len] = NULL; return ctls; } #endif /* Document-class: LDAP::Control * * Create, manipulate and inspect LDAP controls. */ void Init_ldap_misc () { rb_sLDAP_APIInfo = rb_struct_define ("APIInfo", "info_version", /* ldapai_xxxx */ "api_version", "protocol_version", "extensions", "vendor_name", "vendor_version", NULL); rb_define_const (rb_mLDAP, "APIInfo", rb_sLDAP_APIInfo); #ifdef HAVE_LDAPCONTROL rb_cLDAP_Control = rb_define_class_under (rb_mLDAP, "Control", rb_cObject); #if RUBY_VERSION_CODE < 170 rb_define_singleton_method (rb_cLDAP_Control, "new", rb_ldap_control_s_new, -1); #endif #if RUBY_VERSION_CODE >= 173 rb_define_alloc_func (rb_cLDAP_Control, rb_ldap_control_s_allocate); #else rb_define_singleton_method (rb_cLDAP_Control, "allocate", rb_ldap_control_s_allocate, 0); #endif rb_define_method (rb_cLDAP_Control, "initialize", rb_ldap_control_initialize, -1); rb_define_method (rb_cLDAP_Control, "initialize_copy", rb_ldap_control_copy, 1); rb_define_method (rb_cLDAP_Control, "inspect", rb_ldap_control_inspect, 0); rb_define_method (rb_cLDAP_Control, "oid", rb_ldap_control_oid, -1); rb_define_method (rb_cLDAP_Control, "oid=", rb_ldap_control_oid, -1); rb_define_method (rb_cLDAP_Control, "value", rb_ldap_control_value, -1); rb_define_method (rb_cLDAP_Control, "value=", rb_ldap_control_value, -1); rb_define_method (rb_cLDAP_Control, "critical?", rb_ldap_control_critical, -1); rb_define_method (rb_cLDAP_Control, "critical", rb_ldap_control_critical, -1); rb_define_method (rb_cLDAP_Control, "critical=", rb_ldap_control_critical, -1); rb_define_method (rb_cLDAP_Control, "iscritical", rb_ldap_control_critical, -1); rb_define_method (rb_cLDAP_Control, "iscritical=", rb_ldap_control_critical, -1); #endif }
2.078125
2
2024-11-18T19:35:02.507656+00:00
2023-08-22T19:34:56
1a9f55c71ce8fe01a14dc2fdeaebf0f5c2a4d4d4
{ "blob_id": "1a9f55c71ce8fe01a14dc2fdeaebf0f5c2a4d4d4", "branch_name": "refs/heads/master", "committer_date": "2023-08-22T19:34:56", "content_id": "679f6beac38ad83831854168c61e3aa7543c0df4", "detected_licenses": [ "Apache-2.0" ], "directory_id": "0aa9dcb3cef817ec55eaa8fae2102106f939f594", "extension": "c", "filename": "sndlibsupport.c", "fork_events_count": 15, "gha_created_at": "2014-06-27T01:07:32", "gha_event_created_at": "2023-06-28T20:53:49", "gha_language": "C++", "gha_license_id": "Apache-2.0", "github_id": 21259864, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 56671, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/audio/sndlibsupport.c", "provenance": "stackv2-0054.json.gz:6137", "repo_name": "RTcmix/RTcmix", "revision_date": "2023-08-22T19:34:56", "revision_id": "4e89415929d7752f325b7813b5aae2a042c08e64", "snapshot_id": "fd30a7d610b2b7b8688cbb5a6d77475201b8ad07", "src_encoding": "UTF-8", "star_events_count": 45, "url": "https://raw.githubusercontent.com/RTcmix/RTcmix/4e89415929d7752f325b7813b5aae2a042c08e64/src/audio/sndlibsupport.c", "visit_date": "2023-08-30T23:23:48.806948" }
stackv2
/* RTcmix - Copyright (C) 2001 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ /* sndlibsupport.c This file defines functions that help RTcmix use Bill Schottstaedt's sndlib sound file library. The library lets us read and write sound files with various types of header, and it hides most of the endian issues. The functions in this file access the lower-level interfaces to his library, not the higher-level ones defined in sndlib/sound.c. The code serves three main purposes: - Provide (as much as possible) backwards compatibility for legacy cmix code. - Provide wrapper functions for some sndlib calls. - Handle my scheme for encoding peak amplitude stats in header comments, so that they're available for all the header types that sndlib can write. The jury's out on how well this works. -- J. Gibson, 6/1/99 Updated for sndlib v. 13.1 -JGG, 7/19/01 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/time.h> #include <time.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <math.h> #include <errno.h> #include <assert.h> #include <sndlibsupport.h> #include <byte_routines.h> #ifndef SGI #define HAVE_SNPRINTF #endif /* #define NDEBUG */ /* define to disable asserts */ /* Not NULL, and not space, to make sndlib believe this starts a comment. */ #define COMMENT_START_CHAR 0x01 #define COMMENT_ALLOC_WARNING "\ WARNING: Not enough room in header for peak stats and comment.\n" #undef MIN #define MIN(a, b) ((a) < (b) ? (a) : (b)) static int open_rd_or_rdwr(const char *, int); static int format_raw_comment(SFComment *, int, char **); static int get_current_header_comment_alloc(void); static int get_current_header_raw_comment(int, char **); /* ========================================================================== */ /* functions for opening and closing sound files */ /* sndlib_create, sndlib_open_read, sndlib_open_write and sndlib_close are wrappers for various sndlib functions. They're meant to be called only when you plan to use sndlib to do sound data I/O. Don't call them if you're just reading and writing headers (as we do for legacy cmix code) -- call close and open directly. None of these functions check whether the file name exists before opening the file. If it's important, the caller should handle this first. (These wrapper functions do the right things to handle sndlib's internal file descriptor scheme, so callers don't need to worry about this.) */ /* -------------------------------------------------------- sndlib_create --- */ /* Creates a new file and writes a header with the given characteristics. <type> is a sndlib constant for header type (e.g. MUS_AIFC). <format> is a sndlib constant for sound data format (e.g. MUS_BSHORT). (These constants are defined in sndlib.h.) Caller is responsible for checking that the header type and data format are compatible, and that the header type is one that sndlib can write (is WRITEABLE_HEADER_TYPE()). Writes no comment, but allocates enough space in the header for one. NOTE: This will truncate an existing file with <sfname>, so check first! On success, returns a standard file descriptor, and leaves the file position pointer at the end of the header. On failure, returns -1. Caller can check errno then. */ int sndlib_create(const char *sfname, int type, int format, int srate, int chans) { int fd, loc; assert(sfname != NULL && strlen(sfname) <= FILENAME_MAX); /* make sure relevant parts of sndlib are initialized */ mus_header_initialize(); fd = open(sfname, O_RDWR | O_CREAT | O_TRUNC, 0666); if (fd == -1) return -1; if (sndlib_write_header(fd, 0, type, format, srate, chans, NULL, &loc) == -1) return -1; mus_file_set_descriptors(fd, sfname, format, mus_data_format_to_bytes_per_sample(format), loc, chans, type); return fd; } /* ------------------------------------------------------ open_rd_or_rdwr --- */ /* Does the dirty work for sndlib_open_read and sndlib_open_write (below). */ static int open_rd_or_rdwr(const char *sfname, int accesstype) { int fd, format, loc, chans, type; assert(sfname != NULL && strlen(sfname) <= FILENAME_MAX); fd = open(sfname, accesstype); if (fd == -1) return -1; if (sndlib_read_header(fd) == -1) return -1; type = mus_header_type(); format = mus_header_format(); chans = mus_header_chans(); loc = mus_header_data_location(); mus_file_set_descriptors(fd, sfname, format, mus_data_format_to_bytes_per_sample(format), loc, chans, type); if (lseek(fd, loc, SEEK_SET) == -1) { perror("open_rd_or_rdwr: lseek"); return -1; } return fd; } /* ----------------------------------------------------- sndlib_open_read --- */ /* Returns a new file descriptor for <sfname>, opened read-only, and reads its header into the sndlib header buffer. After this, the caller can use sndlib functions (like mus_header_type, mus_header_chans, etc.) to gather information from the header. Leaves file position pointer at start of sound data. The caller should check that this is actually a sound file by using the NOT_A_SOUND_FILE macro (sndlibsupport.h). The caller might want to check first that this file exists. */ int sndlib_open_read(const char *sfname) { return open_rd_or_rdwr(sfname, O_RDONLY); } /* ---------------------------------------------------- sndlib_open_write --- */ /* Just like sndlib_open_read, except that it opens the file for read/write access. See the comments at sndlib_open_read for more. */ int sndlib_open_write(const char *sfname) { return open_rd_or_rdwr(sfname, O_RDWR); } /* --------------------------------------------------------- sndlib_close --- */ /* Closes the file descriptor <fd> and, if <update> is true, updates its header with the number of samples (not frames) contained in the file. <type> is the type of header; <format> is the data format of the samples. If <update> is false, caller can pass any value for the last 3 args. Returns 0 on success; -1 on failure (check errno for reason). */ int sndlib_close(int fd, int update, int type, int format, int nsamps) { assert(fd >= 0); if (update) { int sound_bytes; assert(format > 0 && WRITEABLE_HEADER_TYPE(type)); sound_bytes = nsamps * mus_data_format_to_bytes_per_sample(format); /* keep going even if this fails */ sndlib_set_header_data_size(fd, type, sound_bytes); } mus_file_close_descriptors(fd); return close(fd); } /* ========================================================================== */ /* functions for reading and writing headers */ /* --------------------------------------------------- sndlib_read_header --- */ /* Reads the header of <fd> into the sndlib header buffer, so that we then can call sndlib functions (like mus_header_type, mus_header_chans, etc.) to gather information from the header. When a header has been read into the header buffer, we call it the "current header". Any function in this file with "current_header" as part of its name depends on a previous call to sndlib_read_header. */ int sndlib_read_header(int fd) { assert(fd >= 0); /* Init the part of sndlib we need -- only inits once. */ mus_header_initialize(); if (lseek(fd, 0, SEEK_SET) == -1) return -1; return mus_header_read_with_fd(fd); } /* -------------------------------------------------- sndlib_write_header --- */ /* (a wrapper for mus_header_write_with_fd in sndlib/headers.c) Writes a header to the sound file opened as <fd>. If <data_location> is not NULL, sets the value it references to the offset of the start of sound data in the file. (This is computed by sndlib during the header write.) Assumes that <header_type> is one writeable by sndlib. (Find out in advance by using the WRITEABLE_HEADER_TYPE macro.) Caller is responsible for knowing if <header_type> supports <data_format> (including endianness concerns). The tricky issue is how to deal with <rawcomment>. We call it a "raw" comment, because it's the actual comment we write to the header, including any encoded peak stats. If the file already has a header (indicated by the <header_exists> flag), and <rawcomment> is not NULL, we write this comment to the file, while preserving the amount of space reserved in the file header for its comment. If there isn't enough space in the file for <rawcomment>, we print a warning and write as much of the comment as will fit. If <rawcomment> is NULL (whether or not <header_exists> is true), we allocate DEFAULT_COMMENT_LENGTH bytes for comment space in the header. The idea is to balance two desirable, but sometimes incompatible, aims: keeping enough space in headers for our structured comment, and preserving the sound data start location in existing files, so that a header write doesn't cause sound data loss or corruption (e.g., channel swapping or bad sample word alignment). So the caller has to know what it's getting into. It's best for functions outside of this file to pass NULL for <rawcomment>, and later use sndlib_put_header_comment to write peak stats or a text comment. CAUTION: Be careful not to change the header type of an existing file! This likely will change the sound data start location, with the same consequences (listed just above) as changing the comment allocation. IMPORTANT: Before closing this sound file, you must update the header's idea of how much sound data is in the file, by calling sndlib_set_header_data_size. On success, leaves file position pointer at end of header and returns 0; Otherwise, returns -1. */ int sndlib_write_header(int fd, int header_exists, int header_type, int data_format, int srate, int chans, char *rawcomment, int *data_location) { int result, comment_len = 0; char *comment; assert(fd >= 0 && header_type > -1 && data_format > 0); if (data_location) *data_location = 0; if (header_exists & (rawcomment != NULL)) { if (sndlib_read_header(fd) == -1) { fprintf(stderr, "sndlib_write_header: Error reading header\n"); return -1; } comment_len = get_current_header_comment_alloc(); if (strlen(rawcomment) > comment_len) fprintf(stderr, COMMENT_ALLOC_WARNING); } else comment_len = DEFAULT_COMMENT_LENGTH; comment = (char *)calloc(comment_len + 1, sizeof(char)); if (comment == NULL) { perror("sndlib_write_header: calloc"); return -1; } /* sndlib now ignores comments that start with nulls or spaces, so we trick it into accepting our comment by storing a different character into the beginning of the string. -JGG, 7/20/01 */ comment[0] = COMMENT_START_CHAR; if (rawcomment) strncpy(comment, rawcomment, comment_len); /* Now here's some awful stuff ... the sndlib function mus_header_write_next_header fiddles around with the data location field of the header (to handle a word-alignment problem? -- not sure). The workaround for now is to decrement the comment length passed to mus_header_write_with_fd for NeXT headers. A side-effect is that the last char of the comment won't get written. But our comments are zero- padded so much that there's not likely to be any important data loss. */ if (header_type == MUS_NEXT) if (!(comment_len % 4)) comment_len--; if (lseek(fd, 0, SEEK_SET) == -1) { perror("sndlib_write_header: lseek"); free(comment); return -1; } mus_header_initialize(); /* in case this hasn't been done yet */ result = mus_header_write_with_fd(fd, header_type, srate, chans, 0, 0, data_format, comment, comment_len); if (result != MUS_NO_ERROR) { fprintf(stderr, "sndlib_write_header: Can't write header\n"); free(comment); return -1; } /* Data location computed during header write. */ if (data_location) *data_location = mus_header_data_location(); free(comment); return 0; } /* ------------------------------------------ sndlib_set_header_data_size --- */ /* Update the header of file opened as <fd>, of type <header_type>, with the number of bytes of sound data written to the file, <sound_bytes). */ int sndlib_set_header_data_size(int fd, int header_type, int sound_bytes) { assert(fd >= 0 && header_type >= 0 && sound_bytes >= 0); /* Note: as of sndlib-5.5, this doesn't require us to make sure file's header is in sndlib header buffer. Nor do we have to seek to the beginning of the file first. */ return mus_header_update_with_fd(fd, header_type, sound_bytes); } /* ------------------------------------ sndlib_print_current_header_stats --- */ /* Prints info about the current header into a static string, and returns a pointer to this. Caller should copy this if necessary. If <sfc> is NULL, calls sndlib_get_current_header_comment to retrieve peak stats, otherwise expects that <sfc> holds them. Assumes that <fd> is the file descriptor of the current header. <verbosity> indicates how much info to print: 0 = header type, data format, srate, chans, duration 1 = adds peak stats, if any 2 = adds number of frames and header size Doesn't print the file name or any plain text comment it might have. */ char * sndlib_print_current_header_stats(int fd, SFComment *sfc, int verbosity) { int type, format, data_loc, srate, nchans; int n, nchars; long nsamps; float duration; SFComment *sfcp, nsfc; static char str[1024]; assert(fd >= 0); if (sfc == NULL && verbosity > 0) { if (sndlib_get_current_header_comment(fd, &nsfc) == -1) { fprintf(stderr, "Can't read header comment!\n"); nsfc.offset = -1; /* make sure it's ignored below */ nsfc.comment[0] = '\0'; /* but keep going */ } sfcp = &nsfc; } else sfcp = sfc; type = mus_header_type(); format = mus_header_format(); data_loc = mus_header_data_location(); srate = mus_header_srate(); nchans = mus_header_chans(); nsamps = mus_header_samples(); /* samples, not frames */ duration = (float)(nsamps / nchans) / (float)srate; #ifdef HAVE_SNPRINTF nchars = snprintf(str, 256, "%s, %s\nsrate: %d chans: %d\nduration: %g seconds\n", mus_header_type_name(type), mus_data_format_name(format), srate, nchans, duration); #else nchars = sprintf(str, "%s, %s\nsrate: %d chans: %d\nduration: %g seconds\n", mus_header_type_name(type), mus_data_format_name(format), srate, nchans, duration); #endif if (verbosity == 2) { char tmp[128]; #ifdef HAVE_SNPRINTF snprintf(tmp, 128, "frames: %ld\nheader size: %d bytes\n", nsamps / nchans, data_loc); #else sprintf(tmp, "frames: %ld\nheader size: %d bytes\n", nsamps / nchans, data_loc); #endif strcat(str, tmp); } if (verbosity > 0) { /* want this after verbosity=2 info */ char tmp[80]; if (SFCOMMENT_PEAKSTATS_VALID(sfcp)) { strcat(str, "peak amplitudes:\n"); for (n = 0; n < nchans; n++) { #ifdef HAVE_SNPRINTF snprintf(tmp, 80, " chan %d: peak: %g loc: %ld\n", n, sfcp->peak[n], sfcp->peakloc[n]); #else sprintf(tmp, " chan %d: peak: %g loc: %ld\n", n, sfcp->peak[n], sfcp->peakloc[n]); #endif strcat(str, tmp); } strftime(tmp, 80, " peak stats updated: %a %b %d %H:%M:%S %Z %Y\n", localtime(&sfcp->timetag)); strcat(str, tmp); } else strcat(str, "(no peak amp stats)\n"); } return str; } /* ========================================================================== */ /* functions for reading the header comment with encoded peak stats */ /* === PEAK STATS === Peak amps are encoded at the end of the sound file comment as follows: "[peakamp: <peak> at <loc>, <peak> at <loc>; time=<time>]" where... <peak> is a (possibly floating point) peak amplitude, <loc> is an integer frame number, and <time> is the time of last peak stats update in seconds since 1970. There will be one <peak>, <loc> pair for each channel. The text must appear exactly in this format (e.g., with brackets and punctuation) to be parsed by RTcmix. (The function that parses this is sndlib_get_current_header_comment; the function that writes this is format_raw_comment; both in this file.) For example: "[peakamp: 32767 at 1037829, 27498.58 at 1048292; time=9283478561]" Note that the <time> tag is not year 2038 compliant. ;-) */ #define PEAK_TAG "[maxamp:" /* ------------------------------------ sndlib_get_current_header_comment --- */ /* Fills in an SFComment struct for the given sound file descriptor <fd>. Returns -1 if there's an error; otherwise returns 0. Does NOT close the file. Reads the comment from the file, and checks to see if it encodes peak stats in the format given just above. If it does, then parses the stats and stores them into the <peak> and <peakloc> fields of the SFComment struct. Stores the time of the last update to the file's peak stats into the <timetag> field of the SFComment struct. Stores the comment text preceding -- but not including -- the peak stat text into the <comment> field of the SFComment struct. NOTE: Text following the peak stats will be ignored. If there is no comment in the file, zeros the <comment> field and returns 0. If there are no parseable peak stats (and there can't be if there's no comment!), sets the <offset> field to -1 and returns 0. (Use the SFCOMMENT_PEAKSTATS_VALID macro to see if offset not -1.) If the comment appears to have peak stats, but we fail to parse them, the <comment> field will contain as much of the file's comment text as it will hold; we print a warning and set <offset> to -1. Note that there can be peak stats AND an empty <comment> field, in the (very common) case where the file's comment contains only peak stats. Assumes the header has already been read into sndlib's header buffer. */ int sndlib_get_current_header_comment(int fd, SFComment *sfc) { int n, len, maxchars, found; char *buf, *pstr; assert(fd >= 0 && sfc != NULL); sfc->offset = -1; sfc->comment[0] = '\0'; sfc->timetag = 0L; len = get_current_header_raw_comment(fd, &buf); if (len == -1) return -1; if (len == 0) return 0; /* no comment text at all (not an error) */ if (buf[0] == COMMENT_START_CHAR) { /* empty comment (not an error) */ free(buf); return 0; } maxchars = MIN(len, MAX_COMMENT_CHARS - 1); /* not including term. NULL */ /* See if comment contains peak info. */ found = 0; pstr = buf; while (!found) { pstr = strrchr(pstr, '['); /* search backwards from end of string */ if (pstr == NULL) break; if (strncmp(pstr, PEAK_TAG, strlen(PEAK_TAG)) == 0) { found = 1; break; } if (pstr == buf) /* '[' at beginning of string, but no PEAK_TAG */ break; } /* Copy buf into sfc->comment. This will contain as much of the real file comment as will fit, including any encoded peak stats. If we successfully parse the peak stats below, we'll chop them off the end of sfc->comment. (We don't alter the file, of course!) */ strncpy(sfc->comment, buf, maxchars); sfc->comment[maxchars] = '\0'; /* ensure termination */ /* If we found the peak info tag, parse the statement it introduces, and store the peak values into our SFComment struct. The error checking below seems paranoid, but that's because a user could mangle the peak info while editing a comment. */ if (found) { int nchans; long timetag; char *p, *pos; sfc->offset = pstr - buf; p = strchr(pstr, ':'); if (p == NULL) goto parse_err; p++; nchans = mus_header_chans(); for (n = 0; n < nchans; n++) { double peak; long peakloc; /* read peak amp value */ pos = NULL; errno = 0; peak = strtod(p, &pos); if (peak == 0.0 && pos == p) /* no conversion performed */ goto parse_err; if (errno == ERANGE) /* overflow or underflow */ goto parse_err; sfc->peak[n] = (float)peak; /* find peak location value */ p = strchr(p, 'a'); /* find "at" */ if (p == NULL) goto parse_err; if (*(p+1) != 't') goto parse_err; p += 2; /* skip over "at" */ /* read peak location value */ pos = NULL; errno = 0; peakloc = strtol(p, &pos, 10); if (pos == p) /* no digits to convert */ goto parse_err; if (errno == ERANGE) /* overflow or underflow */ goto parse_err; sfc->peakloc[n] = peakloc; /* skip to info for next channel, or stop */ if (*pos == ';') /* reached end of peak info */ break; /* even if file has more chans */ p = pos + 1; /* skip over ',' separating chans */ } if (*pos != ';') goto parse_err; /* no time tag separator */ p = strchr(pos, '='); /* find end of "time=" */ if (p == NULL) goto parse_err; p++; /* skip over '=' */ /* read time tag value */ pos = NULL; errno = 0; timetag = strtol(p, &pos, 10); if (pos == p) /* no digits to convert */ goto parse_err; if (errno == ERANGE) /* overflow or underflow */ goto parse_err; sfc->timetag = timetag; /* truncate comment to omit peak info (and anything after!) */ if (sfc->offset < maxchars) { int ind = sfc->offset; sfc->comment[ind] = '\0'; if (sfc->comment[ind - 1] == '\n') sfc->comment[ind - 1] = '\0'; /* chop newline */ } } free(buf); return 0; parse_err: sfc->offset = -1; fprintf(stderr, "WARNING: Can't parse peak amp stats!\n"); free(buf); return 0; /* still not really an error! */ } /* -------------------------------------------- sndlib_get_header_comment --- */ /* A wrapper for sndlib_get_current_header_comment() that ensures sndlib has the header for <fd> in its buffer. Returns 0 on success, -1 on failure. */ int sndlib_get_header_comment(int fd, SFComment *sfc) { if (sndlib_read_header(fd) == -1) { fprintf(stderr, "sndlib_get_header_comment: Error reading header\n"); return -1; } return sndlib_get_current_header_comment(fd, sfc); } /* ========================================================================== */ /* functions for writing the header comment with encoded peak stats */ /* --------------------------------------------------- format_raw_comment --- */ /* Translate the data in the SFComment struct <sfc> into the string <rawcomment>, for writing into the file header comment. The struct contains peak stats and a plain text comment. <rawcomment> encodes these according to the syntax described above (see "PEAK STATS"). <nchans> is the number of channels for the sound file. If sfc->offset is -1, doesn't encode the peak stats. <rawcomment> is malloc'd in this function; caller should free it. NOTE: no sound file i/o done in this function. Returns 0 if OK, -1 if error. */ static int format_raw_comment(SFComment *sfc, int nchans, char **rawcomment) { int n; char tmp[128], peakstr[DEFAULT_COMMENT_LENGTH]; /* allocate comment string to pass back */ *rawcomment = (char *)calloc(DEFAULT_COMMENT_LENGTH, sizeof(char)); if (*rawcomment == NULL) { perror("format_raw_comment: calloc"); return -1; } /* prepare peak stats string */ peakstr[0] = 0; if (SFCOMMENT_PEAKSTATS_VALID(sfc)) { /* use supplied peak stats */ strcat(peakstr, PEAK_TAG); for (n = 0; n < nchans; n++) { sprintf(tmp, " %.9g at %ld,", sfc->peak[n], sfc->peakloc[n]); strcat(peakstr, tmp); } peakstr[strlen(peakstr) - 1] = ';'; /* replace last ',' */ sprintf(tmp, " time=%ld]", sfc->timetag); strcat(peakstr, tmp); if (strlen(peakstr) >= MAX_PEAK_CHARS) { fprintf(stderr, "format_raw_comment: Not enough comment space for peak stats\n"); return -1; } } /* else peak stats empty */ /* prepare comment string */ strncpy(*rawcomment, sfc->comment, MAX_COMMENT_CHARS - 1); /* append peak stats string to comment string */ if (peakstr[0] && (*rawcomment)[0]) strcat(*rawcomment, "\n"); /* separate real comment from peak stats */ strcat(*rawcomment, peakstr); return 0; } /* ------------------------------------ sndlib_put_current_header_comment --- */ /* Updates the header of the existing sound file descriptor <fd> using the supplied values for peak amplitudes and their locations (in frames from beginning of file), and the <comment> string. The <peak> and <peakloc> arrays have an element for each channel in the sound file. If <peak> or <peakloc> is NULL, doesn't update the file's peak amp stats. If <comment> is NULL, doesn't update the comment. If it updates the peak stats, it also updates their timetag ("calendar time") when stats written. Note that the peak amp stats are encoded as part of the file comment. (See above for an explanation of this scheme.) Returns 0 on success, and leaves file position pointer at end of header. Otherwise, returns -1. Does NOT close the file. NOTE: This resets the header's data size field to zero, so you have to call sndlib_set_header_data_size later for this file! Assumes the header has already been read into sndlib's header buffer. */ int sndlib_put_current_header_comment(int fd, float peak[], long peakloc[], char *comment) { int result, header_type, chans; char *rawcomment; SFComment sfc; assert(fd >= 0); header_type = mus_header_type(); if (!WRITEABLE_HEADER_TYPE(header_type)) { fprintf(stderr, "sndlib_put_current_header_comment:\n"); fprintf(stderr, " can't write this type of header.\n"); return -1; } if (header_type == MUS_RAW) /* We can't write a comment for these. */ return 0; /* Initialize SFComment struct. */ memset(&sfc, 0, sizeof(SFComment)); sfc.offset = -1; /* If caller isn't supplying all the data, we have to get some of it from the existing file header. */ if (comment == NULL || peak == NULL || peakloc == NULL) { result = sndlib_get_current_header_comment(fd, &sfc); if (result == -1) return -1; } chans = mus_header_chans(); if (peak && peakloc) { /* use supplied peak stats */ struct timeval tp; int n; for (n = 0; n < chans; n++) { sfc.peak[n] = peak[n]; sfc.peakloc[n] = peakloc[n]; } gettimeofday(&tp, NULL); sfc.timetag = tp.tv_sec; /* Though we don't know what the real offset (bytes from header comment start to peak stats text) will be, we set this to something other than -1, so that format_raw_comment() won't ignore the peak stats passed to it. */ sfc.offset = 0; } if (comment) { /* use supplied comment */ strncpy(sfc.comment, comment, MAX_COMMENT_CHARS - 1); sfc.comment[MAX_COMMENT_CHARS - 1] = '\0'; /* ensure termination */ } /* Formatted comment text passed back in malloc'd <rawcomment>. */ result = format_raw_comment(&sfc, chans, &rawcomment); if (result == -1) return -1; /* Check that file header has enough space allocated for comment. Not likely to be a problem, since we pre-allocate enough space in rtoutput and sfcreate. But DEFAULT_COMMENT_LENGTH could change, or the user could save the sound file with Snd, etc. */ if (!sndlib_current_header_comment_alloc_good(rawcomment)) { fprintf(stderr, "sndlib_put_current_header_comment:"); fprintf(stderr, " not enough space for comment in file header\n"); result = -1; goto err; } result = sndlib_write_header(fd, 1, header_type, mus_header_format(), mus_header_srate(), chans, rawcomment, NULL); if (result == -1) goto err; result = 0; err: if (rawcomment) free(rawcomment); return result; } /* -------------------------------------------- sndlib_put_header_comment --- */ /* A wrapper for sndlib_put_current_header_comment() that ensures sndlib has the header for <fd> in its buffer. Returns 0 on success, -1 on failure. */ int sndlib_put_header_comment(int fd, float peak[], long peakloc[], char *comment) { if (sndlib_read_header(fd) == -1) { fprintf(stderr, "sndlib_put_header_comment: Error reading header\n"); return -1; } return sndlib_put_current_header_comment(fd, peak, peakloc, comment); } /* ========================================================================== */ /* miscellaneous helper functions */ /* ------------------------------------- get_current_header_comment_alloc --- */ static int get_current_header_comment_alloc() { int comment_start, comment_end, len; /* offset of first comment byte (from start of header) */ comment_start = mus_header_comment_start(); // Not a valid assumption, since Peak writes comments after sound data. -JGG //assert(comment_start >= 0 && comment_start < 3000); /* see if plausible */ /* offset of last comment byte (from start of header) */ comment_end = mus_header_comment_end(); // Not a valid assumption, since Peak writes comments after sound data. -JGG //assert(comment_end >= 0 && comment_end < 3000); /* total bytes available for comment in header */ len = comment_end - comment_start; assert(len >= 0); return (len > 0 ? len + 1 : len); } /* ----------------------------- sndlib_current_header_comment_alloc_good --- */ /* We write headers with more than enough comment space to hold peak stats and some brief plain text comments. But some programs (like Snd) can save files in a way that removes unused comment space. So we have to make sure there's enough to store our comments. If <rawcomment> is NULL, tests whether file header comment space is exactly DEFAULT_COMMENT_LENGTH bytes long. If <rawcomment> is not NULL, tests whether header has enough space for the <rawcomment> string. Only functions in this file, which know about encoded peak stats, should pass a raw comment string to this function. Returns 1 if the test passes, 0 if it doesn't. Assumes the file we care about is in sndlib's header buffer. */ int sndlib_current_header_comment_alloc_good(char *rawcomment) { int len; len = get_current_header_comment_alloc(); /* Note: DEFAULT_COMMENT_LENGTH includes terminating NULL; strlen doesn't */ if (rawcomment) return (len > strlen(rawcomment)); else return (len == DEFAULT_COMMENT_LENGTH); } /* --------------------------------------- get_current_header_raw_comment --- */ /* Reads the raw header comment string from the file opened as <fd>. Passes back the malloc'd comment in <rawcomment>. Caller should free. The "raw" comment includes all of the comment text, including any peak stats encoded using the scheme described above (at "PEAK STATS"). Returns the length (in bytes) of the comment space allocated in the header, or -1 if error. Note that the allocated space may be larger than the strlen length of the comment string. <rawcomment> is allocated len + 1 bytes; Assumes the header we want has already been read into the sndlib header buffer (sndlib_read_header). Leaves the file position pointer at the end of the comment. */ static int get_current_header_raw_comment(int fd, char **rawcomment) { int start, end, len, bytes; assert(fd >= 0 && rawcomment != NULL); *rawcomment = NULL; start = mus_header_comment_start(); // Not a valid assumption, since Peak writes comments after sound data. -JGG //assert(start >= 0 && start < 3000); end = mus_header_comment_end(); assert(end >= start); len = end - start; if (len > 0) len++; else len = 0; if (len > 0) { *rawcomment = (char *)calloc(len + 1, sizeof(char)); /* incl term NULL */ if (*rawcomment == NULL) { perror("get_current_header_raw_comment: calloc"); return -1; } if (lseek(fd, start, SEEK_SET) == -1) { perror("get_current_header_raw_comment: lseek"); return -1; } bytes = read(fd, *rawcomment, len); /* we should've read the amount sndlib said is there */ if (bytes < len) { fprintf(stderr, "get_current_header_raw_comment: Read failed\n"); return -1; } } /* else no comment text at all (not an error) */ return len; } /* ------------------------------------------ sfcomment_peakstats_current --- */ /* Return 1 if the peak stats in <sfc> are not more than MAX_PEAK_STATS_AGE seconds older than the modification date of the open file represented by the file descriptor <fd>. This constant is defined in H/sfheader.h. Otherwise, return 0. */ int sfcomment_peakstats_current(const SFComment *sfc, const int fd) { struct stat statbuf; if (fstat(fd, &statbuf) == -1) { perror("sfcomment_peakstats_current"); return 0; } return (statbuf.st_mtime <= sfc->timetag + MAX_PEAK_STATS_AGE); } /* ------------------------------------------------------ sndlib_findpeak --- */ /* Finds the peak absolute value per channel, and the location (in frames) of this peak, in the soundfile window specified by <startframe> and <nframes>. Also finds the average (absolute value) amplitude, rms amplitude and average DC offset for this time span. If <outfd> is not -1, writes each input buffer to <outfd> with no change. (So the files must have same byte order.) Stores peak stats into <peak> and <peakloc> arrays, which are assumed to have at least <nchans> locations. Same goes for <ampavg>, <rms> and <dcavg> arrays. Leaves file position pointer of input file unchanged. Input files can be either short integer, floating point or 24-bit integer. Returns 0 if successful, -1 if error. The ability to copy input to output files is probably only useful for the sndpeak program. */ #define BUF_FRAMES (1024 * 16) #define ABS(x) ((x) < 0 ? -(x) : (x)) #define NORMFACTOR 1.0 / 32768.0 #define DENORMFACTOR 32768.0 int sndlib_findpeak(int infd, int outfd, /* ignored if -1 */ int indataloc, /* header size (bytes) */ int outdataloc, /* ignored if outfd is -1 */ int informat, /* sndlib constant */ int nchans, /* of input file */ long startframe, long nframes, float peak[], long peakloc[], double ampavg[], double dcavg[], double rms[]) { int i, n, bytespersamp, isfloat, byteswap; long frames, bufframes, startbyte, bufbytes, bufcount = 0; off_t oldloc; char *buffer; assert(infd >= 0 && indataloc >= 0); assert(!INVALID_DATA_FORMAT(informat)); assert(nchans > 0 && nchans <= MAXCHANS); assert(startframe >= 0 && nframes > 0); assert(peak != NULL && peakloc != NULL); bytespersamp = mus_data_format_to_bytes_per_sample(informat); isfloat = IS_FLOAT_FORMAT(informat); assert(isfloat || bytespersamp == 2 || bytespersamp == 3); #if MUS_LITTLE_ENDIAN byteswap = IS_BIG_ENDIAN_FORMAT(informat); #else byteswap = IS_LITTLE_ENDIAN_FORMAT(informat); #endif for (n = 0; n < nchans; n++) { peak[n] = 0.0; peakloc[n] = 0; ampavg[n] = 0.0; dcavg[n] = 0.0; rms[n] = 0.0; } bufbytes = BUF_FRAMES * bytespersamp * nchans; buffer = (char *)malloc(bufbytes); if (buffer == NULL) { perror("sndlib_findpeak: malloc"); return -1; } if (outfd > -1) { assert(outdataloc >= 0); if (lseek(outfd, outdataloc, SEEK_SET) == -1) { perror("sndlib_findpeak: lseek"); return -1; } } oldloc = lseek(infd, 0, SEEK_CUR); startbyte = (startframe * nchans * bytespersamp) + indataloc; if (lseek(infd, startbyte, SEEK_SET) == -1) { perror("sndlib_findpeak: lseek"); return -1; } for (frames = 0; frames < nframes; frames += bufframes) { long inbytes = read(infd, buffer, bufbytes); if (inbytes == -1) { perror("sndlib_findpeak: read"); goto err; } if (inbytes == 0) break; /* already reached EOF */ bufframes = inbytes / bytespersamp / nchans; if (isfloat) { float fsamp, fabsamp, normsamp; float *fbuf = (float *)buffer; for (i = 0; i < bufframes; i++) { for (n = 0; n < nchans; n++) { fsamp = *fbuf++; if (byteswap) byte_reverse4(&fsamp); fabsamp = (float)fabs((double)fsamp); if (fabsamp > peak[n]) { peak[n] = fabsamp; peakloc[n] = startframe + frames + i; } ampavg[n] += fabsamp * NORMFACTOR; normsamp = fsamp * NORMFACTOR; dcavg[n] += normsamp; rms[n] += normsamp * normsamp; } } } else if (bytespersamp == 3) { float fsamp, fabsamp, normsamp, scalefactor = 1.0 / (float) (1 << 8); unsigned char *bufp = (unsigned char *)buffer; if (informat == MUS_L24INT) { for (i = 0; i < bufframes; i++) { for (n = 0; n < nchans; n++) { int samp = (int) (((bufp[2] << 24) + (bufp[1] << 16) + (bufp[0] << 8)) >> 8); fsamp = (float) samp * scalefactor; fabsamp = fabs(fsamp); if (fabsamp > peak[n]) { peak[n] = fabsamp; peakloc[n] = startframe + frames + i; } ampavg[n] += fabsamp * NORMFACTOR; normsamp = fsamp * NORMFACTOR; dcavg[n] += normsamp; rms[n] += normsamp * normsamp; bufp += 3; } } } else { // informat == MUS_B24INT for (i = 0; i < bufframes; i++) { for (n = 0; n < nchans; n++) { int samp = (int) (((bufp[0] << 24) + (bufp[1] << 16) + (bufp[2] << 8)) >> 8); fsamp = (float) samp * scalefactor; fabsamp = fabs(fsamp); if (fabsamp > peak[n]) { peak[n] = fabsamp; peakloc[n] = startframe + frames + i; } ampavg[n] += fabsamp * NORMFACTOR; normsamp = fsamp * NORMFACTOR; dcavg[n] += normsamp; rms[n] += normsamp * normsamp; bufp += 3; } } } } else if (bytespersamp == 2) { /* short ints */ short samp, absamp; float normsamp; short *sbuf = (short *)buffer; for (i = 0; i < bufframes; i++) { for (n = 0; n < nchans; n++) { samp = *sbuf++; if (byteswap) byte_reverse2(&samp); absamp = ABS(samp); if (absamp > peak[n]) { peak[n] = absamp; peakloc[n] = startframe + frames + i; } ampavg[n] += absamp * NORMFACTOR; normsamp = samp * NORMFACTOR; dcavg[n] += normsamp; rms[n] += normsamp * normsamp; } } } if (outfd > -1) { /* copy to output file (with same byte order) */ long outbytes = write(outfd, buffer, inbytes); if (outbytes != inbytes) { perror("sndlib_findpeak: write"); goto err; } } } /* denormalize averages so that they correspond to input range; we do the normalization to avoid overflow during accumulation. */ for (n = 0; n < nchans; n++) { ampavg[n] = (ampavg[n] / nframes) * DENORMFACTOR; dcavg[n] = (dcavg[n] / nframes) * DENORMFACTOR; rms[n] = pow(rms[n] / nframes, 0.5) * DENORMFACTOR; } free(buffer); lseek(infd, oldloc, SEEK_SET); return 0; err: free(buffer); lseek(infd, oldloc, SEEK_SET); return -1; } /* ========================================================================== */ /* compatibility functions for disk-based cmix to read and write headers */ #ifdef CMIX_LEGACY static int peak_stats_to_sfmaxamp(SFMAXAMP *, SFComment *, int); static int sfmaxamp_to_peak_stats(SFComment *, SFMAXAMP *, int); static int sf_class_to_data_format(int, int); /* ------------------------------------------------------- sndlib_rheader --- */ /* Invoked by the rheader macro in H/sfheader.h. This is meant to be called only by legacy disk-based cmix software, like sound.c and the utility programs. New programs and the RTcmix core should use sndlib_read_header instead. Fills in the fields of <sfh> for the file already opened as <fd>. Checks that sound data format (e.g., 16-bit linear) is of a type that cmix can use, and that the file doesn't have too many channels. Parses peak stats and text comment from the file header comment, and stores them into the sf_maxamp and sf_comment fields of <sfh>. Seeks to beginning of sound data. Returns 0 if OK, -1 if error. */ int sndlib_rheader(int fd, SFHEADER *sfh) { SFComment sfc; assert(fd >= 0 && sfh != NULL); if (sndlib_read_header(fd) == -1) { fprintf(stderr, "sndlib_rheader: Error reading header\n"); return -1; } /* Now we can grab data from sndlib's current header buffer. */ sfheadertype(sfh) = mus_header_type(); if (NOT_A_SOUND_FILE(sfheadertype(sfh))) { fprintf(stderr, "File is probably not a sound file.\n"); return -1; } sfdataformat(sfh) = mus_header_format(); if (!SUPPORTED_DATA_FORMAT_NO24BIT(sfdataformat(sfh))) { fprintf(stderr, "Sound file not in a supported data format. (Can be \n"); fprintf(stderr, "16-bit linear or 32-bit float, either byte order.)\n"); return -1; } sfclass(sfh) = mus_header_data_format_to_bytes_per_sample(); sfdatalocation(sfh) = mus_header_data_location(); sfchans(sfh) = mus_header_chans(); if (sfchans(sfh) > SF_MAXCHAN) { fprintf(stderr, "Soundfile has %d channels (only %d supported)\n", sfchans(sfh), SF_MAXCHAN); return -1; } sfsrate(sfh) = (float)mus_header_srate(); /* mus_header_samples() gives number of samples. */ sfdatasize(sfh) = mus_header_samples() * sfclass(sfh); /* Read peak stats, if any, from file, and copy them from the SFComment struct into our SFHEADER's sf_maxamp struct. We don't really care if there's an error while reading these ... the sf_maxamp struct will be zero'd out in that case. */ sndlib_get_current_header_comment(fd, &sfc); peak_stats_to_sfmaxamp(&sfmaxampstruct(sfh), &sfc, sfchans(sfh)); /* Copy comment string, if any, into SFHEADER. */ strncpy(sfcommentstr(sfh), sfc.comment, MAXCOMM); sfcommentstr(sfh)[MAXCOMM - 1] = '\0'; /* ensure termination */ /* Seek to beginning of snd data. */ if (lseek(fd, sfdatalocation(sfh), SEEK_SET) == -1) { perror("sndlib_rheader: lseek"); return -1; } return 0; } /* ------------------------------------------------------- sndlib_wheader --- */ /* Invoked by the wheader macro in H/sfheader.h. This is meant to be called only by legacy disk-based cmix software, like sound.c and the utility programs. New programs and the RTcmix core should use sndlib_write_header instead. Writes header according to the fields of <sfh> for the file already opened as <fd>. Updates file peak stats, using the ones in <sfh>. Ignores the peak stat timestamp (timetag) it finds there, because sndlib_put_header_comment updates this. It's possible to change the following header fields with this call: header type (must be a WRITEABLE_HEADER_TYPE), class or packmode (internally converted to sndlib data format), sampling rate, number of channels. Be careful changing the header type! This will almost certainly cause some dropped or added samples at beginning of file, and may even cause channel swapping or bad sample word alignment. Before closing an output file, you should update the header's idea of how much sound data there is by calling putlength. Normally the header has already been created (by sfcreate), and this function is called to update it for new peak stats and so forth. But some utility programs (rescale, sndreverse) use this function to write a header on a newly created file. If the file opened as <fd> has zero length, we write a new header on it (with zero'd peak stats and comment). Otherwise, we assume the file has a valid header that just needs updating. In all cases the data format stored in the SFHEADER struct is ignored; it's filled in here by converting from the sf_packmode (sfclass). On success, leaves file position pointer at start of sound data, and returns 0; Otherwise, returns -1. */ int sndlib_wheader(int fd, SFHEADER *sfh) { int result, header_type, data_format; off_t file_length; char *rawcomment = NULL; assert(fd >= 0 && sfh != NULL); header_type = sfheadertype(sfh); if (!WRITEABLE_HEADER_TYPE(header_type)) { fprintf(stderr, "sndlib_wheader: Can't write this type of header\n"); return -1; } data_format = sf_class_to_data_format(sfclass(sfh), header_type); sfdataformat(sfh) = data_format; /* Use AIFF, not AIFC, unless it's a float file. */ if (header_type == MUS_AIFF && data_format == MUS_BFLOAT) header_type = MUS_AIFC; file_length = lseek(fd, 0, SEEK_END); if (file_length == -1) { perror("sndlib_wheader: lseek"); return -1; } if (file_length > 0) { SFComment sfc; /* Copy peak stats and comment into SFComment struct. */ sfmaxamp_to_peak_stats(&sfc, &(sfmaxampstruct(sfh)), sfchans(sfh)); strncpy(sfc.comment, sfcommentstr(sfh), MAX_COMMENT_CHARS); sfc.comment[MAX_COMMENT_CHARS - 1] = '\0'; /* ensure termination */ result = format_raw_comment(&sfc, sfchans(sfh), &rawcomment); if (result == -1) rawcomment = NULL; /* just don't write comment */ } result = sndlib_write_header(fd, (file_length > 0), header_type, data_format, sfsrate(sfh), sfchans(sfh), rawcomment, &(sfdatalocation(sfh))); if (rawcomment) free(rawcomment); return result; } /* -------------------------------------------------------- getheadersize --- */ /* Replacement for old getheadersize in wheader.c. */ int getheadersize(SFHEADER *sfh) { assert(sfh != NULL); return sfdatalocation(sfh); } /* ------------------------------------------------------------ putlength --- */ /* Replacement for old putlength in wheader.c. Using header info in <sfh>, updates data_size field of <sfh> and writes this to file header. Ignores <sfname>, which is there only for compatibility with the old function. Should call this just before closing the file. Returns 0 if OK, -1 if error. */ int putlength(char *sfname, int fd, SFHEADER *sfh) { int result; long header_size; off_t file_length; assert(fd >= 0 && sfh != NULL); if (!WRITEABLE_HEADER_TYPE(sfheadertype(sfh))) { fprintf(stderr, "putlength: Can't write this type of header.\n"); return -1; } header_size = sfdatalocation(sfh); assert(header_size >= 24); /* feeble sanity check */ file_length = lseek(fd, 0, SEEK_END); if (file_length == -1) { perror("putlength: lseek"); return -1; } if (file_length >= header_size) { sfdatasize(sfh) = file_length - header_size; result = sndlib_set_header_data_size(fd, sfheadertype(sfh), sfdatasize(sfh)); if (result == -1) { fprintf(stderr, "putlength: Can't update header data size\n"); return -1; } } else { fprintf(stderr, "putlength: Invalid data_location\n"); return -1; } return 0; } /* Below are versions of getsfcode and putsfcode that work with sndlib. Header codes other than SF_MAXAMP and SF_COMMENT will trigger an error message. The goal here is to keep the old API where possible, so that most callers won't have to be changed. NOTES: (1) The SFHEADER passed to these functions is the header in memory, already read from disk by the rheader macro (in H/sfheader.h). These functions don't do any file i/o. (2) No byte-swapping of maxamp data is ever necessary with sndlib. So any byte-swapping done by code that calls these functions should be commented out for the sndlib version. (3) The way getsfcode works is pretty funky. If you aren't using it in exactly the way cited below, you should use the new function getsfmaxamp instead. */ /* ------------------------------------------------------------ getsfcode --- */ /* This is kind of nasty -- it returns a pointer with the expectation that the caller will increment it by sizeof(SFCODE), in order to copy the SFMAXAMP struct or comment string from the header into local storage. This is to handle the normal use of this function in cmix: char *cp = getsfcode(&sfdesc[fno], SF_MAXAMP); bcopy(cp + sizeof(SFCODE), (char *)&sfm[fno], sizeof(SFMAXAMP)); If you aren't following this usage exactly, you should use the new getsfmaxamp function below, or for a comment, just copy up to MAXCOMM chars from sfcommentstr(sfh) into local storage. Returns NULL if requested code is not of type SF_MAXAMP or SF_COMMENT. */ char * getsfcode(SFHEADER *sfh, int code) { assert(sfh != NULL); switch (code) { case SF_MAXAMP: return ((char *)(&(sfmaxampstruct(sfh))) - sizeof(SFCODE)); break; case SF_COMMENT: return (sfcommentstr(sfh) - sizeof(SFCODE)); break; default: fprintf(stderr, "getsfcode: Requested code type invalid\n"); } return NULL; } /* ------------------------------------------------------------ putsfcode --- */ /* If <codeptr> represents an old IRCAM header code of type SF_MAXAMP, putsfcode blindly copies sizeof(SFMAXAMP) bytes from <ptr> into the <sf_maxamp> field of the given SFHEADER. If <codeptr> represents a header code of type SF_COMMENT, copies up to MAXCOMM chars from <ptr> into the <sf_comment> field of SFHEADER. (Note that we ignore the <bsize> field of the SFCODE struct.) Returns 0 if the requested code is of type SF_MAXAMP or SF_COMMENT; otherwise, returns -1. */ int putsfcode(SFHEADER *sfh, char *ptr, SFCODE *codeptr) { assert(sfh != NULL && ptr != NULL && codeptr != NULL); switch (codeptr->code) { case SF_MAXAMP: memcpy(&(sfmaxampstruct(sfh)), ptr, sizeof(SFMAXAMP)); break; case SF_COMMENT: strncpy(sfcommentstr(sfh), ptr, MAXCOMM - 1); sfcommentstr(sfh)[MAXCOMM - 1] = '\0'; break; default: fprintf(stderr, "putsfcode: Requested code type invalid\n"); return -1; } return 0; } /* ---------------------------------------------------------- getsfmaxamp --- */ /* The old getsfcode has an undesirable API for sndlib purposes. So here's a new function that retrieves an SFMAXAMP struct from an SFHEADER in memory. Copies the sf_maxamp struct of <sfh> into <sfm> (storage allocated by caller). Returns -1 if either argument is NULL; otherwise returns 0. */ int getsfmaxamp(SFHEADER *sfh, SFMAXAMP *sfm) { assert(sfh != NULL && sfm != NULL); memcpy(sfm, &(sfmaxampstruct(sfh)), sizeof(SFMAXAMP)); return 0; } /* ----------------------------------------------- peak_stats_to_sfmaxamp --- */ static int peak_stats_to_sfmaxamp(SFMAXAMP *sfm, SFComment *sfc, int nchans) { int n; assert(sfm != NULL && sfc != NULL); /* awkward: two constants for max, in sfheader.h and rtstuff/rtdefs.h */ assert(nchans > 0 && nchans <= SF_MAXCHAN); memset(sfm, 0, sizeof(SFMAXAMP)); /* zero out the SFMAXAMP struct */ if (SFCOMMENT_PEAKSTATS_VALID(sfc)) { /* sfc has valid peak stats */ for (n = 0; n < nchans; n++) { sfm->value[n] = sfc->peak[n]; sfm->samploc[n] = sfc->peakloc[n]; } sfm->timetag = sfc->timetag; } return 0; } /* ----------------------------------------------- sfmaxamp_to_peak_stats --- */ /* NOTE: This zeros out the SFComment struct, so don't store comment string there before calling this function! */ static int sfmaxamp_to_peak_stats(SFComment *sfc, SFMAXAMP *sfm, int nchans) { int n; assert(sfc != NULL && sfm != NULL); /* awkward: two constants for max, in sfheader.h and rtstuff/rtdefs.h */ assert(nchans > 0 && nchans <= MAXCHANS); memset(sfc, 0, sizeof(SFComment)); /* zero out the SFComment struct */ if (sfm->timetag != 0) { /* sfm has valid peak stats */ for (n = 0; n < nchans; n++) { sfc->peak[n] = sfm->value[n]; sfc->peakloc[n] = sfm->samploc[n]; } sfc->timetag = sfm->timetag; } return 0; } /* ---------------------------------------------- sf_class_to_data_format --- */ /* Return the sndlib data format for the given class and header type. Assumes that 2-byte words are 16-bit linear and 4-byte words are 32-bit float (not 32-bit linear). Also assumes that the data format is big-endian, unless the header type is RIFF (aka WAV). These are safe assumptions for disk-based cmix. */ static int sf_class_to_data_format(int class, int header_type) { int data_format; assert(class == SF_SHORT || class == SF_FLOAT); if (class == SF_SHORT) data_format = MUS_BSHORT; else /* class == SF_FLOAT */ data_format = MUS_BFLOAT; if (header_type == MUS_RIFF) data_format = (data_format == MUS_BSHORT) ? MUS_LSHORT : MUS_LFLOAT; return data_format; } #endif /* CMIX_LEGACY */
2.09375
2
2024-11-18T19:35:03.158360+00:00
2022-03-31T13:40:14
b361e99fd17e3643866076d65f32925261a474fc
{ "blob_id": "b361e99fd17e3643866076d65f32925261a474fc", "branch_name": "refs/heads/master", "committer_date": "2022-03-31T13:40:14", "content_id": "f29a6a1d6414486e7905fc2dbf45462a21460d66", "detected_licenses": [ "MIT" ], "directory_id": "4e7f82bd975bdf43708cbb9636de2450afd38cf9", "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": 91445361, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3662, "license": "MIT", "license_type": "permissive", "path": "/main.c", "provenance": "stackv2-0054.json.gz:6394", "repo_name": "zareldyn/hazlab", "revision_date": "2022-03-31T13:40:14", "revision_id": "882b17d4ea11f81666ae76ca43249a0ce7fa3657", "snapshot_id": "860448d30bf0d4477b56dc7518462b84ee05c51d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/zareldyn/hazlab/882b17d4ea11f81666ae76ca43249a0ce7fa3657/main.c", "visit_date": "2022-06-07T04:34:27.191580" }
stackv2
/* main.c PROGRAMME PRINCIPAL ET FONCTIONS UTILES */ /*=== externe ================================================================*/ #include <stdlib.h> #include <limits.h> #include <GL/glut.h> #include "hazlab.h" #include "textures.h" #include "dimlab.h" extern char Menu( void ); /*menu.c*/ extern void CreationLab( void ); /*crealab.c*/ extern GLfloat* SommetsPtrMurs, * CoordTxPtrMurs, * SommetsPtrSups, * CoordTxPtrSups; extern void Jeu( void ); /*jeu.c*/ extern void InitNav( void ); /*navig.c*/ extern void TermNav( void ); extern void TermTextures( char ); /*textures.c*/ /*=== global(partagé) ========================================================*/ int* LabyPtr; /*début de la zone mémoire contenant la matrice-labyrinthe*/ int** LabyIJ; /*pour utiliser cette matrice sous forme LabyIJ[i][j]*/ int TailleLab; /*taille (de la matrice) d'un coté du labyrinthe*/ hbool LabyConstruit; /*indique l'existence de la matrice*/ char Codage = hLITTLE_ENDIAN; /*par défaut destiné à x86 ;-)*/ char TailleLong = 1; /*taille (calcul ultérieur de la bonne valeur) en octets d'un entier de type "long"*/ char TailleChar = CHAR_BIT/8; /*idem pour un type "char"*/ /*=== échange de la valeur de deux GLbytes ===================================*/ void EchangerGLbyte( GLubyte* const a, GLubyte* const b ) { *a ^= *b; *b ^= *a; *a ^= *b; } /*=== comptage des bits égaux à 1 dans un entier de type "long" ==============*/ huchar CompterBits1( hulong entier ) { huchar cpt = 0; while( entier ) { cpt++; entier &= (entier-1); } return cpt; } /*=== inversion des n octets d'un entier de type "long" ======================*/ void InverserLong( hulong* const entier, char const n ) { char i = -1; hulong masque = -1l, resultat = 0l; masque = ~(masque>>8); /*bits du premier octet à 1, le reste à 0*/ while( ++i <n ) { resultat |= ((*entier & masque)>>((TailleLong-1-i)<<3)) << (i<<3); /*on sélectionne le bon octet grâce au masque et on l'ajoute à la bonne place au résultat*/ masque >>= 8; /*on décale le masque sur l'octet suivant*/ } *entier = resultat; } /*=== vérification du codage interne des entiers =============================*/ hINLINE( static void VerifierCodage( void ) ) { hulong n = -2l; /*dernier bit à 0*/ char p = *(char*)&n; if( p==-1 ) Codage = hBIG_ENDIAN; n = -1l; /*tous les bits à 1*/ while( n >>= 8 ) TailleLong++; } /*=== destruction du labyrinthe ==============================================*/ static void LibererMemoire( void ) { if( LabyConstruit ) { free( LabyPtr ); free( LabyIJ ); free( SommetsPtrMurs ); free( CoordTxPtrMurs ); free( SommetsPtrSups ); free( CoordTxPtrSups ); TermNav(); TermTextures( NBR_TEXTURES ); } } /*=== point d'entrée =========================================================*/ int main( int nbreArgs, char* listArgs[] ) { VerifierCodage(); atexit( LibererMemoire ); glutInit( &nbreArgs, listArgs ); glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH ); while( (TailleLab = Menu()) !=0 ) { TailleLab = TailleLab*4*COEFF_TAILLE-1; CreationLab(); LabyConstruit = hVRAI; InitNav(); Jeu(); LibererMemoire(); LabyConstruit = hFAUX; } return EXIT_SUCCESS; }
2.421875
2
2024-11-18T19:35:03.261758+00:00
2020-04-14T12:53:05
98fe20c1684b5226156bb17d051808859baba196
{ "blob_id": "98fe20c1684b5226156bb17d051808859baba196", "branch_name": "refs/heads/master", "committer_date": "2020-04-14T12:53:05", "content_id": "9d5d0218696353560726c1a757ca6a5aaeff17b9", "detected_licenses": [ "MIT" ], "directory_id": "414fd127c226ad1a2e01b7fc2dba213527f42e3c", "extension": "c", "filename": "render.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 255613055, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10455, "license": "MIT", "license_type": "permissive", "path": "/render.c", "provenance": "stackv2-0054.json.gz:6522", "repo_name": "ymishin/YAPS_old", "revision_date": "2020-04-14T12:53:05", "revision_id": "f35929536ce12d51d8bceedba622cbd9239a5fa2", "snapshot_id": "8aac461178d6b8189fa9745240d4af9ea294d334", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ymishin/YAPS_old/f35929536ce12d51d8bceedba622cbd9239a5fa2/render.c", "visit_date": "2022-04-19T11:40:28.845297" }
stackv2
/** * Copyright (c) 2005,2010 Yury Mishin <[email protected]> * See the file COPYING for copying permission. * * $Id$ */ #include <stdlib.h> #include <string.h> #include "opengl.h" #include "common.h" #include "calc.h" #include "vector.h" #include "render.h" /**********************************************************/ /* The number of display list to draw the obstacles */ #define OBSTACLES_LIST 1 /* The number of display list to draw the help */ #define HELP_LIST 2 /**********************************************************/ /* RGB color to draw the smoothing particles */ static float ParticleColor[3] = { 0.0f, 0.4f, 0.6f }; /* RGB color to draw the boundary particles */ static float BParticleColor[3] = { 0.9f, 0.9f, 0.9f }; /* RGB color to clear the background */ static float BackgroundColor[3] = { 0.7f, 0.7f, 0.7f }; /* RGB color to draw the segments */ static float SegmentColor[3] = { 0.0f, 0.0f, 0.0f }; /* RGB color to draw the triangles' edges */ static float TriangleLineColor[3] = { 0.0f, 0.0f, 0.0f }; /* RGBA color to fill the triangles' interiors */ static float TriangleFillColor[4] = { 0.6f, 0.6f, 0.6f, 0.8f }; /* RGB color to draw the help */ static float HelpColor[3] = { 0.0f, 0.2f, 0.3f }; /**********************************************************/ /* Default size of the window */ int WindowWidth = 500; int WindowHeight = 500; /* Clipping volume (the area to render) */ float ClipVolume; /**********************************************************/ /* Short help which is drawn on the screen */ static char *Help[] = { "Rotation - arrow keys", "Scaling - PgUp/PgDn", "Start/Pause - S", "Exit - Q", }; /* The size of this array */ static int HelpSize = sizeof(Help) / sizeof(Help[0]); /* The factor which define the height of one help's line */ static float HelpLineHeight = 50.0f; /* The factor which define the size of characters to draw the help */ static float HelpCharSize = 0.00015f; /** * Initialize display list(s). */ void InitDisplayLists( void) { int i, j; /* Initialize HELP_LIST */ glNewList( HELP_LIST, GL_COMPILE); /* Color to draw the help */ glColor3fv( HelpColor); glPushMatrix(); for ( i = 0; i < HelpSize; i++ ) { /* Set the origin to draw the next line */ glLoadIdentity(); glTranslatef( 0.0f, ClipVolume - (ClipVolume / HelpLineHeight) * (float)(i + 1), ClipVolume); glScalef( ClipVolume * HelpCharSize, ClipVolume * HelpCharSize, 1.0f); /* Draw the line with help */ for ( j = 0; j < strlen( Help[i]); j++ ) { glutStrokeCharacter( GLUT_STROKE_MONO_ROMAN, Help[i][j]); } } glPopMatrix(); /* End of HELP_LIST */ glEndList(); /* Initialize OBSTACLES_LIST */ glNewList( OBSTACLES_LIST, GL_COMPILE); #if 0 /* Draw boundary particles */ glColor3fv( BParticleColor); for ( i = 0; i < BParticlesNumber; i++ ) { glPushMatrix(); glTranslatef( BParticles[i].Pos[0], BParticles[i].Pos[1], BParticles[i].Pos[2]); glutSolidSphere( 2.0f, 10, 10); glPopMatrix(); } #endif if ( Dimension == 2 ) { /* Obstacles are segments */ struct ObstacleSegment *Segments; Segments = (struct ObstacleSegment *)Obstacles; /* Draw segments */ glBegin( GL_LINES); for ( i = 0; i < ObstaclesNumber; i++ ) { glColor3fv( SegmentColor); glVertex3fv( Segments[i].Vrtx1); glVertex3fv( Segments[i].Vrtx2); } glEnd(); } else if ( Dimension == 3 ) { /* Obstacles are triangles */ struct ObstacleTriangle *Triangles; Triangles = (struct ObstacleTriangle *)Obstacles; /* Draw triangles' edges */ glPolygonMode( GL_FRONT_AND_BACK, GL_LINE); glBegin( GL_TRIANGLES); for ( i = 0; i < ObstaclesNumber; i++ ) { glColor3fv( TriangleLineColor); glVertex3fv( Triangles[i].Vrtx1); glVertex3fv( Triangles[i].Vrtx2); glVertex3fv( Triangles[i].Vrtx3); } glEnd(); /* Fill triangles' interiors */ glPolygonMode( GL_FRONT_AND_BACK, GL_FILL); /* If it is transparent - turn off depth test */ if ( TriangleFillColor[3] < 1.0f ) glDepthMask( GL_FALSE); glBegin( GL_TRIANGLES); for ( i = 0; i < ObstaclesNumber; i++ ) { glColor4fv( TriangleFillColor); glVertex3fv( Triangles[i].Vrtx1); glVertex3fv( Triangles[i].Vrtx2); glVertex3fv( Triangles[i].Vrtx3); } glEnd(); /* Turn on depth test if it was turned off */ if ( TriangleFillColor[3] < 1.0f ) glDepthMask( GL_TRUE); } /* End of OBSTACLES_LIST */ glEndList(); return; } /* InitDisplayLists */ /**********************************************************/ /** * Initialize OpenGL capabilities. */ void InitGLCapabilities( void) { /* Turn on antialiasing for lines */ glEnable( GL_LINE_SMOOTH); glHint( GL_LINE_SMOOTH_HINT, GL_NICEST); /* Turn on Z-Buffer */ glEnable( GL_DEPTH_TEST); glDepthFunc( GL_LEQUAL); /* Turn on blending */ glEnable( GL_BLEND); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); return; } /* InitGLCapabilities */ /**********************************************************/ /********************************************************** * * * GLUT CALLBACKS * * * **********************************************************/ /* State of pause instruction */ static int Pause = 1; /** * GLUT idle callback. */ void IdleCallback( void) { /* Check the state */ if ( Pause == 1 ) { return; } /* Do one calculation step */ DoCalcStep(); /* Redisplay */ glutPostRedisplay(); return; } /* IdleCallBack */ /** * GLUT display callback. */ void DisplayCallback( void) { int i; /* Clear the buffers */ glClearColor( BackgroundColor[0], BackgroundColor[1], BackgroundColor[2], 1.0f); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /* Draw the help */ glCallList( HELP_LIST); /* Draw the particles */ for ( i = 0; i < ParticlesNumber; i++ ) { glPushMatrix(); glTranslatef( Particles[i].Pos[0], Particles[i].Pos[1], Particles[i].Pos[2]); glColor3fv( ParticleColor); glutSolidSphere( 3.5f, 20, 20); glPopMatrix(); } /* Draw the obstacles */ glCallList( OBSTACLES_LIST); /* Swap the buffers */ glutSwapBuffers(); return; } /* DisplayCallback */ /** * GLUT reshape callback. */ void ReshapeCallback( int Width, /* Window's width */ int Height) /* Window's height */ { /* It's not allowed to change the size of the window */ glutReshapeWindow( WindowWidth, WindowHeight); glViewport( 0, 0, WindowWidth, WindowHeight); /* Set projection matrix */ glMatrixMode( GL_PROJECTION); glLoadIdentity(); glOrtho( 0.0f, ClipVolume, 0.0f, ClipVolume, -ClipVolume * 4.0f, ClipVolume * 3.0f); glMatrixMode( GL_MODELVIEW); return; } /* ReshapeCallback */ /** * GLUT keyboard callback. */ void KeyboardCallback( unsigned char Key, /* Key's code */ int X, /* Position of */ int Y) /* the mouse */ { switch (Key) { case 's': case 'S': /* 's' or 'S' - start/pause the simulation */ Pause = Pause ? 0 : 1; break; case 'Q': case 'q': /* 'q' or 'Q' - exit the program */ free( Particles); free( BParticles); if ( Dimension == 2 ) free( (struct ObstacleSegment *)Obstacles); else if ( Dimension == 3 ) free( (struct ObstacleTriangle *)Obstacles); exit( 0); default: break; } return; } /* KeyboardCallback */ /* Scaling/rotation steps */ static float ScaleStep = 0.1f; static float XRotateStep = 1.0f; static float YRotateStep = 1.0f; /* Current scaling/rotation factors */ static float ScaleFactor = 1.0f; static float XRotateFactor = 0.0f; static float YRotateFactor = 0.0f; /** * GLUT special functions callback. */ void SpecialFuncCallback( int Key, /* Key's code */ int X, /* Position of */ int Y) /* the mouse */ { switch (Key) { case GLUT_KEY_UP: XRotateFactor += XRotateStep; break; case GLUT_KEY_DOWN: XRotateFactor -= XRotateStep; break; case GLUT_KEY_LEFT: YRotateFactor += YRotateStep; break; case GLUT_KEY_RIGHT: YRotateFactor -= YRotateStep; break; case GLUT_KEY_PAGE_UP: ScaleFactor += ScaleStep; break; case GLUT_KEY_PAGE_DOWN: ScaleFactor -= ScaleStep; break; default: break; } glLoadIdentity(); /* Set the center of rotation */ glTranslatef( ClipVolume / 2.0f, ClipVolume / 2.0f, ClipVolume / 2.0f); /* Rotate the scene along X-axis */ glRotatef( XRotateFactor, 1.0, 0.0, 0.0); /* Rotate the scene along Y-axis */ glRotatef( YRotateFactor, 0.0, 1.0, 0.0); /* Scale the scene */ if ( ScaleFactor < ScaleStep ) ScaleFactor = ScaleStep; glScalef( ScaleFactor, ScaleFactor, ScaleFactor); /* Restore the origin */ glTranslatef( -ClipVolume / 2.0f, -ClipVolume / 2.0f, -ClipVolume / 2.0f); /* Redisplay the scene */ glutPostRedisplay(); return; } /* SpecialFuncCallback */
2.484375
2
2024-11-18T19:35:03.333796+00:00
2018-04-23T21:23:41
92a9dd5dda895aa58731d15f8453405886ad1a36
{ "blob_id": "92a9dd5dda895aa58731d15f8453405886ad1a36", "branch_name": "refs/heads/develop", "committer_date": "2018-04-23T21:23:41", "content_id": "bb6d3ac943d390f2174936349340f6f6e51e8e1e", "detected_licenses": [ "BSL-1.0" ], "directory_id": "d8860eb725a51fd0ef814bebfb8abaa8a807996d", "extension": "c", "filename": "getptext.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": 2063, "license": "BSL-1.0", "license_type": "permissive", "path": "/pcff/source/getptext.c", "provenance": "stackv2-0054.json.gz:6650", "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/pcff/source/getptext.c", "visit_date": "2021-01-20T03:53:21.763387" }
stackv2
/* *********************************************************************** */ /* *********************************************************************** */ /* Parse Configuration File Facility (PCFF) Library Module Source File */ /* *********************************************************************** */ /* File Name : %M% File Version : %I% Last Extracted : %D% %T% Last Updated : %E% %U% File Description : Get descriptive text for a 'PCFF_PARAM' structure. Revision History : 1999-11-03 --- Creation. Michael L. Brock Copyright Michael L. Brock 1999 - 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) */ /* *********************************************************************** */ /* *********************************************************************** */ /* *********************************************************************** */ /* Required include files . . . */ /* *********************************************************************** */ #include <stdio.h> #include <string.h> #include <strfuncs.h> #include "pcffi.h" /* *********************************************************************** */ /* *********************************************************************** */ char *PCFF_GetParamText(const PCFF_PARAM *param_ptr, char *param_text) { return(chrcat(strcat(strcat(strcat(strcpy(param_text, "parameter name '"), param_ptr->param_name), "', member name '"), param_ptr->member_name), '\'')); } /* *********************************************************************** */ /* *********************************************************************** */ char *PCFF_GetParamTextIndex(const PCFF_PARAM *param_ptr, unsigned int param_index, char *param_text) { sprintf(param_text, "parameter index %u, ", param_index); return(PCFF_GetParamText(param_ptr, param_text + strlen(param_text))); } /* *********************************************************************** */
2.078125
2
2024-11-18T19:35:03.543852+00:00
2019-03-18T02:14:55
94ae952c0ec2e8366201691744218a8fc7cf17df
{ "blob_id": "94ae952c0ec2e8366201691744218a8fc7cf17df", "branch_name": "refs/heads/master", "committer_date": "2019-03-18T02:14:55", "content_id": "2c86e4edf8b32407cae31186e8b49b236b5acdb6", "detected_licenses": [ "CC0-1.0" ], "directory_id": "81ee58d95bc3e14c0b9f10e4ec13bc1d2fd9972f", "extension": "h", "filename": "Vec3.h", "fork_events_count": 0, "gha_created_at": "2019-03-18T02:13:13", "gha_event_created_at": "2019-03-18T02:13:13", "gha_language": null, "gha_license_id": "NOASSERTION", "github_id": 176188401, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3806, "license": "CC0-1.0", "license_type": "permissive", "path": "/Core/Vec3.h", "provenance": "stackv2-0054.json.gz:7034", "repo_name": "ericoporto/fw-public", "revision_date": "2019-03-18T02:14:55", "revision_id": "90bd713cf40604118176883e5aef3c067373bb87", "snapshot_id": "a49af2fed9cb63e5af628cc7a68f60ce7058eff4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ericoporto/fw-public/90bd713cf40604118176883e5aef3c067373bb87/Core/Vec3.h", "visit_date": "2020-04-29T14:10:10.766225" }
stackv2
#ifndef _VEC3_H_ #define _VEC3_H_ #include <math.h> #include "CoreHelpers.h" struct Vec3 { Vec3() restrict(amp) restrict(cpu) { x = y = z = 0; } Vec3(float val) restrict(amp) restrict(cpu) { x = y = z = val; } Vec3(float _x, float _y, float _z) restrict(amp) restrict(cpu) { x = _x; y = _y; z = _z; } union { float m_data[3]; struct { float x, y, z; }; }; static inline Vec3 Cross(const Vec3 & lhs, const Vec3 & rhs) restrict(amp) restrict(cpu) { Vec3 ret; ret.x = lhs.y * rhs.z - lhs.z * rhs.y; ret.y = lhs.z * rhs.x - lhs.x * rhs.z; ret.z = lhs.x * rhs.y - lhs.y * rhs.x; return ret; } static inline float Dot(const Vec3 & lhs, const Vec3 & rhs) restrict(amp) restrict(cpu) { return lhs.x*rhs.x + lhs.y*rhs.y + lhs.z*rhs.z; } inline float LengthSqr() const restrict(amp) restrict(cpu) { return Dot(*this,*this); } inline float Length() const { return sqrtf(LengthSqr()); } inline float InvLength() const { return SafeInv(Length()); } inline void NormalizeMe() { float invLen = InvLength(); x *= invLen; y *= invLen; z *= invLen; } static inline Vec3 Normalize(const Vec3 & lhs) { Vec3 ret = lhs; ret.NormalizeMe(); return ret; } static float Dist(const Vec3 & lhs, const Vec3 & rhs) { Vec3 sub; sub.x = lhs.x-rhs.x; sub.y = lhs.y-rhs.y; sub.z = lhs.z-rhs.z; return sub.Length(); } static float DistSqr(const Vec3 & lhs, const Vec3 & rhs) { Vec3 sub; sub.x = lhs.x-rhs.x; sub.y = lhs.y-rhs.y; sub.z = lhs.z-rhs.z; return sub.LengthSqr(); } static inline Vec3 ProjectPointIntoPlane(const Vec3 & p, const Vec3 & n, const Vec3 & x); static inline bool IsEqual(const Vec3 & lhs, const Vec3 & rhs) { if (lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z) { return true; } return false; } }; inline Vec3 operator*(const Vec3 & lhs, const Vec3 & rhs) restrict(amp) restrict(cpu) { return Vec3(lhs.x*rhs.x,lhs.y*rhs.y,lhs.z*rhs.z); } inline Vec3 operator*(float lhs, const Vec3 & rhs) restrict(amp) restrict(cpu) { return Vec3(lhs*rhs.x,lhs*rhs.y,lhs*rhs.z); } inline Vec3 operator*(const Vec3 & lhs, float rhs) restrict(amp) restrict(cpu) { return Vec3(lhs.x*rhs,lhs.y*rhs,lhs.z*rhs); } inline Vec3 operator+(const Vec3 & lhs, const Vec3 & rhs) restrict(amp) restrict(cpu) { return Vec3(lhs.x+rhs.x,lhs.y+rhs.y,lhs.z+rhs.z); } inline Vec3 operator+(float lhs, const Vec3 & rhs) restrict(amp) restrict(cpu) { return Vec3(lhs+rhs.x,lhs+rhs.y,lhs+rhs.z); } inline Vec3 operator+(const Vec3 & lhs, float rhs) restrict(amp) restrict(cpu) { return Vec3(lhs.x+rhs,lhs.y+rhs,lhs.z+rhs); } inline Vec3 operator/(const Vec3 & lhs, const Vec3 & rhs) restrict(amp) restrict(cpu) { return Vec3(lhs.x/rhs.x,lhs.y/rhs.y,lhs.z/rhs.z); } inline Vec3 operator/(float lhs, const Vec3 & rhs) restrict(amp) restrict(cpu) { return Vec3(lhs/rhs.x,lhs/rhs.y,lhs/rhs.z); } inline Vec3 operator/(const Vec3 & lhs, float rhs) restrict(amp) restrict(cpu) { return Vec3(lhs.x/rhs,lhs.y/rhs,lhs.z/rhs); } inline Vec3 operator-(const Vec3 & lhs, const Vec3 & rhs) restrict(amp) restrict(cpu) { return Vec3(lhs.x-rhs.x,lhs.y-rhs.y,lhs.z-rhs.z); } inline Vec3 operator-(float lhs, const Vec3 & rhs) restrict(amp) restrict(cpu) { return Vec3(lhs-rhs.x,lhs-rhs.y,lhs-rhs.z); } inline Vec3 operator-(const Vec3 & lhs, float rhs) restrict(amp) restrict(cpu) { return Vec3(lhs.x-rhs,lhs.y-rhs,lhs.z-rhs); } inline Vec3 & operator+=(Vec3 & lhs, const Vec3 & rhs) restrict(amp) restrict(cpu) { lhs = lhs+rhs; return lhs; } inline Vec3 & operator-=(Vec3 & lhs, const Vec3 & rhs) restrict(amp) restrict(cpu) { lhs = lhs-rhs; return lhs; } inline Vec3 Vec3::ProjectPointIntoPlane(const Vec3 & p, const Vec3 & n, const Vec3 & x) { return x - Dot(x-p,n)*n; } #endif
2.734375
3
2024-11-18T19:35:06.229555+00:00
2023-05-31T23:22:47
818708e8337bd3daa8e0164ca66541f9b9ff19a7
{ "blob_id": "818708e8337bd3daa8e0164ca66541f9b9ff19a7", "branch_name": "refs/heads/main", "committer_date": "2023-05-31T23:22:47", "content_id": "5dbd8e9707bbda305036db25d4652ca67ed3fecb", "detected_licenses": [ "MIT" ], "directory_id": "4a727ce379e9d21826895699d09164cdac4836d5", "extension": "c", "filename": "fptrs.c", "fork_events_count": 95, "gha_created_at": "2018-11-09T22:21:21", "gha_event_created_at": "2022-11-26T19:09:25", "gha_language": "C", "gha_license_id": "MIT", "github_id": 156924419, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 804, "license": "MIT", "license_type": "permissive", "path": "/notes/session02/fptrs.c", "provenance": "stackv2-0054.json.gz:7418", "repo_name": "RHIT-CSSE/csse332", "revision_date": "2023-05-31T23:22:47", "revision_id": "7b9e292381062d25934c18210e6bbe7241392cdc", "snapshot_id": "83e58d6c377e67d4cfcc37e2f20f18991c5063bf", "src_encoding": "UTF-8", "star_events_count": 10, "url": "https://raw.githubusercontent.com/RHIT-CSSE/csse332/7b9e292381062d25934c18210e6bbe7241392cdc/notes/session02/fptrs.c", "visit_date": "2023-06-08T11:16:43.095931" }
stackv2
#include <stdio.h> #include <stdlib.h> int foo(int x, int y) { printf("in function %s\n", __func__); return x + y; } int bar(int x, int y) { printf("in function %s\n", __func__); return x - y; } int main(int argc, char **argv) { int x = 5, y = 3, z; void *p; // define a function pointer int (*fptr)(int, int) = 0; // change the function pointer to foo fptr = foo; // call fptr printf("calling foo using fptr results in %d\n", fptr(x, y)); // change it to bar now fptr = bar; // call fptr printf("calling bar using fptr results in %d\n", fptr(x, y)); // can also using a void ptr to use a function pointer p = foo; // can also use p = &foo; // but must cast when calling z = ((int (*)(int,int))p)(x, y); printf("z = %d\n", z); exit(EXIT_SUCCESS); }
3.296875
3
2024-11-18T19:35:06.544375+00:00
2015-04-17T12:42:00
b2ef027a65f80aaff3d52c8640d83d8cf0c1d377
{ "blob_id": "b2ef027a65f80aaff3d52c8640d83d8cf0c1d377", "branch_name": "refs/heads/master", "committer_date": "2015-04-17T12:42:00", "content_id": "191a5638d7b9298e270bdbb66b2afd911b903139", "detected_licenses": [ "MIT" ], "directory_id": "98d918302f633a540692c80d8376fca351b734ca", "extension": "h", "filename": "menu_item.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": 1268, "license": "MIT", "license_type": "permissive", "path": "/sourcecode/Common/dConnectDevicePebbleApp/src/menu_item.h", "provenance": "stackv2-0054.json.gz:7932", "repo_name": "PUNIT6425/DeviceConnect", "revision_date": "2015-04-17T12:42:00", "revision_id": "620c274e1b0a331c6a0b4c8f4f7626ca61d179ba", "snapshot_id": "37bc48b8138ff2f8536ccbe8274261d2b61e7d30", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/PUNIT6425/DeviceConnect/620c274e1b0a331c6a0b4c8f4f7626ca61d179ba/sourcecode/Common/dConnectDevicePebbleApp/src/menu_item.h", "visit_date": "2020-04-08T10:18:52.989013" }
stackv2
#ifndef menu_item_h #define menu_item_h typedef struct __attribute__((__packed__)) { bool is_gbitmap ; // Gbitmap(image), text char* title ; // title void* bitmap_or_text ; } MenuItem ; /*! @brief メニューの初期化 @param[in] data GBitmapのデータ @param[in] size データサイズ */ void init_menu_item( void ) ; /*! @brief メニューを追加する @param[in] titleStr メニューのタイトル @param[in] contents 文字列または gbitmap @param[in] is_gbitmap ; */ void entry_menu_item( char* titleStr, void* contents, bool is_gbitmap ); /*! @brief 最新のメニューをリプレースする @param[in] titleStr メニューのタイトル @param[in] contents 文字列または gbitmap @param[in] is_gbitmap ; */ void replace_menu_item( char* title, void* contents, bool is_gbitmap ); /*! @brief メニューを追加する @param[in] index メニューの番号 @return[out] inex に対応する、MenuItem構造体 */ MenuItem* get_menu_item( int index ); /*! @brief メニューを追加する @return[out] メニューの総数を返す */ int how_many_menu_item( void ); /*! @brief メニュー使用後の処理を行う。 */ void menu_cleanup( void ); #endif /* menu_item_h */
2.28125
2
2024-11-18T19:35:06.594655+00:00
2016-01-07T19:32:15
ab8001517ed60912300b2935e078e2d51a64c1e1
{ "blob_id": "ab8001517ed60912300b2935e078e2d51a64c1e1", "branch_name": "refs/heads/master", "committer_date": "2016-01-07T19:32:15", "content_id": "b5ff1fd1955d801fd61ffa9764fbf47e27a86212", "detected_licenses": [ "Apache-2.0" ], "directory_id": "11a10df72bce8dc1a9c6ef9930d1702dec0f2547", "extension": "c", "filename": "parse.c", "fork_events_count": 0, "gha_created_at": "2016-01-09T07:28:36", "gha_event_created_at": "2016-01-09T07:28:36", "gha_language": null, "gha_license_id": null, "github_id": 49315253, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 48237, "license": "Apache-2.0", "license_type": "permissive", "path": "/Platform/Apple/tools/PLASMA/src/parse.c", "provenance": "stackv2-0054.json.gz:8060", "repo_name": "Michaelangel007/lawless-legends", "revision_date": "2016-01-07T19:32:15", "revision_id": "db1e6c3a6c21d69a0c8d27333d491833508beaa9", "snapshot_id": "1be9e0fd5becf1337123b50efc8616825d4feb91", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Michaelangel007/lawless-legends/db1e6c3a6c21d69a0c8d27333d491833508beaa9/Platform/Apple/tools/PLASMA/src/parse.c", "visit_date": "2021-01-22T16:25:20.018444" }
stackv2
/* * Copyright (C) 2015 The 8-Bit Bunch. Licensed under the Apache License, Version 1.1 * (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-1.1>. * 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 <stdio.h> #include "tokens.h" #include "symbols.h" #include "lex.h" #include "codegen.h" #include "parse.h" int infunc = 0, break_tag = 0, cont_tag = 0, stack_loop = 0; t_token prevstmnt; t_token binary_ops_table[] = { /* Highest precedence */ MUL_TOKEN, DIV_TOKEN, MOD_TOKEN, ADD_TOKEN, SUB_TOKEN, SHR_TOKEN, SHL_TOKEN, AND_TOKEN, EOR_TOKEN, OR_TOKEN, GT_TOKEN, GE_TOKEN, LT_TOKEN, LE_TOKEN, EQ_TOKEN, NE_TOKEN, LOGIC_AND_TOKEN, LOGIC_OR_TOKEN /* Lowest precedence */ }; t_token binary_ops_precedence[] = { /* Highest precedence */ 1, 1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 7, 7, 7, 8, 8, 9, 10 /* Lowest precedence */ }; t_token opstack[16]; int precstack[16]; int opsptr = -1; void push_op(t_token op, int prec) { if (++opsptr == 16) { parse_error("Stack overflow\n"); return; } opstack[opsptr] = op; precstack[opsptr] = prec; } t_token pop_op(void) { if (opsptr < 0) { parse_error("Stack underflow\n"); return (0); } return opstack[opsptr--]; } t_token tos_op(void) { return opsptr < 0 ? 0 : opstack[opsptr]; } int tos_op_prec(int tos) { return opsptr <= tos ? 100 : precstack[opsptr]; } long valstack[16]; int typestack[16]; int sizestack[16]; int valptr = -1; void push_val(long value, int size, int type) { if (++valptr == 16) { parse_error("Stack overflow\n"); return; } valstack[valptr] = value; sizestack[valptr] = size; typestack[valptr] = type; } int pop_val(long *value, int *size, int *type) { if (valptr < 0) { parse_error("Stack underflow\n"); return (-1); } *value = valstack[valptr]; *size = sizestack[valptr]; *type = typestack[valptr]; return valptr--; } /* * Constant expression parsing */ int calc_op(t_token op) { long val1, val2; int size1, size2, type1, type2; if (!pop_val(&val2, &size2, &type2)) return 0; pop_val(&val1, &size1, &type1); if (type1 != CONST_TYPE || type2 != CONST_TYPE) { parse_error("Bad constant operand"); return (0); } switch (op) { case MUL_TOKEN: val1 *= val2; break; case DIV_TOKEN: val1 /= val2; break; case MOD_TOKEN: val1 %= val2; break; case ADD_TOKEN: val1 += val2; break; case SUB_TOKEN: val1 -= val2; break; case SHL_TOKEN: val1 <<= val2; break; case SHR_TOKEN: val1 >>= val2; break; case AND_TOKEN: val1 &= val2; break; case OR_TOKEN: val1 |= val2; break; case EOR_TOKEN: val1 ^= val2; break; default: return (0); } size1 = size1 > size2 ? size1 : size2; push_val(val1, size1, type1); return (1); } int parse_constexpr(long *value, int *size); int parse_constterm(long *value, int *size) { int type; /* * Parse terminal tokens. */ switch (type = scan()) { case CHAR_TOKEN: case INT_TOKEN: case ID_TOKEN: case STRING_TOKEN: break; case OPEN_PAREN_TOKEN: if (!(type = parse_constexpr(value, size))) { parse_error("Bad expression in parenthesis"); return (0); } if (scantoken != CLOSE_PAREN_TOKEN) { parse_error("Missing closing parenthesis"); return (0); } break; default: /* * Non-terminal token. */ return (0); } return (type); } int parse_constval(void) { int mod = 0, type, size; long value; value = 0; size = 1; while (!(type = parse_constterm(&value, &size))) { switch (scantoken) { case ADD_TOKEN: /* * Just ignore unary plus, it is a no-op. */ break; case NEG_TOKEN: mod |= 1; break; case COMP_TOKEN: mod |= 2; break; case LOGIC_NOT_TOKEN: mod |= 4; break; case AT_TOKEN: mod |= 8; break; default: return (0); } } /* * Determine which terminal type. */ switch (scantoken) { case CLOSE_PAREN_TOKEN: break; case STRING_TOKEN: size = tokenlen - 1; value = constval; type = STRING_TYPE; if (mod) { parse_error("Invalid string modifiers"); return (0); } break; case CHAR_TOKEN: size = 1; value = constval; type = CONST_TYPE; break; case INT_TOKEN: size = 2; value = constval; type = CONST_TYPE; break; case ID_TOKEN: size = 2; type = id_type(tokenstr, tokenlen); if (type & CONST_TYPE) value = id_const(tokenstr, tokenlen); else if ((type & (FUNC_TYPE | EXTERN_TYPE)) || ((type & ADDR_TYPE) && (mod == 8))) value = id_tag(tokenstr, tokenlen); else return (0); break; default: return (0); } if (mod & 1) value = -value; if (mod & 2) value = ~value; if (mod & 4) value = value ? 0 : -1; push_val(value, size, type); return (type); } int parse_constexpr(long *value, int *size) { int prevmatch; int matchop = 0; int optos = opsptr; int i; int type = CONST_TYPE; *value = 0; *size = 1; do { /* * Parse sequence of double operand operations. */ prevmatch = matchop; matchop = 0; if (parse_constval()) { matchop = 1; scan(); for (i = 0; i < sizeof(binary_ops_table); i++) if (scantoken == binary_ops_table[i]) { matchop = 2; if (binary_ops_precedence[i] >= tos_op_prec(optos)) if (!calc_op(pop_op())) { parse_error(": Invalid binary operation"); return (0); } push_op(scantoken, binary_ops_precedence[i]); break; } } } while (matchop == 2); if (matchop == 0 && prevmatch == 0) return (0); if (matchop == 0 && prevmatch == 2) { parse_error("Missing operand"); return (0); } while (optos < opsptr) if (!calc_op(pop_op())) { parse_error(": Invalid binary operation"); return (0); } pop_val(value, size, &type); return (type); } int parse_const(long *value) { /* * Get simple constant. */ switch (scan()) { case CHAR_TOKEN: case INT_TOKEN: *value = constval; break; case ID_TOKEN: if (id_type(tokenstr, tokenlen) & CONST_TYPE) { *value = id_const(tokenstr, tokenlen); break; } default: *value = 0; return (0); } return (CONST_TYPE); } /* * Normal expression parsing */ int parse_expr(void); int parse_term(void) { /* * Parse terminal tokens. */ switch (scan()) { case CHAR_TOKEN: case INT_TOKEN: case ID_TOKEN: case STRING_TOKEN: break; case OPEN_PAREN_TOKEN: if (!parse_expr()) { parse_error("Bad expression in parenthesis"); return (0); } if (scantoken != CLOSE_PAREN_TOKEN) { parse_error("Missing closing parenthesis"); return (0); } break; default: /* * Non-terminal token. */ return (0); } return (1); } int parse_value(int rvalue) { int cparams; int deref = rvalue; int optos = opsptr; int type = 0, value = 0, emit_value = 0; int ref_type, const_size; long ref_offset, const_offset; /* * Parse pre operand operators. */ while (!parse_term()) { switch (scantoken) { case ADD_TOKEN: /* * Just ignore unary plus, it is a no-op. */ break; case BPTR_TOKEN: if (deref) push_op(scantoken, 0); else { deref++; type |= BPTR_TYPE; } break; case WPTR_TOKEN: if (deref) push_op(scantoken, 0); else { deref++; type |= WPTR_TYPE; } break; case AT_TOKEN: deref--; break; case NEG_TOKEN: case COMP_TOKEN: case LOGIC_NOT_TOKEN: push_op(scantoken, 0); break; default: return (0); } } /* * Determine which terminal type. */ if (scantoken == INT_TOKEN || scantoken == CHAR_TOKEN) { value = constval; type |= CONST_TYPE; } else if (scantoken == ID_TOKEN) { if ((type |= id_type(tokenstr, tokenlen)) & CONST_TYPE) value = id_const(tokenstr, tokenlen); else if (type & VAR_TYPE) value = id_tag(tokenstr, tokenlen); else if (type & FUNC_TYPE) value = id_tag(tokenstr, tokenlen); else { printf("Bad ID type\n"); return (0); } } else if (scantoken == CLOSE_PAREN_TOKEN) { // type |= WORD_TYPE; emit_value = 1; } else if (scantoken == STRING_TOKEN) { /* * This is a special case. Just emit the string and return */ emit_conststr(constval, tokenlen - 1); scan(); return WORD_TYPE; } else return (0); if (type & CONST_TYPE) { /* * Quick optimizations */ while ((optos < opsptr) && ((tos_op() == NEG_TOKEN) || (tos_op() == COMP_TOKEN) || (tos_op() == LOGIC_NOT_TOKEN))) { switch (pop_op()) { case NEG_TOKEN: value = -value; break; case COMP_TOKEN: value = ~value; break; case LOGIC_NOT_TOKEN: value = value ? 0 : -1; break; } } } /* * Parse post operand operators. */ ref_type = type & ~PTR_TYPE; ref_offset = 0; while (scan() == OPEN_PAREN_TOKEN || scantoken == OPEN_BRACKET_TOKEN || scantoken == PTRB_TOKEN || scantoken == PTRW_TOKEN || scantoken == DOT_TOKEN || scantoken == COLON_TOKEN) { switch (scantoken) { case OPEN_PAREN_TOKEN: /* * Function call */ if (emit_value) { if (ref_offset != 0) { emit_const(ref_offset); emit_op(ADD_TOKEN); ref_offset = 0; } if (ref_type & PTR_TYPE) (ref_type & BPTR_TYPE) ? emit_lb() : emit_lw(); if (scan_lookahead() != CLOSE_PAREN_TOKEN) emit_push(); } cparams = 0; while (parse_expr()) { cparams++; if (scantoken != COMMA_TOKEN) break; } if (scantoken != CLOSE_PAREN_TOKEN) { parse_error("Missing closing parenthesis"); return (0); } if (ref_type & (FUNC_TYPE | CONST_TYPE)) emit_call(value, ref_type); else { if (!emit_value) { if (type & CONST_TYPE) emit_const(value); else if (type & VAR_TYPE) { if (type & LOCAL_TYPE) emit_llw(value + ref_offset); else emit_law(value, ref_offset, type); ref_offset = 0; } } else if (cparams) emit_pull(); emit_ical(); } emit_value = 1; ref_type = 0; break; case OPEN_BRACKET_TOKEN: /* * Array of arrays */ if (!emit_value) { if (type & CONST_TYPE) emit_const(value); else if (type & ADDR_TYPE) { if (type & LOCAL_TYPE) emit_localaddr(value + ref_offset); else emit_globaladdr(value, ref_offset, type); ref_offset = 0; } else { parse_error("Bad index reference"); return (0); } emit_value = 1; } else { if (ref_offset != 0) { emit_const(ref_offset); emit_op(ADD_TOKEN); ref_offset = 0; } } while (parse_expr()) { if (scantoken != COMMA_TOKEN) break; emit_indexword(); emit_lw(); } if (scantoken != CLOSE_BRACKET_TOKEN) { parse_error("Missing closing bracket"); return (0); } if (ref_type & (WPTR_TYPE | WORD_TYPE)) { emit_indexword(); ref_type = WPTR_TYPE; } else { emit_indexbyte(); ref_type = BPTR_TYPE; } break; case PTRB_TOKEN: case PTRW_TOKEN: /* * Structure member pointer */ if (!emit_value) { if (type & CONST_TYPE) emit_const(value); else if (type & ADDR_TYPE) { if (type & LOCAL_TYPE) (ref_type & BYTE_TYPE) ? emit_llb(value + ref_offset) : emit_llw(value + ref_offset); else (ref_type & BYTE_TYPE) ? emit_lab(value, ref_offset, type) : emit_law(value, ref_offset, type); } emit_value = 1; } else { if (ref_offset != 0) { emit_const(ref_offset); emit_op(ADD_TOKEN); } if (ref_type & PTR_TYPE) (ref_type & BPTR_TYPE) ? emit_lb() : emit_lw(); } ref_offset = 0; ref_type = (scantoken == PTRB_TOKEN) ? BPTR_TYPE : WPTR_TYPE; if (!parse_const(&ref_offset)) scan_rewind(tokenstr); break; case DOT_TOKEN: case COLON_TOKEN: /* * Structure member offset */ ref_type = (ref_type & (VAR_TYPE | CONST_TYPE)) ? ((scantoken == DOT_TOKEN) ? BYTE_TYPE : WORD_TYPE) : ((scantoken == DOT_TOKEN) ? BPTR_TYPE : WPTR_TYPE); if (parse_const(&const_offset)) ref_offset += const_offset; else scan_rewind(tokenstr); if (!emit_value) { if (type & CONST_TYPE) { value += ref_offset; ref_offset = 0; } else if (type & FUNC_TYPE) { emit_globaladdr(value, ref_offset, type); ref_offset = 0; emit_value = 1; } } break; } } if (emit_value) { if (ref_offset != 0) { emit_const(ref_offset); emit_op(ADD_TOKEN); ref_offset = 0; } if (deref) { if (ref_type & BPTR_TYPE) emit_lb(); else if (ref_type & WPTR_TYPE) emit_lw(); } } else { if (deref) { if (type & CONST_TYPE) { emit_const(value); if (ref_type & VAR_TYPE) (ref_type & BYTE_TYPE) ? emit_lb() : emit_lw(); } else if (type & FUNC_TYPE) emit_call(value, ref_type); else if (type & VAR_TYPE) { if (type & LOCAL_TYPE) (ref_type & BYTE_TYPE) ? emit_llb(value + ref_offset) : emit_llw(value + ref_offset); else (ref_type & BYTE_TYPE) ? emit_lab(value, ref_offset, ref_type) : emit_law(value, ref_offset, ref_type); } } else { if (type & CONST_TYPE) emit_const(value); else if (type & ADDR_TYPE) { if (type & LOCAL_TYPE) emit_localaddr(value + ref_offset); else emit_globaladdr(value, ref_offset, ref_type); } } } while (optos < opsptr) { if (!emit_unaryop(pop_op())) { parse_error(": Invalid unary operation"); return (0); } } if (type & PTR_TYPE) ref_type = type; return (ref_type ? ref_type : WORD_TYPE); } int parse_expr() { int prevmatch; int matchop = 0; int optos = opsptr; int i; int prevtype, type = 0; do { /* * Parse sequence of double operand operations. */ prevmatch = matchop; matchop = 0; if (parse_value(1)) { matchop = 1; for (i = 0; i < sizeof(binary_ops_table); i++) if (scantoken == binary_ops_table[i]) { matchop = 2; if (binary_ops_precedence[i] >= tos_op_prec(optos)) if (!emit_op(pop_op())) { parse_error(": Invalid binary operation"); return (0); } push_op(scantoken, binary_ops_precedence[i]); break; } } } while (matchop == 2); if (matchop == 0 && prevmatch == 2) { parse_error("Missing operand"); return (0); } while (optos < opsptr) if (!emit_op(pop_op())) { parse_error(": Invalid binary operation"); return (0); } return (matchop || prevmatch); } int parse_stmnt(void) { int tag_prevbrk, tag_prevcnt, tag_else, tag_endif, tag_while, tag_wend, tag_repeat, tag_for, tag_choice, tag_of; int type, addr, step; char *idptr; /* * Optimization for last function LEAVE and OF clause. */ if (scantoken != END_TOKEN && scantoken != DONE_TOKEN && scantoken != OF_TOKEN && scantoken != DEFAULT_TOKEN) prevstmnt = scantoken; switch (scantoken) { case IF_TOKEN: if (!parse_expr()) { parse_error("Bad expression"); return (0); } tag_else = tag_new(BRANCH_TYPE); tag_endif = tag_new(BRANCH_TYPE); emit_brfls(tag_else); scan(); do { while (parse_stmnt()) next_line(); if (scantoken != ELSEIF_TOKEN) break; emit_brnch(tag_endif); emit_codetag(tag_else); if (!parse_expr()) { parse_error("Bad expression"); return (0); } tag_else = tag_new(BRANCH_TYPE); emit_brfls(tag_else); } while (1); if (scantoken == ELSE_TOKEN) { emit_brnch(tag_endif); emit_codetag(tag_else); scan(); while (parse_stmnt()) next_line(); emit_codetag(tag_endif); } else { emit_codetag(tag_else); emit_codetag(tag_endif); } if (scantoken != FIN_TOKEN) { parse_error("Missing IF/FIN"); return (0); } break; case WHILE_TOKEN: tag_while = tag_new(BRANCH_TYPE); tag_wend = tag_new(BRANCH_TYPE); tag_prevcnt = cont_tag; cont_tag = tag_while; tag_prevbrk = break_tag; break_tag = tag_wend; emit_codetag(tag_while); if (!parse_expr()) { parse_error("Bad expression"); return (0); } emit_brfls(tag_wend); while (parse_stmnt()) next_line(); if (scantoken != LOOP_TOKEN) { parse_error("Missing WHILE/END"); return (0); } emit_brnch(tag_while); emit_codetag(tag_wend); break_tag = tag_prevbrk; cont_tag = tag_prevcnt; break; case REPEAT_TOKEN: tag_prevbrk = break_tag; break_tag = tag_new(BRANCH_TYPE); tag_repeat = tag_new(BRANCH_TYPE); tag_prevcnt = cont_tag; cont_tag = tag_new(BRANCH_TYPE); emit_codetag(tag_repeat); scan(); while (parse_stmnt()) next_line(); if (scantoken != UNTIL_TOKEN) { parse_error("Missing REPEAT/UNTIL"); return (0); } emit_codetag(cont_tag); cont_tag = tag_prevcnt; if (!parse_expr()) { parse_error("Bad expression"); return (0); } emit_brfls(tag_repeat); emit_codetag(break_tag); break_tag = tag_prevbrk; break; case FOR_TOKEN: stack_loop++; tag_prevbrk = break_tag; break_tag = tag_new(BRANCH_TYPE); tag_for = tag_new(BRANCH_TYPE); tag_prevcnt = cont_tag; cont_tag = tag_for; if (scan() != ID_TOKEN) { parse_error("Missing FOR variable"); return (0); } type = id_type(tokenstr, tokenlen); addr = id_tag(tokenstr, tokenlen); if (scan() != SET_TOKEN) { parse_error("Missing FOR ="); return (0); } if (!parse_expr()) { parse_error("Bad FOR expression"); return (0); } emit_codetag(tag_for); if (type & LOCAL_TYPE) type & BYTE_TYPE ? emit_dlb(addr) : emit_dlw(addr); else type & BYTE_TYPE ? emit_dab(addr, type) : emit_daw(addr, type); if (scantoken == TO_TOKEN) step = 1; else if (scantoken == DOWNTO_TOKEN) step = -1; else { parse_error("Missing FOR TO"); return (0); } if (!parse_expr()) { parse_error("Bad FOR TO expression"); return (0); } step > 0 ? emit_brgt(break_tag) : emit_brlt(break_tag); if (scantoken == STEP_TOKEN) { if (!parse_expr()) { parse_error("Bad FOR STEP expression"); return (0); } emit_op(step > 0 ? ADD_TOKEN : SUB_TOKEN); } else emit_unaryop(step > 0 ? INC_TOKEN : DEC_TOKEN); while (parse_stmnt()) next_line(); if (scantoken != NEXT_TOKEN) { parse_error("Missing FOR/NEXT "); return (0); } emit_brnch(tag_for); cont_tag = tag_prevcnt; emit_codetag(break_tag); emit_drop(); break_tag = tag_prevbrk; stack_loop--; break; case CASE_TOKEN: stack_loop++; tag_prevbrk = break_tag; break_tag = tag_new(BRANCH_TYPE); tag_choice = tag_new(BRANCH_TYPE); tag_of = tag_new(BRANCH_TYPE); if (!parse_expr()) { parse_error("Bad CASE expression"); return (0); } next_line(); while (scantoken != ENDCASE_TOKEN) { if (scantoken == OF_TOKEN) { if (!parse_expr()) { parse_error("Bad CASE OF expression"); return (0); } emit_brne(tag_choice); emit_codetag(tag_of); while (parse_stmnt()) next_line(); tag_of = tag_new(BRANCH_TYPE); if (prevstmnt != BREAK_TOKEN) // Fall through to next OF if no break emit_brnch(tag_of); emit_codetag(tag_choice); tag_choice = tag_new(BRANCH_TYPE); } else if (scantoken == DEFAULT_TOKEN) { emit_codetag(tag_of); tag_of = 0; scan(); while (parse_stmnt()) next_line(); if (scantoken != ENDCASE_TOKEN) { parse_error("Bad CASE DEFAULT clause"); return (0); } } else if (scantoken == EOL_TOKEN) { next_line(); } else { parse_error("Bad CASE clause"); return (0); } } if (tag_of) emit_codetag(tag_of); emit_codetag(break_tag); emit_drop(); break_tag = tag_prevbrk; stack_loop--; break; case CONTINUE_TOKEN: if (cont_tag) emit_brnch(cont_tag); else { parse_error("CONTINUE without loop"); return (0); } break; case BREAK_TOKEN: if (break_tag) emit_brnch(break_tag); else { parse_error("BREAK without loop"); return (0); } break; case RETURN_TOKEN: if (infunc) { int i; for (i = 0; i < stack_loop; i++) emit_drop(); if (!parse_expr()) emit_const(0); emit_leave(); } else { if (!parse_expr()) emit_const(0); emit_ret(); } break; case EOL_TOKEN: case COMMENT_TOKEN: return (1); case ELSE_TOKEN: case ELSEIF_TOKEN: case FIN_TOKEN: case LOOP_TOKEN: case UNTIL_TOKEN: case NEXT_TOKEN: case OF_TOKEN: case DEFAULT_TOKEN: case ENDCASE_TOKEN: case END_TOKEN: case DONE_TOKEN: case DEF_TOKEN: return (0); case ID_TOKEN: idptr = tokenstr; type = id_type(tokenstr, tokenlen); addr = id_tag(tokenstr, tokenlen); if (type & VAR_TYPE) { int elem_type = type; long elem_offset = 0; if (scan() == DOT_TOKEN || scantoken == COLON_TOKEN) { /* * Structure member offset */ int elem_size; elem_type = (scantoken == DOT_TOKEN) ? BYTE_TYPE : WORD_TYPE; if (!parse_const(&elem_offset)) scantoken = ID_TOKEN; else scan(); } if (scantoken == SET_TOKEN) { if (!parse_expr()) { parse_error("Bad expression"); return (0); } if (type & LOCAL_TYPE) (elem_type & BYTE_TYPE) ? emit_slb(addr + elem_offset) : emit_slw(addr + elem_offset); else (elem_type & BYTE_TYPE) ? emit_sab(addr, elem_offset, type) : emit_saw(addr, elem_offset, type); break; } else if (scantoken == INC_TOKEN || scantoken == DEC_TOKEN) { if (type & LOCAL_TYPE) { if (elem_type & BYTE_TYPE) { emit_llb(addr + elem_offset); emit_unaryop(scantoken); emit_slb(addr + elem_offset); } else { emit_llw(addr + elem_offset); emit_unaryop(scantoken); emit_slw(addr + elem_offset); } } else { if (elem_type & BYTE_TYPE) { emit_lab(addr, elem_offset, type); emit_unaryop(scantoken); emit_sab(addr, elem_offset, type); } else { emit_law(addr, elem_offset, type); emit_unaryop(scantoken); emit_saw(addr, elem_offset, type); } } break; } } else if (type & FUNC_TYPE) { if (scan() == EOL_TOKEN) { emit_call(addr, type); emit_drop(); break; } } tokenstr = idptr; default: scan_rewind(tokenstr); if ((type = parse_value(0)) != 0) { if (scantoken == SET_TOKEN) { if (!parse_expr()) { parse_error("Bad expression"); return (0); } if (type & LOCAL_TYPE) (type & (BYTE_TYPE | BPTR_TYPE)) ? emit_sb() : emit_sw(); else (type & (BYTE_TYPE | BPTR_TYPE)) ? emit_sb() : emit_sw(); } else if (scantoken == INC_TOKEN || scantoken == DEC_TOKEN) { if (type & (BYTE_TYPE | BPTR_TYPE)) { emit_dup(); emit_lb(); emit_unaryop(scantoken); emit_sb(); } else { emit_dup(); emit_lw(); emit_unaryop(scantoken); emit_sw(); } } else { if (type & BPTR_TYPE) emit_lb(); else if (type & WPTR_TYPE) emit_lw(); emit_drop(); } } else { parse_error("Syntax error"); return (0); } } if (scan() != EOL_TOKEN && scantoken != COMMENT_TOKEN) { parse_error("Extraneous characters"); return (0); } return (1); } int parse_var(int type) { char *idstr; long constval; int consttype, constsize, arraysize, idlen = 0; long size = 1; if (scan() == OPEN_BRACKET_TOKEN) { size = 0; parse_constexpr(&size, &constsize); if (scantoken != CLOSE_BRACKET_TOKEN) { parse_error("Missing closing bracket"); return (0); } scan(); } if (scantoken == ID_TOKEN) { idstr = tokenstr; idlen = tokenlen; if (scan() == OPEN_BRACKET_TOKEN) { size = 0; parse_constexpr(&size, &constsize); if (scantoken != CLOSE_BRACKET_TOKEN) { parse_error("Missing closing bracket"); return (0); } scan(); } } if (type & WORD_TYPE) size *= 2; if (scantoken == SET_TOKEN) { if (type & (EXTERN_TYPE | LOCAL_TYPE)) { parse_error("Cannot initiallize local/external variables"); return (0); } if (idlen) idglobal_add(idstr, idlen, type, 0); if ((consttype = parse_constexpr(&constval, &constsize))) { /* * Variable initialization. */ arraysize = emit_data(type, consttype, constval, constsize); while (scantoken == COMMA_TOKEN) { if ((consttype = parse_constexpr(&constval, &constsize))) arraysize += emit_data(type, consttype, constval, constsize); else { parse_error("Bad array declaration"); return (0); } } if (size > arraysize) idglobal_size(PTR_TYPE, size, arraysize); } else { parse_error("Bad variable initializer"); return (0); } } else if (idlen) id_add(idstr, idlen, type, size); return (1); } int parse_struc(void) { long size; int type, constsize, offset = 0; char *idstr, strucid[80]; int idlen = 0, struclen = 0; if (scan() == ID_TOKEN) { struclen = tokenlen; for (idlen = 0; idlen < struclen; idlen++) strucid[idlen] = tokenstr[idlen]; } while (next_line() == BYTE_TOKEN || scantoken == WORD_TOKEN || scantoken == EOL_TOKEN) { if (scantoken == EOL_TOKEN) continue; size = 1; type = scantoken == BYTE_TOKEN ? BYTE_TYPE : WORD_TYPE; if (scan() == OPEN_BRACKET_TOKEN) { size = 0; parse_constexpr(&size, &constsize); if (scantoken != CLOSE_BRACKET_TOKEN) { parse_error("Missing closing bracket"); return (0); } scan(); } do { idlen = 0; if (scantoken == ID_TOKEN) { idstr = tokenstr; idlen = tokenlen; if (scan() == OPEN_BRACKET_TOKEN) { size = 0; parse_constexpr(&size, &constsize); if (scantoken != CLOSE_BRACKET_TOKEN) { parse_error("Missing closing bracket"); return (0); } scan(); } } if (type & WORD_TYPE) size *= 2; if (idlen) idconst_add(idstr, idlen, offset); offset += size; } while (scantoken == COMMA_TOKEN); if (scantoken != EOL_TOKEN && scantoken != COMMENT_TOKEN) return (0); } if (struclen) idconst_add(strucid, struclen, offset); return (scantoken == END_TOKEN); } int parse_vars(int type) { long value; int idlen, size; char *idstr; switch (scantoken) { case SYSFLAGS_TOKEN: if (type & (EXTERN_TYPE | LOCAL_TYPE)) { parse_error("sysflags must be global"); return (0); } if (!parse_constexpr(&value, &size)) { parse_error("Bad constant"); return (0); } emit_sysflags(value); break; case CONST_TOKEN: if (scan() != ID_TOKEN) { parse_error("Missing variable"); return (0); } idstr = tokenstr; idlen = tokenlen; if (scan() != SET_TOKEN) { parse_error("Bad LValue"); return (0); } if (!parse_constexpr(&value, &size)) { parse_error("Bad constant"); return (0); } idconst_add(idstr, idlen, value); break; case STRUC_TOKEN: if (!parse_struc()) { parse_error("Bad structure definition"); return (0); } break; case EXPORT_TOKEN: if (type & (EXTERN_TYPE | LOCAL_TYPE)) { parse_error("Cannot export local/imported variables"); return (0); } type = EXPORT_TYPE; idstr = tokenstr; if (scan() != BYTE_TOKEN && scantoken != WORD_TOKEN) { /* * This could be an exported definition. */ scan_rewind(idstr); scan(); return (0); } /* * Fall through to BYTE or WORD declaration. */ case BYTE_TOKEN: case WORD_TOKEN: type |= (scantoken == BYTE_TOKEN) ? BYTE_TYPE : WORD_TYPE; if (!parse_var(type)) return (0); while (scantoken == COMMA_TOKEN) { if (!parse_var(type)) return (0); } break; case PREDEF_TOKEN: /* * Pre definition. */ if (scan() == ID_TOKEN) { type |= PREDEF_TYPE; idstr = tokenstr; idlen = tokenlen; idfunc_add(tokenstr, tokenlen, type, tag_new(type)); while (scan() == COMMA_TOKEN) { if (scan() == ID_TOKEN) { idstr = tokenstr; idlen = tokenlen; idfunc_add(tokenstr, tokenlen, type, tag_new(type)); } else { parse_error("Bad function pre-declaration"); return (0); } } } else { parse_error("Bad function pre-declaration"); return (0); } case EOL_TOKEN: case COMMENT_TOKEN: return (1); default: return (0); } return (1); } int parse_mods(void) { if (scantoken == IMPORT_TOKEN) { if (scan() != ID_TOKEN) { parse_error("Bad import definition"); return (0); } emit_moddep(tokenstr, tokenlen); scan(); while (parse_vars(EXTERN_TYPE)) next_line(); if (scantoken != END_TOKEN) { parse_error("Syntax error"); return (0); } if (scan() != EOL_TOKEN && scantoken != COMMENT_TOKEN) { parse_error("Extraneous characters"); return (0); } } if (scantoken == EOL_TOKEN || scantoken == COMMENT_TOKEN) return (1); emit_moddep(0, 0); return (0); } int parse_defs(void) { char c; int func_tag, cfnparms, type = GLOBAL_TYPE; static char bytecode = 0; if (scantoken == EXPORT_TOKEN) { if (scan() != DEF_TOKEN && scantoken != ASM_TOKEN) { parse_error("Bad export definition"); return 0; } type = EXPORT_TYPE; } if (scantoken == DEF_TOKEN) { if (scan() != ID_TOKEN) { parse_error("Missing function name"); return (0); } emit_bytecode_seg(); bytecode = 1; cfnparms = 0; infunc = 1; type |= DEF_TYPE; if (idglobal_lookup(tokenstr, tokenlen) >= 0) { if (!(id_type(tokenstr, tokenlen) & PREDEF_TYPE)) { // TODO: Print symbols parse_error("Mismatch function type"); return (0); } emit_idfunc(id_tag(tokenstr, tokenlen), PREDEF_TYPE, tokenstr); func_tag = tag_new(type); idfunc_set(tokenstr, tokenlen, type, func_tag); // Override any predef type & tag } else { func_tag = tag_new(type); idfunc_add(tokenstr, tokenlen, type, func_tag); } c = tokenstr[tokenlen]; tokenstr[tokenlen] = '\0'; emit_idfunc(func_tag, type, tokenstr); emit_def(tokenstr, 1); tokenstr[tokenlen] = c; if (scan() == OPEN_PAREN_TOKEN) { do { if (scan() == ID_TOKEN) { cfnparms++; idlocal_add(tokenstr, tokenlen, WORD_TYPE, 2); scan(); } } while (scantoken == COMMA_TOKEN); if (scantoken != CLOSE_PAREN_TOKEN) { parse_error("Bad function parameter list"); return (0); } scan(); } while (parse_vars(LOCAL_TYPE)) next_line(); emit_enter(cfnparms); prevstmnt = 0; while (parse_stmnt()) next_line(); infunc = 0; if (scantoken != END_TOKEN) { parse_error("Syntax error"); return (0); } if (scan() != EOL_TOKEN && scantoken != COMMENT_TOKEN) { parse_error("Extraneous characters"); return (0); } if (prevstmnt != RETURN_TOKEN) { emit_const(0); emit_leave(); } return (1); } else if (scantoken == ASM_TOKEN) { if (scan() != ID_TOKEN) { parse_error("Missing function name"); return (0); } if (bytecode) { parse_error("ASM code only allowed before DEF code"); return (0); } cfnparms = 0; infunc = 1; type |= ASM_TYPE; if (idglobal_lookup(tokenstr, tokenlen) >= 0) { if (!(id_type(tokenstr, tokenlen) & PREDEF_TYPE)) { parse_error("Mismatch function type"); return (0); } emit_idfunc(id_tag(tokenstr, tokenlen), PREDEF_TYPE, tokenstr); func_tag = tag_new(type); idfunc_set(tokenstr, tokenlen, type, func_tag); // Override any predef type & tag } else { func_tag = tag_new(type); idfunc_add(tokenstr, tokenlen, type, func_tag); } c = tokenstr[tokenlen]; tokenstr[tokenlen] = '\0'; emit_idfunc(func_tag, type, tokenstr); emit_def(tokenstr, 0); tokenstr[tokenlen] = c; if (scan() == OPEN_PAREN_TOKEN) { do { if (scan() == ID_TOKEN) { cfnparms++; idlocal_add(tokenstr, tokenlen, WORD_TYPE, 2); scan(); } } while (scantoken == COMMA_TOKEN); if (scantoken != CLOSE_PAREN_TOKEN) { parse_error("Bad function parameter list"); return (0); } scan(); } do { if (scantoken == EOL_TOKEN || scantoken == COMMENT_TOKEN) next_line(); else if (scantoken != END_TOKEN) { emit_asm(inputline); next_line(); } } while (scantoken != END_TOKEN); return (1); } if (scantoken == EOL_TOKEN || scantoken == COMMENT_TOKEN) return (1); return (0); } int parse_module(void) { emit_header(); if (next_line()) { while (parse_mods()) next_line(); while (parse_vars(GLOBAL_TYPE)) next_line(); while (parse_defs()) next_line(); if (scantoken != DONE_TOKEN && scantoken != EOF_TOKEN) { emit_bytecode_seg(); emit_start(); emit_def("_INIT", 1); prevstmnt = 0; while (parse_stmnt()) next_line(); if (scantoken != DONE_TOKEN) parse_error("Missing DONE statement"); if (prevstmnt != RETURN_TOKEN) { emit_const(0); emit_ret(); } } } emit_trailer(); return (0); }
2.421875
2
2024-11-18T19:35:06.677101+00:00
2023-07-30T07:00:50
c624daff4d686d92a685bf7b2d2dda52964dd302
{ "blob_id": "c624daff4d686d92a685bf7b2d2dda52964dd302", "branch_name": "refs/heads/master", "committer_date": "2023-07-30T07:00:50", "content_id": "fac96f61484bf060f5a0c3e15354908569d6dde8", "detected_licenses": [ "MIT" ], "directory_id": "db04ecf258aef8a187823b8e47f4a1ae908e5897", "extension": "c", "filename": "AddingTwoNegabinaryNumbers.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 74735489, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 859, "license": "MIT", "license_type": "permissive", "path": "/C/AddingTwoNegabinaryNumbers.c", "provenance": "stackv2-0054.json.gz:8188", "repo_name": "JumHorn/leetcode", "revision_date": "2023-07-30T07:00:50", "revision_id": "abf145686dcfac860b0f6b26a04e3edd133b238c", "snapshot_id": "9612a26e531ceae7f25e2a749600632da6882075", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/JumHorn/leetcode/abf145686dcfac860b0f6b26a04e3edd133b238c/C/AddingTwoNegabinaryNumbers.c", "visit_date": "2023-08-03T21:12:13.945602" }
stackv2
#include <stdlib.h> #include <string.h> #define max(a, b) (((a) > (b)) ? (a) : (b)) void reverse(int *arr, int first, int last) { for (; first < last; ++first, --last) { int tmp = arr[first]; arr[first] = arr[last]; arr[last] = tmp; } } /** * Note: The returned array must be malloced, assume caller calls free(). */ int *addNegabinary(int *arr1, int arr1Size, int *arr2, int arr2Size, int *returnSize) { int *res = (int *)malloc(sizeof(int) * (max(arr1Size, arr2Size) + 2)); *returnSize = 0; int carry = 0, i = arr1Size - 1, j = arr2Size - 1; while (i >= 0 || j >= 0 || carry) { if (i >= 0) carry += arr1[i--]; if (j >= 0) carry += arr2[j--]; res[(*returnSize)++] = (carry & 1); carry = -(carry >> 1); } while (*returnSize > 1 && res[*returnSize - 1] == 0) --*returnSize; reverse(res, 0, *returnSize - 1); return res; }
3.34375
3
2024-11-18T19:35:06.758448+00:00
2021-02-04T11:32:18
e79dc36a43b6d70510093d80dcb1559664fc1ce9
{ "blob_id": "e79dc36a43b6d70510093d80dcb1559664fc1ce9", "branch_name": "refs/heads/main", "committer_date": "2021-02-04T11:32:18", "content_id": "0a1e60ab550cf58b57a5d2ffc7da56ce8773b346", "detected_licenses": [ "MIT" ], "directory_id": "217b97533a49a425ccfde413e80c7806003425fa", "extension": "c", "filename": "FileRead.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 332183725, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 205, "license": "MIT", "license_type": "permissive", "path": "/FileRead.c", "provenance": "stackv2-0054.json.gz:8317", "repo_name": "Meghraj08/LearnC", "revision_date": "2021-02-04T11:32:18", "revision_id": "23244952a5256cc993d97f304caf7527d8b30e22", "snapshot_id": "603402cdd2e0c1847bbb1a6bea554065073f8afc", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Meghraj08/LearnC/23244952a5256cc993d97f304caf7527d8b30e22/FileRead.c", "visit_date": "2023-02-27T01:12:54.299939" }
stackv2
#include<stdio.h> #include<string.h> void main() { char c; FILE *fp; fp=fopen("Array.c","r"); while((c=fgetc(fp)) != EOF) { printf("%c",c); } fclose(fp); }
2.265625
2
2024-11-18T19:35:07.287025+00:00
2020-03-25T14:54:10
0a6187e2e36283c8ae94f33145f267e15c77ab4b
{ "blob_id": "0a6187e2e36283c8ae94f33145f267e15c77ab4b", "branch_name": "refs/heads/master", "committer_date": "2021-06-28T04:46:03", "content_id": "47c49a734c4834134303af9a14366f4644c1edae", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "d51198a1cecf4f7db0bb36f7e18946e9aaca33f0", "extension": "c", "filename": "iMX8IoMux.c", "fork_events_count": 0, "gha_created_at": "2019-12-08T17:40:07", "gha_event_created_at": "2020-04-15T20:53:23", "gha_language": "C", "gha_license_id": null, "github_id": 226706431, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4243, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/mu_platform_nxp/Silicon/ARM/NXP/iMX8Pkg/Library/iMX8IoMuxLib/iMX8IoMux.c", "provenance": "stackv2-0054.json.gz:8701", "repo_name": "nlshipp/WinIoT-Coral", "revision_date": "2020-03-25T14:54:10", "revision_id": "015e0bc3384feddc8f85e78412d478549e65e64c", "snapshot_id": "96b2f05865fdf2d43ea2dfe7bf932bda8f8fb123", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nlshipp/WinIoT-Coral/015e0bc3384feddc8f85e78412d478549e65e64c/mu_platform_nxp/Silicon/ARM/NXP/iMX8Pkg/Library/iMX8IoMuxLib/iMX8IoMux.c", "visit_date": "2022-10-15T16:08:43.588577" }
stackv2
/** @file * * Copyright (c) Microsoft Corporation. All rights reserved. * * This program and the accompanying materials * are licensed and made available under the terms and conditions of the BSD License * which accompanies this distribution. The full text of the license may be found at * http://opensource.org/licenses/bsd-license.php * * THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, * WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. * **/ #include <PiDxe.h> #include <Library/IoLib.h> #include <Library/DebugLib.h> #include <iMX8.h> #if defined(CPU_IMX8MM) #include <iMX8MMiniIoMux.h> #else #include <iMX8MIoMux.h> #endif // // Muxing functions // VOID ImxPadConfig ( IMX_PAD Pad, IMX_PADCFG PadConfig ) { _Static_assert( (IOMUXC_SELECT_INPUT_UPPER_BOUND - IOMUXC_SELECT_INPUT_BASE_ADDRESS) < (0xff * 4), "Too many SELECT_INPUT registers values to encode in IMX_PADCFG"); // // Configure Mux Control // MmioWrite32 ( IOMUXC_SW_MUX_PAD_BASE_ADDRESS + IMX_IOMUX_PAD_MUX_OFFSET(Pad), _IMX_PADCFG_MUX_CTL(PadConfig)); // // Configure Select Input Control // if (_IMX_PADCFG_SEL_INP(PadConfig) != 0) { DEBUG ((DEBUG_INFO, "Setting INPUT_SELECT %x value %x\n", _IMX_SEL_INP_REGISTER(_IMX_PADCFG_SEL_INP(PadConfig)), _IMX_SEL_INP_VALUE(_IMX_PADCFG_SEL_INP(PadConfig)))); MmioWrite32 ( _IMX_SEL_INP_REGISTER(_IMX_PADCFG_SEL_INP(PadConfig)), _IMX_SEL_INP_VALUE(_IMX_PADCFG_SEL_INP(PadConfig))); } // // Configure Pad Control // MmioWrite32 ( IOMUXC_SW_MUX_PAD_BASE_ADDRESS + IMX_IOMUX_PAD_CTL_OFFSET(Pad), _IMX_PADCFG_PAD_CTL(PadConfig)); } VOID ImxPadDumpConfig ( char *SignalFriendlyName, IMX_PAD Pad ) { IMX_IOMUXC_MUX_CTL muxCtl; muxCtl.AsUint32 = MmioRead32 ( IOMUXC_SW_MUX_PAD_BASE_ADDRESS + IMX_IOMUX_PAD_MUX_OFFSET(Pad)); DEBUG (( DEBUG_INIT, "- %a MUX_CTL(0x%p)=0x%08x: MUX_MODE:%d SION:%d | ", SignalFriendlyName, IOMUXC_SW_MUX_PAD_BASE_ADDRESS + IMX_IOMUX_PAD_MUX_OFFSET(Pad), muxCtl.AsUint32, muxCtl.Fields.MUX_MODE, muxCtl.Fields.SION)); IMX_IOMUXC_PAD_CTL padCtl; padCtl.AsUint32 = MmioRead32 ( IOMUXC_SW_MUX_PAD_BASE_ADDRESS + IMX_IOMUX_PAD_CTL_OFFSET(Pad)); #if defined(CPU_IMX8MM) DEBUG (( DEBUG_INIT, "PAD_CTL(0x%p)=0x%08x: DSE:%d FSEL:%d ODE:%d PUE:%d HYS:%d PE:%d\n", IOMUXC_SW_MUX_PAD_BASE_ADDRESS + IMX_IOMUX_PAD_CTL_OFFSET(Pad), padCtl.AsUint32, padCtl.Fields.DSE, padCtl.Fields.FSEL, padCtl.Fields.ODE, padCtl.Fields.PUE, padCtl.Fields.HYS, padCtl.Fields.PE)); #else DEBUG (( DEBUG_INIT, "PAD_CTL(0x%p)=0x%08x: DSE:%d SRE:%d ODE:%d PUE:%d HYS:%d LVTTL:%d VSEL:%d\n", IOMUXC_SW_MUX_PAD_BASE_ADDRESS + IMX_IOMUX_PAD_CTL_OFFSET(Pad), padCtl.AsUint32, padCtl.Fields.DSE, padCtl.Fields.SRE, padCtl.Fields.ODE, padCtl.Fields.PUE, padCtl.Fields.HYS, padCtl.Fields.LVTTL, padCtl.Fields.VSEL)); #endif } // // GPIO functions // VOID ImxGpioDirection ( IMX_GPIO_BANK Bank, UINT32 IoNumber, IMX_GPIO_DIR Direction ) { volatile IMX_GPIO_REGISTERS *gpioRegisters = (IMX_GPIO_REGISTERS *) IMX_GPIO_BASE; ASSERT (IoNumber < 32); if (Direction == IMX_GPIO_DIR_INPUT) { MmioAnd32 ((UINTN) &gpioRegisters->Banks[Bank - 1].GDIR, ~(1 << IoNumber)); } else { MmioOr32 ((UINTN) &gpioRegisters->Banks[Bank - 1].GDIR, 1 << IoNumber); } } VOID ImxGpioWrite ( IMX_GPIO_BANK Bank, UINT32 IoNumber, IMX_GPIO_VALUE Value ) { volatile IMX_GPIO_REGISTERS *gpioRegisters = (IMX_GPIO_REGISTERS *) IMX_GPIO_BASE; ASSERT (IoNumber < 32); if (Value == IMX_GPIO_LOW) { MmioAnd32 ((UINTN) &gpioRegisters->Banks[Bank - 1].DR, ~(1 << IoNumber)); } else { MmioOr32 ((UINTN) &gpioRegisters->Banks[Bank - 1].DR, 1 << IoNumber); } } IMX_GPIO_VALUE ImxGpioRead ( IMX_GPIO_BANK Bank, UINT32 IoNumber ) { volatile IMX_GPIO_REGISTERS *gpioRegisters = (IMX_GPIO_REGISTERS *) IMX_GPIO_BASE; ASSERT (IoNumber < 32); UINT32 Mask = (1 << IoNumber); UINT32 Psr = MmioRead32 ((UINTN) &gpioRegisters->Banks[Bank - 1].PSR); if (Psr & Mask) { return IMX_GPIO_HIGH; } else { return IMX_GPIO_LOW; } }
2.09375
2
2024-11-18T19:35:07.340995+00:00
2021-10-19T06:03:14
8af10414763513e9fd62c28a5529507712d1ee5d
{ "blob_id": "8af10414763513e9fd62c28a5529507712d1ee5d", "branch_name": "refs/heads/main", "committer_date": "2021-10-19T06:03:14", "content_id": "6cc2ed67c5ca5c82c815b598e2dc8b6d0594e7d2", "detected_licenses": [ "Apache-2.0" ], "directory_id": "bf7885f2e08352253ffcf50bc3e88d1f76062d2e", "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": 365146068, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2742, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/main.c", "provenance": "stackv2-0054.json.gz:8830", "repo_name": "dreiss94/ebyte_sx1276", "revision_date": "2021-10-19T06:03:14", "revision_id": "0d5d6013f2ca1c49c418ac781373f7f8fccd2cbe", "snapshot_id": "8b797db894278ea295ae6073290cd9ffd0dc3342", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dreiss94/ebyte_sx1276/0d5d6013f2ca1c49c418ac781373f7f8fccd2cbe/src/main.c", "visit_date": "2023-08-22T08:47:37.431706" }
stackv2
#include "config.h" #include <stdio.h> #include <signal.h> #include <stdint.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include "become_daemon.h" #include "error.h" #include "e32.h" #include "gpio.h" #include "options.h" struct options opts; struct E32 dev; static void signal_handler(int sig) { int exit_status; if(opts.daemon) info_output("daemon stopping pid=%d sig=%d", getpid(), sig); options_deinit(&opts); exit_status = e32_deinit(&dev, &opts); exit(exit_status); } int main(int argc, char *argv[]) { int err = 0; if (signal(SIGINT, signal_handler) == SIG_ERR) err_output("installing SIGNT signal handler"); if (signal(SIGTERM, signal_handler) == SIG_ERR) err_output("installing SIGTERM signal handler"); options_init(&opts); err = options_parse(&opts, argc, argv); if(err || opts.help) { usage(argv[0]); return err; } if(opts.verbose) { options_print(&opts); } err = e32_init(&dev, &opts); if(err) { err_output("unable to initialize the e32"); goto cleanup; } if(opts.mode != -1) { err |= e32_set_mode(&dev, opts.mode); goto cleanup; } if(opts.test) { uint8_t buf[512]; for(int i=0; i<512; i++) buf[i] = i; e32_transmit(&dev, buf, 512); goto cleanup; } if(opts.reset) { err |= e32_set_mode(&dev, SLEEP); err |= e32_cmd_reset(&dev); err |= e32_set_mode(&dev, NORMAL); goto cleanup; } /* must be in sleep mode to read or write settings */ if(opts.status || opts.settings_write_input[0]) { if(e32_set_mode(&dev, SLEEP)) { err_output("unable to go to sleep mode\n"); goto cleanup; } } if(opts.status) { if(e32_cmd_read_version(&dev)) { err_output("unable to read version\n"); goto cleanup; } if(e32_cmd_read_settings(&dev)) { err_output("unable to read settings\n"); goto cleanup; } e32_print_version(&dev); e32_print_settings(&dev); goto cleanup; } if(opts.settings_write_input[0]) { err |= e32_cmd_write_settings(&dev, opts.settings_write_input); } /* switch back to normal mode for tx/rx */ if(e32_set_mode(&dev, NORMAL)) { err_output("unable to go to normal mode\n"); goto cleanup; } if(opts.daemon) { err = become_daemon(); if(err) { err_output("mail: error becoming daemon: %d\n", err); goto cleanup; } if(write_pidfile("/run/e32.pid")) { errno_output("unable to write pid file\n"); } info_output("daemon started pid=%ld", getpid()); } err |= e32_poll(&dev, &opts); if(err) err_output("error polling %d", err); cleanup: err |= e32_deinit(&dev, &opts); return err; }
2.609375
3
2024-11-18T19:35:07.711740+00:00
2023-06-12T12:58:22
15af97a9b19153ff0e69bc00b52599b5b0d1ce06
{ "blob_id": "15af97a9b19153ff0e69bc00b52599b5b0d1ce06", "branch_name": "refs/heads/master", "committer_date": "2023-06-12T12:58:22", "content_id": "2651cdb5480276fdb1aeed24964bb514b2b6f22c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "ea7cb6ba74377b67aef7dff7788cc4ec292df684", "extension": "c", "filename": "avs_strings.c", "fork_events_count": 19, "gha_created_at": "2014-02-13T13:53:06", "gha_event_created_at": "2021-10-19T09:13:07", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 16804272, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11293, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/utils/avs_strings.c", "provenance": "stackv2-0054.json.gz:9216", "repo_name": "AVSystem/avs_commons", "revision_date": "2023-06-12T12:58:22", "revision_id": "a227958d88cd9fc689a90d2c336ee0eaa1daf17f", "snapshot_id": "426353386e43201df289baaa5943a899c77593c1", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/AVSystem/avs_commons/a227958d88cd9fc689a90d2c336ee0eaa1daf17f/src/utils/avs_strings.c", "visit_date": "2023-06-23T16:58:31.095799" }
stackv2
/* * Copyright 2023 AVSystem <[email protected]> * * 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 <avs_commons_init.h> #ifdef AVS_COMMONS_WITH_AVS_UTILS # include <assert.h> # include <ctype.h> # include <inttypes.h> # include <stdarg.h> # include <stdio.h> # include <stdlib.h> # include <string.h> # if defined(AVS_COMMONS_WITHOUT_FLOAT_FORMAT_SPECIFIERS) \ || defined(AVS_UNIT_TESTING) # include <float.h> # include <math.h> # endif // defined(AVS_COMMONS_WITHOUT_FLOAT_FORMAT_SPECIFIERS) || // defined(AVS_UNIT_TESTING) # include <avsystem/commons/avs_memory.h> # include <avsystem/commons/avs_utils.h> VISIBILITY_SOURCE_BEGIN int avs_simple_vsnprintf(char *out, size_t out_size, const char *format, va_list args) { assert(out || !out_size); int result = vsnprintf(out, out_size, format, args); return (result < 0 || (size_t) result >= out_size) ? -1 : result; } int avs_simple_snprintf(char *out, size_t out_size, const char *format, ...) { va_list args; va_start(args, format); int result = avs_simple_vsnprintf(out, out_size, format, args); va_end(args); return result; } int avs_strcasecmp(const char *s1, const char *s2) { int c1; int c2; do { c1 = toupper(*(const unsigned char *) s1++); c2 = toupper(*(const unsigned char *) s2++); } while (c1 && c2 && c1 == c2); return c1 - c2; } int avs_strncasecmp(const char *s1, const char *s2, size_t n) { int c1 = 0; int c2 = 0; do { if (!n--) { break; } c1 = toupper(*(const unsigned char *) s1++); c2 = toupper(*(const unsigned char *) s2++); } while (c1 && c2 && c1 == c2); return c1 - c2; } char *avs_strtok(char *str, const char *delim, char **saveptr) { // adapted from // https://git.musl-libc.org/cgit/musl/tree/src/string/strtok_r.c if (!str && !(str = *saveptr)) { return NULL; } str += strspn(str, delim); if (!*str) { *saveptr = NULL; return NULL; } *saveptr = str + strcspn(str, delim); if (**saveptr) { *(*saveptr)++ = '\0'; } else { *saveptr = NULL; } return str; } char *avs_strdup(const char *str) { size_t len = strlen(str); char *retval = (char *) avs_malloc(len + 1); if (!retval) { return NULL; } memcpy(retval, str, len + 1); return retval; } void avs_memswap(void *memptr1, void *memptr2, size_t n) { char *const ptr1 = (char *) memptr1; char *const ptr2 = (char *) memptr2; AVS_ASSERT(ptr1 >= ptr2 + n || ptr2 >= ptr1 + n, "memory fragments must not intersect"); for (size_t i = 0; i < n; i++) { char tmp = ptr1[i]; ptr1[i] = ptr2[i]; ptr2[i] = tmp; } } # if defined(AVS_COMMONS_WITHOUT_64BIT_FORMAT_SPECIFIERS) \ || defined(AVS_UNIT_TESTING) static const char * uint64_as_string_custom(char (*buf)[AVS_UINT_STR_BUF_SIZE(uint64_t)], uint64_t value) { char *ptr = *buf + AVS_UINT_STR_BUF_SIZE(uint64_t) - 1; *ptr = '\0'; do { ptr--; *ptr = (char) (value % 10 + '0'); value /= 10; } while (value); assert(ptr >= *buf); return ptr; } static const char * int64_as_string_custom(char (*buf)[AVS_INT_STR_BUF_SIZE(int64_t)], int64_t value) { uint64_t absolute_value; bool negative = false; if (value < 0) { absolute_value = (uint64_t) - (value + 1) + 1; negative = true; } else { absolute_value = (uint64_t) value; } char *ptr = (char *) (intptr_t) uint64_as_string_custom(buf, absolute_value); if (negative) { ptr--; *ptr = '-'; } assert(ptr >= *buf); return ptr; } # endif // defined(AVS_COMMONS_WITHOUT_64BIT_FORMAT_SPECIFIERS) || // defined(AVS_UNIT_TESTING) const char * avs_uint64_as_string_impl__(char (*buf)[AVS_UINT_STR_BUF_SIZE(uint64_t)], uint64_t value) { # ifdef AVS_COMMONS_WITHOUT_64BIT_FORMAT_SPECIFIERS return uint64_as_string_custom(buf, value); # else // AVS_COMMONS_WITHOUT_64BIT_FORMAT_SPECIFIERS snprintf(*buf, AVS_UINT_STR_BUF_SIZE(uint64_t), "%" PRIu64, value); return *buf; # endif // AVS_COMMONS_WITHOUT_64BIT_FORMAT_SPECIFIERS } const char * avs_int64_as_string_impl__(char (*buf)[AVS_INT_STR_BUF_SIZE(int64_t)], int64_t value) { # ifdef AVS_COMMONS_WITHOUT_64BIT_FORMAT_SPECIFIERS return int64_as_string_custom(buf, value); # else // AVS_COMMONS_WITHOUT_64BIT_FORMAT_SPECIFIERS snprintf(*buf, AVS_INT_STR_BUF_SIZE(int64_t), "%" PRId64, value); return *buf; # endif // AVS_COMMONS_WITHOUT_64BIT_FORMAT_SPECIFIERS } # if defined(AVS_COMMONS_WITHOUT_FLOAT_FORMAT_SPECIFIERS) \ || defined(AVS_UNIT_TESTING) static int double_as_string_custom_impl(char *buf, size_t buf_size, double value, int16_t actual_e10, int16_t target_e10, uint8_t precision) { assert(buf_size >= AVS_UINT_STR_BUF_SIZE(uint64_t)); assert(precision >= 1); assert(precision <= 18); int multiplier_e10 = precision - actual_e10 - 1; // For very small values there might be a need to do the multiplication in // multiple stages to avoid overflow of the multiplier. while (multiplier_e10 != 0) { int stage_multiplier_e10 = AVS_MIN(AVS_MAX(multiplier_e10, DBL_MIN_10_EXP), DBL_MAX_10_EXP); value *= pow(10.0, stage_multiplier_e10); multiplier_e10 -= stage_multiplier_e10; } // value shall now be in the [0, 10^precision] range // although usually it'll be in [10^(precision-1), 10^precision) // NOTE: The "+ 0.5" term ensures proper rounding. char *decimal = (char *) (intptr_t) avs_uint64_as_string_impl__( (char(*)[AVS_UINT_STR_BUF_SIZE(uint64_t)]) buf, (uint64_t) (value + 0.5)); assert(decimal >= buf && decimal < buf + buf_size); int16_t decimal_len = (int16_t) strlen(decimal); assert((size_t) decimal_len + 1 < buf_size); int16_t decimal_point_pos = (int16_t) (1 + actual_e10 + decimal_len - target_e10 - precision); assert(decimal_point_pos <= decimal_len); int16_t trailing_zeros = 0; while (trailing_zeros < decimal_len && decimal[decimal_len - 1 - trailing_zeros] == '0') { ++trailing_zeros; } assert(trailing_zeros <= decimal_len); if (trailing_zeros == decimal_len) { return avs_simple_snprintf(buf, buf_size, "0"); } else if (decimal_point_pos <= 0) { assert((size_t) (decimal_len - trailing_zeros - decimal_point_pos + 2) < buf_size); memmove(buf + 2 - decimal_point_pos, decimal, (size_t) (decimal_len - trailing_zeros)); buf[0] = '0'; buf[1] = '.'; for (int i = 2; i < 2 - decimal_point_pos; ++i) { buf[i] = '0'; } buf[decimal_len - trailing_zeros - decimal_point_pos + 2] = '\0'; return decimal_len - trailing_zeros - decimal_point_pos + 2; } else { memmove(buf, decimal, (size_t) decimal_point_pos); if (decimal_point_pos >= decimal_len - trailing_zeros) { buf[decimal_point_pos] = '\0'; return decimal_point_pos; } else { memmove(buf + decimal_point_pos + 1, decimal + decimal_point_pos, (size_t) (decimal_len - decimal_point_pos - trailing_zeros)); buf[decimal_point_pos] = '.'; buf[decimal_len + 1 - trailing_zeros] = '\0'; return decimal_len + 1 - trailing_zeros; } } } static int double_as_string_custom(char *buf, size_t buf_size, double value, uint8_t precision) { static const double EXPONENTIAL_THRESHOLD = 0.0001; assert(precision >= 1); assert(precision <= 18); if (isnan(value)) { return avs_simple_snprintf(buf, buf_size, "nan"); } else if (value == 0.0) { return avs_simple_snprintf(buf, buf_size, "0"); } else if (value < 0.0) { assert(buf_size >= 2); buf[0] = '-'; int result = double_as_string_custom(buf + 1, buf_size - 1, -value, precision); return result >= 0 ? result + 1 : result; } else if (isinf(value)) { // NOTE: With conjunction with the above case, this covers -inf as well return avs_simple_snprintf(buf, buf_size, "inf"); } else { assert(value > 0.0); assert(isfinite(value)); // For IEEE 754-compliant double, this shall be in the [-308, 308] range int16_t e10 = (int16_t) floor(log10(value)); if (value <= EXPONENTIAL_THRESHOLD || e10 >= precision) { int result = double_as_string_custom_impl(buf, buf_size, value, e10, e10, precision); if (result < 0) { return result; } int result2 = avs_simple_snprintf(buf + result, buf_size - (size_t) result, "e%+" PRId16, e10); if (result2 < 0) { return result2; } return result + result2; } else { return double_as_string_custom_impl(buf, buf_size, value, e10, 0, precision); } } } # endif // defined(AVS_COMMONS_WITHOUT_FLOAT_FORMAT_SPECIFIERS) || // defined(AVS_UNIT_TESTING) const char * avs_double_as_string_impl__(char (*buf)[32], double value, uint8_t precision) { assert(precision >= 1); assert(precision <= 18); int result = # ifdef AVS_COMMONS_WITHOUT_FLOAT_FORMAT_SPECIFIERS double_as_string_custom(*buf, sizeof(*buf), value, precision); # else // AVS_COMMONS_WITHOUT_FLOAT_FORMAT_SPECIFIERS avs_simple_snprintf(*buf, sizeof(*buf), "%.*g", precision, value); # endif // AVS_COMMONS_WITHOUT_FLOAT_FORMAT_SPECIFIERS assert(result >= 0); (void) result; return *buf; } # ifdef AVS_UNIT_TESTING # include "tests/utils/strings.c" # endif // AVS_UNIT_TESTING #endif // AVS_COMMONS_WITH_AVS_UTILS
2.15625
2
2024-11-18T19:35:07.990326+00:00
2020-01-06T07:42:43
22265aab1a4a072efc04c2a1a6a9355948191f55
{ "blob_id": "22265aab1a4a072efc04c2a1a6a9355948191f55", "branch_name": "refs/heads/master", "committer_date": "2020-01-06T07:42:43", "content_id": "7944c9b813dc5a0d81a83f30f706a2f3845c8cfa", "detected_licenses": [ "MIT" ], "directory_id": "53a10167fac37e4360698825e4baa6db01876173", "extension": "c", "filename": "23-2강 공용체.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 220875456, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 204, "license": "MIT", "license_type": "permissive", "path": "/C_Language/23-2강 공용체.c", "provenance": "stackv2-0054.json.gz:9602", "repo_name": "gusdn6763/C_Language", "revision_date": "2020-01-06T07:42:43", "revision_id": "b75f7d62e78d3a8f23e57d1d71c1e3ae8c7c8c66", "snapshot_id": "16e58ba11abe553cb829475334c9a76f238f113f", "src_encoding": "UHC", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gusdn6763/C_Language/b75f7d62e78d3a8f23e57d1d71c1e3ae8c7c8c66/C_Language/23-2강 공용체.c", "visit_date": "2020-09-07T18:21:21.807518" }
stackv2
int main232() { union box { int mem1; int mem2; double mem3; }; union box box; box.mem1 = 1; printf("%d %d", box.mem1, box.mem2); //공용체 == 메모리 공유 return 0; }
2.140625
2
2024-11-18T19:35:09.546013+00:00
2021-06-30T04:05:56
b8f8c5feb8562d4f72fa3283a3b1c036745f911b
{ "blob_id": "b8f8c5feb8562d4f72fa3283a3b1c036745f911b", "branch_name": "refs/heads/master", "committer_date": "2021-06-30T04:05:56", "content_id": "de889a7e3ae77ecd944807277ceb8e4169a6b8d3", "detected_licenses": [ "MIT" ], "directory_id": "7c2d27e4548480e4628ae45df2455b4df296043b", "extension": "h", "filename": "math_utils.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 201789857, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2223, "license": "MIT", "license_type": "permissive", "path": "/src/math_utils.h", "provenance": "stackv2-0054.json.gz:10371", "repo_name": "gingerbig/wordnet", "revision_date": "2021-06-30T04:05:56", "revision_id": "651cbec774d77a42daebeb066a85f27afd0aa267", "snapshot_id": "920b30397c068809ba522bdda09b9beb8bc5f05f", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/gingerbig/wordnet/651cbec774d77a42daebeb066a85f27afd0aa267/src/math_utils.h", "visit_date": "2021-07-13T20:26:35.822976" }
stackv2
#ifndef _MATH_UTILS #define _MATH_UTILS /* Calculate matrix multiplication * @param A m x n * @param B n x p * @return result m x p */ void multiplyMatrix(const double *A, const double *B, int m, int n, int p, double *result); /* Calculate matrix C = C + A * B * @param A m x n * @param B n x p * @return C += A * B, m x p */ void multiplyAddMatrix(const double *A, const double *B, int m, int n, int p, double *C); /* Calculate matrix subtraction * @param A: m x n * @param B: m x n * @return result = A - B, m x n, can overwrite A or B */ void subtractMatrix(const double *A, const double *B, int m, int n, double *result); /* Calculate matrix scaled subtraction * @param A: m x n * @param B: m x n ! @param scale: scaling operation doesn't modify matrices! * @return result = A - scale * B, m x n, can overwrite A or B */ void subtractScaleMatrix(const double *A, const double *B, double scale, int m, int n, double *result); /* Calculate matrix sum * @param A: m x n * @param B: m x n * @return result = A + B, m x n, can overwrite A or B */ void addMatrix(const double *A, const double *B, int m, int n, double *result); /* Transpose a matrix * @param A: m x n * @return B: n x m */ void transposeMatrix(const double *A, int m, int n, double *B); /* Scale a matrix * @param A: m x n * @param c: a constant * @return A: cA */ void scaleMatrix(double *A, int m, int n, double c); /* Sum a matrix to a column vector * @param A: m x n * @return v: m x 1 */ void sumColumn2Vector(const double *A, int m, int n, double *v); /* Gaussian random number generator */ double gaussRand(double mean, double std); /* Entry-wise sigmoid function ! A will be overwritten */ void sigmoid(double *A, int m, int n); /* Column-wise softmax function ! A will be overwritten */ void softmax(double *A, int m, int n); /* Average cross entropy of two softmax batches * @param Each column of A & B is a softmax correspondingly * @return Average of all column cross entropies */ double averageCrossEntropy(const double *A, const double *B, int row, int column); #endif
2.6875
3
2024-11-18T19:35:10.340007+00:00
2023-08-14T21:35:58
c0208863d06e8f699a385451701e7a8173601195
{ "blob_id": "c0208863d06e8f699a385451701e7a8173601195", "branch_name": "refs/heads/main", "committer_date": "2023-08-14T21:35:58", "content_id": "b9014b17bc2268faf620ae90ee5ea495ed9c96c3", "detected_licenses": [ "MIT" ], "directory_id": "37e03845cb8de9ed1cf78a335a84b1e22f3c232f", "extension": "c", "filename": "association.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 181378906, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 997, "license": "MIT", "license_type": "permissive", "path": "/lib/sysbvm/association.c", "provenance": "stackv2-0054.json.gz:10884", "repo_name": "ronsaldo/sysmel", "revision_date": "2023-08-14T21:35:58", "revision_id": "021ca52ddfb6d336d3876a2717bb0f593b77130c", "snapshot_id": "8e1e82858c394896e063eadf96e1dbfe9aacf1d0", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/ronsaldo/sysmel/021ca52ddfb6d336d3876a2717bb0f593b77130c/lib/sysbvm/association.c", "visit_date": "2023-08-17T16:11:11.571588" }
stackv2
#include "sysbvm/association.h" #include "internal/context.h" #include <stdlib.h> SYSBVM_API sysbvm_tuple_t sysbvm_association_create(sysbvm_context_t *context, sysbvm_tuple_t key, sysbvm_tuple_t value) { sysbvm_association_t *result = (sysbvm_association_t*)sysbvm_context_allocatePointerTuple(context, context->roots.associationType, SYSBVM_SLOT_COUNT_FOR_STRUCTURE_TYPE(sysbvm_association_t)); result->key = key; result->value = value; return (sysbvm_tuple_t)result; } SYSBVM_API sysbvm_tuple_t sysbvm_weakValueAssociation_create(sysbvm_context_t *context, sysbvm_tuple_t key, sysbvm_tuple_t value) { sysbvm_weakValueAssociation_t *result = (sysbvm_weakValueAssociation_t*)sysbvm_context_allocatePointerTuple(context, context->roots.weakValueAssociationType, SYSBVM_SLOT_COUNT_FOR_STRUCTURE_TYPE(sysbvm_weakValueAssociation_t)); sysbvm_tuple_markWeakObject((sysbvm_tuple_t)result); result->key = key; result->value = value; return (sysbvm_tuple_t)result; }
2.140625
2
2024-11-18T19:35:10.470437+00:00
2016-04-04T20:55:25
130b32cf062b5d63daa7f1cba8f36b0a05c261fa
{ "blob_id": "130b32cf062b5d63daa7f1cba8f36b0a05c261fa", "branch_name": "refs/heads/master", "committer_date": "2016-04-04T20:55:25", "content_id": "8ae4e638bdab11a94cf5dc91019a7906be05bd93", "detected_licenses": [ "MIT" ], "directory_id": "4fdb7e682e2a1227ccf2d54e846a0aba48c241d1", "extension": "c", "filename": "str_lpad.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 55333149, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1981, "license": "MIT", "license_type": "permissive", "path": "/str_lpad.c", "provenance": "stackv2-0054.json.gz:11012", "repo_name": "nobody-mb/asm-crap", "revision_date": "2016-04-04T20:55:25", "revision_id": "0c357df054d7507c8d7f24bc1b0e356f16bab741", "snapshot_id": "1504167c3bbc129b9e735defd26d0597dbc8e00b", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/nobody-mb/asm-crap/0c357df054d7507c8d7f24bc1b0e356f16bab741/str_lpad.c", "visit_date": "2021-01-10T05:42:20.869685" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #define rdtscl(val) asm volatile ("rdtsc" : "=A" (val) : : ); void old_str_lpad (char *dst, const char *src, size_t width, unsigned char pad); void new_str_lpad (char *dst, const char *src, size_t width, unsigned char pad); void asm_str_lpad (char *dst, const char *src, size_t width, unsigned char pad); void test_lpad (char *src, int width, unsigned char pad) { unsigned long t1, t2; char *r1 = calloc(1, 1024); char *r2 = calloc(1, 1024); char *r3 = calloc(1, 1024); memset(r1, 'a', 1023); memset(r2, 'a', 1023); memset(r3, 'a', 1023); old_str_lpad (r1, src, width, pad); rdtscl(t1); old_str_lpad (r1, src, width, pad); rdtscl(t2); printf("old - %5lu cycles - \n%s\n", t2 - t1, r1); new_str_lpad (r2, src, width, pad); rdtscl(t1); new_str_lpad (r2, src, width, pad); rdtscl(t2); printf("new - %5lu cycles - \n%s\n", t2 - t1, r2); asm_str_lpad (r3, src, width, pad); rdtscl(t1); asm_str_lpad (r3, src, width, pad); rdtscl(t2); printf("asm - %5lu cycles - \n%s\n\n", t2 - t1, r3); free(r1); free(r2); free(r3); } void old_str_lpad (char *dst, const char *src, size_t width, unsigned char pad) { int i; do { for (i = 0; i < width; i++) { *dst++ = pad; } while (*src != '\n' && *src) { *dst++ = *src++; } *dst++ = *src; } while (*src++); } void new_str_lpad (char *dst, const char *src, size_t width, unsigned char pad) { int i; i = (int)width; while (i--) *dst++ = pad; do { *dst++ = *src; if (*src == '\n') { i = (int)width; while (i--) *dst++ = pad; } } while (*src++); } int main (void) { test_lpad ("abc\n" "this is a test\n", 2, ' '); test_lpad ("abc\n" "\na\0\nasdf\n", 5, ' '); test_lpad ("\na\0", 2, ' '); test_lpad ("\na\0", 0, ' '); test_lpad ("\n\0\n", 3, ' '); test_lpad ("a\0a", 2, ' '); test_lpad ("asdfadsf\naefsdf\n", 3, '0'); }
3
3
2024-11-18T19:35:10.533573+00:00
2019-12-20T13:52:39
db34ea9f84d4278601e732659f9bbcce03af8131
{ "blob_id": "db34ea9f84d4278601e732659f9bbcce03af8131", "branch_name": "refs/heads/master", "committer_date": "2019-12-20T13:52:39", "content_id": "4696dc4d139ea08e9ceadf91368896d7af1ac403", "detected_licenses": [ "Apache-2.0" ], "directory_id": "3efc50ba20499cc9948473ee9ed2ccfce257d79a", "extension": "c", "filename": "ssh-honeypot.c", "fork_events_count": 4, "gha_created_at": "2019-09-20T18:35:35", "gha_event_created_at": "2019-12-20T13:52:42", "gha_language": "C", "gha_license_id": null, "github_id": 209857592, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 17346, "license": "Apache-2.0", "license_type": "permissive", "path": "/data/others/files/ssh-honeypot.c", "provenance": "stackv2-0054.json.gz:11140", "repo_name": "arthurherbout/crypto_code_detection", "revision_date": "2019-12-20T13:52:39", "revision_id": "3c9ff8a4b2e4d341a069956a6259bf9f731adfc0", "snapshot_id": "7e10ed03238278690d2d9acaa90fab73e52bab86", "src_encoding": "UTF-8", "star_events_count": 9, "url": "https://raw.githubusercontent.com/arthurherbout/crypto_code_detection/3c9ff8a4b2e4d341a069956a6259bf9f731adfc0/data/others/files/ssh-honeypot.c", "visit_date": "2020-07-29T15:34:31.380731" }
stackv2
/* ssh-honeypot -- by Daniel Roberson (daniel(a)planethacker.net) 2016-2019 * * TODO: keep fp open for log_entry; reload on HUP * TODO: config files * TODO: hassh? * i don't see a way to do this right now. from what ive gathered, * libssh doesn't provide an easy way to look at the ssh handshake * packets and see the full list of kex methods, crypto methods, * compression, ... * Thought about modifying the library to just do hassh in there, * trying something with libpcap, or writing another tool altogether. * TODO: add more banners */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <stdarg.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <signal.h> #include <time.h> #include <pwd.h> #include <grp.h> #include <syslog.h> #include <sys/param.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <libssh/libssh.h> #include <libssh/server.h> #include <json-c/json.h> #include "config.h" /* Globals */ char * logfile = LOGFILE; char * pidfile = PIDFILE; char * rsakey = RSAKEY; char * bindaddr = BINDADDR; bool console_output = true; bool daemonize = false; bool use_syslog = false; bool json_logging_file = false; bool json_logging_server = false; char * json_logfile = JSON_LOGFILE; char * json_server = JSON_SERVER; unsigned short json_port = JSON_PORT; int json_sock; char hostname[MAXHOSTNAMELEN]; /* Banners */ static struct banner_info_s { const char *str, *info; } banners[] = { {"", "No banner"}, {"OpenSSH_5.9p1 Debian-5ubuntu1.4", "Ubuntu 12.04"}, {"OpenSSH_7.2p2 Ubuntu-4ubuntu2.1", "Ubuntu 16.04"}, {"OpenSSH_7.6p1 Ubuntu-4ubuntu0.3", "Ubuntu 18.04"}, {"OpenSSH_6.6.1", "openSUSE 42.1"}, {"OpenSSH_6.7p1 Debian-5+deb8u3", "Debian 8.6"}, {"OpenSSH_7.5", "pfSense 2.4.4-RELEASE-p3"}, {"dropbear_2014.63", "dropbear 2014.63"}, }; const size_t num_banners = sizeof banners / sizeof *banners; /* usage() -- prints out usage instructions and exits the program */ static void usage (const char *progname) { fprintf (stderr, "ssh-honeypot %s by %s\n\n", VERSION, AUTHOR); fprintf (stderr, "usage: %s " "[-?h -p <port> -a <address> -b <index> -l <file> -r <file> " "-f <file> -u <user>]\n", progname); fprintf (stderr, "\t-?/-h\t\t-- this help menu\n"); fprintf (stderr, "\t-p <port>\t-- listen port\n"); fprintf (stderr, "\t-a <address>\t-- IP address to bind to\n"); fprintf (stderr, "\t-l <file>\t-- log file\n"); fprintf (stderr, "\t-s\t\t-- toggle syslog usage. Default: %s\n", use_syslog ? "on" : "off"); fprintf (stderr, "\t-r <file>\t-- specify RSA key to use\n"); fprintf (stderr, "\t-f <file>\t-- specify location to PID file\n"); fprintf (stderr, "\t-b\t\t-- list available banners\n"); fprintf (stderr, "\t-b <string>\t-- specify banner string (max 255 characters)\n"); fprintf (stderr, "\t-i <index>\t-- specify banner index\n"); fprintf (stderr, "\t-u <user>\t-- user to setuid() to after bind()\n"); fprintf (stderr, "\t-j <file>\t-- path to JSON logfile\n"); fprintf (stderr, "\t-J <address>\t-- server to send JSON logs\n"); fprintf (stderr, "\t-P <port>\t-- port to send JSON logs\n"); exit (EXIT_FAILURE); } /* pr_banners() -- prints out a list of available banner options */ static void pr_banners () { fprintf (stderr, "Available banners: [index] banner (description)\n"); for (size_t i = 0; i < num_banners; i++) { struct banner_info_s *banner = banners + i; fprintf (stderr, "[%zu] %s (%s)\n", i, banner->str, banner->info); } fprintf (stderr, "Total banners: %zu\n", num_banners); } /* sockprintf() -- send formatted data to a socket */ static int sockprintf (int s, const char *fmt, ...) { int n; char buf[8192] = {0}; va_list vl; va_start (vl, fmt); n = vsnprintf (buf, sizeof(buf), fmt, vl); va_end (vl); return send (s, buf, n, 0); } /* log_entry() -- adds timestamped log entry * -- displays output to stdout if console_output is true */ static int log_entry (const char *fmt, ...) { int n; FILE * fp; time_t t; va_list va; char * timestr; char buf[1024]; time (&t); timestr = strtok (ctime (&t), "\n"); // banish newline character to the land // of wind and ghosts if ((fp = fopen (logfile, "a+")) == NULL) { fprintf (stderr, "Unable to open logfile %s: %s\n", logfile, strerror (errno)); return 1; } va_start (va, fmt); vsnprintf (buf, sizeof(buf), fmt, va); va_end (va); if (use_syslog) syslog (LOG_INFO | LOG_AUTHPRIV, "%s", buf); n = fprintf (fp, "[%s] %s\n", timestr, buf); if (console_output) printf ("[%s] %s\n", timestr, buf); fclose (fp); return n; } /* log_entry_fatal() -- log a message, then exit with EXIT_FAILURE */ void log_entry_fatal (const char *fmt, ...) { va_list vl; va_start (vl, fmt); log_entry (fmt, vl); va_end (vl); exit (EXIT_FAILURE); } /* json_log() -- log JSON formatted data to a file */ static void json_log (const char *msg) { FILE * fp; fp = fopen (json_logfile, "a"); if (fp == NULL) log_entry_fatal ("FATAL: Unable to open JSON log file %s: %s\n", json_logfile, strerror (errno)); fprintf (fp, "%s\n", msg); fclose (fp); } /* json_log_creds() -- log username/password in JSON format */ static void json_log_creds (const char *ip, const char *user, const char *pass) { char * message; json_object *jobj = json_object_new_object (); json_object *j_time = json_object_new_int (time(NULL)); json_object *j_host = json_object_new_string (hostname); json_object *j_client = json_object_new_string (ip); json_object *j_user = json_object_new_string (user); json_object *j_pass = json_object_new_string (pass); json_object *j_event = json_object_new_string ("ssh-honeypot-auth"); json_object_object_add (jobj, "event", j_event); json_object_object_add (jobj, "time", j_time); json_object_object_add (jobj, "host", j_host); json_object_object_add (jobj, "client", j_client); json_object_object_add (jobj, "user", j_user); json_object_object_add (jobj, "pass", j_pass); message = (char *)json_object_to_json_string (jobj); if (json_logging_file) json_log (message); if (json_logging_server) sockprintf (json_sock, "%s\r\n", message); json_object_put (jobj); } /* json_log_kex_error() -- log connections in JSON format */ static void json_log_kex_error (const char *ip) { char * message; json_object *jobj = json_object_new_object (); json_object *j_time = json_object_new_int (time (NULL)); json_object *j_host = json_object_new_string (hostname); json_object *j_client = json_object_new_string (ip); json_object *j_event = json_object_new_string ("ssh-honetpot-kexerror"); json_object_object_add (jobj, "event", j_event); json_object_object_add (jobj, "time", j_time); json_object_object_add (jobj, "host", j_host); json_object_object_add (jobj, "client", j_client); message = (char *)json_object_to_json_string (jobj); if (json_logging_file) json_log (message); if (json_logging_server) sockprintf (json_sock, "%s\r\n", message); json_object_put (jobj); } /* json_log_session() - log information about client sessions */ static void json_log_session (const char *client_ip, const char *banner_c, const char *banner_s, const char *kex_algo, const char *cipher_in, const char *cipher_out, const char *hmac_in, const char *hmac_out) { char * message; json_object *jobj = json_object_new_object (); json_object *j_time = json_object_new_int (time (NULL)); json_object *j_host = json_object_new_string (hostname); json_object *j_client = json_object_new_string (client_ip); json_object *j_event = json_object_new_string ("ssh-honeypot-session"); json_object *j_banner_c = json_object_new_string (banner_c); json_object *j_banner_s = json_object_new_string (banner_s); json_object *j_kex_algo = json_object_new_string (kex_algo); json_object *j_cipher_in = json_object_new_string (cipher_in); json_object *j_cipher_out = json_object_new_string (cipher_out); json_object *j_hmac_in = json_object_new_string (hmac_in); json_object *j_hmac_out = json_object_new_string (hmac_out); json_object_object_add (jobj, "event", j_event); json_object_object_add (jobj, "time", j_time); json_object_object_add (jobj, "host", j_host); json_object_object_add (jobj, "client", j_client); json_object_object_add (jobj, "client_banner", j_banner_c); json_object_object_add (jobj, "server_banner", j_banner_s); json_object_object_add (jobj, "kex_algo", j_kex_algo); json_object_object_add (jobj, "cipher_in", j_cipher_in); json_object_object_add (jobj, "cipher_out", j_cipher_out); json_object_object_add (jobj, "hmac_in", j_hmac_in); json_object_object_add (jobj, "hmac_out", j_hmac_out); message = (char *)json_object_to_json_string (jobj); if (json_logging_file) json_log (message); if (json_logging_server) sockprintf (json_sock, "%s\r\n", message); json_object_put (jobj); } /* get_ssh_ip() -- obtains IP address via ssh_session */ static char *get_ssh_ip (ssh_session session) { static char ip[INET6_ADDRSTRLEN]; struct sockaddr_storage tmp; struct sockaddr_in * s; socklen_t address_len = sizeof(tmp); getpeername (ssh_get_fd (session), (struct sockaddr *)&tmp, &address_len); s = (struct sockaddr_in *)&tmp; inet_ntop (AF_INET, &s->sin_addr, ip, sizeof(ip)); return ip; } /* handle_ssh_auth() -- handles ssh authentication requests, logging * -- appropriately. */ static int handle_ssh_auth (ssh_session session) { ssh_message message; char * ip; ip = get_ssh_ip (session); if (ssh_handle_key_exchange (session)) { log_entry ("%s Error exchanging keys: %s", ip, ssh_get_error (session)); if (json_logging_file || json_logging_server) json_log_kex_error (ip); return -1; } char *banner_c = (char *)ssh_get_clientbanner (session); char *banner_s = (char *)ssh_get_serverbanner (session); char *kex_algo = (char *)ssh_get_kex_algo (session); char *cipher_in = (char *)ssh_get_cipher_in (session); char *cipher_out = (char *)ssh_get_cipher_out (session); char *hmac_in = (char *)ssh_get_hmac_in (session); char *hmac_out = (char *)ssh_get_hmac_out (session); if (json_logging_file || json_logging_server) json_log_session (ip, banner_c, banner_s, ssh_get_kex_algo (session), ssh_get_cipher_in (session), ssh_get_cipher_out (session), ssh_get_hmac_in (session), ssh_get_hmac_out (session)); log_entry ("Session: %s|%s|%s|%s|%s|%s|%s", banner_c, banner_s, kex_algo, cipher_in, cipher_out, hmac_in, hmac_out); for (;;) { if ((message = ssh_message_get (session)) == NULL) break; switch (ssh_message_subtype (message)) { case SSH_AUTH_METHOD_PASSWORD: if (json_logging_file || json_logging_server) json_log_creds (ip, ssh_message_auth_user (message), ssh_message_auth_password (message)); log_entry ("%s %s %s", ip, ssh_message_auth_user (message), ssh_message_auth_password (message)); break; default: break; printf("other: %d\n", ssh_message_subtype (message)); } ssh_message_reply_default (message); ssh_message_free (message); } return 0; } /* write_pid_file() -- writes PID to PIDFILE */ static void write_pid_file (char *path, pid_t pid) { FILE * fp; fp = fopen (path, "w"); if (fp == NULL) log_entry_fatal ("FATAL: Unable to open PID file %s: %s\n", path, strerror (errno)); fprintf (fp, "%d", pid); fclose (fp); } /* drop_privileges() -- drops privileges to specified user/group */ void drop_privileges (char *username) { struct passwd * pw; struct group * grp; pw = getpwnam (username); if (pw == NULL) log_entry_fatal ("FATAL: Username does not exist: %s\n", username); grp = getgrgid (pw->pw_gid); if (grp == NULL) log_entry_fatal ("FATAL: Unable to determine groupfor %d: %s\n", pw->pw_gid, strerror (errno)); /* chown logfile so this user can use it */ if (chown (logfile, pw->pw_uid, pw->pw_gid) == -1) log_entry_fatal ("FATAL: Unable to set permissions for log file %s: %s\n", logfile, strerror (errno)); /* drop group first */ if (setgid (pw->pw_gid) == -1) log_entry_fatal ("FATAL: Unable to drop group permissions to %s: %s\n", grp->gr_name, strerror (errno)); /* drop user privileges */ if (setuid (pw->pw_uid) == -1) log_entry_fatal ("FATAL: Unable to drop user permissions to %s: %s\n", username, strerror (errno)); } /* main() -- main entry point of program */ int main (int argc, char *argv[]) { pid_t pid, child; int opt; unsigned short port = PORT, banner_index = 1; const char * banner = banners[1].str; char * username = NULL; ssh_session session; ssh_bind sshbind; while ((opt = getopt (argc, argv, "h?p:dl:b:i:r:f:su:j:J:P:")) != -1) { switch (opt) { case 'p': /* Listen port */ port = atoi(optarg); break; case 'd': /* Daemonize */ daemonize = true; console_output = false; break; case 'l': /* Log file path */ logfile = optarg; break; case 'a': /* IP to bind to */ bindaddr = optarg; break; case 'r': /* Path to RSA key */ rsakey = optarg; break; case 'f': /* PID file location */ pidfile = optarg; break; case 's': /* Toggle syslog */ use_syslog = use_syslog ? false : true; break; case 'u': /* User to drop privileges to */ username = optarg; break; case 'i': /* Set banner by index */ banner_index = atoi(optarg); if (banner_index >= num_banners) { fprintf (stderr, "FATAL: Invalid banner index\n"); exit (EXIT_FAILURE); } banner = banners[banner_index].str; break; case 'b': /* Specify banner string */ banner = optarg; break; case 'j': /* JSON logfile */ json_logging_file = true; json_logfile = optarg; break; case 'J': /* JSON server */ json_logging_server = true; json_server = optarg; break; case 'P': /* JSON port */ json_port = atoi(optarg); break; case '?': /* Print usage */ case 'h': if (optopt == 'i' || optopt == 'b') { pr_banners(); return EXIT_FAILURE; } default: usage (argv[0]); } } if (gethostname (hostname, sizeof(hostname)) == -1) log_entry_fatal ("FATAL: gethostname(): %s\n", strerror (errno)); if (json_logging_server) { struct sockaddr_in s_addr; json_sock = socket (AF_INET, SOCK_DGRAM, 0); if (json_sock < 0) log_entry_fatal ("FATAL: socket(): %s\n", strerror (errno)); bzero (&s_addr, sizeof(s_addr)); s_addr.sin_family = AF_INET; s_addr.sin_addr.s_addr = inet_addr (json_server); s_addr.sin_port = htons (json_port); /* connect() UDP socket to avoid sendto() */ if (connect (json_sock, (struct sockaddr *)&s_addr, sizeof(s_addr)) == -1) log_entry_fatal ("FATAL: connect(): %s\n", strerror (errno)); } signal (SIGCHLD, SIG_IGN); if (daemonize) { pid = fork(); if (pid < 0) log_entry_fatal ("FATAL: fork(): %s\n", strerror (errno)); else if (pid > 0) { write_pid_file (pidfile, pid); exit (EXIT_SUCCESS); } printf ("ssh-honeypot %s by %s started on port %d. PID %d\n", VERSION, AUTHOR, port, getpid()); } log_entry ("ssh-honeypot %s by %s started on port %d. PID %d", VERSION, AUTHOR, port, getpid()); session = ssh_new (); sshbind = ssh_bind_new (); ssh_bind_options_set (sshbind, SSH_BIND_OPTIONS_BINDADDR, bindaddr); ssh_bind_options_set (sshbind, SSH_BIND_OPTIONS_BINDPORT, &port); ssh_bind_options_set (sshbind, SSH_BIND_OPTIONS_BANNER, banner); ssh_bind_options_set (sshbind, SSH_BIND_OPTIONS_RSAKEY, rsakey); if (ssh_bind_listen (sshbind) < 0) { if (daemonize) printf ("FATAL: ssh_bind_listen(): %s\n", ssh_get_error (sshbind)); log_entry_fatal ("FATAL: ssh_bind_listen(): %s", ssh_get_error (sshbind)); } /* drop privileges */ if (username != NULL) drop_privileges (username); for (;;) { if (ssh_bind_accept (sshbind, session) == SSH_ERROR) log_entry_fatal ("FATAL: ssh_bind_accept(): %s", ssh_get_error (sshbind)); child = fork(); if (child < 0) log_entry_fatal ("FATAL: fork(): %s", strerror (errno)); if (child == 0) exit (handle_ssh_auth (session)); } return EXIT_SUCCESS; }
2.015625
2
2024-11-18T19:35:11.061282+00:00
2020-12-10T06:43:23
4307f09426a07dd534da48709a46515829e2d641
{ "blob_id": "4307f09426a07dd534da48709a46515829e2d641", "branch_name": "refs/heads/master", "committer_date": "2020-12-10T06:43:23", "content_id": "b7ee7fe5feb4f616fdaa01c16ec6866eee4ae620", "detected_licenses": [ "Apache-2.0" ], "directory_id": "b7c423c12fd7ab29b7ac999c33d735969d88f54f", "extension": "c", "filename": "LongNumbers.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 120308957, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3498, "license": "Apache-2.0", "license_type": "permissive", "path": "/semester 1/task12/long/LongNumbers.c", "provenance": "stackv2-0054.json.gz:11652", "repo_name": "DolgopolovaMaria/Software-Engineering-SPBU", "revision_date": "2020-12-10T06:43:23", "revision_id": "3f71d69d98cf713c87c67721a58c777501df1efe", "snapshot_id": "f2cae6caf8de0d0818cc48beb6edecd96fe1959e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/DolgopolovaMaria/Software-Engineering-SPBU/3f71d69d98cf713c87c67721a58c777501df1efe/semester 1/task12/long/LongNumbers.c", "visit_date": "2021-05-04T13:11:16.243348" }
stackv2
#include <stdlib.h> #include <stdio.h> #include "LongNumbers.h" typedef struct longNumber { int numberOfDigits; int *numberInArray; } longNumber; longNumber *createLongNumberFromInt(int intNumber) { longNumber *number = malloc(sizeof(longNumber)); int tempArray[5]; int numberOfDigits = 0; while (intNumber / 16 > 0) { tempArray[numberOfDigits] = intNumber % 16; intNumber = intNumber / 16; numberOfDigits++; } tempArray[numberOfDigits] = intNumber; numberOfDigits++; number->numberInArray = malloc(numberOfDigits * sizeof(int*)); for (int i = 0; i < numberOfDigits; i++) { number->numberInArray[i] = tempArray[i]; } number->numberOfDigits = numberOfDigits; return number; } longNumber *buildLongNumber(int length) { longNumber *number = malloc(sizeof(longNumber)); number->numberInArray = malloc(length * sizeof(int*)); for (int i = 0; i < length; i++) { number->numberInArray[i] = 0; } number->numberOfDigits = length; } char convertNumberTo16(int number) { switch (number) { case 10: { return 'A'; } case 11: { return 'B'; } case 12: { return 'C'; } case 13: { return 'D'; } case 14: { return 'E'; } case 15: { return 'F'; } default: { return number + '0'; } } } void printNumber(longNumber *number) { for (int i = realLength(number) - 1; i >= 0; i--) { printf("%c", convertNumberTo16(number->numberInArray[i])); } } void deleteNumber(longNumber **number) { if (*number == NULL) { return; } free((*number)->numberInArray); free(*number); } int realLength(longNumber *number) { if (number->numberInArray[number->numberOfDigits - 1] == 0) { return number->numberOfDigits - 1; } return number->numberOfDigits; } longNumber *addition(longNumber *first, longNumber *second) { longNumber *max; longNumber *min; if (realLength(first) > realLength(second)) { max = first; min = second; } else { max = second; min = first; } longNumber *result = buildLongNumber(realLength(max) + 1); int carry = 0; for (int i = 0; i < realLength(min); i++) { result->numberInArray[i] = (first->numberInArray[i] + second->numberInArray[i] + carry) % 16; carry = (first->numberInArray[i] + second->numberInArray[i] + carry) / 16; } for (int i = realLength(min); i < realLength(max); i++) { result->numberInArray[i] = (max->numberInArray[i] + carry) % 16; carry = (max->numberInArray[i] + carry) / 16; } result->numberInArray[realLength(max)] = carry; return result; } longNumber *multiplication(longNumber *first, longNumber *second) { longNumber *result = buildLongNumber(realLength(first) + realLength(second)); for (int j = 0; j < realLength(second); j++) { int carry = 0; for (int i = 0; i < realLength(first); i++) { int t = first->numberInArray[i] * second->numberInArray[j] + carry + result->numberInArray[i + j]; result->numberInArray[i + j] = t % 16; carry = t / 16; } result->numberInArray[j + realLength(first)] = carry; } return result; } longNumber *raiseToPower(longNumber *number, int power) { if (power == 0) { longNumber *res = createLongNumberFromInt(1); return res; } if (power % 2 == 1) { longNumber *first = raiseToPower(number, power - 1); longNumber *second = number; longNumber *res = multiplication(first, second); deleteNumber(&first); return res; } else { longNumber *first = raiseToPower(number, power / 2); longNumber *res = multiplication(first, first); deleteNumber(&first); return res; } }
3.578125
4
2024-11-18T19:35:11.793137+00:00
2023-08-15T12:51:41
6f8d925bc49219db976bf042def1a051b7034a4d
{ "blob_id": "6f8d925bc49219db976bf042def1a051b7034a4d", "branch_name": "refs/heads/master", "committer_date": "2023-08-15T12:51:41", "content_id": "8636343c7b5bbf59f1fc45ccb4761f30f6ac7c17", "detected_licenses": [ "MIT", "BSD-2-Clause" ], "directory_id": "a66c41243e165d0f605009c90853ca66fb650a8f", "extension": "c", "filename": "m_thread_rwlock_emu.c", "fork_events_count": 8, "gha_created_at": "2017-09-02T13:45:31", "gha_event_created_at": "2023-07-26T18:52:05", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 102199447, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5202, "license": "MIT,BSD-2-Clause", "license_type": "permissive", "path": "/thread/m_thread_rwlock_emu.c", "provenance": "stackv2-0054.json.gz:12164", "repo_name": "Monetra/mstdlib", "revision_date": "2023-08-15T12:51:41", "revision_id": "d6f2f9ec70f69885a19f7c9d8eb99196d4a42f7b", "snapshot_id": "28b1e83279906d4ec173ba86d3c66aee2c8418de", "src_encoding": "UTF-8", "star_events_count": 34, "url": "https://raw.githubusercontent.com/Monetra/mstdlib/d6f2f9ec70f69885a19f7c9d8eb99196d4a42f7b/thread/m_thread_rwlock_emu.c", "visit_date": "2023-09-05T09:40:59.408236" }
stackv2
/* The MIT License (MIT) * * Copyright (c) 2015 Monetra Technologies, LLC. * * 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 "m_config.h" #include <mstdlib/mstdlib_thread.h> #include "m_thread_int.h" /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ struct M_thread_rwlock { M_thread_mutex_t *mutex; M_thread_cond_t *rd_cond; /* readers wait on this CV */ M_thread_cond_t *wr_cond; /* writers wait on this CV */ ssize_t lockcnt; /* lock count of RW lock >0 read locks == 0 no locks < 0 wr locks */ size_t num_rd; /* number of readers waiting for RW lock */ size_t num_wr; /* number of writers waiting for RW lock */ }; /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ static void M_thread_rwlock_emu_lock_read(M_thread_rwlock_t *rwlock) { M_thread_mutex_lock(rwlock->mutex); /* if write lock, or writer waiting on lock, * wait for the writer to complete and send a signal * to resume operations ... not forgetting to let * the writer know a reader is waiting */ while (rwlock->lockcnt < 0 || rwlock->num_wr > 0) { /* increment so that writer knows reader is waiting */ rwlock->num_rd++; /* cond_wait unlocks the mutex, and waits until a condition on * rd_cond occurs, then relocks the mutex */ M_thread_cond_wait(rwlock->rd_cond, rwlock->mutex); /* decrement, we're no longer waiting */ rwlock->num_rd--; } /* increment, positive number suggests read locks */ rwlock->lockcnt++; M_thread_mutex_unlock(rwlock->mutex); } static void M_thread_rwlock_emu_lock_write(M_thread_rwlock_t *rwlock) { M_thread_mutex_lock(rwlock->mutex); /* If there are locks, wait until a signal (condition) is * sent, and not forget to mark a writer as waiting */ while (rwlock->lockcnt != 0) { rwlock->num_wr++; M_thread_cond_wait(rwlock->wr_cond, rwlock->mutex); rwlock->num_wr--; } /* < 0 is wr lock */ rwlock->lockcnt = -1; M_thread_mutex_unlock(rwlock->mutex); } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ M_thread_rwlock_t *M_thread_rwlock_emu_create(void) { M_thread_rwlock_t *rwlock; rwlock = M_malloc_zero(sizeof(*rwlock)); rwlock->mutex = M_thread_mutex_create(M_THREAD_MUTEXATTR_NONE); rwlock->rd_cond = M_thread_cond_create(M_THREAD_CONDATTR_NONE); rwlock->wr_cond = M_thread_cond_create(M_THREAD_CONDATTR_NONE); return rwlock; } void M_thread_rwlock_emu_destroy(M_thread_rwlock_t *rwlock) { if (rwlock == NULL) return; M_thread_mutex_destroy(rwlock->mutex); M_thread_cond_destroy(rwlock->rd_cond); M_thread_cond_destroy(rwlock->wr_cond); M_free(rwlock); } M_bool M_thread_rwlock_emu_lock(M_thread_rwlock_t *rwlock, M_thread_rwlock_type_t type) { if (rwlock == NULL) return M_FALSE; if (type == M_THREAD_RWLOCK_TYPE_READ) { M_thread_rwlock_emu_lock_read(rwlock); } else { M_thread_rwlock_emu_lock_write(rwlock); } return M_TRUE; } M_bool M_thread_rwlock_emu_unlock(M_thread_rwlock_t *rwlock) { size_t num_wr = 0; size_t num_rd = 0; ssize_t lockcnt; if (rwlock == NULL) return M_FALSE; M_thread_mutex_lock(rwlock->mutex); lockcnt = rwlock->lockcnt; if (lockcnt > 0) { /* Read locks decrement this when unlocking */ rwlock->lockcnt--; /* last reader releasing lock */ if (rwlock->lockcnt == 0) { /* number of waiting writers */ num_wr = rwlock->num_wr; } M_thread_mutex_unlock(rwlock->mutex); /* If writers are waiting send a signal to the next writer in line */ if (num_wr > 0) { M_thread_cond_signal(rwlock->wr_cond); } } else if (lockcnt < 0) { /* Since only one writer can hold a lock, set it to unlocked */ rwlock->lockcnt = 0; num_rd = rwlock->num_rd; num_wr = rwlock->num_wr; M_thread_mutex_unlock(rwlock->mutex); /* if there is another writer waiting, wake up the next one */ if (num_wr > 0) { M_thread_cond_signal(rwlock->wr_cond); } else if (num_rd > 0) { /* otherwise, if there are readers waiting, wake THEM ALL up */ M_thread_cond_broadcast(rwlock->rd_cond); } } return M_TRUE; }
2.296875
2
2024-11-18T19:35:11.926631+00:00
2022-05-26T14:19:16
80e5d6e7157fa188f8ffdee6c51c0966da35c9ff
{ "blob_id": "80e5d6e7157fa188f8ffdee6c51c0966da35c9ff", "branch_name": "refs/heads/master", "committer_date": "2022-05-26T14:19:16", "content_id": "506c82b5eb0364f14c878888cf4251b533ce44c2", "detected_licenses": [ "Apache-2.0", "NICTA-1.0", "BSD-3-Clause" ], "directory_id": "e6f7d3402de55ea950e0cadc9f477a92d718523a", "extension": "c", "filename": "PosixCompat.c", "fork_events_count": 79, "gha_created_at": "2016-01-23T15:10:40", "gha_event_created_at": "2022-11-03T23:57:16", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 50243508, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3261, "license": "Apache-2.0,NICTA-1.0,BSD-3-Clause", "license_type": "permissive", "path": "/dnssd/src/main/jni/mdnsresponder/mDNSWindows/PosixCompat.c", "provenance": "stackv2-0054.json.gz:12292", "repo_name": "andriydruk/RxDNSSD", "revision_date": "2022-05-26T14:19:16", "revision_id": "f50c5680ce94e662d4bae4e19bfeaea15d1eaa8e", "snapshot_id": "5b588dee44a3da8858ad64199e80b2db8319be0e", "src_encoding": "UTF-8", "star_events_count": 290, "url": "https://raw.githubusercontent.com/andriydruk/RxDNSSD/f50c5680ce94e662d4bae4e19bfeaea15d1eaa8e/dnssd/src/main/jni/mdnsresponder/mDNSWindows/PosixCompat.c", "visit_date": "2022-06-24T02:40:27.630247" }
stackv2
/* -*- Mode: C; tab-width: 4 -*- * * Copyright (c) 1997-2004 Apple Computer, Inc. All rights reserved. * * 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 "PosixCompat.h" #include <DebugServices.h> typedef PCHAR (WINAPI * if_indextoname_funcptr_t)(ULONG index, PCHAR name); typedef ULONG (WINAPI * if_nametoindex_funcptr_t)(PCSTR name); unsigned if_nametoindex( const char * ifname ) { HMODULE library; unsigned index = 0; check( ifname ); // Try and load the IP helper library dll if ((library = LoadLibrary(TEXT("Iphlpapi")) ) != NULL ) { if_nametoindex_funcptr_t if_nametoindex_funcptr; // On Vista and above there is a Posix like implementation of if_nametoindex if ((if_nametoindex_funcptr = (if_nametoindex_funcptr_t) GetProcAddress(library, "if_nametoindex")) != NULL ) { index = if_nametoindex_funcptr(ifname); } FreeLibrary(library); } return index; } char* if_indextoname( unsigned ifindex, char * ifname ) { HMODULE library; char * name = NULL; check( ifname ); *ifname = '\0'; // Try and load the IP helper library dll if ((library = LoadLibrary(TEXT("Iphlpapi")) ) != NULL ) { if_indextoname_funcptr_t if_indextoname_funcptr; // On Vista and above there is a Posix like implementation of if_indextoname if ((if_indextoname_funcptr = (if_indextoname_funcptr_t) GetProcAddress(library, "if_indextoname")) != NULL ) { name = if_indextoname_funcptr(ifindex, ifname); } FreeLibrary(library); } return name; } int inet_pton( int family, const char * addr, void * dst ) { struct sockaddr_storage ss; int sslen = sizeof( ss ); ZeroMemory( &ss, sizeof( ss ) ); ss.ss_family = family; if ( WSAStringToAddressA( ( LPSTR ) addr, family, NULL, ( struct sockaddr* ) &ss, &sslen ) == 0 ) { if ( family == AF_INET ) { memcpy( dst, &( ( struct sockaddr_in* ) &ss)->sin_addr, sizeof( IN_ADDR ) ); return 1; } else if ( family == AF_INET6 ) { memcpy( dst, &( ( struct sockaddr_in6* ) &ss)->sin6_addr, sizeof( IN6_ADDR ) ); return 1; } else return 0; } else return 0; } int gettimeofday( struct timeval * tv, struct timezone * tz ) { #define EPOCHFILETIME (116444736000000000i64) if ( tv != NULL ) { FILETIME ft; LARGE_INTEGER li; __int64 t; GetSystemTimeAsFileTime(&ft); li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; t = li.QuadPart; /* In 100-nanosecond intervals */ t -= EPOCHFILETIME; /* Offset to the Epoch time */ t /= 10; /* In microseconds */ tv->tv_sec = ( long )( t / 1000000 ); tv->tv_usec = ( long )( t % 1000000 ); } return 0; } extern struct tm* localtime_r( const time_t * clock, struct tm * result ) { localtime_s( result, clock ); return result; }
2.0625
2
2024-11-18T19:35:11.999937+00:00
2022-07-02T11:17:44
e5e2bea8a5cfff1eecb52508c708f55ac8db0eb4
{ "blob_id": "e5e2bea8a5cfff1eecb52508c708f55ac8db0eb4", "branch_name": "refs/heads/master", "committer_date": "2022-07-02T11:17:44", "content_id": "575c485a5509228bfc69e584348f004b9af2e5ea", "detected_licenses": [ "Unlicense" ], "directory_id": "03b2c80dbc41e904b167d504666e27d798da5447", "extension": "c", "filename": "intern.c", "fork_events_count": 12, "gha_created_at": "2019-02-22T03:11:34", "gha_event_created_at": "2023-03-11T01:36:37", "gha_language": "C", "gha_license_id": "Unlicense", "github_id": 171985905, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3353, "license": "Unlicense", "license_type": "permissive", "path": "/src/intern.c", "provenance": "stackv2-0054.json.gz:12420", "repo_name": "nptcl/npt", "revision_date": "2022-07-02T11:17:44", "revision_id": "aa714a2370ac9fa5348c2fc96159b40b9de3de07", "snapshot_id": "7c1570b497cdce0b8971cb445fbc04cb500232d3", "src_encoding": "UTF-8", "star_events_count": 160, "url": "https://raw.githubusercontent.com/nptcl/npt/aa714a2370ac9fa5348c2fc96159b40b9de3de07/src/intern.c", "visit_date": "2023-03-20T09:13:54.669118" }
stackv2
#include "constant.h" #include "condition.h" #include "define.h" #include "hashtable.h" #include "package.h" #include "package_bittype.h" #include "package_export.h" #include "package_intern.h" #include "package_object.h" #include "strvect.h" #include "sxhash.h" #include "symbol.h" enum symbol_package { COMMON, KEYWORD, SYSTEM, CODE, CLOS, RT, DEFAULT }; struct symbol_header { constindex index; enum symbol_package package; const char *symbol; size_t length; fixnum sxhash; int specialp; int exportp; int findp; }; static struct symbol_header SymbolHeader[] = { #ifdef LISP_64BIT #include "intern_symbol_64.h" #else #include "intern_symbol_32.h" #endif { CONSTANT_EMPTY, DEFAULT, NULL, 0, 0, 0, 0, 0 } }; static int intern_symbol_package_(addr package, struct symbol_header *str, addr *ret) { addr name, value, car, cdr; size_t size, index; /* bitpackage */ Check(! packagep(package), "type error"); Return(strvect_size1_heap_(&name, str->symbol, str->length)); if (str->findp) return intern_package_(package, name, ret, NULL); #ifdef LISP_DEBUG { enum PACKAGE_TYPE debug; addr ignore; Error(find_symbol_package_(package, name, &ignore, &debug)); Check(debug != PACKAGE_TYPE_NIL, "find error"); } #endif make_bitpackage_symbol(&value, ret, name, package); #ifdef LISP_DEBUG { fixnum debug; Error(sxhash_char_equal_(str->symbol, &debug)); Check(debug != str->sxhash, "sxhash error"); } #endif /* intern */ GetPackage(package, PACKAGE_INDEX_TABLE, &package); getsize_hashtable(package, &size); inccount_hashtable(package, 1); GetTableHash(package, &package); /* array[index] -> ((key . nil) . next) * ret -> (key . nil) */ index = str->sxhash % size; GetArrayHash(package, index, &cdr); cons_heap(&car, name, value); cons_heap(&cdr, car, cdr); SetArrayHash(package, index, cdr); return 0; } int intern_symbol_header_(void) { addr symbol, p_common, p_keyword, p_system, p_code, p_clos, p_rt, package; struct symbol_header *table; size_t i; GetConst(PACKAGE_COMMON_LISP, &p_common); GetConst(PACKAGE_KEYWORD, &p_keyword); GetConst(PACKAGE_SYSTEM, &p_system); GetConst(PACKAGE_CODE, &p_code); GetConst(PACKAGE_CLOS, &p_clos); GetConst(PACKAGE_RT, &p_rt); for (i = 0; ; i++) { table = &SymbolHeader[i]; if (table->index == CONSTANT_EMPTY) break; switch (table->package) { case COMMON: package = p_common; Return(intern_symbol_package_(package, table, &symbol)); Return(symbol_export_package_(package, symbol)); break; case KEYWORD: package = p_keyword; Return(intern_symbol_package_(package, table, &symbol)); Return(setkeyword_package_(symbol)); break; case SYSTEM: package = p_system; Return(intern_symbol_package_(package, table, &symbol)); break; case CODE: package = p_code; Return(intern_symbol_package_(package, table, &symbol)); break; case CLOS: package = p_clos; Return(intern_symbol_package_(package, table, &symbol)); break; case RT: package = p_rt; Return(intern_symbol_package_(package, table, &symbol)); break; default: return fmte_("package error.", NULL); } if (table->specialp) setspecial_symbol(symbol); if (table->exportp) { Return(export_package_(package, symbol)); } SetConstant(table->index, symbol); } return 0; }
2.125
2
2024-11-18T19:35:12.261524+00:00
2023-04-07T22:19:18
94bf46bbfba899ecf13468f53357f46525c080fa
{ "blob_id": "94bf46bbfba899ecf13468f53357f46525c080fa", "branch_name": "refs/heads/main", "committer_date": "2023-04-07T22:19:18", "content_id": "ff6cbbd68c55ec64f72b5e3b4edafe60de42ff69", "detected_licenses": [], "directory_id": "3cd3872acbc8b1a79a70b89b2fd58a171e7adc82", "extension": "c", "filename": "bilinear_filter_sse2.c", "fork_events_count": 376, "gha_created_at": "2014-08-13T19:03:21", "gha_event_created_at": "2023-03-24T13:37:34", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 22927608, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12445, "license": "", "license_type": "permissive", "path": "/vp8/common/x86/bilinear_filter_sse2.c", "provenance": "stackv2-0054.json.gz:12677", "repo_name": "webmproject/libvpx", "revision_date": "2023-04-07T22:19:18", "revision_id": "6fd360c684736e351160b131827dfbb207841164", "snapshot_id": "58ab97861063cb521ec0d00ef9cb222ca97873b1", "src_encoding": "UTF-8", "star_events_count": 889, "url": "https://raw.githubusercontent.com/webmproject/libvpx/6fd360c684736e351160b131827dfbb207841164/vp8/common/x86/bilinear_filter_sse2.c", "visit_date": "2023-04-09T15:32:34.688724" }
stackv2
/* * Copyright (c) 2018 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <assert.h> #include <xmmintrin.h> #include "./vp8_rtcd.h" #include "./vpx_config.h" #include "vp8/common/filter.h" #include "vpx_dsp/x86/mem_sse2.h" #include "vpx_ports/mem.h" static INLINE void horizontal_16x16(uint8_t *src, const int stride, uint16_t *dst, const int xoffset) { int h; const __m128i zero = _mm_setzero_si128(); if (xoffset == 0) { for (h = 0; h < 17; ++h) { const __m128i a = _mm_loadu_si128((__m128i *)src); const __m128i a_lo = _mm_unpacklo_epi8(a, zero); const __m128i a_hi = _mm_unpackhi_epi8(a, zero); _mm_store_si128((__m128i *)dst, a_lo); _mm_store_si128((__m128i *)(dst + 8), a_hi); src += stride; dst += 16; } return; } { const __m128i round_factor = _mm_set1_epi16(1 << (VP8_FILTER_SHIFT - 1)); const __m128i hfilter_0 = _mm_set1_epi16(vp8_bilinear_filters[xoffset][0]); const __m128i hfilter_1 = _mm_set1_epi16(vp8_bilinear_filters[xoffset][1]); for (h = 0; h < 17; ++h) { const __m128i a = _mm_loadu_si128((__m128i *)src); const __m128i a_lo = _mm_unpacklo_epi8(a, zero); const __m128i a_hi = _mm_unpackhi_epi8(a, zero); const __m128i a_lo_filtered = _mm_mullo_epi16(a_lo, hfilter_0); const __m128i a_hi_filtered = _mm_mullo_epi16(a_hi, hfilter_0); const __m128i b = _mm_loadu_si128((__m128i *)(src + 1)); const __m128i b_lo = _mm_unpacklo_epi8(b, zero); const __m128i b_hi = _mm_unpackhi_epi8(b, zero); const __m128i b_lo_filtered = _mm_mullo_epi16(b_lo, hfilter_1); const __m128i b_hi_filtered = _mm_mullo_epi16(b_hi, hfilter_1); const __m128i sum_lo = _mm_add_epi16(a_lo_filtered, b_lo_filtered); const __m128i sum_hi = _mm_add_epi16(a_hi_filtered, b_hi_filtered); const __m128i compensated_lo = _mm_add_epi16(sum_lo, round_factor); const __m128i compensated_hi = _mm_add_epi16(sum_hi, round_factor); const __m128i shifted_lo = _mm_srai_epi16(compensated_lo, VP8_FILTER_SHIFT); const __m128i shifted_hi = _mm_srai_epi16(compensated_hi, VP8_FILTER_SHIFT); _mm_store_si128((__m128i *)dst, shifted_lo); _mm_store_si128((__m128i *)(dst + 8), shifted_hi); src += stride; dst += 16; } } } static INLINE void vertical_16x16(uint16_t *src, uint8_t *dst, const int stride, const int yoffset) { int h; if (yoffset == 0) { for (h = 0; h < 16; ++h) { const __m128i row_lo = _mm_load_si128((__m128i *)src); const __m128i row_hi = _mm_load_si128((__m128i *)(src + 8)); const __m128i packed = _mm_packus_epi16(row_lo, row_hi); _mm_store_si128((__m128i *)dst, packed); src += 16; dst += stride; } return; } { const __m128i round_factor = _mm_set1_epi16(1 << (VP8_FILTER_SHIFT - 1)); const __m128i vfilter_0 = _mm_set1_epi16(vp8_bilinear_filters[yoffset][0]); const __m128i vfilter_1 = _mm_set1_epi16(vp8_bilinear_filters[yoffset][1]); __m128i row_0_lo = _mm_load_si128((__m128i *)src); __m128i row_0_hi = _mm_load_si128((__m128i *)(src + 8)); src += 16; for (h = 0; h < 16; ++h) { const __m128i row_0_lo_filtered = _mm_mullo_epi16(row_0_lo, vfilter_0); const __m128i row_0_hi_filtered = _mm_mullo_epi16(row_0_hi, vfilter_0); const __m128i row_1_lo = _mm_load_si128((__m128i *)src); const __m128i row_1_hi = _mm_load_si128((__m128i *)(src + 8)); const __m128i row_1_lo_filtered = _mm_mullo_epi16(row_1_lo, vfilter_1); const __m128i row_1_hi_filtered = _mm_mullo_epi16(row_1_hi, vfilter_1); const __m128i sum_lo = _mm_add_epi16(row_0_lo_filtered, row_1_lo_filtered); const __m128i sum_hi = _mm_add_epi16(row_0_hi_filtered, row_1_hi_filtered); const __m128i compensated_lo = _mm_add_epi16(sum_lo, round_factor); const __m128i compensated_hi = _mm_add_epi16(sum_hi, round_factor); const __m128i shifted_lo = _mm_srai_epi16(compensated_lo, VP8_FILTER_SHIFT); const __m128i shifted_hi = _mm_srai_epi16(compensated_hi, VP8_FILTER_SHIFT); const __m128i packed = _mm_packus_epi16(shifted_lo, shifted_hi); _mm_store_si128((__m128i *)dst, packed); row_0_lo = row_1_lo; row_0_hi = row_1_hi; src += 16; dst += stride; } } } void vp8_bilinear_predict16x16_sse2(uint8_t *src_ptr, int src_pixels_per_line, int xoffset, int yoffset, uint8_t *dst_ptr, int dst_pitch) { DECLARE_ALIGNED(16, uint16_t, FData[16 * 17]); assert((xoffset | yoffset) != 0); horizontal_16x16(src_ptr, src_pixels_per_line, FData, xoffset); vertical_16x16(FData, dst_ptr, dst_pitch, yoffset); } static INLINE void horizontal_8xN(uint8_t *src, const int stride, uint16_t *dst, const int xoffset, const int height) { int h; const __m128i zero = _mm_setzero_si128(); if (xoffset == 0) { for (h = 0; h < height; ++h) { const __m128i a = _mm_loadl_epi64((__m128i *)src); const __m128i a_u16 = _mm_unpacklo_epi8(a, zero); _mm_store_si128((__m128i *)dst, a_u16); src += stride; dst += 8; } return; } { const __m128i round_factor = _mm_set1_epi16(1 << (VP8_FILTER_SHIFT - 1)); const __m128i hfilter_0 = _mm_set1_epi16(vp8_bilinear_filters[xoffset][0]); const __m128i hfilter_1 = _mm_set1_epi16(vp8_bilinear_filters[xoffset][1]); // Filter horizontally. Rather than load the whole array and transpose, load // 16 values (overreading) and shift to set up the second value. Do an // "extra" 9th line so the vertical pass has the necessary context. for (h = 0; h < height; ++h) { const __m128i a = _mm_loadu_si128((__m128i *)src); const __m128i b = _mm_srli_si128(a, 1); const __m128i a_u16 = _mm_unpacklo_epi8(a, zero); const __m128i b_u16 = _mm_unpacklo_epi8(b, zero); const __m128i a_filtered = _mm_mullo_epi16(a_u16, hfilter_0); const __m128i b_filtered = _mm_mullo_epi16(b_u16, hfilter_1); const __m128i sum = _mm_add_epi16(a_filtered, b_filtered); const __m128i compensated = _mm_add_epi16(sum, round_factor); const __m128i shifted = _mm_srai_epi16(compensated, VP8_FILTER_SHIFT); _mm_store_si128((__m128i *)dst, shifted); src += stride; dst += 8; } } } static INLINE void vertical_8xN(uint16_t *src, uint8_t *dst, const int stride, const int yoffset, const int height) { int h; if (yoffset == 0) { for (h = 0; h < height; ++h) { const __m128i row = _mm_load_si128((__m128i *)src); const __m128i packed = _mm_packus_epi16(row, row); _mm_storel_epi64((__m128i *)dst, packed); src += 8; dst += stride; } return; } { const __m128i round_factor = _mm_set1_epi16(1 << (VP8_FILTER_SHIFT - 1)); const __m128i vfilter_0 = _mm_set1_epi16(vp8_bilinear_filters[yoffset][0]); const __m128i vfilter_1 = _mm_set1_epi16(vp8_bilinear_filters[yoffset][1]); __m128i row_0 = _mm_load_si128((__m128i *)src); src += 8; for (h = 0; h < height; ++h) { const __m128i row_1 = _mm_load_si128((__m128i *)src); const __m128i row_0_filtered = _mm_mullo_epi16(row_0, vfilter_0); const __m128i row_1_filtered = _mm_mullo_epi16(row_1, vfilter_1); const __m128i sum = _mm_add_epi16(row_0_filtered, row_1_filtered); const __m128i compensated = _mm_add_epi16(sum, round_factor); const __m128i shifted = _mm_srai_epi16(compensated, VP8_FILTER_SHIFT); const __m128i packed = _mm_packus_epi16(shifted, shifted); _mm_storel_epi64((__m128i *)dst, packed); row_0 = row_1; src += 8; dst += stride; } } } void vp8_bilinear_predict8x8_sse2(uint8_t *src_ptr, int src_pixels_per_line, int xoffset, int yoffset, uint8_t *dst_ptr, int dst_pitch) { DECLARE_ALIGNED(16, uint16_t, FData[8 * 9]); assert((xoffset | yoffset) != 0); horizontal_8xN(src_ptr, src_pixels_per_line, FData, xoffset, 9); vertical_8xN(FData, dst_ptr, dst_pitch, yoffset, 8); } void vp8_bilinear_predict8x4_sse2(uint8_t *src_ptr, int src_pixels_per_line, int xoffset, int yoffset, uint8_t *dst_ptr, int dst_pitch) { DECLARE_ALIGNED(16, uint16_t, FData[8 * 5]); assert((xoffset | yoffset) != 0); horizontal_8xN(src_ptr, src_pixels_per_line, FData, xoffset, 5); vertical_8xN(FData, dst_ptr, dst_pitch, yoffset, 4); } static INLINE void horizontal_4x4(uint8_t *src, const int stride, uint16_t *dst, const int xoffset) { int h; const __m128i zero = _mm_setzero_si128(); if (xoffset == 0) { for (h = 0; h < 5; ++h) { const __m128i a = load_unaligned_u32(src); const __m128i a_u16 = _mm_unpacklo_epi8(a, zero); _mm_storel_epi64((__m128i *)dst, a_u16); src += stride; dst += 4; } return; } { const __m128i round_factor = _mm_set1_epi16(1 << (VP8_FILTER_SHIFT - 1)); const __m128i hfilter_0 = _mm_set1_epi16(vp8_bilinear_filters[xoffset][0]); const __m128i hfilter_1 = _mm_set1_epi16(vp8_bilinear_filters[xoffset][1]); for (h = 0; h < 5; ++h) { const __m128i a = load_unaligned_u32(src); const __m128i b = load_unaligned_u32(src + 1); const __m128i a_u16 = _mm_unpacklo_epi8(a, zero); const __m128i b_u16 = _mm_unpacklo_epi8(b, zero); const __m128i a_filtered = _mm_mullo_epi16(a_u16, hfilter_0); const __m128i b_filtered = _mm_mullo_epi16(b_u16, hfilter_1); const __m128i sum = _mm_add_epi16(a_filtered, b_filtered); const __m128i compensated = _mm_add_epi16(sum, round_factor); const __m128i shifted = _mm_srai_epi16(compensated, VP8_FILTER_SHIFT); _mm_storel_epi64((__m128i *)dst, shifted); src += stride; dst += 4; } } } static INLINE void vertical_4x4(uint16_t *src, uint8_t *dst, const int stride, const int yoffset) { int h; if (yoffset == 0) { for (h = 0; h < 4; h += 2) { const __m128i row = _mm_load_si128((__m128i *)src); __m128i packed = _mm_packus_epi16(row, row); store_unaligned_u32(dst, packed); dst += stride; packed = _mm_srli_si128(packed, 4); store_unaligned_u32(dst, packed); dst += stride; src += 8; } return; } { const __m128i round_factor = _mm_set1_epi16(1 << (VP8_FILTER_SHIFT - 1)); const __m128i vfilter_0 = _mm_set1_epi16(vp8_bilinear_filters[yoffset][0]); const __m128i vfilter_1 = _mm_set1_epi16(vp8_bilinear_filters[yoffset][1]); for (h = 0; h < 4; h += 2) { const __m128i row_0 = _mm_load_si128((__m128i *)src); const __m128i row_1 = _mm_loadu_si128((__m128i *)(src + 4)); const __m128i row_0_filtered = _mm_mullo_epi16(row_0, vfilter_0); const __m128i row_1_filtered = _mm_mullo_epi16(row_1, vfilter_1); const __m128i sum = _mm_add_epi16(row_0_filtered, row_1_filtered); const __m128i compensated = _mm_add_epi16(sum, round_factor); const __m128i shifted = _mm_srai_epi16(compensated, VP8_FILTER_SHIFT); __m128i packed = _mm_packus_epi16(shifted, shifted); storeu_int32(dst, _mm_cvtsi128_si32(packed)); packed = _mm_srli_si128(packed, 4); dst += stride; storeu_int32(dst, _mm_cvtsi128_si32(packed)); dst += stride; src += 8; } } } void vp8_bilinear_predict4x4_sse2(uint8_t *src_ptr, int src_pixels_per_line, int xoffset, int yoffset, uint8_t *dst_ptr, int dst_pitch) { DECLARE_ALIGNED(16, uint16_t, FData[4 * 5]); assert((xoffset | yoffset) != 0); horizontal_4x4(src_ptr, src_pixels_per_line, FData, xoffset); vertical_4x4(FData, dst_ptr, dst_pitch, yoffset); }
2.046875
2
2024-11-18T19:35:12.439400+00:00
2010-11-10T14:40:36
89e4aca7c25afc2c9b2eb0db8ab226984800c321
{ "blob_id": "89e4aca7c25afc2c9b2eb0db8ab226984800c321", "branch_name": "refs/heads/master", "committer_date": "2010-11-10T14:40:36", "content_id": "217d2e1285619b50dc6dd0967d6ed0ad47555072", "detected_licenses": [ "Python-2.0" ], "directory_id": "94de77f95a0a7b4054d33bf5d235fd69572fcec7", "extension": "h", "filename": "xaut.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 1068281, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5766, "license": "Python-2.0", "license_type": "permissive", "path": "/src/xaut.h", "provenance": "stackv2-0054.json.gz:12806", "repo_name": "rofl0r/libxauto", "revision_date": "2010-11-10T14:40:36", "revision_id": "82ef2f362da69b7705338cdab5f2c4e1fd4c505a", "snapshot_id": "7e5f181535b978700316227c63020885d17c4aaa", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/rofl0r/libxauto/82ef2f362da69b7705338cdab5f2c4e1fd4c505a/src/xaut.h", "visit_date": "2016-09-06T15:24:29.572289" }
stackv2
/*************************************************************************** * Copyright (C) 2009 by Chris Parker * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the Python License version 2.5 or later. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * ***************************************************************************/ /* $URL$ $Author$ $Date$ $Rev$ */ #ifndef XAUT_H_ #define XAUT_H_ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <X11/extensions/XTest.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <unistd.h> #include <X11/Xlib.h> #include <X11/Xatom.h> #include <limits.h> #include "xaut_types.h" #include "xaut_display.h" #include "xaut_keyboard.h" #include "xaut_mouse.h" #include "xaut_window.h" // --- Published subroutines, functions and structures /** * Releases any resources created by this code. */ void cleanup(); /** * Print information about what's going on. */ void verbose(BOOL verbose); void extra_verbose(BOOL extra_verbose); // --- End of published stuff /** * Add a code to the list of ascii codes. * @param code the ascii code to add * @param shifted does the shift key need to be down to reach this */ void _add_code(unsigned short code, BOOL shifted); /** * Checks to see if init() has been called, and calls it if not. * Will return false only if init() cannot initialize values. So * can be used as a simple test. */ BOOL _check_init(); /** * Initializes the program. */ void _initialize(); /** * Initializes the list of allowed ascii characters. * These represent any character which can be sent directly, as opposed * to requiring being sent in a brace. So it's possible to send e.g. 'A', * but not the control key. That would require "{Control_L}". * Note that the following keys have special meaning: !^+{}. Respectively * they mean "Alt_L", "Control_L", "Shift_L", and "whatever is inside * is a special key code". * Note that this has some overlap with init_keys(). */ BOOL _init_ascii(); /** * Initializes only the defaults. * The structure "defaults" is filled with values. * @return boolean indication of success. */ BOOL init_defaults(); /** * Indication of whether the requested feature is available. * Not all implementations of X11 support all possible things. * This helps keep things portable. * @param the feature to find * @return boolean indication of whether the requested feature is possible. */ BOOL _is_supported_feature(char *feature); /** * Performs screen coordinate normalization. * Normalizes the coordinates supplied so that * they are at least equal to zero, and * no greater than the maximum coordinate. * Prevents stupid things from happening if e.g. * mouse_move( 10000, 10000 ) is called. * @param x the x coordinate to normalize * @param y the y coordinate to normalize */ void _normalize_coords(int *x, int *y); /** * Performs screen coordinate normalization as regards a window. * Normalizes the coordinates such that they make sense with the * window that is identified by the window handle. For example, * if the window is at 100x100, and the coordinates supplied to mouse_move are * -10, -10, then the mouse will be moved to 90x90. If the * coordinates supplied for the same window are 10, 10, then the * mouse will be moved to 110x110. Note that if the window * handle is not valid, the coordinates will be normalized to the * whole screen using <code>normalize_coords</code>. * * Note that if the window is partially off the screen, the mouse * will move as close as possible to the desired location. The * mouse will not move off the screen. * @param x the x coordinate to normalize * @param y the y coordinate to normalize * @param win a handle to use as a reference point * @return will return FALSE if window handle passed is invalid */ BOOL _normalize_wincoords(int *x, int *y, unsigned long win); /** * Extracts a substring from a string. * <ul>Notes: * <li>You <em>must</em> release the substring when done.</li> * <li>The values for begin and end are inclusive.<li> * <li>The function will return NULL if the string parameter is NULL.</li> * <li>The function will return NULL if the string is empty.</li> * <li>The function will return NULL if the first parameter is greater * than the length of the string.</li> * <li>The end parameter will be reduced to the last character in the * string if end is greater than the end of the string.</li> * </ul> * * @param str the string * @param first the first character to extract * @param last the last character to extract * @return the substring, or null if something went wrong. */ char* _stringmid(const char *str, size_t first, size_t last); /** * Called by X in the event of an error. * X is notified that it should use this function usually just * before a user provided window handle is used. There are a * number of reasons such a call might fail. It may be that * the user closed the window, it may be that a transient * window has closed by itself. Whatever. The point * is that without an error handler, the entire program will * exit. */ int _invalid_window_error_handler(Display *dsp, XErrorEvent *err); #endif /* XAUT_H_ */
2
2
2024-11-18T19:35:12.523737+00:00
2020-06-24T20:23:45
0745d8565a1fc41024106e2158c52085c016df01
{ "blob_id": "0745d8565a1fc41024106e2158c52085c016df01", "branch_name": "refs/heads/master", "committer_date": "2020-06-24T20:23:45", "content_id": "3d325d560c8c96a58c4ba134da2320574a85f3ad", "detected_licenses": [ "MIT" ], "directory_id": "c328a34fa048911bcb20c91d8315dc6239feed73", "extension": "c", "filename": "sentinel.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": 202, "license": "MIT", "license_type": "permissive", "path": "/lecture01/01_io/sentinel.c", "provenance": "stackv2-0054.json.gz:12935", "repo_name": "agronja/cse-34872-su20-examples", "revision_date": "2020-06-24T20:23:45", "revision_id": "683039c19b2e2bd0c3c28713b73e46a9deaa227c", "snapshot_id": "1278c5928e7249fd777fd04c830b4274065f352c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/agronja/cse-34872-su20-examples/683039c19b2e2bd0c3c28713b73e46a9deaa227c/lecture01/01_io/sentinel.c", "visit_date": "2022-11-10T12:41:29.546117" }
stackv2
/* sentinel.c: sentinel */ #include <stdio.h> /* Main execution */ int main(int argc, char *argv[]) { int n; while (scanf("%d", &n) && n > 0) { printf("%d\n", n); } return 0; }
2.734375
3
2024-11-18T19:35:13.002491+00:00
2020-05-20T09:48:01
7829dedbdd3a949c0d69d27a38eb5b26df476405
{ "blob_id": "7829dedbdd3a949c0d69d27a38eb5b26df476405", "branch_name": "refs/heads/master", "committer_date": "2020-05-20T09:48:01", "content_id": "6d7cac903dbc2cf58e6c58a85bf176e425483278", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "2642abc175bf88a692c4b60cb0d88637f8a8a40d", "extension": "c", "filename": "fifo.c", "fork_events_count": 0, "gha_created_at": "2020-05-21T10:11:29", "gha_event_created_at": "2020-05-21T10:11:29", "gha_language": null, "gha_license_id": "NOASSERTION", "github_id": 265816480, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5264, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/base_code/system_programing/fifo/sources/fifo.c", "provenance": "stackv2-0054.json.gz:13449", "repo_name": "nevergo1/embed_linux_tutorial", "revision_date": "2020-05-20T09:48:01", "revision_id": "21f7938694859858b3a977a717723568d6a7fd04", "snapshot_id": "65b87c006eeb0359fb35af6dffe697856323b504", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/nevergo1/embed_linux_tutorial/21f7938694859858b3a977a717723568d6a7fd04/base_code/system_programing/fifo/sources/fifo.c", "visit_date": "2022-07-30T15:48:38.648910" }
stackv2
/**fifo.c */ /** * 无名管道,它只能用于具有亲缘关系的进程之间,这就大大地限制了管道的使用。有名管道的出现突破了这种限制, 它可以使互不相关的两个进程实现彼此通信。 * 该管道可以通过路径名来指出,并且在文件系统中是可见的。在建立了管道之后,两个进程就可以把它当作普通文件一样进行读写操作,使用非常方便。 * 不过 FIFO 是严格地遵循先进先出规则的,对管道及 FIFO 的读总是从开始处返回数据,对它们的写则把数据添加到末尾,它们不支持如 lseek()等文件定位操作。 * 有名管道的创建可以使用函数 mkfifo(),该函数类似文件中的 open()操作,可以指定管道的路径和打开的模式 * * 在创建管道成功之后,就可以使用 open()、 read()和 write()这些函数了。与普通文件的开发设置一样,对于为读而打开的管道可在 open()中设置 O_RDONLY, * 对于为写而打开的管道可在 open()中设置 O_WRONLY,在这里与普通文件不同的是阻塞问题。由于普通文件的读写时不会出现阻塞问题,而在管道的读写中却有阻塞的可能, * 这里的非阻塞标志可以在 open()函数中设定为 O_NONBLOCK。下面分别对阻塞打开和非阻塞打开的读写进行讨论。 * (1)对于读进程。 *  若该管道是阻塞打开,且当前 FIFO 内没有数据,则对读进程而言将一直阻塞到有数据写入。 *  若该管道是非阻塞打开,则不论 FIFO 内是否有数据,读进程都会立即执行读操作。即如果 FIFO内没有数据,则读函数将立刻返回 0。 * (2)对于写进程。 *  若该管道是阻塞打开,则写操作将一直阻塞到数据可以被写入。 *  若该管道是非阻塞打开而不能写入全部数据,则读操作进行部分写入或者调用失败 * * 函数原型 int mkfifo(const char *filename,mode_t mode) * 函数传入值 filename:要创建的管道名字(包含路径) * 函数传入值 mode: *  O_RDONLY:读管道 *  O_WRONLY:写管道 *  O_RDWR:读写管道 *  O_NONBLOCK:非阻塞 *  O_CREAT:如果该文件不存在,那么就创建一个新的文件,并用第三个参数为其设置权限 *  O_EXCL:如果使用 O_CREAT 时文件存在,那么可返回错误消息。这一参数可测试文件是否存在 * 函数返回值: *  0:成功 *  EACCESS:参数 filename 所指定的目录路径无可执行的权限 *  EEXIST:参数 filename 所指定的文件已存在 *  ENAMETOOLONG:参数 filename 的路径名称太长 *  ENOENT:参数 filename 包含的目录不存在 *  ENOSPC:文件系统的剩余空间不足 *  ENOTDIR:参数 filename 路径中的目录存在但却非真正的目录 *  EROFS:参数 filename 指定的文件存在于只读文件系统内 */ #include <sys/wait.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <string.h> #define MYFIFO "myfifo" /* 有名管道文件名*/ #define MAX_BUFFER_SIZE PIPE_BUF /* 4096 定义在于 limits.h 中*/ void fifo_read(void) { char buff[MAX_BUFFER_SIZE]; int fd; int nread; printf("***************** read fifo ************************\n"); /* 判断有名管道是否已存在,若尚未创建,则以相应的权限创建*/ if (access(MYFIFO, F_OK) == -1) { if ((mkfifo(MYFIFO, 0666) < 0) && (errno != EEXIST)) { printf("Cannot create fifo file\n"); exit(1); } } /* 以只读阻塞方式打开有名管道 */ fd = open(MYFIFO, O_RDONLY); if (fd == -1) { printf("Open fifo file error\n"); exit(1); } memset(buff, 0, sizeof(buff)); if ((nread = read(fd, buff, MAX_BUFFER_SIZE)) > 0) { printf("Read '%s' from FIFO\n", buff); } printf("***************** close fifo ************************\n"); close(fd); exit(0); } void write_fifo(void) { int fd; char buff[] = "this is a fifo test demo"; int nwrite; sleep(2); //等待子进程先运行 /* 以只写阻塞方式打开 FIFO 管道 */ fd = open(MYFIFO, O_WRONLY | O_CREAT, 0644); if (fd == -1) { printf("Open fifo file error\n"); exit(1); } printf("Write '%s' to FIFO\n", buff); /*向管道中写入字符串*/ nwrite = write(fd, buff, MAX_BUFFER_SIZE); if(wait(NULL)) //等待子进程退出 { close(fd); exit(0); } } int main() { pid_t result; /*调用 fork()函数*/ result = fork(); /*通过 result 的值来判断 fork()函数的返回情况,首先进行出错处理*/ if(result == -1) { printf("Fork error\n"); } else if (result == 0) /*返回值为 0 代表子进程*/ { fifo_read(); } else /*返回值大于 0 代表父进程*/ { write_fifo(); } return result; }
2.796875
3
2024-11-18T19:35:13.402642+00:00
2014-12-09T08:27:58
b9d389c742ad3b4fe91e5c61a94b6f698242fe85
{ "blob_id": "b9d389c742ad3b4fe91e5c61a94b6f698242fe85", "branch_name": "refs/heads/master", "committer_date": "2014-12-09T08:27:58", "content_id": "f4c2c858a3e7569ea80b18325efebcc59409c60b", "detected_licenses": [ "MIT" ], "directory_id": "9d6f0aee4582cc60c41720b0175ed270611f9644", "extension": "c", "filename": "transform.c", "fork_events_count": 0, "gha_created_at": "2019-03-24T11:59:28", "gha_event_created_at": "2019-03-24T11:59:28", "gha_language": null, "gha_license_id": null, "github_id": 177408636, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2435, "license": "MIT", "license_type": "permissive", "path": "/Sources-C/Programming=++Algorithms;/chapter08/transform.c", "provenance": "stackv2-0054.json.gz:13578", "repo_name": "marclayson/Algorithms-CSharp-Translation", "revision_date": "2014-12-09T08:27:58", "revision_id": "8d5f1807e5c45bd33f86840338509aa6777f99dd", "snapshot_id": "3777288900f11e057ef9aacb6d7c735111405713", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/marclayson/Algorithms-CSharp-Translation/8d5f1807e5c45bd33f86840338509aa6777f99dd/Sources-C/Programming=++Algorithms;/chapter08/transform.c", "visit_date": "2020-05-01T09:49:10.166831" }
stackv2
#include <stdio.h> #include <string.h> #define MAX 100 #define COST_DELETE 1 #define COST_INSERT 2 #define COST_REPLACE(i, j) ((s1[i] == s2[j]) ? 0 : 3) #define min2(a, b) ((a < b) ? a : b) /* Връща по-малкия от 2 аргумента */ #define min(a, b, c) min2(min2(a, b), c) /* Връща най-малкия от 3 аргумента */ unsigned F[MAX+1][MAX+1]; /* Целева функция */ unsigned n1; /* Дължина на първия низ */ unsigned n2; /* Дължина на втория низ */ const char *s1 = "_abracadabra"; /* Изходен низ (първият символ няма значение) */ const char *s2 = "_mabragabra"; /* Низ-цел (първият символ няма значение) */ /* Намира разстоянието между два низа */ unsigned editDistance(void) { unsigned i, j; /* Инициализация */ for (i = 0; i <= n1; i++) F[i][0] = i * COST_DELETE; for (j = 0; j <= n2; j++) F[0][j] = j * COST_INSERT; /* Основен цикъл */ for (i = 1; i <= n1; i++) for (j = 1; j <= n2; j++) F[i][j] = min(F[i - 1][j - 1] + COST_REPLACE(i, j), F[i][j - 1] + COST_INSERT, F[i - 1][j] + COST_DELETE); return F[n1][n2]; } /* Извежда операциите по редактирането */ void printEditOperations(unsigned i, unsigned j) { if (0 == j) for (j = 1; j <= i; j++) printf("DELETE(%u) ", j); else if (0 == i) for (i = 1; i <= j; i++) printf("INSERT(%u,%c) ", i, s2[i]); else if (i > 0 && j > 0) { if (F[i][j] == F[i - 1][j - 1] + COST_REPLACE(i, j)) { printEditOperations(i - 1, j - 1); if (COST_REPLACE(i, j) > 0) printf("REPLACE(%u,%c) ", i, s2[j]); } else if (F[i][j] == F[i][j - 1] + COST_INSERT) { printEditOperations(i, j - 1); printf("INSERT(%u,%c) ", i, s2[j]); } else if (F[i][j] == F[i - 1][j] + COST_DELETE) { printEditOperations(i - 1, j); printf("DELETE(%u) ", i); } } } int main(void) { n1 = strlen(s1) - 1; n2 = strlen(s2) - 1; printf("\nМинимално разстояние между двата низа: %u\n", editDistance()); printEditOperations(n1, n2); return 0; }
3.15625
3
2024-11-18T19:35:13.654826+00:00
2019-03-01T05:16:46
71387c9b1b83a399fac7279299caf8dadf434859
{ "blob_id": "71387c9b1b83a399fac7279299caf8dadf434859", "branch_name": "refs/heads/master", "committer_date": "2019-03-01T05:16:46", "content_id": "a887d7d4f0a3fc3f44812c5eeac74a13e4d67390", "detected_licenses": [ "MIT" ], "directory_id": "5a17a3d150c4773318d397a46878d2fd74c0671f", "extension": "c", "filename": "muwu3.c", "fork_events_count": 0, "gha_created_at": "2018-12-26T11:38:10", "gha_event_created_at": "2018-12-26T11:38:10", "gha_language": null, "gha_license_id": "MIT", "github_id": 163173406, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2149, "license": "MIT", "license_type": "permissive", "path": "/nitan/quest11/tlbb/muwu3.c", "provenance": "stackv2-0054.json.gz:13706", "repo_name": "cantona/NT6", "revision_date": "2019-03-01T05:16:46", "revision_id": "073f4d491b3cfe6bfbe02fbad12db8983c1b9201", "snapshot_id": "e9adc7308619b614990fa64456c294fad5f07d61", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cantona/NT6/073f4d491b3cfe6bfbe02fbad12db8983c1b9201/nitan/quest11/tlbb/muwu3.c", "visit_date": "2020-04-15T21:16:28.817947" }
stackv2
// cool 980725 // Modify By River 98/12 //COOL@SJ,9908 //tangfeng@SJ,2004 #include <ansi.h> #include <room.h> inherit ROOM; #define QUESTDIR1 "quest/天龍八部/凌波微步篇/" void create() { set("short", "石屋裏"); set("long", @LONG 這裏是石屋裏了,裏面黑漆漆的,什麼也看不清楚,陽光都被門口的一塊 大巖石擋住了,只能透過幾縷石縫中透過來的陽光,你打量着這間屋子。 LONG ); set("item_desc", ([ "yan" : "一塊大巖石,可以試着推開!。\n", ])); setup(); } void init() { object ob,obj; ob=this_player(); if (interactive(ob) && !present("qingnian nanzi", this_object()) && !present("duan yu",this_object()) && ob->query_temp(QUESTDIR1+"kill_duan") && ob->query(QUESTDIR1+"pass_shanlu") && !ob->query(QUESTDIR1+"over")){ obj=new(__DIR__"npc/dy"); obj->move(this_object()); } if (userp(ob)) { remove_call_out("close"); call_out("close", 2, this_object()); } add_action("do_tui", "tui"); add_action("do_tui", "push"); } int do_tui(string arg) { int i; i = this_player()->query("neili"); if( !arg || arg!="yan" ) return notify_fail("你要推什麼?\n"); message_vision(HIY"$N站在門後,把雙掌放在巖上,深深的吸了一口氣,雙臂一發勁,大喝一聲“開”。\n"NOR, this_player()); if ( i >=800 ){ message_vision(RED"$N只聽一陣轟響,大石緩緩的移開了!\n"NOR, this_player()); set("exits/out", __DIR__"muwu2"); this_player()->add("neili",-800); remove_call_out("close"); call_out("close", 5, this_object()); } else { message_vision("$N卻見大石紋絲不動,看來$N的內力還不夠。\n", this_player()); this_player()->set("neili",0); } return 1; } void close(object room) { message("vision",YEL"大石緩緩移動,把石屋再次封住了。\n"NOR, room); room->delete("exits/out"); }
2.125
2
2024-11-18T19:35:14.119127+00:00
2021-09-16T10:25:14
1c983861fb4486a527266a7deb6a500f470f6392
{ "blob_id": "1c983861fb4486a527266a7deb6a500f470f6392", "branch_name": "refs/heads/main", "committer_date": "2021-09-16T10:25:14", "content_id": "409020b266ec27cdac43955e8c7d1fa03f079365", "detected_licenses": [ "Apache-2.0" ], "directory_id": "6d78df767e2ef3391f3aaf3b4984e5e3acdd47bd", "extension": "c", "filename": "LinkedList.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 407103204, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11173, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/collection/LinkedList.c", "provenance": "stackv2-0054.json.gz:14092", "repo_name": "tansudasli/data-structures", "revision_date": "2021-09-16T10:25:14", "revision_id": "9f476ab65cf209aa9dd70885e7d437a3e2b7a94d", "snapshot_id": "37d0e8945473e7a2c2f0644856eebe2f0c6817db", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tansudasli/data-structures/9f476ab65cf209aa9dd70885e7d437a3e2b7a94d/src/collection/LinkedList.c", "visit_date": "2023-08-10T20:53:55.090611" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include "../header/LinkedList.h" /** * Initializes and creates 1st node of ArrayList, sets head and returns head. * So client can use head in his code. * Sets Tail and Head pointers to the 1st node. To create as a sorted list set sorted=true. * <br><br> * @param d : DATA to attach as new head node * @param sorted : sorted list. default false. * @return : head node which points to (1st node) */ NODE * create(DATA d, bool sorted) { NODE *head = (NODE *) calloc(1, sizeof(NODE)); if (!head) { perror("no-allocation"); return NULL; } //init head->header.tail = NULL; head->header.nodeCount = 0; head->header.sorted = (sorted ? sorted : false); head->next = NULL; head->previous = NULL; //inject head->data.info = d.info; head->header.tail = head; head->header.nodeCount++; return head; } /** * Appends to the last node.<br> * Use insertSorted() method in a sorted list. * <br><br> * @param head : head node's addr. If, head is NULL, error occurs. Use create() first, to get a head * @param d : DATA to append as new node */ void append(NODE **head, DATA d) { if (!head) { perror("not created"); return; } // insertSorted() calls attach() and append() methods automatically. Enabling this creates error. // if ((*head)->header.sorted) { // perror("invalid usage in a sorted list"); // return; // } NODE *p = (NODE *) calloc(1, sizeof(NODE)); if (!p) { perror("no-allocation"); return; } //init new node p->data = d; p->next = NULL; p->previous = (*head)->header.tail; //append (*head)->header.tail->next = p; //injections (*head)->header.tail = p; (*head)->header.nodeCount++; } /** * Replaces 1st (head) node, and makes it second node. Sets new node as the head.<br> * Use insertSorted() method in a sorted list. * <br><br> * @param head : head node's addr. After replacement, it is updated as new head addr, and HEADER data copied to the new. * If, head is NULL, error occurs. Use create() first, to get a head * @param d : DATA to attach as new node */ void attach(NODE **head, DATA d) { if (!head) { perror("not created"); return; } // insertSorted() calls attach() and append() methods automatically. Enabling this creates error. // if ((*head)->header.sorted) { // perror("invalid usage in a sorted list"); // return; // } NODE *p = (NODE *) calloc(1, sizeof(NODE)); if (!p) { perror("no-allocation"); return; } //init new node p->data = d; p->next = *head; p->previous = NULL; (*head)->previous = p; //attach p->header.tail = (*head)->header.tail; p->header.nodeCount = (*head)->header.nodeCount; p->header.sorted = (*head)->header.sorted; *head = p; //injections (*head)->header.nodeCount++; } /** * Inserts between head and tail nodes.<br> * If, * - s is head, then inserting BEFORE triggers attach(), and updates head in-place again. * - s is tail, then inserting AFTER triggers append() * - otherwise, searches s, then inserts regarding pos (BEFORE or AFTER). * <br><br> * @param head : head node's addr. If, head is NULL, error occurs. Use create() first, to get a head. * If, It is sorted, error occurs, use insertSorted(). * @param s : DATA to find node * @param d : DATA to insert as new node * @param pos : BEFORE or AFTER position to insert */ void insert(NODE **head, DATA s, DATA d, POSITION pos) { if (!head) { perror("not created"); return; } if ((*head)->header.sorted) { perror("invalid usage in a sorted list"); return; } //search //todo: uses search() instead of binarySearch(). optimize NODE *p = search(head, s); if (!p) { perror("not found"); return; } //if p is the first node, so inserting before means attaching! if (p == *head && pos == BEFORE) { printf("...trigger attach()"); attach(head, d); return; } //if p is the last node, so inserting after means appending! if (p == (*head)->header.tail && pos == AFTER) { printf("...trigger append()"); append(head, d); return; } //init NODE *tmp = (NODE *) calloc(1, sizeof(NODE)); if(!tmp) { perror("no-allocation"); return; } //insert: between which means no touch to head or tail nodes if (pos == BEFORE) { tmp->data = d; tmp->next = p; tmp->previous = p->previous; p->previous->next = tmp; p->previous = tmp; //injections (*head)->header.nodeCount++; } else { tmp->data = d; tmp->next = p->next; tmp->previous = p; p->next->previous = tmp; p->next = tmp; //injections (*head)->header.nodeCount++; } } /** * Inserts as sorted. * <br><br> * @param head : head node's addr. If, head is null, use create() as sorted true. * @param d : DATA to insert as new node */ void insertSorted(NODE **head, DATA d) { if (!head) { perror("not created"); return; } if (!(*head)->header.sorted) { perror("invalid usage in an unsorted list"); return; } //if head is valid, means i have a node. //init new node NODE *p = (NODE *) calloc(1, sizeof(NODE)); p->data = d; // <, 1st node comparison NODE *cursor = *head; if (p->data.info < cursor->data.info) { //comparison I attach(head, d); return; } // > then 1st node, but we should find appropriate place cursor = cursor->next; while (cursor) { // > then head, so compare with next node, so, we should use < operator, to find the node that is right if (p->data.info < cursor->data.info) { //comparison II //insert before! p->next = cursor; p->previous = cursor->previous; cursor->previous->next = p; cursor->previous = p; //injections (*head)->header.nodeCount++; break; } cursor = cursor->next; }; // at the end of list, and cursor is null (,or just after initialized), means we traversed all nodes. if (!cursor) { append(head, d); } return; } /** * Deletes node<br> * If,<br> * s is 1st node, delete 1st, adjust head<br> * s is 1st and only node, delete and free()<br> * s is last, delete last, adjust tail <br> * s is between 1st and last, delete<br> * s is not found, error<br> * <br><br> * @param head : head node's addr. * @param s : DATA to search and to delete * @return : if error occurs, return -1 or return 0 */ int delete(NODE **head, DATA s) { //search vs binarySearch //delete //injections return 0; } /** * Searches from head to tail node. * <br><br> * @param head, If head is NULL, error occurs * @param s : DATA to search in nodes * @return : if founds, returns the node, otherwise NULL. */ NODE * search(NODE **head, DATA s) { //todo: compare function ? if (!head) { perror("not created"); return NULL; } //loop all NODE *cursor = *head; do { if (cursor->data.info == s.info) //comparison break; cursor = cursor->next; } while (cursor); return cursor; } /** * Finds middle node and then, makes a comparison. * Focuses always the middle, and compares with the middle. * At last steps, either b or e will be null, or b > e. * Works on sorted data. * <br><br> * @param head, If head is NULL, error occurs. If it is not sorted, error occurs. * @param s : DATA to search in nodes * @return : if founds, returns the node, otherwise NULL. */ NODE * binarySearch(NODE **head, DATA s) { if (!head) { perror("not created"); return NULL; } if (!(*head)->header.sorted) { perror("invalid usage in an unsorted list"); return NULL; } //compare middle, then divide again, till it found NODE *b = *head, *e = (*head)->header.tail, *m = NULL; do { //find middle m = getMiddle(b, e); if (!m) return NULL; //decide what to do if (s.info == m->data.info) return m; if (s.info > m->data.info) b = m->next; if (s.info < m->data.info) e = m->previous; //if, invalid, break if (b > e) break; } while (e); //todo: (e || b) ? return NULL; } /** * Head node. * <br><br> * @param head * @return head */ NODE * getHead(NODE **head) { return *head; } /** * Last node * <br><br> * @param head * @return tail */ NODE * getTail(NODE **head) { return (*head)->header.tail; } /** * Locates middle node, using start and end node approach. So it can be called recursively. * Uses 2 pointers, one moves 1-step, second moves 2-steps. When faster reaches the end, slow points to the middle. * Better than mathematical (n/2) approach, if you can not have (or not meaningful) index-based reach. * Useful for binarySearch() method. * * @param b : beginning node. At first call, it is the head ! * @param e : end node. At first call, it is the tail * @return : middle node */ NODE * getMiddle(NODE *b, NODE *e) { if (!b) { return NULL; } if (!e) { return NULL; } // NODE *slow = b, *fast = b; while (fast != e) { //moving fast 2-steps cause missing end point. if (fast->next == e) { slow = slow->next; break; } slow = slow->next; fast = fast->next->next; }; return slow; } /** * Node count * <br><br> * @param head * @return size */ int size(NODE **head) { return (*head)->header.nodeCount; } /** * Sorted * * @param head * @return true if sorted, or false (default) */ bool isSorted(NODE **head) { return (*head)->header.sorted; } /** * Empty * <br><br> * @param head * @return size equals 0, true, or false */ bool isEmpty(NODE **head) { return ((*head)->header.nodeCount == 0) ? true : false; } /** * some internal stats, pointer's addr etc... * <br><br> * @param head */ void stats(NODE **head) { if (!head) { perror("not created"); return; } printf("\n\n---------------stats----------------\n"); NODE *cursor = *head; printf("seq data prev\t\t p\t\t next\n"); int i = 0; do { printf("%d %d\t %p\t %p\t %p\n", i, cursor->data.info, cursor->previous, cursor, cursor->next); i++; cursor = cursor->next; } while (cursor); printf("------------end of stats------------\n"); } /** * Prints all nodes * <br><br> * @param head */ void display(NODE **head) { if (!head) { perror("not created"); return; } NODE *cursor = *head; do { printf("%d ", cursor->data.info); cursor = cursor->next; } while (cursor); }
3.09375
3
2024-11-18T19:35:15.553506+00:00
2020-11-06T17:10:02
9b8f1529b67022b1afa1dd9ff960cf0f60b82257
{ "blob_id": "9b8f1529b67022b1afa1dd9ff960cf0f60b82257", "branch_name": "refs/heads/main", "committer_date": "2020-11-06T17:10:02", "content_id": "12afdb4be1454c92d5f90b5f8bef609e552e18c9", "detected_licenses": [ "MIT" ], "directory_id": "aa55649b76891e98d0ecdd8a07c4eb54abfd41ac", "extension": "c", "filename": "ex08.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 310658649, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3433, "license": "MIT", "license_type": "permissive", "path": "/sprint2/modulo4/ex08/ex08.c", "provenance": "stackv2-0054.json.gz:15503", "repo_name": "joaomfas/SCOMP-2019-2020", "revision_date": "2020-11-06T17:10:02", "revision_id": "69acdd6f8da665dfa5ee9f0909d6a69105c54cd1", "snapshot_id": "02bab3588fcc120daad74aab1dedba23fc268a93", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/joaomfas/SCOMP-2019-2020/69acdd6f8da665dfa5ee9f0909d6a69105c54cd1/sprint2/modulo4/ex08/ex08.c", "visit_date": "2023-01-04T01:43:12.019137" }
stackv2
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/wait.h> #include <sys/types.h> #include <semaphore.h> #include <errno.h> #include <time.h> #define SEMS_NOME_BASE "/sem_ex08" #define MAX_TAM_STR 25 /** * devolve 0 no processo pai, devolve >0 nos processos filho */ int cria_filhos(int n) { pid_t pid; int i; for(i=0; i<n; i++) { pid=fork(); if(pid<0) return -1; else if(pid==0) return i+1; } return 0; } /** * funçao para imprimir mensagem */ void imprimirMsg(char *msg) { printf("%s", msg); fflush(stdout); } int main(int argc, char* argv[]) { int i; const int QTD_FILHOS = 2; const int QTD_SEMS = 2; //pode parecer excessivo, mas permite reutilizar o código para exercícios com mais semáforos char sems_names[QTD_SEMS][MAX_TAM_STR]; //Nomes para os semáforos, um nome em cada linha da matriz de chars enum index{SEM_printS, SEM_printC}; //enumerado para facilitar a leitura do código de acesso aos semáforos int sems_init_values[] = {1, 0}; //Valor inicial para cada um dos semáforos //Confirma se o número de semáforos está de acordo com o tamanho do vetor de inicializações if(sizeof(sems_init_values)/sizeof(sems_init_values[0]) != QTD_SEMS) { perror("Incorrect size for sems_init_values!!! "); exit(EXIT_FAILURE); } /***** SEMAFOROS *****/ sem_t* sems[QTD_SEMS]; for(i=0; i<QTD_SEMS; i++) { snprintf(sems_names[i], MAX_TAM_STR, "%s%d", SEMS_NOME_BASE, i); //gera o nome para o semáforo if ((sems[i] = sem_open(sems_names[i], O_CREAT | O_EXCL, 0644, sems_init_values[i])) == SEM_FAILED ) { fprintf(stderr, "sem_open() failed for %s!!!\n%s\n", sems_names[i], strerror(errno)); exit(EXIT_FAILURE); } } /******** PROCESSOS *******/ int id = cria_filhos(QTD_FILHOS); //Os processos têm de ser criados DEPOIS da memória partilhada e dos semáforos if(id == -1) { perror("fork() failed!!! "); exit(EXIT_FAILURE); } /*** Código dos filhos ***/ //P1 if(id==1){ int value; for(i=0; i<30; i++){ sem_wait(sems[SEM_printS]); imprimirMsg(" S"); sem_getvalue(sems[SEM_printS],&value); printf(" -> O valor do sem_S: %d\n", value); if(value==0){ sem_post(sems[SEM_printC]); sem_post(sems[SEM_printC]); } } exit(EXIT_SUCCESS); } //P2 if(id==2){ int value; for(i=0; i<30; i++){ sem_wait(sems[SEM_printC]); imprimirMsg(" C"); sem_getvalue(sems[SEM_printC],&value); printf(" -> O valor do sem_C: %d\n", value); if(value==0){ sem_post(sems[SEM_printS]); sem_post(sems[SEM_printS]); } } exit(EXIT_SUCCESS); } /***** Código do pai *****/ if(id==0){ int status; for(i=0; i<QTD_FILHOS; i++) { wait(&status); if(WEXITSTATUS(status) != EXIT_SUCCESS) { perror("Filho terminou com erro! "); exit(EXIT_FAILURE); } } } /***** Código para o pai e filho *****/ //Fechar os semaforos for(i=0; i<QTD_SEMS; i++) if(sem_close(sems[i]) < 0) { fprintf(stderr, "sem_close() failed on %s\n%s\n", sems_names[i], strerror(errno)); exit(EXIT_FAILURE); } /***** Código apenas para o pai *****/ if(id==0) { //Remover os semaforos for(i=0; i<QTD_SEMS; i++) if (sem_unlink(sems_names[i]) < 0) { fprintf(stderr, "sem_unlink() failed on %s\n%s\n", sems_names[i], strerror(errno)); exit(EXIT_FAILURE); } } return EXIT_SUCCESS; }
3.28125
3
2024-11-18T19:35:16.910243+00:00
2019-12-16T01:05:11
951aa470fd807bb87718a82329acde55a5fafdc9
{ "blob_id": "951aa470fd807bb87718a82329acde55a5fafdc9", "branch_name": "refs/heads/master", "committer_date": "2019-12-16T01:05:11", "content_id": "28117b4092667dbf44c22ae7661308ba0f82159b", "detected_licenses": [ "MIT" ], "directory_id": "24ca00d20bfa69090acc736c1586a08132904a55", "extension": "c", "filename": "printSpeed.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 217872153, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 438, "license": "MIT", "license_type": "permissive", "path": "/chapter4/printSpeed.c", "provenance": "stackv2-0054.json.gz:15887", "repo_name": "Faramita2/C-Primer-Plus-Exercises", "revision_date": "2019-12-16T01:05:11", "revision_id": "a3110d33ddd0647c288f01a0789289753d6f0b4a", "snapshot_id": "a1ec4d0f76c58d1c55ae6ece4feff8bb8979dadb", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Faramita2/C-Primer-Plus-Exercises/a3110d33ddd0647c288f01a0789289753d6f0b4a/chapter4/printSpeed.c", "visit_date": "2020-08-29T00:58:49.442124" }
stackv2
#include<stdio.h> /* * Print download speed. */ int main(void) { float file_size; float download_speed; printf("Input your download speed in Mb/s.\n"); scanf("%f", &download_speed); printf("Input your download file size in MB.\n"); scanf("%f", &file_size); printf("At %.2f megabits per second, a file of %.2f megabytes\ndownloads in %.2f seconds.\n", download_speed, file_size, file_size / download_speed * 8); return 0; }
3.046875
3
2024-11-18T19:35:17.012651+00:00
2018-11-12T20:17:45
432c0eae14fa742dc9f37174d6c74a0676b3c9cb
{ "blob_id": "432c0eae14fa742dc9f37174d6c74a0676b3c9cb", "branch_name": "refs/heads/master", "committer_date": "2018-11-12T20:17:45", "content_id": "b256114179227fb8104c2667a9c5f842b596b4f9", "detected_licenses": [ "MIT" ], "directory_id": "3b0c6c660752619130a191f6da01769c666f1ba4", "extension": "c", "filename": "Problem-4.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 157210954, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4607, "license": "MIT", "license_type": "permissive", "path": "/Problem-4.c", "provenance": "stackv2-0054.json.gz:16015", "repo_name": "cosminalexandru/Programare-Procedurala-Laborator-6", "revision_date": "2018-11-12T20:17:45", "revision_id": "a7aea08f9a4f8f1d3836f46b29ddc3ca21953cd2", "snapshot_id": "c82135e0f32dbef509186fc989f0ed5fe9cc498f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cosminalexandru/Programare-Procedurala-Laborator-6/a7aea08f9a4f8f1d3836f46b29ddc3ca21953cd2/Problem-4.c", "visit_date": "2020-04-05T21:10:58.896814" }
stackv2
#include <stdlib.h> #include <stdio.h> typedef struct { int id; char nume[20], prenume[20]; float nota; } Student; enum { CREARE = 1, AFISARE, MODIFICARE, ADAUGARE }; /** * * @param nume_fisier_binar represent the name of binary file * @param n represent the number of the students */ void creare(char *nume_fisier_binar, int n) { FILE *binaryFile = fopen(nume_fisier_binar, "wb"); for (int i = 0; i < n; i++) { Student student; printf("Introduceti id-ul:"); scanf("%d", &student.id); printf("Introduceti numele:"); scanf("%s", student.nume); printf("Introduceti prenumele:"); scanf("%s", student.prenume); printf("Introduceti nota:"); scanf("%f", &student.nota); fwrite(&student, sizeof(Student), 1, binaryFile); } fclose(binaryFile); } /** * * @param nume_fisier_binar * @param nume_fisier_text */ void afisare(char *nume_fisier_binar, char *nume_fisier_text) { FILE *textFile, *binaryFile; binaryFile = fopen(nume_fisier_binar, "rb"); if (binaryFile == NULL) { printf("Fisier inexistent!"); exit(0); } textFile = fopen(nume_fisier_text, "w"); fseek(binaryFile, 0, SEEK_END); int studentsNumber = ftell(binaryFile) / sizeof(Student); rewind(binaryFile); Student students[100]; fread(students, studentsNumber * sizeof(Student), 1, binaryFile); for (int i = 0; i < studentsNumber; i++) { fprintf(textFile, "%d %s %s %f \n", students[i].id, students[i].nume, students[i].prenume, students[i].nota); } fclose(textFile); fclose(binaryFile); } /** * * @param nume_fisier_binar * @param id * @param nota */ void modificare(char *nume_fisier_binar, int id, float nota) { FILE *binaryFile = fopen(nume_fisier_binar, "rb+"); if (binaryFile == 0) { printf("Fisierul nu exista!"); exit(0); } fseek(binaryFile, 0, SEEK_END); int studentsNumber = ftell(binaryFile) / sizeof(Student); rewind(binaryFile); int index = 0; while (index < studentsNumber) { Student student; fseek(binaryFile, index * sizeof(Student), SEEK_SET); fread(&student, sizeof(Student), 1, binaryFile); if (student.id == id) { student.nota = nota; fseek(binaryFile, index * sizeof(Student), SEEK_SET); fwrite(&student, sizeof(Student), 1, binaryFile); break; } else index++; } fclose(binaryFile); } /** * * @param nume_fisier_binar * @param student */ void adaugare(char *nume_fisier_binar, Student student) { FILE *binaryFile = fopen(nume_fisier_binar, "ab+"); if (binaryFile == NULL) { printf("Fisier inexistent"); exit(0); } fwrite(&student, sizeof(Student), 1, binaryFile); fclose(binaryFile); } //int main() { // int studentsNumber; // char studentsFile[] = "students.bin"; // char studentsTextFile[] = "students.txt"; // int optiune; // printf("Alegeti una din urmatoarele optiuni: 1.Creare catalog\n 2.Export studenti\n 3.Modificare nota\n 4.Adaugare"); // scanf("%d", &optiune); // switch (optiune) { // case CREARE : { // printf("Introduceti numarul de studenti:"); // scanf("%d", &studentsNumber); // creare(studentsFile, studentsNumber); // afisare(studentsFile, studentsTextFile); // break; // } // case AFISARE: { // afisare(studentsFile, studentsTextFile); // break; // } // // case MODIFICARE: { // int id; // float nota; // printf("Introduceti id-ul:"); // scanf("%d", &id); // printf("Introduceti nota:"); // scanf("%f", &nota); // modificare(studentsFile, id, nota); // afisare(studentsFile, studentsTextFile); // break; // } // case ADAUGARE: { // Student student; // printf("Introduceti id-ul:"); // scanf("%d", &student.id); // printf("Introduceti numele:"); // scanf("%s", student.nume); // printf("Introduceti prenumele:"); // scanf("%s", student.prenume); // printf("Introduceti nota:"); // scanf("%f", &student.nota); // adaugare(studentsFile, student); // afisare(studentsFile, studentsTextFile); // break; // } // default: // afisare(studentsFile, studentsTextFile); // } // return 0; //}
3.34375
3
2024-11-18T19:35:20.377099+00:00
2015-07-08T10:37:11
ca443e09f233442ec08d4d31156ebef6bed0e7bc
{ "blob_id": "ca443e09f233442ec08d4d31156ebef6bed0e7bc", "branch_name": "refs/heads/master", "committer_date": "2015-07-08T10:37:11", "content_id": "99662db15457aabed97c8ebc8e7f334f5fa029cd", "detected_licenses": [ "MIT" ], "directory_id": "e583ccc0c85742dca7bdbf3424388bbfa456044d", "extension": "c", "filename": "skeem.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": 2768, "license": "MIT", "license_type": "permissive", "path": "/src/skeem.c", "provenance": "stackv2-0054.json.gz:20826", "repo_name": "agumonkey/skeem", "revision_date": "2015-07-08T10:37:11", "revision_id": "4a008d9bc86aba79bc05c8007e4a3878764b9635", "snapshot_id": "97768afa7368bfe13f21eaea605a9560b804e8c1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/agumonkey/skeem/4a008d9bc86aba79bc05c8007e4a3878764b9635/src/skeem.c", "visit_date": "2021-05-29T16:09:51.035139" }
stackv2
/* Copyright (c) 2015 Vibhav Pant <[email protected]> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #include "token.h" #include "types.h" #include "builtins.h" #include "mem.h" #include <string.h> #include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <setjmp.h> #define SKEEM_VERSION "1.0a" #define get_input(i) \ { \ size_t __n__; \ getline(&(i), &__n__, stream); \ } int main(int argc, char **argv) { #ifdef DEBUG setbuf(stdout, NULL); #endif char *input = NULL; FILE *stream = argc > 1 ? fopen(argv[1], "r") : stdin; if (stream == NULL) { perror("fopen"); exit(EXIT_FAILURE); } if (stream == stdin) printf("skeem version %s\n", SKEEM_VERSION); mem_init(); builtins_init(); paren_depth = 0; nquotes = 0; while (true) { if (stream == stdin) printf("skeem> "); if (setjmp(err)) { if (stream != stdin) exit(EXIT_FAILURE); clear_tokens(); continue; } input: get_input(input); if (input[0] == '\n') continue; scan(input, strlen(input)); if (feof(stdin)) break; if (paren_depth < 0) { fprintf(stderr, "Unbalanced expression\n"); paren_depth = 0; longjmp(err, 1); } if (nquotes % 2 != 0 || paren_depth != 0) { if (stream == stdin) { printf("... "); fflush(stdout); } goto input; } register object_t *obj = tokens_to_obj(); if (obj == NULL) continue; no_gc = false; obj = eval(obj); if (stream == stdin) { printf("=> "); fflush(stdout); print_obj(obj, stdout); putchar('\n'); } clear_tokens(); if (feof(stream)) break; } return 0; }
2.0625
2
2024-11-18T19:35:20.547828+00:00
2020-04-14T10:41:14
64f8c13e245eda2fb28cd5b7686bb271136df1b9
{ "blob_id": "64f8c13e245eda2fb28cd5b7686bb271136df1b9", "branch_name": "refs/heads/master", "committer_date": "2020-04-14T10:41:14", "content_id": "ccdd849bfce6b6373321e0c0ab3de304b69006e1", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "e7b3364c789de80ba98996596291fbd10554cb59", "extension": "c", "filename": "stdlib.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": 1484, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/utils/stdlib.c", "provenance": "stackv2-0054.json.gz:20956", "repo_name": "iliemihai/calypso_os", "revision_date": "2020-04-14T10:41:14", "revision_id": "80023f250ba2039c55029db2c22033ebacd8e0b3", "snapshot_id": "ce0080b7a1d4aec5cc0373fdbcfc1bd0f747ce97", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/iliemihai/calypso_os/80023f250ba2039c55029db2c22033ebacd8e0b3/utils/stdlib.c", "visit_date": "2022-04-13T11:28:25.987171" }
stackv2
#include <stdlib.h> #include <s_heap.h> #include <string.h> #include <semaphore.h> /**************************************************************************** * Public Data ****************************************************************************/ extern heap_t g_my_heap; extern sem_t g_heap_sema; /**************************************************************************** * Public Functions ****************************************************************************/ void *malloc(size_t size) { void *new_mem = NULL; sem_wait(&g_heap_sema); new_mem = s_alloc(size, &g_my_heap); sem_post(&g_heap_sema); return new_mem; } void free(void *ptr) { sem_wait(&g_heap_sema); s_free(ptr, &g_my_heap); sem_post(&g_heap_sema); } void *calloc(size_t nmemb, size_t size) { uint8_t *ptr = malloc(nmemb * size); if (ptr == NULL) return NULL; memset(ptr, 0, nmemb * size); return ptr; } void *realloc(void *ptr, size_t size) { void *new_mem = NULL; sem_wait(&g_heap_sema); new_mem = s_realloc(ptr, size, &g_my_heap); sem_post(&g_heap_sema); return new_mem; } void *reallocarray(void *ptr, size_t nmemb, size_t size) { return NULL; } unsigned long atol(const char *nptr) { unsigned long res = 0; for (int i = 0; nptr[i] != '\0'; ++i) res = res * 10 + nptr[i] - '0'; return res; } int atoi(const char *nptr) { int res = 0; for (int i = 0; nptr[i] != '\0'; ++i) res = res * 10 + nptr[i] - '0'; return res; }
2.90625
3
2024-11-18T19:35:22.311928+00:00
2017-08-25T20:43:26
77ba47cd25811217cf6039929fed6d9fb12d04f8
{ "blob_id": "77ba47cd25811217cf6039929fed6d9fb12d04f8", "branch_name": "refs/heads/master", "committer_date": "2017-08-25T20:43:26", "content_id": "e49a19031e9268b22352b0ffcabbfcdc85e96a52", "detected_licenses": [ "MIT" ], "directory_id": "748429025020e6b1f91539cb0991600b9b4956b2", "extension": "c", "filename": "xdump.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 101428641, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3924, "license": "MIT", "license_type": "permissive", "path": "/xdump.c", "provenance": "stackv2-0054.json.gz:21212", "repo_name": "blendin/xdump", "revision_date": "2017-08-25T20:43:26", "revision_id": "b50a2105696924ba7464e7e93ebe79ba5108d611", "snapshot_id": "cd4962f2318bbe6c9b315b102d00e5d690bfd17f", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/blendin/xdump/b50a2105696924ba7464e7e93ebe79ba5108d611/xdump.c", "visit_date": "2021-01-20T05:19:34.026737" }
stackv2
/* * Brendon Tiszka * Simple tool for dumping a executables memory */ #include <sys/mman.h> #include <sys/ptrace.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <assert.h> #include <string.h> #include <fcntl.h> #include <time.h> #include <errno.h> #define MAXBUF 8192 /* User defined values */ #define DEBUG 0 #define PAGE_SIZE 4096 #define MAPPREFIX "map-" #define MEMPREFIX "mem-" #define BINSUFFIX ".bin" #define LOW_ADDR PAGE_SIZE #define HIGH_ADDR 0xffffffff #define USE_PROC_DIR 1 /* End user defined values */ #define debug(x...) { \ fprintf(stderr, x); \ fflush(stderr); \ }\ #define fatal(x...) { \ fprintf(stderr, "[-] ERROR: " x); \ exit(1); \ }\ void usage(char *myname) { debug("Usage: %s filename\n", myname); exit(3); } int dump_with_proc(FILE *mapfile, pid_t child) { int i; char tmp[MAXBUF]; int *writeptr; char *filepath; while (fgets(tmp, MAXBUF, mapfile)) { int dumpfile, dumpcnt; char small[MAXBUF]; unsigned int st, en, len; if (sscanf(tmp, "%x-%x", &st, &en) != 2) { debug("[!] Parse error in /proc/%d/maps: %s", child, tmp); continue; } len = en - st; if (DEBUG) debug("%x %x\n", st, en); if ((filepath=strchr(tmp,'/'))) { *(filepath-1)=0; sprintf(small, MAPPREFIX "%x-%x" BINSUFFIX, st, en); } else { if (strchr(tmp, '\n')) *strchr(tmp,'\n')=0; sprintf(small, MEMPREFIX "%x-%x" BINSUFFIX, st, en); } if (DEBUG) debug("%s\n", small); writeptr = calloc(len, 1); for (i = 0; i < len/4; i++) writeptr[i] = ptrace(PTRACE_PEEKDATA, child, i*4+st, 0); dumpfile = open(small, O_WRONLY | O_TRUNC | O_CREAT | O_EXCL, 0600); if (dumpfile < 0) fatal("Cannot open output file %s.\n", small); if (write(dumpfile, writeptr, len) != len) fatal("Short write to %s.\n", small); dumpcnt++; close(dumpfile); } return 1; } int dump_segment(pid_t child, size_t addr) { char small[MAXBUF]; int *writeptr; int i, dumpfile; memset(small, 0, MAXBUF); writeptr = calloc(PAGE_SIZE, 1); for (i = 0; i < PAGE_SIZE/4; i++) writeptr[i] = ptrace(PTRACE_PEEKDATA, child, i*4+addr, 0); sprintf(small, MEMPREFIX "%zx-%zx" BINSUFFIX, addr, addr+PAGE_SIZE); dumpfile = open(small, O_WRONLY | O_TRUNC | O_CREAT | O_EXCL, 0600); if (dumpfile < 0) fatal("Cannot open output file %s.\n", small); if (write(dumpfile, writeptr, PAGE_SIZE) != PAGE_SIZE) fatal("Short write to %s.\n", small); return 1; } int do_memsearch(pid_t child) { size_t lo_addr, hi_addr, addr; lo_addr = LOW_ADDR; hi_addr = HIGH_ADDR; for (addr = lo_addr; addr < hi_addr; addr += PAGE_SIZE) { errno = 0; int q = ptrace(PTRACE_PEEKDATA, child, addr, 0); if (errno == 0) { if (DEBUG) debug("found: %zx %x\n", addr, q); dump_segment(child, addr); } } return 1; } int do_trace(pid_t child) { FILE *mapfile; int status, canproc; char tmp[MAXBUF]; waitpid(child, &status, 0); assert(WIFSTOPPED(status)); sprintf(tmp, "/proc/%d/maps", child); mapfile=fopen(tmp, "r"); canproc = USE_PROC_DIR; if (!mapfile) { canproc = 0; } if (canproc) dump_with_proc(mapfile, child); else do_memsearch(child); ptrace(PTRACE_DETACH); return 0; } int do_child(int argc, char **argv) { char *args [argc+1]; int i; for (i = 0; i < argc; i++) args[i] = argv[i]; args[argc] = NULL; debug("argc %d execvp(%s, args) \n", argc, args[0]); if (ptrace(PTRACE_TRACEME) == 0) { return execvp(args[0], args); } fatal("Couldn't attach to process"); } int main(int argc, char *argv[]) { pid_t child; if (DEBUG) debug("version 0.1 brendon tiszka\n\n"); if (argc<2) usage(argv[0]); child = fork(); if (child == 0) { return do_child(argc - 1, argv + 1); } else { return do_trace(child); } }
2.59375
3
2024-11-18T19:35:22.810191+00:00
2016-04-05T05:21:37
7f02333a04d4e89f060ea049cc86f5a13aeeb921
{ "blob_id": "7f02333a04d4e89f060ea049cc86f5a13aeeb921", "branch_name": "refs/heads/master", "committer_date": "2016-04-05T05:21:37", "content_id": "191bcbc1db2fbeec9b92ca5e986700b5c50dbe50", "detected_licenses": [ "Apache-2.0" ], "directory_id": "955573308aec351c27aa02a3363393920cbbcc01", "extension": "h", "filename": "ring.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 55469489, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4077, "license": "Apache-2.0", "license_type": "permissive", "path": "/ring.h", "provenance": "stackv2-0054.json.gz:21727", "repo_name": "coolper/spice-replay-debugger", "revision_date": "2016-04-05T05:21:37", "revision_id": "eca21639b4e8cfa8cb23f8da6cba6c5acf8261fe", "snapshot_id": "aaec751fa9f9bfae54f63b1fabcf4625355a420b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/coolper/spice-replay-debugger/eca21639b4e8cfa8cb23f8da6cba6c5acf8261fe/ring.h", "visit_date": "2021-01-10T13:14:29.611254" }
stackv2
/* -*- Mode: C; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* Copyright (C) 2009 Red Hat, Inc. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, see <http://www.gnu.org/licenses/>. */ #ifndef _H_RING2 #define _H_RING2 #include <spice/macros.h> SPICE_BEGIN_DECLS typedef struct Ring RingItem; typedef struct Ring { RingItem *prev; RingItem *next; } Ring; static inline void ring_init(Ring *ring) { ring->next = ring->prev = ring; } static inline void ring_item_init(RingItem *item) { item->next = item->prev = NULL; } static inline int ring_item_is_linked(RingItem *item) { return !!item->next; } static inline int ring_is_empty(Ring *ring) { //spice_assert(ring->next != NULL && ring->prev != NULL); return ring == ring->next; } static inline void ring_add(Ring *ring, RingItem *item) { //spice_assert(ring->next != NULL && ring->prev != NULL); //spice_assert(item->next == NULL && item->prev == NULL); item->next = ring->next; item->prev = ring; ring->next = item->next->prev = item; } static inline void ring_add_after(RingItem *item, RingItem *pos) { ring_add(pos, item); } static inline void ring_add_before(RingItem *item, RingItem *pos) { ring_add(pos->prev, item); } static inline void __ring_remove(RingItem *item) { item->next->prev = item->prev; item->prev->next = item->next; item->prev = item->next = 0; } static inline void ring_remove(RingItem *item) { //spice_assert(item->next != NULL && item->prev != NULL); //spice_assert(item->next != item); __ring_remove(item); } static inline RingItem *ring_get_head(Ring *ring) { RingItem *ret; //spice_assert(ring->next != NULL && ring->prev != NULL); if (ring_is_empty(ring)) { return NULL; } ret = ring->next; return ret; } static inline RingItem *ring_get_tail(Ring *ring) { RingItem *ret; //spice_assert(ring->next != NULL && ring->prev != NULL); if (ring_is_empty(ring)) { return NULL; } ret = ring->prev; return ret; } static inline RingItem *ring_next(Ring *ring, RingItem *pos) { RingItem *ret; //spice_assert(ring->next != NULL && ring->prev != NULL); //spice_assert(pos); //spice_assert(pos->next != NULL && pos->prev != NULL); ret = pos->next; return (ret == ring) ? NULL : ret; } static inline RingItem *ring_prev(Ring *ring, RingItem *pos) { RingItem *ret; //spice_assert(ring->next != NULL && ring->prev != NULL); //spice_assert(pos); //spice_assert(pos->next != NULL && pos->prev != NULL); ret = pos->prev; return (ret == ring) ? NULL : ret; } #define RING_FOREACH_SAFE(var, next, ring) \ for ((var) = ring_get_head(ring); \ (var) && ((next) = ring_next(ring, (var)), 1); \ (var) = (next)) #define RING_FOREACH(var, ring) \ for ((var) = ring_get_head(ring); \ (var); \ (var) = ring_next(ring, var)) #define RING_FOREACH_REVERSED(var, ring) \ for ((var) = ring_get_tail(ring); \ (var); \ (var) = ring_prev(ring, var)) static inline unsigned int ring_get_length(Ring *ring) { RingItem *i; unsigned int ret = 0; for (i = ring_get_head(ring); i != NULL; i = ring_next(ring, i)) ret++; return ret; } SPICE_END_DECLS #endif
2.3125
2
2024-11-18T19:35:23.181949+00:00
2023-07-07T18:41:40
3d1a3849d3087f80780ad87f22a5a584f2b8a3ab
{ "blob_id": "3d1a3849d3087f80780ad87f22a5a584f2b8a3ab", "branch_name": "refs/heads/master", "committer_date": "2023-07-07T18:41:40", "content_id": "ada4184c56524736bbcf968e45b20825ae6390e3", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "c26d7b0ed875357278e61627da2da0650da77986", "extension": "c", "filename": "ps.c", "fork_events_count": 59, "gha_created_at": "2014-04-09T13:25:46", "gha_event_created_at": "2023-07-18T07:35:36", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 18598087, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 20695, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/cmd/ps.c", "provenance": "stackv2-0054.json.gz:21983", "repo_name": "RetroBSD/retrobsd", "revision_date": "2023-07-07T18:41:40", "revision_id": "486f81f6abff01c7dcc207235cd2979b226a95ff", "snapshot_id": "5343d9e3c424637fc3ad5b03fe720b2744490025", "src_encoding": "UTF-8", "star_events_count": 282, "url": "https://raw.githubusercontent.com/RetroBSD/retrobsd/486f81f6abff01c7dcc207235cd2979b226a95ff/src/cmd/ps.c", "visit_date": "2023-09-02T23:12:05.110883" }
stackv2
/* * 1999/8/11 - Remove reference to SDETACH. It was removed from the kernel * (finally) because it was not needed. * * 1997/12/16 - Fix coredump when processing -U. * * 1996/11/16 - Move 'psdatabase' in /var/run. * * 12/20/94 - Missing casts caused errors in reporting on swapped * processes - sms * 1/7/93 - Heavily revised when the symbol table format changed - sms * * ps - process status * Usage: ps [ acgklnrtuwxU# ] [ corefile [ swapfile ] ] */ #include <stdio.h> #include <stdlib.h> #include <pwd.h> #include <a.out.h> #include <ctype.h> #include <string.h> #include <strings.h> #include <unistd.h> #include <fcntl.h> #include <sys/param.h> #include <sys/file.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <sys/user.h> #include <sys/proc.h> #include <utmp.h> #include <paths.h> #include <psout.h> #define within(x,y,z) (((unsigned)(x) >= (y)) && ((unsigned)(x) < (z))) #define round(x,y) ((long) ((((long) (x) + (long) (y) - 1L) / (long) (y)) * (long) (y))) struct nlist nl[] = { #define X_PROC 0 { "_proc" }, #define X_NPROC 1 { "_nproc" }, #define X_HZ 2 { "_hz" }, { "_ipc" }, { "_lbolt" }, { "_memlock" }, { "_runin" }, { "_runout" }, { "_selwait" }, { "_u" }, { "" }, }; /* * This is no longer the size of a symbol's name, symbols can be much * larger now. This define says how many characters of a symbol's name * to save in the wait channel name. A new define has been created to * limit the size of symbol string read from the string table. */ #define NNAMESIZ 8 #define MAXSYMLEN 32 struct proc *mproc, proc[8]; struct user u; int hz; int chkpid = 0; char aflg; /* -a: all processes, not just mine */ char cflg; /* -c: not complete listing of args, just comm. */ char gflg; /* -g: complete listing including group headers, etc */ char kflg; /* -k: read from core file instead of real memory */ char lflg; /* -l: long listing form */ char nflg; /* -n: numeric wchans */ char rflg; /* -r: raw output in style <psout.h> */ char uflg; /* -u: user name */ char wflg; /* -w[w]: wide terminal */ char xflg; /* -x: ALL processes, even those without ttys */ char *tptr, *mytty; char *uname; int file; int nproc; int nchans; int nttys; int npr; /* number of processes found so far */ int twidth; /* terminal width */ int cmdstart; /* start position for command field */ char *memf; /* name of kernel memory file */ char *kmemf = "/dev/kmem"; /* name of physical memory file */ char *swapf; /* name of swap file to use */ int kmem, mem, swap; /* * Structure for the unix wchan table */ typedef struct wchan { char cname[NNAMESIZ]; unsigned caddr; } WCHAN; WCHAN *wchand; /* * 256 terminals was not only wasteful but unrealistic. For one thing * 2.11BSD uses bit 7 of the minor device (for almost all terminal interfaces) * to indicate direct/modem status - this means that 128 terminals is * a better maximum number of terminals, for another thing the system can't * support 256 terminals - other resources (memory, files, processes) will * have been exhausted long ago. If 'ps' complains about too many terminals * it is time to clean up /dev! */ #define MAXTTYS 160 /* 128 plus a few extra */ struct ttys { char name[14]; /* MAXNAMLEN uses too much memory, besides */ /* device names tend to be very short */ dev_t ttyd; } allttys[MAXTTYS]; struct map { off_t b1, e1; off_t f1; off_t b2, e2; off_t f2; }; struct winsize ws; struct map datmap; struct psout *outargs; /* info for first npr processes */ /* * Attempt to avoid stats by guessing minor device * numbers from tty names. Console is known, * know that r(hp|up|mt) are unlikely as are different mem's, * floppy, null, tty, etc. */ void maybetty(cp) register char *cp; { register struct ttys *dp; struct stat stb; /* Allow only terminal devices. */ switch (cp[0]) { case 'c': if (strcmp(cp, "console") == 0) break; return; case 't': if (strncmp(cp, "tty", 3) == 0) break; return; default: return; } if (nttys >= MAXTTYS) { fprintf(stderr, "ps: tty table overflow\n"); exit(1); } dp = &allttys[nttys++]; (void)strcpy(dp->name, cp); if (stat(dp->name, &stb) == 0 && (stb.st_mode & S_IFMT) == S_IFCHR) dp->ttyd = stb.st_rdev; else dp->ttyd = -1; } void getdev() { register DIR *df; register struct direct *dbuf; if (chdir("/dev") < 0) { perror("/dev"); exit(1); } if ((df = opendir(".")) == NULL) { fprintf(stderr, "Can't open . in /dev\n"); exit(1); } while ((dbuf = readdir(df))) maybetty(dbuf->d_name); closedir(df); } char * gettty() { register int tty_step; register char *p; if (u.u_ttyp) { for (tty_step = 0; tty_step < nttys; ++tty_step) { if (allttys[tty_step].ttyd == u.u_ttyd) { p = allttys[tty_step].name; if (strncmp(p, "tty", 3) == 0) p += 3; return(p); } } } return("?"); } unsigned getptr(adr) off_t adr; { unsigned ptr = 0; if (lseek(file, adr, 0) == (off_t) -1 || read (file, &ptr, sizeof(ptr)) != sizeof(ptr)) return 0; return ptr; } int getbyte(adr) register char *adr; { char b; if (lseek(file, (off_t) adr, 0) == (off_t) -1 || read (file, &b, 1) < 1) return(0); return((unsigned) b); } int getcmd(a, addr) off_t addr; register struct psout *a; { /* amount of top of stack to examine for args */ #define ARGLIST (DEV_BSIZE * 2) char abuf [ARGLIST]; char cmd[82], *bp; off_t ap; unsigned ssize, cp; /* in case of early return */ bp = a->o_args; strcat(bp, " ("); strcat(bp, u.u_comm); strcat(bp, ")"); bp[63] = 0; /* max room in psout is 64 chars */ if (mproc->p_pid == 0) return(1); /* look for in-core process */ if (mproc->p_flag & SLOAD) { addr += mproc->p_ssize; /* file offset to top of stack */ lseek(file, addr - sizeof (char **), 0); if (read(file, (char *) &ap, sizeof (char *)) != sizeof (char *)) return (1); if (ap == 0) return(1); bp = cmd; while (bp < cmd + sizeof(a->o_args)) { int c, nbad = 0; cp = getptr(ap); if (! cp) break; ap += sizeof(char*); while ((c = getbyte(cp++)) && bp < cmd + sizeof (a->o_args)) { if (c < ' ' || c > '~') { if (nbad++ > 3) break; continue; } *bp++ = c; } *bp++ = ' '; } *bp++ = 0; strcpy(a->o_args, cmd); return(1); } /* process is swapped out */ ssize = mproc->p_ssize; if (ssize <= sizeof(abuf)) { lseek(file, addr, 0); if (read(file, abuf, ssize) != ssize) return (1); } else { /* skip some blocks of stack */ ssize = (ssize % DEV_BSIZE) + DEV_BSIZE; addr += mproc->p_ssize - ssize; lseek(file, addr, 0); if (read(file, abuf, sizeof(abuf)) != sizeof(abuf)) return (1); } ap = *(unsigned*) &abuf[ssize - sizeof(unsigned)]; if (ap == 0) return(1); bp = cmd; while (bp < cmd + sizeof(a->o_args)) { int i, c, nbad = 0; i = ap + ssize - USER_DATA_END; if ((i & 3) || i < 0 || i >= ssize) break; cp = *(unsigned*) &abuf[i]; if (! cp) break; ap += sizeof(char*); while (bp < cmd + sizeof (a->o_args)) { i = cp++ + ssize - USER_DATA_END; if (i < 0 || i >= ssize) break; c = abuf[i]; if (! c) break; if (c < ' ' || c > '~') { if (nbad++ > 3) break; continue; } *bp++ = c; } *bp++ = ' '; } *bp++ = 0; if (cmd[0] > ' ' && (cmd[0] != '-' || cmd[1] > ' ')) strcpy(a->o_args, cmd); if (xflg || gflg || tptr || cmd[0] != '-') return(1); return(0); } /* * Save command data to outargs[]. * Return 1 on success. */ int savcom(puid) int puid; { char *tp; off_t addr; off_t daddr, saddr; register struct psout *a; register struct proc *procp = mproc; register struct user *up = &u; long txtsiz, datsiz, stksiz; if (procp->p_flag & SLOAD) { addr = procp->p_addr; daddr = procp->p_daddr; saddr = procp->p_saddr; file = mem; } else { addr = (off_t)procp->p_addr * DEV_BSIZE; daddr = (off_t)procp->p_daddr * DEV_BSIZE; saddr = (off_t)procp->p_saddr * DEV_BSIZE; file = swap; } lseek(file, addr, 0); if (read(file, (char *) up, sizeof (u)) != sizeof (u)) return(0); txtsiz = up->u_tsize; /* set up address maps for user pcs */ datsiz = up->u_dsize; stksiz = up->u_ssize; datmap.b1 = txtsiz; datmap.e1 = datmap.b1 + datsiz; datmap.f1 = daddr; datmap.f2 = saddr; datmap.b2 = stackbas(stksiz); datmap.e2 = stacktop(stksiz); tp = gettty(); if ((tptr && strncmp(tptr, tp, 2) != 0) || (! aflg && strncmp(mytty, tp, 2) != 0)) return(0); a = &outargs[npr]; /* saving com starts here */ a->o_uid = puid; a->o_pid = procp->p_pid; a->o_flag = procp->p_flag; a->o_ppid = procp->p_ppid; a->o_cpu = procp->p_cpu; a->o_pri = procp->p_pri; a->o_nice = procp->p_nice; a->o_addr0 = procp->p_addr; a->o_size = (procp->p_dsize + procp->p_ssize + USIZE) / DEV_BSIZE; a->o_wchan = procp->p_wchan; a->o_pgrp = procp->p_pgrp; strncpy(a->o_tty, tp, sizeof (a->o_tty)); a->o_ttyd = tp[0] == '?' ? -1 : up->u_ttyd; a->o_stat = procp->p_stat; a->o_flag = procp->p_flag; if (a->o_stat == SZOMB) return(1); a->o_utime = up->u_ru.ru_utime; a->o_stime = up->u_ru.ru_stime; a->o_cutime = up->u_cru.ru_utime; a->o_cstime = up->u_cru.ru_stime; a->o_sigs = (int)up->u_signal[SIGINT] + (int)up->u_signal[SIGQUIT]; a->o_uname[0] = 0; strncpy(a->o_comm, up->u_comm, MAXCOMLEN); if (cflg) return (1); else return getcmd(a, saddr); } int pscomp(x1, x2) register struct psout *x1, *x2; { register int c; c = (x1)->o_ttyd - (x2)->o_ttyd; if (c == 0) c = (x1)->o_pid - (x2)->o_pid; return(c); } /* * fixup figures out everybodys name and sorts into a nice order. */ void fixup(np) register int np; { register int i; register struct passwd *pw; if (uflg) { setpwent(); /* * If we want names, traverse the password file. For each * passwd entry, look for it in the processes. * In case of multiple entries in the password file we believe * the first one (same thing ls does). */ while ((pw = getpwent()) != (struct passwd *) NULL) { for (i = 0; i < np; i++) if (outargs[i].o_uid == pw->pw_uid) { if (outargs[i].o_uname[0] == 0) strcpy(outargs[i].o_uname, pw->pw_name); } } endpwent(); } qsort(outargs, np, sizeof (outargs[0]), pscomp); } int wchancomp(x1, x2) register WCHAN *x1, *x2; { if (x1->caddr > x2->caddr) return(1); else if (x1->caddr == x2->caddr) return(0); else return(-1); } void addchan(name, caddr) char *name; unsigned caddr; { static int left = 0; register WCHAN *wp; if (left == 0) { if (wchand) { left = 50; wchand = (WCHAN *)realloc(wchand, (nchans + left) * sizeof (struct wchan)); } else { left = 300; wchand = (WCHAN *)malloc(left * sizeof (struct wchan)); } if (! wchand) { fprintf(stderr, "ps: out of wait channel memory\n"); nflg++; return; } } wp = &wchand[nchans++]; left--; strncpy(wp->cname, name, NNAMESIZ - 1); wp->cname[NNAMESIZ-1] = '\0'; wp->caddr = caddr; } char * getchan(chan) register unsigned int chan; { register int i; register char *prevsym; prevsym = ""; if (chan) { for (i = 0; i < nchans; i++) { if (wchand[i].caddr > chan) return (prevsym); prevsym = wchand[i].cname; } } return(prevsym); } void perrexit(msg) char *msg; { perror(msg); exit(1); } void openfiles(argc, argv) char **argv; { if (kflg) kmemf = argc > 1 ? argv[1] : _PATH_CORE; kmem = open(kmemf, 0); if (kmem < 0) perrexit(kmemf); if (!kflg) memf = _PATH_MEM; else memf = kmemf; mem = open(memf, 0); if (mem < 0) perrexit(memf); swapf = argc > 2 ? argv[2] : _PATH_SWAP; swap = open(swapf, 0); if (swap < 0) perrexit(swapf); } void getkvars(argc,argv) int argc; char **argv; { knlist(nl); if (! nflg) { int i; for (i=0; i<sizeof(nl)/sizeof(*nl); i++) { if (nl[i].n_value != 0) addchan(nl[i].n_name + 1, nl[i].n_value); } qsort(wchand, nchans, sizeof(WCHAN), wchancomp); } getdev(); /* find number of procs */ if (nl[X_NPROC].n_value) { int ret = lseek(kmem, (off_t)nl[X_NPROC].n_value, 0); if (ret == -1 || read(kmem, (char *)&nproc, sizeof(nproc)) != sizeof(nproc)) { perror(kmemf); exit(1); } } else { fputs("nproc not in namelist\n", stderr); exit(1); } outargs = (struct psout *)calloc(nproc, sizeof(struct psout)); if (!outargs) { fputs("ps: not enough memory for saving info\n", stderr); exit(1); } /* find value of hz */ lseek(kmem, (off_t)nl[X_HZ].n_value, 0); read(kmem, (char *)&hz, sizeof(hz)); } void ptime(a) struct psout *a; { time_t tm; tm = (a->o_utime + a->o_stime + 30) / hz; printf("%3ld:",tm / 60); tm %= 60; printf(tm < 10 ? "0%ld" : "%ld",tm); } char *uhdr = "USER PID NICE SZ TTY TIME"; void upr(a) register struct psout *a; { printf("%-8.8s%6u%4d%4d %-3.3s",a->o_uname,a->o_pid,a->o_nice,a->o_size,a->o_tty); ptime(a); } char *shdr = " PID TTY TIME"; void spr (a) register struct psout *a; { printf("%6u %-3.3s",a->o_pid,a->o_tty); ptime(a); } char *lhdr = " F S UID PID PPID CPU PRI NICE ADDR SZ WCHAN TTY TIME"; void lpr(a) register struct psout *a; { static char clist[] = "0SWRIZT"; printf("%3o %c%6u%6u%6u%4d%4d%4d%#7x%4d", 0377 & a->o_flag, clist[(unsigned char)a->o_stat], a->o_uid, a->o_pid, a->o_ppid, a->o_cpu & 0377, a->o_pri, a->o_nice, a->o_addr0, a->o_size); if (nflg) if (a->o_wchan) printf("%*.*x", NNAMESIZ, NNAMESIZ, (unsigned) a->o_wchan); else fputs(" ", stdout); else printf(" %-*.*s",NNAMESIZ, NNAMESIZ, getchan(a->o_wchan)); printf(" %-3.3s",a->o_tty); ptime(a); } void printhdr() { register char *hdr, *cmdstr = " COMMAND"; if (rflg) return; if (lflg && uflg) { fputs("ps: specify only one of l and u.\n",stderr); exit(1); } hdr = lflg ? lhdr : (uflg ? uhdr : shdr); fputs(hdr,stdout); cmdstart = strlen(hdr); if (cmdstart + strlen(cmdstr) >= twidth) cmdstr = " CMD"; printf("%s\n", cmdstr); fflush(stdout); } int main (argc, argv) char **argv; { int uid, euid, puid, nread; register int i, j; char *ap; register struct proc *procp; if ((ioctl(fileno(stdout), TIOCGWINSZ, &ws) != -1 && ioctl(fileno(stderr), TIOCGWINSZ, &ws) != -1 && ioctl(fileno(stdin), TIOCGWINSZ, &ws) != -1) || ws.ws_col == 0) twidth = 80; else twidth = ws.ws_col; mytty = ttyname(0); argc--, argv++; if (argc > 0) { ap = argv [0]; while (*ap) switch (*ap++) { case '-': break; case 'a': aflg++; break; case 'c': cflg++; break; case 'g': gflg++; break; case 'k': kflg++; break; case 'l': lflg = 1; break; case 'n': nflg++; lflg = 1; break; case 'r': rflg++; break; case 't': if (*ap) { tptr = ap; } else if (! mytty) { /* Stdin is not a tty - 't' flag ignored. */ break; } else { tptr = mytty; if (strncmp(tptr, "/dev/", 5) == 0) tptr += 5; } if (strncmp(tptr, "tty", 3) == 0) tptr += 3; aflg++; gflg++; if (tptr && *tptr == '?') xflg++; while (*ap) ap++; break; case 'u': uflg = 1; break; case 'w': if (wflg) twidth = BUFSIZ; else if (twidth < 132) twidth = 132; wflg++; break; case 'x': xflg++; break; default: if (!isdigit(ap[-1])) break; chkpid = atoi(--ap); *ap = '\0'; aflg++; xflg++; break; } } openfiles(argc, argv); getkvars(argc, argv); lseek(kmem, (off_t)nl[X_PROC].n_value, 0); uid = getuid(); euid = geteuid(); /* handle case where ps is in background and ttyname returns 0 */ if (!mytty) mytty = ""; if (!strncmp(mytty,"/dev/",5)) mytty += 5; if (!strncmp(mytty,"tty",3)) mytty += 3; printhdr(); for (i = 0; i < nproc; i += 8) { j = nproc - i; if (j > 8) j = 8; j *= sizeof (struct proc); if ((nread = read(kmem, (char *) proc, j)) != j) { fprintf(stderr, "ps: error reading proc table from %s\n", kmemf); if (nread == -1) break; } for (j = nread / sizeof (struct proc) - 1; j >= 0; j--) { mproc = &proc[j]; procp = mproc; /* skip processes that don't exist */ if (procp->p_stat == 0) continue; /* skip those without a tty unless -x */ if (procp->p_pgrp == 0 && xflg == 0) continue; /* skip group leaders on a tty unless -g, -x, or -t.. */ if (!tptr && !gflg && !xflg && procp->p_ppid == 1) continue; /* -g also skips those where **argv is "-" - see savcom */ puid = procp->p_uid; /* skip other peoples processes unless -a or a specific pid */ if ((uid != puid && euid != puid && aflg == 0) || (chkpid != 0 && chkpid != procp->p_pid)) continue; if (savcom(puid)) npr++; } } fixup(npr); for (i = 0; i < npr; i++) { register int cmdwidth = twidth - cmdstart - 2; register struct psout *a = &outargs[i]; if (rflg) { if (write(1, (char *) a, sizeof (*a)) != sizeof (*a)) perror("write"); continue; } else if (lflg) lpr(a); else if (uflg) upr(a); else spr(a); if (cmdwidth < 0) cmdwidth = 80 - cmdstart - 2; if (a->o_stat == SZOMB) printf("%.*s", cmdwidth, " <defunct>"); else if (a->o_pid == 0) printf("%.*s", cmdwidth, " swapper"); else printf(" %.*s", twidth - cmdstart - 2, cflg ? a->o_comm : a->o_args); putchar('\n'); } exit(!npr); }
2.203125
2
2024-11-18T19:35:23.233584+00:00
2021-07-11T23:29:09
8a84959c6a32a7edb9c4aab6c0522395e5998d16
{ "blob_id": "8a84959c6a32a7edb9c4aab6c0522395e5998d16", "branch_name": "refs/heads/master", "committer_date": "2021-07-11T23:29:09", "content_id": "94403c5d5017d16f988be2b221bf4fe910d0479a", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "6b0fae428ca6ee32ac9417c0c05a61fad4f47a7e", "extension": "h", "filename": "ds_queue.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 270120894, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 746, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/ds_queue.h", "provenance": "stackv2-0054.json.gz:22111", "repo_name": "Surgams/libdstruct", "revision_date": "2021-07-11T23:29:09", "revision_id": "da3b3e25d80bd9b3b46eec239b87611000506c0b", "snapshot_id": "e6b38372439dea23d96d304a2b65acb9d32b9b99", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Surgams/libdstruct/da3b3e25d80bd9b3b46eec239b87611000506c0b/src/ds_queue.h", "visit_date": "2023-06-06T20:58:35.722886" }
stackv2
/** * Copyright (c) 2020 Surgams * * This library is free software; you can redistribute it and/or modify it * under the terms of the BSD license. See LICENSE for details. * **/ #ifndef DS_QUEUE_H #define DS_QUEUE_H #include <stdint.h> #include "ds_list.h" /* Implement queues as linked lists */ typedef DS_List DS_Queue; typedef DS_List_Ptr DS_Queue_Ptr; /* PUblic Interface */ #define ds_queue_init ds_list_init #define ds_queue_purge ds_list_purge #define ds_queue_free ds_list_free uint8_t ds_queue_enqueue (DS_Queue_Ptr queue, const void *data); uint8_t ds_queue_dequeue (DS_Queue_Ptr queue, void **data); #define ds_queue_peek(queue)((queue)->head == NULL ? NULL : (queue)->head->data) #define ds_queue_size ds_list_size #endif
2.25
2
2024-11-18T19:35:23.819833+00:00
2019-09-07T17:23:55
472bd3e5fe1770741dac5ff2fa42cac1d6e0e8c5
{ "blob_id": "472bd3e5fe1770741dac5ff2fa42cac1d6e0e8c5", "branch_name": "refs/heads/master", "committer_date": "2019-09-07T17:23:55", "content_id": "013a0467972ef8cc9bcef11a88a9628bd95a32c2", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "a564ec14337391f1da7fbf09974364a8354ce541", "extension": "c", "filename": "fibbo.c", "fork_events_count": 5, "gha_created_at": "2017-08-09T02:03:46", "gha_event_created_at": "2017-11-21T09:06:32", "gha_language": "C", "gha_license_id": null, "github_id": 99754591, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 211, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/material/Recursao/src/fibbo.c", "provenance": "stackv2-0054.json.gz:22239", "repo_name": "Gigers/data-struct", "revision_date": "2019-09-07T17:23:55", "revision_id": "f54917247a4e75ffe15783b0a025185d2215309a", "snapshot_id": "37b931204e5460b17d9a7060a072a1035eea167e", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/Gigers/data-struct/f54917247a4e75ffe15783b0a025185d2215309a/material/Recursao/src/fibbo.c", "visit_date": "2021-06-26T11:55:01.686092" }
stackv2
#include <stdio.h> int fibbo(int max){ if(max <= 2){ return 1; } else { return fibbo(max - 1) + fibbo(max - 2); } } void main(void){ int max = 5; printf("%d\n", fibbo(max)); }
3.28125
3
2024-11-18T19:35:23.998591+00:00
2019-10-16T02:00:13
59139bc8bc86dcb03eae6b5edc86aad91b1ca4dc
{ "blob_id": "59139bc8bc86dcb03eae6b5edc86aad91b1ca4dc", "branch_name": "refs/heads/master", "committer_date": "2019-10-16T02:00:13", "content_id": "070e6bb2f3a6b015b97a8030b67a7c7e5db749a0", "detected_licenses": [ "MIT" ], "directory_id": "14ce2b152f202c1f9c30fb39fed145d0ddabfad4", "extension": "c", "filename": "window.c", "fork_events_count": 1, "gha_created_at": "2018-12-27T20:07:20", "gha_event_created_at": "2019-10-15T05:36:19", "gha_language": "C", "gha_license_id": "MIT", "github_id": 163332048, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6440, "license": "MIT", "license_type": "permissive", "path": "/src/de/window/window.c", "provenance": "stackv2-0054.json.gz:22495", "repo_name": "xbuster17/dream-engine", "revision_date": "2019-10-16T02:00:13", "revision_id": "f260b9b5f4a32803232bbc033beff0e0c317e952", "snapshot_id": "cf19ffc6afc25e9d0bb77a1f23e1d2b3d624bcb8", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/xbuster17/dream-engine/f260b9b5f4a32803232bbc033beff0e0c317e952/src/de/window/window.c", "visit_date": "2020-04-13T16:51:11.082249" }
stackv2
#include "window.h" #include "../de_struct.h" #include "../android/glext.h" #ifdef ANDROID #define DE_WINDOW_DEFAULT_FLAGS SDL_WINDOW_BORDERLESS | SDL_WINDOW_RESIZABLE | SDL_WINDOW_FULLSCREEN #else #define DE_WINDOW_DEFAULT_FLAGS SDL_WINDOW_BORDERLESS | SDL_WINDOW_RESIZABLE #endif int dwindow_glext_init(void); void dwindow_glext_quit(void); int dwindow_init(int x, int y, int flags){ dwindow_preconfig(); SDL_Init(SDL_INIT_EVERYTHING); if(!flags) flags = DE_WINDOW_DEFAULT_FLAGS; flags |= SDL_WINDOW_OPENGL; #ifdef ANDROID // only possible window size is screen size x=0; y=0; flags |= SDL_WINDOW_FULLSCREEN; #endif #ifdef __EMSCRIPTEN__ // fix sdl bug by resizing the canvas inmediatelly x=0; y=0; #endif SDL_DisplayMode mode; SDL_GetDisplayMode(0, 0, &mode); if(!x || !y){ x = mode.w; y = mode.h; } De.screen_size[0] = mode.w; De.screen_size[1] = mode.h; De.size[0] = x; De.size[1] = y; De.fsize[0] = x; De.fsize[1] = y; De.res = (float)y / (float)x; #if __EMSCRIPTEN__ // fixme: starts stretched De.win = SDL_CreateWindow("no title", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, x/8, y/8, flags); SDL_SetWindowSize(De.win, x, y); #else De.win = SDL_CreateWindow("no title", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, x, y, flags); #endif if (De.win == NULL) { DE_LOGE("error: could not create window; %s", SDL_GetError()); return 1; } SDL_GetWindowPosition(De.win, &x, &y); De.wpos[0]=x; De.wpos[1]=y; De.ctx = SDL_GL_CreateContext(De.win); SDL_GL_MakeCurrent(De.win, De.ctx); if (dwindow_glext_init()) return 2; dwindow_get_gl_info(); #if defined ANDROID || defined __EMSCRIPTEN__ dwindow_fullscreen(true); #endif // dwindow_resized(x, y); return 0; } void dwindow_quit(void){ SDL_DestroyWindow(De.win); SDL_GL_DeleteContext(De.ctx); // dandroid_glext_quit(); dwindow_glext_quit(); DE_LOG("window destroyed"); } void dwindow_size(int x, int y){ if(De.is_android) return; if(De.size[0] == x && De.size[1] == y) return; SDL_SetWindowSize(De.win, x, y); De.size[0] = x; De.size[1] = y; De.fsize[0] = x; De.fsize[1] = y; } void dwindow_pos(int x, int y){ if(De.is_android) return; if(De.wpos[0] == x && De.wpos[1] == y) return; SDL_SetWindowPosition(De.win, x, y); De.wpos[0] = x; De.wpos[1] = y; } #include "../gl/gl.h" // gl_viewport void dwindow_resized(int x, int y){ assert(x>0); assert(y>0); printf("window resized %i,%i\n",x,y); dfbo_bind(0); dviewport(x, y); De.size = (v2i){x, y}; De.fsize = (v2f){x, y}; De.ctx_size = (v2i){x, y}; De.res = ((float)y) / ((float)x); De.ctx_res = De.res; } bool dwindow_focus(void){ return De.window_focus; } void dwindow_fullscreen(bool b){ SDL_SetWindowFullscreen(De.win, b); #if defined __EMSCRIPTEN__ emscripten_enter_soft_fullscreen("canvas", NULL); #endif } void dwindow_preconfig(void){ #if defined _win32 // opengl 3.0, compatibility profile SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); #elif defined ANDROID // gles 2.0 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); // SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); #elif defined __EMSCRIPTEN__ // gles 3.0 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); #else // gles3.0 for all SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); #endif SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); /* buffer sizes */ // SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); // SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); // SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); // SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); // SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); // SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); /* antialias */ // fixme: not reporting SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4); } void dwindow_title(char* title){ SDL_SetWindowTitle(De.win, title); } void dwindow_get_gl_info(void){ De.gl_driver = (char*)SDL_GetCurrentVideoDriver(); De.gl_version = (char*)glGetString(GL_VERSION); De.gl_renderer = (char*)glGetString(GL_RENDERER); // De.gles_v2 = strstr(De.gl_version, "OpenGL ES 2.") ? true : false; De.gles_v2 = true; } int dwindow_glext_init(void){ De.glext_has_vao = 0; #ifdef _WIN32 GLenum glewError = glewInit(); if (glewError != GLEW_OK) { DE_LOGE("GLEW: ERROR: %s\n", glewGetErrorString(glewError)); return 1; } De.glext_has_vao = 1; #else dandroid_glext_init(); #endif return 0; } void dwindow_glext_quit(void){ } #if 0 #include <dlfcn.h> PFNGLBINDVERTEXARRAYOESPROC glBindVertexArray; PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArrays; PFNGLGENVERTEXARRAYSOESPROC glGenVertexArrays; PFNGLISVERTEXARRAYOESPROC glIsVertexArray; static char _inited = 0; static void* _libhandle; void dandroid_glext_init(void){ // glBindVertexArray = glBindVertexArrayOES; // glDeleteVertexArrays = glDeleteVertexArraysOES; // glGenVertexArrays = glGenVertexArraysOES; // glIsVertexArray = glIsVertexArrayOES; if (_inited) return; _inited = 1; if(De.gles_v2) _libhandle = dlopen( "libGLESv2.so", RTLD_LAZY | RTLD_GLOBAL ); else _libhandle = dlopen( "libGLESv3.so", RTLD_LAZY | RTLD_GLOBAL ); if(!_libhandle) DE_LOGE("libGLESv2/3.so not found!"); //VAO glBindVertexArray = (PFNGLBINDVERTEXARRAYOESPROC)dlsym( _libhandle, "glBindVertexArrayOES"); glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSOESPROC)dlsym( _libhandle, "glDeleteVertexArraysOES"); glGenVertexArrays = (PFNGLGENVERTEXARRAYSOESPROC)dlsym( _libhandle, "glGenVertexArraysOES"); glIsVertexArray = (PFNGLISVERTEXARRAYOESPROC)dlsym(_libhandle, "glIsVertexArrayOES"); if(!glBindVertexArray || !glDeleteVertexArrays || !glGenVertexArrays || !glIsVertexArray) De.glext_has_vao = 0; else De.glext_has_vao = 1; } void dandroid_glext_quit(void){ if (_inited) dlclose(_libhandle); _inited = 0; } #endif
2.265625
2
2024-11-18T19:35:24.093853+00:00
2020-01-20T20:01:38
62dcf7c9f6e63580e91023b948a76c3a8675878c
{ "blob_id": "62dcf7c9f6e63580e91023b948a76c3a8675878c", "branch_name": "refs/heads/master", "committer_date": "2020-01-20T20:01:38", "content_id": "2e9d3230e529831625c447a2124df4f64da77a07", "detected_licenses": [ "Apache-2.0" ], "directory_id": "bbfc04b11097405976358a544a6aeede901d2a4e", "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": 234745110, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4364, "license": "Apache-2.0", "license_type": "permissive", "path": "/apps/scanner/src/main.c", "provenance": "stackv2-0054.json.gz:22623", "repo_name": "stalehd/bacondinner", "revision_date": "2020-01-20T20:01:38", "revision_id": "6b1ed787f174993ce9145b7d7b4684e001960731", "snapshot_id": "5d26911813fbf8225697eeeda677fe852c70405a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/stalehd/bacondinner/6b1ed787f174993ce9145b7d7b4684e001960731/apps/scanner/src/main.c", "visit_date": "2020-12-14T12:33:47.231446" }
stackv2
#include "sysinit/sysinit.h" #include "os/os.h" #include "console/console.h" #include "host/ble_hs.h" #include "host/ble_gap.h" #include "host/ble_hs_adv.h" static void ble_app_set_addr(void) { ble_addr_t addr; int rc; rc = ble_hs_id_gen_rnd(1, &addr); assert(rc == 0); rc = ble_hs_id_set_rnd(addr.val); assert(rc == 0); } static uint64_t devices[10]; static uint8_t didx = 0; static bool add_addr(ble_addr_t addr) { uint64_t *tmp = (uint64_t *)&addr; uint64_t val = *tmp; for (int i = 0; i < 10; i++) { if (devices[i] == val) { return false; } } if (didx >= 10) { didx = 0; } devices[didx++] = val; return true; } static int gap_event_cb(struct ble_gap_event *event, void *arg) { if (event->type == BLE_GAP_EVENT_DISC) { if (add_addr(event->disc.addr)) { console_printf("Found BLE device: %02x%02x%02x %02x%02x%02x RSSI: %d data=%d\n", event->disc.addr.val[0], event->disc.addr.val[1], event->disc.addr.val[2], event->disc.addr.val[3], event->disc.addr.val[4], event->disc.addr.val[5], event->disc.rssi, event->disc.length_data); } /* 02 01 06 1A FF 4C 00 02 15: iBeacon prefix (fixed except for 3rd byte - flags) B9 40 7F 30 F5 F8 46 6E AF F9 25 55 6B 57 FE 6D: proximity UUID (here: Estimote’s fixed UUID) 00 49: major 00 0A: minor C5: 2’s complement of measured TX power */ if (event->disc.addr.val[0] == 0x4c && event->disc.addr.val[1] == 0x00) { // Apple identifier if (event->disc.addr.val[2] == 0x02 && event->disc.addr.val[3] == 0x15) { // iBeacon identifier console_printf("Found iBeacon rssi=%d\n", event->disc.rssi); } } return 0; } if (event->type == BLE_GAP_EVENT_EXT_DISC) { if (event->ext_disc.length_data > 25) { if (event->ext_disc.data[4] == 0xff && event->ext_disc.data[7] == 0x02 && event->ext_disc.data[5] == 0x4c && event->ext_disc.data[6] == 0x00) { // 02 01 06 1a ff 4c 00 02 15 // 01 12 23 34 45 56 67 78 89 9a ab bc cd de ef f0 16 // 00 02 00 0a 00 console_printf("iBeacon major: %02x%02x minor: %02x%02x RSSI: %d (tx power=%02x)\n", event->ext_disc.data[25], event->ext_disc.data[26], event->ext_disc.data[27], event->ext_disc.data[28], event->ext_disc.rssi, event->ext_disc.data[29]); } } return 0; } console_printf("GAP event %d\n", event->type); return 0; } static void ble_app_discover(void) { int rc; struct ble_gap_disc_params disc_params = { .itvl = 0, .window = 0, .filter_policy = 0, .limited = 0, .passive = 1, .filter_duplicates = 0, }; /* struct ble_gap_ext_disc_params disc_params = { .itvl = 0, .window = 0, .passive = 0, };*/ uint8_t own_addr_type; rc = ble_hs_id_infer_auto(0, &own_addr_type); if (rc != 0) { console_printf("Error inferring auto address"); } /* rc = ble_gap_ext_disc(own_addr_type, 0, 0, 0, 0, 0, NULL, NULL, gap_event_cb, NULL);*/ rc = ble_gap_disc(own_addr_type, BLE_HS_FOREVER, &disc_params, gap_event_cb, NULL); if (rc != 0) { console_printf("Error starting discovery: %d\n", rc); } } static void ble_app_on_sync(void) { /* Generate a non-resolvable private address. */ ble_app_set_addr(); /* scan for devices */ ble_app_discover(); console_printf("Sync completed\n"); } int main(int argc, char **argv) { /* Initialize all packages. */ sysinit(); ble_hs_cfg.sync_cb = ble_app_on_sync; ble_hs_cfg.store_status_cb = ble_store_util_status_rr; console_printf("Starting scanner...\n"); /* As the last thing, process events from default event queue. */ while (1) { os_eventq_run(os_eventq_dflt_get()); } return 0; }
2.421875
2
2024-11-18T19:35:24.242626+00:00
2018-11-06T17:51:16
c827ac8d06e25c3803e101fb6b64decda710d732
{ "blob_id": "c827ac8d06e25c3803e101fb6b64decda710d732", "branch_name": "refs/heads/master", "committer_date": "2018-11-06T17:51:16", "content_id": "b3cb1afaf0898e650a7584fdec10d45d44a683fd", "detected_licenses": [ "MIT" ], "directory_id": "14972bb4d48feaff6d52d102076a327253985eb1", "extension": "c", "filename": "user.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": 4382, "license": "MIT", "license_type": "permissive", "path": "/Examples/SIGFOX Radio/user.c", "provenance": "stackv2-0054.json.gz:22881", "repo_name": "BiaMirkai/SIGFOX-EDK", "revision_date": "2018-11-06T17:51:16", "revision_id": "fb7cc6b56f7be329a301e08b18572031bc18bca0", "snapshot_id": "2d733835499c6b8e14fd9c2d6c5341f427209878", "src_encoding": "ISO-8859-1", "star_events_count": 0, "url": "https://raw.githubusercontent.com/BiaMirkai/SIGFOX-EDK/fb7cc6b56f7be329a301e08b18572031bc18bca0/Examples/SIGFOX Radio/user.c", "visit_date": "2020-04-18T03:13:30.791397" }
stackv2
/*************************************************************************************************/ /* INFO */ /*************************************************************************************************/ /* * uDEV Soluções Tecnológicas Ltda * Embedded Development Kit (EDK) * * SIGFOX Radio Example * * In this example, the SIGFOX modem will send one message, without * receive confirmation, and end the transmission. * * To send continuously, re-set the boolean variable to false * within the fnRADIO_CALLBACK_TX_End_Ok( ) function. * * */ /*************************************************************************************************/ /* INCLUDES */ /*************************************************************************************************/ #include "main.h" #include "radio.h" #include "debug.h" #include "console_usb.h" #include "delay_loop.h" /*************************************************************************************************/ /* LOW-POWER OPERATION */ /*************************************************************************************************/ // This variable dictates whether the board operates in low-power mode, // or in normal-power mode. // The default is TRUE, which corresponds to low-power mode. // In low-power, the board cannot communicate via USB, so USB serial communication is // not an option, and using a serial terminal will not work. // To debug via USB, you must set this variable to FALSE. bool __b_system_low_power_enabled__ = false; /*************************************************************************************************/ /* VARIABLES */ /*************************************************************************************************/ bool sent=false; /*************************************************************************************************/ /* INTERNAL FUNCTIONS */ /*************************************************************************************************/ void fnUSER_Setup() { // Code within this context will be run ONCE. fnCONSOLE_USB_Init( ); // After starting the USB Virtual COM Port, we inserted a delay of 500ms to allow // the connection to be established, so we are able to print the SIGFOX data below. fnDELAY_LOOP_ms( 500 ); fnRADIO_Init( ); fnDEBUG_Const_String( "\r\nSigfox ID: " ); fnDEBUG_String_Size( fnRADIO_Get_Sigfox_Id(), 8 ); fnDEBUG_Const_String( "; \r\n" ); fnDEBUG_Const_String( "Sigfox PAC: " ); fnDEBUG_String_Size( fnRADIO_Get_Sigfox_Pac(), 16 ); fnDEBUG_Const_String( "; \r\n" ); fnDEBUG_Uint8_Value( "SIGFOX Downlink Data: ", fnRADIO_Get_Sigfox_Downlink_Data( ), "; \r\n" ); } void fnUSER_Loop( ) { // Code within this context will be run continuously. if ( sent==false ) { // In this configuration, the SIGFOX sends a message without expecting a confirmation // from the server, only a confirmation that the transmission (TX) was successful. fnRADIO_Send_Message( "Test", 4, false ); sent = true; } } // Please check the "radio.h" file in the /SDK/INCLUDES folder for explanations on each function. void fnRADIO_CALLBACK_Tx_End_Ok( ) { fnDEBUG_Const_String( "TX_End_OK\r\n" ); sent = false; } void fnRADIO_CALLBACK_Tx_End_Error( ) { fnDEBUG_Const_String( "TX_End_Error\r\n" ); sent = false; } void fnRADIO_CALLBACK_Rx_End_Ok( ) { fnDEBUG_Const_String( "RX_End_Ok\r\n" ); fnDEBUG_Uint8_Value( "SIGFOX Downlink Data: ", fnRADIO_Get_Sigfox_Downlink_Data( ), "; \r\n" ); sent = false; } void fnRADIO_CALLBACK_Rx_End_Error( ) { fnDEBUG_Const_String( "RX_End_error\r\n" ); sent = false; } /*************************************************************************************************/ /* END OF FILE */ /*************************************************************************************************/
2.375
2
2024-11-18T19:35:24.338645+00:00
2019-12-27T07:59:12
aaaa6cf2ae1ef7a380a9a773d3d693a03f2e1f1a
{ "blob_id": "aaaa6cf2ae1ef7a380a9a773d3d693a03f2e1f1a", "branch_name": "refs/heads/master", "committer_date": "2019-12-27T07:59:12", "content_id": "8446de57fcfdc8ab381f2ad62533f90cf1b7bf9b", "detected_licenses": [ "MIT" ], "directory_id": "1159af3c46f4c23c72d2afd05ec4e520a2ef3014", "extension": "h", "filename": "nGramReader.h", "fork_events_count": 1, "gha_created_at": "2020-03-06T13:44:27", "gha_event_created_at": "2020-03-06T13:44:28", "gha_language": null, "gha_license_id": null, "github_id": 245430346, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1778, "license": "MIT", "license_type": "permissive", "path": "/src/nGramReader.h", "provenance": "stackv2-0054.json.gz:23009", "repo_name": "byzhjj/OMEN", "revision_date": "2019-12-27T07:59:12", "revision_id": "9c593756ae7f3fd77b599acf5d85954a67f4fd9e", "snapshot_id": "f9f42b2d18ba6bc010d68e7ae0c6d29eb5ec1a7c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/byzhjj/OMEN/9c593756ae7f3fd77b599acf5d85954a67f4fd9e/src/nGramReader.h", "visit_date": "2021-02-24T11:35:22.930680" }
stackv2
/* * nGramReader.h * @authors: Fabian Angelstorf, Franziska Juckel * @copyright: Horst Goertz Institute for IT-Security, Ruhr-University Bochum * * Provides functions to read nGram and the according configuration from files * under the given filenames and store them in the given arrays. * */ #ifndef NGRAMREADER_H_ #define NGRAMREADER_H_ #include "common.h" #include "commonStructs.h" // === intern functions === /* * // reads config file * BOOL read_config(); * * // skips the header of given fp * BOOL skip_header(); * * // reads any level file assigning the read values to the given levelArray * BOOL read_levelFromFile(); * * // reads any count file assigning the read values to the given countArray * BOOL read_countFromFile(); * * // reads any array from given file according to the arrayType * BOOL read_array(); */ // === public funtions === /* * Reads all needed input files (levels for nGram and initalProb, count and levels for lengths) * based on the config file that must be set in filenames, creating the filenames (attaching * the default file ending) and sets the corresponding @nGrams and @alphabet variables using the * other read function (read_ngramLevel, read_initialProbLevel, read_lengthLevel, read_lengthCount). * Returns TRUE, if reading was successful. * Otherwise any occurred error can be checked using the @errorHandler */ bool read_inputFiles (struct nGram_struct *nGrams, // nGram arrays (must be initialized) struct alphabet_struct *alphabet, // alphabet (must be initialized) struct filename_struct *filenames, // filenames (must contain a set config file name!) char *maxLevel // max level ); #endif /* NGRAMIO_H_ */
2.109375
2
2024-11-18T19:35:26.458733+00:00
2018-02-16T16:37:21
40a0c994b810ce43ed0fa5aa022f51002289e7e4
{ "blob_id": "40a0c994b810ce43ed0fa5aa022f51002289e7e4", "branch_name": "refs/heads/master", "committer_date": "2018-02-16T16:37:21", "content_id": "4c16e6a5d8cdefe67717a8e81280e0aeb3b5b7c7", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "273851ca87d0e38b4da24d1ab1b53687d23647d0", "extension": "h", "filename": "tcoap_utils.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": 2620, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/tcoap_utils.h", "provenance": "stackv2-0054.json.gz:23396", "repo_name": "waxiangzi/tiny-coap", "revision_date": "2018-02-16T16:37:21", "revision_id": "de9303062bfbe2747fcb2000fe45686457fd7639", "snapshot_id": "80f3d9cfe8640600dfd0ed09cb12df6ce5a890b8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/waxiangzi/tiny-coap/de9303062bfbe2747fcb2000fe45686457fd7639/tcoap_utils.h", "visit_date": "2020-07-06T01:00:04.848333" }
stackv2
/** * tcoap_utils.h * * Author: Serge Maslyakov, [email protected] * Copyright 2017 Serge Maslyakov. All rights reserved. * */ #ifndef __TCOAP_UTILS_H #define __TCOAP_UTILS_H #include "tcoap.h" #ifdef __cplusplus extern "C" { #endif #define TCOAP_CHECK_STATUS(h,s) ((h)->statuses_mask & (s)) #define TCOAP_SET_STATUS(h,s) ((h)->statuses_mask |= (s)) #define TCOAP_RESET_STATUS(h,s) ((h)->statuses_mask &= ~(s)) #define TCOAP_CHECK_RESP(m,s) ((m) & (s)) #define TCOAP_SET_RESP(m,s) ((m) |= (s)) #define TCOAP_RESET_RESP(m,s) ((m) = ~(s)) typedef enum { TCOAP_UNKNOWN = (int) 0x0000, TCOAP_ALL_STATUSES = (int) 0xffff, TCOAP_SENDING_PACKET = (int) 0x0001, TCOAP_WAITING_RESP = (int) 0x0002, TCOAP_DEBUG_ON = (int) 0x0080 } tcoap_handle_status; typedef enum { TCOAP_RESP_EMPTY = (int) 0x00000000, TCOAP_RESP_ACK = (int) 0x00000001, TCOAP_RESP_PIGGYBACKED = (int) 0x00000002, TCOAP_RESP_NRST = (int) 0x00000004, TCOAP_RESP_SEPARATE = (int) 0x00000008, TCOAP_RESP_SUCCESS_CODE = (int) 0x00000010, TCOAP_RESP_FAILURE_CODE = (int) 0x00000020, TCOAP_RESP_TCP_SIGNAL_CODE = (int) 0x00000020, TCOAP_RESP_NEED_SEND_ACK = (int) 0x00000100, TCOAP_RESP_INVALID_PACKET = (int) 0x80000000 } tcoap_parsing_result; /** * @brief Encoding options and add it to the packet * * @param buf - pointer on packet buffer * @param option - pointer on first element of linked list of options. Must not be NULL. * * @return length of data that was added to the buffer */ uint32_t encoding_options(uint8_t * const buf, const tcoap_option_data * option); /** * @brief Decoding options from response * * @param response - incoming packet * @param option - pointer on first element of linked list * @param opt_start_idx - index of options in the incoming packet * @param payload_start_idx - pointer on variable for storing idx of payload in the incoming packet * * @return status of operations */ tcoap_error decoding_options(const tcoap_data * const response, tcoap_option_data * option, const uint32_t const opt_start_idx, uint32_t * const payload_start_idx); /** * @brief Add payload to the packet * * @param buf - pointer on packet buffer * @param payload - data with payload * * @return length of data that was added to the buffer */ uint32_t fill_payload(uint8_t * const buf, const tcoap_data * const payload); #ifdef __cplusplus } #endif #endif /* __TCOAP_UTILS_H */
2.1875
2
2024-11-18T19:35:28.224605+00:00
2022-06-15T08:28:06
e04983980b00eab68a786523aa6b52d7368cdeb6
{ "blob_id": "e04983980b00eab68a786523aa6b52d7368cdeb6", "branch_name": "refs/heads/master", "committer_date": "2022-06-15T08:28:06", "content_id": "a8cca05dd307928b134fcd56fdf193671994674e", "detected_licenses": [ "MIT" ], "directory_id": "8431217d91596f39fac1a3b856dfc75d4dd274f5", "extension": "c", "filename": "decode.c", "fork_events_count": 0, "gha_created_at": "2020-03-09T14:29:24", "gha_event_created_at": "2020-03-09T14:29:25", "gha_language": null, "gha_license_id": "MIT", "github_id": 246057988, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4138, "license": "MIT", "license_type": "permissive", "path": "/C/decode.c", "provenance": "stackv2-0054.json.gz:23653", "repo_name": "Dens49/blurhash", "revision_date": "2022-06-15T08:28:06", "revision_id": "df358338f0b482028ff82a1212fb588839353a1c", "snapshot_id": "b793750e1dc11fd018a5d28dc21a896dc94f63df", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Dens49/blurhash/df358338f0b482028ff82a1212fb588839353a1c/C/decode.c", "visit_date": "2022-07-12T09:41:54.074592" }
stackv2
#include "decode.h" #include "common.h" static char chars[83] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~"; static inline uint8_t clampToUByte(int * src) { if( *src >= 0 && *src <= 255 ) return *src; return (*src < 0) ? 0 : 255; } static inline uint8_t * createByteArray(int size) { return (uint8_t *)malloc(size * sizeof(uint8_t)); } int decodeToInt(const char * string, int start, int end) { int value = 0, iter1 = 0, iter2 = 0; for( iter1 = start; iter1 < end; iter1 ++) { int index = -1; for(iter2 = 0; iter2 < 83; iter2 ++) { if (chars[iter2] == string[iter1]) { index = iter2; break; } } if (index == -1) return -1; value = value * 83 + index; } return value; } bool isValidBlurhash(const char * blurhash) { const int hashLength = strlen(blurhash); if ( !blurhash || strlen(blurhash) < 6) return false; int sizeFlag = decodeToInt(blurhash, 0, 1); //Get size from first character int numY = (int)floorf(sizeFlag / 9) + 1; int numX = (sizeFlag % 9) + 1; if (hashLength != 4 + 2 * numX * numY) return false; return true; } void decodeDC(int value, float * r, float * g, float * b) { *r = sRGBToLinear(value >> 16); // R-component *g = sRGBToLinear((value >> 8) & 255); // G-Component *b = sRGBToLinear(value & 255); // B-Component } void decodeAC(int value, float maximumValue, float * r, float * g, float * b) { int quantR = (int)floorf(value / (19 * 19)); int quantG = (int)floorf(value / 19) % 19; int quantB = (int)value % 19; *r = signPow(((float)quantR - 9) / 9, 2.0) * maximumValue; *g = signPow(((float)quantG - 9) / 9, 2.0) * maximumValue; *b = signPow(((float)quantB - 9) / 9, 2.0) * maximumValue; } int decodeToArray(const char * blurhash, int width, int height, int punch, int nChannels, uint8_t * pixelArray) { if (! isValidBlurhash(blurhash)) return -1; if (punch < 1) punch = 1; int sizeFlag = decodeToInt(blurhash, 0, 1); int numY = (int)floorf(sizeFlag / 9) + 1; int numX = (sizeFlag % 9) + 1; int iter = 0; float r = 0, g = 0, b = 0; int quantizedMaxValue = decodeToInt(blurhash, 1, 2); if (quantizedMaxValue == -1) return -1; float maxValue = ((float)(quantizedMaxValue + 1)) / 166; int colors_size = numX * numY; float colors[colors_size][3]; for(iter = 0; iter < colors_size; iter ++) { if (iter == 0) { int value = decodeToInt(blurhash, 2, 6); if (value == -1) return -1; decodeDC(value, &r, &g, &b); colors[iter][0] = r; colors[iter][1] = g; colors[iter][2] = b; } else { int value = decodeToInt(blurhash, 4 + iter * 2, 6 + iter * 2); if (value == -1) return -1; decodeAC(value, maxValue * punch, &r, &g, &b); colors[iter][0] = r; colors[iter][1] = g; colors[iter][2] = b; } } int bytesPerRow = width * nChannels; int x = 0, y = 0, i = 0, j = 0; int intR = 0, intG = 0, intB = 0; for(y = 0; y < height; y ++) { for(x = 0; x < width; x ++) { float r = 0, g = 0, b = 0; for(j = 0; j < numY; j ++) { for(i = 0; i < numX; i ++) { float basics = cos((M_PI * x * i) / width) * cos((M_PI * y * j) / height); int idx = i + j * numX; r += colors[idx][0] * basics; g += colors[idx][1] * basics; b += colors[idx][2] * basics; } } intR = linearTosRGB(r); intG = linearTosRGB(g); intB = linearTosRGB(b); pixelArray[nChannels * x + 0 + y * bytesPerRow] = clampToUByte(&intR); pixelArray[nChannels * x + 1 + y * bytesPerRow] = clampToUByte(&intG); pixelArray[nChannels * x + 2 + y * bytesPerRow] = clampToUByte(&intB); if (nChannels == 4) pixelArray[nChannels * x + 3 + y * bytesPerRow] = 255; // If nChannels=4, treat each pixel as RGBA instead of RGB } } return 0; } uint8_t * decode(const char * blurhash, int width, int height, int punch, int nChannels) { int bytesPerRow = width * nChannels; uint8_t * pixelArray = createByteArray(bytesPerRow * height); if (decodeToArray(blurhash, width, height, punch, nChannels, pixelArray) == -1) return NULL; return pixelArray; } void freePixelArray(uint8_t * pixelArray) { if (pixelArray) { free(pixelArray); } }
2.796875
3
2024-11-18T19:35:28.400928+00:00
2020-06-30T13:34:01
e0e4749d71b152da248023772c9c0778b8a627be
{ "blob_id": "e0e4749d71b152da248023772c9c0778b8a627be", "branch_name": "refs/heads/master", "committer_date": "2020-06-30T13:34:01", "content_id": "9844cdef7ce0279b05cce3e4d32f5fa8ef65e1be", "detected_licenses": [ "MIT" ], "directory_id": "7f0da976cdc6595e9cdd1b20d9f3e6864af772fe", "extension": "c", "filename": "bsp.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 260966147, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13649, "license": "MIT", "license_type": "permissive", "path": "/module/bsp.c", "provenance": "stackv2-0054.json.gz:23909", "repo_name": "KW-DONG/Relta", "revision_date": "2020-06-30T13:34:01", "revision_id": "8a456699e8194ddd10aa55b4b7f44c6a0c4c9657", "snapshot_id": "4cf482d2ca66ed5d320cfc03a28c3bdb3c7ec127", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/KW-DONG/Relta/8a456699e8194ddd10aa55b4b7f44c6a0c4c9657/module/bsp.c", "visit_date": "2022-11-12T06:56:39.228881" }
stackv2
#include "bsp.h" #include "config.h" //f12,f1,f3,d10,d8,e15,e7,e9,e13 void TIM2_PWM_Detect(void) { //PA2 GPIO_InitTypeDef GPIO_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_Init(GPIOD,&GPIO_InitStructure); } void TIM3_PWM_Detect(void) { //PC11 GPIO_InitTypeDef GPIO_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_Init(GPIOC,&GPIO_InitStructure); } void TIM4_PWM_Detect(void) { //PC10 GPIO_InitTypeDef GPIO_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_Init(GPIOC,&GPIO_InitStructure); } void Bsp_Stepper_Init(void) { GPIO_InitTypeDef GPIO_InitStructure; //Enables or disables the AHB1 peripheral clock. RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA|RCC_AHB1Periph_GPIOD|RCC_AHB1Periph_GPIOC|RCC_AHB1Periph_GPIOF,ENABLE); //direction pin GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15|GPIO_Pin_6; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_Init(GPIOA,&GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7; GPIO_Init(GPIOC,&GPIO_InitStructure); //A4988 microstepping GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6|GPIO_Pin_7|GPIO_Pin_8; GPIO_Init(GPIOF,&GPIO_InitStructure); /* //detect pin GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9|GPIO_Pin_11; GPIO_Init(GPIOC, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; GPIO_Init(GPIOD, &GPIO_InitStructure); */ } void Bsp_TIM2_PWM_Init(uint32_t psc) { GPIO_InitTypeDef GPIO_InitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; TIM_OCInitTypeDef TIM_OCInitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE); GPIO_PinAFConfig(GPIOB,GPIO_PinSource11,GPIO_AF_TIM2); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_Init(GPIOB,&GPIO_InitStructure); TIM_TimeBaseStructure.TIM_Prescaler=psc; TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Down; TIM_TimeBaseStructure.TIM_Period=TIM_ARR; //自动重装载值 TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1; TIM_TimeBaseInit(TIM2,&TIM_TimeBaseStructure);//初始化定时器14 TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2; TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; TIM_OC4Init(TIM2, &TIM_OCInitStructure); TIM_OC4PreloadConfig(TIM2, TIM_OCPreload_Enable); TIM_ARRPreloadConfig(TIM2,ENABLE); TIM_Cmd(TIM2, DISABLE); TIM_SetCompare4(TIM2, TIM_ARR/2); } void Bsp_TIM3_PWM_Init(uint32_t psc) { GPIO_InitTypeDef GPIO_InitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; TIM_OCInitTypeDef TIM_OCInitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE); GPIO_PinAFConfig(GPIOC,GPIO_PinSource6,GPIO_AF_TIM3); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_OD; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_Init(GPIOC,&GPIO_InitStructure); TIM_TimeBaseStructure.TIM_Prescaler=psc; TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Down; TIM_TimeBaseStructure.TIM_Period=TIM_ARR; //自动重装载值 TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1; TIM_TimeBaseInit(TIM3,&TIM_TimeBaseStructure);//初始化定时器14 TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2; TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; TIM_OC1Init(TIM3, &TIM_OCInitStructure); TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable); TIM_ARRPreloadConfig(TIM3,ENABLE); TIM_Cmd(TIM3, DISABLE); TIM_SetCompare1(TIM3, TIM_ARR/2); } void Bsp_TIM4_PWM_Init(uint32_t psc) { GPIO_InitTypeDef GPIO_InitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; TIM_OCInitTypeDef TIM_OCInitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4,ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE); GPIO_PinAFConfig(GPIOB,GPIO_PinSource6,GPIO_AF_TIM4); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_Init(GPIOB,&GPIO_InitStructure); TIM_TimeBaseStructure.TIM_Prescaler=psc; TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Down; TIM_TimeBaseStructure.TIM_Period=TIM_ARR; //自动重装载值 TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1; TIM_TimeBaseInit(TIM4,&TIM_TimeBaseStructure);//初始化定时器14 TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2; TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; TIM_OC1Init(TIM4, &TIM_OCInitStructure); TIM_OC1PreloadConfig(TIM4, TIM_OCPreload_Enable); TIM_ARRPreloadConfig(TIM4,ENABLE); TIM_Cmd(TIM4, DISABLE); TIM_SetCompare1(TIM4, TIM_ARR/2); } void Bsp_TIM5_Init(uint32_t psc) { TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5,ENABLE); TIM_TimeBaseInitStructure.TIM_Period = TIM_ARR; TIM_TimeBaseInitStructure.TIM_Prescaler=psc; TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up; TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV1; TIM_TimeBaseInit(TIM5,&TIM_TimeBaseInitStructure); TIM_ITConfig(TIM5,TIM_IT_Update,ENABLE); TIM_Cmd(TIM5,ENABLE); NVIC_InitStructure.NVIC_IRQChannel=TIM5_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=2; NVIC_InitStructure.NVIC_IRQChannelSubPriority=2; NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE; NVIC_Init(&NVIC_InitStructure); } void Bsp_LED_Init(void) { GPIO_InitTypeDef GPIO_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9|GPIO_Pin_10; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_Init(GPIOF, &GPIO_InitStructure); } void Bsp_UART_Init(uint32_t bound) { GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE); GPIO_PinAFConfig(GPIOA,GPIO_PinSource9,GPIO_AF_USART1); GPIO_PinAFConfig(GPIOA,GPIO_PinSource10,GPIO_AF_USART1); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_Init(GPIOA,&GPIO_InitStructure); USART_InitStructure.USART_BaudRate = bound; USART_InitStructure.USART_WordLength = USART_WordLength_8b; USART_InitStructure.USART_StopBits = USART_StopBits_1; USART_InitStructure.USART_Parity = USART_Parity_No; USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; USART_Init(USART1, &USART_InitStructure); USART_Cmd(USART1, ENABLE); USART_ClearFlag(USART1, USART_FLAG_TC); USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3; NVIC_InitStructure.NVIC_IRQChannelSubPriority =3; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); } void Bsp_UART_Send(uint8_t* content, uint8_t len) { uint8_t i; for (i=0;i<len;i++) { USART_SendData(USART1, content[i]); while(USART_GetFlagStatus(USART1,USART_FLAG_TC)!=SET); } } void Bsp_Switch_Init(void) { GPIO_InitTypeDef GPIO_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1|GPIO_Pin_2|GPIO_Pin_3; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN ; GPIO_Init(GPIOC, &GPIO_InitStructure); } void Bsp_KEY_Init(void) { GPIO_InitTypeDef GPIO_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA|RCC_AHB1Periph_GPIOE, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN ; GPIO_Init(GPIOE, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN ; GPIO_Init(GPIOA, &GPIO_InitStructure); } //key void Bsp_EXTI0_Init(void) { NVIC_InitTypeDef NVIC_InitStructure; EXTI_InitTypeDef EXTI_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE); SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOA, EXTI_PinSource0); EXTI_InitStructure.EXTI_Line = EXTI_Line0; EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising; EXTI_InitStructure.EXTI_LineCmd = ENABLE; EXTI_Init(&EXTI_InitStructure); NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x00; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); } void Bsp_EXTI4_Init(void) { NVIC_InitTypeDef NVIC_InitStructure; EXTI_InitTypeDef EXTI_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE); SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOE, EXTI_PinSource4); EXTI_InitStructure.EXTI_Line = EXTI_Line4; EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising; EXTI_InitStructure.EXTI_LineCmd = ENABLE; EXTI_Init(&EXTI_InitStructure); NVIC_InitStructure.NVIC_IRQChannel = EXTI4_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x00; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); } //limit switch void Bsp_EXTI1_Init(void) { NVIC_InitTypeDef NVIC_InitStructure; EXTI_InitTypeDef EXTI_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE); SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOC, EXTI_PinSource1); EXTI_InitStructure.EXTI_Line = EXTI_Line1; EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling; EXTI_InitStructure.EXTI_LineCmd = ENABLE; EXTI_Init(&EXTI_InitStructure); NVIC_InitStructure.NVIC_IRQChannel = EXTI1_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x00; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x01; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); } void Bsp_EXTI2_Init(void) { NVIC_InitTypeDef NVIC_InitStructure; EXTI_InitTypeDef EXTI_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE); SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOC, EXTI_PinSource2); EXTI_InitStructure.EXTI_Line = EXTI_Line2; EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling; EXTI_InitStructure.EXTI_LineCmd = ENABLE; EXTI_Init(&EXTI_InitStructure); NVIC_InitStructure.NVIC_IRQChannel = EXTI2_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x00; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x01; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); } void Bsp_EXTI3_Init(void) { NVIC_InitTypeDef NVIC_InitStructure; EXTI_InitTypeDef EXTI_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE); SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOC, EXTI_PinSource3); EXTI_InitStructure.EXTI_Line = EXTI_Line3; EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling; EXTI_InitStructure.EXTI_LineCmd = ENABLE; EXTI_Init(&EXTI_InitStructure); NVIC_InitStructure.NVIC_IRQChannel = EXTI3_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x00; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x01; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); }
2.40625
2
2024-11-18T19:35:28.467904+00:00
2023-02-26T18:08:10
6f5b9bc00b77468986a295d589d98a53cfe78730
{ "blob_id": "6f5b9bc00b77468986a295d589d98a53cfe78730", "branch_name": "refs/heads/master", "committer_date": "2023-02-26T18:08:10", "content_id": "d7f70249c2a0e582b3373d51bc0ea2ea2f6db8af", "detected_licenses": [ "MIT" ], "directory_id": "ad47553916e261516cf85d62549405f1eef8bb47", "extension": "c", "filename": "p9.c", "fork_events_count": 5, "gha_created_at": "2019-01-24T12:26:25", "gha_event_created_at": "2023-07-19T12:59:21", "gha_language": "C", "gha_license_id": "MIT", "github_id": 167363898, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1193, "license": "MIT", "license_type": "permissive", "path": "/p9.c", "provenance": "stackv2-0054.json.gz:24037", "repo_name": "aap/pdp11", "revision_date": "2023-02-26T18:08:10", "revision_id": "8f65056c4cfb4107f44d45509314354832a49f18", "snapshot_id": "df98489246217f99558cfc27feb1a802443640ac", "src_encoding": "UTF-8", "star_events_count": 47, "url": "https://raw.githubusercontent.com/aap/pdp11/8f65056c4cfb4107f44d45509314354832a49f18/p9.c", "visit_date": "2023-07-20T12:51:22.160331" }
stackv2
#include "11.h" void exit(int code) { if(code == 0) threadexitsall(nil); threadexitsall("botch"); } void threadmain(int argc, char *argv[]) { int ret; ret = xmain(argc, argv); exit(ret); } static void clockproc(void *arg) { int i; Channel *c; c = arg; for(i = 0; ; i++){ /* tick at 60Hz */ if(i == 2){ i = 0; sleep(17); }else sleep(16); sendul(c, 1); } } void initclock(Clock *clk) { if(clk->chan == nil){ clk->chan = chancreate(sizeof(ulong), 5); proccreate(clockproc, clk->chan, 1024); } } int handleclock(Clock *clk) { static int n; // TODO? maybe check more often? n = (n+1)%100; if(n != 0) return 0; return nbrecvul(clk->chan) != 0; } int ttyopen(Tty *tty) { int fd[2], srvfd; pipe(fd); tty->fd = fd[0]; srvfd = create("/srv/pdp11tty", OWRITE|ORCLOSE|OCEXEC, 0600); if(srvfd < 0) return 1; fprint(srvfd, "%d", fd[1]); return 0; } static void ttyreader(void *arg) { Tty *tty = arg; char c; for(;;){ read(tty->fd, &c, 1); send(tty->chan, &c); } } int ttyinput(Tty *tty, char *c) { if(tty->chan == nil){ tty->chan = chancreate(sizeof(char), 0); proccreate(ttyreader, tty, 1024); } return nbrecv(tty->chan, c) == 1; }
2.421875
2
2024-11-18T19:35:28.737317+00:00
2021-01-31T22:14:59
747534bb26fbea7b5ecd90146b9a1bbf249f2563
{ "blob_id": "747534bb26fbea7b5ecd90146b9a1bbf249f2563", "branch_name": "refs/heads/master", "committer_date": "2021-01-31T22:14:59", "content_id": "68ea839df5023969ca2963d78bea17b53b59f397", "detected_licenses": [ "MIT" ], "directory_id": "8020344780b8ae1860f7c804b81c3d7e9c6bf200", "extension": "c", "filename": "gpio_unit.c", "fork_events_count": 4, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 244537967, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4369, "license": "MIT", "license_type": "permissive", "path": "/MenuManager-V0.1.0/CHARACTER_LCD/GPIO_UNIT/gpio_unit.c", "provenance": "stackv2-0054.json.gz:24550", "repo_name": "Majid-Derhambakhsh/menu-manager", "revision_date": "2021-01-31T22:14:59", "revision_id": "6d78b080cf5d53e54061ac2c727bb058bc4bef34", "snapshot_id": "b16243345d1fd18afbdeb8e01691715d9ef21369", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/Majid-Derhambakhsh/menu-manager/6d78b080cf5d53e54061ac2c727bb058bc4bef34/MenuManager-V0.1.0/CHARACTER_LCD/GPIO_UNIT/gpio_unit.c", "visit_date": "2021-02-11T23:20:34.330705" }
stackv2
/* ------------------------------------------------------------------------------ ~ File : gpio_unit.c ~ Author : Majid Derhambakhsh ~ Version: V0.2.0 ~ Created: 06/29/2019 03:57:00 AM ~ Brief : ~ Support: [email protected] ------------------------------------------------------------------------------ ~ Description: ~ Attention : ~ Changes : Add : GPIO_ReadRegister Function for read data of register Change Driver module name to gpio_unit.x ------------------------------------------------------------------------------ */ #include "gpio_unit.h" /* ------------- Functions ------------- */ void GPIO_WritePin(volatile uint8_t *GPIOx , uint8_t GPIO_Pin , uint8_t PinState) /* Function for write data to output */ { switch (PinState) { case _GPIO_PIN_RESET: { *GPIOx &= ~GPIO_Pin; /* Select and set register value */ } break; case _GPIO_PIN_SET: { *GPIOx |= GPIO_Pin; /* Select and set register value */ } break; } } /* Guide : Parameters : GPIOx : where x can be (A..F) to select the GPIO peripheral for Atmega - Tiny family. GPIO_Pin : specifies the port bit to be written. This parameter can be one of (1 << x) where x can be (0..7). PinState : specifies the value to be written to the selected bit. This parameter can be one of the values: _GPIO_PIN_RESET: to clear the port pin. _GPIO_PIN_SET: to set the port pin. Return Values : Example : GPIO_WritePin( &PORTA , 0xFF , _GPIO_PIN_SET ); GPIO_WritePin( &PORTA , 0xFF , _GPIO_PIN_RESET ); */ /* ------------------------- */ void GPIO_ClearPin(volatile uint8_t *GPIOx , uint8_t GPIO_Pin) /* Function for clear pin */ { *GPIOx &= ~(1 << GPIO_Pin); /* Select and set register value */ } /* Guide : Parameters : GPIOx : where x can be (A..F) to select the GPIO peripheral for Atmega - Tiny family. GPIO_Pin : specifies the port bit to be written. This parameter can be (0..7). Return Values : Example : GPIO_ClearPin( &PORTA , 2 ); */ /* ------------------------- */ uint8_t GPIO_ReadPin(volatile uint8_t *GPIOx , uint8_t GPIO_Pin) /* Function for read pin state */ { return ( (*GPIOx >> GPIO_Pin) & 1); /* Take and return register value */ } /* Guide : Parameters : GPIOx : where x can be (A..F) to select the GPIO peripheral for Atmega - Tiny family. GPIO_Pin : specifies the port bit to be written. This parameter can be (0..7). Return Values : Example : GPIO_ReadPin( &PINA , 3 ); */ /* ------------------------- */ uint8_t GPIO_ReadPort(volatile uint8_t *GPIOx) /* Function for read port value */ { return *GPIOx; /* Take and return register value */ } /* Guide : Parameters : GPIOx : where x can be (A..F) to select the GPIO peripheral for Atmega - Tiny family. Return Values : PINx Register value. Example : uint8_t port_value; port_value = GPIO_ReadPort( &PINA ); */ /* ------------------------- */ void GPIO_TogglePin(volatile uint8_t *GPIOx , uint8_t GPIO_Pin) /* Function for toggle pin */ { *GPIOx ^= (1 << GPIO_Pin); /* Select and set register value */ } /* Guide : Parameters : GPIOx : where x can be (A..F) to select the GPIO peripheral for Atmega - Tiny family. GPIO_Pin : specifies the port bit to be written. This parameter can be (0..7). Return Values : Example : GPIO_TogglePin( &PORTA , 3 ); */ /* ------------------------- */ uint8_t GPIO_ReadRegister(volatile uint8_t *REGISTERx) /* Function for read register value */ { return *REGISTERx; /* Take and return register value */ } /* Guide : Parameters : REGISTERx : Select the GPIO Register for Atmega - Tiny family. Return Values : Register x value. Example : uint8_t register_value; port_value = GPIO_ReadRegister( &DDRA ); */ /* Program End */
2.765625
3
2024-11-18T19:35:28.817706+00:00
2020-11-27T00:46:52
3e869b5ea2839c8152a272017cdcbb8d17ff9043
{ "blob_id": "3e869b5ea2839c8152a272017cdcbb8d17ff9043", "branch_name": "refs/heads/main", "committer_date": "2020-11-27T00:46:52", "content_id": "309752ebaecf4756aa530bb95b06555346a1c113", "detected_licenses": [ "MIT" ], "directory_id": "1062ef41d4d2db3c826500f443d30306d482c1fa", "extension": "c", "filename": "16-binary_tree_is_perfect.c", "fork_events_count": 2, "gha_created_at": "2020-11-23T16:00:26", "gha_event_created_at": "2020-11-24T17:11:55", "gha_language": "C", "gha_license_id": "MIT", "github_id": 315367000, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1508, "license": "MIT", "license_type": "permissive", "path": "/16-binary_tree_is_perfect.c", "provenance": "stackv2-0054.json.gz:24681", "repo_name": "AlisonQuinter17/binary_trees", "revision_date": "2020-11-27T00:46:52", "revision_id": "351ad78bd431037ae586b14b61325d610bac40b1", "snapshot_id": "b8bf8ec53c2e23185ec2d4186b89e45281c9e776", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/AlisonQuinter17/binary_trees/351ad78bd431037ae586b14b61325d610bac40b1/16-binary_tree_is_perfect.c", "visit_date": "2023-01-15T03:38:19.799026" }
stackv2
#include "binary_trees.h" /** * binary_tree_height - measures the height of a binary tree * @tree: a pointer to the root node of the tree to measure the height. * Return: height of a binary tree or 0 if tree is null. */ size_t binary_tree_height(const binary_tree_t *tree) { size_t left_height = 0, right_height = 0; if (!tree || (!tree->left && !tree->right)) { return (0); } left_height = binary_tree_height(tree->left); right_height = binary_tree_height(tree->right); if (left_height < right_height) { return (right_height + 1); } return (left_height + 1); } /** * binary_tree_balance - measures the balance factor of a binary tree. * @tree: Pointer to the root node of the tree to measure the balance factor. * Return: 0 if tree don't exist. **/ int binary_tree_balance(const binary_tree_t *tree) { int l, r; if (!tree) return (0); l = (tree->left) ? (int)binary_tree_height(tree->left) : -1; r = (tree->right) ? (int)binary_tree_height(tree->right) : -1; return (l - r); } /** * binary_tree_is_perfect - Checks if a binary tree is perfect * @tree: Pointer to the root node of the tree to check * Return: 0 or NULL if tree not exist. */ int binary_tree_is_perfect(const binary_tree_t *tree) { int balance, left = 0, right = 0; balance = binary_tree_balance(tree); if (!tree) return (0); if (balance == 0) { left = binary_tree_is_perfect(tree->left); right = binary_tree_is_perfect(tree->right); if (left == right) return (1); } return (0); }
3.203125
3
2024-11-18T19:35:30.287398+00:00
2021-04-21T16:55:12
8b587d31aa210ac4704c6613bfa4ce2d0ed0df47
{ "blob_id": "8b587d31aa210ac4704c6613bfa4ce2d0ed0df47", "branch_name": "refs/heads/main", "committer_date": "2021-04-21T16:55:12", "content_id": "271a97bfa47ed6165452e1331f6833d560bafb55", "detected_licenses": [ "MIT" ], "directory_id": "bc7e827750c17596ec2f345e8565b48c0c3ac7bb", "extension": "c", "filename": "sigmoid.c", "fork_events_count": 0, "gha_created_at": "2021-04-21T16:50:41", "gha_event_created_at": "2021-04-21T16:50:42", "gha_language": null, "gha_license_id": "MIT", "github_id": 360242469, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2299, "license": "MIT", "license_type": "permissive", "path": "/src/sigmoid.c", "provenance": "stackv2-0054.json.gz:24937", "repo_name": "adimehta03/cDNN", "revision_date": "2021-04-21T16:55:12", "revision_id": "75425e01d7948c51b9dcae0524a80d6e3ccdd424", "snapshot_id": "0f0061f69edab45e333e8433b525715950006845", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/adimehta03/cDNN/75425e01d7948c51b9dcae0524a80d6e3ccdd424/src/sigmoid.c", "visit_date": "2023-04-18T21:04:22.037121" }
stackv2
#include <cdnn/activations.h> #include <cdnn/model.h> extern __Model__ * m; dARRAY * forward_pass_sigmoid(){ dARRAY * sigmoid_outf = NULL; sigmoid_outf = (dARRAY*)malloc(sizeof(dARRAY)); sigmoid_outf->matrix = (float*)calloc(m->current_layer->DENSE->cache->shape[0]*m->current_layer->DENSE->cache->shape[1],sizeof(float)); omp_set_num_threads(8); #pragma omp parallel for num_threads(8) shared(sigmoid_outf) schedule(static) for(int i=0;i<m->current_layer->DENSE->cache->shape[0]*m->current_layer->DENSE->cache->shape[1];i++){ float exp_res = 0.0f; //For numerical stability if(m->current_layer->DENSE->cache->matrix[i]>0.0f){ exp_res = (float)exp(-1 * m->current_layer->DENSE->cache->matrix[i]); sigmoid_outf->matrix[i] = 1.0f/(1.0f + exp_res); } else if(m->current_layer->DENSE->cache->matrix[i]<0.0f){ exp_res = (float)exp(m->current_layer->DENSE->cache->matrix[i]); sigmoid_outf->matrix[i] = exp_res/(1.0f + exp_res); } // if(sigmoid_outf->matrix[i]>=0.99f) sigmoid_outf->matrix[i] = 0.98980; // else if(sigmoid_outf->matrix[i]<=0.00001f) sigmoid_outf->matrix[i] = 0.0015; } sigmoid_outf->shape[0] = m->current_layer->DENSE->cache->shape[0]; sigmoid_outf->shape[1] = m->current_layer->DENSE->cache->shape[1]; return sigmoid_outf; } dARRAY * backward_pass_sigmoid(){ dARRAY * sigmoid_outb = NULL; dARRAY * temp = NULL; dARRAY * one = NULL; int dims[] = {m->current_layer->DENSE->A->shape[0],m->current_layer->DENSE->A->shape[1]}; one = ones(dims); temp = subtract(one,m->current_layer->DENSE->A); free2d(one); one=NULL; sigmoid_outb = multiply(m->current_layer->DENSE->A,temp); free2d(temp); temp = NULL; return sigmoid_outb; } Sigmoid * Sigmoid__init__(dARRAY * layer_matrix){ Sigmoid * sigmoid = (Sigmoid*)malloc(sizeof(Sigmoid)); sigmoid->forward = forward_pass_sigmoid; sigmoid->backward = backward_pass_sigmoid; sigmoid->in_dims[0] = sigmoid->out_dims[0] = layer_matrix->shape[0]; sigmoid->in_dims[1] = sigmoid->out_dims[1] = layer_matrix->shape[1]; return sigmoid; } dARRAY * (sigmoid)(Sigmoid_args args){ Sigmoid * s = Sigmoid__init__(args.input); if(!args.status) return s->forward(args.input); else return s->backward(args.input); free(s); s=NULL; }
2.125
2
2024-11-18T19:35:30.472062+00:00
2016-01-27T17:19:21
94ceea149f71859541aa102c81c0495052130853
{ "blob_id": "94ceea149f71859541aa102c81c0495052130853", "branch_name": "refs/heads/master", "committer_date": "2016-01-27T17:19:21", "content_id": "411b8ff899d145cad545c8bb9c0a325da88e459a", "detected_licenses": [ "MIT" ], "directory_id": "649edc1598dbe9f17462ece9992295cb0832f274", "extension": "c", "filename": "task1.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 42600682, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 603, "license": "MIT", "license_type": "permissive", "path": "/2015-2016/A/15/03/task1.c", "provenance": "stackv2-0054.json.gz:25194", "repo_name": "elsys/po-homework-2015-1", "revision_date": "2016-01-27T17:19:21", "revision_id": "797eb1bf06654c0947f71c2e2fdf9577fe334988", "snapshot_id": "2963edb8d84a4ecc07a3a926f00e7ea852a1ca5a", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/elsys/po-homework-2015-1/797eb1bf06654c0947f71c2e2fdf9577fe334988/2015-2016/A/15/03/task1.c", "visit_date": "2021-05-30T18:32:19.479230" }
stackv2
#include <stdio.h> //Ot standartniq vhod se vuvejda chislo n. Trqbva da se izvede triugulnik s visochina n i osnova 2n-1 int main() { int n, i, l; printf("Input triangle height: "); scanf("%d", &n); while(n<2) printf("How do you expect me to create a text triangle with less than 2 characters height?"); for(i=0; i<n; i++) { for(l=0; l<=(n+1+i); l++) { if(l==(n+1) && i==0) printf(".\n"); else if(l==(n+1-i)) printf("/"); else if(l==(n+1+i)) printf("\\\n"); else if(i==n-1 && l>(n+1-i) && l<(n+1+i)) printf("_"); else printf(" "); } } return 1; }
3.234375
3