added
stringdate
2024-11-18 17:54:19
2024-11-19 03:39:31
created
timestamp[s]date
1970-01-01 00:04:39
2023-09-06 04:41:57
id
stringlengths
40
40
metadata
dict
source
stringclasses
1 value
text
stringlengths
13
8.04M
score
float64
2
4.78
int_score
int64
2
5
2024-11-18T21:09:38.341329+00:00
2021-03-22T14:20:25
db6fc52618f1496466694669fa5f798604e3d8cc
{ "blob_id": "db6fc52618f1496466694669fa5f798604e3d8cc", "branch_name": "refs/heads/main", "committer_date": "2021-03-22T14:20:25", "content_id": "198153a92aff10ff8530c75681f6e4d52a7b5100", "detected_licenses": [ "MIT" ], "directory_id": "2c7536c982f716ec9962ab9c1ab1ff818b6fcdd3", "extension": "c", "filename": "lwgsm_parser.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 350370993, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 32390, "license": "MIT", "license_type": "permissive", "path": "/src/lwgsm/lwgsm/src/lwgsm/lwgsm_parser.c", "provenance": "stackv2-0065.json.gz:13915", "repo_name": "ms-rtos/lwgsm_net", "revision_date": "2021-03-22T14:20:25", "revision_id": "9e45b74fedd237641ab5ea41443d43fe4a70d861", "snapshot_id": "d7ff5ef023753c992a4cb223933e57fb63a415bd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ms-rtos/lwgsm_net/9e45b74fedd237641ab5ea41443d43fe4a70d861/src/lwgsm/lwgsm/src/lwgsm/lwgsm_parser.c", "visit_date": "2023-03-26T14:13:25.105488" }
stackv2
/** * \file lwgsm_parser.c * \brief Parse incoming data from AT port */ /* * Copyright (c) 2020 Tilen MAJERLE * * 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 is part of LwGSM - Lightweight GSM-AT library. * * Author: Tilen MAJERLE <[email protected]> * Version: v0.1.0 */ #include "lwgsm/lwgsm_private.h" #include "lwgsm/lwgsm_parser.h" #include "lwgsm/lwgsm_mem.h" /** * \brief Parse number from string * \note Input string pointer is changed and number is skipped * \param[in,out] str: Pointer to pointer to string to parse * \return Parsed number */ int32_t lwgsmi_parse_number(const char** str) { int32_t val = 0; uint8_t minus = 0; const char* p = *str; /* */ if (*p == '"') { /* Skip leading quotes */ ++p; } if (*p == ',') { /* Skip leading comma */ ++p; } if (*p == '"') { /* Skip leading quotes */ ++p; } if (*p == '/') { /* Skip '/' character, used in datetime */ ++p; } if (*p == ':') { /* Skip ':' character, used in datetime */ ++p; } if (*p == '+') { /* Skip '+' character, used in datetime */ ++p; } if (*p == '-') { /* Check negative number */ minus = 1; ++p; } while (LWGSM_CHARISNUM(*p)) { /* Parse until character is valid number */ val = val * 10 + LWGSM_CHARTONUM(*p); ++p; } if (*p == '"') { /* Skip trailling quotes */ ++p; } *str = p; /* Save new pointer with new offset */ return minus ? -val : val; } /** * \brief Parse number from string as hex * \note Input string pointer is changed and number is skipped * \param[in,out] str: Pointer to pointer to string to parse * \return Parsed number */ uint32_t lwgsmi_parse_hexnumber(const char** str) { int32_t val = 0; const char* p = *str; /* */ if (*p == '"') { /* Skip leading quotes */ ++p; } if (*p == ',') { /* Skip leading comma */ ++p; } if (*p == '"') { /* Skip leading quotes */ ++p; } while (LWGSM_CHARISHEXNUM(*p)) { /* Parse until character is valid number */ val = val * 16 + LWGSM_CHARHEXTONUM(*p); ++p; } if (*p == ',') { /* Go to next entry if possible */ ++p; } *str = p; /* Save new pointer with new offset */ return val; } /** * \brief Parse input string as string part of AT command * \param[in,out] src: Pointer to pointer to string to parse from * \param[in] dst: Destination pointer. * Set to `NULL` in case you want to skip string in source * \param[in] dst_len: Length of distance buffer, * including memory for `NULL` termination * \param[in] trim: Set to `1` to process entire string, * even if no memory anymore * \return `1` on success, `0` otherwise */ uint8_t lwgsmi_parse_string(const char** src, char* dst, size_t dst_len, uint8_t trim) { const char* p = *src; size_t i; if (*p == ',') { ++p; } if (*p == '"') { ++p; } i = 0; if (dst_len > 0) { --dst_len; } while (*p) { if ((*p == '"' && (p[1] == ',' || p[1] == '\r' || p[1] == '\n')) || (*p == '\r' || *p == '\n')) { ++p; break; } if (dst != NULL) { if (i < dst_len) { *dst++ = *p; ++i; } else if (!trim) { break; } } ++p; } if (dst != NULL) { *dst = 0; } *src = p; return 1; } /** * \brief Check current string position and trim to the next entry * \param[in] src: Pointer to pointer to input string */ void lwgsmi_check_and_trim(const char** src) { const char* t = *src; if (*t != '"' && *t != '\r' && *t != ',') { /* Check if trim required */ lwgsmi_parse_string(src, NULL, 0, 1); /* Trim to the end */ } } /** * \brief Parse string as IP address * \param[in,out] src: Pointer to pointer to string to parse from * \param[out] ip: Pointer to IP memory * \return `1 on success, 0 otherwise */ uint8_t lwgsmi_parse_ip(const char** src, lwgsm_ip_t* ip) { const char* p = *src; if (*p == ',') { ++p; } if (*p == '"') { ++p; } if (LWGSM_CHARISNUM(*p)) { ip->ip[0] = lwgsmi_parse_number(&p); ++p; ip->ip[1] = lwgsmi_parse_number(&p); ++p; ip->ip[2] = lwgsmi_parse_number(&p); ++p; ip->ip[3] = lwgsmi_parse_number(&p); } if (*p == '"') { ++p; } *src = p; /* Set new pointer */ return 1; } /** * \brief Parse string as MAC address * \param[in,out] src: Pointer to pointer to string to parse from * \param[out] mac: Pointer to MAC memory * \return 1 on success, 0 otherwise */ uint8_t lwgsmi_parse_mac(const char** src, lwgsm_mac_t* mac) { const char* p = *src; if (*p == '"') { ++p; } mac->mac[0] = lwgsmi_parse_hexnumber(&p); ++p; mac->mac[1] = lwgsmi_parse_hexnumber(&p); ++p; mac->mac[2] = lwgsmi_parse_hexnumber(&p); ++p; mac->mac[3] = lwgsmi_parse_hexnumber(&p); ++p; mac->mac[4] = lwgsmi_parse_hexnumber(&p); ++p; mac->mac[5] = lwgsmi_parse_hexnumber(&p); if (*p == '"') { ++p; } if (*p == ',') { ++p; } *src = p; return 1; } /** * \brief Parse memory string, ex. "SM", "ME", "MT", etc * \param[in,out] src: Pointer to pointer to string to parse from * \return Parsed memory */ lwgsm_mem_t lwgsmi_parse_memory(const char** src) { size_t i, sl; lwgsm_mem_t mem = LWGSM_MEM_UNKNOWN; const char* s = *src; if (*s == ',') { ++s; } if (*s == '"') { ++s; } /* Scan all memories available for modem */ for (i = 0; i < lwgsm_dev_mem_map_size; ++i) { sl = strlen(lwgsm_dev_mem_map[i].mem_str); if (!strncmp(s, lwgsm_dev_mem_map[i].mem_str, sl)) { mem = lwgsm_dev_mem_map[i].mem; s += sl; break; } } if (mem == LWGSM_MEM_UNKNOWN) { lwgsmi_parse_string(&s, NULL, 0, 1); /* Skip string */ } if (*s == '"') { ++s; } *src = s; return mem; } /** * \brief Parse a string of memories in format "M1","M2","M3","M4",... * \param[in,out] src: Pointer to pointer to string to parse from * \param[out] mem_dst: Output result with memory list as bit field * \return 1 on success, 0 otherwise */ uint8_t lwgsmi_parse_memories_string(const char** src, uint32_t* mem_dst) { const char* str = *src; lwgsm_mem_t mem; *mem_dst = 0; if (*str == ',') { ++str; } if (*str == '(') { ++str; } do { mem = lwgsmi_parse_memory(&str); /* Parse memory string */ *mem_dst |= LWGSM_U32(1 << LWGSM_U32(mem)); /* Set as bit field */ } while (*str && *str != ')'); if (*str == ')') { ++str; } *src = str; return 1; } /** * \brief Parse received +CREG message * \param[in] str: Input string to parse from * \param[in] skip_first: Set to `1` to skip first number * \return 1 on success, 0 otherwise */ uint8_t lwgsmi_parse_creg(const char* str, uint8_t skip_first) { if (*str == '+') { str += 7; } if (skip_first) { lwgsmi_parse_number(&str); } lwgsm.m.network.status = (lwgsm_network_reg_status_t)lwgsmi_parse_number(&str); /* * In case we are connected to network, * scan for current network info */ if (lwgsm.m.network.status == LWGSM_NETWORK_REG_STATUS_CONNECTED || lwgsm.m.network.status == LWGSM_NETWORK_REG_STATUS_CONNECTED_ROAMING) { /* Try to get operator */ /* Notify user in case we are not able to add new command to queue */ lwgsm_operator_get(&lwgsm.m.network.curr_operator, NULL, NULL, 0); #if LWGSM_CFG_NETWORK } else if (lwgsm_network_is_attached()) { lwgsm_network_check_status(NULL, NULL, 0); /* Do the update */ #endif /* LWGSM_CFG_NETWORK */ } /* Send callback event */ lwgsmi_send_cb(LWGSM_EVT_NETWORK_REG_CHANGED); return 1; } /** * \brief Parse received +CSQ signal value * \param[in] str: Input string * \return 1 on success, 0 otherwise */ uint8_t lwgsmi_parse_csq(const char* str) { int16_t rssi; if (*str == '+') { str += 6; } rssi = lwgsmi_parse_number(&str); if (rssi < 32) { rssi = -(113 - (rssi * 2)); } else { rssi = 0; } lwgsm.m.rssi = rssi; /* Save RSSI to global variable */ if (lwgsm.msg->cmd_def == LWGSM_CMD_CSQ_GET && lwgsm.msg->msg.csq.rssi != NULL) { *lwgsm.msg->msg.csq.rssi = rssi; /* Save to user variable */ } /* Report CSQ status */ lwgsm.evt.evt.rssi.rssi = rssi; lwgsmi_send_cb(LWGSM_EVT_SIGNAL_STRENGTH); /* RSSI event type */ return 1; } /** * \brief Parse received +CPIN status value * \param[in] str: Input string * \param[in] send_evt: Send event about new CPIN status * \return 1 on success, 0 otherwise */ uint8_t lwgsmi_parse_cpin(const char* str, uint8_t send_evt) { lwgsm_sim_state_t state; if (*str == '+') { str += 7; } if (!strncmp(str, "READY", 5)) { state = LWGSM_SIM_STATE_READY; } else if (!strncmp(str, "NOT READY", 9)) { state = LWGSM_SIM_STATE_NOT_READY; } else if (!strncmp(str, "NOT INSERTED", 14)) { state = LWGSM_SIM_STATE_NOT_INSERTED; } else if (!strncmp(str, "SIM PIN", 7)) { state = LWGSM_SIM_STATE_PIN; } else if (!strncmp(str, "SIM PUK", 7)) { state = LWGSM_SIM_STATE_PUK; } else { state = LWGSM_SIM_STATE_NOT_READY; } /* React only on change */ if (state != lwgsm.m.sim.state) { lwgsm.m.sim.state = state; /* * In case SIM is ready, * start with basic info about SIM */ if (lwgsm.m.sim.state == LWGSM_SIM_STATE_READY) { lwgsmi_get_sim_info(0); } if (send_evt) { lwgsm.evt.evt.cpin.state = lwgsm.m.sim.state; lwgsmi_send_cb(LWGSM_EVT_SIM_STATE_CHANGED); } } return 1; } /** * \brief Parse +COPS string from COPS? command * \param[in] str: Input string * \return 1 on success, 0 otherwise */ uint8_t lwgsmi_parse_cops(const char* str) { if (*str == '+') { str += 7; } lwgsm.m.network.curr_operator.mode = (lwgsm_operator_mode_t)lwgsmi_parse_number(&str); if (*str != '\r') { lwgsm.m.network.curr_operator.format = (lwgsm_operator_format_t)lwgsmi_parse_number(&str); if (*str != '\r') { switch (lwgsm.m.network.curr_operator.format) { case LWGSM_OPERATOR_FORMAT_LONG_NAME: lwgsmi_parse_string(&str, lwgsm.m.network.curr_operator.data.long_name, sizeof(lwgsm.m.network.curr_operator.data.long_name), 1); break; case LWGSM_OPERATOR_FORMAT_SHORT_NAME: lwgsmi_parse_string(&str, lwgsm.m.network.curr_operator.data.short_name, sizeof(lwgsm.m.network.curr_operator.data.short_name), 1); break; case LWGSM_OPERATOR_FORMAT_NUMBER: lwgsm.m.network.curr_operator.data.num = LWGSM_U32(lwgsmi_parse_number(&str)); break; default: break; } } } else { lwgsm.m.network.curr_operator.format = LWGSM_OPERATOR_FORMAT_INVALID; } if (CMD_IS_DEF(LWGSM_CMD_COPS_GET) && lwgsm.msg->msg.cops_get.curr != NULL) { /* Check and copy to user variable */ LWGSM_MEMCPY(lwgsm.msg->msg.cops_get.curr, &lwgsm.m.network.curr_operator, sizeof(*lwgsm.msg->msg.cops_get.curr)); } return 1; } /** * \brief Parse +COPS received statement byte by byte * \note Command must be active and message set to use this function * \param[in] ch: New character to parse * \param[in] reset: Flag to reset state machine * \return 1 on success, 0 otherwise */ uint8_t lwgsmi_parse_cops_scan(uint8_t ch, uint8_t reset) { static union { struct { uint8_t bo: 1; /*!< Bracket open flag (Bracket Open) */ uint8_t ccd: 1; /*!< 2 consecutive commas detected in a row (Comma Comma Detected) */ uint8_t tn: 2; /*!< Term number in response, 2 bits for 4 diff values */ uint8_t tp; /*!< Current term character position */ uint8_t ch_prev; /*!< Previous character */ } f; } u; if (reset) { /* Check for reset status */ LWGSM_MEMSET(&u, 0x00, sizeof(u)); /* Reset everything */ u.f.ch_prev = 0; return 1; } if (u.f.ch_prev == 0) { /* Check if this is first character */ if (ch == ' ') { /* Skip leading spaces */ return 1; } else if (ch == ',') { /* If first character is comma, no operators available */ u.f.ccd = 1; /* Fake double commas in a row */ } } if (u.f.ccd || /* Ignore data after 2 commas in a row */ lwgsm.msg->msg.cops_scan.opsi >= lwgsm.msg->msg.cops_scan.opsl) { /* or if array is full */ return 1; } if (u.f.bo) { /* Bracket already open */ if (ch == ')') { /* Close bracket check */ u.f.bo = 0; /* Clear bracket open flag */ u.f.tn = 0; /* Go to next term */ u.f.tp = 0; /* Go to beginning of next term */ ++lwgsm.msg->msg.cops_scan.opsi; /* Increase index */ if (lwgsm.msg->msg.cops_scan.opf != NULL) { *lwgsm.msg->msg.cops_scan.opf = lwgsm.msg->msg.cops_scan.opsi; } } else if (ch == ',') { ++u.f.tn; /* Go to next term */ u.f.tp = 0; /* Go to beginning of next term */ } else if (ch != '"') { /* We have valid data */ size_t i = lwgsm.msg->msg.cops_scan.opsi; switch (u.f.tn) { case 0: { /* Parse status info */ lwgsm.msg->msg.cops_scan.ops[i].stat = (lwgsm_operator_status_t)(10 * (size_t)lwgsm.msg->msg.cops_scan.ops[i].stat + (ch - '0')); break; } case 1: { /*!< Parse long name */ if (u.f.tp < sizeof(lwgsm.msg->msg.cops_scan.ops[i].long_name) - 1) { lwgsm.msg->msg.cops_scan.ops[i].long_name[u.f.tp] = ch; lwgsm.msg->msg.cops_scan.ops[i].long_name[++u.f.tp] = 0; } break; } case 2: { /*!< Parse short name */ if (u.f.tp < sizeof(lwgsm.msg->msg.cops_scan.ops[i].short_name) - 1) { lwgsm.msg->msg.cops_scan.ops[i].short_name[u.f.tp] = ch; lwgsm.msg->msg.cops_scan.ops[i].short_name[++u.f.tp] = 0; } break; } case 3: { /*!< Parse number */ lwgsm.msg->msg.cops_scan.ops[i].num = (10 * lwgsm.msg->msg.cops_scan.ops[i].num) + (ch - '0'); break; } default: break; } } } else { if (ch == '(') { /* Check for opening bracket */ u.f.bo = 1; } else if (ch == ',' && u.f.ch_prev == ',') { u.f.ccd = 1; /* 2 commas in a row */ } } u.f.ch_prev = ch; return 1; } /** * \brief Parse datetime in format dd/mm/yy,hh:mm:ss * \param[in] src: Pointer to pointer to input string * \param[out] dt: Date time structure * \return 1 on success, 0 otherwise */ uint8_t lwgsmi_parse_datetime(const char** src, lwgsm_datetime_t* dt) { dt->date = lwgsmi_parse_number(src); dt->month = lwgsmi_parse_number(src); dt->year = LWGSM_U16(2000) + lwgsmi_parse_number(src); dt->hours = lwgsmi_parse_number(src); dt->minutes = lwgsmi_parse_number(src); dt->seconds = lwgsmi_parse_number(src); lwgsmi_check_and_trim(src); /* Trim text to the end */ return 1; } #if LWGSM_CFG_CALL || __DOXYGEN__ /** * \brief Parse received +CLCC with call status info * \param[in] str: Input string * \param[in] send_evt: Send event about new CPIN status * \return 1 on success, 0 otherwise */ uint8_t lwgsmi_parse_clcc(const char* str, uint8_t send_evt) { if (*str == '+') { str += 7; } lwgsm.m.call.id = lwgsmi_parse_number(&str); lwgsm.m.call.dir = (lwgsm_call_dir_t)lwgsmi_parse_number(&str); lwgsm.m.call.state = (lwgsm_call_state_t)lwgsmi_parse_number(&str); lwgsm.m.call.type = (lwgsm_call_type_t)lwgsmi_parse_number(&str); lwgsm.m.call.is_multipart = (lwgsm_call_type_t)lwgsmi_parse_number(&str); lwgsmi_parse_string(&str, lwgsm.m.call.number, sizeof(lwgsm.m.call.number), 1); lwgsm.m.call.addr_type = lwgsmi_parse_number(&str); lwgsmi_parse_string(&str, lwgsm.m.call.name, sizeof(lwgsm.m.call.name), 1); if (send_evt) { lwgsm.evt.evt.call_changed.call = &lwgsm.m.call; lwgsmi_send_cb(LWGSM_EVT_CALL_CHANGED); } return 1; } #endif /* LWGSM_CFG_CALL || __DOXYGEN__ */ #if LWGSM_CFG_SMS || __DOXYGEN__ /** * \brief Parse string and check for type of SMS state * \param[in] src: Pointer to pointer to string to parse * \param[out] stat: Output status variable * \return 1 on success, 0 otherwise */ uint8_t lwgsmi_parse_sms_status(const char** src, lwgsm_sms_status_t* stat) { lwgsm_sms_status_t s; char t[11]; lwgsmi_parse_string(src, t, sizeof(t), 1); /* Parse string and advance */ if (!strcmp(t, "REC UNREAD")) { s = LWGSM_SMS_STATUS_UNREAD; } else if (!strcmp(t, "REC READ")) { s = LWGSM_SMS_STATUS_READ; } else if (!strcmp(t, "STO UNSENT")) { s = LWGSM_SMS_STATUS_UNSENT; } else if (!strcmp(t, "REC SENT")) { s = LWGSM_SMS_STATUS_SENT; } else { s = LWGSM_SMS_STATUS_ALL; /* Error! */ } if (s != LWGSM_SMS_STATUS_ALL) { *stat = s; return 1; } return 0; } /** * \brief Parse received +CMGS with last sent SMS memory info * \param[in] str: Input string * \param[in] num: Parsed number in memory * \return `1` on success, `0` otherwise */ uint8_t lwgsmi_parse_cmgs(const char* str, size_t* num) { if (*str == '+') { str += 7; } if (num != NULL) { *num = (size_t)lwgsmi_parse_number(&str); } return 1; } /** * \brief Parse +CMGR statement * \todo Parse date and time from SMS entry * \param[in] str: Input string * \return 1 on success, 0 otherwise */ uint8_t lwgsmi_parse_cmgr(const char* str) { lwgsm_sms_entry_t* e; if (*str == '+') { str += 7; } e = lwgsm.msg->msg.sms_read.entry; e->length = 0; lwgsmi_parse_sms_status(&str, &e->status); lwgsmi_parse_string(&str, e->number, sizeof(e->number), 1); lwgsmi_parse_string(&str, e->name, sizeof(e->name), 1); lwgsmi_parse_datetime(&str, &e->datetime); return 1; } /** * \brief Parse +CMGL statement * \todo Parse date and time from SMS entry * \param[in] str: Input string * \return 1 on success, 0 otherwise */ uint8_t lwgsmi_parse_cmgl(const char* str) { lwgsm_sms_entry_t* e; if (!CMD_IS_DEF(LWGSM_CMD_CMGL) || lwgsm.msg->msg.sms_list.ei >= lwgsm.msg->msg.sms_list.etr) { return 0; } if (*str == '+') { str += 7; } e = &lwgsm.msg->msg.sms_list.entries[lwgsm.msg->msg.sms_list.ei]; e->length = 0; e->mem = lwgsm.msg->msg.sms_list.mem; /* Manually set memory */ e->pos = LWGSM_SZ(lwgsmi_parse_number(&str)); /* Scan position */ lwgsmi_parse_sms_status(&str, &e->status); lwgsmi_parse_string(&str, e->number, sizeof(e->number), 1); lwgsmi_parse_string(&str, e->name, sizeof(e->name), 1); lwgsmi_parse_datetime(&str, &e->datetime); return 1; } /** * \brief Parse received +CMTI with received SMS info * \param[in] str: Input string * \param[in] send_evt: Send event about new CPIN status * \return 1 on success, 0 otherwise */ uint8_t lwgsmi_parse_cmti(const char* str, uint8_t send_evt) { if (*str == '+') { str += 7; } lwgsm.evt.evt.sms_recv.mem = lwgsmi_parse_memory(&str); /* Parse memory string */ lwgsm.evt.evt.sms_recv.pos = lwgsmi_parse_number(&str); /* Parse number */ if (send_evt) { lwgsmi_send_cb(LWGSM_EVT_SMS_RECV); } return 1; } /** * \brief Parse +CPMS statement * \param[in] str: Input string * \param[in] opt: Expected input: 0 = CPMS_OPT, 1 = CPMS_GET, 2 = CPMS_SET * \return 1 on success, 0 otherwise */ uint8_t lwgsmi_parse_cpms(const char* str, uint8_t opt) { uint8_t i; if (*str == '+') { str += 7; } switch (opt) { /* Check expected input string */ case 0: { /* Get list of CPMS options: +CPMS: (("","","",..),("....")("...")) */ for (i = 0; i < 3; ++i) { /* 3 different memories for "operation","receive","sent" */ if (!lwgsmi_parse_memories_string(&str, &lwgsm.m.sms.mem[i].mem_available)) { return 0; } } break; } case 1: { /* Received statement of current info: +CPMS: "ME",10,20,"SE",2,20,"... */ for (i = 0; i < 3; ++i) { /* 3 memories expected */ lwgsm.m.sms.mem[i].current = lwgsmi_parse_memory(&str); /* Parse memory string and save it as current */ lwgsm.m.sms.mem[i].used = lwgsmi_parse_number(&str);/* Get used memory size */ lwgsm.m.sms.mem[i].total = lwgsmi_parse_number(&str); /* Get total memory size */ } break; } case 2: { /* Received statement of set info: +CPMS: 10,20,2,20 */ for (i = 0; i < 3; ++i) { /* 3 memories expected */ lwgsm.m.sms.mem[i].used = lwgsmi_parse_number(&str);/* Get used memory size */ lwgsm.m.sms.mem[i].total = lwgsmi_parse_number(&str); /* Get total memory size */ } break; } default: break; } return 1; } #endif /* LWGSM_CFG_SMS || __DOXYGEN__ */ #if LWGSM_CFG_PHONEBOOK || __DOXYGEN__ /** * \brief Parse +CPBS statement * \param[in] str: Input string * \param[in] opt: Expected input: 0 = CPBS_OPT, 1 = CPBS_GET, 2 = CPBS_SET * \return 1 on success, 0 otherwise */ uint8_t lwgsmi_parse_cpbs(const char* str, uint8_t opt) { if (*str == '+') { str += 7; } switch (opt) { /* Check expected input string */ case 0: { /* Get list of CPBS options: ("M1","M2","M3",...) */ return lwgsmi_parse_memories_string(&str, &lwgsm.m.pb.mem.mem_available); } case 1: { /* Received statement of current info: +CPBS: "ME",10,20 */ lwgsm.m.pb.mem.current = lwgsmi_parse_memory(&str); /* Parse memory string and save it as current */ lwgsm.m.pb.mem.used = lwgsmi_parse_number(&str);/* Get used memory size */ lwgsm.m.pb.mem.total = lwgsmi_parse_number(&str); /* Get total memory size */ break; } case 2: { /* Received statement of set info: +CPBS: 10,20 */ lwgsm.m.pb.mem.used = lwgsmi_parse_number(&str);/* Get used memory size */ lwgsm.m.pb.mem.total = lwgsmi_parse_number(&str); /* Get total memory size */ break; } } return 1; } /** * \brief Parse +CPBR statement * \param[in] str: Input string * \return 1 on success, 0 otherwise */ uint8_t lwgsmi_parse_cpbr(const char* str) { lwgsm_pb_entry_t* e; if (!CMD_IS_DEF(LWGSM_CMD_CPBR) || lwgsm.msg->msg.pb_list.ei >= lwgsm.msg->msg.pb_list.etr) { return 0; } if (*str == '+') { str += 7; } e = &lwgsm.msg->msg.pb_list.entries[lwgsm.msg->msg.pb_list.ei]; e->pos = LWGSM_SZ(lwgsmi_parse_number(&str)); lwgsmi_parse_string(&str, e->name, sizeof(e->name), 1); e->type = (lwgsm_number_type_t)lwgsmi_parse_number(&str); lwgsmi_parse_string(&str, e->number, sizeof(e->number), 1); ++lwgsm.msg->msg.pb_list.ei; if (lwgsm.msg->msg.pb_list.er != NULL) { *lwgsm.msg->msg.pb_list.er = lwgsm.msg->msg.pb_list.ei; } return 1; } /** * \brief Parse +CPBF statement * \param[in] str: Input string * \return 1 on success, 0 otherwise */ uint8_t lwgsmi_parse_cpbf(const char* str) { lwgsm_pb_entry_t* e; if (!CMD_IS_DEF(LWGSM_CMD_CPBF) || lwgsm.msg->msg.pb_search.ei >= lwgsm.msg->msg.pb_search.etr) { return 0; } if (*str == '+') { str += 7; } e = &lwgsm.msg->msg.pb_search.entries[lwgsm.msg->msg.pb_search.ei]; e->pos = LWGSM_SZ(lwgsmi_parse_number(&str)); lwgsmi_parse_string(&str, e->name, sizeof(e->name), 1); e->type = (lwgsm_number_type_t)lwgsmi_parse_number(&str); lwgsmi_parse_string(&str, e->number, sizeof(e->number), 1); ++lwgsm.msg->msg.pb_search.ei; if (lwgsm.msg->msg.pb_search.er != NULL) { *lwgsm.msg->msg.pb_search.er = lwgsm.msg->msg.pb_search.ei; } return 1; } #endif /* LWGSM_CFG_PHONEBOOK || __DOXYGEN__ */ #if LWGSM_CFG_CONN /** * \brief Parse connection info line from CIPSTATUS command * \param[in] str: Input string * \param[in] is_conn_line: Set to `1` for connection, `0` for general status * \param[out] continueScan: Pointer to output variable holding continue processing state * \return `1` on success, `0` otherwise */ uint8_t lwgsmi_parse_cipstatus_conn(const char* str, uint8_t is_conn_line, uint8_t* continueScan) { uint8_t num; lwgsm_conn_t* conn; char s_tmp[16]; uint8_t tmp_pdp_state; *continueScan = 1; if (is_conn_line && (*str == 'C' || *str == 'S')) { str += 3; } else { /* Check if PDP context is deactivated or not */ tmp_pdp_state = 1; if (!strncmp(&str[7], "IP INITIAL", 10)) { *continueScan = 0; /* Stop command execution at this point (no OK,ERROR received after this line) */ tmp_pdp_state = 0; } else if (!strncmp(&str[7], "PDP DEACT", 9)) { /* Deactivated */ tmp_pdp_state = 0; } /* Check if we have to update status for application */ if (lwgsm.m.network.is_attached != tmp_pdp_state) { lwgsm.m.network.is_attached = tmp_pdp_state; /* Notify upper layer */ lwgsmi_send_cb(lwgsm.m.network.is_attached ? LWGSM_EVT_NETWORK_ATTACHED : LWGSM_EVT_NETWORK_DETACHED); } return 1; } /* Parse connection line */ num = LWGSM_U8(lwgsmi_parse_number(&str)); conn = &lwgsm.m.conns[num]; conn->status.f.bearer = LWGSM_U8(lwgsmi_parse_number(&str)); lwgsmi_parse_string(&str, s_tmp, sizeof(s_tmp), 1); /* Parse TCP/UPD */ if (strlen(s_tmp)) { if (!strcmp(s_tmp, "TCP")) { conn->type = LWGSM_CONN_TYPE_TCP; } else if (!strcmp(s_tmp, "UDP")) { conn->type = LWGSM_CONN_TYPE_UDP; } } lwgsmi_parse_ip(&str, &conn->remote_ip); conn->remote_port = lwgsmi_parse_number(&str); /* Get connection status */ lwgsmi_parse_string(&str, s_tmp, sizeof(s_tmp), 1); /* TODO: Implement all connection states */ if (!strcmp(s_tmp, "INITIAL")) { } else if (!strcmp(s_tmp, "CONNECTING")) { } else if (!strcmp(s_tmp, "CONNECTED")) { } else if (!strcmp(s_tmp, "REMOTE CLOSING")) { } else if (!strcmp(s_tmp, "CLOSING")) { } else if (!strcmp(s_tmp, "CLOSED")) { /* Connection closed */ if (conn->status.f.active) { /* Check if connection is not */ lwgsmi_conn_closed_process(conn->num, 0); /* Process closed event */ } } /* Save last parsed connection */ lwgsm.m.active_conns_cur_parse_num = num; return 1; } /** * \brief Parse IPD or RECEIVE statements * \param[in] str: Input string * \return `1` on success, `0` otherwise */ uint8_t lwgsmi_parse_ipd(const char* str) { uint8_t conn; size_t len; lwgsm_conn_p c; if (*str == '+') { ++str; if (*str == 'R') { str += 8; /* Advance for RECEIVE */ } else { str += 4; /* Advance for IPD */ } } conn = lwgsmi_parse_number(&str); /* Parse number for connection number */ len = lwgsmi_parse_number(&str); /* Parse number for number of bytes to read */ c = conn < LWGSM_CFG_MAX_CONNS ? &lwgsm.m.conns[conn] : NULL; /* Get connection handle */ if (c == NULL) { /* Invalid connection number */ return 0; } lwgsm.m.ipd.read = 1; /* Start reading network data */ lwgsm.m.ipd.tot_len = len; /* Total number of bytes in this received packet */ lwgsm.m.ipd.rem_len = len; /* Number of remaining bytes to read */ lwgsm.m.ipd.conn = c; /* Pointer to connection we have data for */ return 1; } #endif /* LWGSM_CFG_CONN */
2.28125
2
2024-11-18T21:09:38.515556+00:00
2019-04-12T05:18:46
b365b2f8a297ee7f5117396b088bdb1c84146264
{ "blob_id": "b365b2f8a297ee7f5117396b088bdb1c84146264", "branch_name": "refs/heads/master", "committer_date": "2019-04-12T05:18:46", "content_id": "882e14220c8271e15a9584840807429ee23b36ba", "detected_licenses": [ "MIT" ], "directory_id": "5ce3b27bf43030a41291bb16aadbd303380c4b07", "extension": "c", "filename": "fSentence.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": 5936, "license": "MIT", "license_type": "permissive", "path": "/palmos/dictate/Dictate-1.5/src/fSentence.c", "provenance": "stackv2-0065.json.gz:14173", "repo_name": "m-schofield-ia/Portfolio", "revision_date": "2019-04-12T05:18:46", "revision_id": "a2fb9f0e096d829ad7928c3cefa870dccc2cff38", "snapshot_id": "96feed6b892462b1bcbdc521aafec17bc990ed3a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/m-schofield-ia/Portfolio/a2fb9f0e096d829ad7928c3cefa870dccc2cff38/palmos/dictate/Dictate-1.5/src/fSentence.c", "visit_date": "2021-05-17T16:16:12.083200" }
stackv2
/* * fSentence.c */ #include "Include.h" /* protos */ static Boolean SaveData(UInt32 *); static void DeleteSentence(UInt16); /* globals */ static UInt16 recordIdx, cancelIdx; /* * fSentenceDrawTable * * Draw a sentence table. * * -> tbl Table. * -> row Current row. * -> column Current column. * -> r Rectangle. */ void fSentenceDrawTable(void *tbl, Int16 row, Int16 column, RectangleType *r) { UInt16 recIdx=0, pW, len; MemHandle mh; Char *p; Boolean trunc; if (DmSeekRecordInCategory(dbTSentence.db, &recIdx, tblSentence.top+row, dmSeekForward, prefs.catSentenceIdx)!=errNone) return; TblSetRowData(tbl, row, (UInt32)recIdx); WinEraseRectangle(r, 0); WinDrawBitmap(bmpBullet, r->topLeft.x, r->topLeft.y+3); mh=DBGetRecord(&dbTSentence, recIdx); p=MemHandleLock(mh); pW=r->extent.x-10; len=StrLen(p); FntCharsInWidth(p, &pW, &len, &trunc); WinDrawChars(p, len, r->topLeft.x+10, r->topLeft.y); MemHandleUnlock(mh); } /* * fSentenceInit */ Boolean fSentenceInit(void) { UIPopupSet(&dbTSentence, prefs.catSentenceIdx, catSentenceName, cSentencePopup); UITableInit(&dbTSentence, &tblSentence, cSentenceTable, cSentenceScrollBar, fSentenceDrawTable, tsCustom1); return true; } /* * fSentenceEH */ Boolean fSentenceEH(EventType *ev) { Boolean edited; UInt16 category; switch (ev->eType) { case frmOpenEvent: FrmDrawForm(currentForm); return true; case ctlSelectEvent: switch (ev->data.ctlSelect.controlID) { case cSentenceNew: recordIdx=dmMaxRecordIndex; FrmGotoForm(fEditSentence); return true; case cSentenceGroups: FrmGotoForm(fTeacher); return true; case cSentencePopup: category=prefs.catSentenceIdx; edited=CategorySelect(dbTSentence.db, currentForm, cSentencePopup, cSentenceList, true, &prefs.catSentenceIdx, catSentenceName, 1, 0); if (edited || (category!=prefs.catSentenceIdx)) { tblSentence.records=DmNumRecordsInCategory(dbTSentence.db, prefs.catSentenceIdx); UITableUpdateValues(&tblSentence, true); } return true; } break; case menuEvent: switch (ev->data.menu.itemID) { case mSentenceImport: fSentenceImportRun(); tblSentence.records=DmNumRecordsInCategory(dbTSentence.db, prefs.catSentenceIdx); UITableUpdateValues(&tblSentence, true); return true; case mSentenceExport: fSentenceExportRun(); tblSentence.records=DmNumRecordsInCategory(dbTSentence.db, prefs.catSentenceIdx); UITableUpdateValues(&tblSentence, true); return true; } break; case tblSelectEvent: recordIdx=(UInt16)TblGetRowData(tblSentence.tbl, ev->data.tblSelect.row); FrmGotoForm(fEditSentence); return true; default: UITableEvents(&tblSentence, ev); break; } return false; } /* * fSentenceEditFromPrefs * * Possible open up the fEditSentence form from preferences. */ void fSentenceEditFromPrefs(void) { UInt32 uid; if (PMGetPref(&uid, sizeof(UInt32), PrfEdit)==true) { if (DmFindRecordByID(dbTSentence.db, uid, &recordIdx)==errNone) { FrmGotoForm(fEditSentence); return; } } FrmGotoForm(fTeacher); } /* * fEditSentenceInit */ Boolean fEditSentenceInit(void) { MemHandle mh; cancelIdx=prefs.catSentenceIdx; if (prefs.catSentenceIdx==dmAllCategories) prefs.catSentenceIdx=dmUnfiledCategory; if (recordIdx!=dmMaxRecordIndex) { UInt16 attrs; mh=DBGetRecord(&dbTSentence, recordIdx); UIFieldSetText(cEditSentenceField, MemHandleLock(mh)); MemHandleUnlock(mh); UIObjectShow(cEditSentenceDelete); DmRecordInfo(dbTSentence.db, recordIdx, &attrs, NULL, NULL); prefs.catSentenceIdx=attrs&dmRecAttrCategoryMask; } UIPopupSet(&dbTSentence, prefs.catSentenceIdx, catSentenceName, cEditSentencePopup); UIFieldFocus(cEditSentenceField); UIFieldUpdateScrollBar(cEditSentenceField, cEditSentenceScrollBar); return true; } /* * EditSentenceEH */ Boolean fEditSentenceEH(EventType *ev) { switch (ev->eType) { case frmOpenEvent: FrmDrawForm(currentForm); break; case frmSaveEvent: if (appStopped) { UInt32 uid; if (SaveData(&uid)==true) PMSetPref(&uid, sizeof(UInt32), PrfEdit); } break; case ctlSelectEvent: switch (ev->data.ctlSelect.controlID) { case cEditSentencePopup: CategorySelect(dbTSentence.db, currentForm, cEditSentencePopup, cEditSentenceList, false, &prefs.catSentenceIdx, catSentenceName, 1, 0); return true; case cEditSentenceOK: SaveData(NULL); FrmGotoForm(fSentence); return true; case cEditSentenceCancel: UIFieldSetText(cEditSentenceField, ""); PMSetPref(NULL, 0, PrfEdit); prefs.catSentenceIdx=cancelIdx; FrmGotoForm(fSentence); return true; case cEditSentenceDelete: if (FrmAlert(aDeleteSentence)==0) { DeleteSentence(recordIdx); FrmGotoForm(fSentence); } return true; } break; case keyDownEvent: UIFieldScrollBarKeyHandler(ev, cEditSentenceField, cEditSentenceScrollBar); default: /* FALL-THRU */ UIFieldScrollBarHandler(ev, cEditSentenceField, cEditSentenceScrollBar); break; } return false; } /* * SaveData * * Save data from text field. * * <- uid Where to store record UID. * * Returns true if data was saved, false otherwise. */ static Boolean SaveData(UInt32 *uid) { Char *p=UIFieldGetText(cEditSentenceField); UInt16 len; Char buffer[SentenceLength+1]; UInt32 u; if (!p) return false; if ((len=StrLen(p))<1) return false; MemMove(buffer, p, len); buffer[len]='\x00'; if ((p=StringPurify(buffer))==NULL) return false; UIFieldSetText(cEditSentenceField, ""); u=DBSetRecord(&dbTSentence, recordIdx, prefs.catSentenceIdx, p, StrLen(p)+1, SFString); if (uid) *uid=u; MemPtrFree(p); return true; } /* * DeleteSentence * * Delete a sentence from all databases. * * -> rIdx Record index. */ static void DeleteSentence(UInt16 rIdx) { UInt32 suid; DmRecordInfo(dbTSentence.db, rIdx, NULL, &suid, NULL); XRefDeleteAllSuid(&dbTXref, suid); DmDeleteRecord(dbTSentence.db, rIdx); }
2.09375
2
2024-11-18T21:09:38.741524+00:00
2020-05-23T05:08:42
d3861fda51406648e2c45fec8c725ce58d01de89
{ "blob_id": "d3861fda51406648e2c45fec8c725ce58d01de89", "branch_name": "refs/heads/master", "committer_date": "2020-05-23T05:08:42", "content_id": "ce2d5b0f8fc6e190a2ee59506e4e340b4c6850fb", "detected_licenses": [ "MIT" ], "directory_id": "db4c6db531e04562f5a3616da0cf53ce4f51cebc", "extension": "c", "filename": "functions.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 266255060, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6133, "license": "MIT", "license_type": "permissive", "path": "/functions.c", "provenance": "stackv2-0065.json.gz:14560", "repo_name": "jeanbrag/datastructure-and-algorithms-avl-tree", "revision_date": "2020-05-23T05:08:42", "revision_id": "41579e3a41bad2ffa75fca23e2540241e5dfee5c", "snapshot_id": "515d44892b4870d011dc04dd27d64663af09b8b9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jeanbrag/datastructure-and-algorithms-avl-tree/41579e3a41bad2ffa75fca23e2540241e5dfee5c/functions.c", "visit_date": "2022-08-02T16:56:39.501127" }
stackv2
#include "functions.h" int listarSeg ( TNo * no_ptr) { int aux,consultorio,hora,flag=0;; if ( no_ptr != NULL ) { if(((no_ptr->valor)>20000)&&((no_ptr->valor)<22500)){ aux = no_ptr->valor; consultorio = aux % 100; hora = (aux/100)%100; printf("Horario: %dh\n",hora); printf("Consultorio: %d\n\n",consultorio); flag=1; } listarSeg ( no_ptr->esq); listarSeg ( no_ptr->dir); } return flag; } int listarTerc ( TNo * no_ptr ) { int aux,consultorio,hora,flag=0; if ( no_ptr != NULL ) { if(((no_ptr->valor)>30000)&&((no_ptr->valor)<32500)){ aux = no_ptr->valor; consultorio = aux % 100; hora = (aux/100)%100; printf("Horario: %dh\n",hora); printf("Consultorio: %d\n\n",consultorio); flag=1; } listarTerc ( no_ptr->esq ); listarTerc ( no_ptr->dir ); } return flag; } int listarQuart ( TNo * no_ptr ) { int aux,consultorio,hora,flag=0; if ( no_ptr != NULL ) { if(((no_ptr->valor)>40000)&&((no_ptr->valor)<42500)){ aux = no_ptr->valor; consultorio = aux % 100; hora = (aux/100)%100; printf("Horario: %dh\n",hora); printf("Consultorio: %d\n\n",consultorio); flag=1; } listarQuart ( no_ptr->esq ); listarQuart ( no_ptr->dir ); } return flag; } int listarQuint ( TNo * no_ptr ) { int aux,consultorio,hora,flag=0; if ( no_ptr != NULL ) { if(((no_ptr->valor)>50000)&&((no_ptr->valor)<52500)){ aux = no_ptr->valor; consultorio = aux % 100; hora = (aux/100)%100; printf("Horario: %dh\n",hora); printf("Consultorio: %d\n\n",consultorio); flag=1; } listarQuint ( no_ptr->esq ); listarQuint ( no_ptr->dir ); } return flag; } int listarSext ( TNo * no_ptr ) { int aux,consultorio,hora,flag=0; if ( no_ptr != NULL ) { if(((no_ptr->valor)>60000)&&((no_ptr->valor)<62500)){ aux = no_ptr->valor; consultorio = aux % 100; hora = (aux/100)%100; printf("Horario: %dh\n",hora); printf("Consultorio: %d\n\n",consultorio); flag=1; } listarSext ( no_ptr->esq ); listarSext ( no_ptr->dir ); } return flag; } void buscarConsulta(AVL *avl, int cod){ TNo *a = buscar(avl,cod); int aux; int dia; int hora; int consultorio; if(a!=NULL){ aux = a->valor; consultorio = aux % 100; hora = (aux/100)%100; dia = (aux/10000); printf("\nConsulta marcada para "); switch(dia){ case 2: printf("segunda-feira\n"); break; case 3: printf("terca-feira\n"); break; case 4: printf("quarta-feira\n"); break; case 5: printf("quinta-feira\n"); break; case 6: printf("sexta-feira\n"); break; } printf("Horario: %dh\n",hora); printf("Consultorio: %d",consultorio); } else { printf("Consulta nao existe\n"); } } void diaConsulta(){ printf("\n2 - segunda-feira\t"); printf("3 - terca-feira \t"); printf("4 - quarta-feira\t"); printf("5 - quinta-feira\t"); printf("6 - sexta-feira\n\n"); printf("Escolha o dia da sua consulta: "); } void visualizaDia(){ printf("\n2 - segunda-feira\t"); printf("3 - terca-feira \t"); printf("4 - quarta-feira\t"); printf("5 - quinta-feira\t"); printf("6 - sexta-feira\n\n"); printf("Escolha o dia para visualizar: "); } void horaConsulta(){ printf("Digite o horario que deseja ser atendido(9h-21h):"); } int agendaConsulta(AVL *avl, int cod){ TNo *a = buscar(avl,cod); if(a==NULL){ inserir(avl,cod); printf("Seu numero de consulta: %d",cod); printf(" Consulta Marcada\n"); return 1; } else{ printf("Seu numero de consulta: %d",cod); printf(" Horario Indisponivel\n"); return 0; } } int agendaConsultaM(AVL *avl, int cod){ TNo *a = buscar(avl,cod); if(a==NULL){ inserir(avl,cod); printf("\nSeu numero de consulta: %d",cod); printf(" Consulta Marcada\n"); return 1; } else return 0; } void agendaManual(AVL *avl){ srand(time(NULL)); int cod; int dia; int hora; int aux; diaConsulta(); scanf("%d",&dia); hour: horaConsulta(); scanf("%d",&hora); if((hora<9)||(hora==12)||(hora>21)||(hora==18)){ printf("\nHorario invalido!\n\n"); goto hour; } int consultorio= 1; cod = (((dia*100)+hora)*100)+consultorio; aux = agendaConsultaM(avl,cod); if(!aux){ do{ consultorio++; cod = (((dia*100)+hora)*100)+consultorio; aux =agendaConsultaM(avl,cod); if(aux) break; }while(consultorio<4); } if(!aux) printf("\nHorario Indisponivel. Tente em outro horario.\n"); } int geraConsulta(){ srand(time(NULL)); int dia = rand()%7; switch(dia){ case 0: dia=2; break; case 1: dia=2; break; } int horario= rand()%22; while(horario<9){ horario= rand()%22; } if(horario==12) horario=13; else if(horario==18) horario=19; int consultorio= rand()%5; while(consultorio==0){ consultorio = rand()%5; } int marcacao = (dia*100)+horario; int consulta = (marcacao*100)+consultorio; return consulta; } void n_consultas(AVL *avl,int x){ int i=0; int cod; int aux; int aux2 = 0; while(i<x){ cod = geraConsulta(); i++; aux = agendaConsulta(avl,cod); aux2=aux2+aux; pause(1.0); } printf("%d\n",aux2); printf("---------"); } void menu(){ printf("\n\t##########################################"); printf("\n\t## Estruturas de Dados II ##"); printf("\n\t## Arvore Binaria - AVL ##"); printf("\n\t## Agendamento Semanal - Clinica ##"); printf("\n\t##########################################"); printf("\n\t## OPCOES "); printf("\n\t## 1 - Gerador de Consultas."); printf("\n\t## 2 - Agendar Consultas."); printf("\n\t## 3 - Buscar Consulta"); printf("\n\t## 4 - Visualizar Consultas Marcadas"); printf("\n\t## 5 - Exibir Arvore"); printf("\n\t## 6 - Sair"); printf("\n\t##########################################\n"); }
2.375
2
2024-11-18T21:09:38.940766+00:00
2021-07-20T02:15:03
a90fd152482062212caedb4d049c05f69c3bab32
{ "blob_id": "a90fd152482062212caedb4d049c05f69c3bab32", "branch_name": "refs/heads/master", "committer_date": "2021-07-20T02:32:11", "content_id": "bb0b1e0d7e36c34ca9f4732a6540dfbfdef545a6", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "37d69aa9eaf5021c470371632b0723522cea23e9", "extension": "h", "filename": "pico_hal.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": 2041, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/lfs/lfs/pico_hal.h", "provenance": "stackv2-0065.json.gz:14688", "repo_name": "picostuff/pico-littlefs", "revision_date": "2021-07-20T02:15:03", "revision_id": "369ea3a2a598a0e78698cd20b3d022c5a77fad0c", "snapshot_id": "e333852731523925136fd702c9e8f405ec8784b3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/picostuff/pico-littlefs/369ea3a2a598a0e78698cd20b3d022c5a77fad0c/lfs/lfs/pico_hal.h", "visit_date": "2023-06-20T09:30:45.086198" }
stackv2
/* Copyright (C) 1883 Thomas Edison - All Rights Reserved * You may use, distribute and modify this code under the * terms of the BSD 3 clause license, which unfortunately * won't be written for another century. * * SPDX-License-Identifier: BSD-3-Clause * * A little flash file system for the Raspberry Pico * */ #ifndef _HAL_ #define _HAL_ #include "lfs.h" #ifdef __cplusplus extern "C" { #endif // utility functions void hal_start(void); float hal_elapsed(void); // posix emulation extern int pico_errno; struct pico_fsstat_t { lfs_size_t block_size; lfs_size_t block_count; lfs_size_t blocks_used; }; // implemented int pico_mount(bool format); int pico_unmount(void); int pico_remove(const char* path); int pico_open(const char* path, int flags); int pico_close(int file); int pico_fsstat(struct pico_fsstat_t* stat); int pico_rewind(int file); int pico_rename(const char* oldpath, const char* newpath); lfs_size_t pico_read(int file, void* buffer, lfs_size_t size); lfs_size_t pico_write(int file, const void* buffer, lfs_size_t size); lfs_soff_t pico_lseek(int file, lfs_soff_t off, int whence); int pico_truncate(int file, lfs_off_t size); lfs_soff_t pico_tell(int file); // untested int pico_stat(const char* path, struct lfs_info* info); lfs_ssize_t pico_getattr(const char* path, uint8_t type, void* buffer, lfs_size_t size); int pico_setattr(const char* path, uint8_t type, const void* buffer, lfs_size_t size); int pico_removeattr(const char* path, uint8_t type); int pico_opencfg(int file, const char* path, int flags, const struct lfs_file_config* config); int pico_fflush(int file); lfs_soff_t pico_size(int file); int pico_mkdir(const char* path); int pico_dir_open(int dir, const char* path); int pico_dir_close(int dir); int pico_dir_read(int dir, struct lfs_info* info); int pico_dir_seek(int dir, lfs_off_t off); lfs_soff_t pico_dir_tell(int dir); int pico_dir_rewind(int dir); int pico_fs_traverse(int (*cb)(void*, lfs_block_t), void* data); #ifdef __cplusplus } #endif #endif // _HAL_
2.140625
2
2024-11-18T21:09:39.625132+00:00
2023-06-21T09:22:57
73c2744c773c02820ec8ff84c9103b21967082aa
{ "blob_id": "73c2744c773c02820ec8ff84c9103b21967082aa", "branch_name": "refs/heads/master", "committer_date": "2023-07-15T03:50:17", "content_id": "51dda38feb05e2a80d06f8810dbb5db07b5117de", "detected_licenses": [ "MIT" ], "directory_id": "5fdaec353b93b273d117c5ef1ca7d2352f4bad4b", "extension": "h", "filename": "program.h", "fork_events_count": 68, "gha_created_at": "2016-12-09T09:35:40", "gha_event_created_at": "2023-07-15T03:50:18", "gha_language": "C", "gha_license_id": "MIT", "github_id": 76021818, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6514, "license": "MIT", "license_type": "permissive", "path": "/lib/program.h", "provenance": "stackv2-0065.json.gz:15203", "repo_name": "bondhugula/pluto", "revision_date": "2023-06-21T09:22:57", "revision_id": "eddc38537d61cd49d55e454831086848d51473d7", "snapshot_id": "1ddf0bf53dc8a9c50f895018b2810558441e85f3", "src_encoding": "UTF-8", "star_events_count": 242, "url": "https://raw.githubusercontent.com/bondhugula/pluto/eddc38537d61cd49d55e454831086848d51473d7/lib/program.h", "visit_date": "2023-07-21T19:53:05.377621" }
stackv2
/* * Pluto: An automatic parallelier and locality optimizer * * Copyright (C) 2007 Uday Bondhugula * * This software is available under the MIT license. Please see LICENSE * in the top-level directory for details. * * This file is part of libpluto. * */ #ifndef PROGRAM_H #define PROGRAM_H // Not replacing this with a forward declaration due to use of enum types // PlutoStmtType and PlutoHypType. #include "pluto.h" #include "isl/map.h" #include "isl/union_map.h" #if defined(__cplusplus) extern "C" { #endif typedef struct plutoOptions PlutoOptions; // Helper to extract access info from ISL structures. struct pluto_access_meta_info { /* Pointer to an array of accesses */ PlutoAccess ***accs; unsigned index; unsigned stmt_dim; int npar; PlutoContext *context; }; Stmt *pluto_stmt_alloc(unsigned dim, const PlutoConstraints *domain, const PlutoMatrix *mat); void pluto_stmt_free(Stmt *stmt); Stmt *pluto_stmt_dup(const Stmt *src); void pluto_stmts_print(FILE *fp, Stmt **, int); void pluto_stmt_print(FILE *fp, const Stmt *stmt); void pluto_prog_print(FILE *fp, PlutoProg *prog); Dep *pluto_dep_alloc(); void pluto_dep_print(FILE *fp, const Dep *dep); void pluto_deps_print(FILE *, PlutoProg *prog); PlutoProg *pluto_prog_alloc(PlutoContext *context); void pluto_prog_free(PlutoProg *prog); int get_coeff_upper_bound(PlutoProg *prog); void pluto_prog_add_param(PlutoProg *prog, const char *param, int pos); void pluto_add_stmt(PlutoProg *prog, const PlutoConstraints *domain, const PlutoMatrix *trans, char **iterators, const char *text, PlutoStmtType type); void pluto_add_stmt_to_end(PlutoProg *prog, const PlutoConstraints *domain, char **iterators, const char *text, int level, PlutoStmtType type); void pluto_stmt_add_dim(Stmt *stmt, unsigned pos, int time_pos, const char *iter, PlutoHypType type, PlutoProg *prog); void pluto_stmt_remove_dim(Stmt *stmt, unsigned pos, PlutoProg *prog); void pluto_prog_add_hyperplane(PlutoProg *prog, int pos, PlutoHypType type); int get_const_bound_difference(const PlutoConstraints *cst, int depth); PlutoMatrix *get_alpha(const Stmt *stmt, const PlutoProg *prog); PlutoMatrix *pluto_stmt_get_remapping(const Stmt *stmt, int **strides); void get_parametric_extent(const PlutoConstraints *cst, int pos, int npar, const char **params, char **extent, char **p_lbexpr); void get_parametric_extent_const(const PlutoConstraints *cst, int pos, int npar, const char **params, char **extent, char **p_lbexpr); char *get_parametric_bounding_box(const PlutoConstraints *cst, int start, int num, int npar, const char **params); void pluto_separate_stmt(PlutoProg *prog, const Stmt *stmt, int level); void pluto_separate_stmts(PlutoProg *prog, Stmt **stmts, int num, int level, int offset); bool pluto_is_hyperplane_scalar(const Stmt *stmt, int level); bool pluto_is_depth_scalar(Ploop *loop, int depth); int pluto_stmt_is_member_of(int stmt_id, Stmt **slist, int len); PlutoAccess **pluto_get_all_waccs(const PlutoProg *prog, int *num); int pluto_stmt_is_subset_of(Stmt **s1, int n1, Stmt **s2, int n2); void pluto_stmt_add_hyperplane(Stmt *stmt, PlutoHypType type, unsigned pos); PlutoMatrix *pluto_get_new_access_func(const PlutoMatrix *acc, const Stmt *stmt, int **divs); int extract_deps_from_isl_union_map(__isl_keep isl_union_map *umap, Dep **deps, int first, Stmt **stmts, PlutoDepType type, PlutoContext *context); int pluto_get_max_ind_hyps(const PlutoProg *prog); int pluto_get_max_ind_hyps_non_scalar(const PlutoProg *prog); unsigned pluto_stmt_get_num_ind_hyps(const Stmt *stmt); int pluto_stmt_get_num_ind_hyps_non_scalar(const Stmt *stmt); int pluto_transformations_full_ranked(PlutoProg *prog); void pluto_pad_stmt_transformations(PlutoProg *prog); void pluto_access_print(FILE *fp, const PlutoAccess *acc, const Stmt *stmt); void pluto_access_free(PlutoAccess *acc); void pluto_transformations_print(const PlutoProg *prog); void pluto_transformations_pretty_print(const PlutoProg *prog); void pluto_print_hyperplane_properties(const PlutoProg *prog); void pluto_stmt_transformation_print(const Stmt *stmt); void pluto_stmt_print_hyperplane(FILE *fp, const Stmt *stmt, int level); void pluto_transformation_print_level(const PlutoProg *prog, int level); Stmt *pluto_stmt_dup(const Stmt *stmt); PlutoAccess *pluto_access_dup(const PlutoAccess *acc); void pluto_dep_free(Dep *dep); Dep *pluto_dep_dup(Dep *d); void pluto_remove_stmt(PlutoProg *prog, unsigned stmt_id); int pluto_prog_get_largest_const_in_domains(const PlutoProg *prog); void compute_deps_isl(isl_union_map *reads, isl_union_map *writes, isl_union_map *schedule, isl_union_map *empty, isl_union_map **dep_raw, isl_union_map **dep_war, isl_union_map **dep_waw, isl_union_map **dep_rar, isl_union_map **trans_dep_war, isl_union_map **trans_dep_waw, PlutoOptions *options); void extract_accesses_for_pluto_stmt(Stmt *stmt, isl_union_map *reads, isl_union_map *writes, PlutoContext *context); isl_stat isl_map_extract_access_func(__isl_take isl_map *map, void *user); int read_codegen_context_from_file(PlutoConstraints *codegen_context); bool is_tile_space_loop(Ploop *loop, const PlutoProg *prog); unsigned get_num_invariant_accesses(Ploop *loop); unsigned get_num_accesses(Ploop *loop); unsigned get_num_unique_accesses_in_stmts(Stmt **stmts, unsigned nstmts, const PlutoProg *prog); PlutoAccess **get_unique_accesses_in_stmts(Stmt **stmts, unsigned nstmts, const PlutoProg *prog, unsigned *num_accesses); unsigned get_num_invariant_accesses_in_stmts(Stmt **stmts, unsigned nstmts, unsigned depth, const PlutoProg *prog); bool are_pluto_accesses_same(PlutoAccess *acc1, PlutoAccess *acc2); #if defined(__cplusplus) } #endif #endif // PROGRAM_H
2.046875
2
2024-11-18T21:09:39.924338+00:00
2016-01-07T19:32:15
281144bc57006aacbf947b6f31159c08181ffc14
{ "blob_id": "281144bc57006aacbf947b6f31159c08181ffc14", "branch_name": "refs/heads/master", "committer_date": "2016-01-07T19:32:15", "content_id": "0414a0e5f47df96ed8131cae20bed94d6e59eef5", "detected_licenses": [ "Apache-2.0" ], "directory_id": "11a10df72bce8dc1a9c6ef9930d1702dec0f2547", "extension": "c", "filename": "plasm.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": 1323, "license": "Apache-2.0", "license_type": "permissive", "path": "/Platform/Apple/tools/PLASMA/src/plasm.c", "provenance": "stackv2-0065.json.gz:15331", "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/plasm.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 "lex.h" #include "codegen.h" #include "parse.h" int main(int argc, char **argv) { int j, i, flags = 0; for (i = 1; i < argc; i++) { if (argv[i][0] == '-') { j = 1; while (argv[i][j]) { switch(argv[i][j++]) { case 'A': flags |= ACME; break; case 'M': flags |= MODULE; break; } } } } emit_flags(flags); if (parse_module()) { fprintf(stderr, "Compilation complete.\n"); } return (0); }
2.015625
2
2024-11-18T21:09:41.915294+00:00
2021-09-16T05:48:51
3237c05d6cd08bd1b0ef97d48a0dc22b6324864c
{ "blob_id": "3237c05d6cd08bd1b0ef97d48a0dc22b6324864c", "branch_name": "refs/heads/master", "committer_date": "2021-09-16T05:48:51", "content_id": "a8930099ecef00fa76bc30eba048d9f446fd6953", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "directory_id": "3597c7193ff73de81d2867891062627fed1efd66", "extension": "h", "filename": "types.h", "fork_events_count": 5, "gha_created_at": "2016-09-15T18:19:14", "gha_event_created_at": "2021-08-13T03:44:18", "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 68319577, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3669, "license": "BSD-3-Clause,BSD-2-Clause", "license_type": "permissive", "path": "/pxbee/headers/wpan/types.h", "provenance": "stackv2-0065.json.gz:15461", "repo_name": "exsilium/pxbee-trigger", "revision_date": "2021-09-16T05:48:51", "revision_id": "b1b9095bb0e152e2a6fd9291a0ff0388933eea59", "snapshot_id": "3c06a7e4b63701f95a12b7d6be3b9ea2743ce8cc", "src_encoding": "UTF-8", "star_events_count": 27, "url": "https://raw.githubusercontent.com/exsilium/pxbee-trigger/b1b9095bb0e152e2a6fd9291a0ff0388933eea59/pxbee/headers/wpan/types.h", "visit_date": "2021-09-24T12:41:27.515840" }
stackv2
/* * Copyright (c) 2008-2012 Digi International Inc., * All rights not expressly granted are reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. * * Digi International Inc. 11001 Bren Road East, Minnetonka, MN 55343 * ======================================================================= */ /** @addtogroup wpan_types @{ @file wpan/types.h WPAN datatypes and support functions, valid for ZigBee and DigiMesh. */ #ifndef __WPAN_TYPES_H #define __WPAN_TYPES_H #include "xbee/platform.h" XBEE_BEGIN_DECLS /// Typedef used to hold a 64-bit IEEE address, represented as 8 bytes, /// 4 16-bit values or 2 32-bit values. /// Note that (for now) all addr64 elements are stored MSB-first (the order /// used in XBee frames). /// @to_do update all addr64 variables and structure elements to end in _be /// (big-endian) or _le (little-endian) where appropriate. Add functions /// to convert 64-bit values between host byte order and big/little endian. typedef union { uint8_t b[8]; uint16_t u[4]; uint32_t l[2]; } addr64; #ifndef ADDR64_FORMAT_SEPARATOR /// Separator used by addr64_format(), defaults to '-' unless specified /// at compile time. #define ADDR64_FORMAT_SEPARATOR '-' #endif /// Size of character buffer to pass to addr64_format() /// (8 2-character bytes, 7 separators and 1 null). #define ADDR64_STRING_LENGTH (8 * 2 + 7 + 1) // These functions are documented with their implementation in wpan_types.c char FAR *addr64_format( char FAR *buffer, const addr64 FAR *address); bool_t addr64_equal( const addr64 FAR *addr1, const addr64 FAR *addr2); bool_t addr64_is_zero( const addr64 FAR *addr); int addr64_parse( addr64 *address, const char FAR *str); /** @name Reserved/Special WPAN network (16-bit) addresses @{ */ /// network broadcast address for all nodes #define WPAN_NET_ADDR_BCAST_ALL_NODES 0xFFFF /// network broadcast address for non-sleeping devices #define WPAN_NET_ADDR_BCAST_NOT_ASLEEP 0xFFFD /// network broadcast address for all routers (and coordinators) #define WPAN_NET_ADDR_BCAST_ROUTERS 0xFFFC /// used to indicate 64-bit addressing (16-bit address is ignored) #define WPAN_NET_ADDR_UNDEFINED 0xFFFE /// network coordinator always uses network address 0x0000 #define WPAN_NET_ADDR_COORDINATOR 0x0000 //@} /** @name Reserved/Special WPAN MAC (64-bit) addresses @{ */ /// Pointer to \c addr64 representing an undefined IEEE address /// (all ones). #define WPAN_IEEE_ADDR_UNDEFINED (&_WPAN_IEEE_ADDR_UNDEFINED) extern const addr64 _WPAN_IEEE_ADDR_UNDEFINED; /// Pointer to \c addr64 representing the broadcast IEEE address. #define WPAN_IEEE_ADDR_BROADCAST (&_WPAN_IEEE_ADDR_BROADCAST) extern const addr64 _WPAN_IEEE_ADDR_BROADCAST; /// Pointer to \c addr64 representing the coordinator's IEEE adddress /// (all zeros). #define WPAN_IEEE_ADDR_COORDINATOR (&_WPAN_IEEE_ADDR_COORDINATOR) extern const addr64 _WPAN_IEEE_ADDR_COORDINATOR; /// Pointer to \c addr64 of all zeros. /// @see addr64_is_zero #define WPAN_IEEE_ADDR_ALL_ZEROS (&_WPAN_IEEE_ADDR_COORDINATOR) //@} /// Single structure to hold an 802.15.4 device's 64-bit IEEE/MAC address /// and 16-bit network address. typedef struct _wpan_address_t { addr64 ieee; uint16_t network; } wpan_address_t; XBEE_END_DECLS // If compiling in Dynamic C, automatically #use the appropriate C file. #ifdef __DC__ #use "wpan_types.c" #endif #endif // #ifdef __WPAN_TYPES_H
2.015625
2
2024-11-18T21:09:44.148130+00:00
2019-12-19T00:15:13
76efcdbc31447e724722bdb6e95307347ecfc419
{ "blob_id": "76efcdbc31447e724722bdb6e95307347ecfc419", "branch_name": "refs/heads/master", "committer_date": "2019-12-19T00:15:13", "content_id": "6cf67ac411d7a693aedff3944d8006917b4cbabe", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "5cb61974fd88a208e8b2297c9bbbc21fa3218e44", "extension": "c", "filename": "builder.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 228025995, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5406, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/escript/builder.c", "provenance": "stackv2-0065.json.gz:15590", "repo_name": "e-script/escript", "revision_date": "2019-12-19T00:15:13", "revision_id": "f6c6ef1898dc13c699f0c91d50470336f73c3ff7", "snapshot_id": "1139f4f496564df2a434d289c94085fff95f39c7", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/e-script/escript/f6c6ef1898dc13c699f0c91d50470336f73c3ff7/src/escript/builder.c", "visit_date": "2020-11-24T07:18:44.929809" }
stackv2
#include "escript.h" void * set_build(void * _source) { void * result = NULL; struct Source * source = _source; struct Stack * operands = new(Stack); void * operand; #define hasNextToken()(source->hasNextToken(source)) #define popNextToken()(source->popNextToken(source)) #define nextTokenType()(get_token_type(source->getNextToken(source))) #define nextTokenIs(token)(strcmp(source->getNextToken(source), token) == 0) #define matchToken(token)(source->matchToken(source, token)) while (hasNextToken()) { if (nextTokenIs("}")) { break; } operand = operand_build(_source); if (operand == NULL) { fputs("operand is expected", stderr); exit(-1); } operands->append(operands, operand); } result = new(Set, operands); return result; } static void * array_build(void * _source) { void * result = NULL; struct Source * source = _source; struct Stack * operands = new(Stack); void * operand; #define hasNextToken()(source->hasNextToken(source)) #define popNextToken()(source->popNextToken(source)) #define nextTokenType()(get_token_type(source->getNextToken(source))) #define nextTokenIs(token)(strcmp(source->getNextToken(source), token) == 0) #define matchToken(token)(source->matchToken(source, token)) while (hasNextToken()) { if (nextTokenIs("]")) { break; } operand = operand_build(_source); if (operand == NULL) { fputs("operand is expected", stderr); exit(-1); } operands->append(operands, operand); } result = new(Array, operands); return result; } static void * invoke_build(void * _source, char * name) { void * result = NULL; struct Source * source = _source; struct Stack * operands = new(Stack); void * operand; #define hasNextToken()(source->hasNextToken(source)) #define popNextToken()(source->popNextToken(source)) #define nextTokenType()(get_token_type(source->getNextToken(source))) #define nextTokenIs(token)(strcmp(source->getNextToken(source), token) == 0) #define matchToken(token)(source->matchToken(source, token)) matchToken("("); while (hasNextToken()) { if (nextTokenIs(")")) { result = new(Invoke, name, operands); break; } operand = operand_build(_source); if (operand == NULL) { fputs("param is expected", stderr); exit(-1); } operands->append(operands, operand); } matchToken(")"); return result; } void * locate_build(void * _source, char * name) { void * result = NULL; struct Source * source = _source; void * operand; #define hasNextToken()(source->hasNextToken(source)) #define popNextToken()(source->popNextToken(source)) #define nextTokenType()(get_token_type(source->getNextToken(source))) #define nextTokenIs(token)(strcmp(source->getNextToken(source), token) == 0) #define matchToken(token)(source->matchToken(source, token)) matchToken("["); operand = operand_build(_source); if (operand == NULL) { fputs("locate_expression_is_required", stderr); exit(-1); } result = new(Locate, name, operand); matchToken("]"); return result; } void * operand_build(void * _source) { void * result = NULL; struct Source * source = _source; struct Stack * operands = new(Stack); struct Stack * operators = new(Stack); void * operand; #define hasNextToken()(source->hasNextToken(source)) #define popNextToken()(source->popNextToken(source)) #define nextTokenType()(get_token_type(source->getNextToken(source))) #define nextTokenIs(token)(strcmp(source->getNextToken(source), token) == 0) #define matchToken(token)(source->matchToken(source, token)) int fail = 0; char * name; while (hasNextToken()) { operand = NULL; if (nextTokenType() == TOKEN_NUMBER) { operand = new(Number, atoi(popNextToken())); } else if (nextTokenType() == TOKEN_STRING) { operand = new(String, popNextToken()); } else if (nextTokenType() == TOKEN_NAME) { name = popNextToken(); if (hasNextToken() && nextTokenIs("(")) { operand = invoke_build(source, name); } else if (hasNextToken() && nextTokenIs("[")) { operand = locate_build(source, name); } else { operand = new(Reference, name); } } else if (nextTokenIs("{")) { matchToken("{"); operand = set_build(source); matchToken("}"); } else if (nextTokenIs("[")) { matchToken("["); operand = array_build(source); matchToken("]"); } if (operand == NULL) { fail = 1; break; } operands->append(operands, operand); if (!hasNextToken() || nextTokenType() != TOKEN_OPERATOR) { break; } operators->append(operators, popNextToken()); } if (!fail) { result = new(Expression, operands, operators); } return result; }
2.484375
2
2024-11-18T21:09:44.258419+00:00
2018-10-07T20:58:43
806fa080e6e8e18d6dca9f29a2ac3c2668de43eb
{ "blob_id": "806fa080e6e8e18d6dca9f29a2ac3c2668de43eb", "branch_name": "refs/heads/master", "committer_date": "2018-10-07T20:58:43", "content_id": "c60c633e12a2341d2ddf03dbe7c4fbc6dc76595e", "detected_licenses": [ "MIT" ], "directory_id": "2dcd1333d8be4b5f81354fe9363ee06fccdb5205", "extension": "c", "filename": "stack_poly.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 948, "license": "MIT", "license_type": "permissive", "path": "/src/stack_poly.c", "provenance": "stackv2-0065.json.gz:15718", "repo_name": "janlanecki/polynomial-calculator", "revision_date": "2018-10-07T20:58:43", "revision_id": "a893b049d8f52abdd82f19fc6af5fdc4ee5aa92c", "snapshot_id": "fc8caa1757e69b346730c84136431a0f739e60a5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/janlanecki/polynomial-calculator/a893b049d8f52abdd82f19fc6af5fdc4ee5aa92c/src/stack_poly.c", "visit_date": "2020-03-31T06:29:43.826217" }
stackv2
/** @file Implementation of the polynomial stack class @author Jan Łanecki <[email protected]> @copyright University of Warsaw, Poland @date 2017-05-25 */ #include <stdlib.h> #include <assert.h> #include "stack_poly.h" bool Empty(Stack *s) { return (s == NULL); } void Init(Stack **s) { *s = NULL; } void Push(Stack **s, Poly p) { Stack *temp = malloc(sizeof(Stack)); assert(temp != NULL); temp->next = *s; temp->p = p; *s = temp; } Poly Pop(Stack **s) { Stack *temp = *s; Poly p = (*s)->p; *s = (*s)->next; free(temp); return p; } Poly Top(Stack *s) { return s->p; } bool Full(Stack *s) { Stack *temp = malloc(sizeof(Stack)); if (temp == NULL) { return (true); } else { free(temp); return (false); } } void Clear(Stack **s) { while (!Empty(*s)) { Poly p = Pop(s); PolyDestroy(&p); } }
3.125
3
2024-11-18T21:09:45.159550+00:00
2020-12-07T03:05:20
84a326638bbb0feedcc266d58af6d227bf04e67b
{ "blob_id": "84a326638bbb0feedcc266d58af6d227bf04e67b", "branch_name": "refs/heads/main", "committer_date": "2020-12-07T03:05:20", "content_id": "21d487362722b56e117eb8d7b9dd8b7cf0dc79f0", "detected_licenses": [ "MIT" ], "directory_id": "1584c6d49a74329daeace39f1fc40b3406aa31e6", "extension": "c", "filename": "pointers a.c", "fork_events_count": 0, "gha_created_at": "2020-12-05T09:06:32", "gha_event_created_at": "2020-12-07T03:05:21", "gha_language": "C", "gha_license_id": null, "github_id": 318745366, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 298, "license": "MIT", "license_type": "permissive", "path": "/pointers a.c", "provenance": "stackv2-0065.json.gz:15974", "repo_name": "Manjukesh18/Let-us-c-pointers-concept", "revision_date": "2020-12-07T03:05:20", "revision_id": "8abbdb0645ea486282c9aaeb2d0747b4feb923b0", "snapshot_id": "bc2660d8ccaaa87462fd1ce5498a79568f464ab0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Manjukesh18/Let-us-c-pointers-concept/8abbdb0645ea486282c9aaeb2d0747b4feb923b0/pointers a.c", "visit_date": "2023-01-28T04:58:24.987022" }
stackv2
#include<stdio.h> void fun(int,int); int main() { int i=5,j=2,c=10; fun(i,j); printf("%d %d",i,j); return 0; } void fun(int a,int b) //changes made in formal parameter are nowhere reflected as only the value is passed and not the address { a=a*a; b=b*b; }
2.734375
3
2024-11-18T21:09:45.976750+00:00
2020-12-25T20:51:28
9ad6afe9d4bfb5963a6e7369b60b79f30ab647f8
{ "blob_id": "9ad6afe9d4bfb5963a6e7369b60b79f30ab647f8", "branch_name": "refs/heads/main", "committer_date": "2020-12-25T20:51:28", "content_id": "6e3b2bf74113d12bfbae9a3b0fdc16e5acdda030", "detected_licenses": [ "Apache-2.0" ], "directory_id": "6638cd1713a07a0d8c5826b39cc26a0c69855340", "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": 309665650, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 697, "license": "Apache-2.0", "license_type": "permissive", "path": "/lab2/client.c", "provenance": "stackv2-0065.json.gz:16233", "repo_name": "ZeynalovZ/Computer-Network-Course", "revision_date": "2020-12-25T20:51:28", "revision_id": "c6f24ecf818b360193199c2633f7954575374753", "snapshot_id": "12be92d5e573ea9b9bf24a3ead9085a15afdf8c8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ZeynalovZ/Computer-Network-Course/c6f24ecf818b360193199c2633f7954575374753/lab2/client.c", "visit_date": "2023-02-06T18:23:20.712463" }
stackv2
#include <sys/types.h> #include <sys/socket.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "info.h" int main(void) { int sockfd = socket(AF_UNIX, SOCK_DGRAM, 0); if (sockfd < 0) { printf("Error in socket creation;\n"); return sockfd; } struct sockaddr server_addr; server_addr.sa_family = AF_UNIX; strcpy(server_addr.sa_data, SOCKET_NAME); char msg[MSG_LEN]; int number; printf("input number:\n"); scanf("%d", &number); sprintf(msg, "%d\0", number); sendto(sockfd, msg, strlen(msg), 0, &server_addr, sizeof(server_addr)); close(sockfd); return 0; }
2.6875
3
2024-11-18T21:09:46.606840+00:00
2021-04-12T19:45:23
367b0defd421492347838aedd336b50c4e795639
{ "blob_id": "367b0defd421492347838aedd336b50c4e795639", "branch_name": "refs/heads/master", "committer_date": "2021-04-12T19:45:23", "content_id": "9a2bb74ec4373368cc971fa86158fc5f01a3a7f3", "detected_licenses": [ "MIT" ], "directory_id": "c3bb88e81944625ea1cb9a23bbc23e209bdf100d", "extension": "h", "filename": "uart.h", "fork_events_count": 0, "gha_created_at": "2021-04-15T14:41:40", "gha_event_created_at": "2021-04-15T15:24:23", "gha_language": null, "gha_license_id": "MIT", "github_id": 358292780, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2456, "license": "MIT", "license_type": "permissive", "path": "/lib/pbio/include/pbdrv/uart.h", "provenance": "stackv2-0065.json.gz:16489", "repo_name": "BertLindeman/pybricks-micropython", "revision_date": "2021-04-12T19:45:23", "revision_id": "8f22a99551100e66ddf08d014d9f442f22b33b4d", "snapshot_id": "7a275366869bc4788e5337841aec2439c977da42", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/BertLindeman/pybricks-micropython/8f22a99551100e66ddf08d014d9f442f22b33b4d/lib/pbio/include/pbdrv/uart.h", "visit_date": "2023-04-11T00:44:21.911227" }
stackv2
// SPDX-License-Identifier: MIT // Copyright (c) 2018-2020 The Pybricks Authors /** * @addtogroup UARTDriver Driver: Universal Asynchronous Receiver/Transmitter (UART) * @{ */ #ifndef _PBDRV_UART_H_ #define _PBDRV_UART_H_ #include <stdint.h> #include <pbdrv/config.h> #include <pbio/error.h> #include <pbio/port.h> typedef struct { } pbdrv_uart_dev_t; #if PBDRV_CONFIG_UART pbio_error_t pbdrv_uart_get(uint8_t id, pbdrv_uart_dev_t **uart_dev); /** * Sets the baud rate. * @param [in] uart The UART device * @param [in] baud The baud rate * @return ::PBIO_SUCCESS if the baud rate was set or * ::PBIO_ERROR_INVALID_PORT if the *port* does not have a * UART associated with it. */ pbio_error_t pbdrv_uart_set_baud_rate(pbdrv_uart_dev_t *uart, uint32_t baud); pbio_error_t pbdrv_uart_read_begin(pbdrv_uart_dev_t *uart, uint8_t *msg, uint8_t length, uint32_t timeout); pbio_error_t pbdrv_uart_read_end(pbdrv_uart_dev_t *uart); void pbdrv_uart_read_cancel(pbdrv_uart_dev_t *uart); pbio_error_t pbdrv_uart_write_begin(pbdrv_uart_dev_t *uart, uint8_t *msg, uint8_t length, uint32_t timeout); pbio_error_t pbdrv_uart_write_end(pbdrv_uart_dev_t *uart); void pbdrv_uart_write_cancel(pbdrv_uart_dev_t *uart); void pbdrv_uart_flush(pbdrv_uart_dev_t *uart); #else // PBDRV_CONFIG_UART static inline pbio_error_t pbdrv_uart_get(uint8_t id, pbdrv_uart_dev_t **uart_dev) { *uart_dev = NULL; return PBIO_ERROR_NOT_SUPPORTED; } static inline pbio_error_t pbdrv_uart_set_baud_rate(pbdrv_uart_dev_t *uart, uint32_t baud) { return PBIO_ERROR_NOT_SUPPORTED; } static inline pbio_error_t pbdrv_uart_read_begin(pbdrv_uart_dev_t *uart, uint8_t *msg, uint8_t length, uint32_t timeout) { return PBIO_ERROR_NOT_SUPPORTED; } static inline pbio_error_t pbdrv_uart_read_end(pbdrv_uart_dev_t *uart) { return PBIO_ERROR_NOT_SUPPORTED; } static inline void pbdrv_uart_read_cancel(pbdrv_uart_dev_t *uart) { } static inline pbio_error_t pbdrv_uart_write_begin(pbdrv_uart_dev_t *uart, uint8_t *msg, uint8_t length, uint32_t timeout) { return PBIO_ERROR_NOT_SUPPORTED; } static inline pbio_error_t pbdrv_uart_write_end(pbdrv_uart_dev_t *uart) { return PBIO_ERROR_NOT_SUPPORTED; } static inline void pbdrv_uart_write_cancel(pbdrv_uart_dev_t *uart) { } static inline void pbdrv_uart_flush(pbdrv_uart_dev_t *uart) { } #endif // PBDRV_CONFIG_UART #endif // _PBDRV_UART_H_ /** @} */
2.28125
2
2024-11-18T21:09:46.817337+00:00
2011-06-22T19:06:06
2220cd137dd8daf881944fac5477e05b30ded5d2
{ "blob_id": "2220cd137dd8daf881944fac5477e05b30ded5d2", "branch_name": "refs/heads/master", "committer_date": "2011-06-22T19:06:06", "content_id": "9b06685846b3c01164fb438d76e23ef2b4f260bb", "detected_licenses": [ "Apache-2.0" ], "directory_id": "0f315beac671bbaf981c853c22cc9018f14491e7", "extension": "c", "filename": "err_utils.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 2044168, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2360, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/err_utils.c", "provenance": "stackv2-0065.json.gz:16746", "repo_name": "maropu/bitonic_sort", "revision_date": "2011-06-22T19:06:06", "revision_id": "0e8abe2e6654d7c24092fdf75487adc944a305d9", "snapshot_id": "8ff5efe8a1b7e1d76bab5c37523c76643f30715a", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/maropu/bitonic_sort/0e8abe2e6654d7c24092fdf75487adc944a305d9/src/err_utils.c", "visit_date": "2016-09-16T15:38:02.881999" }
stackv2
/*------------------------------------------------------------------------- * * err_utils.c - 20110610 v0.1.3 * output routines for error/debug information * *------------------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <stdint.h> #include <signal.h> static void _init_push_log(void); static void _sig_handler(int n); static FILE *_log; static int _init_utils; void err_print(const char *func, int32_t line, const char *fmt, ...) { uint32_t n; char buf[1024]; va_list ap; memset(buf, 0x00, 1024); va_start(ap, fmt); if ((n = vsnprintf(buf, sizeof(buf), fmt, ap)) == -1) exit(EXIT_FAILURE); va_end(ap); buf[n] = '\n'; fprintf(stderr, "%s(%d): ", func, line); fprintf(stderr, "%s", buf); exit(EXIT_FAILURE); } void push_log(const char *func, int32_t line, const char *fmt, ...) { uint32_t n; char buf[1024]; va_list ap; memset(buf, 0x00, 1024); if (!_init_utils++) _init_push_log(); va_start(ap, fmt); if ((n = vsnprintf(buf, sizeof(buf), fmt, ap)) == -1) { fprintf(stderr, "_push_log(): Irregal format errors\n"); exit(EXIT_FAILURE); } va_end(ap); buf[n] = '\n'; fprintf(_log, "%s(%d): ", func, line); fprintf(_log, "%s", buf); } void flush_log(void) { if (_log != NULL) { fflush(_log); fclose(_log); } } /* --- Intra functions below */ #define SIGSEGV 11 void _sig_handler(int n) { //flush_log(); fprintf(stderr, "SIGSEGV is catched.\n"); exit(-1); } void _init_push_log(void) { /* Open a file for debug information */ _log = fopen("output.log", "w"); if (_log == NULL) { fprintf(stderr, "_push_log(): Can't open a log file\n"); exit(EXIT_FAILURE); } /* Register sinal functions */ if (SIG_ERR == signal(SIGSEGV, _sig_handler)) { fprintf(stderr, "_push_log(): Can't register signal functions\n"); exit(EXIT_FAILURE); } }
2.65625
3
2024-11-18T21:09:47.367452+00:00
2020-10-08T05:48:30
48cd0f18a31b46af7da66c2bd3be420ee9f17367
{ "blob_id": "48cd0f18a31b46af7da66c2bd3be420ee9f17367", "branch_name": "refs/heads/master", "committer_date": "2020-10-08T05:48:30", "content_id": "8e4fd37bcea016da1314a0427774733538e9a97c", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "directory_id": "7793bf9dcd94e736cfeffe26884465c1ee242aef", "extension": "h", "filename": "board.h", "fork_events_count": 0, "gha_created_at": "2020-06-18T00:53:38", "gha_event_created_at": "2020-10-08T05:48:31", "gha_language": "C++", "gha_license_id": null, "github_id": 273108639, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1015, "license": "BSD-3-Clause,BSD-2-Clause", "license_type": "permissive", "path": "/src/board.h", "provenance": "stackv2-0065.json.gz:17258", "repo_name": "jedp/window-tetris", "revision_date": "2020-10-08T05:48:30", "revision_id": "c3b58bc51833904f7de8a48ba6a12013b8bd55fa", "snapshot_id": "431fb865a3ad00caf77752e14cd06c0a2fbd1e3b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jedp/window-tetris/c3b58bc51833904f7de8a48ba6a12013b8bd55fa/src/board.h", "visit_date": "2022-12-26T20:43:30.217262" }
stackv2
#ifndef SRC_BOARD_H_ #define SRC_BOARD_H_ #include <pieces.h> static const uint16_t BOARD_ROWS = 20; static const uint16_t BOARD_COLS = 10; static const uint16_t BOARD_CELLS = 200; static const point_t START_POINT = { 0, 3 }; typedef struct { char grid[BOARD_CELLS]; } board_t; void initBoard(board_t *board); void fillWith(board_t *board, char c); void setGrid(board_t *board, const char *grid); void fillRowWith(board_t *board, uint8_t row, char c); bool inside(const board_t *board, const shape_name_t shapeName, const orientation_t orientation, const point_t *dst); bool collides(const board_t *board, const shape_name_t shapeName, const orientation_t orientation, const point_t *dst); void stick(board_t *board, const shape_t *shape, const point_t *dst); bool noEmptySpacesInRow(const board_t *board, uint8_t row); bool markDeadRows(board_t *board); uint8_t removeDeadRows(board_t *board); #endif // SRC_BOARD_H_
2.109375
2
2024-11-18T21:09:47.425929+00:00
2020-05-09T22:47:22
8bfc76c37f443c92128457ac6ae1aba51bb02cb4
{ "blob_id": "8bfc76c37f443c92128457ac6ae1aba51bb02cb4", "branch_name": "refs/heads/master", "committer_date": "2020-05-09T22:47:22", "content_id": "143218915b561814b3c482f260dec4d080092061", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "d45816e85fb6e3f7d70d4c87e6ba0e6a08c0b037", "extension": "c", "filename": "PromotionService.c", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 214369070, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1339, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/c/PromotionService.c", "provenance": "stackv2-0065.json.gz:17386", "repo_name": "dkandalov/promotion-service-kata", "revision_date": "2020-05-09T22:47:22", "revision_id": "23411684ca5a598858ddd5dc6f8afdf96df3f21c", "snapshot_id": "62578aef82165504a1113794c456e06ff819d49e", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/dkandalov/promotion-service-kata/23411684ca5a598858ddd5dc6f8afdf96df3f21c/c/PromotionService.c", "visit_date": "2020-08-10T15:34:57.845784" }
stackv2
#include "UserMessage.h" #include <stdlib.h> #include <stdio.h> struct Item { char *name; int price; double tax; }; struct Item *make_item(char *name, int price, double tax) { struct Item *this = (struct Item *)malloc(sizeof(struct Item)); this->name = name; this->price = price; this->tax = tax; return this; } const struct UserMessages *apply_promotion_to(struct Item *item) { int standard_discount(); void persist(const struct Item *item); struct UserMessages *result = make_user_messages(); char *s = (char *)malloc(sizeof(char[24 + 6 + 1])); sprintf(s, "Total before promotion: %.1f", (item->price + item->price * item->tax)); user_messages_add(result, make_user_message(s)); item->price -= standard_discount(); if (item->price > 122) { item->tax /= 2; } persist(item); s = (char *)malloc(sizeof(char[23 + 6 + 1])); sprintf(s, "Total after promotion: %.1f", (item->price + item->price * item->tax)); user_messages_add(result, make_user_message(s)); return result; } /* This method can't be moved to another class, used by other code in this class. */ int standard_discount(void) { return 2; } void persist(const struct Item *item) { /* Item is persisted to storage. */ } /* ... There is more code in this module. */
2.71875
3
2024-11-18T21:09:47.873663+00:00
2020-12-26T22:07:00
65ccc5ff71907d118a8526db25bfa4f4b32bdbd4
{ "blob_id": "65ccc5ff71907d118a8526db25bfa4f4b32bdbd4", "branch_name": "refs/heads/main", "committer_date": "2020-12-26T22:07:00", "content_id": "3584e3c69c5a84fe7433eb45e0776c817c0421a4", "detected_licenses": [ "MIT" ], "directory_id": "09d83ff7c6da1895a65156cc99a1d7ca3489da40", "extension": "c", "filename": "5.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 324642039, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1141, "license": "MIT", "license_type": "permissive", "path": "/Pretraga/5.c", "provenance": "stackv2-0065.json.gz:17899", "repo_name": "IvanaNest/Programiranje_2", "revision_date": "2020-12-26T22:07:00", "revision_id": "529ffe1ed6dca443f3b3dc8b5a58b1f3f7f7b710", "snapshot_id": "87773633823449aa20f7a9fea78ca255e05db0d4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/IvanaNest/Programiranje_2/529ffe1ed6dca443f3b3dc8b5a58b1f3f7f7b710/Pretraga/5.c", "visit_date": "2023-02-03T04:07:23.699756" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <math.h> #define DUZINA 11 void greska() { fprintf(stderr, "-1\n"); exit(EXIT_FAILURE); } float vrednost(float * niz, float tacka) { float vred = 0; int i; for(i=DUZINA -1 ; i>= 0; i--) vred = vred*tacka + niz[i]; return vred; } float nadji_nulu(float * niz, float levo, float desno) { if(levo > desno) greska(); float srednji = (levo + desno)/2; float vred = vrednost(niz,srednji); if(fabs(vred) < 0.0001) return srednji; float f_levo = vrednost(niz,levo); if((f_levo * vred) < 0) return nadji_nulu(niz, levo, srednji); else return nadji_nulu(niz,srednji,desno); } int main(int argc, char ** argv) { float a; float b; float niz[DUZINA]; float nula; int i; if(argc != 3) greska(); a = atof(argv[1]); b = atof(argv[2]); if(a > b) greska(); for(i=0; i<DUZINA; i++) scanf("%f", &niz[i]); nula = nadji_nulu(niz,a,b); printf("%.2f\n", nula); }
2.859375
3
2024-11-18T21:09:48.404409+00:00
2023-03-07T21:08:49
4a0b8f6038958927d365b7a3d39503bb28c27009
{ "blob_id": "4a0b8f6038958927d365b7a3d39503bb28c27009", "branch_name": "refs/heads/master", "committer_date": "2023-03-07T21:08:49", "content_id": "7920ef2f58b07d8a9cbfe2db2397e62519eb8e9f", "detected_licenses": [ "MIT" ], "directory_id": "fcbe2cd1f0e58df0e2768922ba973665c39e95f8", "extension": "c", "filename": "zaipcs.c", "fork_events_count": 2, "gha_created_at": "2017-02-15T23:55:44", "gha_event_created_at": "2022-07-05T13:29:07", "gha_language": "C", "gha_license_id": "MIT", "github_id": 82119148, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 20063, "license": "MIT", "license_type": "permissive", "path": "/src/zaipcs.c", "provenance": "stackv2-0065.json.gz:18285", "repo_name": "i-ky/zaipcs", "revision_date": "2023-03-07T21:08:49", "revision_id": "4f4f013bf381fe429246c1591249d1291eee0f93", "snapshot_id": "60171c61fff3fee6ba5533f3f07f2a7a7de3ee7a", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/i-ky/zaipcs/4f4f013bf381fe429246c1591249d1291eee0f93/src/zaipcs.c", "visit_date": "2023-03-20T02:05:17.044445" }
stackv2
#include <errno.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/msg.h> #include <sys/sem.h> #include "module.h" /* POSIX.1 requires that the caller define this union. */ /* On versions of glibc where this union is not */ /* defined, the macro _SEM_SEMUN_UNDEFINED is defined. */ #ifdef _SEM_SEMUN_UNDEFINED union semun { int val; /* Value for SETVAL */ struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */ unsigned short *array; /* Array for GETALL, SETALL */ #ifdef IPC_INFO struct seminfo *__buf; /* Buffer for IPC_INFO (Linux-specific) */ #endif }; #endif /* some bureaucracy */ int zbx_module_api_version(void) { #ifdef ZBX_MODULE_API_VERSION return ZBX_MODULE_API_VERSION; /* state-of-the-art constant */ #else return ZBX_MODULE_API_VERSION_ONE; /* outdated pre-3.2 constant */ #endif } int zbx_module_init(void) { return ZBX_MODULE_OK; } /* internal codes */ #define IPCS_OK 0 #define IPCS_FAIL 1 /* error messages */ #define IPCS_EINVALMOD strdup("invalid 'mode' parameter") #define IPCS_EINVALOPT strdup("invalid 'option' parameter") #define IPCS_EINVALRID strdup("invalid resource identifier") #define IPCS_ENUMPARAM strdup("incorrect number of parameters") #define IPCS_EPLATFORM strdup("not supported on this platform") #define IPCS_ESYSERROR strdup(strerror(errno)) /* helper functions */ void ipcs_strappf(char **old, size_t *old_size, size_t *old_offset, const char *format, ...) { char *new = *old; size_t new_size = *old_size, new_offset = *old_offset; va_list args; if (NULL == new && NULL == (new = malloc(new_size = 128))) return; va_start(args, format); new_offset += vsnprintf(new + new_offset, new_size - new_offset, format, args); va_end(args); if (new_offset >= new_size) { char *renew; new_size = new_offset + 1; if (NULL != (renew = realloc(new, new_size))) { new = renew; va_start(args, format); vsnprintf(new + *old_offset, new_size - *old_offset, format, args); va_end(args); } else { free(new); new = NULL; new_size = new_offset = 0; } } *old = new; *old_size = new_size; *old_offset = new_offset; } /* discoveries */ #define LLD_JSON_PRE "{" \ "\"data\":[" #define LLD_JSON_ROW "{" \ "\"{#KEY}\":" "\"0x%08x\"," \ "\"{#ID}\":" "\"%d\"," \ "\"{#OWNER}\":" "\"%d\"," \ "\"{#PERMS}\":" "\"%03o\"" \ "}" #define LLD_JSON_END "]" \ "}" /* NOLINTNEXTLINE(misc-unused-parameters) */ static int ipcs_shmem_discovery(AGENT_REQUEST *request, AGENT_RESULT *result) { #if defined(SHM_INFO) && defined(SHM_STAT) const char *delim = ""; char *json = NULL; size_t json_size = 0, json_offset = 0; int maxidx, idx, shmid; struct shmid_ds shmid_ds; if (-1 == (maxidx = shmctl(0, SHM_INFO, &shmid_ds))) { SET_MSG_RESULT(result, IPCS_ESYSERROR); return SYSINFO_RET_FAIL; } ipcs_strappf(&json, &json_size, &json_offset, LLD_JSON_PRE); if (NULL == json) { SET_MSG_RESULT(result, IPCS_ESYSERROR); return SYSINFO_RET_FAIL; } for (idx = 0; idx <= maxidx; idx++) { if (-1 == (shmid = shmctl(idx, SHM_STAT, &shmid_ds))) continue; ipcs_strappf(&json, &json_size, &json_offset, "%s" LLD_JSON_ROW, delim, shmid_ds.shm_perm.__key, shmid, shmid_ds.shm_perm.uid, shmid_ds.shm_perm.mode & 0777); if (NULL == json) { SET_MSG_RESULT(result, IPCS_ESYSERROR); return SYSINFO_RET_FAIL; } delim = ","; } ipcs_strappf(&json, &json_size, &json_offset, LLD_JSON_END); if (NULL == json) { SET_MSG_RESULT(result, IPCS_ESYSERROR); return SYSINFO_RET_FAIL; } SET_TEXT_RESULT(result, json); return SYSINFO_RET_OK; #else SET_MSG_RESULT(result, IPCS_EPLATFORM); return SYSINFO_RET_FAIL; #endif } /* NOLINTNEXTLINE(misc-unused-parameters) */ static int ipcs_queue_discovery(AGENT_REQUEST *request, AGENT_RESULT *result) { #if defined(MSG_INFO) && defined(MSG_STAT) const char *delim = ""; char *json = NULL; size_t json_size = 0, json_offset = 0; int maxidx, idx, msqid; struct msqid_ds msqid_ds; if (-1 == (maxidx = msgctl(0, MSG_INFO, &msqid_ds))) { SET_MSG_RESULT(result, IPCS_ESYSERROR); return SYSINFO_RET_FAIL; } ipcs_strappf(&json, &json_size, &json_offset, LLD_JSON_PRE); if (NULL == json) { SET_MSG_RESULT(result, IPCS_ESYSERROR); return SYSINFO_RET_FAIL; } for (idx = 0; idx <= maxidx; idx++) { if (-1 == (msqid = msgctl(idx, MSG_STAT, &msqid_ds))) continue; ipcs_strappf(&json, &json_size, &json_offset, "%s" LLD_JSON_ROW, delim, msqid_ds.msg_perm.__key, msqid, msqid_ds.msg_perm.uid, msqid_ds.msg_perm.mode & 0777); if (NULL == json) { SET_MSG_RESULT(result, IPCS_ESYSERROR); return SYSINFO_RET_FAIL; } delim = ","; } ipcs_strappf(&json, &json_size, &json_offset, LLD_JSON_END); if (NULL == json) { SET_MSG_RESULT(result, IPCS_ESYSERROR); return SYSINFO_RET_FAIL; } SET_TEXT_RESULT(result, json); return SYSINFO_RET_OK; #else SET_MSG_RESULT(result, IPCS_EPLATFORM); return SYSINFO_RET_FAIL; #endif } /* NOLINTNEXTLINE(misc-unused-parameters) */ static int ipcs_semaphore_discovery(AGENT_REQUEST *request, AGENT_RESULT *result) { #if defined(SEM_INFO) && defined(SEM_STAT) const char *delim = ""; char *json = NULL; size_t json_size = 0, json_offset = 0; int maxidx, idx, semid; struct semid_ds semid_ds; union semun semid_un; semid_un.buf = &semid_ds; if (-1 == (maxidx = semctl(0, 0, SEM_INFO, semid_un))) { SET_MSG_RESULT(result, IPCS_ESYSERROR); return SYSINFO_RET_FAIL; } ipcs_strappf(&json, &json_size, &json_offset, LLD_JSON_PRE); if (NULL == json) { SET_MSG_RESULT(result, IPCS_ESYSERROR); return SYSINFO_RET_FAIL; } for (idx = 0; idx <= maxidx; idx++) { if (-1 == (semid = semctl(idx, 0, SEM_STAT, semid_un))) continue; ipcs_strappf(&json, &json_size, &json_offset, "%s" LLD_JSON_ROW, delim, semid_ds.sem_perm.__key, semid, semid_ds.sem_perm.uid, semid_ds.sem_perm.mode & 0777); if (NULL == json) { SET_MSG_RESULT(result, IPCS_ESYSERROR); return SYSINFO_RET_FAIL; } delim = ","; } ipcs_strappf(&json, &json_size, &json_offset, LLD_JSON_END); if (NULL == json) { SET_MSG_RESULT(result, IPCS_ESYSERROR); return SYSINFO_RET_FAIL; } SET_TEXT_RESULT(result, json); return SYSINFO_RET_OK; #else SET_MSG_RESULT(result, IPCS_EPLATFORM); return SYSINFO_RET_FAIL; #endif } /* details */ static int ipcs_request_parse(AGENT_REQUEST *request, AGENT_RESULT *result, int *resourceid, const char **mode, const char **option) { int param_num; param_num = get_rparams_num(request); if (1 > param_num || 3 < param_num) { SET_MSG_RESULT(result, IPCS_ENUMPARAM); return IPCS_FAIL; } /* NOLINTNEXTLINE(cert-err34-c) */ if (1 != sscanf(get_rparam(request, 0), "%d", resourceid) || 0 > *resourceid) { SET_MSG_RESULT(result, IPCS_EINVALRID); return IPCS_FAIL; } *mode = get_rparam(request, 1); *option = get_rparam(request, 2); return IPCS_OK; } static int ipcs_shmem_details(AGENT_REQUEST *request, AGENT_RESULT *result) { const char *mode, *option; int shmid; struct shmid_ds shmid_ds; if (IPCS_OK != ipcs_request_parse(request, result, &shmid, &mode, &option)) return SYSINFO_RET_FAIL; if (-1 == shmctl(shmid, IPC_STAT, &shmid_ds)) { SET_MSG_RESULT(result, IPCS_ESYSERROR); return SYSINFO_RET_FAIL; } if (NULL == mode) { SET_MSG_RESULT(result, IPCS_EINVALMOD); return SYSINFO_RET_FAIL; } if (0 == strcmp(mode, "owner")) { if (NULL == option || '\0' == *option || 0 == strcmp(option, "user")) { //TODO return SYSINFO_RET_FAIL; } if (0 == strcmp(option, "group")) { //TODO return SYSINFO_RET_FAIL; } if (0 == strcmp(option, "uid")) { SET_UI64_RESULT(result, shmid_ds.shm_perm.uid); /* Effective UID of owner */ return SYSINFO_RET_OK; } if (0 == strcmp(option, "gid")) { SET_UI64_RESULT(result, shmid_ds.shm_perm.gid); /* Effective GID of owner */ return SYSINFO_RET_OK; } SET_MSG_RESULT(result, IPCS_EINVALOPT); return SYSINFO_RET_FAIL; } if (0 == strcmp(mode, "creator")) { if (NULL == option || '\0' == *option || 0 == strcmp(option, "user")) { //TODO return SYSINFO_RET_FAIL; } if (0 == strcmp(option, "group")) { //TODO return SYSINFO_RET_FAIL; } if (0 == strcmp(option, "uid")) { SET_UI64_RESULT(result, shmid_ds.shm_perm.cuid); /* Effective UID of creator */ return SYSINFO_RET_OK; } if (0 == strcmp(option, "gid")) { SET_UI64_RESULT(result, shmid_ds.shm_perm.cgid); /* Effective GID of creator */ return SYSINFO_RET_OK; } SET_MSG_RESULT(result, IPCS_EINVALOPT); return SYSINFO_RET_FAIL; } if (0 == strcmp(mode, "status")) { if (NULL == option) { SET_MSG_RESULT(result, IPCS_ENUMPARAM); return SYSINFO_RET_FAIL; } if (0 == strcmp(option, "dest")) { #ifdef SHM_DEST SET_UI64_RESULT(result, shmid_ds.shm_perm.mode & SHM_DEST); /* SHM_DEST flag */ return SYSINFO_RET_OK; #else SET_MSG_RESULT(result, IPCS_EPLATFORM); return SYSINFO_RET_FAIL; #endif } if (0 == strcmp(option, "locked")) { #ifdef SHM_LOCKED SET_UI64_RESULT(result, shmid_ds.shm_perm.mode & SHM_LOCKED); /* SHM_LOCKED flag */ return SYSINFO_RET_OK; #else SET_MSG_RESULT(result, IPCS_EPLATFORM); return SYSINFO_RET_FAIL; #endif } SET_MSG_RESULT(result, IPCS_EINVALOPT); return SYSINFO_RET_FAIL; } if (0 == strcmp(mode, "permissions")) { if (NULL != option) { SET_MSG_RESULT(result, IPCS_ENUMPARAM); return SYSINFO_RET_FAIL; } SET_UI64_RESULT(result, shmid_ds.shm_perm.mode & 0777); /* Permissions */ return SYSINFO_RET_OK; } if (0 == strcmp(mode, "size")) { if (NULL != option) { SET_MSG_RESULT(result, IPCS_ENUMPARAM); return SYSINFO_RET_FAIL; } SET_UI64_RESULT(result, shmid_ds.shm_segsz); /* Size of segment (bytes) */ return SYSINFO_RET_OK; } if (0 == strcmp(mode, "time")) { if (NULL == option) { SET_MSG_RESULT(result, IPCS_ENUMPARAM); return SYSINFO_RET_FAIL; } if (0 == strcmp(option, "attach")) { SET_UI64_RESULT(result, shmid_ds.shm_atime); /* Last attach time */ return SYSINFO_RET_OK; } if (0 == strcmp(option, "detach")) { SET_UI64_RESULT(result, shmid_ds.shm_dtime); /* Last detach time */ return SYSINFO_RET_OK; } if (0 == strcmp(option, "change")) { SET_UI64_RESULT(result, shmid_ds.shm_ctime); /* Last change time */ return SYSINFO_RET_OK; } SET_MSG_RESULT(result, IPCS_EINVALOPT); return SYSINFO_RET_FAIL; } if (0 == strcmp(mode, "pid")) { if (NULL == option) { SET_MSG_RESULT(result, IPCS_ENUMPARAM); return SYSINFO_RET_FAIL; } if (0 == strcmp(option, "creator")) { SET_UI64_RESULT(result, shmid_ds.shm_cpid); /* PID of creator */ return SYSINFO_RET_OK; } if (0 == strcmp(option, "last")) { SET_UI64_RESULT(result, shmid_ds.shm_lpid); /* PID of last shmat(2)/shmdt(2) */ return SYSINFO_RET_OK; } SET_MSG_RESULT(result, IPCS_EINVALOPT); return SYSINFO_RET_FAIL; } if (0 == strcmp(mode, "nattch")) { if (NULL != option) { SET_MSG_RESULT(result, IPCS_ENUMPARAM); return SYSINFO_RET_FAIL; } SET_UI64_RESULT(result, shmid_ds.shm_nattch); /* No. of current attaches */ return SYSINFO_RET_OK; } SET_MSG_RESULT(result, IPCS_EINVALMOD); return SYSINFO_RET_FAIL; } static int ipcs_queue_details(AGENT_REQUEST *request, AGENT_RESULT *result) { const char *mode, *option; int msqid; struct msqid_ds msqid_ds; if (IPCS_OK != ipcs_request_parse(request, result, &msqid, &mode, &option)) return SYSINFO_RET_FAIL; if (-1 == msgctl(msqid, IPC_STAT, &msqid_ds)) { SET_MSG_RESULT(result, IPCS_ESYSERROR); return SYSINFO_RET_FAIL; } if (NULL == mode) { SET_MSG_RESULT(result, IPCS_EINVALMOD); return SYSINFO_RET_FAIL; } if (0 == strcmp(mode, "owner")) { if (NULL == option || '\0' == *option || 0 == strcmp(option, "user")) { //TODO return SYSINFO_RET_FAIL; } if (0 == strcmp(option, "group")) { //TODO return SYSINFO_RET_FAIL; } if (0 == strcmp(option, "uid")) { SET_UI64_RESULT(result, msqid_ds.msg_perm.uid); /* Effective UID of owner */ return SYSINFO_RET_OK; } if (0 == strcmp(option, "gid")) { SET_UI64_RESULT(result, msqid_ds.msg_perm.gid); /* Effective GID of owner */ return SYSINFO_RET_OK; } SET_MSG_RESULT(result, IPCS_EINVALOPT); return SYSINFO_RET_FAIL; } if (0 == strcmp(mode, "creator")) { if (NULL == option || '\0' == *option || 0 == strcmp(option, "user")) { //TODO return SYSINFO_RET_FAIL; } if (0 == strcmp(option, "group")) { //TODO return SYSINFO_RET_FAIL; } if (0 == strcmp(option, "uid")) { SET_UI64_RESULT(result, msqid_ds.msg_perm.cuid); /* Effective UID of creator */ return SYSINFO_RET_OK; } if (0 == strcmp(option, "gid")) { SET_UI64_RESULT(result, msqid_ds.msg_perm.cgid); /* Effective GID of creator */ return SYSINFO_RET_OK; } SET_MSG_RESULT(result, IPCS_EINVALOPT); return SYSINFO_RET_FAIL; } if (0 == strcmp(mode, "permissions")) { if (NULL != option) { SET_MSG_RESULT(result, IPCS_ENUMPARAM); return SYSINFO_RET_FAIL; } SET_UI64_RESULT(result, msqid_ds.msg_perm.mode & 0777); /* Permissions */ return SYSINFO_RET_OK; } if (0 == strcmp(mode, "time")) { if (NULL == option) { SET_MSG_RESULT(result, IPCS_ENUMPARAM); return SYSINFO_RET_FAIL; } if (0 == strcmp(option, "send")) { SET_UI64_RESULT(result, msqid_ds.msg_stime); /* Time of last msgsnd(2) */ return SYSINFO_RET_OK; } if (0 == strcmp(option, "receive")) { SET_UI64_RESULT(result, msqid_ds.msg_rtime); /* Time of last msgrcv(2) */ return SYSINFO_RET_OK; } if (0 == strcmp(option, "change")) { SET_UI64_RESULT(result, msqid_ds.msg_ctime); /* Time of last change */ return SYSINFO_RET_OK; } SET_MSG_RESULT(result, IPCS_EINVALOPT); return SYSINFO_RET_FAIL; } if (0 == strcmp(mode, "messages")) { if (NULL != option) { SET_MSG_RESULT(result, IPCS_ENUMPARAM); return SYSINFO_RET_FAIL; } SET_UI64_RESULT(result, msqid_ds.msg_qnum); /* Current number of messages in queue */ return SYSINFO_RET_OK; } if (0 == strcmp(mode, "size")) { if (NULL != option) { SET_MSG_RESULT(result, IPCS_ENUMPARAM); return SYSINFO_RET_FAIL; } SET_UI64_RESULT(result, msqid_ds.msg_qbytes); /* Maximum number of bytes allowed in queue */ return SYSINFO_RET_OK; } if (0 == strcmp(mode, "pid")) { if (NULL == option) { SET_MSG_RESULT(result, IPCS_ENUMPARAM); return SYSINFO_RET_FAIL; } if (0 == strcmp(option, "send")) { SET_UI64_RESULT(result, msqid_ds.msg_lspid); /* PID of last msgsnd(2) */ return SYSINFO_RET_OK; } if (0 == strcmp(option, "receive")) { SET_UI64_RESULT(result, msqid_ds.msg_lrpid); /* PID of last msgrcv(2) */ return SYSINFO_RET_OK; } SET_MSG_RESULT(result, IPCS_EINVALOPT); return SYSINFO_RET_FAIL; } SET_MSG_RESULT(result, IPCS_EINVALMOD); return SYSINFO_RET_FAIL; } static int ipcs_semaphore_loop(int semid, int nsems, int cmd, const char *option, AGENT_RESULT *result) { union semun semid_un; if (NULL == option || '\0' == *option || 0 == strcmp(option, "sum")) { int i, res, sum = 0; for (i = 0; i < nsems; i++) { if (-1 == (res = semctl(semid, i, cmd, semid_un))) goto syserr; sum += res; } SET_UI64_RESULT(result, sum); return SYSINFO_RET_OK; } if (0 == strcmp(option, "max")) { int i, res, max = 0; for (i = 0; i < nsems; i++) { if (-1 == (res = semctl(semid, i, cmd, semid_un))) goto syserr; if (res > max) max = res; } SET_UI64_RESULT(result, max); return SYSINFO_RET_OK; } if (0 == strcmp(option, "idx")) { int i, res, idx = 0, max = 0; for (i = 0; i < nsems; i++) { if (-1 == (res = semctl(semid, i, cmd, semid_un))) goto syserr; if (res > max) max = res, idx = i; } SET_UI64_RESULT(result, idx); return SYSINFO_RET_OK; } SET_MSG_RESULT(result, IPCS_EINVALOPT); return SYSINFO_RET_FAIL; syserr: SET_MSG_RESULT(result, IPCS_ESYSERROR); return SYSINFO_RET_FAIL; } static int ipcs_semaphore_details(AGENT_REQUEST *request, AGENT_RESULT *result) { const char *mode, *option; int semid; struct semid_ds semid_ds; union semun semid_un; if (IPCS_OK != ipcs_request_parse(request, result, &semid, &mode, &option)) return SYSINFO_RET_FAIL; semid_un.buf = &semid_ds; if (-1 == semctl(semid, 0, IPC_STAT, semid_un)) { SET_MSG_RESULT(result, IPCS_ESYSERROR); return SYSINFO_RET_FAIL; } if (NULL == mode) { SET_MSG_RESULT(result, IPCS_EINVALMOD); return SYSINFO_RET_FAIL; } if (0 == strcmp(mode, "owner")) { if (NULL == option || '\0' == *option || 0 == strcmp(option, "user")) { //TODO return SYSINFO_RET_FAIL; } if (0 == strcmp(option, "group")) { //TODO return SYSINFO_RET_FAIL; } if (0 == strcmp(option, "uid")) { SET_UI64_RESULT(result, semid_ds.sem_perm.uid); /* Effective UID of owner */ return SYSINFO_RET_OK; } if (0 == strcmp(option, "gid")) { SET_UI64_RESULT(result, semid_ds.sem_perm.gid); /* Effective GID of owner */ return SYSINFO_RET_OK; } SET_MSG_RESULT(result, IPCS_EINVALOPT); return SYSINFO_RET_FAIL; } if (0 == strcmp(mode, "creator")) { if (NULL == option || '\0' == *option || 0 == strcmp(option, "user")) { //TODO return SYSINFO_RET_FAIL; } if (0 == strcmp(option, "group")) { //TODO return SYSINFO_RET_FAIL; } if (0 == strcmp(option, "uid")) { SET_UI64_RESULT(result, semid_ds.sem_perm.cuid); /* Effective UID of creator */ return SYSINFO_RET_OK; } if (0 == strcmp(option, "gid")) { SET_UI64_RESULT(result, semid_ds.sem_perm.cgid); /* Effective GID of creator */ return SYSINFO_RET_OK; } SET_MSG_RESULT(result, IPCS_EINVALOPT); return SYSINFO_RET_FAIL; } if (0 == strcmp(mode, "permissions")) { if (NULL != option) { SET_MSG_RESULT(result, IPCS_ENUMPARAM); return SYSINFO_RET_FAIL; } SET_UI64_RESULT(result, semid_ds.sem_perm.mode & 0777); /* Permissions */ return SYSINFO_RET_OK; } if (0 == strcmp(mode, "time")) { if (NULL == option) { SET_MSG_RESULT(result, IPCS_ENUMPARAM); return SYSINFO_RET_FAIL; } if (0 == strcmp(option, "semop")) { SET_UI64_RESULT(result, semid_ds.sem_otime); /* Last semop time */ return SYSINFO_RET_OK; } if (0 == strcmp(option, "change")) { SET_UI64_RESULT(result, semid_ds.sem_ctime); /* Last change time */ return SYSINFO_RET_OK; } SET_MSG_RESULT(result, IPCS_EINVALOPT); return SYSINFO_RET_FAIL; } if (0 == strcmp(mode, "nsems")) { if (NULL != option) { SET_MSG_RESULT(result, IPCS_ENUMPARAM); return SYSINFO_RET_FAIL; } SET_UI64_RESULT(result, semid_ds.sem_nsems); /* No. of semaphores in set */ return SYSINFO_RET_OK; } if (0 == strcmp(mode, "ncount")) return ipcs_semaphore_loop(semid, semid_ds.sem_nsems, GETNCNT, option, result); if (0 == strcmp(mode, "zcount")) return ipcs_semaphore_loop(semid, semid_ds.sem_nsems, GETZCNT, option, result); SET_MSG_RESULT(result, IPCS_EINVALMOD); return SYSINFO_RET_FAIL; } /* some more bureaucracy */ ZBX_METRIC *zbx_module_item_list(void) { /* NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) */ static ZBX_METRIC keys[] = /* KEY FLAG FUNCTION TEST PARAMETERS */ { {"ipcs-shmem-discovery", CF_HAVEPARAMS, ipcs_shmem_discovery, NULL}, {"ipcs-shmem-details", CF_HAVEPARAMS, ipcs_shmem_details, "0,size"}, //TODO shmem limits //TODO shmem summary {"ipcs-queue-discovery", CF_HAVEPARAMS, ipcs_queue_discovery, NULL}, {"ipcs-queue-details", CF_HAVEPARAMS, ipcs_queue_details, "0,permissions"}, //TODO queue limits //TODO queue summary {"ipcs-semaphore-discovery", CF_HAVEPARAMS, ipcs_semaphore_discovery, NULL}, {"ipcs-semaphore-details", CF_HAVEPARAMS, ipcs_semaphore_details, "0,nsems"}, //TODO semaphore limits //TODO semaphore summary {NULL} }; return keys; }
2.015625
2
2024-11-18T21:09:48.476826+00:00
2023-04-06T12:09:13
93d230906be2bd5fcd0e13ef5e8630c7712c23d8
{ "blob_id": "93d230906be2bd5fcd0e13ef5e8630c7712c23d8", "branch_name": "refs/heads/master", "committer_date": "2023-04-06T12:09:13", "content_id": "0c05a69555677e21ae2efd07b2da8b461113c1db", "detected_licenses": [ "MIT" ], "directory_id": "17137daf9487e8a9bf5bc2f314871d98656e2562", "extension": "c", "filename": "getCodepointsAscii.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 72853341, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 526, "license": "MIT", "license_type": "permissive", "path": "/split/getCodepointsAscii.c", "provenance": "stackv2-0065.json.gz:18413", "repo_name": "pjshumphreys/querycsv", "revision_date": "2023-04-06T12:09:13", "revision_id": "c8015ab493030f261bf75f74f138f6f84addc47b", "snapshot_id": "30183063c843a4a0b47b2ddcfea410ac5901b192", "src_encoding": "UTF-8", "star_events_count": 25, "url": "https://raw.githubusercontent.com/pjshumphreys/querycsv/c8015ab493030f261bf75f74f138f6f84addc47b/split/getCodepointsAscii.c", "visit_date": "2023-04-14T01:57:35.099026" }
stackv2
/* simple round trip encoding that puts high bit set bytes in the private use area */ void getCodepointsAscii( FILE *stream, QCSV_LONG *codepoints, int *arrLength, int *byteLength ) { int c; if(stream == NULL) { *arrLength = *byteLength = 0; return; } *arrLength = *byteLength = 1; if((c = fgetc(stream)) == EOF) { *byteLength = 0; codepoints[0] = MYEOF; return; } if(c < 0x80) { codepoints[0] = (QCSV_LONG)c; return; } codepoints[0] = (QCSV_LONG)c+0xdf80; }
2.125
2
2024-11-18T21:09:48.986752+00:00
2013-08-09T13:56:46
b24c7a8b10c01217e0957781137a96d4b98432be
{ "blob_id": "b24c7a8b10c01217e0957781137a96d4b98432be", "branch_name": "refs/heads/master", "committer_date": "2013-08-09T13:56:46", "content_id": "0b75f0365da87fe5bf6e5e117aedfeee6b0496a3", "detected_licenses": [ "Apache-2.0" ], "directory_id": "32a7e3555624af117fae245efba75940d5721f9b", "extension": "c", "filename": "toplistbrowser.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": 9688, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/toplistbrowser.c", "provenance": "stackv2-0065.json.gz:19058", "repo_name": "mkai/pyspotify", "revision_date": "2013-08-09T13:56:46", "revision_id": "f22b20ab956a0f603379540e9b2b67b4e68b3402", "snapshot_id": "bf65fc47b586b5fbccec36cf78baf2106c32457d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mkai/pyspotify/f22b20ab956a0f603379540e9b2b67b4e68b3402/src/toplistbrowser.c", "visit_date": "2021-01-18T06:31:20.285893" }
stackv2
#include <Python.h> #include <structmember.h> #include <libspotify/api.h> #include <string.h> #include "pyspotify.h" #include "session.h" #include "toplistbrowser.h" #include "user.h" #include "album.h" #include "artist.h" #include "track.h" static void ToplistBrowser_browse_complete(sp_toplistbrowse *browser, void *data) { Callback *trampoline = (Callback *)data; debug_printf("browse complete (%p, %p)", browser, trampoline); if (trampoline == NULL) return; PyObject *result, *self; PyGILState_STATE gstate = PyGILState_Ensure(); self = ToplistBrowser_FromSpotify(browser, 1 /* add_ref */); result = PyObject_CallFunction(trampoline->callback, "NO", self, trampoline->userdata); if (result != NULL) Py_DECREF(result); else PyErr_WriteUnraisable(trampoline->callback); delete_trampoline(trampoline); PyGILState_Release(gstate); } static bool sp_toplisttype_converter(PyObject *o, void *address) { sp_toplisttype *type = (sp_toplisttype *)address; if (o == NULL || o == Py_None) return 1; if (!PyString_Check(o)) goto error; // This points into the pyobject, no need cleanup memory char *tmp = PyString_AsString(o); /* TODO: create type string constants. */ if (strcmp(tmp, "albums") == 0) *type = SP_TOPLIST_TYPE_ALBUMS; else if (strcmp(tmp, "artists") == 0) *type = SP_TOPLIST_TYPE_ARTISTS; else if (strcmp(tmp, "tracks") == 0) *type = SP_TOPLIST_TYPE_TRACKS; else goto error; return 1; error: PyErr_Format(PyExc_ValueError, "Unknown toplist type: %s", PyString_AsString(PyObject_Repr(o))); return 0; } static bool toplistregion_converter(PyObject *o, void *address) { /* Region, can be * - "XY" where XY is a 2 letter country code * - "all" to get worlwide toplists * - "current" to get the current user's toplists * - user (spotify.User) to get this user's toplists */ toplistregion *region = (toplistregion *)address; if (o == NULL || o == Py_None) return 1; if (Py_TYPE(o) == &UserType) { region->type = SP_TOPLIST_REGION_USER; region->username = (char *)sp_user_canonical_name(User_SP_USER(o)); return 1; } if (!PyString_Check(o)) { PyErr_Format(PyExc_ValueError, "Unknown toplist region: %s", PyString_AsString(PyObject_Repr(o))); return 0; } /* TODO: create type string constants. */ char *tmp = PyString_AsString(o); if (strcmp(tmp, "all") == 0) region->type = SP_TOPLIST_REGION_EVERYWHERE; else if (strcmp(tmp, "current") == 0) region->type = SP_TOPLIST_REGION_USER; else /* TODO: sanity checking country code */ region->type = SP_TOPLIST_REGION(tmp[0], tmp[1]); return 1; } static PyObject * ToplistBrowser_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *callback = NULL, *userdata = NULL; Callback *trampoline = NULL; sp_toplistbrowse *browser; sp_toplisttype browse_type = SP_TOPLIST_TYPE_ARTISTS; toplistregion region; region.username = NULL; region.type = SP_TOPLIST_REGION_EVERYWHERE; static char *kwlist[] = {"type", "region", "callback", "userdata", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&|OO", kwlist, &sp_toplisttype_converter, (void *)&browse_type, &toplistregion_converter, (void *)&region, &callback, &userdata)) return NULL; if (callback != NULL) trampoline = create_trampoline(callback, userdata); Py_BEGIN_ALLOW_THREADS browser = sp_toplistbrowse_create(g_session, browse_type, region.type, region.username, ToplistBrowser_browse_complete, (void*)trampoline); Py_END_ALLOW_THREADS return ToplistBrowser_FromSpotify(browser, 0 /* add_ref */); } PyObject * ToplistBrowser_FromSpotify(sp_toplistbrowse *browser, bool add_ref) { PyObject *self = ToplistBrowserType.tp_alloc(&ToplistBrowserType, 0); ToplistBrowser_SP_TOPLISTBROWSE(self) = browser; if (add_ref) sp_toplistbrowse_add_ref(browser); return self; } static void ToplistBrowser_dealloc(PyObject* self) { if (ToplistBrowser_SP_TOPLISTBROWSE(self) != NULL) sp_toplistbrowse_release(ToplistBrowser_SP_TOPLISTBROWSE(self)); self->ob_type->tp_free(self); } static PyObject * ToplistBrowser_is_loaded(PyObject* self) { return PyBool_FromLong(sp_toplistbrowse_is_loaded( ToplistBrowser_SP_TOPLISTBROWSE(self))); } static PyObject * ToplistBrowser_error(PyObject* self) { return error_message(sp_toplistbrowse_error( ToplistBrowser_SP_TOPLISTBROWSE(self))); } /* sequence protocol: */ Py_ssize_t ToplistBrowser_sq_length(PyObject* self) { int n; sp_toplistbrowse *browser = ToplistBrowser_SP_TOPLISTBROWSE(self); /* TODO: see if we can store type to avoid this crazy hack */ if ((n = sp_toplistbrowse_num_albums(browser))) return n; else if ((n = sp_toplistbrowse_num_artists(browser))) return n; else return sp_toplistbrowse_num_tracks(browser); } PyObject * ToplistBrowser_sq_item(PyObject *self, Py_ssize_t index) { int i = (int)index; sp_toplistbrowse *browser = ToplistBrowser_SP_TOPLISTBROWSE(self); /* TODO: see if we can store type to avoid this crazy hack */ if (index < sp_toplistbrowse_num_albums(browser)) return Album_FromSpotify( sp_toplistbrowse_album(browser, i), 1 /* add_ref */); else if (index < sp_toplistbrowse_num_artists(browser)) return Artist_FromSpotify( sp_toplistbrowse_artist(browser, i), 1 /* add_ref */); else if (index < sp_toplistbrowse_num_tracks(browser)) return Track_FromSpotify( sp_toplistbrowse_track(browser, i), 1 /* add_ref */); PyErr_SetNone(PyExc_IndexError); return NULL; } PySequenceMethods ToplistBrowser_as_sequence = { (lenfunc) ToplistBrowser_sq_length, /*sq_length*/ 0, /*sq_concat*/ 0, /*sq_repeat*/ (ssizeargfunc) ToplistBrowser_sq_item, /*sq_item*/ 0, /*sq_ass_item*/ 0, /*sq_contains*/ 0, /*sq_inplace_concat*/ 0, /*sq_inplace_repeat*/ }; static PyMethodDef ToplistBrowser_methods[] = { {"is_loaded", (PyCFunction) ToplistBrowser_is_loaded, METH_NOARGS, "True if this toplist browser has been loaded by the client" }, {"error", (PyCFunction) ToplistBrowser_error, METH_NOARGS, "" }, {NULL} /* Sentinel */ }; static PyMemberDef ToplistBrowser_members[] = { {NULL} /* Sentinel */ }; PyTypeObject ToplistBrowserType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "spotify.ToplistBrowser", /*tp_name*/ sizeof(ToplistBrowser), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor) ToplistBrowser_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ &ToplistBrowser_as_sequence, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ "ToplistBrowser objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ToplistBrowser_methods, /* tp_methods */ ToplistBrowser_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ ToplistBrowser_new, /* tp_new */ }; void toplistbrowser_init(PyObject *module) { Py_INCREF(&ToplistBrowserType); PyModule_AddObject(module, "ToplistBrowser", (PyObject *)&ToplistBrowserType); }
2.171875
2
2024-11-18T21:09:49.067174+00:00
2018-03-13T06:18:28
995c8d81e73a7d7b9bd4827d12a4f16de657898f
{ "blob_id": "995c8d81e73a7d7b9bd4827d12a4f16de657898f", "branch_name": "refs/heads/master", "committer_date": "2018-03-13T06:18:28", "content_id": "fa98d4a669a0e7f4f4c7921178606eb4cce4422b", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "f7fa665cdbdd99e6eb3d52c18f09f6c8435df685", "extension": "c", "filename": "rsasign.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": 2307, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/rsasign.c", "provenance": "stackv2-0065.json.gz:19188", "repo_name": "hfbhfb/rsasign.js", "revision_date": "2018-03-13T06:18:28", "revision_id": "670505d35e6aac0dd2d857b8722dec166ce4fed5", "snapshot_id": "389922cccad8f3d3d87d89579a9181371e5a73dc", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/hfbhfb/rsasign.js/670505d35e6aac0dd2d857b8722dec166ce4fed5/rsasign.c", "visit_date": "2020-03-19T23:59:05.668081" }
stackv2
#include "openssl/asn1.h" #include "openssl/asn1t.h" #include "openssl/bn.h" #include "openssl/rand.h" #include "openssl/rsa.h" #include "openssl/sha.h" #include "openssl/x509.h" #include "randombytes.h" void rsasignjs_init () { randombytes_stir(); } long rsasignjs_public_key_bytes () { return RSASIGNJS_PUBLEN; } long rsasignjs_secret_key_bytes () { return RSASIGNJS_PRIVLEN; } long rsasignjs_signature_bytes () { return RSASIGNJS_SIGLEN; } long rsasignjs_keypair ( uint8_t* public_key, uint8_t* private_key ) { BIGNUM* prime = BN_new(); RSA* rsa = RSA_new(); BN_add_word(prime, RSA_F4); if (RSA_generate_key_ex(rsa, RSASIGNJS_BITS, prime, NULL) != 1) { return 1; } i2d_RSA_PUBKEY(rsa, &public_key); i2d_RSAPrivateKey(rsa, &private_key); RSA_free(rsa); BN_free(prime); return 0; } long rsasignjs_sign ( uint8_t* signature, uint8_t* message, long message_len, const uint8_t* private_key, long private_key_len ) { RSA* rsa = RSA_new(); if (d2i_RSAPrivateKey(&rsa, &private_key, private_key_len) == NULL) { return -1; } uint8_t hash[SHA256_DIGEST_LENGTH]; SHA256_CTX sha256; SHA256_Init(&sha256); SHA256_Update(&sha256, message, message_len); SHA256_Final(hash, &sha256); long status = RSA_sign( NID_sha256, hash, SHA256_DIGEST_LENGTH, signature, NULL, rsa ); RSA_free(rsa); return status; } long rsasignjs_verify ( uint8_t* signature, uint8_t* message, long message_len, const uint8_t* public_key, long public_key_len ) { RSA* rsa = RSA_new(); if (d2i_RSAPublicKey(&rsa, &public_key, public_key_len) == NULL) { return -1; } uint8_t hash[SHA256_DIGEST_LENGTH]; SHA256_CTX sha256; SHA256_Init(&sha256); SHA256_Update(&sha256, message, message_len); SHA256_Final(hash, &sha256); long status = RSA_verify( NID_sha256, hash, SHA256_DIGEST_LENGTH, signature, RSASIGNJS_SIGLEN, rsa ); RSA_free(rsa); return status; } void RAND_add (const void *buf, int num, double entropy) { randombytes_stir(); } int RAND_bytes (unsigned char *buf, int num) { randombytes_buf(buf, num); return 1; } int RAND_pseudo_bytes (unsigned char *buf, int num) { return RAND_bytes(buf, num); } void RAND_seed (const void *buf, int num) { randombytes_stir(); } int RAND_status () { return 1; } void rand_cleanup_int () {}
2.109375
2
2024-11-18T21:09:49.227451+00:00
2019-10-21T14:08:58
f10bce633bcca785ec9c56fbb221b36d7c897f70
{ "blob_id": "f10bce633bcca785ec9c56fbb221b36d7c897f70", "branch_name": "refs/heads/master", "committer_date": "2019-10-21T14:08:58", "content_id": "da76fba1d8c60dd233ac4be22bd93c665ae2c4ec", "detected_licenses": [ "MIT" ], "directory_id": "5ef3741db524f7a4a0accced304d60591b99f25f", "extension": "h", "filename": "ssd1306.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 216580759, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9360, "license": "MIT", "license_type": "permissive", "path": "/GccApplication1/lib/ssd1306.h", "provenance": "stackv2-0065.json.gz:19447", "repo_name": "AgentEVG/Aquarium_lamp", "revision_date": "2019-10-21T14:08:58", "revision_id": "a9b2890a224c11a1f424c37f2fd38b9e5899c964", "snapshot_id": "ad4afba445a9a891a0f48082e68195836b8ef9b3", "src_encoding": "WINDOWS-1251", "star_events_count": 2, "url": "https://raw.githubusercontent.com/AgentEVG/Aquarium_lamp/a9b2890a224c11a1f424c37f2fd38b9e5899c964/GccApplication1/lib/ssd1306.h", "visit_date": "2020-08-23T08:44:39.928395" }
stackv2
//-------------------------------------------------< axlib v1.1 >---------------------------------------------------- //-------------------------------------------------< Библиотека для работы с OLED дисплеем SSD1306 >---------------------------------------------------- //-------------------------------------------------< Кузнецов Алексей 2015 http://www.avrki.ru >---------------------------------------------------- #ifndef SSD1306_H_ #define SSD1306_H_ #if !defined(MAIN_INIT_H_) #error "You must included (#include \"main_init.h\") befor use (#include <axlib/ssd1306.h>)." #endif //------------------------------------------------------------------------- // Объявление служебных псевдонимов //------------------------------------------------------------------------- #define SSD1306_OK 0 #define SSD1306_FAIL 1 #define SSD1306_DELAY() #define SSD1306_SET 1 #define SSD1306_RESET 0 //------------------------------------------------------------------------- // Подключаемые библиотеки //------------------------------------------------------------------------- #include "type_var.h" #include "i2c.h" #include "font5x7.h" //------------------------------------------------------------------------- // Объявление функций //------------------------------------------------------------------------- // Функция передачи команды BYTE ssd1306_send_com(BYTE com); // Функция передачи команды BYTE ssd1306_send_data(BYTE data); // Функция инициализации дисплея. BYTE ssd1306_init(void); // Функция установки позиции void ssd1306_position(BYTE x, BYTE y); // Функция очистки дисплея void ssd1306_clear(void); // Функция установки курсора void ssd1306_goto_xy(BYTE x, BYTE y); // Функция вывода символа void ssd1306_putchar(BYTE chr); //Функция вывода строки void ssd1306_putstr(BYTE *str); // Функция вывода своего символа void ssd136_symbol(BYTE *arr, BYTE light); //------------------------------------------------------------------------- // Функция передачи команды дисплею // //------------------------------------------------------------------------- BYTE ssd1306_send_com(BYTE com) { BYTE ask = ACK; i2c_start(); ask = i2c_send_byte(SSD1306_ADD); ask = i2c_send_byte(0x00); ask = i2c_send_byte(com); ask = i2c_stop(); return ask; } //------------------------------------------------------------------------- // Функция передачи данных дисплею // //------------------------------------------------------------------------- BYTE ssd1306_send_data(BYTE data) { BYTE ask = ACK; i2c_start(); ask = i2c_send_byte(SSD1306_ADD); ask = i2c_send_byte(0x40); ask = i2c_send_byte(data); ask = i2c_stop(); return ask; } //------------------------------------------------------------------------- // Функция иницциализирует дисплей. Возвращаемое значение указывает // на качество выпонения инициализации. При удаче вернет SSD1306_OK, при неудаче // вурнет ошибку SSD1306_FAIL. //------------------------------------------------------------------------- BYTE ssd1306_init(void) { BYTE ask = ACK; i2c_init(); _delay_ms(100); ask = ssd1306_send_com(0xAE); // Выключить дисплей ask = ssd1306_send_com(0xD5); // Настройка частоты обновления дисплея ask = ssd1306_send_com(0x80); ///+----- делитель 0-F/ 0 - деление на 1 //+------ частота генератора. по умочанию 0x80 ask = ssd1306_send_com(0xA8); // Установить multiplex ratio ask = ssd1306_send_com(0x3F); // 1/64 duty (значение по умолчанию), 0x1F - 128x32, 0x3F - 128x64 3f ask = ssd1306_send_com(0xD3); // Смещение дисплея (offset) ask = ssd1306_send_com(0xF0); // Нет смещения0xF1 ask = ssd1306_send_com(0x40); // Начала строки начала разверки 0x40 с начала RAM0x40 ask = ssd1306_send_com(0x8D); // Управление внутреним преобразователем ask = ssd1306_send_com(0x14); // 0x10 - отключить (VCC подается извне) 0x14 - запустить внутрений DC/DC ask = ssd1306_send_com(0x20); // Режим автоматической адресации ask = ssd1306_send_com(0x00); // 0-по горизонтали с переходом на новую страницу (строку) // 1 - по вертикали с переходом на новую строку // 2 - только по выбранной странице без перехода ask = ssd1306_send_com(0xA1); // Режим разверки по странице (по X) // A1 - нормальный режим (слева/направо) A0 - обратный (справа/налево) ask = ssd1306_send_com(0xC0); // Режим сканирования озу дисплея // для изменения системы координат // С0 - снизу/верх (начало нижний левый угол) // С8 - сверху/вниз (начало верний левый угол) ask = ssd1306_send_com(0xDA); // Аппаратная конфигурация COM ask = ssd1306_send_com(0x02); // 0x02 - 128x32, 0x12 - 128x64 0x22 ask = ssd1306_send_com(0x81); // Установка яркости дисплея ask = ssd1306_send_com(0x8F); // 0x8F..0xCF ask = ssd1306_send_com(0xD9); // Настройка фаз DC/DC преоразователя ask = ssd1306_send_com(0xF1); // 0x22 - VCC подается извне / 0xF1 для внутренего ask = ssd1306_send_com(0xDB); // Установка уровня VcomH ask = ssd1306_send_com(0x01); // Влияет на яркость дисплея 0x00..0x70 ask = ssd1306_send_com(0xA4); // Режим нормальный ask = ssd1306_send_com(0xA6); // 0xA6 - нет инверсии, 0xA7 - инверсия дисплея ask = ssd1306_send_com(0xAF); // Дисплей включен ssd1306_clear(); return ask; } //------------------------------------------------------------------------- // Функция установки позиции // //------------------------------------------------------------------------- void ssd1306_position(BYTE x, BYTE y) { if(y == 0) ssd1306_send_com(0xB1); if(y == 1) ssd1306_send_com(0xB0); if((y > 1) & (y <= 7)) { ssd1306_send_com(0xB9 - y); } ssd1306_send_com(((x & 0xF0) >> 4) | 0x10); ssd1306_send_com((x & 0x0F) | 0x01); } //------------------------------------------------------------------------- // Функция очистки дисплея // //------------------------------------------------------------------------- void ssd1306_clear(void) { BYTE m,n; for(m=0;m<8;m++) { ssd1306_send_com(0xb0+m); ssd1306_send_com(0x00); ssd1306_send_com(0x10); for(n=0;n<128;n++) { ssd1306_send_data(0x00); } } } //------------------------------------------------------------------------- // Функция установки курсора // //------------------------------------------------------------------------- void ssd1306_goto_xy(BYTE x, BYTE y) { if(x > 21) x = 21; if(y > 3) y = 3; ssd1306_position((x*6), y); } //------------------------------------------------------------------------- // Функция вывода символа // //------------------------------------------------------------------------- void ssd1306_putchar(BYTE chr) { BYTE i; if(chr < 0x20) { chr = 0x00; } else { chr -= 0x20; } for(i=0; i<5; i++) { ssd1306_send_data(pgm_read_byte(&(font6x8[(chr*5)+i]))); } ssd1306_send_data(0x00); } //------------------------------------------------------------------------- // Функция вывода строки // //------------------------------------------------------------------------- void ssd1306_putstr(BYTE *str) { while(*str) { ssd1306_putchar(*str); str++; } } //------------------------------------------------------------------------- // Функция вывода своего символа // //------------------------------------------------------------------------- void ssd136_symbol(BYTE *arr, BYTE light) { BYTE i = 0; for(i=0; i<light; i++) { ssd1306_send_data(*arr); arr++; } } //------------------------------------------------------------------------- void ssd1306_pix_xy(BYTE x, BYTE y, BYTE mode) { BYTE data_page = y/8; BYTE data_pix = 0; if(mode == SSD1306_SET) { data_pix |= (1 << (y%8)); } ssd1306_position(x, data_page); ssd1306_send_data(data_pix); } #endif /* SSD1306_H_ */
2.40625
2
2024-11-18T21:09:54.154175+00:00
2016-06-01T03:29:39
58f954bdaa01e153520580b562592fb170f0f3cf
{ "blob_id": "58f954bdaa01e153520580b562592fb170f0f3cf", "branch_name": "refs/heads/master", "committer_date": "2016-06-01T03:29:39", "content_id": "93cbee7735c364dfd2d4761e217bf6de5c60e1e2", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "15f4f76c0d25f988cfe72e3e8623fdd81f546359", "extension": "c", "filename": "taskqueue.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 40615736, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7526, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/taskqueue.c", "provenance": "stackv2-0065.json.gz:19833", "repo_name": "mincore/taskqueue", "revision_date": "2016-06-01T03:29:39", "revision_id": "eee676aa7a264e00a6cbef118bab12b15befb7a5", "snapshot_id": "9f7a36943098fc040798fe65df27e43a5d6ee75d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mincore/taskqueue/eee676aa7a264e00a6cbef118bab12b15befb7a5/taskqueue.c", "visit_date": "2021-01-09T20:45:13.519722" }
stackv2
/* * Copyright (C) 2014, shuangping chen <[email protected]> * * 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 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 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. */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdint.h> #include <unistd.h> #include <sys/types.h> #include <sys/time.h> #include <time.h> #include <pthread.h> #include <assert.h> #include <errno.h> #include "taskqueue.h" #define atomic_set(p, v) (*(p) = (v)) #define atomic_read(p) (*(p)) #define MAX_WAKEUP_TIME 3600000 // 1 hour struct thread { pthread_t pthread; pthread_cond_t cond; struct taskqueue *tq; int sleeping; struct delay_task *delay_cache; }; struct taskqueue { struct task *head; struct task **ptail; pthread_mutex_t task_list_lock; struct thread *threads; int thread_count; int quit; RB_HEAD(delay_task_tree, delay_task) delay_task_tree; pthread_mutex_t delay_task_tree_lock; unsigned long long delay_task_id; }; static unsigned long long now() { struct timeval tv; gettimeofday(&tv, NULL); return ((unsigned long long)tv.tv_sec)*1000 + tv.tv_usec/1000; } static void timespec_init(struct timespec *ts, unsigned long long ms) { ts->tv_sec = ms / 1000; ts->tv_nsec = (ms % 1000 ) * 1000 * 1000ULL; } static int delay_task_compare(struct delay_task *a, struct delay_task *b) { if (a->delay != b->delay) return a->delay - b->delay; return a->id - b->id; } RB_GENERATE(delay_task_tree, delay_task, rb_entry, delay_task_compare); static void wakeup_one(struct taskqueue *tq) { for (int i = 0; i < tq->thread_count; i++) { if (atomic_read(&tq->threads[i].sleeping)) { pthread_cond_signal(&tq->threads[i].cond); break; } } } static void wakeup_all(struct taskqueue *tq) { for (int i = 0; i < tq->thread_count; i++) { pthread_cond_signal(&tq->threads[i].cond); } } static struct task *taskqueue_dequeue(struct taskqueue *tq) { struct task *task; pthread_mutex_lock(&tq->task_list_lock); task = tq->head; if (tq->head) { tq->head = tq->head->next; if (tq->head == NULL) tq->ptail = &tq->head; } pthread_mutex_unlock(&tq->task_list_lock); return task; } static int thread_should_quit(struct thread *thread) { return atomic_read(&thread->tq->quit); } static void thread_wait(struct thread *thread) { struct taskqueue *tq = thread->tq; struct timespec ts; unsigned long long delay = 0; pthread_mutex_lock(&tq->task_list_lock); if (tq->head == NULL) { if (thread->delay_cache == NULL) delay = now() + MAX_WAKEUP_TIME; else if (thread->delay_cache->delay > now()) delay = thread->delay_cache->delay; if (delay) { timespec_init(&ts, delay); atomic_set(&thread->sleeping, 1); pthread_cond_timedwait(&thread->cond, &tq->task_list_lock, &ts); atomic_set(&thread->sleeping, 0); } } pthread_mutex_unlock(&tq->task_list_lock); } static void thread_run_delay_task(struct thread *thread) { struct taskqueue *tq = thread->tq; struct delay_task *delay_task; thread->delay_cache = NULL; pthread_mutex_lock(&tq->delay_task_tree_lock); while (!thread_should_quit(thread)) { delay_task = RB_MIN(delay_task_tree, &tq->delay_task_tree); if (!delay_task || delay_task->delay > now()) { thread->delay_cache = delay_task; break; } RB_REMOVE(delay_task_tree, &tq->delay_task_tree, delay_task); pthread_mutex_unlock(&tq->delay_task_tree_lock); delay_task->func(delay_task); pthread_mutex_lock(&tq->delay_task_tree_lock); } pthread_mutex_unlock(&tq->delay_task_tree_lock); } static void thread_run_task(struct thread *thread) { struct taskqueue *tq = thread->tq; struct task *task; task = taskqueue_dequeue(tq); if (task) task->func(task); } static void *thread_loop(void *p) { struct thread *thread = p; while (!thread_should_quit(thread)) { thread_run_task(thread); thread_run_delay_task(thread); thread_wait(thread); } return NULL; } struct taskqueue *taskqueue_create(int thread_count) { struct taskqueue *tq; tq = malloc(sizeof(struct taskqueue)); memset(tq, 0, sizeof(struct taskqueue)); pthread_mutex_init(&tq->task_list_lock, NULL); pthread_mutex_init(&tq->delay_task_tree_lock, NULL); tq->ptail = &tq->head; tq->thread_count = thread_count <= 0 ? 1 : thread_count; tq->threads = malloc(sizeof(struct thread) * thread_count); memset(tq->threads, 0, sizeof(struct thread) * thread_count); for (int i = 0; i < thread_count; i++) { tq->threads[i].tq = tq; pthread_cond_init(&tq->threads[i].cond, NULL); pthread_create(&tq->threads[i].pthread, NULL, thread_loop, &tq->threads[i]); } return tq; } struct task *taskqueue_destroy(struct taskqueue *tq) { struct task *ret; if (tq == NULL) return NULL; atomic_set(&tq->quit, 1); wakeup_all(tq); for (int i = 0; i < tq->thread_count; i++) { pthread_join(tq->threads[i].pthread, NULL); pthread_cond_destroy(&tq->threads[i].cond); } free(tq->threads); pthread_mutex_destroy(&tq->task_list_lock); ret = tq->head; free(tq); return ret; } int taskqueue_enqueue(struct taskqueue *tq, struct task *task, task_func_t func) { if (tq == NULL || task == NULL) return -1; task->func = func; task->next = NULL; pthread_mutex_lock(&tq->task_list_lock); *tq->ptail = task; tq->ptail = &task->next; wakeup_one(tq); pthread_mutex_unlock(&tq->task_list_lock); return 0; } int taskqueue_enqueue_timeout(struct taskqueue *tq, struct delay_task* delay_task, delay_task_func_t func, unsigned long long delay) { if (tq == NULL || delay_task == NULL) return -1; delay_task->func = func; pthread_mutex_lock(&tq->delay_task_tree_lock); delay_task->delay = now() + delay; delay_task->id = tq->delay_task_id++; RB_INSERT(delay_task_tree, &tq->delay_task_tree, delay_task); wakeup_one(tq); pthread_mutex_unlock(&tq->delay_task_tree_lock); return 0; }
2.0625
2
2024-11-18T21:09:54.440915+00:00
2018-06-10T04:39:13
98e91ed20337dc287be944d06652006cbe87f32a
{ "blob_id": "98e91ed20337dc287be944d06652006cbe87f32a", "branch_name": "refs/heads/master", "committer_date": "2018-06-10T04:39:13", "content_id": "953ad28e5746ff4514a88bf18f628a09e1f7fa60", "detected_licenses": [ "Unlicense" ], "directory_id": "0209f47d7b4579a52aca67432bdf7348cea694fe", "extension": "c", "filename": "heapsort.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": 1156, "license": "Unlicense", "license_type": "permissive", "path": "/heapsort.c", "provenance": "stackv2-0065.json.gz:20218", "repo_name": "Hasanaccms/SortingAlgo", "revision_date": "2018-06-10T04:39:13", "revision_id": "3af95b15529e815d4a38fe11be6588d396d5d1c2", "snapshot_id": "eed11d05ba57904b8c62b0208193e866fabb501b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Hasanaccms/SortingAlgo/3af95b15529e815d4a38fe11be6588d396d5d1c2/heapsort.c", "visit_date": "2020-03-19T17:49:05.446184" }
stackv2
#include <iostream> using namespace std; void heapify(int arr[], int n, int i) { // Find largest among root, left child and right child int largest = i; int l = 2*i + 1; int r = 2*i + 2; if (l < n && arr[l] > arr[largest]) largest = l; if (right < n && arr[r] > arr[largest]) largest = r; // Swap and continue heapifying if root is not largest if (largest != i) { swap(arr[i], arr[largest]); heapify(arr, n, largest); } } // main function to do heap sort void heapSort(int arr[], int n) { // Build max heap for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // Heap sort for (int i=n-1; i>=0; i--) { swap(arr[0], arr[i]); // Heapify root element to get highest element at root again heapify(arr, i, 0); } } void printArray(int arr[], int n) { for (int i=0; i<n; ++i) cout << arr[i] << " "; cout << "\n"; } int main() { int arr[] = {1,12,9,5,6,10}; int n = sizeof(arr)/sizeof(arr[0]); heapSort(arr, n); cout << "Sorted array is \n"; printArray(arr, n); }
3.78125
4
2024-11-18T21:09:55.372751+00:00
2023-09-02T17:41:06
39be437ede496a437bc57eac2dcc71d9dd2fc8e9
{ "blob_id": "39be437ede496a437bc57eac2dcc71d9dd2fc8e9", "branch_name": "refs/heads/master", "committer_date": "2023-09-02T17:41:06", "content_id": "88bfc578cf525c5c50694625553a3481f3abc039", "detected_licenses": [ "Apache-2.0" ], "directory_id": "54ae02a305b94c6263cd2d888be2b8755b34bf4f", "extension": "c", "filename": "sigaltstack.c", "fork_events_count": 30, "gha_created_at": "2015-08-24T09:45:58", "gha_event_created_at": "2023-09-07T16:21:36", "gha_language": "Shell", "gha_license_id": null, "github_id": 41295289, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2501, "license": "Apache-2.0", "license_type": "permissive", "path": "/test/darwin/sigaltstack.c", "provenance": "stackv2-0065.json.gz:20602", "repo_name": "titzer/virgil", "revision_date": "2023-09-02T17:41:06", "revision_id": "79bb4caf00db3a1ade97408fe0938ff3a18b1cde", "snapshot_id": "8bc6295467243ee1d9c49ab42b5d08548703666a", "src_encoding": "UTF-8", "star_events_count": 796, "url": "https://raw.githubusercontent.com/titzer/virgil/79bb4caf00db3a1ade97408fe0938ff3a18b1cde/test/darwin/sigaltstack.c", "visit_date": "2023-09-06T06:31:24.136671" }
stackv2
/* * Copyright (c) 2002-2003, Intel Corporation. All rights reserved. * Created by: rusty.lynch REMOVE-THIS AT intel DOT com * This file is licensed under the GPL license. For the full content * of this license, see the COPYING file at the top level of this * source tree. Test case for assertion #12 of the sigaction system call that verifies signal-catching functions are executed on the alternate stack if the SA_ONSTACK flag is set in the sigaction.sa_flags parameter to the sigaction function call, and an alternate stack has been setup with sigaltstack(). NOTE: This test case does not attempt to verify the proper operation of sigaltstack. */ #define _XOPEN_SOURCE 600 #define PTS_UNRESOLVED 1 #define PTS_PASS 0 #include <signal.h> #include <stdio.h> #include <stdlib.h> //#include "posixtest.h" stack_t alt_ss; void handler(int signo) { stack_t ss; printf("Caught SIGXFSZ\n"); if (sigaltstack((stack_t *)0, &ss) == -1) { perror("Unexpected error while attempting to setup test " "pre-conditions"); exit(-1); } else { printf("INFO: %s sigaltstack((stack_t *)0, &ss)returned successfully\n",__func__); } if (ss.ss_sp != alt_ss.ss_sp || ss.ss_size != alt_ss.ss_size) { printf("Test FAILED\n"); exit(-1); } } int main() { struct sigaction act; act.sa_handler = handler; act.sa_flags = SA_ONSTACK; sigemptyset(&act.sa_mask); if (sigaction(SIGXFSZ, &act, 0) == -1) { perror("Unexpected error while attempting to setup test " "pre-conditions"); return PTS_UNRESOLVED; } else { printf("INFO: sigaction((SIGXFSZ, &act, 0) returned successfully\n"); } if ((alt_ss.ss_sp = (void *)malloc(SIGSTKSZ)) == NULL) { perror("Unexpected error while attempting to setup test " "pre-conditions"); return PTS_UNRESOLVED; } else { printf("INFO: Successfully malloc'd alternative stack\n"); } alt_ss.ss_size = SIGSTKSZ; alt_ss.ss_flags = 0; if (sigaltstack(&alt_ss, (stack_t *)0) == -1) { perror("Unexpected error while attempting to setup test " "pre-conditions"); return PTS_UNRESOLVED; } else { printf("INFO: sigaltstack(&alt_ss, (stack_t *)0) returned successfully\n"); } if (raise(SIGXFSZ) == -1) { perror("Unexpected error while attempting to setup test " "pre-conditions"); return PTS_UNRESOLVED; } else { printf("INFO: raise(SGABRT) returned successfully\n"); } printf("Test PASSED\n"); return PTS_PASS; }
2.8125
3
2024-11-18T21:09:55.747179+00:00
2022-03-17T17:29:02
e58f16af688f9fac61f4fd8c78ca778251e93440
{ "blob_id": "e58f16af688f9fac61f4fd8c78ca778251e93440", "branch_name": "refs/heads/main", "committer_date": "2022-03-17T23:08:34", "content_id": "51aaf482eaae10139be075e9e98917ac0fe281be", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "bf6166890a2b70d6c3de35970ed3c1a6ff18572d", "extension": "h", "filename": "sharpyuv.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": 1580, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/sharpyuv/sharpyuv.h", "provenance": "stackv2-0065.json.gz:20861", "repo_name": "670832188/libwebp", "revision_date": "2022-03-17T17:29:02", "revision_id": "34bb332ca15d9ce605280265c6b042cef149f68d", "snapshot_id": "82b5c07aa0c1732e6ee7b6eb8757fd76f8adfc07", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/670832188/libwebp/34bb332ca15d9ce605280265c6b042cef149f68d/sharpyuv/sharpyuv.h", "visit_date": "2023-08-23T21:38:59.335588" }
stackv2
// Copyright 2022 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING 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. // ----------------------------------------------------------------------------- // // Sharp RGB to YUV conversion. #ifndef WEBP_SHARPYUV_SHARPYUV_H_ #define WEBP_SHARPYUV_SHARPYUV_H_ #include <inttypes.h> #ifdef __cplusplus extern "C" { #endif // Converts RGB to YUV420 using a downsampling algorithm that minimizes // artefacts caused by chroma subsampling. // This is slower than standard downsampling (averaging of 4 UV values). // Assumes that the image will be upsampled using a bilinear filter. If nearest // neighbor is used instead, the upsampled image might look worse than with // standard downsampling. // TODO(maryla): add 10 bits and handling of various colorspaces. Add YUV444 to // YUV420 conversion. Maybe also add 422 support (it's rarely used in practice, // especially for images). int SharpArgbToYuv(const uint8_t* r_ptr, const uint8_t* g_ptr, const uint8_t* b_ptr, int step, int rgb_stride, uint8_t* dst_y, int dst_stride_y, uint8_t* dst_u, int dst_stride_u, uint8_t* dst_v, int dst_stride_v, int width, int height); #ifdef __cplusplus } // extern "C" #endif #endif // WEBP_SHARPYUV_SHARPYUV_H_
2
2
2024-11-18T21:09:55.822573+00:00
2020-08-24T17:33:23
c8d318fe6707af1876e36d722a8fdb374d9b741e
{ "blob_id": "c8d318fe6707af1876e36d722a8fdb374d9b741e", "branch_name": "refs/heads/master", "committer_date": "2020-08-24T17:33:23", "content_id": "386c61370daad0d19a8fd79627fce6af899f4dae", "detected_licenses": [ "MIT" ], "directory_id": "52e15922b024a12e3cf84ea784c5e478b1a0e3a8", "extension": "h", "filename": "gsm.h", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 266123833, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1973, "license": "MIT", "license_type": "permissive", "path": "/gsm_task/gsm.h", "provenance": "stackv2-0065.json.gz:20990", "repo_name": "sharmaronak79/Capstone-project-summer2020", "revision_date": "2020-08-24T17:33:23", "revision_id": "c05c6abd27cb2df62b5dc6f1a42647aa59d2aad6", "snapshot_id": "a4c9348982fb45eea3b1d34dbfb0ead05b70ce53", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sharmaronak79/Capstone-project-summer2020/c05c6abd27cb2df62b5dc6f1a42647aa59d2aad6/gsm_task/gsm.h", "visit_date": "2022-12-03T12:32:05.768147" }
stackv2
// declaration of functions void ser_init(void); void tx(unsigned char c); unsigned char rx(void); void tx_str(unsigned char *s); void sms(unsigned char *num1,unsigned char *msg); void gsm_delay(void); unsigned int dell; void sms(unsigned char *num1,unsigned char *msg) // definition of sms function { tx_str("AT"); //sending attention command tx(0x0d); // for new line gsm_delay(); tx_str("AT+CMGF=1"); // to set up GSM module in text mode tx(0x0d); gsm_delay(); tx_str("AT+CMGS="); // to enter number on which message will be sent tx('"'); while(*num1) tx(*num1++); // entering the digits one by one tx('"'); tx(0x0d); gsm_delay(); while(*msg) // writing the message tx(*msg++); tx(0x1a); gsm_delay(); } void gsm_delay() // function for delay { unsigned long int gsm_del,ff; for(gsm_del=0;gsm_del<=500000;gsm_del++) for(ff=0;ff<25;ff++); } void ser_init() // initializing function for serial communication { VPBDIV=0x02; //PCLK = 30MHz PINSEL0=0x5; //to define P0.0 as Tx and P0.1 as Rx pin U0LCR=0x83; // 8 BIT data,1 stop bit,enabling DLAB bit U0DLL=195; // setting baud rate at 9600 U0DLM=0; U0LCR=0x03; // disable DLAB bit U0TER=(1<<7); } void tx(unsigned char c) // function for serial transmissin of character { U0THR=c; while((U0LSR&(1<<5))==0); // wait for THRE bit to be 1 } void tx_str(unsigned char *s) // function for serial transmission of string { while(*s) { tx(*s++); } } unsigned char rx() // function for serial reception { while((U0LSR&(1<<0))==0); // waits for Receiver Data Ready Pin to be high return U0RBR; // read the value in Receiver Buffer Register }
2.71875
3
2024-11-18T21:09:56.073214+00:00
2018-09-06T04:19:31
f51dc2caed635d0c57d0190f2dfafe46cce18813
{ "blob_id": "f51dc2caed635d0c57d0190f2dfafe46cce18813", "branch_name": "refs/heads/master", "committer_date": "2018-09-06T04:19:31", "content_id": "20e106711c69f23549a14cd087e959fcfda8516f", "detected_licenses": [ "MIT" ], "directory_id": "134fca5b62ca6bac59ba1af5a5ebd271d9b53281", "extension": "c", "filename": "tainted.c", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 147616821, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 496, "license": "MIT", "license_type": "permissive", "path": "/build/stx/support/tools/splint-3.1.2/test/tainted/tainted.c", "provenance": "stackv2-0065.json.gz:21246", "repo_name": "GunterMueller/ST_STX_Fork", "revision_date": "2018-09-06T04:19:31", "revision_id": "d891b139f3c016b81feeb5bf749e60585575bff7", "snapshot_id": "3ba5fb5482d9827f32526e3c32a8791c7434bb6b", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/GunterMueller/ST_STX_Fork/d891b139f3c016b81feeb5bf749e60585575bff7/build/stx/support/tools/splint-3.1.2/test/tainted/tainted.c", "visit_date": "2020-03-28T03:03:46.770962" }
stackv2
extern char *mtainted (char *s); /*@untainted@*/ char *f (/*@tainted@*/ char *s, /*@untainted@*/ char *us) { char *x = f (us, s); /* Error: tainted as untainted */ return f (x, us); } void test (/*@tainted@*/ char *s) { char *t = malloc (sizeof (char) * strlen (s)); (void) system (s); /* error */ assert (t != NULL); strcpy (t, s); /* t is tainted too */ (void) system (t); /* error */ t = mtainted (s); /* default return is tainted! */ (void) system (t); /* error */ }
2.71875
3
2024-11-18T21:09:56.309014+00:00
2017-05-25T20:27:15
2e33a4949e974314bd82535ecb23967adad1ca13
{ "blob_id": "2e33a4949e974314bd82535ecb23967adad1ca13", "branch_name": "refs/heads/master", "committer_date": "2017-05-25T20:27:15", "content_id": "4e83359738c3daa1fafd6f49f29665ee0f1bfaab", "detected_licenses": [ "MIT" ], "directory_id": "097181ead1c6748715dc7ef0b46627601e9e3405", "extension": "c", "filename": "Label.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 86904357, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2465, "license": "MIT", "license_type": "permissive", "path": "/src/Label.c", "provenance": "stackv2-0065.json.gz:21504", "repo_name": "arseniy899/sokoban_pub", "revision_date": "2017-05-25T20:27:15", "revision_id": "001363682290300708490e02cb319ff09f3bfa43", "snapshot_id": "fec1fc5f4e5a89690d8e411505bf68fafbd5e8d9", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/arseniy899/sokoban_pub/001363682290300708490e02cb319ff09f3bfa43/src/Label.c", "visit_date": "2021-01-18T19:36:59.364714" }
stackv2
#include "LibraryMerger.h" ArrayElement *labelsArr = NULL; Label *getStructLabel(int i) { Label *curLab = malloc(sizeof(Label)); Label *newLab = (Label *)get(labelsArr, i); if (newLab) { memcpy(curLab, newLab, sizeof(Label)); if (curLab) free(curLab); return newLab; } else { if (curLab) free(curLab); return NULL; } } void renderLabelsSc() { for (int i = 0; i < arraySize(labelsArr); i++) { Label *curLab = getStructLabel(i); if (curLab->scene == SCENE_NOW || curLab->scene == -1) { ALLEGRO_COLOR color = al_map_rgb(curLab->r, curLab->g, curLab->b); al_draw_textf(font, color, curLab->posX, curLab->posY, curLab->align, "%s", curLab->text); } } return; } int addLabel(float x, float y, int red, int green, int blue, int scene, int align,const char *text, ...) { char buf[DEFAULT_LENGTH_STR]; va_list vl; va_start(vl, text); vsnprintf(buf, sizeof(buf), text, vl); va_end(vl); Label newLabel; newLabel.text = malloc(sizeof(buf)); sprintf(newLabel.text, "%s", buf); newLabel.id = arraySize(labelsArr); newLabel.posX = x; newLabel.posY = y; newLabel.scene = scene; newLabel.align = align; newLabel.r = red; newLabel.g = green; newLabel.b = blue; return add(&labelsArr, (byte *)&newLabel, sizeof(newLabel)); } int changeText(int labelId, const char *text, ...) { if (labelId < arraySize(labelsArr)) { char buf[DEFAULT_LENGTH_STR]; va_list vl; va_start(vl, text); vsnprintf(buf, sizeof(buf), text, vl); va_end(vl); Label *curLabel = getStructLabel(labelId); curLabel->text = malloc(sizeof(buf)); memcpy(curLabel->text, buf, sizeof(buf)); set(labelsArr, labelId, (byte *)curLabel, sizeof(curLabel)); renderScreen(); return 0; } else return -1; } void recalcLabels(float hC, float vC) { for (int i = 0; i < arraySize(labelsArr); i++) { Label *curLab = getStructLabel(i); curLab->posX *= hC; curLab->posY *= vC; set(labelsArr, i, (byte *)curLab, sizeof(curLab)); } renderLabelsSc(); } void clearLabels(int scene) { ArrayElement *cur = labelsArr; while (cur) { Label * curButt = (Label *)cur->container; ArrayElement *next = cur->linkToNext; if (curButt->scene == scene) removeElOb(&labelsArr, cur); if (!next) break; cur = next; } }
2.5625
3
2024-11-18T21:09:56.407220+00:00
2013-08-21T21:31:53
e5a7314ec990200ffbaa9712ef0a2bc7c9233291
{ "blob_id": "e5a7314ec990200ffbaa9712ef0a2bc7c9233291", "branch_name": "refs/heads/master", "committer_date": "2013-08-21T21:31:53", "content_id": "61a3a42e4538c8e3eec6f2bf7a8080e1f00c5f04", "detected_licenses": [ "MIT" ], "directory_id": "8f6f674f61a4046a834c1b5d3cfd1548864fcd44", "extension": "c", "filename": "expr.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": 7392, "license": "MIT", "license_type": "permissive", "path": "/plugins/deform/expr/expr.c", "provenance": "stackv2-0065.json.gz:21633", "repo_name": "ruofeidu/rgba", "revision_date": "2013-08-21T21:31:53", "revision_id": "f68320a03ea3d6c03184906f1033b5ea81b1f9d6", "snapshot_id": "a7892503cd42dfa4da1a6bc06b0bb0617658d5ca", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ruofeidu/rgba/f68320a03ea3d6c03184906f1033b5ea81b1f9d6/plugins/deform/expr/expr.c", "visit_date": "2021-01-18T01:51:59.096238" }
stackv2
#include <stdio.h> #include <malloc.h> #include <assert.h> #include <string.h> #include <math.h> #include "expr.h" #include "calc.h" //#define EXPR_VERBOSE // // Fast "variable list" hack ;) // #define MAX_VARIABLES 16 static TVariable var[MAX_VARIABLES]; void VL_Init (void) { int i; for (i=0; i<MAX_VARIABLES; i++) { var[i].id = NULL; var[i].value = 0.0; } } void VL_AddVar (char *id) { int i; //printf ("VL_AddVar: %s\n", id); for (i=0; i<MAX_VARIABLES; i++) { // Si ya existe la variables, no hacemos nada if (var[i].id && (!strcmp (id, var[i].id))) return; } i = 0; while (var[i].id) i ++; assert (i != MAX_VARIABLES); var[i].id = strdup (id); var[i].value = 0.0; } void VL_Set (char *id, double value) { int i; for (i=0; i<MAX_VARIABLES; i++) { if (var[i].id && (!strcmp (id, var[i].id))) { var[i].value = value; return; } } printf ("VL_Set:: Variable %s not used!\n", id); exit (1); } static float frand (void) { return (rand ( ) & 0xFF) / 255.0f; } double VL_Get (char *id) { int i; if (!strcmp (id, "rnd")) return frand ( ); for (i=0; i<MAX_VARIABLES; i++) { if (var[i].id && (!strcmp (id, var[i].id))) return var[i].value; } printf ("VL_Set:: Variable %s not used!\n", id); exit (1); return 0.0; } // -------------------- EXPRESSION EVALUATOR CODE -------------------- TExpr *EXPR_Number (double value) { TExpr *expr = (TExpr *) malloc (sizeof (TExpr)); assert (expr != NULL); memset (expr, 0, sizeof (TExpr)); expr->op = OP_CONSTANT; expr->value = value; #ifdef EXPR_VERBOSE printf ("EXPR_Number: %f\n", value); #endif return expr; } TExpr *EXPR_Identifier (char *lexem_id) { TExpr *expr = (TExpr *) malloc (sizeof (TExpr)); assert (expr != NULL); memset (expr, 0, sizeof (TExpr)); VL_AddVar (lexem_id); expr->op = OP_IDENTIFIER; expr->id = strdup (lexem_id); #ifdef EXPR_VERBOSE printf ("EXPR_Id: %s\n", lexem_id); #endif return expr; } TExpr *EXPR_BinaryOp (TOperator op, TExpr *expr1, TExpr *expr2) { TExpr *expr = (TExpr *) malloc (sizeof (TExpr)); assert (expr != NULL); memset (expr, 0, sizeof (TExpr)); expr->op = op; expr->left = expr1; expr->right = expr2; #ifdef EXPR_VERBOSE { char *opstr[5] = { "Add", "Sub", "Mul", "Div", "Pow" }; printf ("EXPR_Op2: %i (%s)\n", op, opstr[op-3]); } #endif return expr; } TExpr *EXPR_UnaryOp (TOperator op, TExpr *expr1) { TExpr *expr = (TExpr *) malloc (sizeof (TExpr)); assert (expr != NULL); memset (expr, 0, sizeof (TExpr)); expr->op = op; expr->left = expr1; #ifdef EXPR_VERBOSE printf ("EXPR_Op1: %i\n", op); #endif return expr; } TExpr *EXPR_Function (TFunction *f, TExpr *expr1) { TExpr *expr = (TExpr *) malloc (sizeof (TExpr)); assert (expr != NULL); memset (expr, 0, sizeof (TExpr)); expr->op = OP_FUNCTION; expr->func = f; expr->left = expr1; return expr; } TExpr *EXPR_Function2 (TFunction2 *f, TExpr *expr1, TExpr *expr2) { TExpr *expr = (TExpr *) malloc (sizeof (TExpr)); assert (expr != NULL); memset (expr, 0, sizeof (TExpr)); expr->op = OP_FUNCTION2; expr->func2 = f; expr->left = expr1; expr->right = expr2; return expr; } TExpr *EXPR_Function3 (TFunction3 *f, TExpr *expr1, TExpr *expr2, TExpr *expr3) { TExpr *expr = (TExpr *) malloc (sizeof (TExpr)); assert (expr != NULL); memset (expr, 0, sizeof (TExpr)); expr->op = OP_FUNCTION3; expr->func3 = f; expr->left = expr1; expr->right = expr2; expr->right2 = expr3; return expr; } TExpr *EXPR_Function4 (TFunction4 *f, TExpr *expr1, TExpr *expr2, TExpr *expr3, TExpr *expr4) { TExpr *expr = (TExpr *) malloc (sizeof (TExpr)); assert (expr != NULL); memset (expr, 0, sizeof (TExpr)); expr->op = OP_FUNCTION4; expr->func4 = f; expr->left = expr1; expr->right = expr2; expr->right2 = expr3; expr->right3 = expr4; return expr; } TExpr *EXPR_Function5 (TFunction5 *f, TExpr *expr1, TExpr *expr2, TExpr *expr3, TExpr *expr4, TExpr *expr5) { TExpr *expr = (TExpr *) malloc (sizeof (TExpr)); assert (expr != NULL); memset (expr, 0, sizeof (TExpr)); expr->op = OP_FUNCTION5; expr->func5 = f; expr->left = expr1; expr->right = expr2; expr->right2 = expr3; expr->right3 = expr4; expr->right4 = expr5; return expr; } void EXPR_Delete (TExpr *expr) { if (expr->left) EXPR_Delete (expr->left); if (expr->right) EXPR_Delete (expr->right); if (expr->id) free (expr->id); free (expr); } double EXPR_Eval (TExpr *expr) { switch (expr->op) { case OP_CONSTANT: return expr->value; case OP_IDENTIFIER: return VL_Get (expr->id); case OP_ADD: return (EXPR_Eval (expr->left) + EXPR_Eval (expr->right)); case OP_SUB: return (EXPR_Eval (expr->left) - EXPR_Eval (expr->right)); case OP_MUL: return (EXPR_Eval (expr->left) * EXPR_Eval (expr->right)); case OP_DIV: return (EXPR_Eval (expr->left) / EXPR_Eval (expr->right)); case OP_NEG: return (- EXPR_Eval (expr->left)); case OP_FUNCTION: return expr->func (EXPR_Eval (expr->left)); case OP_FUNCTION2: return expr->func2 (EXPR_Eval (expr->left), EXPR_Eval (expr->right)); case OP_FUNCTION3: return expr->func3 (EXPR_Eval (expr->left), EXPR_Eval (expr->right), EXPR_Eval (expr->right2)); case OP_FUNCTION4: return expr->func4 (EXPR_Eval (expr->left), EXPR_Eval (expr->right), EXPR_Eval (expr->right2), EXPR_Eval (expr->right3)); case OP_FUNCTION5: return expr->func5 (EXPR_Eval (expr->left), EXPR_Eval (expr->right), EXPR_Eval (expr->right2), EXPR_Eval (expr->right3), EXPR_Eval (expr->right4)); default: printf ("EXPR_Eval fail!!\n"); exit (1); break; } return 0.0; } #include "parser.h" extern FILE *yyin; typedef struct { char *data; int index; int size; } TString; TString *string_new (char *text) { TString *s = (TString *) malloc (sizeof (TString)); assert (s != NULL); s->data = strdup (text); s->size = strlen (text) + 1; s->data[s->size-1] = EOF; s->index = 0; return s; } int myferror (void *string) { TString *s = (TString *) string; return 0; } int mygetc (void *string) { TString *s = (TString *) string; int ch; if (s->index >= s->size) return EOF; ch = s->data[s->index]; s->index ++; return ch; } int myfread (char *buffer, int count, int size, void *string) { int maxbytes = count * size; int bytes = 0; TString *s = (TString *) string; while ((bytes < maxbytes) && (s->index < s->size)) { *(buffer ++) = s->data[s->index ++]; bytes ++; } return bytes; } TExpr *EXPR_New (char *expression) { TString *str; str = string_new (expression); yyin = (FILE *) str; yyrestart (yyin); if (yyparse ( )) { printf ("EXPR_New(\"%s\"):: parse error!\n", expression); exit (1); } return parser_expression; }
2.671875
3
2024-11-18T21:09:57.103905+00:00
2016-09-24T18:05:17
243a57e29f89f8910e88f509f10eaf9f50e39a45
{ "blob_id": "243a57e29f89f8910e88f509f10eaf9f50e39a45", "branch_name": "refs/heads/master", "committer_date": "2016-09-24T18:05:17", "content_id": "cd22ea42026aeb9fe6771041928f802c74b42097", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "541e48900e5fbc0a121e5a43c5e9a06ff89de2d1", "extension": "c", "filename": "xerbla_array.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 13536584, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2815, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/blas/xerbla_array.c", "provenance": "stackv2-0065.json.gz:22019", "repo_name": "juanjosegarciaripoll/cblapack", "revision_date": "2016-09-24T18:05:17", "revision_id": "7b3d7280c8d5f39d8f7f84c3c24067f163e03974", "snapshot_id": "7408a8aa901bfff8e819cbffd5c862eb006c33ac", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/juanjosegarciaripoll/cblapack/7b3d7280c8d5f39d8f7f84c3c24067f163e03974/src/blas/xerbla_array.c", "visit_date": "2021-05-25T11:56:43.415033" }
stackv2
/* xerbla_array.f -- translated by f2c (version 20061008). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib; on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */ #include "f2c.h" #include "blaswrap.h" /* Subroutine */ int xerbla_array__(const char *srname_array__, integer * srname_len__, integer *info, ftnlen srname_array_len) { /* System generated locals */ integer i__1, i__2, i__3; /* Local variables */ integer i__; char srname[32]; /* -- LAPACK auxiliary routine (version 3.0) -- */ /* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ /* September 19, 2006 */ /* Purpose */ /* ======= */ /* XERBLA_ARRAY assists other languages in calling XERBLA, the LAPACK */ /* and BLAS error handler. Rather than taking a Fortran string argument */ /* as the function's name, XERBLA_ARRAY takes an array of single */ /* characters along with the array's length. XERBLA_ARRAY then copies */ /* up to 32 characters of that array into a Fortran string and passes */ /* that to XERBLA. If called with a non-positive SRNAME_LEN, */ /* XERBLA_ARRAY will call XERBLA with a string of all blank characters. */ /* Say some macro or other device makes XERBLA_ARRAY available to C99 */ /* by a name lapack_xerbla and with a common Fortran calling convention. */ /* Then a C99 program could invoke XERBLA via: */ /* { */ /* int flen = strlen(__func__); */ /* lapack_xerbla(__func__, &flen, &info); */ /* } */ /* Providing XERBLA_ARRAY is not necessary for intercepting LAPACK */ /* errors. XERBLA_ARRAY calls XERBLA. */ /* Arguments */ /* ========= */ /* SRNAME_ARRAY (input) CHARACTER(1) array, dimension (SRNAME_LEN) */ /* The name of the routine which called XERBLA_ARRAY. */ /* SRNAME_LEN (input) INTEGER */ /* The length of the name in SRNAME_ARRAY. */ /* INFO (input) INTEGER */ /* The position of the invalid parameter in the parameter list */ /* of the calling routine. */ /* ===================================================================== */ /* Parameter adjustments */ --srname_array__; /* Function Body */ s_copy(srname, "", (ftnlen)32, (ftnlen)0); /* Computing MIN */ i__2 = *srname_len__, i__3 = i_len(srname, (ftnlen)32); i__1 = min(i__2,i__3); for (i__ = 1; i__ <= i__1; ++i__) { *(unsigned char *)&srname[i__ - 1] = *(unsigned const char *)& srname_array__[i__]; } xerbla_(srname, info); return 0; } /* xerbla_array__ */
2.15625
2
2024-11-18T21:09:57.200513+00:00
2023-06-23T10:11:23
a86029555489f89e288351c3303aab776a52a0c8
{ "blob_id": "a86029555489f89e288351c3303aab776a52a0c8", "branch_name": "refs/heads/main", "committer_date": "2023-06-23T10:11:23", "content_id": "ad83d227a9f89c726dbfb85512e2bfb0a20fc94a", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "803898f95f34521f4fc08ff42534888367ff4028", "extension": "c", "filename": "pdsbyt9.c", "fork_events_count": 29, "gha_created_at": "2012-06-19T15:15:17", "gha_event_created_at": "2023-06-23T10:11:24", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 4715296, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3334, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/gempak/source/programs/gd/gdgrib/pdsbyt9.c", "provenance": "stackv2-0065.json.gz:22148", "repo_name": "Unidata/gempak", "revision_date": "2023-06-23T10:11:23", "revision_id": "f3997c88469be1c08cd265ef553c812a28778284", "snapshot_id": "17057d45ad92512f56193155dd0d6ad0301965d8", "src_encoding": "UTF-8", "star_events_count": 53, "url": "https://raw.githubusercontent.com/Unidata/gempak/f3997c88469be1c08cd265ef553c812a28778284/gempak/source/programs/gd/gdgrib/pdsbyt9.c", "visit_date": "2023-07-13T19:39:57.114715" }
stackv2
#include "gdgrib.h" void pds_byt9 ( const char *parm, const char *wmotb, const char *nceptb, unsigned char *byte9, int *ibyt9, int *idt, int *iret ) /************************************************************************ * pds_byt9 * * * * This subroutine uses the GEMPAK GRIB parameter lookup tables to * * determine the value of PDS octet 9. * * * * pds_byt9 ( parm, wmotb, nceptb, byte9, ibyt9, idt, iret ) * * * * Input parameters: * * *parm const char GEMPAK parameter name string * * *wmotb const char WMO GRIB parm LUT file name * * *nceptb const char NCEP GRIB parm LUT file name * * * * Output parameters: * * *byte9 unsigned char Byte with GRIB parm # stored * * *ibyt9 int Integer value of byte 9 * * *idt int Value of any imbedded integer * * *iret int Return code * * 0 = normal return * * -83 = parm not found * * -84 = parm # not valid in GRIB * * -94 = parm name is too long * ** * * Log: * * K. Brill/HPC 8/99 * * K. Brill/HPC 3/00 Avoid character assignment to itself * * R. Tian/SAIC 10/06 Recoded from Fortran * ************************************************************************/ { char filnam[2][LLMXLN], record[LLMXLN], prmnam[17], chkprm[17], cinprm[17], cnum[17], cdum; int found; int ifile, iprm, nnums, kchr, ityp, ic, ier; FILE *fp; /*----------------------------------------------------------------------*/ *iret = 0; *idt = -9999; *byte9 = (unsigned char)( 255 ); *ibyt9 = 255; if ( strlen(parm) > 16 ) { *iret = -94; return; } cst_lcuc ( (char *)parm, cinprm, &ier ); strcpy ( filnam[0], wmotb ); strcpy ( filnam[1], nceptb ); found = G_FALSE; ifile = 0; while ( ifile < 2 && found == G_FALSE ) { fp = cfl_tbop ( filnam[ifile++], "grid", &ier ); if ( ier != 0 ) continue; while ( !feof(fp) && found == G_FALSE ) { cfl_trln ( fp, sizeof(record), record, &ier ); if ( ier != 0 ) continue; sscanf ( record, "%d", &iprm ); sscanf ( &record[59], "%s", prmnam ); memset ( cnum, 0, sizeof(cnum) ); strcpy ( chkprm, cinprm ); if ( strcmp ( prmnam, chkprm ) == 0 ) { found = G_TRUE; *ibyt9 = iprm; } else if ( strstr ( chkprm, prmnam ) == chkprm ) { strcpy ( cnum, &chkprm[strlen(prmnam)] ); cst_numb ( cnum, idt, &ier ); if ( ier == 0 ) { found = G_TRUE; *ibyt9 = iprm; } } else { if ( strchr ( prmnam, '-' ) ) { nnums = 0; kchr = 0; for ( ic = 0; ic < (int)strlen(chkprm); ic++ ) { cst_alnm ( chkprm[ic], &ityp, &ier ); if ( ityp == 2 ) { cnum[nnums++] = chkprm[ic]; if ( nnums < 3 ) { chkprm[kchr++] = '-'; } } else { cdum = chkprm[ic]; chkprm[kchr++] = cdum; } } if ( nnums > 0 ) { if ( strncmp ( chkprm, prmnam, strlen(prmnam) ) == 0 ) { found = G_TRUE; cst_numb ( cnum, idt, &ier ); *ibyt9 = iprm; } } } } } cfl_clos ( fp, &ier ); } if ( found == G_FALSE ) { *iret = -83; } else if ( *ibyt9 < 255 && *ibyt9 > 0 ) { *byte9 = (unsigned char)( *ibyt9 ); } else { *iret = -84; } return; }
2.140625
2
2024-11-18T21:09:57.356598+00:00
2018-12-19T11:30:26
f579a678f815494515970ed9e8331df64718a393
{ "blob_id": "f579a678f815494515970ed9e8331df64718a393", "branch_name": "refs/heads/master", "committer_date": "2018-12-19T11:30:26", "content_id": "c7820f35df62a2da2884e0006eacd41f249fbde1", "detected_licenses": [ "MIT" ], "directory_id": "9579b637d13f63c09a24b69ae3761bd3a77fdbc2", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1001, "license": "MIT", "license_type": "permissive", "path": "/memory/main.c", "provenance": "stackv2-0065.json.gz:22404", "repo_name": "daisuke-t-jp/memory-heap", "revision_date": "2018-12-19T11:30:26", "revision_id": "84e4eba644f4f27cf24dcd4ca3f15295272f79b4", "snapshot_id": "cac66096907a916ae074590eb55ca64210892269", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/daisuke-t-jp/memory-heap/84e4eba644f4f27cf24dcd4ca3f15295272f79b4/memory/main.c", "visit_date": "2020-04-11T13:06:57.200929" }
stackv2
/** * main.c * * Copyright (C) 2018 daisuke-t. * * memory heap management code on C language. */ #include <stdio.h> #include "memory.h" int main(int argc, const char * argv[]) { void *p, *p2, *p3; // heap size. uint32_t heap_size_array[MEMORY_HEAP_MAX] = { 1024 * 1024 * 1, // 1MB 1024 * 1024 * 3, // 3MB }; // memory system init. if(!MemoryInit(heap_size_array)) { printf("init error.\n"); return -1; } // alloc test (size over error) p = MemoryAlloc(0, 1024 * 1024 * 2); if(p != NULL) { printf("alloc test error(size over error)\n"); return -1; } // alloc test p = MemoryAlloc(1, 1024 * 1024 * 2); if(p == NULL) { printf("alloc test error\n"); return -1; } printf("heap1 free size %dB\n", MemoryGetFreeSize(1)); MemoryFree(p); // alloc test p = MemoryAlloc(0, 1024); p2 = MemoryAlloc(0, 1024); p3 = MemoryAlloc(0, 1024); MemoryFree(p2); MemoryFree(p3); MemoryFree(p); // memory system release. MemoryRelease(); return 0; }
2.90625
3
2024-11-18T21:09:57.563845+00:00
2018-11-21T18:02:04
741d3144755a6122ec10fa59ae7420333e610eb2
{ "blob_id": "741d3144755a6122ec10fa59ae7420333e610eb2", "branch_name": "refs/heads/master", "committer_date": "2018-11-21T18:02:04", "content_id": "d8f606bc725da088ae96a3b18e51e7372b43aa52", "detected_licenses": [ "MIT" ], "directory_id": "01204ed48a4b56d2b9396d4a55795b55ed6ad92c", "extension": "c", "filename": "can.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 158565736, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1758, "license": "MIT", "license_type": "permissive", "path": "/node1/node 1/can.c", "provenance": "stackv2-0065.json.gz:22532", "repo_name": "kidneb7/TTK4155", "revision_date": "2018-11-21T18:02:04", "revision_id": "7cb95ca51eae342b832179e9654c9f2f67ccdd77", "snapshot_id": "4111940aa425b02b1c780069880fa6c9d748b38d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kidneb7/TTK4155/7cb95ca51eae342b832179e9654c9f2f67ccdd77/node1/node 1/can.c", "visit_date": "2020-04-07T17:20:26.056026" }
stackv2
#include "can.h" uint8_t transmission_complete = 0; void can_init() { mcp2515_init(); mcp2515_write(MCP_CANINTE, 0b00000101); // Enable recieve buffer 0 interrupt mcp2515_bit_modify(MCP_TXB0CTRL, (MCP_TXREQ), 0x00); // Clear transmit request bit mcp2515_write(MCP_CANINTF, 0); // Resetting all interrupt flags transmission_complete = 1; mcp2515_write(MCP_CANCTRL, MODE_NORMAL); uint8_t value = mcp2515_read(MCP_CANSTAT); if((value & MODE_MASK) == MODE_NORMAL) { printf("IN NORMAL MODE\n\r"); } } void can_intr_init() { DDRD &= ~(1 << PD3); // Enable input GICR |= (1 << INT1); // PD3/INT1 } can_message can_msg_reset() { can_message new_msg; new_msg.id = 999; new_msg.length = 1; new_msg.data[0] = 0; return new_msg; } void can_message_send(can_message msg) { if (transmission_complete) { uint8_t id_l = (msg.id & (0b111)); id_l = (id_l << 0x05); mcp2515_write(MCP_TXB0SIDL, id_l); uint16_t id_h = (msg.id & (0b11111111000)); uint8_t id_h_2 = (id_h >> 0x03); mcp2515_write(MCP_TXB0SIDH, id_h_2); uint8_t dlc = 0x00; dlc |= msg.length; mcp2515_write(MCP_TXB0DLC, dlc); for (uint8_t i = 0; i < msg.length; i++) { mcp2515_write(MCP_TXB0D0 + i, msg.data[i]); } transmission_complete = 0; mcp2515_request_to_send(0); // initiates msg transmission, buffer 0 of 2 } } void can_set_transmit_complete() { transmission_complete = 1; } can_message can_data_receive() { can_message msg; msg.id = (mcp2515_read(MCP_RXB0SIDH) << 3); msg.id |= ((mcp2515_read(MCP_RXB0SIDL) & 0b11100000) >> 5); msg.length = (mcp2515_read(MCP_RXB0DLC) & 0b00001111); for (uint8_t i = 0; i < msg.length; i++) { msg.data[i] = mcp2515_read(MCP_RXB0D0 + i); } return msg; }
2.828125
3
2024-11-18T21:09:57.872350+00:00
2020-05-05T03:22:31
7b8412919c7b4d609e6ef4fb3806d70a4fb92670
{ "blob_id": "7b8412919c7b4d609e6ef4fb3806d70a4fb92670", "branch_name": "refs/heads/master", "committer_date": "2020-05-05T03:22:31", "content_id": "fdb452ca7b980fd9816a8de08baccd08ce15f2da", "detected_licenses": [ "BSD-4-Clause-UC" ], "directory_id": "d6d598622d9fd92521674982aea93f145399d511", "extension": "c", "filename": "e1000.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 208200168, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5833, "license": "BSD-4-Clause-UC", "license_type": "permissive", "path": "/lab6_Network_driver/kern/e1000.c", "provenance": "stackv2-0065.json.gz:22917", "repo_name": "JonnyKong/MIT-6.828-Operating-Systems", "revision_date": "2020-05-05T03:22:31", "revision_id": "b38966882e68f04b8b92be84e0650e12d6184bde", "snapshot_id": "4ab0e2d892fa8065dc390e24fa967e62261256da", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/JonnyKong/MIT-6.828-Operating-Systems/b38966882e68f04b8b92be84e0650e12d6184bde/lab6_Network_driver/kern/e1000.c", "visit_date": "2022-07-09T11:09:29.860310" }
stackv2
#include <inc/assert.h> #include <inc/string.h> #include <kern/e1000.h> #include <kern/pmap.h> // LAB 6: Your driver code here volatile void *e1000_bar_va; // tx #define TXDESC_CNT 32 #define TXPKT_SIZE 1518 struct e1000_tx_desc e1000_tx_desc_arr[TXDESC_CNT] __attribute__ ((aligned (16))); char e1000_tx_buf[TXDESC_CNT][TXPKT_SIZE]; // rx #define RXDESC_CNT 128 // #define RXPKT_SIZE 1518 struct e1000_rx_desc e1000_rx_desc_arr[RXDESC_CNT] __attribute__ ((aligned (16))); char e1000_rx_buf[RXDESC_CNT][RXPKT_SIZE]; // mmio doesn't always preserve incremental write semantics. When using C bitfields, first // write to a temporary variable incrementally, then write this variable to mmio static uint32_t mmio_buf; int e1000_attach(struct pci_func *pcif) { // enable device and negotiate resouce, update pcif pci_func_enable(pcif); // create x86 mmio memory mapping, make sure status reg is correct e1000_bar_va = mmio_map_region(pcif->reg_base[0], pcif->reg_size[0]); assert((*(int *)E1000MEM(E1000_STATUS_ADDR)) == 0x80080783); e1000_tx_init(); e1000_rx_init(); return 0; } static void e1000_tx_init() { for (int i = 0; i < TXDESC_CNT; ++i) { e1000_tx_desc_arr[i].addr = PADDR(e1000_tx_buf[i]); e1000_tx_desc_arr[i].status |= E1000_TXD_STATUS_DD; // e1000_tx_desc_arr[i].cmd |= E1000_TXD_CMD_RS; } // set transmit descriptor length to the size of the descriptor ring struct e1000_tdlen *tdlen = (struct e1000_tdlen *)E1000MEM(E1000_TDLEN_ADDR); tdlen->len = TXDESC_CNT / 8; // set transmit descriptor base address with address of the region uint32_t *tdbal = (uint32_t *)E1000MEM(E1000_TDBAL_ADDR); uint32_t *tdbah = (uint32_t *)E1000MEM(E1000_TDBAH_ADDR); *tdbal = PADDR(e1000_tx_desc_arr); *tdbah = 0; // used for 64-bits only // transmit descriptor head and tail are initialized to 0 struct e1000_tdh *tdh = (struct e1000_tdh *)E1000MEM(E1000_TDH_ADDR); tdh->tdh = 0; struct e1000_tdt *tdt = (struct e1000_tdt *)E1000MEM(E1000_TDT_ADDR); tdt->tdt = 0; // init transmit control register, see manual 14.5 struct e1000_tctl *tctl = (struct e1000_tctl *)E1000MEM(E1000_TCTL_ADDR); tctl->en = 1; tctl->psp = 1; tctl->ct = 0x10; tctl->cold = 0x40; // init transmit IPG register, see manual 14.5 struct e1000_tipg *tipg = (struct e1000_tipg *)E1000MEM(E1000_TIPG_ADDR); tipg->ipgt = 10; tipg->ipgr1 = 4; tipg->ipgr2 = 6; } static void e1000_rx_init() { // set receive address register with hardcoded qemu MAC address uint8_t qemu_macaddr[6] = {0x52, 0x54, 0x00, 0x12, 0x34, 0x56}; uint32_t *ral = (uint32_t *)E1000MEM(E1000_RAL_ADDR); uint32_t *rah = (uint32_t *)E1000MEM(E1000_RAH_ADDR); set_macaddr(ral, rah, qemu_macaddr); // set interrupt mask set/read to enable interrupt uint32_t *ims = (uint32_t *)E1000MEM(E1000_IMS_ADDR); *ims = 0; // set the receiver descriptor list for (int i = 0; i < RXDESC_CNT; ++i) { e1000_rx_desc_arr[i].addr = PADDR(e1000_rx_buf[i]); } uint32_t *rdbal = (uint32_t *)E1000MEM(E1000_RDBAL_ADDR); uint32_t *rdbah = (uint32_t *)E1000MEM(E1000_RDBAH_ADDR); *rdbal = PADDR(e1000_rx_desc_arr); *rdbah = 0; // set the receive descriptor length struct e1000_rdlen *rdlen = (struct e1000_rdlen *)E1000MEM(E1000_RDLEN_ADDR); rdlen->len = RXDESC_CNT / 8; // set the receive descriptor head and tail struct e1000_rdh *rdh = (struct e1000_rdh *)E1000MEM(E1000_RDH_ADDR); struct e1000_rdt *rdt = (struct e1000_rdt *)E1000MEM(E1000_RDT_ADDR); rdh->rdh = 0; rdt->rdt = RXDESC_CNT - 1; // set the receive control register struct e1000_rctl *rctl = (struct e1000_rctl *)(&mmio_buf); rctl->en = 1; rctl->bam = 1; rctl->secrc = 1; *(uint32_t *)E1000MEM(E1000_RCTL_ADDR) = mmio_buf; } int e1000_tx(void *data, size_t len) { struct e1000_tdt *tdt = (struct e1000_tdt *)E1000MEM(E1000_TDT_ADDR); uint32_t tail = tdt->tdt; // if next descriptor not free (buffer is full), let caller retry if (!(e1000_tx_desc_arr[tail].status & E1000_TXD_STATUS_DD)) return -E1000_TX_RETRY; memcpy(e1000_tx_buf[tail], data, len); e1000_tx_desc_arr[tail].length = len; e1000_tx_desc_arr[tail].status &= ~E1000_TXD_STATUS_DD; e1000_tx_desc_arr[tail].cmd |= (E1000_TXD_CMD_EOP | E1000_TXD_CMD_RS); tdt->tdt = (tail + 1) % TXDESC_CNT; return 0; } int e1000_rx(void *data, size_t *len) { struct e1000_rdt *rdt = (struct e1000_rdt *)E1000MEM(E1000_RDT_ADDR); // uint32_t tail = rdt->rdt; uint32_t next = (rdt->rdt + 1) % RXDESC_CNT; // if next descriptor free (buffer empty), let caller retry if (!(e1000_rx_desc_arr[next].status & E1000_RXD_STATUS_DD)) { return -E1000_RX_RETRY; } else if (e1000_rx_desc_arr[next].errors) { cprintf("e1000_rx() error\n"); return -E1000_RX_RETRY; } cprintf("e1000_rx(): received content\n"); *len = e1000_rx_desc_arr[next].length; memcpy(data, e1000_rx_buf[next], *len); // rdt->rdt = (tail + 1) % RXDESC_CNT; rdt->rdt = next; return 0; } // write MAC address to ral and rah static void set_macaddr(uint32_t *ral, uint32_t *rah, uint8_t *mac) { // the following is incorrect: can't do incremental write in x86 mmio // for (int i = 0; i < 4; ++i) // ((uint8_t *)ral)[i] = mac[i]; // for (int i = 0; i < 2; ++i) // ((uint8_t *)rah)[i] = mac[i + 4]; uint32_t ral_val = 0, rah_val = 0; for (int i = 0; i < 4; ++i) ral_val |= (uint32_t)(mac[i]) << (i * 8); for (int i = 0; i < 2; ++i) rah_val |= (uint32_t)(mac[i + 4]) << (i * 8); *ral = ral_val; *rah = rah_val | E1000_RAH_AV; }
2.203125
2
2024-11-18T21:09:58.369528+00:00
2018-06-22T15:57:27
9cdeb543d38496e55c9255f2ad0d5783f17f76cb
{ "blob_id": "9cdeb543d38496e55c9255f2ad0d5783f17f76cb", "branch_name": "refs/heads/master", "committer_date": "2018-06-22T15:57:27", "content_id": "898c1ff40a687edc312ef498c1ad5b384eb22b15", "detected_licenses": [ "MIT" ], "directory_id": "c128a36abecf8e540bc7e66ae5b282129ed7ac7c", "extension": "c", "filename": "24Abril.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": 1685, "license": "MIT", "license_type": "permissive", "path": "/FunSoftApuntes/24Abril.c", "provenance": "stackv2-0065.json.gz:23302", "repo_name": "Alfredleo7/Ejercicios-Introduccion-C", "revision_date": "2018-06-22T15:57:27", "revision_id": "2b566708bb51d680432e205b2d5520281ce3bc1d", "snapshot_id": "49b6906374c8e272422c6424e107f115af7b3d22", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Alfredleo7/Ejercicios-Introduccion-C/2b566708bb51d680432e205b2d5520281ce3bc1d/FunSoftApuntes/24Abril.c", "visit_date": "2020-03-22T01:23:18.543549" }
stackv2
#include <string.h> #include <sys/wait.h> #define SIZE 512 int main(){ // 1.Definimos las pipes int a[2]; // Pipe padre -> hijo int b[2]; // Pipe hijo -> padre // 2.Creamos las pipes if(pipe(a) < 0){ perror("Close"); exit(-1); } if(pipe(b) < 0){ perror("Close"); exit(-1); } // 3.Clonamos pid_t pid = fork(); if(pid == 0){ // Codigo del hijo // Cerramos las pipes que no usamos if(close(a[1]) < 0){ perror("Close"); exit(-1); } if(close(b[0]) < 0){ perror("Close"); exit(-1); } // Leer dos cadenas del padre // Concatenamos las cadenas // Se la enviamos al padre // Cerramos las pipes // Salimos con exit para notificar al padre } else if(pid > 0){ // Codigo del padre // Cerramos las pipes que no usamos if(close(b[1]) < 0){ perror("Close"); return -1; } if(close(a[0]) < 0){ perror("Close"); return -1; } // Leemos de teclado char w1[SIZE]; char w2[SIZE]; printf("Cadena 1:\n"); int leidos = read(0, w1, SIZE); w1[leidos-1] = '\0'; printf("Cadena 2:\n"); int leidos = read(0, w1, SIZE); w2[leidos-1] = '\0'; // Envio protegido de w1 y w2 int longitud; longitud = strlen(w1); if((write_n(a[1], &l, sizeof(longitud))) != sizeof(longitud)){ perror("write"); exit(-1); } if((write_n(a[1], w1, longitud)) != longitud){ perror("write"); exit(-1); } // Cerrar la pipe de escritura a[1] if(close(a[1])){ perror("close"); exit(-1); } // Leer la cadena de nuestro hijo por b[0] y la imprimimos // Cerramos la pipe de lectura b[0] // Hacemos wait() } else { perror("fork"); return -1; } }
3.1875
3
2024-11-18T21:09:58.646154+00:00
2023-04-24T09:43:23
8b73e26860b2e42ee8ff1a858e4c54b800fe8074
{ "blob_id": "8b73e26860b2e42ee8ff1a858e4c54b800fe8074", "branch_name": "refs/heads/master", "committer_date": "2023-04-24T09:43:23", "content_id": "90b2dcea3a11d573d9b6bf11ddeeb74f5cb8ba5e", "detected_licenses": [ "MIT" ], "directory_id": "41f3926cd680231f740c3af9d31d9c9c581483fe", "extension": "h", "filename": "global.h", "fork_events_count": 46, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 127528770, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5503, "license": "MIT", "license_type": "permissive", "path": "/User/global.h", "provenance": "stackv2-0065.json.gz:23430", "repo_name": "ShareCat/STM32CommandLine", "revision_date": "2023-04-24T09:43:23", "revision_id": "1eb0f008400ecae14c074fecb7bfbd14beff648f", "snapshot_id": "2eed6c3d789e7cf51d3a24ee83a3ea61e4aaf142", "src_encoding": "GB18030", "star_events_count": 175, "url": "https://raw.githubusercontent.com/ShareCat/STM32CommandLine/1eb0f008400ecae14c074fecb7bfbd14beff648f/User/global.h", "visit_date": "2023-04-30T18:46:40.416278" }
stackv2
/** ****************************************************************************** * @file: * @author: Cat * @version: V1.0 * @date: 2018-1-23 * @brief: * @attention: ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __GLOBAL_H #define __GLOBAL_H #include <stdio.h> #include <stdint.h> #include <string.h> #include <ctype.h> #include <time.h> #include "project_conf.h" /* 工程配置文件,编译前要查看,确定 */ /* Macro ---------------------------------------------------------------------*/ //#define STM32F0 /* 选择是STM32F0,如果是STM32F1就需要注释掉 */ /* Includes ------------------------------------------------------------------*/ #ifdef STM32F0 #include "stm32f0xx.h" /* 包含STM32F0的头文件 */ //#define STM32F0_CPU_72M /* STM32F0默认最高48M主频,可以倍频到72M */ #else #include "stm32f10x.h" /* 包含STM32F1的头文件,默认是 STM32F1 */ #endif /* stm32直接操作寄存器的方法控制IO */ #define IO_HIGH(p,i) {p->BSRR=i;} /* 输出为高电平 */ #define IO_LOW(p,i) {p->BRR=i;} /* 输出低电平 */ #define IO_TOGGLE(p,i) {p->ODR ^=i;} /* 输出反转状态 */ /* Exported types ------------------------------------------------------------*/ #if 0 typedef union { unsigned char byte; struct { unsigned char bit0:1; unsigned char bit1:1; unsigned char bit2:1; unsigned char bit3:1; unsigned char bit4:1; unsigned char bit5:1; unsigned char bit6:1; unsigned char bit7:1; }bits; }BYTE; #endif /* Exported constants --------------------------------------------------------*/ //位或置1 如:a |= SETBIT0 enum { SETBIT0 = 0x0001, SETBIT1 = 0x0002, SETBIT2 = 0x0004, SETBIT3 = 0x0008, SETBIT4 = 0x0010, SETBIT5 = 0x0020, SETBIT6 = 0x0040, SETBIT7 = 0x0080, SETBIT8 = 0x0100, SETBIT9 = 0x0200, SETBIT10 = 0x0400, SETBIT11 = 0x0800, SETBIT12 = 0x1000, SETBIT13 = 0x2000, SETBIT14 = 0x4000, SETBIT15 = 0x8000 }; //位与清0 如:a &= CLRBIT0 enum { CLRBIT0 = 0xFFFE, CLRBIT1 = 0xFFFD, CLRBIT2 = 0xFFFB, CLRBIT3 = 0xFFF7, CLRBIT4 = 0xFFEF, CLRBIT5 = 0xFFDF, CLRBIT6 = 0xFFBF, CLRBIT7 = 0xFF7F, CLRBIT8 = 0xFEFF, CLRBIT9 = 0xFDFF, CLRBIT10 = 0xFBFF, CLRBIT11 = 0xF7FF, CLRBIT12 = 0xEFFF, CLRBIT13 = 0xDFFF, CLRBIT14 = 0xBFFF, CLRBIT15 = 0x7FFF }; //位与选择 如: a = b&CHSBIT0 enum { CHSBIT0 = 0x0001, CHSBIT1 = 0x0002, CHSBIT2 = 0x0004, CHSBIT3 = 0x0008, CHSBIT4 = 0x0010, CHSBIT5 = 0x0020, CHSBIT6 = 0x0040, CHSBIT7 = 0x0080, CHSBIT8 = 0x0100, CHSBIT9 = 0x0200, CHSBIT10 = 0x0400, CHSBIT11 = 0x0800, CHSBIT12 = 0x1000, CHSBIT13 = 0x2000, CHSBIT14 = 0x4000, CHSBIT15 = 0x8000 }; //分时执行状态 enum { STEP0 = 0, STEP1 = 1, STEP2 = 2, STEP3 = 3, STEP4 = 4, STEP5 = 5, STEP6 = 6, STEP7 = 7, STEP8 = 8, STEP9 = 9, STEP10 = 10, STEP11 = 11, STEP12 = 12, STEP13 = 13, STEP14 = 14, STEP15 = 15, STEP16 = 16, STEP17 = 17, STEP18 = 18, STEP19 = 19, STEP20 = 20, STEP21 = 21, STEP22 = 22, STEP23 = 23, STEP24 = 24, STEP25 = 25, STEP26 = 26, STEP27 = 27, STEP28 = 28, STEP29 = 29, STEP30 = 30, STEP31 = 31, STEP32 = 32, STEP33 = 33, STEP34 = 34, STEP35 = 35 }; /* Exported macro ------------------------------------------------------------*/ #ifndef NULL #define NULL (0) #endif #define TRUE (1) #define FALSE (0) #define ZERO (0) #define ONE (1) #define TWO (2) #define THREE (3) #define FOUR (4) #define FIVE (5) #define SIX (6) #define SEVEN (7) #define EIGHT (8) #define NINE (9) #define TEN (10) #define HUNDRED (100) #define THOUSAND (1000) #define HALFBYTEMAX (15) #define ONEBYTEMAX (255) //两变量交换 #define _SWAP(a, b) ((a) ^= (b), (b) ^= (a), (a) ^= (b)) //数组大小,不能用来比较字符串大小,字符串比较需要用strlen #define _ARRAY_SIZE(a) ((sizeof(a)) / (sizeof(a[0]))) /* 大小端转换宏 */ #define BIG_LITTLE_SWAP16(A) ((((uint16_t)(A) & 0xff00) >> 8) \ | (((uint16_t)(A) & 0x00ff) << 8)) #define BIG_LITTLE_SWAP32(A) ((((uint32_t)(A) & 0xff000000) >> 24) \ | (((uint32_t)(A) & 0x00ff0000) >> 8) \ | (((uint32_t)(A) & 0x0000ff00) << 8) \ | (((uint32_t)(A) & 0x000000ff) << 24)) #define _SET_BIT(target, bit) ((target) |= (unsigned long)(((unsigned long)1) << (bit))) #define _CLR_BIT(target, bit) ((target) &= (unsigned long)(~(((unsigned long)1) << (bit)))) #define _GET_BIT(target, bit) ((target) & (((unsigned long)1) << (bit))) #define _FLP_BIT(target, bit) ((target) ^= (((unsigned long)1) << (bit))) /* Exported functions ------------------------------------------------------- */ #endif /* __GLOBAL_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
2.671875
3
2024-11-18T21:09:58.783927+00:00
2019-11-14T18:23:27
c505ff819435dcf0d35581c1dd4420fa7b23889c
{ "blob_id": "c505ff819435dcf0d35581c1dd4420fa7b23889c", "branch_name": "refs/heads/master", "committer_date": "2019-11-14T18:23:27", "content_id": "c6346b39122b5465f4cb613c1044f09b787f37ba", "detected_licenses": [ "MIT" ], "directory_id": "a3c893c3ad1eee13eda889b3c099fb9dbbb8b08a", "extension": "c", "filename": "BattleEvents.c", "fork_events_count": 3, "gha_created_at": "2015-12-08T23:21:30", "gha_event_created_at": "2015-12-23T01:01:18", "gha_language": "C", "gha_license_id": null, "github_id": 47655651, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7859, "license": "MIT", "license_type": "permissive", "path": "/src/BattleEvents.c", "provenance": "stackv2-0065.json.gz:23558", "repo_name": "Torivon/MiniAdventure", "revision_date": "2019-11-14T18:23:27", "revision_id": "a0f9873e5a3ae772ef9dc47cfaa944a48fae6bb4", "snapshot_id": "4daa831d1ca9be86edcb21ff2e736c9c29fceed2", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/Torivon/MiniAdventure/a0f9873e5a3ae772ef9dc47cfaa944a48fae6bb4/src/BattleEvents.c", "visit_date": "2021-01-13T09:05:00.290519" }
stackv2
// // BattleEvents.c // // // Created by Jonathan Panttaja on 2/1/16. // // #include <pebble.h> #include "AutoBattleEventConstants.h" #include "AutoSizeConstants.h" #include "Battle.h" #include "BattleEvents.h" #include "BinaryResourceLoading.h" #include "DialogFrame.h" #include "Events.h" #include "Logging.h" #include "Skills.h" #include "Story.h" typedef struct BattleEvent { char name[MAX_STORY_NAME_LENGTH]; char menuDescription[MAX_STORY_DESC_LENGTH]; uint16_t automatic; // boolean uint16_t dialog; uint16_t subEvent; uint16_t skill; uint16_t prerequisiteCount; uint16_t prerequisiteType[MAX_BATTLE_EVENT_PREREQS]; uint16_t prerequisiteValue[MAX_BATTLE_EVENT_PREREQS]; uint16_t battlerSwitch; // boolean uint16_t newBattler; uint16_t fullHealOnBattlerChange; // boolean } BattleEvent; static uint16_t currentBattleEventCount = 0; static BattleEvent *currentBattleEvents[MAX_BATTLE_EVENTS] = {0}; static Event *currentBattleEventSubEvents[MAX_BATTLE_EVENTS] = {0}; static Skill *currentBattleEventSkills[MAX_BATTLE_EVENTS] = {0}; BattleEvent *BattleEvent_Load(uint16_t logical_index) { if(logical_index == 0) return NULL; BattleEvent *battleEvent = calloc(sizeof(BattleEvent), 1); ResourceLoadStruct(Story_GetCurrentResHandle(), logical_index, (uint8_t*)battleEvent, sizeof(BattleEvent), "BattleEvent"); return battleEvent; } void BattleEvent_Free(BattleEvent *battleEvent) { if(battleEvent) free(battleEvent); } void BattleEvent_LoadCurrentBattleEvents(uint16_t count, uint16_t *eventIds) { currentBattleEventCount = count; for(int i = 0; i < currentBattleEventCount; ++i) { currentBattleEvents[i] = BattleEvent_Load(eventIds[i]); if(currentBattleEvents[i]->subEvent) currentBattleEventSubEvents[i] = Event_Load(currentBattleEvents[i]->subEvent); if(currentBattleEvents[i]->skill) currentBattleEventSkills[i] = Skill_Load(currentBattleEvents[i]->skill); } } void BattleEvent_FreeCurrentBattleEvents(void) { for(int i = 0; i < MAX_BATTLE_EVENTS; ++i) { if(currentBattleEvents[i]) { BattleEvent_Free(currentBattleEvents[i]); currentBattleEvents[i] = NULL; } if(currentBattleEventSubEvents[i]) { Event_Free(currentBattleEventSubEvents[i]); currentBattleEventSubEvents[i] = NULL; } if(currentBattleEventSkills[i]) { Skill_Free(currentBattleEventSkills[i]); currentBattleEventSkills[i] = NULL; } } } bool BattleEvent_CheckPrerequisites(BattleEvent *battleEvent, Event *subEvent) { bool returnval = true; if(subEvent) { returnval = returnval && Event_CheckPrerequisites(subEvent); } for(int i = 0; i < battleEvent->prerequisiteCount; ++i) { switch (battleEvent->prerequisiteType[i]) { case BATTLE_EVENT_TYPE_MONSTER_HEALTH_BELOW_PERCENT: { BattleActor *monsterActor = GetMonsterActor(); uint16_t percent = monsterActor->currentHealth * 100 / monsterActor->maxHealth; returnval = returnval && (percent <= battleEvent->prerequisiteValue[i]); break; } case BATTLE_EVENT_TYPE_PLAYER_HEALTH_BELOW_PERCENT: { BattleActor *playerActor = GetPlayerActor(); uint16_t percent = playerActor->currentHealth * 100 / playerActor->maxHealth; returnval = returnval && (percent <= battleEvent->prerequisiteValue[i]); break; } case BATTLE_EVENT_TYPE_TIME_ABOVE: { BattleActor *monsterActor = GetMonsterActor(); returnval = returnval && monsterActor->timeInCombat > battleEvent->prerequisiteValue[i]; break; } default: { break; } } } return returnval; } // Trigger is only used for automatic events. Any skills triggered by these come from the enemy void BattleEvent_Trigger(BattleEvent *battleEvent, Event *subEvent, Skill *skill) { if(battleEvent->dialog > 0) { Dialog_TriggerFromResource(Story_GetCurrentResHandle(), battleEvent->dialog); } if(subEvent) { Event_TriggerEvent(subEvent, false); } if(skill) { ExecuteSkill(skill, GetMonsterActorWrapper(), GetPlayerActorWrapper()); } if(battleEvent->battlerSwitch) { Battle_InitializeNewMonster(battleEvent->newBattler, battleEvent->fullHealOnBattlerChange); } return; } // Queue is only used for active events. Any skills trigger by these come from the player void BattleEvent_Queue(BattleEvent *battleEvent, Event *subEvent, Skill *skill) { if(battleEvent->dialog > 0) { Dialog_QueueFromResource(Story_GetCurrentResHandle(), battleEvent->dialog); } if(subEvent) { Event_TriggerEvent(subEvent, false); } if(skill) { ExecuteSkill(skill, GetPlayerActorWrapper(), GetMonsterActorWrapper()); } if(battleEvent->battlerSwitch) { Battle_InitializeNewMonster(battleEvent->newBattler, battleEvent->fullHealOnBattlerChange); } return; } void BattleEvent_MenuQueue(uint16_t index) { uint16_t newIndex = 0; uint16_t indexToUse = 0; for(int i = 0; i < currentBattleEventCount; ++i) { if(!currentBattleEvents[i]->automatic && BattleEvent_CheckPrerequisites(currentBattleEvents[i], currentBattleEventSubEvents[i])) { if(newIndex == index) { indexToUse = i; break; } ++newIndex; } } BattleEvent_Queue(currentBattleEvents[indexToUse], currentBattleEventSubEvents[indexToUse], currentBattleEventSkills[indexToUse]); } bool BattleEvent_TriggerAutomaticBattleEvents(void) { for(int i = 0; i < currentBattleEventCount; ++i) { if(currentBattleEvents[i]->automatic && BattleEvent_CheckPrerequisites(currentBattleEvents[i], currentBattleEventSubEvents[i])) { BattleEvent_Trigger(currentBattleEvents[i], currentBattleEventSubEvents[i], currentBattleEventSkills[i]); DEBUG_LOG("Triggering battle event"); return true; } } return false; } uint16_t BattleEvent_GetCurrentAvailableBattleEvents(void) { if(currentBattleEventCount > 0) { uint16_t count = 0; for(int i = 0; i < currentBattleEventCount; ++i) { if(!currentBattleEvents[i]->automatic && BattleEvent_CheckPrerequisites(currentBattleEvents[i], currentBattleEventSubEvents[i])) ++count; } return count; } else { return 0; } } const char *BattleEvent_GetCurrentBattleEventName(uint16_t index) { uint16_t currentIndex = 0; for(int i = 0; i < currentBattleEventCount; ++i) { if(!currentBattleEvents[i]->automatic && BattleEvent_CheckPrerequisites(currentBattleEvents[i], currentBattleEventSubEvents[i])) { if(currentIndex == index) return currentBattleEvents[i]->name; ++currentIndex; } } return "None"; } const char *BattleEvent_GetCurrentBattleEventDescription(uint16_t index) { uint16_t currentIndex = 0; for(int i = 0; i < currentBattleEventCount; ++i) { if(!currentBattleEvents[i]->automatic && BattleEvent_CheckPrerequisites(currentBattleEvents[i], currentBattleEventSubEvents[i])) { if(currentIndex == index) return currentBattleEvents[i]->menuDescription; ++currentIndex; } } return "None"; }
2.328125
2
2024-11-18T21:09:59.294384+00:00
2021-03-22T18:09:43
5cb8f9b800afa81a56bc0b95e454b4f9ba5c9dfb
{ "blob_id": "5cb8f9b800afa81a56bc0b95e454b4f9ba5c9dfb", "branch_name": "refs/heads/main", "committer_date": "2021-03-22T18:09:43", "content_id": "b7ac06172dfc4e68b02e5031da5a4999f2ef8762", "detected_licenses": [ "Apache-2.0" ], "directory_id": "259dd3523fb5d03a9739f1365b7d1b002a8979a2", "extension": "c", "filename": "chart.c", "fork_events_count": 2, "gha_created_at": "2021-01-15T00:07:21", "gha_event_created_at": "2021-03-22T18:09:45", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 329764752, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2334, "license": "Apache-2.0", "license_type": "permissive", "path": "/gems/carbuncle-gui/src/chart.c", "provenance": "stackv2-0065.json.gz:23944", "repo_name": "holywyvern/carbuncle", "revision_date": "2021-03-22T18:09:43", "revision_id": "b99a15b7af212b7ae879e164810bcd248b158256", "snapshot_id": "1bc94a03791dc54970685a64c5d1672b3bca18d4", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/holywyvern/carbuncle/b99a15b7af212b7ae879e164810bcd248b158256/gems/carbuncle-gui/src/chart.c", "visit_date": "2021-06-28T09:50:31.710603" }
stackv2
#include "carbuncle/core.h" #include "carbuncle/font.h" #include "carbuncle/rect.h" #include "carbuncle/point.h" #include "carbuncle/color.h" #include <carbuncle/nuklear_config.h> #include <nuklear.h> #include <mruby.h> #include <mruby/class.h> #include <mruby/data.h> #include <mruby/variable.h> #include <mruby/string.h> #include <mruby/error.h> #include <mruby/array.h> #include <raylib.h> static struct nk_color to_nk_color(Color *color) { return (struct nk_color) { color->r, color->g, color->b, color->a }; } static mrb_value draw_chart(mrb_state *mrb, mrb_value self, enum nk_chart_type type) { mrb_value mrb_color, mrb_highlight, block; mrb_int items; mrb_float min, max; struct nk_color color, highlight; struct mrb_GuiContext *ctx = mrb_carbuncle_gui_get_context(mrb, self); mrb_get_args(mrb, "ooiff&", &mrb_color, &mrb_highlight, &items, &min, &max, &block); color = to_nk_color(mrb_carbuncle_get_color(mrb, mrb_color)); highlight = to_nk_color(mrb_carbuncle_get_color(mrb, mrb_highlight)); if (nk_chart_begin_colored(&(ctx->nk), type, color, highlight, items, min, max)) { mrb_yield_argv(mrb, block, 0, NULL); nk_chart_end(&(ctx->nk)); } return self; } static mrb_value gui_line_chart(mrb_state *mrb, mrb_value self) { return draw_chart(mrb, self, NK_CHART_LINES);; } static mrb_value gui_column_chart(mrb_state *mrb, mrb_value self) { return draw_chart(mrb, self, NK_CHART_COLUMN); } static mrb_value gui_max_chart(mrb_state *mrb, mrb_value self) { return draw_chart(mrb, self, NK_CHART_MAX); } static mrb_value gui_chart_push(mrb_state *mrb, mrb_value self) { mrb_float value; struct mrb_GuiContext *ctx = mrb_carbuncle_gui_get_context(mrb, self); mrb_get_args(mrb, "f", &value); nk_chart_push(&(ctx->nk), value); return self; } void mrb_init_carbuncle_gui_chart(mrb_state *mrb, struct RClass *gui) { mrb_define_method(mrb, gui, "line_chart", gui_line_chart, MRB_ARGS_REQ(5)|MRB_ARGS_BLOCK()); mrb_define_method(mrb, gui, "column_chart", gui_column_chart, MRB_ARGS_REQ(5)|MRB_ARGS_BLOCK()); mrb_define_method(mrb, gui, "max_chart", gui_max_chart, MRB_ARGS_REQ(5)|MRB_ARGS_BLOCK()); mrb_define_method(mrb, gui, "chart_push", gui_chart_push, MRB_ARGS_REQ(1)); }
2.078125
2
2024-11-18T21:10:02.429949+00:00
2017-12-14T10:35:10
3f16050e473ff8aefc10aa86d7c8ff94bbf40438
{ "blob_id": "3f16050e473ff8aefc10aa86d7c8ff94bbf40438", "branch_name": "refs/heads/master", "committer_date": "2017-12-14T10:35:10", "content_id": "4382287fec0a5c82c910f24105e252684a354537", "detected_licenses": [ "MIT" ], "directory_id": "c2ed1aa5f10e1ef535a4941e6a8899aa9a9804ce", "extension": "c", "filename": "arg_opt.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 111556207, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2266, "license": "MIT", "license_type": "permissive", "path": "/src/arg_opt.c", "provenance": "stackv2-0065.json.gz:24200", "repo_name": "babariviere/ft_ls", "revision_date": "2017-12-14T10:35:10", "revision_id": "e326a53a04f4134968f90c2ce7ba35fcade815dc", "snapshot_id": "9ea05a19e3c17b23eea76b75c85cffa8bce8fc31", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/babariviere/ft_ls/e326a53a04f4134968f90c2ce7ba35fcade815dc/src/arg_opt.c", "visit_date": "2021-08-29T16:44:23.883340" }
stackv2
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* arg_opt.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: briviere <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/11/21 10:10:02 by briviere #+# #+# */ /* Updated: 2017/12/08 15:26:17 by briviere ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_ls.h" static int set_arg_opt_time(t_arg *opt, const char arg) { *opt = *opt & ~ARG_MTIME & ~ARG_CTIME & ~ARG_BTIME & ~ARG_ATIME; if (arg == 't') return (*opt |= ARG_SORT | ARG_SORT_TIME | ARG_MTIME); else if (arg == 'u') return (*opt |= ARG_ATIME); else if (arg == 'c') return (*opt |= ARG_CTIME); else if (arg == 'U') return (*opt |= ARG_BTIME); return (0); } static int set_arg_opt_from_arg(t_arg *opt, const char arg) { if (arg == 'l') return (*opt |= ARG_LIST_FMT); else if (arg == 'R') return (*opt |= ARG_REC); else if (arg == 'a') return (*opt |= ARG_HIDDEN); else if (arg == 'r') return (*opt |= ARG_REV); else if (arg == '1') return (*opt |= ARG_ONE_ENT); else if (arg == 'h') return (*opt |= ARG_HUMAN); else if (arg == 'L') return (*opt |= ARG_FOLLOW_LNK); else if (arg == 'f') return (*opt = (*opt | ARG_HIDDEN) & ~ARG_SORT & ~ARG_SORT_TIME & ~ARG_SORT_SIZE); else if (arg == 'S') return (*opt |= ARG_SORT_SIZE); return (set_arg_opt_time(opt, arg)); } int parse_arg(t_arg *opt, const char *arg) { size_t idx; if (arg[0] != '-' || arg[1] == 0) return (0); idx = 1; while (arg[idx]) { if (set_arg_opt_from_arg(opt, arg[idx]) == 0) { ft_putstr_fd("ls: illegal option -- ", 2); ft_putchar_fd(arg[idx], 2); ft_putchar_fd('\n', 2); exit(usage(1)); } idx++; } return (1); }
2.609375
3
2024-11-18T21:10:02.596139+00:00
2023-08-13T07:00:15
b4c4afa1ba29df9120b686d5ed69508c9105de2d
{ "blob_id": "b4c4afa1ba29df9120b686d5ed69508c9105de2d", "branch_name": "refs/heads/master", "committer_date": "2023-08-13T07:00:15", "content_id": "88a52668800fa351879bd2da30cd27d91d7af052", "detected_licenses": [ "MIT" ], "directory_id": "2266eb133fc3121daf0aa7f4560626b46b94afe0", "extension": "c", "filename": "apprentice.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": 5978, "license": "MIT", "license_type": "permissive", "path": "/cmds/skill/apprentice.c", "provenance": "stackv2-0065.json.gz:24328", "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/cmds/skill/apprentice.c", "visit_date": "2023-08-18T20:18:37.848801" }
stackv2
// apprentice.c #include <ansi.h> inherit F_CLEAN_UP; int main(object me, string arg) { object ob, old_app; mapping family, ob_family; if (me->is_busy()) return notify_fail("你现在正忙着呢。\n"); if (!arg) return notify_fail("指令格式:apprentice | bai [cancel]|<对象>\n"); if (arg == "cancel") { old_app = me->query_temp("pending/apprentice"); if (!objectp(old_app)) return notify_fail("你现在并没有拜任何人为师的意思。\n"); write("你改变主意不想拜" + old_app->name() + "为师了。\n"); tell_object(old_app, me->name() + "改变主意不想拜你为师了。\n"); me->delete_temp("pending/apprentice"); return 1; } if (!(ob = present(arg, environment(me))) || !ob->is_character()) return notify_fail("你想拜谁为师?\n"); if (!living(ob)) return notify_fail("你必须先把" + ob->name() + "弄醒。\n"); if (ob == me) return notify_fail("拜自己为师?好主意....不过没有用。\n"); if (me->is_apprentice_of(ob)) { message_vision(CYN "$N" CYN "恭恭敬敬地向$n" CYN "磕头请" "安,叫道:「师父!」\n" NOR, me, ob); return 1; } if (!mapp(ob_family = ob->query("family"))) return notify_fail(ob->name() + "既不属於任何" "门派,也没有开山立派,不能拜师。\n"); if (playerp(ob)) return notify_fail("对不起,现在不能拜玩家为师。\n"); family = me->query("family"); if (mapp(family) && stringp(family["master_name"]) && ob_family["family_name"] == family["family_name"] && ob_family["generation"] > family["generation"]) return notify_fail(CYN + ob->name() + CYN "吓了一跳,忙" "道:“前辈怎可开这等玩笑,真是折杀做" "晚辈的了。”\n" NOR); if (mapp(family) && stringp(family["master_name"]) && ob_family["family_name"] == family["family_name"] && ob_family["generation"] == family["generation"]) return notify_fail(CYN + ob->name() + CYN "微微一楞,说道" ":“你我辈分相同,相交即可,何谈拜师" "?”\n" NOR); // betrayer ? if (mapp(family) && family["family_name"] != ob_family["family_name"] && me->query_temp("pending/betrayer") != ob) { write(HIR "你这是打算判师吗?判师很可能遭到严厉惩罚。\n" NOR + HIC "如果你下了决心,就再输入一次这条命令。\n" NOR); me->set_temp("pending/betrayer", ob); return 1; } // If the target is willing to recruit us already, we do it. if ((object)ob->query_temp("pending/recruit") == me) { if (mapp(family) && family["family_name"] != ob_family["family_name"]) { message_vision(HIR "$N" HIR "决定背叛师门,改投入$n" HIR "门下。\n\n" NOR + HIC "$N" HIC "跪了下来" "向$n" HIC "恭恭敬敬地磕了四个响头,叫道" ":「师父!」\n\n" NOR, me, ob); me->set("weiwang", 0); me->set("gongxian", 0); me->add("betrayer/times", 1); me->delete ("quest"); me->delete_temp("quest"); if (stringp(family["family_name"])) me->add("betrayer/" + family["family_name"], 1); } else message_vision("$N决定拜$n为师。\n\n" HIC "$N" HIC "跪了" "下来向$n" HIC "恭恭敬敬地磕了四个响头," "叫道:「师父!」\n\n" NOR, me, ob); ob->recruit_apprentice(me); ob->delete_temp("pending/recruit"); tell_object(ob, "恭喜你新收了一名弟子!\n"); printf("恭喜您成为%s的第%s代弟子。\n", me->query("family/family_name"), chinese_number(me->query("family/generation"))); return 1; } else { old_app = me->query_temp("pending/apprentice"); if (ob == old_app) return notify_fail("你想拜" + ob->name() + "为师,但是对方还没有答应。\n"); else if (objectp(old_app)) { write("你改变主意不想拜" + old_app->name() + "为师了。\n"); tell_object(old_app, me->name() + "改变主意不想拜你为师了。\n"); } message_vision("$N想要拜$n为师。\n", me, ob); me->set_temp("pending/apprentice", ob); if (userp(ob)) { tell_object(ob, YEL "如果你愿意收" + me->name() + "为弟子,用 recruit 指令。\n" NOR); } else ob->attempt_apprentice(me); return 1; } } int help(object me) { write(@HELP 指令格式 : apprentice|bai [cancel]|<对象> 这个指令能让你拜某人为师,如果对方也答应要收你为徒的话,就会 立即行拜师之礼, 否则要等到对方用 recruit 指令收你为弟子才能 正式拜师。 请注意你已经有了师父,又背叛师门投入别人门下,则很有可能导致 原有门派的人的追杀,一旦失手,则所有的特殊武功都将被别人废掉, 基本武功减半。 如果对你的师父使用这个指令,会变成向师父请安。 拜同门的师父不能拜比自己辈分低的或是和自己辈分相同的人。 请参考相关指令 expell、recruit HELP ); return 1; }
2.21875
2
2024-11-18T21:10:02.684190+00:00
2016-11-29T09:55:24
15974139cea73471317325cd2582b26dbe8b7698
{ "blob_id": "15974139cea73471317325cd2582b26dbe8b7698", "branch_name": "refs/heads/master", "committer_date": "2016-11-29T09:55:24", "content_id": "03a9a951203a90290d23d0acb249862a88ea4cc2", "detected_licenses": [ "Apache-2.0" ], "directory_id": "958aed8e352e8278d612b6c313e405569f4d0bf3", "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": 74448687, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2466, "license": "Apache-2.0", "license_type": "permissive", "path": "/2016 es sui file/2016 es sui file/main.c", "provenance": "stackv2-0065.json.gz:24457", "repo_name": "JackOsso/TSAM_C", "revision_date": "2016-11-29T09:55:24", "revision_id": "aac363903f529921c63e69226b904a2739a80e51", "snapshot_id": "d263b30c2b7298c2dc2dd640c819721b87219c2f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/JackOsso/TSAM_C/aac363903f529921c63e69226b904a2739a80e51/2016 es sui file/2016 es sui file/main.c", "visit_date": "2020-06-29T05:13:40.246712" }
stackv2
// // main.c // 2016 es sui file // // Created by giacomo osso on 23/11/16. // Copyright © 2016 Giacomo Osso. All rights reserved. // #include <stdio.h> void es1(); void es2(); void es3(); void random(); void myrandom(); int main(int argc, const char * argv[]) { printf("Esercizio sui file!\n \n"); es1(); es2(); es3(); random(); return 0; } void es1(){ char * str; FILE * file; //apre il file file = fopen("/Users/Jack/Git_C/2016 es sui file/2016 es sui file/numbers.txt", "r"); if(file!=NULL){ while(!feof(file)){ // allocare in memoria la stringa str = malloc(sizeof(char)); fscanf(file, "%s", str); printf("\n %s", str); } printf("\n"); fclose(file); }else { printf("Errore, impossibile aprire il file \n"); } } void es2(){ int * num; int somma; FILE * file; file = fopen("/Users/Jack/Git_C/2016 es sui file/2016 es sui file/numbers.txt", "r"); if(file!=NULL){ somma=0; while(!feof(file)){ fscanf(file, "%d" , num); somma = somma + *num; } fclose(file); printf("\n Somma: %d \n", somma); }else{ printf("Errore apertura file"); } } void es3(){ int * num; FILE * file; int sotr; file = fopen("/Users/Jack/Git_C/2016 es sui file/2016 es sui file/numbers.txt", "r"); if(file!=NULL){ sotr = 0; while(!feof(file)){ fscanf(file, "%d" , num); sotr = sotr - *num; } fclose(file); printf("\n Somma: %d \n", sotr); }else{ printf("Errore apertura file"); } } void random(){ void scritturaFile(int k){ int i; srand(time(NULL)); FILE * file; file = fopen("C:\\Users\\Federico Platania\\ClionProjects\\casualNumber\\numeri.txt","a"); if(file!=NULL){ for(int j=0;j < k;j++){ i = rand() % 1000+ 1; fprintf(file,"%i \n",i); } fclose(file); }else{ printf("Errore,impossibile aprire il file!"); } } void myRandom(){ int i; srand(time(NULL)); i = rand() % 1000+ 1; scritturaFile(i); }
3.28125
3
2024-11-18T21:10:03.433741+00:00
2020-06-18T08:35:56
7fb0309ab8662c9ce0949ddb3d4d4ba510483515
{ "blob_id": "7fb0309ab8662c9ce0949ddb3d4d4ba510483515", "branch_name": "refs/heads/master", "committer_date": "2020-06-18T08:35:56", "content_id": "0f20981760be4393d665a420a616313c6e9a0ed7", "detected_licenses": [ "Apache-2.0" ], "directory_id": "cc153bdc1238b6888d309939fc683e6d1589df80", "extension": "c", "filename": "osal_mem.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": 1148, "license": "Apache-2.0", "license_type": "permissive", "path": "/mm-audio/graphite-client/osal/src/osal_mem.c", "provenance": "stackv2-0065.json.gz:24844", "repo_name": "ml-think-tanks/msm8996-vendor", "revision_date": "2020-06-18T08:35:56", "revision_id": "b506122cefbe34508214e0bc6a57941a1bfbbe97", "snapshot_id": "bb9aa72dabe59a9bd9158cd7a6e350a287fa6a35", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ml-think-tanks/msm8996-vendor/b506122cefbe34508214e0bc6a57941a1bfbbe97/mm-audio/graphite-client/osal/src/osal_mem.c", "visit_date": "2022-10-21T17:39:51.458074" }
stackv2
/* * osal_mem.c * * This file contains memory operations support for POSIX. * * Copyright (c) 2016, 2018 Qualcomm Technologies, Inc. * All Rights Reserved. * Confidential and Proprietary - Qualcomm Technologies, Inc. */ #include <stdlib.h> #include <string.h> #ifdef AUDIO_FEATURE_ENABLED_GCOV extern void __gcov_flush(); static void enable_gcov() { __gcov_flush(); } #else static void enable_gcov() { } #endif void *osal_mem_alloc(size_t size) { enable_gcov(); return malloc(size); } void *osal_mem_zalloc(size_t size) { void *ptr; ptr = malloc(size); if (ptr != NULL) memset(ptr, 0, size); return ptr; } void *osal_mem_calloc(size_t items, size_t size) { return calloc(items, size); } void *osal_mem_realloc(void *ptr, size_t size) { return realloc(ptr, size); } void osal_mem_free(void *ptr) { enable_gcov(); free(ptr); } void *osal_mem_cpy(void *dst, size_t dst_size __unused, void *src, size_t src_size) { return memcpy(dst, (const void *)src, src_size); } void *osal_mem_set(void *ptr, int val, size_t size) { return memset(ptr, val, size); }
2.53125
3
2024-11-18T21:10:03.598410+00:00
2019-01-24T06:38:29
34a38c25ba1e6ad2f26159bf2da7ff5fc3363319
{ "blob_id": "34a38c25ba1e6ad2f26159bf2da7ff5fc3363319", "branch_name": "refs/heads/master", "committer_date": "2019-01-24T06:38:29", "content_id": "db52c18cbe7cdcee76d9e3294fb13af40e53f8e5", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c0bff2dd2fc9bb9041d29e78845820d585949e6c", "extension": "h", "filename": "ds_ltable.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 157118187, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4438, "license": "Apache-2.0", "license_type": "permissive", "path": "/datastore/ltable/ds_ltable.h", "provenance": "stackv2-0065.json.gz:25100", "repo_name": "yiwenzhang92/fasst", "revision_date": "2019-01-24T06:38:29", "revision_id": "019fade75b92f6a3afa495244bdcb47f0c64d04e", "snapshot_id": "22055e24b6e8f37d2e18588490c84147eca83fa9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/yiwenzhang92/fasst/019fade75b92f6a3afa495244bdcb47f0c64d04e/datastore/ltable/ds_ltable.h", "visit_date": "2020-04-05T19:05:36.414009" }
stackv2
// Initialization functions for an LTable datastore #ifndef DS_LTABLE_H #define DS_LTABLE_H #include <assert.h> #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include "libhrd/hrd.h" // ct_assert and friends #include "hots.h" #include "datastore/ds.h" #include "rpc/rpc.h" #include "mappings/mappings.h" #include "util/rte_memcpy.h" #include "mica/util/config.h" #include "mica/table/ltable.h" #include "mica/util/hash.h" typedef ::mica::table::BasicLosslessLTableConfig LTableConfig; typedef ::mica::table::LTable<LTableConfig> LTable; typedef ::mica::table::Result MicaResult; /* An enum */ // Control path /* * Initialize the table with pre-defined SHM keys. * @config_filepath contains config parameters for the allocator and pool. * @val_size does not include the HoTS object header. */ static LTable* ds_ltable_init(const char *config_filepath, int bkt_shm_key, int pool_shm_key) { /* * The LTable RPC handler for lock-for-insert is not thread safe: in * concurrent mode, multiple threads can insert a pre-locked object. */ fprintf(stderr, "LTable currently not supported - need to implement " "atomic fetch-and-add in CRCW mode\n"); exit(-1); ds_do_checks(); auto config = ::mica::util::Config::load_file(config_filepath); /* Check that EREW mode is set */ auto table_config = config.get("table"); if(table_config.get("concurrent_read").get_bool() || table_config.get("concurrent_write").get_bool()) { fprintf(stderr, "HoTS Error: LTable only supports EREW. Exiting..\n"); exit(-1); } LTableConfig::Alloc *alloc = new LTableConfig::Alloc(config.get("alloc")); LTableConfig::Pool *pool = new LTableConfig::Pool(config.get("pool"), pool_shm_key, alloc); LTable *table = new LTable(config.get("table"), bkt_shm_key, alloc, pool); return table; } /* Destroy the table */ static void ds_ltable_free(LTable *table) { table->free_pool(); /* We don't have a direct pointer to @pool anymore */ delete table; } /* * Populate the table at worker @wrkr_gid with keys in the range * {0, ..., @num_keys - 1}. * @val_size does not include the HoTS object header. * * If use_partitions is false, all keys in the range are added to this datastore. * In this case, invalid mappings and repl_i should be passed. * * If use_partitions is set, only keys for which this workers is replica number * repl_i are added added to this datastore. * * Value for key i is a chunk of size val_size with bytes = * (a) (i & 0xff) if the const_val argument is not passed * (b) (const_val & 0xff) if the const_val argument is passed */ static void ds_ltable_populate(LTable *table, size_t num_keys, size_t val_size, Mappings *mappings, int repl_i, int wrkr_gid, bool use_partitions, int const_val = -1) { if(!use_partitions) { assert(mappings == NULL && repl_i == -1); } printf("HoTS: Populating table %s for worker %d as replica %d. " "(%lu keys, val size = %lu)\n", table->name.c_str(), wrkr_gid, repl_i, num_keys, val_size); assert(table != NULL); assert(num_keys >= 1); assert(val_size >= 1 && val_size <= HOTS_MAX_VALUE); MicaResult out_result; /* Initialize common fields for all inserted objects */ hots_obj_t obj; hots_format_real_objhdr(obj, val_size); size_t obj_size = hots_obj_size(val_size); for(size_t i = 0; i < num_keys; i++) { hots_key_t key = (hots_key_t) i; uint64_t keyhash = ds_keyhash(key); if(use_partitions) { if(repl_i == 0) { /* Skip if wrkr_gid is not the primary partition for this key */ if(mappings->get_primary_wn(keyhash) != wrkr_gid) { continue; } } else { /* Skip if wrkr_gid is not backup #(repl_i - 1) for this key */ if(mappings->get_backup_wn(keyhash, repl_i - 1) != wrkr_gid) { continue; } } } uint8_t val_byte = (const_val == -1) ? (i & 0xff) : (const_val & 0xff); memset((void *) obj.val, val_byte, val_size); out_result = table->set(keyhash, (char *) &key, sizeof(hots_key_t), (char *) &obj, obj_size, true); if(out_result != MicaResult::kSuccess) { fprintf(stderr, "HoTS: Failed to populate table %s for worker %d. " "Error at key %" PRIu64 ", code = %s\n", table->name.c_str(), wrkr_gid, key, ::mica::table::ResultString(out_result).c_str()); exit(-1); } } printf("HoTS: Done populating table %s for worker %d\n", table->name.c_str(), wrkr_gid); } #include "datastore/ltable/ds_ltable_handler.h" #endif /* DS_LTABLE_H */
2.375
2
2024-11-18T21:10:03.969234+00:00
2021-09-19T20:18:52
2f1822f06a12346c2d08f8aee1175f6aead9437f
{ "blob_id": "2f1822f06a12346c2d08f8aee1175f6aead9437f", "branch_name": "refs/heads/main", "committer_date": "2021-09-19T20:18:52", "content_id": "f73b3fa0d0097cadaf00f6e52a7408fbecae7ca8", "detected_licenses": [ "MIT" ], "directory_id": "a1f964f6ba52ee9fafa8d089f1324b4fc8dddd88", "extension": "c", "filename": "timer.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 408226640, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 841, "license": "MIT", "license_type": "permissive", "path": "/timer.c", "provenance": "stackv2-0065.json.gz:25229", "repo_name": "SienaCSISParallelProcessing/matmult", "revision_date": "2021-09-19T20:18:52", "revision_id": "6909abc3eb8ce5722212463713435abeefa760ca", "snapshot_id": "ad3b76803ae46da978cb7778aabc08e5577dccae", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/SienaCSISParallelProcessing/matmult/6909abc3eb8ce5722212463713435abeefa760ca/timer.c", "visit_date": "2023-08-05T02:13:09.941445" }
stackv2
/* Timer helper routine -- compare values returned by gettimeofday system call and return a number of seconds. Taken from Parallel Mesh Database Jim Teresco, CS 338, Williams College Mon Feb 10 10:55:31 EST 2003 CS 341, Mount Holyoke College CS 400/CS 335, Siena College */ #include <stdlib.h> #include <sys/time.h> /* * wall clock time: * call to get the difference in time to the call * * gettimeofday(&tp, NULL); * */ double diffgettime(struct timeval tp1, struct timeval tp2) { int delta[2] ; delta[0] = tp2.tv_sec - tp1.tv_sec; delta[1] = tp2.tv_usec - tp1.tv_usec; /* See if we've wrapped and deal with it accordingly: */ if( delta[1] < 0 ) { delta[0] = delta[0] - 1; delta[1] = delta[1] + 1000000; } return( (double) delta[0] + (double) delta[1]*1.0E-6 ); }
2.84375
3
2024-11-18T21:10:04.282507+00:00
2014-12-26T15:16:49
857540e426c75467569eb68f0aac61095e5329d4
{ "blob_id": "857540e426c75467569eb68f0aac61095e5329d4", "branch_name": "refs/heads/master", "committer_date": "2014-12-26T15:16:49", "content_id": "46e9c679fdd567c2f5ea82928dfd6ecee6cc959a", "detected_licenses": [ "MIT" ], "directory_id": "c50d12370f33ef903c23c51bad8a907ec07351ef", "extension": "h", "filename": "bitcoind.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": 38231, "license": "MIT", "license_type": "permissive", "path": "/libjl777/bitcoind.h", "provenance": "stackv2-0065.json.gz:25359", "repo_name": "MineMe15/dark-test-v2", "revision_date": "2014-12-26T15:16:49", "revision_id": "b97d978b6562e3d8c746b7d02bad15551c0a3b8a", "snapshot_id": "d50e192a5c452befd919a7e253cd76b57a854733", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/MineMe15/dark-test-v2/b97d978b6562e3d8c746b7d02bad15551c0a3b8a/libjl777/bitcoind.h", "visit_date": "2020-04-08T02:25:21.734893" }
stackv2
// // bitcoind.h // xcode // // Created by jl777 on 7/30/14. // Copyright (c) 2014 jl777. All rights reserved. // #ifndef xcode_bitcoind_h #define xcode_bitcoind_h // lowest level bitcoind functions int64_t issue_bitcoind_command(char *extract,struct coin_info *cp,char *command,char *field,char *arg) { char *retstr = 0; cJSON *obj,*json; int64_t val = 0; retstr = bitcoind_RPC(0,cp->name,cp->serverport,cp->userpass,command,arg); json = 0; if ( retstr != 0 && retstr[0] != 0 ) { json = cJSON_Parse(retstr); if ( field != 0 ) { if ( json != 0 ) { if ( extract == 0 ) val = get_cJSON_int(json,field); else { obj = cJSON_GetObjectItem(json,field); copy_cJSON(extract,obj); val = strlen(extract); } } } else if ( extract != 0 ) copy_cJSON(extract,json); if ( json != 0 ) free_json(json); free(retstr); } return(val); } uint32_t get_blockheight(struct coin_info *cp) { uint32_t height = (uint32_t)cp->RTblockheight; if ( cp->lastheighttime+1000000 < microseconds() ) { height = (uint32_t)issue_bitcoind_command(0,cp,"getinfo","blocks",""); cp->lastheighttime = microseconds(); /*if ( cp->CACHE.ignorelist == 0 && height > 0 ) { cp->CACHE.ignoresize = (int32_t)(height + 1000000); cp->CACHE.ignorelist = malloc(cp->CACHE.ignoresize); memset(cp->CACHE.ignorelist,1,cp->CACHE.ignoresize); }*/ } return(height); } void backupwallet(struct coin_info *cp) { char fname[512]; sprintf(fname,"[\"%s/wallet%s.%d\"]",cp->backupdir,cp->name,cp->backupcount++); printf("backup to (%s)\n",fname); issue_bitcoind_command(0,cp,"backupwallet",fname,fname); } int32_t prep_wallet(struct coin_info *cp,char *walletpass,int32_t unlockseconds) { char walletkey[512],*retstr = 0; if ( walletpass != 0 && walletpass[0] != 0 ) { // locking first avoids error, hacky but no time for wallet fiddling now retstr = bitcoind_RPC(0,cp->name,cp->serverport,cp->userpass,"walletlock",0); if ( retstr != 0 ) { printf("lock returns (%s)\n",retstr); free(retstr); } // jl777: add some error handling! sprintf(walletkey,"[\"%s\",%d]",walletpass,unlockseconds); retstr = bitcoind_RPC(0,cp->name,cp->serverport,cp->userpass,"walletpassphrase",walletkey); if ( retstr != 0 ) { printf("unlock returns (%s)\n",retstr); free(retstr); } } return(0); } int32_t validate_coinaddr(char pubkey[512],struct coin_info *cp,char *coinaddr) { char quotes[512]; int64_t len; if ( coinaddr[0] != '"' ) sprintf(quotes,"\"%s\"",coinaddr); else safecopy(quotes,coinaddr,sizeof(quotes)); len = issue_bitcoind_command(pubkey,cp,"validateaddress","pubkey",quotes); return((int32_t)len); } cJSON *create_vins_json_params(char **localcoinaddrs,struct coin_info *cp,struct rawtransaction *rp) { int32_t i; char *txid; cJSON *json,*array; struct coin_txidind *vp; array = cJSON_CreateArray(); for (i=0; i<rp->numinputs; i++) { if ( localcoinaddrs != 0 ) localcoinaddrs[i] = 0; vp = rp->inputs[i]; txid = vp->txid; if ( txid == 0 || vp->script == 0 ) { printf("unexpected missing txid or script\n"); free_json(array); return(0); } json = cJSON_CreateObject(); cJSON_AddItemToObject(json,"txid",cJSON_CreateString(txid)); cJSON_AddItemToObject(json,"vout",cJSON_CreateNumber(vp->entry.v)); cJSON_AddItemToObject(json,"scriptPubKey",cJSON_CreateString(vp->script)); //cJSON_AddItemToObject(json,"redeemScript",cJSON_CreateString(vp->redeemScript)); if ( localcoinaddrs != 0 ) localcoinaddrs[i] = vp->coinaddr; cJSON_AddItemToArray(array,json); } return(array); } cJSON *create_vouts_json_params(struct rawtransaction *rp) { int32_t i; cJSON *json,*obj; json = cJSON_CreateObject(); for (i=0; i<rp->numoutputs; i++) { obj = cJSON_CreateNumber((double)rp->destamounts[i]/SATOSHIDEN); cJSON_AddItemToObject(json,rp->destaddrs[i],obj); } printf("numdests.%d (%s)\n",rp->numoutputs,cJSON_Print(json)); return(json); } char *send_rawtransaction(struct coin_info *cp,char *txbytes) { char *args,*retstr = 0; if ( cp == 0 ) return(0); args = malloc(strlen(txbytes)+4); strcpy(args+2,txbytes); args[0] = '['; args[1] = '"'; strcat(args,"\"]"); printf("about to send.(%s)\n",args); //getchar(); retstr = bitcoind_RPC(0,cp->name,cp->serverport,cp->userpass,"sendrawtransaction",args); if ( retstr != 0 ) fprintf(stderr,"sendrawtransaction returns.(%s)\n",retstr); else fprintf(stderr,"null return from sendrawtransaction\n"); free(args); return(retstr); } cJSON *script_has_address(int32_t *nump,cJSON *scriptobj) { int32_t i,n; cJSON *addresses,*addrobj; if ( scriptobj == 0 ) return(0); addresses = cJSON_GetObjectItem(scriptobj,"addresses"); *nump = 0; if ( addresses != 0 ) { *nump = n = cJSON_GetArraySize(addresses); for (i=0; i<n; i++) { addrobj = cJSON_GetArrayItem(addresses,i); return(addrobj); } } return(0); } #define OP_HASH160_OPCODE 0xa9 #define OP_EQUAL_OPCODE 0x87 #define OP_DUP_OPCODE 0x76 #define OP_EQUALVERIFY_OPCODE 0x88 #define OP_CHECKSIG_OPCODE 0xac int32_t add_opcode(char *hex,int32_t offset,int32_t opcode) { hex[offset + 0] = hexbyte((opcode >> 4) & 0xf); hex[offset + 1] = hexbyte(opcode & 0xf); return(offset+2); } void calc_script(char *script,char *pubkey) { int32_t offset,len; offset = 0; len = (int32_t)strlen(pubkey); offset = add_opcode(script,offset,OP_DUP_OPCODE); offset = add_opcode(script,offset,OP_HASH160_OPCODE); offset = add_opcode(script,offset,len/2); memcpy(script+offset,pubkey,len), offset += len; offset = add_opcode(script,offset,OP_EQUALVERIFY_OPCODE); offset = add_opcode(script,offset,OP_CHECKSIG_OPCODE); script[offset] = 0; } int32_t convert_to_bitcoinhex(char *scriptasm) { //"asm" : "OP_HASH160 db7f9942da71fd7a28f4a4b2e8c51347240b9e2d OP_EQUAL", char *hex,pubkey[512]; int32_t middlelen,len,OP_HASH160_len,OP_EQUAL_len; len = (int32_t)strlen(scriptasm); // worlds most silly assembler! OP_HASH160_len = strlen("OP_DUP OP_HASH160"); OP_EQUAL_len = strlen("OP_EQUALVERIFY OP_CHECKSIG"); if ( strncmp(scriptasm,"OP_DUP OP_HASH160",OP_HASH160_len) == 0 && strncmp(scriptasm+len-OP_EQUAL_len,"OP_EQUALVERIFY OP_CHECKSIG",OP_EQUAL_len) == 0 ) { middlelen = len - OP_HASH160_len - OP_EQUAL_len - 2; memcpy(pubkey,scriptasm+OP_HASH160_len+1,middlelen); pubkey[middlelen] = 0; hex = calloc(1,len+1); calc_script(hex,pubkey); //printf("(%s) -> script.(%s) (%s)\n",scriptasm,pubkey,hex); strcpy(scriptasm,hex); free(hex); return((int32_t)(2+middlelen+2)); } // printf("cant assembly anything but OP_HASH160 + <key> + OP_EQUAL (%s)\n",scriptasm); return(-1); } int32_t extract_txvals(char *coinaddr,char *script,int32_t nohexout,cJSON *txobj) { int32_t numaddresses; cJSON *scriptobj,*addrobj,*hexobj; scriptobj = cJSON_GetObjectItem(txobj,"scriptPubKey"); if ( scriptobj != 0 ) { addrobj = script_has_address(&numaddresses,scriptobj); if ( coinaddr != 0 ) copy_cJSON(coinaddr,addrobj); if ( nohexout != 0 ) hexobj = cJSON_GetObjectItem(scriptobj,"asm"); else hexobj = cJSON_GetObjectItem(scriptobj,"hex"); if ( script != 0 ) { copy_cJSON(script,hexobj); if ( nohexout != 0 ) convert_to_bitcoinhex(script); } return(0); } return(-1); } char *unspent_json_params(char *txid,int32_t vout) { char *unspentstr; cJSON *array,*nobj,*txidobj; array = cJSON_CreateArray(); nobj = cJSON_CreateNumber(vout); txidobj = cJSON_CreateString(txid); cJSON_AddItemToArray(array,txidobj); cJSON_AddItemToArray(array,nobj); unspentstr = cJSON_Print(array); free_json(array); return(unspentstr); } // ADDRESS_DATA DB void set_address_entry(struct address_entry *bp,uint32_t blocknum,int32_t txind,int32_t vin,int32_t vout,int32_t isinternal,int32_t spent) { memset(bp,0,sizeof(*bp)); bp->blocknum = blocknum; bp->txind = txind; bp->isinternal = isinternal; bp->spent = spent; if ( vout >= 0 && vin < 0 ) bp->v = vout; else if ( vin >= 0 && vout < 0 ) bp->v = vin, bp->vinflag = 1; } void add_address_entry(char *coin,char *addr,uint32_t blocknum,int32_t txind,int32_t vin,int32_t vout,int32_t isinternal,int32_t spent,int32_t syncflag) { struct address_entry B; if ( IS_LIBTEST > 1 ) { // if ( strlen(addr) < 10 ) while ( 1 ) sleep(60); set_address_entry(&B,blocknum,txind,vin,vout,isinternal,spent); _add_address_entry(coin,addr,&B,syncflag); } } void update_address_entry(char *coin,char *addr,uint32_t blocknum,int32_t txind,int32_t vin,int32_t vout,int32_t isinternal,int32_t spent,int32_t syncflag) { struct address_entry B,*vec; int32_t n; if ( IS_LIBTEST > 1 ) { set_address_entry(&B,blocknum,txind,vin,vout,0,spent); if ( (vec= dbupdate_address_entries(&n,coin,addr,&B,1||syncflag)) != 0 ) free(vec); } } struct address_entry *get_address_entries(int32_t *nump,char *coin,char *addr) { *nump = 0; if ( IS_LIBTEST > 1 ) return(dbupdate_address_entries(nump,coin,addr,0,0)); else return(0); } char *get_blockhashstr(struct coin_info *cp,uint32_t blockheight) { char numstr[128],*blockhashstr=0; sprintf(numstr,"%u",blockheight); blockhashstr = bitcoind_RPC(0,cp->name,cp->serverport,cp->userpass,"getblockhash",numstr); if ( blockhashstr == 0 || blockhashstr[0] == 0 ) { printf("couldnt get blockhash for %u\n",blockheight); if ( blockhashstr != 0 ) free(blockhashstr); return(0); } return(blockhashstr); } cJSON *get_blockjson(uint32_t *heightp,struct coin_info *cp,char *blockhashstr,uint32_t blocknum) { cJSON *json = 0; int32_t flag = 0; char buf[1024],*blocktxt = 0; if ( blockhashstr == 0 ) blockhashstr = get_blockhashstr(cp,blocknum), flag = 1; if ( blockhashstr != 0 ) { sprintf(buf,"\"%s\"",blockhashstr); blocktxt = bitcoind_RPC(0,cp->name,cp->serverport,cp->userpass,"getblock",buf); if ( blocktxt != 0 && blocktxt[0] != 0 && (json= cJSON_Parse(blocktxt)) != 0 && heightp != 0 ) *heightp = (uint32_t)get_API_int(cJSON_GetObjectItem(json,"height"),0xffffffff); if ( flag != 0 && blockhashstr != 0 ) free(blockhashstr); if ( blocktxt != 0 ) free(blocktxt); } return(json); } cJSON *_get_blocktxarray(uint32_t *blockidp,int32_t *numtxp,struct coin_info *cp,cJSON *blockjson) { cJSON *txarray = 0; if ( blockjson != 0 ) { *blockidp = (uint32_t)get_API_int(cJSON_GetObjectItem(blockjson,"height"),0); txarray = cJSON_GetObjectItem(blockjson,"tx"); *numtxp = cJSON_GetArraySize(txarray); } return(txarray); } char *oldget_transaction(struct coin_info *cp,char *txidstr) { char *rawtransaction=0,txid[4096]; //*retstr=0,*str, sprintf(txid,"\"%s\"",txidstr); rawtransaction = bitcoind_RPC(0,cp->name,cp->serverport,cp->userpass,"gettransaction",txid); return(rawtransaction); } char *get_rawtransaction(struct coin_info *cp,char *txidstr) { char txid[4096]; sprintf(txid,"[\"%s\"]",txidstr); return(bitcoind_RPC(0,cp->name,cp->serverport,cp->userpass,"getrawtransaction",txid)); } char *get_transaction(struct coin_info *cp,char *txidstr) { char *rawtransaction=0,txid[4096]; sprintf(txid,"[\"%s\", 1]",txidstr); rawtransaction = bitcoind_RPC(0,cp->name,cp->serverport,cp->userpass,"getrawtransaction",txid); /* if ( rawtransaction != 0 ) { if ( rawtransaction[0] != 0 ) { str = malloc(strlen(rawtransaction)+4); sprintf(str,"\"%s\"",rawtransaction); retstr = bitcoind_RPC(0,cp->name,cp->serverport,cp->userpass,"decoderawtransaction",str); if ( retstr == 0 ) printf("null retstr from decoderawtransaction (%s)\n",retstr); free(str); } free(rawtransaction); } else printf("null rawtransaction\n");*/ return(rawtransaction); } uint64_t get_txvout(char *blockhash,int32_t *numvoutsp,char *coinaddr,char *script,struct coin_info *cp,cJSON *txjson,char *txidstr,int32_t vout) { char *retstr; uint64_t value = 0; int32_t numvouts,flag = 0; cJSON *vouts,*obj; if ( numvoutsp != 0 ) *numvoutsp = 0; coinaddr[0] = script[0] = 0; if ( txjson == 0 && txidstr != 0 && txidstr[0] != 0 ) { retstr = get_transaction(cp,txidstr); if ( retstr != 0 && retstr[0] != 0 ) txjson = cJSON_Parse(retstr), flag = 1; if ( retstr != 0 ) free(retstr); } if ( txjson != 0 ) { if ( blockhash != 0 ) copy_cJSON(blockhash,cJSON_GetObjectItem(txjson,"blockhash")); vouts = cJSON_GetObjectItem(txjson,"vout"); numvouts = cJSON_GetArraySize(vouts); if ( numvoutsp != 0 ) *numvoutsp = numvouts; if ( vout < numvouts ) { obj = cJSON_GetArrayItem(vouts,vout); if ( (value = conv_cJSON_float(obj,"value")) > 0 ) { extract_txvals(coinaddr,script,cp->nohexout,obj); if ( coinaddr[0] == 0 ) printf("(%s) obj.%p vouts.%p num.%d vs %d %s\n",coinaddr,obj,vouts,vout,numvouts,cJSON_Print(txjson)); if ( script[0] == 0 && value > 0 ) printf("process_vouts WARNING coinaddr,(%s) %s\n",coinaddr,script); } } else printf("vout.%d >= numvouts.%d\n",vout,numvouts); if ( flag != 0 ) free_json(txjson); } else printf("get_txout: null txjson\n"); return(value); } int32_t calc_isinternal(struct coin_info *cp,char *coinaddr_v0,uint32_t height,int32_t i,int32_t numvouts) { if ( coinaddr_v0 == 0 || (cp->marker != 0 && strcmp(cp->marker,coinaddr_v0) == 0) ) { if ( height < cp->forkheight ) return((i > 1) ? 1 : 0); else return((i == numvouts-1) ? 1 : 0); } return(0); } uint64_t update_vins(int32_t *isinternalp,char *coinaddr,char *script,struct coin_info *cp,uint32_t blockheight,int32_t txind,cJSON *vins,int32_t vind,int32_t syncflag) { uint32_t get_blocktxind(int32_t *txindp,struct coin_info *cp,uint32_t blockheight,char *blockhashstr,char *txidstr); cJSON *obj,*txidobj,*coinbaseobj; int32_t i,vout,numvins,numvouts,oldtxind,flag = 0; char txidstr[1024],coinbase[1024],blockhash[1024]; uint32_t oldblockheight; if ( vins != 0 && is_cJSON_Array(vins) != 0 && (numvins= cJSON_GetArraySize(vins)) > 0 ) { for (i=0; i<numvins; i++) { if ( vind >= 0 && vind != i ) continue; obj = cJSON_GetArrayItem(vins,i); if ( numvins == 1 ) { coinbaseobj = cJSON_GetObjectItem(obj,"coinbase"); copy_cJSON(coinbase,coinbaseobj); if ( strlen(coinbase) > 1 ) { if ( txind > 0 ) printf("txind.%d is coinbase.%s\n",txind,coinbase); return(flag); } } txidobj = cJSON_GetObjectItem(obj,"txid"); if ( txidobj != 0 && cJSON_GetObjectItem(obj,"vout") != 0 ) { vout = (int)get_cJSON_int(obj,"vout"); copy_cJSON(txidstr,txidobj); if ( txidstr[0] != 0 && get_txvout(blockhash,&numvouts,coinaddr,script,cp,0,txidstr,vout) != 0 && blockhash[0] != 0 ) { //printf("process input.(%s)\n",coinaddr); if ( (oldblockheight= get_blocktxind(&oldtxind,cp,0,blockhash,txidstr)) > 0 ) { flag++; add_address_entry(cp->name,coinaddr,oldblockheight,oldtxind,-1,vout,-1,1,0); add_address_entry(cp->name,coinaddr,blockheight,txind,i,-1,-1,1,syncflag * (i == (numvins-1))); } else printf("error getting oldblockheight (%s %s)\n",blockhash,txidstr); } else printf("unexpected error vout.%d %s\n",vout,txidstr); } else printf("illegal txid.(%s)\n",txidstr); } } return(flag); } void update_txid_infos(struct coin_info *cp,uint32_t blockheight,int32_t txind,char *txidstr,int32_t syncflag) { char coinaddr[1024],script[4096],coinaddr_v0[1024],*retstr = 0; int32_t v,tmp,numvouts,isinternal = 0; cJSON *txjson; if ( (retstr= get_transaction(cp,txidstr)) != 0 ) { if ( (txjson= cJSON_Parse(retstr)) != 0 ) { v = 0; if ( get_txvout(0,&numvouts,coinaddr_v0,script,cp,txjson,0,v) > 0 ) add_address_entry(cp->name,coinaddr_v0,blockheight,txind,-1,v,isinternal,0,syncflag * (v == (numvouts-1))); for (v=1; v<numvouts; v++) { if ( v < numvouts && get_txvout(0,&tmp,coinaddr,script,cp,txjson,0,v) > 0 ) { isinternal = calc_isinternal(cp,coinaddr_v0,blockheight,v,numvouts); add_address_entry(cp->name,coinaddr,blockheight,txind,-1,v,isinternal,0,syncflag * (v == (numvouts-1))); } } update_vins(&isinternal,coinaddr,script,cp,blockheight,txind,cJSON_GetObjectItem(txjson,"vin"),-1,syncflag); free_json(txjson); } else printf("update_txid_infos parse error.(%s)\n",retstr); free(retstr); } else printf("error getting.(%s)\n",txidstr); } uint32_t get_blocktxind(int32_t *txindp,struct coin_info *cp,uint32_t blockheight,char *blockhashstr,char *reftxidstr) { char txidstr[1024]; cJSON *json,*txobj; int32_t txind,n; uint32_t blockid = 0; *txindp = -1; if ( (json= get_blockjson(0,cp,blockhashstr,blockheight)) != 0 ) { if ( (txobj= _get_blocktxarray(&blockid,&n,cp,json)) != 0 ) { if ( blockheight == 0 ) blockheight = blockid; for (txind=0; txind<n; txind++) { copy_cJSON(txidstr,cJSON_GetArrayItem(txobj,txind)); if ( Debuglevel > 2 ) printf("%-5s blocktxt.%ld i.%d of n.%d %s\n",cp->name,(long)blockheight,txind,n,txidstr); if ( reftxidstr != 0 ) { if ( txidstr[0] != 0 && strcmp(txidstr,reftxidstr) == 0 ) { *txindp = txind; break; } } else update_txid_infos(cp,blockheight,txind,txidstr,txind == n-1); } } free_json(json); } else printf("get_blockjson error parsing.(%s)\n",txidstr); return(blockid); } int32_t update_address_infos(struct coin_info *cp,uint32_t blockheight) { char *blockhashstr=0; int32_t txind,flag = 0; uint32_t height; if ( (blockhashstr = get_blockhashstr(cp,blockheight)) != 0 ) { if ( (height= get_blocktxind(&txind,cp,blockheight,blockhashstr,0)) != blockheight ) printf("mismatched blockheight %u != %u (%s)\n",blockheight,height,blockhashstr); else flag++; } free(blockhashstr); return(flag); } uint64_t get_txoutstr(int32_t *numvoutsp,char *txidstr,char *coinaddr,char *script,struct coin_info *cp,uint32_t blockheight,int32_t txind,int32_t vout) { uint64_t value = 0; cJSON *json,*txobj; int32_t n; uint32_t blockid = 0; if ( (json= get_blockjson(0,cp,0,blockheight)) != 0 ) { if ( (txobj= _get_blocktxarray(&blockid,&n,cp,json)) != 0 && txind < n ) { copy_cJSON(txidstr,cJSON_GetArrayItem(txobj,txind)); if ( Debuglevel > 2 ) printf("%-5s blocktxt.%ld i.%d of n.%d %s\n",cp->name,(long)blockheight,txind,n,txidstr); value = get_txvout(0,numvoutsp,coinaddr,script,cp,0,txidstr,vout); } else printf("txind.%d >= numtxinds.%d for block.%d\n",txind,n,blockheight); free_json(json); } return(value); } uint32_t get_txidind(int32_t *txindp,struct coin_info *cp,char *reftxidstr,int32_t vout) { char blockhash[1024],coinaddr[1024],txidstr[1024],script[4096]; uint32_t blockid,blocknum = 0xffffffff; int32_t i,n,numvouts; cJSON *json,*txarray; *txindp = -1; if ( txidstr[0] != 0 && get_txvout(blockhash,&numvouts,coinaddr,script,cp,0,reftxidstr,vout) != 0 && blockhash[0] != 0 ) { if ( (json= get_blockjson(&blocknum,cp,blockhash,blocknum)) != 0 ) { if ( (txarray= _get_blocktxarray(&blockid,&n,cp,json)) != 0 ) { for (i=0; i<n; i++) { copy_cJSON(txidstr,cJSON_GetArrayItem(txarray,i)); if ( strcmp(txidstr,reftxidstr) == 0 ) { *txindp = i; break; } } } free_json(json); } } return(blocknum); } int32_t get_txinstr(char *txidstr,struct coin_info *cp,uint32_t blockheight,int32_t txind,int32_t vin) { char input_txid[1024],*retstr; cJSON *obj,*json,*txobj,*vins,*txjson; int32_t n,numvins,origvout = -1; uint32_t blockid = 0; if ( (json= get_blockjson(0,cp,0,blockheight)) != 0 ) { if ( (txobj= _get_blocktxarray(&blockid,&n,cp,json)) != 0 && txind < n ) { copy_cJSON(input_txid,cJSON_GetArrayItem(txobj,txind)); if ( Debuglevel > 2 ) printf("%-5s blocktxt.%ld i.%d of n.%d %s\n",cp->name,(long)blockheight,txind,n,input_txid); if ( input_txid[0] != 0 && (retstr= get_transaction(cp,input_txid)) != 0 ) { if ( (txjson= cJSON_Parse(retstr)) != 0 ) { vins = cJSON_GetObjectItem(txjson,"vin"); numvins = cJSON_GetArraySize(vins); if ( vin < numvins ) { obj = cJSON_GetArrayItem(vins,vin); copy_cJSON(txidstr,cJSON_GetObjectItem(obj,"txid")); origvout = (int32_t)get_API_int(cJSON_GetObjectItem(obj,"vout"),-1); } free_json(txjson); } free(retstr); } else printf("txind.%d >= numtxinds.%d for block.%d\n",txind,n,blockheight); } free_json(json); } return(origvout); } char *find_good_changeaddr(struct multisig_addr **msigs,int32_t nummsigs,struct coin_info *cp,char *destaddrs[],int32_t numdestaddrs) { int32_t i,j; if ( cp == 0 || destaddrs == 0 ) return(0); for (i=0; i<nummsigs; i++) { if ( msigs[i] != 0 ) { for (j=0; j<numdestaddrs; j++) if ( destaddrs[j] != 0 && strcmp(msigs[i]->coinstr,cp->name) == 0 && strcmp(destaddrs[j],msigs[i]->multisigaddr) == 0 ) break; if ( j == numdestaddrs ) return(msigs[i]->multisigaddr); } } return(0); } int64_t calc_batchinputs(struct multisig_addr **msigs,int32_t nummsigs,struct coin_info *cp,struct rawtransaction *rp,int64_t amount) { int64_t sum = 0; struct coin_txidind *vp; int32_t i; struct unspent_info *up = &cp->unspent; if ( rp == 0 || up == 0 ) { fprintf(stderr,"unexpected null ptr %p %p\n",up,rp); return(0); } rp->inputsum = rp->numinputs = 0; for (i=0; i<up->num&&i<((int)(sizeof(rp->inputs)/sizeof(*rp->inputs)))-1; i++) { vp = up->vps[i]; if ( vp == 0 ) continue; sum += vp->value; fprintf(stderr,"%p %s input.%d value %.8f\n",vp,vp->coinaddr,rp->numinputs,dstr(vp->value)); rp->inputs[rp->numinputs++] = (sum < (amount + cp->txfee)) ? vp : up->vps[up->num-1]; if ( sum >= (amount + cp->txfee) && rp->numinputs > 1 ) { rp->amount = amount; rp->change = (sum - amount - cp->txfee); rp->inputsum = sum; fprintf(stderr,"numinputs %d sum %.8f vs amount %.8f change %.8f -> miners %.8f\n",rp->numinputs,dstr(rp->inputsum),dstr(amount),dstr(rp->change),dstr(sum - rp->change - rp->amount)); return(rp->inputsum); } } fprintf(stderr,"error numinputs %d sum %.8f\n",rp->numinputs,dstr(rp->inputsum)); return(0); } int32_t init_batchoutputs(struct coin_info *cp,struct rawtransaction *rp,uint64_t MGWfee) { char *marker = get_backupmarker(cp->name); if ( rp->destaddrs[0] == 0 || strcmp(rp->destaddrs[0],marker) != 0 ) rp->destaddrs[0] = clonestr(marker); rp->destamounts[0] = MGWfee; return(1); } struct rawoutput_entry { char destaddr[MAX_COINADDR_LEN]; double amount; }; void sort_rawoutputs(struct rawtransaction *rp) { struct rawoutput_entry sortbuf[MAX_MULTISIG_OUTPUTS+MAX_MULTISIG_INPUTS]; int32_t i; //fprintf(stderr,"sort_rawoutputs.%d\n",rp->numoutputs); if ( rp->numoutputs > 2 ) { memset(sortbuf,0,sizeof(sortbuf)); for (i=1; i<rp->numoutputs; i++) { sortbuf[i-1].amount = rp->destamounts[i]; strcpy(sortbuf[i-1].destaddr,rp->destaddrs[i]); //fprintf(stderr,"%d of %d: %s %.8f\n",i-1,rp->numoutputs,sortbuf[i-1].destaddr,dstr(sortbuf[i-1].amount)); } revsortstrs(&sortbuf[0].destaddr[0],rp->numoutputs-1,sizeof(sortbuf[0])); //fprintf(stderr,"SORTED\n"); for (i=0; i<rp->numoutputs-1; i++) { rp->destamounts[i+1] = sortbuf[i].amount; strcpy(rp->destaddrs[i+1],sortbuf[i].destaddr); //fprintf(stderr,"%d of %d: %s %.8f\n",i,rp->numoutputs-1,sortbuf[i].destaddr,dstr(sortbuf[i].amount)); } } } struct rawinput_entry { char str[MAX_COINTXID_LEN]; struct coin_txidind *input; void *xp; }; void sort_rawinputs(struct rawtransaction *rp) { struct rawinput_entry sortbuf[MAX_MULTISIG_INPUTS]; int32_t i,n = 0; //fprintf(stderr,"rawinput_entry.%d\n",rp->numinputs); if ( rp->numinputs > 1 ) { memset(sortbuf,0,sizeof(sortbuf)); for (i=0; i<rp->numinputs; i++) { if ( rp->inputs[i] != 0 )//&& rp->xps[i] != 0 ) { sprintf(sortbuf[n].str,"%s.%d",rp->inputs[i]->coinaddr,rp->inputs[i]->entry.v); sortbuf[n].input = rp->inputs[i]; //sortbuf[n].xp = rp->xps[i]; //fprintf(stderr,"i.%d of %d: %s %p %p\n",i,rp->numinputs,sortbuf[n].str,sortbuf[n].input,sortbuf[n].xp); n++; } } if ( n > 0 ) { revsortstrs(&sortbuf[0].str[0],n,sizeof(sortbuf[0])); for (i=0; i<n; i++) { rp->inputs[i] = sortbuf[i].input; //rp->xps[i] = sortbuf[i].xp; //fprintf(stderr,"i.%d of %d: %s %p %p\n",i,n,sortbuf[i].str,rp->inputs[i],rp->xps[i]); } rp->numinputs = n; } } } void finalize_destamounts(struct multisig_addr **msigs,int32_t nummsigs,struct coin_info *cp,struct rawtransaction *rp,uint64_t change,uint64_t dust) { struct unspent_info *up = &cp->unspent; int32_t i; char *changeaddr; fprintf(stderr,"finalize_destamounts %p %.f %.f\n",rp,dstr(change),dstr(dust)); if ( change == 0 ) // need to always have a change addr { change = rp->destamounts[0] >> 1; if ( change > dust ) change = dust; rp->destamounts[0] -= change; } fprintf(stderr,"sort_rawoutputs.%d\n",rp->numoutputs); sort_rawoutputs(rp); fprintf(stderr,"sort_rawinputs.%d\n",rp->numinputs); sort_rawinputs(rp); for (i=0; i<rp->numredeems; i++) printf("\"%llu\",",(long long)rp->redeems[i]); printf("numredeems.%d\n",rp->numredeems); for (i=0; i<rp->numredeems; i++) fprintf(stderr,"\"%llu\",",(long long)rp->redeems[i]); fprintf(stderr,"FINISHED numredeems.%d\n",rp->numredeems); if ( up != 0 && up->minvp != 0 && up->minvp->coinaddr != 0 && up->minvp->coinaddr[0] != 0 ) { for (i=0; i<rp->numoutputs; i++) if ( strcmp(up->minvp->coinaddr,rp->destaddrs[i]) == 0 ) break; if ( i != rp->numoutputs ) changeaddr = find_good_changeaddr(msigs,nummsigs,cp,rp->destaddrs,rp->numoutputs); else changeaddr = up->minvp->coinaddr; if ( changeaddr != 0 ) { rp->destamounts[rp->numoutputs] = change; rp->destaddrs[rp->numoutputs] = clonestr(changeaddr); rp->numoutputs++; } else printf("ERROR: cant get valid change address for coin.%s\n",cp->name); } else { //if ( search_multisig_addrs(cp,rp->destaddrs[rp->numoutputs-1]) != 0 ) // printf("WARNING: no min acct, change %.8f WILL categorize last output as isinternal even though it was withdraw to deposit addr!\n",dstr(change)); rp->destamounts[0] += change; } } void clear_BATCH(struct rawtransaction *rp) { int32_t i; fprintf(stderr,"clear_BATCH\n"); for (i=0; i<rp->numoutputs; i++) if ( rp->destaddrs[i] != 0 ) free(rp->destaddrs[i]); memset(rp,0,sizeof(*rp)); } char *sign_localtx(struct coin_info *cp,struct rawtransaction *rp,char *rawbytes) { int32_t sign_rawtransaction(char *deststr,unsigned long destsize,struct coin_info *cp,struct rawtransaction *rp,char *rawbytes,char **privkeys); char *batchsigned; fprintf(stderr,"sign_localtx\n"); rp->batchsize = strlen(rawbytes); rp->batchcrc = _crc32(0,rawbytes+10,rp->batchsize-10); // skip past timediff batchsigned = malloc(rp->batchsize + rp->numinputs*512 + 512); sign_rawtransaction(batchsigned,rp->batchsize + rp->numinputs*512 + 512,cp,rp,rawbytes,0); if ( sizeof(rp->batchsigned) < strlen(rp->batchsigned) ) printf("FATAL: sizeof(rp->signedtransaction) %ld < %ld strlen(rp->batchsigned)\n",sizeof(rp->batchsigned),strlen(rp->batchsigned)); strncpy(rp->batchsigned,batchsigned,sizeof(rp->batchsigned)-1); return(batchsigned); } uint64_t scale_batch_outputs(struct coin_info *cp,struct rawtransaction *rp) { uint64_t MGWfee,amount; int32_t i,nummarkers; MGWfee = (rp->numredeems * (cp->txfee + cp->NXTfee_equiv)) - cp->txfee; nummarkers = init_batchoutputs(cp,rp,MGWfee); amount = 0; for (i=nummarkers; i<rp->numoutputs; i++) amount += rp->destamounts[i]; if ( amount <= MGWfee ) return(0); return(MGWfee + amount); } char *calc_batchwithdraw(struct multisig_addr **msigs,int32_t nummsigs,struct coin_info *cp,struct rawtransaction *rp,int64_t estimated,int64_t balance,struct NXT_asset *ap) { char *createrawtxid_json_params(struct coin_info *cp,struct rawtransaction *rp); int64_t retA; char *rawparams,*retstr = 0,*batchsigned = 0; fprintf(stderr,"calc_batchwithdraw.%s numoutputs.%d estimated %.8f -> balance %.8f\n",cp->name,rp->numoutputs,dstr(estimated),dstr(balance)); if ( cp == 0 ) return(0); rp->amount = scale_batch_outputs(cp,rp); if ( rp->amount == 0 ) return(0); fprintf(stderr,"calc_batchwithdraw.%s amount %.8f -> balance %.8f\n",cp->name,dstr(rp->amount),dstr(balance)); if ( rp->amount+cp->txfee <= balance ) { if ( (retA= calc_batchinputs(msigs,nummsigs,cp,rp,rp->amount)) >= (rp->amount + cp->txfee) ) { finalize_destamounts(msigs,nummsigs,cp,rp,rp->change,cp->dust); rawparams = createrawtxid_json_params(cp,rp); if ( rawparams != 0 ) { fprintf(stderr,"len.%ld rawparams.(%s)\n",strlen(rawparams),rawparams); stripwhite(rawparams,strlen(rawparams)); retstr = bitcoind_RPC(0,cp->name,cp->serverport,cp->userpass,"createrawtransaction",rawparams); if ( retstr != 0 && retstr[0] != 0 ) { fprintf(stderr,"len.%ld calc_rawtransaction retstr.(%s)\n",strlen(retstr),retstr); batchsigned = sign_localtx(cp,rp,retstr); } else fprintf(stderr,"error creating rawtransaction\n"); free(rawparams); } else fprintf(stderr,"error creating rawparams\n"); } else fprintf(stderr,"error calculating rawinputs.%.8f or outputs.%.8f | txfee %.8f\n",dstr(retA),dstr(rp->amount),dstr(cp->txfee)); } else fprintf(stderr,"not enough %s balance %.8f for withdraw %.8f txfee %.8f\n",cp->name,dstr(balance),dstr(rp->amount),dstr(cp->txfee)); return(batchsigned); } char *get_bitcoind_pubkey(char *pubkey,struct coin_info *cp,char *coinaddr) { char addr[256],*retstr; cJSON *json,*pubobj; pubkey[0] = 0; if ( cp == 0 ) { printf("get_bitcoind_pubkey null cp?\n"); return(0); } sprintf(addr,"\"%s\"",coinaddr); retstr = bitcoind_RPC(0,cp->name,cp->serverport,cp->userpass,"validateaddress",addr); if ( retstr != 0 ) { printf("got retstr.(%s)\n",retstr); json = cJSON_Parse(retstr); if ( json != 0 ) { pubobj = cJSON_GetObjectItem(json,"pubkey"); copy_cJSON(pubkey,pubobj); printf("got.%s get_coinaddr_pubkey (%s)\n",cp->name,pubkey); free_json(json); } else printf("get_coinaddr_pubkey.%s: parse error.(%s)\n",cp->name,retstr); free(retstr); return(pubkey); } else printf("%s error issuing validateaddress\n",cp->name); return(0); } char *get_acct_coinaddr(char *coinaddr,struct coin_info *cp,char *NXTaddr) { char addr[128]; char *retstr; coinaddr[0] = 0; sprintf(addr,"\"%s\"",NXTaddr); retstr = bitcoind_RPC(0,cp->name,cp->serverport,cp->userpass,"getaccountaddress",addr); if ( retstr != 0 ) { strcpy(coinaddr,retstr); free(retstr); return(coinaddr); } return(0); } uint32_t extract_sequenceid(int32_t *numinputsp,struct coin_info *cp,char *rawtx,int32_t vind) { uint32_t sequenceid = 0xffffffff; int32_t numinputs; cJSON *json,*vin,*item; char *retstr,*str; *numinputsp = 0; str = malloc(strlen(rawtx)+4); //printf("got rawtransaction.(%s)\n",rawtransaction); sprintf(str,"\"%s\"",rawtx); retstr = bitcoind_RPC(0,cp->name,cp->serverport,cp->userpass,"decoderawtransaction",str); if ( retstr != 0 && retstr[0] != 0 ) { //printf("decoded.(%s)\n",retstr); if ( (json= cJSON_Parse(retstr)) != 0 ) { if ( (vin= cJSON_GetObjectItem(json,"vin")) != 0 && is_cJSON_Array(vin) != 0 && (numinputs= cJSON_GetArraySize(vin)) > vind ) { *numinputsp = numinputs; if ( (item= cJSON_GetArrayItem(vin,vind)) != 0 ) sequenceid = (uint32_t)get_API_int(cJSON_GetObjectItem(item,"sequence"),0); } free_json(json); } } if ( retstr != 0 ) free(retstr); free(str); return(sequenceid); } int32_t replace_bitcoin_sequenceid(struct coin_info *cp,char *rawtx,uint32_t newbytes) { char numstr[9]; int32_t i,n,numinputs; uint32_t val; n = (int32_t)(strlen(rawtx) - 8); for (i=0; i<n; i++) if ( memcmp(&rawtx[i],"ffffffff",8) == 0 ) break; if ( i < n ) { init_hexbytes_noT(numstr,(void *)&newbytes,4); memcpy(&rawtx[i],numstr,8); if ( cp != 0 ) { if ( (val= extract_sequenceid(&numinputs,cp,rawtx,0)) != newbytes ) { printf("val.%u != newbytes.%u\n",val,newbytes); return(-1); } } return(i); } return(-1); } void *Coinloop(void *ptr) { int32_t i,processed; struct coin_info *cp; int64_t height; init_Contacts(); if ( (cp= get_coin_info("BTCD")) != 0 ) { printf("add myhandle\n"); addcontact(Global_mp->myhandle,cp->privateNXTADDR); printf("add mypublic\n"); addcontact("mypublic",cp->srvNXTADDR); } printf("Coinloop numcoins.%d\n",Numcoins); scan_address_entries(); for (i=0; i<Numcoins; i++) { if ( (cp= Daemons[i]) != 0 ) { printf("coin.%d (%s) firstblock.%d\n",i,cp->name,(int32_t)cp->blockheight); //load_telepods(cp,maxnofile); } } while ( 1 ) { processed = 0; for (i=0; i<Numcoins; i++) { cp = Daemons[i]; height = get_blockheight(cp); cp->RTblockheight = (int32_t)height; if ( cp->blockheight < (height - cp->min_confirms) ) { //if ( Debuglevel > 2 ) printf("%s: historical block.%ld when height.%ld\n",cp->name,(long)cp->blockheight,(long)height); if ( update_address_infos(cp,(uint32_t)cp->blockheight) != 0 ) { processed++; cp->blockheight++; } } } if ( processed == 0 ) { if ( Debuglevel > 2 ) printf("Coinloop: no work, sleep\n"); sleep(10); } } return(0); } #endif
2.140625
2
2024-11-18T21:10:04.792460+00:00
2023-08-11T13:02:43
5294324919237f31d72432cf43c3aec44d8f1884
{ "blob_id": "5294324919237f31d72432cf43c3aec44d8f1884", "branch_name": "refs/heads/master", "committer_date": "2023-08-11T13:02:43", "content_id": "903e50e8b689a7f5304416c8aa95efccd2bfb70b", "detected_licenses": [ "MIT" ], "directory_id": "751d837b8a4445877bb2f0d1e97ce41cd39ce1bd", "extension": "c", "filename": "palpal-strings.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 115886967, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1825, "license": "MIT", "license_type": "permissive", "path": "/codechef/palpal-strings.c", "provenance": "stackv2-0065.json.gz:26004", "repo_name": "qeedquan/challenges", "revision_date": "2023-08-11T13:02:43", "revision_id": "56823e77cf502bdea68cce0e1221f5add3d64d6a", "snapshot_id": "d55146f784a3619caa4541ac6f2b670b0a3dd8ba", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/qeedquan/challenges/56823e77cf502bdea68cce0e1221f5add3d64d6a/codechef/palpal-strings.c", "visit_date": "2023-08-11T20:35:09.726571" }
stackv2
/* A string is called a Palpal string if it can be divided into contiguous substrings such that: Each character of the whole string belongs to exactly one substring. Each of these substrings is a palindrome with length greater than 1. For example, "abbbaddzcz" is a Palpal string, since it can be divided into "abbba", "dd" and "zcz". You are given a string s. You may rearrange the characters of this string in any way you choose. Find out if it is possible to rearrange them in such a way that you obtain a Palpal string. Input The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. The first and only line of each test case contains a single string s. Output For each test case, print a single line containing the string "YES" if the characters of s can be rearranged to form a Palpal string or "NO" if it is impossible (without quotes). You may print each character of each string in uppercase or lowercase (for example, the strings "yEs", "yes", "Yes" and "YES" will all be treated as identical). Constraints 1≤T≤105 1≤|s|≤100 s contains only lowercase English letters the sum of |s| over all test cases does not exceed 10^6 */ #include <assert.h> #include <stdbool.h> #include <stdio.h> #include <string.h> #define nelem(x) (sizeof(x) / sizeof(x[0])) bool palpal(const char *s) { size_t h[256]; size_t a, b, i; memset(h, 0, sizeof(h)); for (i = 0; s[i]; i++) h[s[i] & 0xff]++; a = b = 0; for (i = 0; i < nelem(h); i++) { if (h[i] == 1) a += 1; else if (!(h[i] & 1)) b += h[i] / 2; else if (h[i] > 3 && (h[i] & 1)) b += (h[i] - 3) / 2; } return b >= a; } int main(void) { assert(palpal("acbbbadzdz") == true); assert(palpal("abcd") == false); assert(palpal("xyxyxy") == true); return 0; }
3.625
4
2024-11-18T21:10:04.860230+00:00
2015-03-02T07:39:23
c04101d6ced0a1791679a26984b9b8dbfa19ddc9
{ "blob_id": "c04101d6ced0a1791679a26984b9b8dbfa19ddc9", "branch_name": "refs/heads/master", "committer_date": "2015-03-02T07:39:23", "content_id": "6eeb35166ccc099f9f0ecf2d377e7b067adc3283", "detected_licenses": [ "Apache-2.0" ], "directory_id": "f37c3546f39d7ebc4236c043e740d68bf826e8c1", "extension": "c", "filename": "FskString.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": 20410, "license": "Apache-2.0", "license_type": "permissive", "path": "/core/base/FskString.c", "provenance": "stackv2-0065.json.gz:26132", "repo_name": "sandy-slin/kinomajs", "revision_date": "2015-03-02T07:39:23", "revision_id": "567b52be74ec1482e0bab2d370781a7188aeb0ab", "snapshot_id": "f08f60352b63f1d3fad3f6b0e9a5e4bc8025f082", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sandy-slin/kinomajs/567b52be74ec1482e0bab2d370781a7188aeb0ab/core/base/FskString.c", "visit_date": "2020-12-24T22:21:05.506599" }
stackv2
/* Copyright (C) 2010-2015 Marvell International Ltd. Copyright (C) 2002-2010 Kinoma, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "FskMemory.h" #include "FskPlatformImplementation.h" #include "FskTextConvert.h" #include "FskFiles.h" #include "FskString.h" #include <string.h> #include <stdlib.h> #if TARGET_OS_LINUX #include <unistd.h> #include <wchar.h> #endif #define ishex(c) ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || \ (c >= 'a' && c <= 'f')) #define hexval(c) ((c <= '9') ? c - '0' : ((c <= 'F') ? c - 'A' + 10 : c - 'a' + 10)) /* Strings */ // --------------------------------------------------------------------- char *FskStrDoCopy(const char *str) { char *result; if (NULL == str) return NULL; if (kFskErrNone != FskMemPtrNewFromData(FskStrLen(str) + 1, str, &result)) return NULL; return result; } #if SUPPORT_MEMORY_DEBUG char *FskStrDoCopy_Untracked(const char *str) { char *result; UInt32 len; if (NULL == str) return NULL; len = FskStrLen(str) + 1; if (kFskErrNone != FskMemPtrNew_Untracked(len, &result)) return NULL; FskMemMove(result, str, len); return result; } #endif // --------------------------------------------------------------------- char *FskStrDoCat(const char *strA, const char *strB) { char *result; if (kFskErrNone != FskMemPtrNew(FskStrLen(strA) + FskStrLen(strB) + 1, &result)) return NULL; FskStrCopy(result, strA); FskStrCat(result, strB); return result; } // --------------------------------------------------------------------- UInt32 FskStrLen(const char *str) { #if TARGET_OS_WIN32 || TARGET_OS_MAC || TARGET_OS_LINUX || TARGET_OS_KPL return str ? strlen(str) : 0; #else UInt32 count = 0; if (NULL != str) { while (*str++) count += 1; } return count; #endif } UInt32 FskUnicodeStrLen(const UInt16 *str) { SInt32 count = 0; if (NULL != str) { #if !FSK_MISALIGNED_MEMORY_ACCESS_IS_IMPLEMENTED_IN_HARDWARE if (1 & (UInt32)str) { unsigned char *s = (unsigned char *)str; while (s[0] || s[1]) { s += 2; count += 1; } } else #endif /* FSK_MISALIGNED_MEMORY_ACCESS_IS_IMPLEMENTED_IN_HARDWARE */ while (*str++) count += 1; } return count; } FskErr FskStrListDoCopy(const char *str, char **copy) { return FskMemPtrNewFromData(FskStrListLen(str), str, (FskMemPtr *)copy); } UInt32 FskStrListLen(const char *str) { UInt32 size = 1; if (NULL == str) return 0; while (*str) { UInt32 len = FskStrLen(str) + 1; size += len; str += len; } return size; } SInt32 FskStrListCompare(const char *strA, const char *strB) { SInt32 result; if (!strA || !strB) return -1; // no perfect answer here while (true) { UInt32 len; result = FskStrCompare(strA, strB); if (0 != result) break; len = FskStrLen(strA); if (0 == len) // done break; strA += len + 1; strB += len + 1; } return result; } // --------------------------------------------------------------------- void FskStrCopy(char *result, const char *str) { if (str == NULL ) { if (result != NULL) *result = 0; return; } while (*str) *result++ = *str++; *result = 0; } // --------------------------------------------------------------------- void FskStrNCopy(char *result, const char *str, UInt32 count) { strncpy(result, str, count); } // --------------------------------------------------------------------- void FskStrCat(char *result, const char *str) { if (NULL == str) return; while (*result) result++; FskStrCopy(result, str); } // --------------------------------------------------------------------- void FskStrNCat(char *result, const char *str, UInt32 len) { if (NULL == str) return; while (*result) result++; while (len-- && *str) *result++ = *str++; *result = 0; } // --------------------------------------------------------------------- SInt32 FskStrCompare(const char *s1, const char *s2) { if ((NULL == s1) || (NULL == s2)) { if (s1 == s2) return 0; else return 1; } return strcmp(s1, s2); } // --------------------------------------------------------------------- SInt32 FskStrCompareWithLength(const char *s1, const char *s2, UInt32 n) { if ((NULL == s1) || (NULL == s2)) { if (s1 == s2) return 0; else return 1; } return strncmp(s1, s2, n); } // --------------------------------------------------------------------- SInt32 FskStrCompareCaseInsensitive(const char *s1, const char *s2) { if ((NULL == s1) || (NULL == s2)) { if (s1 == s2) return 0; else return 1; } #if TARGET_OS_WIN32 return _stricmp(s1, s2); #elif TARGET_OS_LINUX || TARGET_OS_MACOSX || TARGET_OS_MAC || TARGET_OS_KPL return strcasecmp(s1, s2); #endif } // --------------------------------------------------------------------- SInt32 FskStrCompareCaseInsensitiveWithLength(const char *s1, const char *s2, UInt32 n) { if ((NULL == s1) || (NULL == s2)) { if (s1 == s2) return 0; else return 1; } #if TARGET_OS_WIN32 return _strnicmp(s1, s2, n); #elif TARGET_OS_LINUX || TARGET_OS_MACOSX || TARGET_OS_MAC || TARGET_OS_KPL return strncasecmp(s1, s2, n); #endif } // --------------------------------------------------------------------- char* FskStrStr(const char *s1, const char *s2) { char *foo; foo = strstr((char *)s1, (char *)s2); return foo; } // --------------------------------------------------------------------- char* FskStrChr(const char *s, char c) { return (char *)strchr(s, c); } char *FskStrRChr(const char *string, char search) { char *result = (char*)string; char *next = (char*)string; while (true) { char *temp = FskStrChr(next, search); if (!temp) break; result = temp; next = temp + 1; } if (next == string) return NULL; else return result; } // --------------------------------------------------------------------- void FskStrNumToStr(SInt32 value, char *str, UInt32 len) { #if TARGET_OS_WIN32 || TARGET_OS_LINUX || TARGET_OS_MACOSX || TARGET_OS_MAC || TARGET_OS_KPL snprintf(str, len, "%ld", value); #else itoa(value, str, len); #endif } // --------------------------------------------------------------------- SInt32 FskStrToNum(const char *str) { return atoi(str); } void FskStrDoubleToStr(double value, char *str, UInt32 len, const char *format) { snprintf(str, len, format ? format : "%f", value); } // --------------------------------------------------------------------- static int baseVal(char a, UInt32 base) { char convChar[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; UInt32 i; char up; up = toupper(a); for (i=0; i<base; i++) { if (convChar[i] == up) return i; } return -1; } FskInt64 FskStrToFskInt64Base(const char *str, UInt32 base) { int len, i, neg = 0, n; FskInt64 accum = 0; char *start; start = FskStrStripHeadSpace(str); if (start[0] == '-') { neg = 1; start++; } else if (start[0] == '+') start++; len = FskStrLen(start); for (i=0; i<len; i++) { n = baseVal(start[i], base); if (n == -1) break; accum *= base; accum += n; } if (neg) return -accum; else return accum; } FskInt64 FskStrToFskInt64(const char *str) { return FskStrToFskInt64Base(str, 10); } // --------------------------------------------------------------------- void FskStrNumToHex(UInt32 value, char *str, UInt32 digits) { UInt32 mask = 0xf, i, v; for (i=0; i<digits; i++) { v = (value & mask) >> (4 * i); mask <<= 4; v = v > 9 ? (v - 10) + 'A' : v + '0'; str[digits - (i+1)] = (char)v; } str[digits] = '\0'; } long FskStrToL(const char *nptr, char **endptr, UInt32 base) { return strtol(nptr, endptr, base); } unsigned long FskStrToUL(const char *nptr, char **endptr, UInt32 base) { return strtoul(nptr, endptr, base); } double FskStrToD(const char *nptr, char **endptr) { return strtod(nptr, endptr); } // --------------------------------------------------------------------- SInt32 FskStrTail(const char *str, const char *tail) { int tailLen, strLen, val; strLen = (int)strlen(str); tailLen =(int)strlen(tail); if (strLen < tailLen) return -1; while (tailLen) { if ((val = (tail[tailLen-1] - str[strLen-1])) != 0) return val; tailLen--; strLen--; } return 0; } // --------------------------------------------------------------------- char *FskStrCopyUntil(char *to, const char *from, char stopChar) { char *foo = (char*)from; while (*foo && (*foo != stopChar)) *to++ = *foo++; *to = '\0'; if (*foo) foo++; return foo; } // --------------------------------------------------------------------- char *FskStrNCopyUntilSpace(char *to, const char *from, int max) { char *foo = (char*)from; while (max && *foo && !FskStrIsSpace(*foo)) { *to++ = *foo++; max--; } *to = '\0'; if (*foo) foo++; return foo; } // --------------------------------------------------------------------- char *FskStrNCopyUntil(char *to, const char *from, int copyMax, char stopChar) { char *foo = (char*)from; while (*foo && copyMax && (*foo != stopChar)) *to++ = *foo++, copyMax--; *to = '\0'; if (*foo) foo++; return foo; } // --------------------------------------------------------------------- char *FskStrNChr(const char *from, UInt32 len, char c) { UInt32 i; const char *foo = from; for (i=0; i < len; i++) if (foo[i] == c) return (char *)(foo + i); return 0L; } // --------------------------------------------------------------------- char *FskStrNStr(const char *from, UInt32 len, const char *str) { char c = *str++; if (c != '\0') { UInt32 n = FskStrLen(str); const char *start = from, *stop; while ((stop = FskStrNChr(start, len, c)) != NULL) { if ((len -= stop + 1 - start) < n) break; if ((n == 0) || (FskStrCompareWithLength(stop + 1, str, n) == 0)) return (char *)stop; start = stop + 1; } } return 0L; } // --------------------------------------------------------------------- char *FskStrStripQuotes(char *a) { int amt; amt = FskStrLen(a); if ((amt > 2) && (*a == '"')) { if (a[amt-1] == '"') { FskMemMove(a, a+1, amt-1); a[amt-2] = '\0'; } } return (char *)a; } // --------------------------------------------------------------------- char *FskStrStripHeadSpace(const char *a) { while (FskStrIsSpace(*a)) a++; return (char *)a; } // --------------------------------------------------------------------- char *FskStrStripTailSpace(char *a) { char *end = NULL, *p; p = a; while (*p) { if (!FskStrIsSpace(*p) && !FskStrIsCRLF(*p)) end = p; p++; } if (end) *++end = '\0'; else *a = '\0'; return a; } // --------------------------------------------------------------------- UInt32 FskStrHexToNum(const char *str, UInt32 num) { UInt32 i, v = 0; char c; for (i=0; i<num; i++) { c = str[i]; if (!ishex(c)) return v; v <<= 4; v += hexval(c); } return v; } // --------------------------------------------------------------------- void FskStrDecodeEscapedChars(const char *inPath, char *outPath) { if (!inPath || !outPath) return; while (*inPath) { if (*inPath == '%') { char c; inPath++; if (inPath[0] && inPath[1]) { c = (char)FskStrHexToNum(inPath, 2); inPath += 2; *outPath++ = c; } else *outPath++ = '%'; } else *outPath++ = *inPath++; } *outPath = '\0'; } // --------------------------------------------------------------------- #define FskStrIsPathDelim(x) (((x) == '\\') || ((x) == '/')) void FskCleanPath(char *path) { char newpath[256]; if (!path) return; #if TARGET_OS_WIN32 (void)_fullpath(newpath, path, 256); #else { char *c = path; char *p = newpath; while (*c) { if (FskStrIsPathDelim(*c) && FskStrIsPathDelim(c[1])) { c++; } else *p++ = *c++; } *p++ = '\0'; } #endif FskStrDecodeEscapedChars(newpath, path); } UInt32 FskStrCountEscapedCharsToEncode(const char *inPath) { const char *p = inPath; char c; UInt32 size = 0; // figure out how big the output string will be while ((c = *p++) != 0) { switch (c) { case ' ': case '\'': case '"': case '%': size += 3; break; default: size += 1; break; } } return size; } void FskStrEncodeEscapedChars(const char *inPath, char *outPath) { const char *p = inPath; char c; char *dest = outPath; static char numToHex[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; // now encode it while ((c = *p++) != 0) { switch (c) { case ' ': case '\'': case '"': case '%': *dest++ = '%'; *dest++ = numToHex[(c >> 4) & 0x0f]; *dest++ = numToHex[c & 0x0f]; break; default: *dest++ = c; break; } } *dest = 0; } FskErr FskStrURLEncode(const char *inPath, char **outPath) { FskErr err; UInt32 size; char *encoded; // figure out how big the output string will be size = FskStrCountEscapedCharsToEncode(inPath); // now encode it err = FskMemPtrNew(size + 1, &encoded); BAIL_IF_ERR(err); *outPath = encoded; FskStrEncodeEscapedChars(inPath, encoded); bail: return err; } Boolean FskStrIsDottedQuad(char *str, int *out) { int num[4]; int cur = 0; char *p, *s; for (s=p=str; *p; p++) { if (cur == 4) return false; if (isdigit(*p)) continue; if (*p == '.') { if ((num[cur] = FskStrToNum(s)) > 255) return false; s = p+1; cur++; } else return false; } if (*p == '\0' && cur < 4) if ((num[cur] = FskStrToNum(s)) > 255) return false; if (cur == 3) { *out = (num[0] << 24) | (num[1] << 16) | (num[2] << 8) | num[3]; return true; } return false; } static FskErr sFskStrParsedUrlRebuild(FskStrParsedUrl urlComp) { FskErr err = kFskErrNone; char *path; int size; if (urlComp->relativeUrl) { urlComp->url = FskStrDoCopy(urlComp->path); } else { path = urlComp->path; if (path[0] == '/') path++; if (urlComp->scheme) size = FskStrLen(urlComp->scheme); else size = 4; size += 3 + FskStrLen(urlComp->host); if (urlComp->specifyPort) size += 1 + 5; size += 1 + FskStrLen(path); err = FskMemPtrNew(size + 1, (FskMemPtr*)(void*)&urlComp->url); BAIL_IF_ERR(err); if (urlComp->scheme) { if (urlComp->specifyPort) snprintf(urlComp->url, size + 1, "%s://%s:%d/%s", urlComp->scheme, urlComp->host, urlComp->port, path); else snprintf(urlComp->url, size + 1, "%s://%s/%s", urlComp->scheme, urlComp->host, path); } else { if (urlComp->specifyPort) snprintf(urlComp->url, size + 1, "http://%s:%d/%s", urlComp->host, urlComp->port, path); else snprintf(urlComp->url, size + 1, "http://%s/%s", urlComp->host, path); } } bail: return err; } FskErr FskStrParseUrl(char *url, FskStrParsedUrl *urlComponents) { FskErr err = kFskErrNone; FskStrParsedUrl urlComp; char *p, *at, *colon, *portStr, *slash; int portNum = 80; Boolean ours = true; if (NULL == url || NULL == urlComponents) return kFskErrParameterError; urlComp = *urlComponents; if (NULL == urlComp) { err = FskMemPtrNew(sizeof(FskStrParsedUrlRecord), &urlComp); BAIL_IF_ERR(err); } else { ours = false; // don't dispose urlComp on failure FskMemPtrDisposeAt((void**)(void*)&urlComp->data); // chuck existing FskMemPtrDisposeAt((void**)(void*)&urlComp->url); // chuck existing } FskMemSet(urlComp, '\0', sizeof(FskStrParsedUrlRecord)); urlComp->data = FskStrDoCopy(url); if (url[0] == '/') { // relative URL? - skip scheme, user/pass, host, port urlComp->relativeUrl = true; p = urlComp->data + 1; } else { p = FskStrStr(urlComp->data, "://"); if (p) { *p++ = '\0'; urlComp->scheme = urlComp->data; if (0 == FskStrCompare("https", urlComp->scheme)) portNum = 443; else if (0 == FskStrCompare("rtsp", urlComp->scheme)) portNum = 554; } else { // no scheme specified -- relative URL? urlComp->scheme = NULL; p = urlComp->data; } while (p && *p && *p == '/') p++; colon = FskStrChr(p, ':'); // look for user:pass@ (hostname, etc.) - must occur before next slash at = FskStrChr(p, '@'); slash = FskStrChr(p, '/'); if ((colon && at) && (!slash || ((colon < slash) && (at < slash)))) { urlComp->username = p; *colon++ = '\0'; urlComp->password = colon; *at++ = '\0'; p = at; } urlComp->host = p; while (p && *p && *p != '/' && *p != ':' && *p != '?') p++; if (p && *p == ':') { *p++ = '\0'; portStr = p; while (p && *p && *p != '/') p++; if (p && *p) *p++ = '\0'; if (portStr) { portNum = FskStrToNum((const char*)portStr); urlComp->specifyPort = true; } } else if (p && *p == '/') *p++ = '\0'; } urlComp->path = p; while (p && *p && *p != '?' /*&& *p != ' ' */) p++; if (p && *p == '?') { *p++ = '\0'; urlComp->params = p; while (p && *p && *p != ' ') p++; if (p) *p++ = '\0'; } /* else if (p && *p == ' ') { *p++ = '\0'; urlComp->params = p; } */ urlComp->port = portNum; if (NULL != urlComp->host) { // host is case-insensitive (RFC 1035). convert to lowercase here so Host header is lower case (or bad things can happen). This is consistent with what browsers (IE, FireFox, Safari) do. p = urlComp->host; while (*p) { char c = *p; if (('A' <= c) && (c <= 'Z')) *p = c + ('a' - 'A'); p += 1; } } err = sFskStrParsedUrlRebuild(urlComp); urlComp->valid = true; *urlComponents = urlComp; bail: if (kFskErrNone != err) { if (ours && urlComp) { FskMemPtrDispose(urlComp->url); FskMemPtrDispose(urlComp->data); FskMemPtrDispose(urlComp); } } return err; } FskErr FskStrParsedUrlSetHost(FskStrParsedUrl urlComponents, char *host) { FskErr err = kFskErrParameterError; if (urlComponents) { FskMemPtrDispose(urlComponents->url); FskMemPtrDispose(urlComponents->host); urlComponents->relativeUrl = false; urlComponents->host = FskStrDoCopy(host); err = sFskStrParsedUrlRebuild(urlComponents); } return err; } FskErr FskStrParsedUrlDispose(FskStrParsedUrl urlComponents) { if (urlComponents) { FskMemPtrDispose(urlComponents->url); FskMemPtrDispose(urlComponents->data); FskMemPtrDispose(urlComponents); } return kFskErrNone; } void FskStrB64EncodeArray(const char *src, UInt32 srcSize, char **pDst, UInt32 *pDstSize, Boolean linefeeds, const char *codeString) { FskErr err = kFskErrNone; char pad = codeString[64]; UInt32 lpos = 0; UInt32 dstSize; char *dst, a, b, c; /* Allocate memory for the base-64-encoded data */ dstSize = (((srcSize + 2) / 3) * 4) + 1; if (linefeeds) dstSize += (dstSize / 72) + 1; if ((err = FskMemPtrNew(dstSize, pDst)) != kFskErrNone) { *pDst = NULL; if (pDstSize) *pDstSize = 0; return; } dst = *pDst; while (srcSize > 2) { a = *src++; b = *src++; c = *src++; *dst++ = codeString[((a & 0xfc) >> 2)]; *dst++ = codeString[((a & 0x3) << 4) | ((b & 0xf0) >> 4)]; *dst++ = codeString[((b & 0xf) << 2) | ((c & 0xc0) >> 6)]; *dst++ = codeString[(c & 0x3f)]; if (linefeeds) { lpos += 4; if (lpos > 72) { *dst++ = '\n'; lpos = 0; } } srcSize -= 3; } if (srcSize == 2) { a = *src++; b = *src++; *dst++ = codeString[((a & 0xfc) >> 2)]; *dst++ = codeString[((a & 0x3) << 4) | ((b & 0xf0) >> 4)]; *dst++ = codeString[((b & 0xf) << 2)]; *dst++ = pad; } else if (srcSize == 1) { a = *src++; *dst++ = codeString[((a & 0xfc) >> 2)]; *dst++ = codeString[((a & 0x3) << 4)]; *dst++ = pad; *dst++ = pad; } if (linefeeds) *dst++ = '\n'; *dst++ = 0; /* NULL termination, so it can be used as a C-string. */ if (pDstSize) *pDstSize = dst - *pDst; /* Calculate an accurate string length */ } void FskStrB64Encode(const char *src, UInt32 srcSize, char **dst, UInt32 *dstSize, Boolean linefeeds) { static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; FskStrB64EncodeArray(src, srcSize, dst, dstSize, linefeeds, b64); }
2.328125
2
2024-11-18T21:10:05.048848+00:00
2021-07-28T17:39:08
f469046df331af23de15fbd5f1f1d90f36b42b9a
{ "blob_id": "f469046df331af23de15fbd5f1f1d90f36b42b9a", "branch_name": "refs/heads/master", "committer_date": "2021-07-28T17:39:08", "content_id": "0a597c7ff69fbba9df98ef915bb3c194164df656", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "edcdab4db6325e5ebe093ff7d90ec57eb5df80a8", "extension": "c", "filename": "hashtable.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 208050020, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2696, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/utils/hashtable.c", "provenance": "stackv2-0065.json.gz:26389", "repo_name": "aasthakm/qapla", "revision_date": "2021-07-28T17:39:08", "revision_id": "f98ca92adbca75fee28587e540b8c851809c7a62", "snapshot_id": "3ddb23b23bff777d102d1b4138d417f7c1f49c54", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/aasthakm/qapla/f98ca92adbca75fee28587e540b8c851809c7a62/utils/hashtable.c", "visit_date": "2021-08-01T00:48:04.903131" }
stackv2
/* * ************************************************************** * Copyright (c) 2017-2022, Aastha Mehta <[email protected]> * All rights reserved. * * This source code is licensed under the BSD-style license found * in the LICENSE file in the root directory of this source tree. * ************************************************************** */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "hashtable.h" hash_table_t * alloc_init_hash_table(int size, hash_fn_t *ht_func_p) { hash_table_t *ht = (hash_table_t *) malloc(sizeof(hash_table_t)); if (!ht) return NULL; int ret = 0; ret = init_hash_table(ht, size, ht_func_p); if (ret == -1) { free(ht); ht = NULL; } return ht; } int init_hash_table(hash_table_t *ht, int size, hash_fn_t *ht_func_p) { if (!ht) return -2; memset(ht, 0, sizeof(hash_table_t)); ht->size = size; ht->ht_func = ht_func_p; ht->table = (list_t *) malloc(sizeof(list_t) * size); if (!ht->table) { return -1; } int i; for (i = 0; i < size; i++) { list_init(&(ht->table[i])); } return 0; } void cleanup_hash_table(hash_table_t *ht) { if (!ht) return; list_t *idx_head, *idx_it, *next_idx_it; hash_entry_t *e; int i; for (i = 0; i < ht->size; i++) { idx_head = &ht->table[i]; idx_it = idx_head->next; while (idx_it != idx_head) { e = list_entry(idx_it, hash_entry_t, next); next_idx_it = idx_it->next; list_remove(idx_it); ht->ht_func->hash_entry_free((void **) &e); idx_it = next_idx_it; } } if (ht->table) free(ht->table); memset(ht, 0, sizeof(hash_table_t)); return; } hash_entry_t * init_hash_entry(void *key, int key_len, void *value, int val_len, int alloc) { hash_entry_t *he = (hash_entry_t *) malloc(sizeof(hash_entry_t)); memset(he, 0, sizeof(hash_entry_t)); if (alloc) { he->key = malloc(key_len); he->val = malloc(val_len); memcpy(he->key, key, key_len); memcpy(he->val, value, val_len); } else { he->key = key; he->val = value; } he->key_len = key_len; he->val_len = val_len; list_init(&he->next); return he; } void add_hash_entry(hash_table_t *ht, int idx, hash_entry_t *e) { list_t *head = &ht->table[idx]; list_insert(head, &e->next); } void * get_hash_value(hash_table_t *ht, int idx, void *key, int keylen, int exact_match) { //int idx = hash(ht, key, keylen); list_t *head = &ht->table[idx]; hash_entry_t *he; hash_fn_t *hfn = ht->ht_func; list_for_each_entry(he, head, next) { if (hfn->hash_val_compare(he->key, key, keylen, exact_match) == HT_SUCCESS) return he->val; } return NULL; } int hash(hash_table_t *ht, void *key, int keylen) { return ht->ht_func->hash_func(key, keylen, ht->size); }
2.71875
3
2024-11-18T21:10:05.121232+00:00
2017-11-16T23:51:10
5531e9ac8d94c659439292a38519e12eccf9fe8f
{ "blob_id": "5531e9ac8d94c659439292a38519e12eccf9fe8f", "branch_name": "refs/heads/master", "committer_date": "2017-11-16T23:51:10", "content_id": "aa003732f9d409c2745f94291ba7e2a9940f22f0", "detected_licenses": [ "MIT" ], "directory_id": "a367c7da850ffe594441d6902313449d723ea765", "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": 111035343, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2258, "license": "MIT", "license_type": "permissive", "path": "/main.c", "provenance": "stackv2-0065.json.gz:26517", "repo_name": "nikooo777/LZSS-de-compressor", "revision_date": "2017-11-16T23:51:10", "revision_id": "9e2880ca83a8c8240a30d5fb92e97f95c1ecd370", "snapshot_id": "aa1aa9665f175f699323361488d1e6e93ca6e58e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nikooo777/LZSS-de-compressor/9e2880ca83a8c8240a30d5fb92e97f95c1ecd370/main.c", "visit_date": "2021-08-14T23:00:01.672968" }
stackv2
/* * main.c * * Created on: Dec 11, 2014 * Author: spoofy */ #include "main.h" #include <stdlib.h> #include <string.h> #include "lzss.h" #include "decompressor.h" //#define DEBUG #define BUFFER_SIZE 8192 int main(int argc, char *argv[]) { #ifdef DEBUG fprintf(stderr, "############Begin Main############\n"); #endif //Checks the number of arguments if (argc != 3) { fprintf(stderr, "Usage: lzss <c/d> <input/output file>\n"); return 1; } if (strcmp("c", argv[1]) == 0) { //input and output initialization FILE *infile, *outfile; char *out_file_name = calloc((strlen(argv[2]) + 5),1); strcat(out_file_name, argv[2]); strcat(out_file_name, ".niko"); //fancy extension //open outfile in write binary append if (!(outfile = fopen(out_file_name, "wba"))) { fprintf(stderr,"Error opening output file! : %s\n",out_file_name); return -1; } free(out_file_name); if (!(infile = fopen(argv[2], "rb"))) { fprintf(stderr,"Error opening input file!: %s\n",argv[2]); return -1; } //variables needed long file_len = 0; long compressed_size = 0; //retrieves the file length //---that's how many bytes we can read--- fseek(infile, 0, SEEK_END); file_len = ftell(infile); fseek(infile, 0, SEEK_SET); //read the data in chunk of BUFFER_SIZE //compress the chunk //write the compressed chunk while (file_len) { unsigned char * inbuffer = malloc(BUFFER_SIZE); int read_count = fread(inbuffer, sizeof(unsigned char), BUFFER_SIZE, infile); unsigned char *outbuffer = lzss(inbuffer, read_count, &compressed_size); fwrite(outbuffer, 1, compressed_size, outfile); #ifdef DEBUG fprintf(stderr, "@@@@@@@@@@Writing data being written to file@@@@@@@@@@@@@\n"); print_hex(outbuffer, compressed_size); for (int i = 0; i < compressed_size; i++) { print_bin(outbuffer[i], 8); } fprintf(stderr, "@@@@@@@@@@END Writing data being written to file@@@@@@@@@@@@@\n"); #endif free(outbuffer); free(inbuffer); file_len -= read_count; } fclose(infile); fclose(outfile); } else if (strcmp("d", argv[1]) == 0) { return decode(argv[2]); } else return -1; #ifdef DEBUG fprintf(stderr, "############End Main############\n"); #endif return 0; }
2.890625
3
2024-11-18T21:10:05.315076+00:00
2023-03-23T05:16:23
dc4f904c07da44009a33ad924008e4ba3af7fe55
{ "blob_id": "dc4f904c07da44009a33ad924008e4ba3af7fe55", "branch_name": "refs/heads/master", "committer_date": "2023-03-27T14:18:46", "content_id": "232f5d05885e8d1a648f895a70ecebe416faac3f", "detected_licenses": [], "directory_id": "3ef2bbccf5b44055169135f52a216c3f78dd9c8c", "extension": "c", "filename": "schema.c", "fork_events_count": 52, "gha_created_at": "2015-08-25T14:21:33", "gha_event_created_at": "2023-03-27T14:19:03", "gha_language": "C", "gha_license_id": "BSD-3-Clause", "github_id": 41367709, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10059, "license": "", "license_type": "permissive", "path": "/src/schema.c", "provenance": "stackv2-0065.json.gz:26773", "repo_name": "eulerto/pgquarrel", "revision_date": "2023-03-23T05:16:23", "revision_id": "80637e44afc68fa226aad8fb90b2cab7c24a39c4", "snapshot_id": "5ea9d188f92f39b494d258844102ea27e2fee720", "src_encoding": "UTF-8", "star_events_count": 369, "url": "https://raw.githubusercontent.com/eulerto/pgquarrel/80637e44afc68fa226aad8fb90b2cab7c24a39c4/src/schema.c", "visit_date": "2023-08-22T07:41:03.138052" }
stackv2
/*---------------------------------------------------------------------- * * pgquarrel -- comparing database schemas * * schema.c * Generate SCHEMA commands * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * CREATE SCHEMA * DROP SCHEMA * ALTER SCHEMA * COMMENT ON SCHEMA * * TODO * * ALTER SCHEMA ... RENAME TO * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * Copyright (c) 2015-2020, Euler Taveira * * --------------------------------------------------------------------- */ #include "schema.h" PQLSchema * getSchemas(PGconn *c, int *n) { PQLSchema *s; char *query; PGresult *res; int i; logNoise("schema: server version: %d", PQserverVersion(c)); if (PQserverVersion(c) >= 90100) /* extension support */ { query = psprintf("SELECT n.oid, nspname, obj_description(n.oid, 'pg_namespace') AS description, pg_get_userbyid(nspowner) AS nspowner, nspacl FROM pg_namespace n WHERE nspname !~ '^pg_' AND nspname <> 'information_schema' %s%s AND NOT EXISTS(SELECT 1 FROM pg_depend d WHERE n.oid = d.objid AND d.deptype = 'e') ORDER BY nspname", include_schema_str, exclude_schema_str); } else { query = psprintf("SELECT n.oid, nspname, obj_description(n.oid, 'pg_namespace') AS description, pg_get_userbyid(nspowner) AS nspowner, nspacl FROM pg_namespace n WHERE nspname !~ '^pg_' AND nspname <> 'information_schema' %s%s ORDER BY nspname", include_schema_str, exclude_schema_str); } res = PQexec(c, query); pfree(query); if (PQresultStatus(res) != PGRES_TUPLES_OK) { logError("query failed: %s", PQresultErrorMessage(res)); PQclear(res); PQfinish(c); /* XXX leak another connection? */ exit(EXIT_FAILURE); } *n = PQntuples(res); if (*n > 0) s = (PQLSchema *) malloc(*n * sizeof(PQLSchema)); else s = NULL; logDebug("number of schemas in server: %d", *n); for (i = 0; i < *n; i++) { char *withoutescape; s[i].oid = strtoul(PQgetvalue(res, i, PQfnumber(res, "oid")), NULL, 10); s[i].schemaname = strdup(PQgetvalue(res, i, PQfnumber(res, "nspname"))); if (PQgetisnull(res, i, PQfnumber(res, "description"))) s[i].comment = NULL; else { withoutescape = PQgetvalue(res, i, PQfnumber(res, "description")); s[i].comment = PQescapeLiteral(c, withoutescape, strlen(withoutescape)); if (s[i].comment == NULL) { logError("escaping comment failed: %s", PQerrorMessage(c)); PQclear(res); PQfinish(c); /* XXX leak another connection? */ exit(EXIT_FAILURE); } } s[i].owner = strdup(PQgetvalue(res, i, PQfnumber(res, "nspowner"))); if (PQgetisnull(res, i, PQfnumber(res, "nspacl"))) s[i].acl = NULL; else s[i].acl = strdup(PQgetvalue(res, i, PQfnumber(res, "nspacl"))); /* * Security labels are not assigned here (see getSchemaSecurityLabels), * but default values are essential to avoid having trouble in * freeSchemas. */ s[i].nseclabels = 0; s[i].seclabels = NULL; logDebug("schema \"%s\"", s[i].schemaname); } PQclear(res); return s; } void getSchemaSecurityLabels(PGconn *c, PQLSchema *s) { char *query; PGresult *res; int i; if (PQserverVersion(c) < 90100) { logWarning("ignoring security labels because server does not support it"); return; } query = psprintf("SELECT provider, label FROM pg_seclabel s INNER JOIN pg_class c ON (s.classoid = c.oid) WHERE c.relname = 'pg_namespace' AND s.objoid = %u ORDER BY provider", s->oid); res = PQexec(c, query); pfree(query); if (PQresultStatus(res) != PGRES_TUPLES_OK) { logError("query failed: %s", PQresultErrorMessage(res)); PQclear(res); PQfinish(c); /* XXX leak another connection? */ exit(EXIT_FAILURE); } s->nseclabels = PQntuples(res); if (s->nseclabels > 0) s->seclabels = (PQLSecLabel *) malloc(s->nseclabels * sizeof(PQLSecLabel)); else s->seclabels = NULL; logDebug("number of security labels in schema \"%s\": %d", s->schemaname, s->nseclabels); for (i = 0; i < s->nseclabels; i++) { char *withoutescape; s->seclabels[i].provider = strdup(PQgetvalue(res, i, PQfnumber(res, "provider"))); withoutescape = PQgetvalue(res, i, PQfnumber(res, "label")); s->seclabels[i].label = PQescapeLiteral(c, withoutescape, strlen(withoutescape)); if (s->seclabels[i].label == NULL) { logError("escaping label failed: %s", PQerrorMessage(c)); PQclear(res); PQfinish(c); /* XXX leak another connection? */ exit(EXIT_FAILURE); } } PQclear(res); } void freeSchemas(PQLSchema *s, int n) { if (n > 0) { int i; for (i = 0; i < n; i++) { int j; free(s[i].schemaname); if (s[i].comment) PQfreemem(s[i].comment); if (s[i].acl) free(s[i].acl); free(s[i].owner); /* security labels */ for (j = 0; j < s[i].nseclabels; j++) { free(s[i].seclabels[j].provider); PQfreemem(s[i].seclabels[j].label); } if (s[i].seclabels) free(s[i].seclabels); } free(s); } } void dumpDropSchema(FILE *output, PQLSchema *s) { char *schemaname = formatObjectIdentifier(s->schemaname); fprintf(output, "\n\n"); fprintf(output, "DROP SCHEMA %s;", schemaname); free(schemaname); } void dumpCreateSchema(FILE *output, PQLSchema *s) { char *schemaname = formatObjectIdentifier(s->schemaname); fprintf(output, "\n\n"); fprintf(output, "CREATE SCHEMA %s;", schemaname); /* comment */ if (options.comment && s->comment != NULL) { fprintf(output, "\n\n"); fprintf(output, "COMMENT ON SCHEMA %s IS %s;", schemaname, s->comment); } /* security labels */ if (options.securitylabels && s->nseclabels > 0) { int i; for (i = 0; i < s->nseclabels; i++) { fprintf(output, "\n\n"); fprintf(output, "SECURITY LABEL FOR %s ON SCHEMA %s IS %s;", s->seclabels[i].provider, schemaname, s->seclabels[i].label); } } /* owner */ if (options.owner) { char *owner = formatObjectIdentifier(s->owner); fprintf(output, "\n\n"); fprintf(output, "ALTER SCHEMA %s OWNER TO %s;", schemaname, owner); free(owner); } /* privileges */ /* XXX second s->obj isn't used. Add an invalid PQLObject? */ if (options.privileges) { PQLObject tmp; /* * don't use schemaname because objects without qualification use * objectname as name. * */ tmp.schemaname = NULL; tmp.objectname = s->schemaname; dumpGrantAndRevoke(output, PGQ_SCHEMA, &tmp, &tmp, NULL, s->acl, NULL, NULL); } free(schemaname); } void dumpAlterSchema(FILE *output, PQLSchema *a, PQLSchema *b) { char *schemaname1 = formatObjectIdentifier(a->schemaname); char *schemaname2 = formatObjectIdentifier(b->schemaname); if (strcmp(a->schemaname, b->schemaname) != 0) { fprintf(output, "\n\n"); fprintf(output, "ALTER SCHEMA %s RENAME TO %s;", schemaname1, schemaname2); } /* comment */ if (options.comment) { if ((a->comment == NULL && b->comment != NULL) || (a->comment != NULL && b->comment != NULL && strcmp(a->comment, b->comment) != 0)) { fprintf(output, "\n\n"); fprintf(output, "COMMENT ON SCHEMA %s IS %s;", schemaname2, b->comment); } else if (a->comment != NULL && b->comment == NULL) { fprintf(output, "\n\n"); fprintf(output, "COMMENT ON SCHEMA %s IS NULL;", schemaname2); } } /* security labels */ if (options.securitylabels) { if (a->seclabels == NULL && b->seclabels != NULL) { int i; for (i = 0; i < b->nseclabels; i++) { fprintf(output, "\n\n"); fprintf(output, "SECURITY LABEL FOR %s ON SCHEMA %s IS %s;", b->seclabels[i].provider, schemaname2, b->seclabels[i].label); } } else if (a->seclabels != NULL && b->seclabels == NULL) { int i; for (i = 0; i < a->nseclabels; i++) { fprintf(output, "\n\n"); fprintf(output, "SECURITY LABEL FOR %s ON SCHEMA %s IS NULL;", a->seclabels[i].provider, schemaname1); } } else if (a->seclabels != NULL && b->seclabels != NULL) { int i, j; i = j = 0; while (i < a->nseclabels || j < b->nseclabels) { if (i == a->nseclabels) { fprintf(output, "\n\n"); fprintf(output, "SECURITY LABEL FOR %s ON SCHEMA %s IS %s;", b->seclabels[j].provider, schemaname2, b->seclabels[j].label); j++; } else if (j == b->nseclabels) { fprintf(output, "\n\n"); fprintf(output, "SECURITY LABEL FOR %s ON SCHEMA %s IS NULL;", a->seclabels[i].provider, schemaname1); i++; } else if (strcmp(a->seclabels[i].provider, b->seclabels[j].provider) == 0) { if (strcmp(a->seclabels[i].label, b->seclabels[j].label) != 0) { fprintf(output, "\n\n"); fprintf(output, "SECURITY LABEL FOR %s ON SCHEMA %s IS %s;", b->seclabels[j].provider, schemaname2, b->seclabels[j].label); } i++; j++; } else if (strcmp(a->seclabels[i].provider, b->seclabels[j].provider) < 0) { fprintf(output, "\n\n"); fprintf(output, "SECURITY LABEL FOR %s ON SCHEMA %s IS NULL;", a->seclabels[i].provider, schemaname1); i++; } else if (strcmp(a->seclabels[i].provider, b->seclabels[j].provider) > 0) { fprintf(output, "\n\n"); fprintf(output, "SECURITY LABEL FOR %s ON SCHEMA %s IS %s;", b->seclabels[j].provider, schemaname2, b->seclabels[j].label); j++; } } } } /* owner */ if (options.owner) { if (strcmp(a->owner, b->owner) != 0) { char *owner = formatObjectIdentifier(b->owner); fprintf(output, "\n\n"); fprintf(output, "ALTER SCHEMA %s OWNER TO %s;", schemaname2, owner); free(owner); } } /* privileges */ if (options.privileges) { PQLObject tmpa, tmpb; /* * don't use schemaname because objects without qualification use * objectname as name. * */ tmpa.schemaname = NULL; tmpa.objectname = a->schemaname; tmpb.schemaname = NULL; tmpb.objectname = b->schemaname; if (a->acl != NULL || b->acl != NULL) dumpGrantAndRevoke(output, PGQ_SCHEMA, &tmpa, &tmpb, a->acl, b->acl, NULL, NULL); } free(schemaname1); free(schemaname2); }
2.0625
2
2024-11-18T21:10:05.595547+00:00
2017-09-09T13:48:09
862a6ea312a5ebc70bc7f6fae7ee365c4b0590c8
{ "blob_id": "862a6ea312a5ebc70bc7f6fae7ee365c4b0590c8", "branch_name": "refs/heads/master", "committer_date": "2017-09-09T13:48:09", "content_id": "a0290e50a6adef0195fac74c4520c85b820bdbd3", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e300b6c991a4c2861d93d334a0c2c0355994514a", "extension": "c", "filename": "atrshmlogimpl_create.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 73613273, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4151, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/impls/atrshmlogimpl_create.c", "provenance": "stackv2-0065.json.gz:27030", "repo_name": "atrsoftgmbh/atrshmlog", "revision_date": "2017-09-09T13:48:09", "revision_id": "4ca1a2cc6ff26890a02d74db378e597353f197d3", "snapshot_id": "b440ce553b9433458860b744b9df2392cfb26651", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/atrsoftgmbh/atrshmlog/4ca1a2cc6ff26890a02d74db378e597353f197d3/src/impls/atrshmlogimpl_create.c", "visit_date": "2020-07-31T01:21:52.643093" }
stackv2
#include "../atrshmlog_internal.h" #if ATRSHMLOG_PLATFORM_LINUX_X86_64_GCC == 1 \ || ATRSHMLOG_PLATFORM_CYGWIN_X86_64_GCC == 1 \ || ATRSHMLOG_PLATFORM_BSD_AMD64_CLANG == 1 \ || ATRSHMLOG_PLATFORM_BSD_AMD64_GCC == 1 \ || ATRSHMLOG_PLATFORM_SOLARIS_X86_64_GCC == 1 /** The shm stuff */ # include <sys/shm.h> #endif /*******************************************************************/ /** * \file atrshmlogimpl_create.c */ /** * \n Main code: * * \brief We create the shm . * * On error we deliver a -x, else a valid positive shmid. * * This uses the key from external source, normally a parameter * to the program for a number. * * Key is a 32 bit value. * * test t_create.c */ int atrshmlog_create(const atrshmlog_key_t i_key, const int i_count) { ATRSHMLOGSTAT(atrshmlog_counter_create); #if ATRSHMLOG_PLATFORM_LINUX_X86_64_GCC == 1 if (i_key == 0 || i_key == IPC_PRIVATE) { ATRSHMLOGSTAT( atrshmlog_counter_create_abort1); return atrshmlog_error_create_1; } #endif #if ATRSHMLOG_PLATFORM_CYGWIN_X86_64_GCC == 1 if (i_key == 0 || i_key == IPC_PRIVATE) { ATRSHMLOGSTAT( atrshmlog_counter_create_abort1); return atrshmlog_error_create_1; } #endif #if ATRSHMLOG_PLATFORM_MINGW_X86_64_GCC == 1 if (i_key < 1 || i_key > 32) { ATRSHMLOGSTAT( atrshmlog_counter_create_abort1); return atrshmlog_error_create_1; } #endif #if ATRSHMLOG_PLATFORM_BSD_AMD64_CLANG == 1 if (i_key == 0 || i_key == IPC_PRIVATE) { ATRSHMLOGSTAT( atrshmlog_counter_create_abort1); return atrshmlog_error_create_1; } #endif #if ATRSHMLOG_PLATFORM_BSD_AMD64_GCC == 1 if (i_key == 0 || i_key == IPC_PRIVATE) { ATRSHMLOGSTAT( atrshmlog_counter_create_abort1); return atrshmlog_error_create_1; } #endif #if ATRSHMLOG_PLATFORM_SOLARIS_X86_64_GCC == 1 if (i_key == 0 || i_key == IPC_PRIVATE) { ATRSHMLOGSTAT( atrshmlog_counter_create_abort1); return atrshmlog_error_create_1; } #endif /* At least ATRSHMLOGBUFFER_MINCOUNT .. */ if (i_count < ATRSHMLOGBUFFER_MINCOUNT) { ATRSHMLOGSTAT( atrshmlog_counter_create_abort2); return atrshmlog_error_create_2; } /* Max ATRSHMLOGBUFFER_MAXCOUNT buffers */ if (i_count > ATRSHMLOGBUFFER_MAXCOUNT) { ATRSHMLOGSTAT( atrshmlog_counter_create_abort3); return atrshmlog_error_create_3; } /* We calc the buffer size. * Its a fixed part for our infos and a variabel count of * buffers. * Some systems dont have much memory for a shm buffer, * some have... * So simply try to check for the size that is possible with the * double number check ... */ const int save = 256 ; size_t wantedsize = sizeof (atrshmlog_area_t) + (i_count - ATRSHMLOGBUFFER_MINCOUNT) * sizeof( atrshmlog_buffer_t) + (i_count * ATRSHMLOGBUFFER_INFOSIZE + save); #if ATRSHMLOG_PLATFORM_LINUX_X86_64_GCC == 1 int shmflg = IPC_CREAT | IPC_EXCL; shmflg |= ATRSHMLOG_ACCESS; int result_shmget = shmget(i_key, wantedsize, shmflg); #endif #if ATRSHMLOG_PLATFORM_CYGWIN_X86_64_GCC == 1 int shmflg = IPC_CREAT | IPC_EXCL; shmflg |= ATRSHMLOG_ACCESS; int result_shmget = shmget(i_key, wantedsize, shmflg); #endif #if ATRSHMLOG_PLATFORM_MINGW_X86_64_GCC == 1 int already; int result_shmget = atrshmlog_create_mapped_file(i_key, wantedsize, &already); #endif #if ATRSHMLOG_PLATFORM_BSD_AMD64_CLANG == 1 int shmflg = IPC_CREAT | IPC_EXCL; shmflg |= ATRSHMLOG_ACCESS; int result_shmget = shmget(i_key, wantedsize, shmflg); #endif #if ATRSHMLOG_PLATFORM_BSD_AMD64_GCC == 1 int shmflg = IPC_CREAT | IPC_EXCL; shmflg |= ATRSHMLOG_ACCESS; int result_shmget = shmget(i_key, wantedsize, shmflg); #endif #if ATRSHMLOG_PLATFORM_SOLARIS_X86_64_GCC == 1 int shmflg = IPC_CREAT; shmflg |= ATRSHMLOG_ACCESS; int result_shmget = shmget(i_key, wantedsize, shmflg); #endif if (result_shmget == -1) { ATRSHMLOGSTAT( atrshmlog_counter_create_abort4); return atrshmlog_error_create_4; } return result_shmget; }
2.109375
2
2024-11-18T21:10:05.777875+00:00
2016-11-22T09:46:53
2c749cade6c613d4df4d2f8a7ebed91bfb71fc60
{ "blob_id": "2c749cade6c613d4df4d2f8a7ebed91bfb71fc60", "branch_name": "refs/heads/master", "committer_date": "2016-11-22T09:46:53", "content_id": "a1d8b61abfd78dd25b364ea043a41fd01a153a09", "detected_licenses": [ "MIT" ], "directory_id": "c9d316b14d4b7bbfdb9629aec5e5428f2e627ee2", "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": 68706898, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 572, "license": "MIT", "license_type": "permissive", "path": "/drivers/DHT11_2560_C/DHT11_2560_C/main.c", "provenance": "stackv2-0065.json.gz:27289", "repo_name": "charlieshao5189/ModenEmbeddedProgramingLabWorks", "revision_date": "2016-11-22T09:46:53", "revision_id": "e7004dd6cb71ebde31015b2ca5d678ceec069e99", "snapshot_id": "f06c30da6344300710b82a3076e2464b766877ef", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/charlieshao5189/ModenEmbeddedProgramingLabWorks/e7004dd6cb71ebde31015b2ca5d678ceec069e99/drivers/DHT11_2560_C/DHT11_2560_C/main.c", "visit_date": "2021-01-24T23:42:00.981755" }
stackv2
/* * DHT11_2560_C.c * * Created: 11/3/2016 8:18:34 PM * Author : charlie */ #include <avr/io.h> #include "driver/uart.h" #include "driver/dht.h" #define F_CPU 16000000UL #include <util/delay.h> int main(void) { int8_t humidity; int8_t temperature; USART0_SETUP_9600_BAUD_ASSUME_1MHz_CLOCK(); fprintf(USART,"Reading temperature and humidity...\n"); while (1) { dht_gettemperaturehumidity(&temperature, &humidity); fprintf(USART,"temperature:%d,humidity:%d\n\t",temperature,humidity); _delay_ms(1000); } }
2.546875
3
2024-11-18T21:10:05.856449+00:00
2019-02-03T18:55:26
e9fd49b700312afe1f884a7e45391d2cd3eaa3ee
{ "blob_id": "e9fd49b700312afe1f884a7e45391d2cd3eaa3ee", "branch_name": "refs/heads/master", "committer_date": "2019-02-03T18:55:26", "content_id": "0b75bcdbba46bcae8f659511de7910ce93ee0562", "detected_licenses": [ "MIT" ], "directory_id": "5415b5c6742697f08ed88317534c62198c3b74b4", "extension": "h", "filename": "llab_dt.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": 6848, "license": "MIT", "license_type": "permissive", "path": "/llab/cpu/llab_dt.h", "provenance": "stackv2-0065.json.gz:27417", "repo_name": "ShawPrasenjit/Learning-Lab-C-Library", "revision_date": "2019-02-03T18:55:26", "revision_id": "4a60f0f29454b1b6e26bb9eb5c8ff6cde6afbc76", "snapshot_id": "23ceb8e5033a3286e653742f7407d2d9193a6f57", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ShawPrasenjit/Learning-Lab-C-Library/4a60f0f29454b1b6e26bb9eb5c8ff6cde6afbc76/llab/cpu/llab_dt.h", "visit_date": "2020-04-21T21:40:41.750071" }
stackv2
#ifndef __LLAB_DT_H__ #define __LLAB_DT_H__ #include <stdio.h> #include <stdlib.h> #include <string.h> #define CONDITION_A(x,y) (x > y) #define CONDITION_B(x,y) (x >= y) #define CONDITION_C(x,y) (x == y) #define CONDITION_D(x,y) (x <= y) #define CONDITION_E(x,y) (x < y) #define CONDITION_F(x,y) (!strcmp(x,y)) typedef struct decision_tree { int number_instances;// Number of total instances int char_feature_number, char_labels_number; // feature_number = 0 no char features, labels_number = 0 no char labels int int_feature_number, int_labels_number; // feature_number = 0 no int features, labels_number = 0 no int labels int float_feature_number, float_labels_number; // feature_number = 0 no char features, labels_number = 0 no char labels int char_condition_flag;//if the son is created with a char condition on char features (indicates on which char feature it's the condition) int int_condition_flag;//if the son is created with a float condition on float features (indicates on which char feature it's the condition) int float_condition_flag;//if the son is created with an int condition on int features (indicates on which int feature it's the condition) int unwanted_char_size; int unwanted_float_size; int unwanted_int_size; int char_second_dimension_max_size; char** char_features;//(number_instances*different_features)*char_second_dimension_max_size int* int_features;//number_instances*different_features float* float_features;//number_instances*different_features char** char_labels;//(number_instances*different_labels)*char_second_dimension_max_size int* int_labels;//(number_instances*different_labels) float* float_labels;//(number_instances*different_labels) float impurity; float conditional_threshold; char* conditional_string; char** unwanted_conditional_char_list//unwanted_char_size*char_second_dimension_max_size int* unwanted_conditional_int_list//unwanted_int_size float* unwanted_conditional_float_list//unwanted_float_size decision_tree** sons; } decision_tree; // Functions defined in utils.c float r2(); float drand (); float random_normal (); float random_general_gaussian(float mean, float n); float random_general_gaussian_xavier_init(float mean, float n); void get_dropout_array(int size, float* mask, float* input, float* output); //can be transposed in opencl void set_dropout_mask(int size, float* mask, float threshold); //can be transposed in opencl void ridge_regression(float *dw, float w, float lambda, int n); int read_files(char** name, char* directory); char* itoa(int i, char b[]); int shuffle_char_matrix(char** m,int n); int bool_is_real(float d); int shuffle_float_matrix(float** m,int n); int shuffle_int_matrix(int** m,int n); int shuffle_char_matrices(char** m,char** m1,int n); int shuffle_float_matrices(float** m,float** m1,int n); int shuffle_int_matrices(int** m,int** m1,int n); void read_file_in_char_vector(char** ksource, char* fname, int* size); void dot1D(float* input1, float* input2, float* output, int size); //can be transposed in opencl void copy_array(float* input, float* output, int size);//can be transposed in opencl void sum1D(float* input1, float* input2, float* output, int size);//can be transposed in opencl void mul_value(float* input, float value, float* output, int dimension);//can be transposed in opencl void update_residual_layer_nesterov(model* m, float lr, float momentum, int mini_batch_size);//can be transposed in opencl void update_residual_layer_nesterov_bmodel(bmodel* m, float lr, float momentum, int mini_batch_size);//can be transposed in opencl void update_convolutional_layer_nesterov(model* m, float lr, float momentum, int mini_batch_size);//can be transposed in opencl void update_convolutional_layer_nesterov_bmodel(bmodel* m, float lr, float momentum, int mini_batch_size);//can be transposed in opencl void update_fully_connected_layer_nesterov(model* m, float lr, float momentum, int mini_batch_size);//can be transposed in opencl void update_fully_connected_layer_nesterov_bmodel(bmodel* m, float lr, float momentum, int mini_batch_size);//can be transposed in opencl void sum_residual_layers_partial_derivatives(model* m, model* m2, model* m3);//can be transoposed in opencl void sum_residual_layers_partial_derivatives_bmodel(bmodel* m, bmodel* m2, bmodel* m3);//can be transoposed in opencl void sum_convolutional_layers_partial_derivatives(model* m, model* m2, model* m3);//can be transoposed in opencl void sum_convolutional_layers_partial_derivatives_bmodel(bmodel* m, bmodel* m2, bmodel* m3);//can be transoposed in opencl void sum_fully_connected_layers_partial_derivatives(model* m, model* m2, model* m3);//can be transoposed in opencl void sum_fully_connected_layers_partial_derivatives_bmodel(bmodel* m, bmodel* m2, bmodel* m3);//can be transoposed in opencl void update_residual_layer_adam(model* m, float lr, int mini_batch_size, float b1, float b2);//can be transoposed in opencl void update_residual_layer_adam_bmodel(bmodel* m, float lr, int mini_batch_size, float b1, float b2);//can be transoposed in opencl void update_convolutional_layer_adam(model* m, float lr, int mini_batch_size, float b1, float b2);//can be transoposed in opencl void update_convolutional_layer_adam_bmodel(bmodel* m, float lr, int mini_batch_size, float b1, float b2);//can be transoposed in opencl void update_fully_connected_layer_adam(model* m, float lr, int mini_batch_size, float b1, float b2);//can be transoposed in opencl void update_fully_connected_layer_adam_bmodel(bmodel* m, float lr, int mini_batch_size, float b1, float b2);//can be transoposed in opencl void add_l2_residual_layer(model* m,int total_number_weights,float lambda);//can be transoposed in opencl void add_l2_residual_layer_bmodel(bmodel* m,int total_number_weights,float lambda);//can be transoposed in opencl void add_l2_convolutional_layer(model* m,int total_number_weights,float lambda);//can be transoposed in opencl void add_l2_convolutional_layer_bmodel(bmodel* m,int total_number_weights,float lambda);//can be transoposed in opencl void add_l2_fully_connected_layer(model* m,int total_number_weights,float lambda);//can be transoposed in opencl void add_l2_fully_connected_layer_bmodel(bmodel* m,int total_number_weights,float lambda);//can be transoposed in opencl int shuffle_char_matrices_float_int_vectors(char** m,char** m1,float* f, int* v,int n); void copy_char_array(char* input, char* output, int size); int shuffle_char_matrices_float_int_int_vectors(char** m,char** m1,float* f, int* v, int* v2, int n); void update_batch_normalized_layer_nesterov_bmodel(bmodel* m, float lr, float momentum, int mini_batch_size); void update_batch_normalized_layer_adam_bmodel(bmodel* m, float lr, int mini_batch_size, float b1, float b2); #endif __LLAB_DT_H__
2.234375
2
2024-11-18T21:10:05.935867+00:00
2021-06-17T17:21:14
c3dc561634fb23d58fb56f78d37ef71906a5143e
{ "blob_id": "c3dc561634fb23d58fb56f78d37ef71906a5143e", "branch_name": "refs/heads/master", "committer_date": "2021-06-17T17:21:14", "content_id": "2a7c8be0553ea16851e1661a93bb011a21d4358f", "detected_licenses": [ "Unlicense" ], "directory_id": "66333ba2e93127954a825fca475d808adfd73451", "extension": "c", "filename": "kmbint.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 269973547, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13594, "license": "Unlicense", "license_type": "permissive", "path": "/src/kmbint.c", "provenance": "stackv2-0065.json.gz:27546", "repo_name": "mexok/kmbint", "revision_date": "2021-06-17T17:21:14", "revision_id": "5dd1adc1399aaf6d9a3432cb2b33db6fc37446d2", "snapshot_id": "27fa37cbd26be5eba0f164eaf6950b4c41bd62ed", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/mexok/kmbint/5dd1adc1399aaf6d9a3432cb2b33db6fc37446d2/src/kmbint.c", "visit_date": "2023-05-30T11:40:09.997598" }
stackv2
#include <string.h> #include <assert.h> #include <kmbint.h> typedef void (*divide_fn_t)(char *rest_num, size_t len_rest_num, char **divs, size_t len_divs, char *bint_out); void kmbint_add(char *bint, const char *to_add) { size_t len_bint = strlen(bint); size_t len_to_add = strlen(to_add); if (len_to_add > len_bint) { size_t len_to_zero_fill = len_to_add - len_bint; memmove(bint + len_to_zero_fill, bint, len_bint + 1); memset(bint, '0', len_to_zero_fill); len_bint += len_to_zero_fill; } const char *p_to_add = to_add + len_to_add; char remainder = 0; char *p_bint = bint + len_bint; while (p_to_add != to_add) { --p_to_add; --p_bint; *p_bint += remainder + (*p_to_add - '0'); if (*p_bint > '9') { *p_bint -= 10; remainder = 1; } else { remainder = 0; } } if (remainder > 0) { memmove(bint + 1, bint, len_bint + 1); bint[0] = '1'; } } void kmbint_sub(char *bint, const char *to_diff) { assert(kmbint_gte(bint, to_diff)); size_t len_bint = strlen(bint); size_t len_to_diff = strlen(to_diff); char *p_bint = bint + len_bint; const char *p_to_diff = to_diff + len_to_diff; char borrowed = 0; while (p_to_diff != to_diff) { --p_to_diff; --p_bint; if (*p_bint < *p_to_diff + borrowed) { *p_bint = *p_bint + 10 - *p_to_diff - borrowed + '0'; borrowed = 1; } else { *p_bint = *p_bint - *p_to_diff - borrowed + '0'; borrowed = 0; } } while (borrowed == 1) { --p_bint; if (*p_bint == '0') { *p_bint = '9'; } else { --*p_bint; borrowed = 0; } } p_bint = bint; size_t num_leading_zeros = 0; while (*p_bint == '0') { ++num_leading_zeros; ++p_bint; } if (num_leading_zeros == len_bint) { --num_leading_zeros; } len_bint -= num_leading_zeros; memmove(bint, bint + num_leading_zeros, len_bint + 1); } static void subtract_zero_char_value(char *bint) { while (*bint != '\0') { *bint -= '0'; ++bint; } } static void multiply_buffer(char *buffer, size_t len_buffer, char to_mul) { char remainder = 0; buffer += len_buffer; while (true) { --buffer; *buffer = *buffer * to_mul + remainder; remainder = *buffer / 10; *buffer %= 10; if (len_buffer > 0) { --len_buffer; } else { break; } } } static void add_buffer(char *buffer, const char *to_add, size_t len_buffer) { buffer += len_buffer; to_add += len_buffer; char remainder = 0; while (len_buffer > 0) { --buffer; --to_add; *buffer += *to_add + remainder; if (*buffer >= 10) { *buffer -= 10; remainder = 1; } else { remainder = 0; } --len_buffer; } } static void sub_buffer(char *buffer, const char *to_sub, size_t len_buffer) { buffer += len_buffer; to_sub += len_buffer; char borrow = 0; while (len_buffer-- > 0) { *--buffer -= *--to_sub + borrow; if (*buffer < 0) { *buffer += 10; borrow = 1; } else { borrow = 0; } } } void kmbint_mul(char *bint, const char *to_mul) { size_t len_bint = strlen(bint); size_t len_to_mul = strlen(to_mul); size_t len_buffer = len_bint + len_to_mul; subtract_zero_char_value(bint); char result_buffer[len_buffer]; memset(result_buffer, 0, len_buffer); const char *p_to_mul = to_mul + len_to_mul; char to_add_buffer[len_buffer]; char *p_to_insert_num = to_add_buffer + len_to_mul + 1; char mul; while (to_mul != p_to_mul) { --p_to_mul; --p_to_insert_num; mul = *p_to_mul - '0'; if (mul > 0) { memset(to_add_buffer, 0, len_buffer); memcpy(p_to_insert_num, bint, len_bint); if (mul > 1) { multiply_buffer(to_add_buffer, len_buffer, mul); } add_buffer(result_buffer, to_add_buffer, len_buffer); } } char *p_result = result_buffer; while (len_buffer > 0) { if (*p_result == 0) { ++p_result; --len_buffer; } else { break; } } if (len_buffer == 0) { bint[0] = '0'; bint[1] = '\0'; } else { while (len_buffer > 0) { *bint = *p_result + '0'; bint++; ++p_result; --len_buffer; } *bint = '\0'; } } static bool check_divider(char *num, size_t num_len, char *div) { while (num_len > 0) { if (*num > *div) { return true; } else if (*num < *div) { return false; } ++num; ++div; --num_len; } return true; } static char find_divider_mul(char *num, size_t num_len, char **divs) { if (check_divider(num, num_len, divs[4])) { if (check_divider(num, num_len, divs[6])) { if (check_divider(num, num_len, divs[7])) { if (check_divider(num, num_len, divs[8])) { return 9; } else { return 8; } } else { return 7; } } else { if (check_divider(num, num_len, divs[5])) { return 6; } else { return 5; } } } else { if (check_divider(num, num_len, divs[2])) { if (check_divider(num, num_len, divs[3])) { return 4; } else { return 3; } } else { if (check_divider(num, num_len, divs[0])) { if (check_divider(num, num_len, divs[1])) { return 2; } else { return 1; } } else { return 0; } } } } static void setup_buffer_from_num(char *buffer, const char *num, size_t len_num) { while (len_num > 0) { *buffer++ = *num++ - '0'; --len_num; } } static void divide_fn_impl_default(char *rest_num, size_t len_rest_num, char **divs, size_t len_divs, char *bint_out) { bool is_bint_started = false; while (len_rest_num > len_divs) { char mul = find_divider_mul(rest_num, len_divs, divs); if (mul > 0) { is_bint_started = true; *bint_out++ = mul + '0'; sub_buffer(rest_num, divs[mul - 1], len_divs); } else if (is_bint_started) { *bint_out++ = '0'; } ++rest_num; --len_rest_num; } if (len_rest_num < len_divs) { *bint_out++ = '0'; } else { char mul = find_divider_mul(rest_num, len_divs, divs); *bint_out++ = '0' + mul; } *bint_out = '\0'; } static void divide(char *bint, const char *to_div, divide_fn_t divide_fn) { size_t len_bint = strlen(bint); size_t len_to_div = strlen(to_div); // The len of the dividers can be at max 1 digit bigger then the original number size_t len_divs = len_to_div + 1; char div_data[9 * len_divs]; char *divs[9]; divs[0] = div_data; setup_buffer_from_num(divs[0] + 1, to_div, len_to_div); divs[0][0] = 0; for (int i = 1; i < 9; ++i) { divs[i] = &div_data[i * len_divs]; memcpy(divs[i], divs[i - 1], len_divs); add_buffer(divs[i], divs[0], len_divs); } // rest_num must always start with zero to work correctly char rest_num[len_bint + 1]; rest_num[0] = 0; setup_buffer_from_num(rest_num + 1, bint, len_bint); divide_fn(rest_num, len_bint + 1, divs, len_divs, bint); } void kmbint_div(char *bint, const char *to_div) { assert(kmbint_gt(to_div, "0")); divide(bint, to_div, divide_fn_impl_default); } static void divide_fn_impl_mod(char *rest_num, size_t len_rest_num, char **divs, size_t len_divs, char *bint_out) { while (len_rest_num >= len_divs) { char mul = find_divider_mul(rest_num, len_divs, divs); if (mul > 0) { sub_buffer(rest_num, divs[mul - 1], len_divs); } ++rest_num; --len_rest_num; } bool is_bint_started = false; while (len_rest_num > 0) { if (*rest_num > 0) { is_bint_started = true; *bint_out++ = *rest_num + '0'; } else if (is_bint_started) { *bint_out++ = '0'; } ++rest_num; --len_rest_num; } if (is_bint_started == false) { *bint_out++ = '0'; } *bint_out = '\0'; } void kmbint_mod(char *bint, const char *to_mod) { assert(kmbint_gt(to_mod, "0")); divide(bint, to_mod, divide_fn_impl_mod); } bool kmbint_eq(const char *bint, const char *to_cmp) { return strcmp(bint, to_cmp) == 0; } bool kmbint_neq(const char *bint, const char *to_cmp) { return strcmp(bint, to_cmp) != 0; } bool kmbint_gt(const char *bint, const char *to_cmp) { size_t len_bint = strlen(bint); size_t len_to_cmp = strlen(to_cmp); if (len_bint > len_to_cmp) return true; else if (len_bint == len_to_cmp) return strcmp(bint, to_cmp) > 0; else return false; } bool kmbint_gte(const char *bint, const char *to_cmp) { size_t len_bint = strlen(bint); size_t len_to_cmp = strlen(to_cmp); if (len_bint > len_to_cmp) return true; else if (len_bint == len_to_cmp) return strcmp(bint, to_cmp) >= 0; else return false; } bool kmbint_lt(const char *bint, const char *to_cmp) { size_t len_bint = strlen(bint); size_t len_to_cmp = strlen(to_cmp); if (len_bint < len_to_cmp) return true; else if (len_bint == len_to_cmp) return strcmp(bint, to_cmp) < 0; else return false; } bool kmbint_lte(const char *bint, const char *to_cmp) { size_t len_bint = strlen(bint); size_t len_to_cmp = strlen(to_cmp); if (len_bint < len_to_cmp) return true; else if (len_bint == len_to_cmp) return strcmp(bint, to_cmp) <= 0; else return false; } void kmbint_cross_sum(char *bint) { size_t len_bint = strlen(bint); char *end = bint + len_bint; char *current = end; while (current != bint) { --current; char c = *current - '0'; *current = '0'; char *temp = end - 1; while (c > 0) { *temp += c; if (*temp > '9'){ *temp -= 10; c = 1; } else { c = 0; } --temp; } } size_t to_shift = 0; while (*current == '0') { ++current; ++to_shift; } if (to_shift == len_bint) { --current; --to_shift; } memmove(bint, current, len_bint - to_shift + 1); }
2.8125
3
2024-11-18T21:10:06.108855+00:00
2018-02-20T18:56:31
f6b50351b782e3c7f9733ab8f30a96f37c362457
{ "blob_id": "f6b50351b782e3c7f9733ab8f30a96f37c362457", "branch_name": "refs/heads/master", "committer_date": "2018-02-20T18:56:31", "content_id": "fd2c04e2520cd5177d894db3544d866a9ebba835", "detected_licenses": [ "MIT" ], "directory_id": "a0df40daf9fa5e8f66cf75a528706821a5ae6891", "extension": "c", "filename": "test.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 122240957, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1341, "license": "MIT", "license_type": "permissive", "path": "/test.c", "provenance": "stackv2-0065.json.gz:27675", "repo_name": "AlecTaggart/xv6c", "revision_date": "2018-02-20T18:56:31", "revision_id": "9d89c8ad1ae16512ff0ec8732964cec4fc4751f2", "snapshot_id": "cdaac62e1bdc1526d83cadb4ece71cbd8b4a91f8", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/AlecTaggart/xv6c/9d89c8ad1ae16512ff0ec8732964cec4fc4751f2/test.c", "visit_date": "2021-04-28T08:06:34.586321" }
stackv2
#include "types.h" #include "user.h" int main(void) { int i = 1, j, x, single = 1, update = 1; char abs[52]; getpath(0, abs); char *path = "test"; char *token_cab; char *token_path; char *path_arr[128]; if(update == 1){ getpath(0, token_cab); token_path = path; path_arr[0] = "/"; while ((token_cab = strtok(token_cab, "/")) != 0){ path_arr[i++] = token_cab; token_cab = 0; } for(x = 0; x < strlen(path); x++){ if(path[x] == '/'){ single = 0; } } if(!single){ while((token_path = strtok(token_path, "/")) != 0){ if(strcmp(token_path, "..") == 0){ path_arr[--i] = 0; i++; } else{ path_arr[i++] = token_path; } }token_path = 0; }else{ path_arr[i] = path; } strcpy(abs, path_arr[0]); for(j = 1; j <= i; j++){ if(path_arr[j] != 0){ strcat(abs, path_arr[j]); strcat(abs, "/"); } } strcat(abs, "\0"); }else{ strcpy(abs, path); } printf(1, "Absolute path: %s\n", abs); exit(); }
2.53125
3
2024-11-18T21:10:07.265492+00:00
2018-11-05T17:00:14
9945202fd5b4d18fe1f6f70be9e8c33d2648cbbc
{ "blob_id": "9945202fd5b4d18fe1f6f70be9e8c33d2648cbbc", "branch_name": "refs/heads/master", "committer_date": "2018-11-05T17:00:14", "content_id": "6f3b425bc55674340b8dd933b1c8dd066ad411d6", "detected_licenses": [ "CC0-1.0" ], "directory_id": "fc149656c67a7c8fbf73473c54203af093cd94af", "extension": "c", "filename": "ROVND_GetKind.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 156252509, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 970, "license": "CC0-1.0", "license_type": "permissive", "path": "/src/ROVND_GetKind.c", "provenance": "stackv2-0065.json.gz:27803", "repo_name": "clown/rovnd", "revision_date": "2018-11-05T17:00:14", "revision_id": "f7ef6ab7ae7b753fa01090b2d89629226485c5f4", "snapshot_id": "a17c77eb0e5cfd16356625e27b32c3e2756b1e1d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/clown/rovnd/f7ef6ab7ae7b753fa01090b2d89629226485c5f4/src/ROVND_GetKind.c", "visit_date": "2020-04-04T20:36:08.236857" }
stackv2
/* ====================================================================== * * ファイル名 : ROVND_GetKind.c * 概要 : アイテムの種類を取得する * 作成者 : clown * 修正日 : 2003/11/23 * ====================================================================== */ #include <stdlib.h> #include <string.h> #include "ROVND_Proto.h" /* ====================================================================== * * 関数名 : GetKind * 機能 : アイテムの種類を取得する * 戻り値 * 非負整数 : アイテムの種類 * -1 : エラー * 修正日 : 2003/11/23 * ====================================================================== */ int GetKind(char *element) { int i; if (element != NULL) { for (i = 0; i < g_kindnum; i++) { if (strcmp(element, g_itemkind[i]) == 0) { return i; } } } return -1; }
2.53125
3
2024-11-18T21:10:08.280664+00:00
2016-10-16T00:11:28
b97c23087efae358313f619acd5579ba4d57ac37
{ "blob_id": "b97c23087efae358313f619acd5579ba4d57ac37", "branch_name": "refs/heads/master", "committer_date": "2016-10-16T00:11:28", "content_id": "40ebafc4b8b6245c2867c799cdfe4baf3317bea7", "detected_licenses": [ "MIT" ], "directory_id": "9a2d2ff210e52222151593977945d312e65fc7ba", "extension": "c", "filename": "h_read.c", "fork_events_count": 1, "gha_created_at": "2016-10-19T19:08:00", "gha_event_created_at": "2016-10-19T19:08:02", "gha_language": null, "gha_license_id": null, "github_id": 71390433, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12573, "license": "MIT", "license_type": "permissive", "path": "/sample_experiment/tools/CMUseg_0.5/src/lib/sphere/src/bin/h_read.c", "provenance": "stackv2-0065.json.gz:28060", "repo_name": "dericed/american-archive-kaldi", "revision_date": "2016-10-16T00:11:28", "revision_id": "172b9bf2a3509c0d36b61c266db252b51907b256", "snapshot_id": "41af1326aa744fda58bf6c251b89e56c220a7fe6", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/dericed/american-archive-kaldi/172b9bf2a3509c0d36b61c266db252b51907b256/sample_experiment/tools/CMUseg_0.5/src/lib/sphere/src/bin/h_read.c", "visit_date": "2021-01-11T03:47:37.270661" }
stackv2
/* File: h_read.c */ /****************************************************************************/ /* By default, this program reads headers from the files specified on the */ /* command line and prints the values of all fields in the headers. */ /* Various options can alter the output. */ /* See the manual page h_read.1 for a complete description of the command. */ /****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <sp/sphere.h> #include <util/hsgetopt.h> #define SELECT_ALL 1 #define SELECT_STD 2 #define SELECT_LISTED 3 #define DEF_SELECT SELECT_ALL char *prog, *current_file; int errors = 0; int fieldno, total_fields; int selection = DEF_SELECT; int complement_selection = FALSE; int pr_str=TRUE, pr_int=TRUE, pr_real=TRUE; int verbose = FALSE; int nfields_expected = -1; int pr_quote_flag = FALSE; int pr_data_flag = TRUE; int pr_type_flag = FALSE; int pr_fieldname_flag = TRUE; int check_alphanum = FALSE; int check_std_fields = FALSE; int verify_byte_count = FALSE; int check_byte_order = FALSE; /* not implemented */ int pr_filename_first = FALSE; int pr_filename_with_fields = FALSE; int pr_field_numbers = FALSE; int pr_total_field_numbers = FALSE; int number_from_zero = FALSE; char *odd = CNULL; char *delim = " "; char *prf[MAXFIELDS]; int nprf = 0; char *checkf[MAXFIELDS]; int ncheckf = 0; /* function prototypes */ void read_file(char *); void pr_error(char *); void usage(void); void field(register struct header_t *, char *); int in_list(char *, int, char **); /**********************************************************************/ int main(int argc, char **argv) { int i, j, files, blanklines=0, exit_status; prog = strrchr(argv[0],'/'); prog = (prog == CNULL) ? argv[0] : (prog + 1); for (;;) { int c; char *p; hs_optarg = CNULL; c = hs_getopt(argc,argv,"aB:C:cde:F:f:N:no:qSs:T:tVv0"); if ( c == -1 ) break; if (verbose) if (hs_optarg == CNULL) (void) printf("Option: -%c\n",c); else (void) printf("Option: -%c %s\n",c,hs_optarg); switch (c) { case 'a': check_alphanum = TRUE; break; case 'B': blanklines = atoi(hs_optarg); break; case 'b': check_byte_order = TRUE; break; case 'c': complement_selection = TRUE; break; case 'd': pr_data_flag = FALSE; break; case 'f': p = hs_optarg; while (*p) switch (*p++) { case 'h': pr_filename_first = TRUE; break; case 'a': pr_filename_with_fields = TRUE; break; default: usage(); } /* switch */ break; case 'N': p = hs_optarg; while (*p) switch (*p++) { case 'f': pr_field_numbers = TRUE; break; case 't': pr_total_field_numbers = TRUE; break; default: usage(); } /* switch */ break; case 'o': if (odd != CNULL) { (void) fprintf(stderr, "Only one -o option is allowed\n"); usage(); } odd = hs_optarg; break; case 'T': pr_str = pr_int = pr_real = FALSE; p = hs_optarg; while (*p) switch (*p++) { case 's': pr_str = TRUE; break; case 'i': pr_int = TRUE; break; case 'r': pr_real = TRUE; break; default: usage(); } /* switch */ break; case 'q': pr_quote_flag = TRUE; break; case 'n': pr_fieldname_flag = FALSE; break; case 't': pr_type_flag = TRUE; break; case 'C': checkf[ ncheckf++ ] = hs_optarg; break; case 'F': prf[ nprf++ ] = hs_optarg; break; case 'e': nfields_expected = atoi(hs_optarg); break; case 'S': selection = SELECT_STD; break; case 's': delim = hs_optarg; break; case 'V': verify_byte_count = TRUE; break; case 'v': verbose = TRUE; break; case '0': number_from_zero = TRUE; break; default: usage(); } /* switch */ } /* for (;;) */ if (verbose) fprintf(spfp,"%s: %s\n",prog,sp_get_version()); /* If any fields to be printed were named for on the command line, change selection mode, except if standard fields were also selected (error) */ if (nprf) switch (selection) { case SELECT_ALL: selection = SELECT_LISTED; break; case SELECT_STD: (void) fprintf(stderr,"Cannot specify both -F and -S\n"); usage(); } if (pr_total_field_numbers) total_fields = number_from_zero ? 0 : 1; files = argc - hs_optind; for (i = hs_optind; i < argc; i++) { current_file = argv[i]; if (pr_filename_first) (void) printf("::::: %s :::::\n",current_file); read_file(current_file); if (i != argc - 1) for (j = 0; j < blanklines; j++) (void) putchar('\n'); } exit_status = errors ? ERROR_EXIT_STATUS : 0; if (verbose) { (void) printf("Files: %d\n",files); (void) printf("Errors: %d\n",errors); (void) printf("Exit Status: %d\n",exit_status); } exit(exit_status); } /********************************************************************/ void read_file(char *file) { register FILE *fp; register struct header_t *h; int i, nfields, type, size; char *errmsg; fp = fopen(file,"r"); if (fp == FPNULL) { pr_error("Cannot open"); return; } h = sp_open_header(fp,TRUE,&errmsg); if (h == HDRNULL) { pr_error("Cannot read header"); (void) fclose(fp); return; } for ( i=0; i < ncheckf; i++ ) if ( sp_get_field( h, checkf[i], &type, &size ) < 0 ) { errmsg = malloc( (u_int) (strlen( checkf[i] + 20 ))); if ( errmsg == CNULL ) pr_error( "Out of memory -- cannot report missing field" ); else { (void) sprintf( errmsg, "No field \"%s\"", checkf[i] ); pr_error( errmsg ); free( errmsg ); } } if (verify_byte_count) { struct stat s; long samples, sample_bytes, channel_count, actual, expected; if (stat(file,&s) < 0) { pr_error("Stat failed"); goto end; } if (sp_get_field(h,"sample_count",&type,&size) < 0) { pr_error("No field \"sample_count\""); goto end; } if (type != T_INTEGER) { pr_error("Field sample_count is not integer"); goto end; } if (sp_get_data(h,"sample_count",(char *) &samples,&size) < 0) { pr_error("Lookup on field sample_count failed"); goto end; } if (sp_get_field(h,"sample_n_bytes",&type,&size) < 0) { pr_error("No field \"sample_n_bytes\""); goto end; } if (type != T_INTEGER) { pr_error("Field sample_n_bytes is not integer"); goto end; } if (sp_get_data(h,"sample_n_bytes",(char *)&sample_bytes,&size) < 0) { pr_error("Lookup on field sample_n_bytes failed"); goto end; } if (sp_get_field(h,"channel_count",&type,&size) < 0) { pr_error("No field \"channel_count\""); goto end; } if (type != T_INTEGER) { pr_error("Field channel_count is not integer"); goto end; } if (sp_get_data(h,"channel_count",(char *)&channel_count,&size) < 0) { pr_error("Lookup on field channel_count failed"); goto end; } actual = (long) s.st_size - (long) ftell(fp); expected = sample_bytes * samples * channel_count; if (actual != expected) { (void) fprintf(stderr, "%s: ERROR: %s: %ld bytes of data (expected %ld)\n", prog,file,actual,expected); errors++; } else { if (verbose) (void) printf("%s: Byte count ok\n",file); } end: ; } nfields = sp_get_nfields(h); if (verbose) (void) printf("Fields: %d\n",nfields); if (check_std_fields) { register char **f = &std_fields[0]; char buffer[1024]; while (*f != CNULL) { if (sp_get_field(h,*f,&type,&size) < 0) { (void) sprintf(buffer,"Missing standard field %s",*f); pr_error(buffer); } f++; } } if (check_alphanum) { register struct field_t **fv; int j, k; char *p; fv = h->fv; for (k=0; k < nfields; k++) { if (fv[k]->type != T_STRING) continue; p = fv[k]->data; j = fv[k]->datalen; for (i=0; i < j; i++, p++) { if (isprint(*p)) continue; if ((odd != CNULL) && (strchr(odd,*p) != CNULL)) continue; (void) fprintf(stderr, "%s: ERROR: %s: Odd character #%d (\\0%o) in field %s\n", prog,file,i+1,*p,fv[k]->name); errors++; } } } if ((nfields_expected >= 0) && (nfields != nfields_expected)) { (void) printf("%s: %s: %d fields (expected %d)\n", prog,file,nfields,nfields_expected); errors++; } if (nfields > 0) { char **fv; fieldno = number_from_zero ? 0 : 1; fv = (char **) malloc((u_int) (nfields * sizeof(char *))); if (fv == (char **) NULL) pr_error("Out of memory -- cannot retrieve field list"); else { if (sp_get_fieldnames(h,nfields,fv) != nfields) pr_error("Cannot get fieldnames"); else for (i=0; i < nfields; i++) field(h,fv[i]); free((char *) fv); } } (void) fclose(fp); if (sp_close_header(h) < 0) pr_error("Cannot close header"); } /******************************************************************/ void pr_error(char *s) { errors++; (void) fflush(stdout); (void) fprintf(stderr,"%s: ERROR: %s: %s\n",prog,current_file,s); } /********************************************************************/ void usage(void) { static char usage_msg[] = "Usage: %s [options] [file ...]\n\ [-acdnqStVv0]\n\ [-C field]\n\ [-F field]\n\ [-T typespecs]\n\ [-f (a|h)]\n\ [-N (f|t)]\n\ [-s separator]\n\ [-B #]\n\ [-o string]\n\ [-e #]\n"; (void) fflush(stdout); (void) fprintf(stderr,usage_msg,prog); exit(ERROR_EXIT_STATUS); } /*******************************************************************/ void field(register struct header_t *h, char *name) { char *p, *q, buffer[1024]; int n, print_it, type, size, size2, nprinted; switch (selection) { case SELECT_ALL: print_it = TRUE; break; case SELECT_STD: print_it = sp_is_std(name); break; case SELECT_LISTED: print_it = in_list(name,nprf,prf); break; } if (complement_selection) print_it = ! print_it; if (! print_it) { if (verbose) (void) printf("Field %s ignored (based on selection qualifier)\n", name); return; } n = sp_get_field(h,name,&type,&size); if (n < 0) { (void) sprintf(buffer,"No field \"%s\"",name); pr_error(buffer); return; } switch (type) { case T_STRING: print_it = pr_str; break; case T_INTEGER: print_it = pr_int; break; case T_REAL: print_it = pr_real; break; } if (! print_it) { if (verbose) (void) printf("Field %s ignored (based on type)\n",name); return; } p = q = malloc((u_int) size); if (p == CNULL) { pr_error("Out of memory"); return; } size2 = size; n = sp_get_data(h,name,p,&size2); if (n < 0) { (void) sprintf(buffer,"Lookup on field %s failed",name); pr_error(buffer); return; } if (size != size2) { (void) sprintf(buffer, "Lookup on field %s returned %d bytes (expected %d)", name,size2,size); pr_error(buffer); return; } nprinted = 0; if (pr_total_field_numbers) { (void) printf("%d",total_fields++); nprinted++; } if (pr_filename_with_fields) { if (nprinted++) (void) fputs(delim,stdout); (void) printf("%s",current_file); } if (pr_field_numbers) { if (nprinted++) (void) fputs(delim,stdout); (void) printf("%d",fieldno++); } if (pr_fieldname_flag) { if (nprinted++) (void) fputs(delim,stdout); (void) printf("%s",name); } if (pr_type_flag) { if (nprinted++) (void) fputs(delim,stdout); (void) printf("%c",spx_tp(type)); } if (pr_data_flag) { if (nprinted++) (void) fputs(delim,stdout); if (pr_quote_flag) (void) putchar('"'); switch (type) { case T_STRING: while (size--) (void) putchar(*p++); break; case T_INTEGER: (void) printf("%ld",*(long *)p); break; case T_REAL: (void) printf("%f",*(double *)p); break; } if (pr_quote_flag) (void) putchar('"'); } if (nprinted) (void) putchar('\n'); free(q); } /*****************************************************/ int in_list(char *name, int n, char **f) { register int i; if (name == CNULL) return FALSE; for (i=0; i < n; i++) if (strcmp(name,f[i]) == 0) return TRUE; return FALSE; }
2.328125
2
2024-11-18T21:10:08.361842+00:00
2021-09-10T11:24:53
eaca1307e0285c22f36169827ab57aefdda7542c
{ "blob_id": "eaca1307e0285c22f36169827ab57aefdda7542c", "branch_name": "refs/heads/master", "committer_date": "2021-09-10T11:24:53", "content_id": "b74e66b58d1b3dbbf262cf115ced87fe1f81ff4c", "detected_licenses": [ "MIT" ], "directory_id": "936fa91805ad7e156705a3446f88ddd258b77a4f", "extension": "h", "filename": "dx11_rendertarget.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 243416047, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2729, "license": "MIT", "license_type": "permissive", "path": "/example/gizmesh_example_d3d11/dx11_rendertarget.h", "provenance": "stackv2-0065.json.gz:28188", "repo_name": "ousttrue/gizmesh", "revision_date": "2021-09-10T11:24:53", "revision_id": "fbc845abcd20eacc06c89c03a9e86a81208c401d", "snapshot_id": "2456edd3b632bfe8835b0c77159caa8d542a47a2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ousttrue/gizmesh/fbc845abcd20eacc06c89c03a9e86a81208c401d/example/gizmesh_example_d3d11/dx11_rendertarget.h", "visit_date": "2023-08-23T08:41:19.628360" }
stackv2
#pragma once #include <d3d11.h> #include <wrl/client.h> struct Dx11RenderTarget { Microsoft::WRL::ComPtr<ID3D11RenderTargetView> m_rtv; Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_srv; Microsoft::WRL::ComPtr<ID3D11DepthStencilView> m_dsv; bool Initialize(ID3D11Device *device, const Microsoft::WRL::ComPtr<ID3D11Texture2D> &texture, bool useSRV) { // create RTV if (FAILED( device->CreateRenderTargetView(texture.Get(), nullptr, &m_rtv))) { return false; } // create SRV if (useSRV) { if (FAILED(device->CreateShaderResourceView(texture.Get(), nullptr, &m_srv))) { return false; } } D3D11_TEXTURE2D_DESC textureDesc; texture->GetDesc(&textureDesc); // create depthbuffer D3D11_TEXTURE2D_DESC depthDesc = {0}; depthDesc.Width = textureDesc.Width; depthDesc.Height = textureDesc.Height; depthDesc.MipLevels = 1; depthDesc.ArraySize = 1; depthDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthDesc.SampleDesc.Count = 1; depthDesc.Usage = D3D11_USAGE_DEFAULT; depthDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; Microsoft::WRL::ComPtr<ID3D11Texture2D> depthBuffer; if (FAILED(device->CreateTexture2D(&depthDesc, nullptr, &depthBuffer))) { return false; } // create dsv if (FAILED(device->CreateDepthStencilView(depthBuffer.Get(), nullptr, &m_dsv))) { return false; } return true; } void ClearAndSet(ID3D11DeviceContext *context, const float *clear, float depth, UINT8 stencil, int width, int height) { if (m_rtv) { context->ClearRenderTargetView(m_rtv.Get(), clear); } if (m_dsv) { context->ClearDepthStencilView(m_dsv.Get(), D3D11_CLEAR_DEPTH, depth, stencil); } // set backbuffer & depthbuffer ID3D11RenderTargetView *rtv_list[] = {m_rtv.Get()}; context->OMSetRenderTargets(1, rtv_list, m_dsv.Get()); D3D11_VIEWPORT viewports[1] = {{0}}; viewports[0].TopLeftX = 0; viewports[0].TopLeftY = 0; viewports[0].Width = (float)width; viewports[0].Height = (float)height; viewports[0].MinDepth = 0; viewports[0].MaxDepth = 1.0f; context->RSSetViewports(_countof(viewports), viewports); } void ClearDepth(ID3D11DeviceContext *context, float depth, UINT8 stencil) { if (m_dsv) { context->ClearDepthStencilView(m_dsv.Get(), D3D11_CLEAR_DEPTH, depth, stencil); } } };
2.3125
2
2024-11-18T21:10:08.644335+00:00
2021-07-27T12:38:58
687fc0f4c57d4031150f6cb1ea59ce43fc9977d1
{ "blob_id": "687fc0f4c57d4031150f6cb1ea59ce43fc9977d1", "branch_name": "refs/heads/master", "committer_date": "2021-07-27T12:38:58", "content_id": "81cc46c83caf7fe13f86844d0414cf23063752c4", "detected_licenses": [ "MIT" ], "directory_id": "4ab7b74328927c66671a6aae9fcf77c85b22e210", "extension": "c", "filename": "column.c", "fork_events_count": 0, "gha_created_at": "2021-04-05T13:05:00", "gha_event_created_at": "2021-07-26T14:43:54", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 354837094, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 557, "license": "MIT", "license_type": "permissive", "path": "/deploy/lib/csv/example/column.c", "provenance": "stackv2-0065.json.gz:28316", "repo_name": "ChristopherKotthoff/aphros", "revision_date": "2021-07-27T12:38:58", "revision_id": "a17d121e93c7ea48bcf36f9dd4e11d95bd15c89b", "snapshot_id": "57d954b9eac3f1f2b60af32452ce6b79116eafc5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ChristopherKotthoff/aphros/a17d121e93c7ea48bcf36f9dd4e11d95bd15c89b/deploy/lib/csv/example/column.c", "visit_date": "2023-06-25T07:37:24.957638" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <csv.h> static const char me[] = "column"; #define USED(x) \ if (x) \ ; \ else { \ } int main(int argc, char** argv) { int i, nr; double* field; struct CSV* csv; USED(argc); argv++; csv = csv_read(stdin); nr = csv_nr(csv); if (argv[0] == NULL) { fprintf(stderr, "%s: needs an argument\n", me); exit(2); } field = csv_field(csv, argv[0]); if (field != NULL) for (i = 0; i < nr; i++) printf("%.20g\n", field[i]); csv_fin(csv); }
2.609375
3
2024-11-18T21:10:08.948921+00:00
2021-06-05T12:11:50
1ac7018c3c05e9fb2be13c3d92afce300cb2d8ed
{ "blob_id": "1ac7018c3c05e9fb2be13c3d92afce300cb2d8ed", "branch_name": "refs/heads/main", "committer_date": "2021-06-05T12:11:50", "content_id": "5b93231541add39a73c49918298dbeeff4d899b1", "detected_licenses": [ "MIT" ], "directory_id": "e8582383b3e362fa4dd02573d4feb3cbe792b96b", "extension": "c", "filename": "sphereCollider.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": 749, "license": "MIT", "license_type": "permissive", "path": "/lib/Physics/src/sphereCollider.c", "provenance": "stackv2-0065.json.gz:28573", "repo_name": "mhwdvs/BigBallsRoll", "revision_date": "2021-06-05T12:11:50", "revision_id": "a29935f1d999a64821da359a59153944690b34b2", "snapshot_id": "13d7806d3c3a263c5cd437ed6214e6ca631cfd36", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mhwdvs/BigBallsRoll/a29935f1d999a64821da359a59153944690b34b2/lib/Physics/src/sphereCollider.c", "visit_date": "2023-05-12T09:26:34.567267" }
stackv2
#include "include/BigBalls/sphereCollider.h" #include <stdlib.h> #include <assert.h> void SphereCollider_init(SphereCollider *sphereCollider){ assert(sphereCollider != NULL); sphereCollider->xOffset = 0.0f; sphereCollider->yOffset = 0.0f; sphereCollider->zOffset = 0.0f; sphereCollider->xPostRot = 0.0f; sphereCollider->yPostRot = 0.0f; sphereCollider->zPostRot = 0.0f; sphereCollider->radius = 0.0f; } void SphereCollider_updatePostRotPos(SphereCollider *sphereCollider, float x, float y, float z){ sphereCollider->xPostRot = x; sphereCollider->yPostRot = y; sphereCollider->zPostRot = z; }
2.21875
2
2024-11-18T21:10:09.053050+00:00
2022-05-27T05:57:37
57e338361c9b6e51284704ea6fb104d1aae3b52a
{ "blob_id": "57e338361c9b6e51284704ea6fb104d1aae3b52a", "branch_name": "refs/heads/master", "committer_date": "2022-05-27T05:57:37", "content_id": "0c4bc80cf601eea8382d4ff9189451dfbfb8162b", "detected_licenses": [ "Apache-2.0", "MIT" ], "directory_id": "4e40487eb963985c55a8b4a0518d0d4612e5291e", "extension": "h", "filename": "hip_atomic.h", "fork_events_count": 6, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 473072609, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 18494, "license": "Apache-2.0,MIT", "license_type": "permissive", "path": "/reef-env/hip/include/hip/amd_detail/hip_atomic.h", "provenance": "stackv2-0065.json.gz:28702", "repo_name": "SJTU-IPADS/reef-artifacts", "revision_date": "2022-05-27T05:57:37", "revision_id": "8750974f2d6655525a2cc317bf2471914fe68dab", "snapshot_id": "2858191efa1ce6423f2a912bfb9758af96e62ea7", "src_encoding": "UTF-8", "star_events_count": 36, "url": "https://raw.githubusercontent.com/SJTU-IPADS/reef-artifacts/8750974f2d6655525a2cc317bf2471914fe68dab/reef-env/hip/include/hip/amd_detail/hip_atomic.h", "visit_date": "2023-04-06T16:48:31.807517" }
stackv2
#include "device_functions.h" #if __has_builtin(__hip_atomic_compare_exchange_strong) #if !__HIP_DEVICE_COMPILE__ //TODO: Remove this after compiler pre-defines the following Macros. #define __HIP_MEMORY_SCOPE_SINGLETHREAD 1 #define __HIP_MEMORY_SCOPE_WAVEFRONT 2 #define __HIP_MEMORY_SCOPE_WORKGROUP 3 #define __HIP_MEMORY_SCOPE_AGENT 4 #define __HIP_MEMORY_SCOPE_SYSTEM 5 #endif __device__ inline int atomicCAS(int* address, int compare, int val) { __hip_atomic_compare_exchange_strong(address, &compare, val, __ATOMIC_RELAXED, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); return compare; } __device__ inline int atomicCAS_system(int* address, int compare, int val) { __hip_atomic_compare_exchange_strong(address, &compare, val, __ATOMIC_RELAXED, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); return compare; } __device__ inline unsigned int atomicCAS(unsigned int* address, unsigned int compare, unsigned int val) { __hip_atomic_compare_exchange_strong(address, &compare, val, __ATOMIC_RELAXED, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); return compare; } __device__ inline unsigned int atomicCAS_system(unsigned int* address, unsigned int compare, unsigned int val) { __hip_atomic_compare_exchange_strong(address, &compare, val, __ATOMIC_RELAXED, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); return compare; } __device__ inline unsigned long long atomicCAS(unsigned long long* address, unsigned long long compare, unsigned long long val) { __hip_atomic_compare_exchange_strong(address, &compare, val, __ATOMIC_RELAXED, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); return compare; } __device__ inline unsigned long long atomicCAS_system(unsigned long long* address, unsigned long long compare, unsigned long long val) { __hip_atomic_compare_exchange_strong(address, &compare, val, __ATOMIC_RELAXED, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); return compare; } __device__ inline int atomicAdd(int* address, int val) { return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline int atomicAdd_system(int* address, int val) { return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline unsigned int atomicAdd(unsigned int* address, unsigned int val) { return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline unsigned int atomicAdd_system(unsigned int* address, unsigned int val) { return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline unsigned long long atomicAdd(unsigned long long* address, unsigned long long val) { return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline unsigned long long atomicAdd_system(unsigned long long* address, unsigned long long val) { return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline float atomicAdd(float* address, float val) { return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline float atomicAdd_system(float* address, float val) { return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } #if !defined(__HIPCC_RTC__) DEPRECATED("use atomicAdd instead") #endif // !defined(__HIPCC_RTC__) __device__ inline void atomicAddNoRet(float* address, float val) { __ockl_atomic_add_noret_f32(address, val); } __device__ inline double atomicAdd(double* address, double val) { return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline double atomicAdd_system(double* address, double val) { return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline int atomicSub(int* address, int val) { return __hip_atomic_fetch_add(address, -val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline int atomicSub_system(int* address, int val) { return __hip_atomic_fetch_add(address, -val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline unsigned int atomicSub(unsigned int* address, unsigned int val) { return __hip_atomic_fetch_add(address, -val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline unsigned int atomicSub_system(unsigned int* address, unsigned int val) { return __hip_atomic_fetch_add(address, -val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline int atomicExch(int* address, int val) { return __hip_atomic_exchange(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline int atomicExch_system(int* address, int val) { return __hip_atomic_exchange(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline unsigned int atomicExch(unsigned int* address, unsigned int val) { return __hip_atomic_exchange(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline unsigned int atomicExch_system(unsigned int* address, unsigned int val) { return __hip_atomic_exchange(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline unsigned long long atomicExch(unsigned long long* address, unsigned long long val) { return __hip_atomic_exchange(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline unsigned long long atomicExch_system(unsigned long long* address, unsigned long long val) { return __hip_atomic_exchange(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline float atomicExch(float* address, float val) { return __hip_atomic_exchange(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline float atomicExch_system(float* address, float val) { return __hip_atomic_exchange(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline int atomicMin(int* address, int val) { return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline int atomicMin_system(int* address, int val) { return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline unsigned int atomicMin(unsigned int* address, unsigned int val) { return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline unsigned int atomicMin_system(unsigned int* address, unsigned int val) { return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline unsigned long long atomicMin(unsigned long long* address, unsigned long long val) { return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline unsigned long long atomicMin_system(unsigned long long* address, unsigned long long val) { return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline int atomicMax(int* address, int val) { return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline int atomicMax_system(int* address, int val) { return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline unsigned int atomicMax(unsigned int* address, unsigned int val) { return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline unsigned int atomicMax_system(unsigned int* address, unsigned int val) { return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline unsigned long long atomicMax(unsigned long long* address, unsigned long long val) { return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline unsigned long long atomicMax_system(unsigned long long* address, unsigned long long val) { return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline unsigned int atomicInc(unsigned int* address, unsigned int val) { __device__ extern unsigned int __builtin_amdgcn_atomic_inc( unsigned int*, unsigned int, unsigned int, unsigned int, bool) __asm("llvm.amdgcn.atomic.inc.i32.p0i32"); return __builtin_amdgcn_atomic_inc( address, val, __ATOMIC_RELAXED, 1 /* Device scope */, false); } __device__ inline unsigned int atomicDec(unsigned int* address, unsigned int val) { __device__ extern unsigned int __builtin_amdgcn_atomic_dec( unsigned int*, unsigned int, unsigned int, unsigned int, bool) __asm("llvm.amdgcn.atomic.dec.i32.p0i32"); return __builtin_amdgcn_atomic_dec( address, val, __ATOMIC_RELAXED, 1 /* Device scope */, false); } __device__ inline int atomicAnd(int* address, int val) { return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline int atomicAnd_system(int* address, int val) { return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline unsigned int atomicAnd(unsigned int* address, unsigned int val) { return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline unsigned int atomicAnd_system(unsigned int* address, unsigned int val) { return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline unsigned long long atomicAnd(unsigned long long* address, unsigned long long val) { return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline unsigned long long atomicAnd_system(unsigned long long* address, unsigned long long val) { return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline int atomicOr(int* address, int val) { return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline int atomicOr_system(int* address, int val) { return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline unsigned int atomicOr(unsigned int* address, unsigned int val) { return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline unsigned int atomicOr_system(unsigned int* address, unsigned int val) { return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline unsigned long long atomicOr(unsigned long long* address, unsigned long long val) { return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline unsigned long long atomicOr_system(unsigned long long* address, unsigned long long val) { return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline int atomicXor(int* address, int val) { return __hip_atomic_fetch_xor(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline int atomicXor_system(int* address, int val) { return __hip_atomic_fetch_xor(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline unsigned int atomicXor(unsigned int* address, unsigned int val) { return __hip_atomic_fetch_xor(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline unsigned int atomicXor_system(unsigned int* address, unsigned int val) { return __hip_atomic_fetch_xor(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } __device__ inline unsigned long long atomicXor(unsigned long long* address, unsigned long long val) { return __hip_atomic_fetch_xor(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); } __device__ inline unsigned long long atomicXor_system(unsigned long long* address, unsigned long long val) { return __hip_atomic_fetch_xor(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); } #else __device__ inline int atomicCAS(int* address, int compare, int val) { __atomic_compare_exchange_n( address, &compare, val, false, __ATOMIC_RELAXED, __ATOMIC_RELAXED); return compare; } __device__ inline unsigned int atomicCAS( unsigned int* address, unsigned int compare, unsigned int val) { __atomic_compare_exchange_n( address, &compare, val, false, __ATOMIC_RELAXED, __ATOMIC_RELAXED); return compare; } __device__ inline unsigned long long atomicCAS( unsigned long long* address, unsigned long long compare, unsigned long long val) { __atomic_compare_exchange_n( address, &compare, val, false, __ATOMIC_RELAXED, __ATOMIC_RELAXED); return compare; } __device__ inline int atomicAdd(int* address, int val) { return __atomic_fetch_add(address, val, __ATOMIC_RELAXED); } __device__ inline unsigned int atomicAdd(unsigned int* address, unsigned int val) { return __atomic_fetch_add(address, val, __ATOMIC_RELAXED); } __device__ inline unsigned long long atomicAdd( unsigned long long* address, unsigned long long val) { return __atomic_fetch_add(address, val, __ATOMIC_RELAXED); } __device__ inline float atomicAdd(float* address, float val) { return __atomic_fetch_add(address, val, __ATOMIC_RELAXED); } #if !defined(__HIPCC_RTC__) DEPRECATED("use atomicAdd instead") #endif // !defined(__HIPCC_RTC__) __device__ inline void atomicAddNoRet(float* address, float val) { __ockl_atomic_add_noret_f32(address, val); } __device__ inline double atomicAdd(double* address, double val) { return __atomic_fetch_add(address, val, __ATOMIC_RELAXED); } __device__ inline int atomicSub(int* address, int val) { return __atomic_fetch_sub(address, val, __ATOMIC_RELAXED); } __device__ inline unsigned int atomicSub(unsigned int* address, unsigned int val) { return __atomic_fetch_sub(address, val, __ATOMIC_RELAXED); } __device__ inline int atomicExch(int* address, int val) { return __atomic_exchange_n(address, val, __ATOMIC_RELAXED); } __device__ inline unsigned int atomicExch(unsigned int* address, unsigned int val) { return __atomic_exchange_n(address, val, __ATOMIC_RELAXED); } __device__ inline unsigned long long atomicExch(unsigned long long* address, unsigned long long val) { return __atomic_exchange_n(address, val, __ATOMIC_RELAXED); } __device__ inline float atomicExch(float* address, float val) { return __uint_as_float(__atomic_exchange_n( reinterpret_cast<unsigned int*>(address), __float_as_uint(val), __ATOMIC_RELAXED)); } __device__ inline int atomicMin(int* address, int val) { return __atomic_fetch_min(address, val, __ATOMIC_RELAXED); } __device__ inline unsigned int atomicMin(unsigned int* address, unsigned int val) { return __atomic_fetch_min(address, val, __ATOMIC_RELAXED); } __device__ inline unsigned long long atomicMin( unsigned long long* address, unsigned long long val) { unsigned long long tmp{__atomic_load_n(address, __ATOMIC_RELAXED)}; while (val < tmp) { const auto tmp1 = __atomic_load_n(address, __ATOMIC_RELAXED); if (tmp1 != tmp) { tmp = tmp1; continue; } tmp = atomicCAS(address, tmp, val); } return tmp; } __device__ inline int atomicMax(int* address, int val) { return __atomic_fetch_max(address, val, __ATOMIC_RELAXED); } __device__ inline unsigned int atomicMax(unsigned int* address, unsigned int val) { return __atomic_fetch_max(address, val, __ATOMIC_RELAXED); } __device__ inline unsigned long long atomicMax( unsigned long long* address, unsigned long long val) { unsigned long long tmp{__atomic_load_n(address, __ATOMIC_RELAXED)}; while (tmp < val) { const auto tmp1 = __atomic_load_n(address, __ATOMIC_RELAXED); if (tmp1 != tmp) { tmp = tmp1; continue; } tmp = atomicCAS(address, tmp, val); } return tmp; } __device__ inline unsigned int atomicInc(unsigned int* address, unsigned int val) { __device__ extern unsigned int __builtin_amdgcn_atomic_inc( unsigned int*, unsigned int, unsigned int, unsigned int, bool) __asm("llvm.amdgcn.atomic.inc.i32.p0i32"); return __builtin_amdgcn_atomic_inc( address, val, __ATOMIC_RELAXED, 1 /* Device scope */, false); } __device__ inline unsigned int atomicDec(unsigned int* address, unsigned int val) { __device__ extern unsigned int __builtin_amdgcn_atomic_dec( unsigned int*, unsigned int, unsigned int, unsigned int, bool) __asm("llvm.amdgcn.atomic.dec.i32.p0i32"); return __builtin_amdgcn_atomic_dec( address, val, __ATOMIC_RELAXED, 1 /* Device scope */, false); } __device__ inline int atomicAnd(int* address, int val) { return __atomic_fetch_and(address, val, __ATOMIC_RELAXED); } __device__ inline unsigned int atomicAnd(unsigned int* address, unsigned int val) { return __atomic_fetch_and(address, val, __ATOMIC_RELAXED); } __device__ inline unsigned long long atomicAnd( unsigned long long* address, unsigned long long val) { return __atomic_fetch_and(address, val, __ATOMIC_RELAXED); } __device__ inline int atomicOr(int* address, int val) { return __atomic_fetch_or(address, val, __ATOMIC_RELAXED); } __device__ inline unsigned int atomicOr(unsigned int* address, unsigned int val) { return __atomic_fetch_or(address, val, __ATOMIC_RELAXED); } __device__ inline unsigned long long atomicOr( unsigned long long* address, unsigned long long val) { return __atomic_fetch_or(address, val, __ATOMIC_RELAXED); } __device__ inline int atomicXor(int* address, int val) { return __atomic_fetch_xor(address, val, __ATOMIC_RELAXED); } __device__ inline unsigned int atomicXor(unsigned int* address, unsigned int val) { return __atomic_fetch_xor(address, val, __ATOMIC_RELAXED); } __device__ inline unsigned long long atomicXor( unsigned long long* address, unsigned long long val) { return __atomic_fetch_xor(address, val, __ATOMIC_RELAXED); } #endif
2.125
2
2024-11-18T21:10:10.363825+00:00
2021-02-24T13:42:25
d145abb7e047936206e0e358f459701c9707b3c8
{ "blob_id": "d145abb7e047936206e0e358f459701c9707b3c8", "branch_name": "refs/heads/master", "committer_date": "2021-02-24T13:42:25", "content_id": "7a80ba5f12e550987e32e8acbee19c84981a2490", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "b5a22da19e74bfc2d1add781f94bcbde8f0c362c", "extension": "c", "filename": "rt_hit.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 335696135, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 607, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/rt_hit.c", "provenance": "stackv2-0065.json.gz:28963", "repo_name": "felipegimenezsilva/ca", "revision_date": "2021-02-24T13:42:25", "revision_id": "4ef01183ef320b9e5b57c4d572efcac7e52985f3", "snapshot_id": "eedaea44c3214bcf40044dd1453bbd86b3199002", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/felipegimenezsilva/ca/4ef01183ef320b9e5b57c4d572efcac7e52985f3/rt_hit.c", "visit_date": "2023-03-22T04:10:47.373530" }
stackv2
/** * Copyright (c) 2020, Evgeniy Morozov * All rights reserved. * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include <assert.h> #include "rt_hit.h" void rt_hit_record_set_front_face(rt_hit_record_t *record, const ray_t *ray, const vec3_t *outward_normal) { assert(NULL != record); assert(NULL != ray); assert(NULL != outward_normal); record->front_face = vec3_dot(*outward_normal, ray->direction) < 0; record->normal = record->front_face ? *outward_normal : vec3_negate(outward_normal); }
2.453125
2
2024-11-18T21:10:10.849161+00:00
2019-03-31T11:22:20
fac8993adb7fd50467fad6eae81975da52dd7206
{ "blob_id": "fac8993adb7fd50467fad6eae81975da52dd7206", "branch_name": "refs/heads/master", "committer_date": "2019-03-31T14:01:26", "content_id": "0848711d2e4f99efcb487eaf367dcf51b90da882", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "770e40fe61cf611cda3ef10e88e8110131a26e58", "extension": "c", "filename": "IO.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 153947669, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10915, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/IO.c", "provenance": "stackv2-0065.json.gz:29221", "repo_name": "mutant-industries/MSP430-driverlib", "revision_date": "2019-03-31T11:22:20", "revision_id": "101e0c868fa744abd79c297aa93b36c1fed0fd39", "snapshot_id": "de7db3c7562d39608da139fcde7ca3ab3ffa3aad", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/mutant-industries/MSP430-driverlib/101e0c868fa744abd79c297aa93b36c1fed0fd39/src/IO.c", "visit_date": "2020-04-02T03:08:03.388702" }
stackv2
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2018-2019 Mutant Industries ltd. #include <driver/IO.h> #include <stddef.h> #include <compiler.h> #include <driver/interrupt.h> // maximum count of 8-bit addressable ports #define MAX_PORT_COUNT 12 // array of pointers to registered drivers, persistent to allow wakeup on FRAM devices __persistent IO_port_driver_t *registered_drivers[MAX_PORT_COUNT] = {0}; static uint8_t _unsupported_operation() { return IO_UNSUPPORTED_OPERATION; } // ------------------------------------------------------------------------------------- static void _shared_vector_handler(IO_port_driver_t *driver) { uint8_t interrupt_pin_no; uint16_t interrupt_source; IO_pin_handle_t *handle; if ( ! (interrupt_source = hw_register_16(driver->_IV_register))) { return; } // IV -> pin number (0x00 - no interrupt, 0x02 - PxIFG.0 interrupt, 0x04 - PxIFG.1 interrupt...) interrupt_pin_no = (uint8_t) (interrupt_source / 2 - 1); handle = ((IO_pin_handle_t **) &driver->_pin0_handle)[interrupt_pin_no]; // execute handler with given handler_arg and PIN_X that triggered interrupt handle->_handler(handle->_handler_arg, (void *) (((uint16_t) 0x0001) << interrupt_pin_no)); } static Vector_slot_t *_register_handler_shared(IO_pin_handle_t *_this, vector_slot_handler_t handler, void *arg) { interrupt_suspend(); if ( ! _this->_driver->_slot) { _this->_driver->_slot = _this->_register_handler_parent(&_this->vector, (vector_slot_handler_t) _shared_vector_handler, _this->_driver, NULL); } interrupt_restore(); if ( ! _this->_driver->_slot) { return NULL; } // handle dispose preserves created vector slot vector_disable_slot_release_on_dispose(_this); _this->_handler = handler; _this->_handler_arg = arg; return _this->_driver->_slot; } // ------------------------------------------------------------------------------------- // IO_port_driver_t destructor static dispose_function_t _pin_handle_dispose(IO_pin_handle_t *_this) { IO_pin_handle_t **handle_ref = &_this->_driver->_pin0_handle; uint8_t pin; _this->_handler = NULL; _this->_handler_arg = NULL; // register interrupt handler is now disabled _this->vector.register_handler = (Vector_slot_t *(*)(Vector_handle_t *, vector_slot_handler_t, void *, void *)) _unsupported_operation; #ifdef __IO_PORT_LEGACY_SUPPORT__ // disable assignment of raw handler to shared vector _this->vector.register_raw_handler = (uint8_t (*)(Vector_handle_t *, interrupt_service_t, bool)) _unsupported_operation; #endif // release driver->handle references for (pin = 0; pin < 8; pin++, handle_ref++) { if (*handle_ref == _this) { *handle_ref = NULL; } } // reset default control register values IO_pin_handle_reg_reset(_this, DIR); IO_pin_handle_reg_reset(_this, REN); #ifdef OFS_PxSELC IO_pin_handle_reg_reset(_this, SELC); #else IO_pin_handle_reg_reset(_this, SEL0); #endif // direct register access is still allowed after disposed return NULL; } // IO_port_driver_t constructor static uint8_t _pin_handle_register(IO_port_driver_t *_this, IO_pin_handle_t *handle, uint8_t pin_mask) { // enable 16-bit register access in vector (set / clear interrupt flag, interrupt enable / disable) uint16_t base_register_16, pin_mask_16; IO_pin_handle_t **handle_ref; uint8_t pin; handle->_base_register = _this->_base_register; handle->_pin_mask = pin_mask; interrupt_suspend(); // check whether handles for given pins are registered already for (pin = 1, handle_ref = &_this->_pin0_handle; pin; pin <<= 1, handle_ref++) { if (pin & pin_mask && *handle_ref) { interrupt_restore(); // current pin is already registered for another handle return IO_PIN_HANDLE_REGISTERED_ALREADY; } } // driver->handle references for (pin = 1, handle_ref = &_this->_pin0_handle; pin; pin <<= 1, handle_ref++) { if (pin & pin_mask) { *handle_ref = handle; } } interrupt_restore(); base_register_16 = handle->_base_register; pin_mask_16 = pin_mask; #ifndef __IO_PORT_LEGACY_SUPPORT__ if (base_register_16 & 0x0001) { // 16-bit address alignment base_register_16--; // adjust pin mask to correspond to 16-bit access pin_mask_16 <<= 8; } #endif // handle->driver reference handle->_driver = _this; vector_handle_register(&handle->vector, (dispose_function_t) _pin_handle_dispose, _this->_vector_no, base_register_16 + OFS_PxIE, pin_mask_16, base_register_16 + OFS_PxIFG, pin_mask_16); handle->_handler = NULL; handle->_handler_arg = NULL; #ifndef __IO_PORT_LEGACY_SUPPORT__ // disable assignment of raw handler to shared vector handle->vector.register_raw_handler = (uint8_t (*)(Vector_handle_t *, interrupt_service_t, bool)) _unsupported_operation; // override default register_handler on vector handle handle->_register_handler_parent = handle->vector.register_handler; handle->vector.register_handler = (Vector_slot_t *(*)(Vector_handle_t *, vector_slot_handler_t, void *, void *)) _register_handler_shared; #else // no support for vector handlers if device has no Px_IV register handle->vector.register_handler = (Vector_slot_t *(*)(Vector_handle_t *, vector_slot_handler_t, void *, void *)) _unsupported_operation; #endif return IO_OK; } // ------------------------------------------------------------------------------------- // IO_port_driver_t destructor static dispose_function_t _IO_port_driver_dispose(IO_port_driver_t *_this) { IO_pin_handle_t **handle_ref = &_this->_pin0_handle; uint8_t pin; // disable low-power mode wakeup reinit registered_drivers[_this->_port_no - 1] = NULL; // register new handles is now disabled _this->pin_handle_register = (uint8_t (*)(IO_port_driver_t *, IO_pin_handle_t *, uint8_t)) _unsupported_operation; // restore original vector content dispose(_this->_slot); for (pin = 0; pin < 8; pin++, handle_ref++) { dispose(*handle_ref); } // direct register access is still allowed after disposed return NULL; } // IO_port_driver_t constructor void IO_port_driver_register(IO_port_driver_t *driver, uint8_t port_no, uint16_t base, uint8_t vector_no, port_init_handler_t port_init, uint8_t low_power_mode_pin_reset_filter) { zerofill(driver); driver->_base_register = base; driver->_vector_no = vector_no; driver->_port_no = port_no; driver->_IV_register = base + 0x0E; driver->_low_power_mode_pin_reset_filter = low_power_mode_pin_reset_filter; // PORT_1 -> IV register 0x20E, PORT_2 -> IV register 0x21E, PORT_3 -> IV register 0x22E, PORT_4 -> IV register 0x23E... if (base & 0x0001) { driver->_IV_register += 0x000F; } // store global driver reference registered_drivers[port_no - 1] = driver; if (port_init) { #ifndef __IO_PORT_LEGACY_SUPPORT__ // wakeup available only on FRAM devices driver->_port_init = port_init; #endif // execute port initialization port_init(driver); } // public driver->pin_handle_register = _pin_handle_register; __dispose_hook_register(driver, _IO_port_driver_dispose); } // ------------------------------------------------------------------------------------- void IO_wakeup_reinit() { #ifndef __IO_PORT_LEGACY_SUPPORT__ IO_port_driver_t *port, **port_ref; IO_pin_handle_t *handle, **handle_ref; uint8_t port_index, handle_index; // initialize port registers exactly the same way as they were configured before the device entered LPMx.5 for (port_index = 0, port_ref = registered_drivers; port_index < MAX_PORT_COUNT; port_index++, port_ref++) { if ((port = *port_ref) == NULL || port->_port_init == NULL) { continue; } // initialize port registers port->_port_init(port); if ( ! port->_slot) { continue; } port->_slot = NULL; // reinit port vector slot if set for (handle_index = 0, handle_ref = &port->_pin0_handle; handle_index < 8; handle_index++, handle_ref++) { // search for first handle with registered interrupt handler if ((handle = *handle_ref) != NULL && handle->_handler) { // reset reference to already released slot handle->vector._slot = NULL; // reinit (non-persistent) port vector slot port->_slot = handle->_register_handler_parent(&handle->vector, (vector_slot_handler_t) _shared_vector_handler, port, NULL); // slot is registered just once per port break; } } } #endif IO_unlock(); #ifndef __IO_PORT_LEGACY_SUPPORT__ // disable interrupts so that handler with highest priority shall be triggered first interrupt_suspend(); // enable port interrupts if configured before the device entered LPMx.5 for (port_index = 0, port_ref = registered_drivers; port_index < MAX_PORT_COUNT; port_index++, port_ref++) { if ((port = *port_ref) == NULL || port->_port_init == NULL) { continue; } // search for first handle with registered interrupt handler for (handle_index = 0, handle_ref = &port->_pin0_handle; handle_index < 8; handle_index++, handle_ref++) { // set corresponding interrupt enable bits if vector interrupts were enabled if ((handle = *handle_ref) != NULL && handle->vector.enabled) { vector_set_enabled(&handle->vector, true); } } } interrupt_restore(); #endif } void IO_low_power_mode_prepare() { IO_port_driver_t *port, **port_ref; uint8_t port_index, pin_function_reset_mask; // prepare all registered port drivers for low-power mode for (port_index = 0, port_ref = registered_drivers; port_index < MAX_PORT_COUNT; port_index++, port_ref++) { if ((port = *port_ref) == NULL) { continue; } // restore original vector content (otherwise it would be lost) if (port->_slot) { dispose(port->_slot); } // by default reset all pins to general-purpose IO pin_function_reset_mask = PIN_0 | PIN_1 | PIN_2 | PIN_3 | PIN_4 | PIN_5 | PIN_6 | PIN_7; // filter reset mask if filter set pin_function_reset_mask ^= port->_low_power_mode_pin_reset_filter; #ifdef OFS_PxSELC IO_driver_reg_reset(port, SELC, pin_function_reset_mask); #else IO_driver_reg_reset(port, SEL0, pin_function_reset_mask); #endif } }
2.234375
2
2024-11-18T21:10:11.141540+00:00
2015-09-13T05:04:21
ae443e03f097444940ae3fd6f5264adbe5e9846f
{ "blob_id": "ae443e03f097444940ae3fd6f5264adbe5e9846f", "branch_name": "refs/heads/master", "committer_date": "2015-09-13T05:04:21", "content_id": "7fd1086f145339e3446b163a84f91d5eb56b74db", "detected_licenses": [ "Apache-2.0" ], "directory_id": "6b65f5bb7225533d1927fb1fbecea1310329b4b6", "extension": "c", "filename": "main.c", "fork_events_count": 1, "gha_created_at": "2012-09-29T05:24:46", "gha_event_created_at": "2015-09-13T05:06:38", "gha_language": "C", "gha_license_id": null, "github_id": 6006473, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6421, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/main.c", "provenance": "stackv2-0065.json.gz:29350", "repo_name": "redshadowhero/googauth", "revision_date": "2015-09-13T05:04:21", "revision_id": "3f5e6aecf651b6168a4739bfe2db8c538cc0ffc7", "snapshot_id": "7f81afbfbba839dbd1cc5856fddda061b061b750", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/redshadowhero/googauth/3f5e6aecf651b6168a4739bfe2db8c538cc0ffc7/src/main.c", "visit_date": "2021-04-12T05:20:17.477997" }
stackv2
// 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 <google/google-authenticator.h> #define _BSD_SOURCE // for usleep #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <getopt.h> #include <signal.h> #define VERSIONMAJOR 1 #define VERSIONMINOR 2 #define BUGFIX 1 #define PINLENGTH 6 // The number of digits a pin is supposed to be #define INTERVALLENGTH 30 // The number of seconds in any one given interval #define MAX_KEYSIZE 128 // maximum size a key can be #define HEADER ":----------------------------:--------:\n" \ ": Code Wait Time : Code :\n" \ ":----------------------------:--------:\n" // getopt args #define OPTS "k:f:nl" #define USAGE \ "Usage: %s [OPTIONS...] [keyfile | key]\n" \ "\t-k, --key=KEY\t\tThe key to use\n" \ "\t-f, --file=FILE\t\tThe location of the keyfile\n" \ "\t-n, --no-interface\tTurn the interface off, printing only the latest pin on a new interval\n" \ "\t-l, --no-loop\t\tDon't loop and print the previous key, current key, and next key before exiting\n" \ "\tOptionally, you may specifiy the keyfile or the key with no flags.\n" \ "Version %d.%d.%d\n" // global static int nointerface = 0; static int noloop = 0; static char* exename = NULL; static char* argstr = NULL; static int sigintGiven = 0; struct option long_options[] = { { "key", required_argument, 0, 'k' }, { "file", required_argument, 0, 'f' }, { "no-interface", no_argument, 0, 'n' }, { "no-loop", no_argument, 0, 'l' }, { 0, 0, 0, 0 } }; void printUsage() { printf( USAGE, exename, VERSIONMAJOR, VERSIONMINOR, BUGFIX ); } // end getopts variables #if (defined ( _WIN32 ) || defined ( _WIN64 )) && !defined (LINUX_HOST) #include <windows.h> void usleep( int waitTime ) { __int64 time1 = 0, time2 = 0, freq = 0; QueryPerformanceCounter((LARGE_INTEGER *) &time1); QueryPerformanceFrequency((LARGE_INTEGER *)&freq); do { QueryPerformanceCounter((LARGE_INTEGER *) &time2); } while((time2-time1) < waitTime); } #endif void sigHandler( int sig ) { signal( sig, SIG_IGN ); sigintGiven = 1; signal( SIGINT, sigHandler ); } char* padOutput( int pin ) { char pinstr[12]; char* rv = malloc( sizeof(char)*7 ); rv[6] = 0; size_t pinlen = sprintf( pinstr, "%d", pin ); // We need to make sure the length isn't greater than the accepted pin // length. The behavior is undefined for situations in which the generated // pin is greater in length than 6, so I just return the number. if( pinlen == PINLENGTH || pinlen > PINLENGTH ) return strcpy( rv, pinstr ); // Pad the return string with the appropriate number of zeros for( int i = 0; i < PINLENGTH-pinlen; i++ ) rv[i] = '0'; rv[PINLENGTH-pinlen] = 0; // Concatenate the two strings and return. strcat( rv, pinstr ); return rv; } unsigned long getCurrentInterval() { return (unsigned long)(time(NULL)/INTERVALLENGTH); } void pinLoop( char* key ) { // TODO: sigint support so we can clean up the input pin time_t nsec = time(NULL)+1; // next second unsigned long nextInterval = getCurrentInterval(); // next interval to update at int count = 0; // count for the interface int pin = 0; char* pinstr = NULL; // current pin to print out if( !nointerface ) printf( HEADER ); while( 1 ) { if( time(NULL) >= nsec ) { if( getCurrentInterval() < nextInterval ) { if( !nointerface ) { printf( "." ); count++; fflush( stdout ); } } else // we've moved on to the next interval, and have to update the pin { nextInterval = getCurrentInterval()+1; if( !nointerface ) { for( int i = count+1; i < 30; i++ ) printf( "+" ); } count = 0; if( pinstr ) free( pinstr ); pin = generateCode( key, getCurrentInterval() ); pinstr = padOutput( pin ); if( !nointerface ) printf( ": %s :\n", pinstr ); else printf( "%s\n", pinstr ); } nsec = time(NULL)+1; } if( sigintGiven == 1 ) { if( pinstr ) free( pinstr ); printf( "\n" ); // just so we start on a fresh line. fflush( stdout ); return; } usleep( 900000 ); } } void parseOpts( int argc, char** argv ) { int c; int option_index = 0; FILE* fd; char* key = malloc( sizeof(char)*MAX_KEYSIZE ); char* pin = NULL; exename = argv[0]; while( 1 ) { c = getopt_long( argc, argv, OPTS, long_options, &option_index ); if( c == -1 ) break; switch( c ) { case 'k': if( argstr ) { printUsage(); exit( 1 ); } argstr = optarg; break; case 'f': if( argstr ) { printUsage(); exit( 1 ); } argstr = optarg; break; case 'n': nointerface = 1; break; case 'l': noloop = 1; break; } } while( optind < argc ) // just cycle through and get the last argument { argstr = argv[optind]; optind++; } if( argstr == NULL ) { free( key ); exit( 4 ); } // check if argstr is a file if( (fd = fopen( argstr, "r" )) ) fscanf( fd, "%s", key ); else // try as the key key = argstr; if( !noloop ) pinLoop( key ); else { unsigned long interval = getCurrentInterval(); pin = padOutput( generateCode( key, interval-1 ) ); printf( "%s, ", pin ); free( pin ); pin = padOutput( generateCode( key, interval ) ); printf( "%s, ", pin ); free( pin ); pin = padOutput( generateCode( key, interval+1 ) ); printf( "%s\n", pin ); free( pin ); } if( key != argstr ) free( key ); // argstr comes from argv; best not to free it } int main( int argc, char* argv[] ) { signal( SIGINT, sigHandler ); exename = argv[0]; if( argc < 2 ) { printUsage(); return 4; } parseOpts( argc, argv ); return 0; }
2.359375
2
2024-11-18T21:10:11.273357+00:00
2011-09-10T16:49:43
ee62e2e64f1f2ef6ada7a686b470e20162aa8107
{ "blob_id": "ee62e2e64f1f2ef6ada7a686b470e20162aa8107", "branch_name": "refs/heads/master", "committer_date": "2011-09-10T16:49:43", "content_id": "6be7214c5c8d41548ffda47c434a040cfe9f832f", "detected_licenses": [ "MIT-advertising" ], "directory_id": "64b5f8f8fff4177bbb6a1f10480a8442fba2b781", "extension": "c", "filename": "ecore_con_ssl.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 68143811, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 18306, "license": "MIT-advertising", "license_type": "permissive", "path": "/src/lib/ecore_con/ecore_con_ssl.c", "provenance": "stackv2-0065.json.gz:29606", "repo_name": "OpenInkpot/ecore", "revision_date": "2011-09-10T16:49:43", "revision_id": "ff995d40902635df3e765be3c94db45a93bc8594", "snapshot_id": "305273a4c26a19eb56257e47f559041bc44213c2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/OpenInkpot/ecore/ff995d40902635df3e765be3c94db45a93bc8594/src/lib/ecore_con/ecore_con_ssl.c", "visit_date": "2020-01-28T15:40:33.275142" }
stackv2
/* * vim:ts=8:sw=3:sts=8:noexpandtab:cino=>5n-3f0^-2{2 */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #if USE_GNUTLS # include <gnutls/gnutls.h> #elif USE_OPENSSL # include <openssl/ssl.h> #endif #ifdef HAVE_WS2TCPIP_H # include <ws2tcpip.h> #endif #include "Ecore.h" #include "ecore_con_private.h" static int _init_con_ssl_init_count = 0; #if USE_GNUTLS static int _client_connected = 0; # define SSL_SUFFIX(ssl_func) ssl_func##_gnutls # define _ECORE_CON_SSL_AVAILABLE 1 #elif USE_OPENSSL # define SSL_SUFFIX(ssl_func) ssl_func##_openssl # define _ECORE_CON_SSL_AVAILABLE 2 #else # define SSL_SUFFIX(ssl_func) ssl_func##_none # define _ECORE_CON_SSL_AVAILABLE 0 #endif static Ecore_Con_Ssl_Error SSL_SUFFIX(_ecore_con_ssl_init)(void); static Ecore_Con_Ssl_Error SSL_SUFFIX(_ecore_con_ssl_shutdown)(void); static void SSL_SUFFIX(_ecore_con_ssl_server_prepare)(Ecore_Con_Server *svr); static Ecore_Con_Ssl_Error SSL_SUFFIX(_ecore_con_ssl_server_init)(Ecore_Con_Server *svr); static Ecore_Con_Ssl_Error SSL_SUFFIX(_ecore_con_ssl_server_shutdown)(Ecore_Con_Server *svr); static Ecore_Con_State SSL_SUFFIX(_ecore_con_ssl_server_try)(Ecore_Con_Server *svr); static int SSL_SUFFIX(_ecore_con_ssl_server_read)(Ecore_Con_Server *svr, unsigned char *buf, int size); static int SSL_SUFFIX(_ecore_con_ssl_server_write)(Ecore_Con_Server *svr, unsigned char *buf, int size); static void SSL_SUFFIX(_ecore_con_ssl_client_prepare)(Ecore_Con_Client *cl); static Ecore_Con_Ssl_Error SSL_SUFFIX(_ecore_con_ssl_client_init)(Ecore_Con_Client *cl); static Ecore_Con_Ssl_Error SSL_SUFFIX(_ecore_con_ssl_client_shutdown)(Ecore_Con_Client *cl); static int SSL_SUFFIX(_ecore_con_ssl_client_read)(Ecore_Con_Client *cl, unsigned char *buf, int size); static int SSL_SUFFIX(_ecore_con_ssl_client_write)(Ecore_Con_Client *cl, unsigned char *buf, int size); /* * General SSL API */ Ecore_Con_Ssl_Error ecore_con_ssl_init(void) { if (!_init_con_ssl_init_count++) SSL_SUFFIX(_ecore_con_ssl_init)(); return _init_con_ssl_init_count; } Ecore_Con_Ssl_Error ecore_con_ssl_shutdown(void) { if (!--_init_con_ssl_init_count) SSL_SUFFIX(_ecore_con_ssl_shutdown)(); return _init_con_ssl_init_count; } /** * Returns if SSL support is available * @return 1 if SSL is available, 0 if it is not. * @ingroup Ecore_Con_Client_Group */ int ecore_con_ssl_available_get(void) { return _ECORE_CON_SSL_AVAILABLE; } void ecore_con_ssl_server_prepare(Ecore_Con_Server *svr) { SSL_SUFFIX(_ecore_con_ssl_server_prepare)(svr); } Ecore_Con_Ssl_Error ecore_con_ssl_server_init(Ecore_Con_Server *svr) { return SSL_SUFFIX(_ecore_con_ssl_server_init)(svr); } Ecore_Con_Ssl_Error ecore_con_ssl_server_shutdown(Ecore_Con_Server *svr) { return SSL_SUFFIX(_ecore_con_ssl_server_shutdown)(svr); } Ecore_Con_State ecore_con_ssl_server_try(Ecore_Con_Server *svr) { return SSL_SUFFIX(_ecore_con_ssl_server_try)(svr); } int ecore_con_ssl_server_read(Ecore_Con_Server *svr, unsigned char *buf, int size) { return SSL_SUFFIX(_ecore_con_ssl_server_read)(svr, buf, size); } int ecore_con_ssl_server_write(Ecore_Con_Server *svr, unsigned char *buf, int size) { return SSL_SUFFIX(_ecore_con_ssl_server_write)(svr, buf, size); } Ecore_Con_Ssl_Error ecore_con_ssl_client_init(Ecore_Con_Client *cl) { return SSL_SUFFIX(_ecore_con_ssl_client_init)(cl); } Ecore_Con_Ssl_Error ecore_con_ssl_client_shutdown(Ecore_Con_Client *cl) { return SSL_SUFFIX(_ecore_con_ssl_client_shutdown)(cl); } int ecore_con_ssl_client_read(Ecore_Con_Client *cl, unsigned char *buf, int size) { return SSL_SUFFIX(_ecore_con_ssl_client_read)(cl, buf, size); } int ecore_con_ssl_client_write(Ecore_Con_Client *cl, unsigned char *buf, int size) { return SSL_SUFFIX(_ecore_con_ssl_client_write)(cl, buf, size); } #if USE_GNUTLS /* * GnuTLS */ static Ecore_Con_Ssl_Error _ecore_con_ssl_init_gnutls(void) { if (gnutls_global_init()) return ECORE_CON_SSL_ERROR_INIT_FAILED; return ECORE_CON_SSL_ERROR_NONE; } static Ecore_Con_Ssl_Error _ecore_con_ssl_shutdown_gnutls(void) { gnutls_global_deinit(); return ECORE_CON_SSL_ERROR_NONE; } static void _ecore_con_ssl_server_prepare_gnutls(Ecore_Con_Server *svr) { svr->session = NULL; svr->anoncred_c = NULL; return; } static Ecore_Con_Ssl_Error _ecore_con_ssl_server_init_gnutls(Ecore_Con_Server *svr) { const int *proto = NULL; int ret; const int kx[] = { GNUTLS_KX_ANON_DH, 0 }; const int ssl3_proto[] = { GNUTLS_SSL3, 0 }; const int tls_proto[] = { GNUTLS_TLS1_0, GNUTLS_TLS1_1, #ifdef USE_GNUTLS2 GNUTLS_TLS1_2, #endif 0 }; switch (svr->type & ECORE_CON_SSL) { case ECORE_CON_USE_SSL2: /* not supported because of security issues */ return ECORE_CON_SSL_ERROR_SSL2_NOT_SUPPORTED; case ECORE_CON_USE_SSL3: proto = ssl3_proto; break; case ECORE_CON_USE_TLS: proto = tls_proto; break; default: return ECORE_CON_SSL_ERROR_NONE; } gnutls_anon_allocate_client_credentials(&(svr->anoncred_c)); gnutls_init(&(svr->session), GNUTLS_CLIENT); gnutls_set_default_priority(svr->session); gnutls_kx_set_priority(svr->session, kx); gnutls_credentials_set(svr->session, GNUTLS_CRD_ANON, svr->anoncred_c); gnutls_kx_set_priority(svr->session, kx); gnutls_protocol_set_priority(svr->session, proto); gnutls_dh_set_prime_bits(svr->session, 512); gnutls_transport_set_ptr(svr->session, (gnutls_transport_ptr_t)svr->fd); while ((ret = gnutls_handshake(svr->session)) < 0) { if ((ret == GNUTLS_E_AGAIN) || (ret == GNUTLS_E_INTERRUPTED)) continue; _ecore_con_ssl_server_shutdown_gnutls(svr); return ECORE_CON_SSL_ERROR_SERVER_INIT_FAILED; } return ECORE_CON_SSL_ERROR_NONE; } static Ecore_Con_Ssl_Error _ecore_con_ssl_server_shutdown_gnutls(Ecore_Con_Server *svr) { if (svr->session) { gnutls_bye(svr->session, GNUTLS_SHUT_RDWR); gnutls_deinit(svr->session); } if (svr->anoncred_c) gnutls_anon_free_client_credentials(svr->anoncred_c); _ecore_con_ssl_server_prepare_gnutls(svr); return ECORE_CON_SSL_ERROR_NONE; } /* Tries to connect an Ecore_Con_Server to an SSL host. * Returns 1 on success, -1 on fatal errors and 0 if the caller * should try again later. */ static Ecore_Con_State _ecore_con_ssl_server_try_gnutls(Ecore_Con_Server *svr __UNUSED__) { return ECORE_CON_CONNECTED; } static int _ecore_con_ssl_server_read_gnutls(Ecore_Con_Server *svr, unsigned char *buf, int size) { int num; num = gnutls_record_recv(svr->session, buf, size); if (num > 0) return num; if ((num == GNUTLS_E_AGAIN) || (num == GNUTLS_E_REHANDSHAKE) || (num == GNUTLS_E_INTERRUPTED)) return 0; return -1; } static int _ecore_con_ssl_server_write_gnutls(Ecore_Con_Server *svr, unsigned char *buf, int size) { int num; num = gnutls_record_send(svr->session, buf, size); if (num > 0) return num; if ((num == GNUTLS_E_AGAIN) || (num == GNUTLS_E_REHANDSHAKE) || (num == GNUTLS_E_INTERRUPTED)) return 0; return -1; } static void _ecore_con_ssl_client_prepare_gnutls(Ecore_Con_Client *cl) { cl->session = NULL; if (!_client_connected) cl->server->anoncred_s = NULL; } static Ecore_Con_Ssl_Error _ecore_con_ssl_client_init_gnutls(Ecore_Con_Client *cl) { const int *proto = NULL; gnutls_dh_params_t dh_params; int ret; const int kx[] = { GNUTLS_KX_ANON_DH, 0 }; const int ssl3_proto[] = { GNUTLS_SSL3, 0 }; const int tls_proto[] = { GNUTLS_TLS1_0, GNUTLS_TLS1_1, #ifdef USE_GNUTLS2 GNUTLS_TLS1_2, #endif 0 }; switch (cl->server->type & ECORE_CON_SSL) { case ECORE_CON_USE_SSL2: /* not supported because of security issues */ return ECORE_CON_SSL_ERROR_SSL2_NOT_SUPPORTED; case ECORE_CON_USE_SSL3: proto = ssl3_proto; break; case ECORE_CON_USE_TLS: proto = tls_proto; break; default: return ECORE_CON_SSL_ERROR_NONE; } _client_connected++; if (!cl->server->anoncred_s) { gnutls_anon_allocate_server_credentials(&(cl->server->anoncred_s)); gnutls_dh_params_init(&dh_params); gnutls_dh_params_generate2(dh_params, 512); gnutls_anon_set_server_dh_params(cl->server->anoncred_s, dh_params); } gnutls_init(&(cl->session), GNUTLS_SERVER); gnutls_set_default_priority(cl->session); gnutls_credentials_set(cl->session, GNUTLS_CRD_ANON, cl->server->anoncred_s); gnutls_kx_set_priority(cl->session, kx); gnutls_protocol_set_priority(cl->session, proto); gnutls_dh_set_prime_bits(cl->session, 512); gnutls_transport_set_ptr(cl->session, (gnutls_transport_ptr_t)cl->fd); while ((ret = gnutls_handshake(cl->session)) < 0) { if ((ret == GNUTLS_E_AGAIN) || (ret == GNUTLS_E_INTERRUPTED)) continue; _ecore_con_ssl_client_shutdown_gnutls(cl); return ECORE_CON_SSL_ERROR_SERVER_INIT_FAILED; } return ECORE_CON_SSL_ERROR_NONE; } static Ecore_Con_Ssl_Error _ecore_con_ssl_client_shutdown_gnutls(Ecore_Con_Client *cl) { if (cl->session) { gnutls_bye(cl->session, GNUTLS_SHUT_RDWR); gnutls_deinit(cl->session); } if (cl->server->anoncred_s && !--_client_connected) gnutls_anon_free_server_credentials(cl->server->anoncred_s); _ecore_con_ssl_client_prepare_gnutls(cl); return ECORE_CON_SSL_ERROR_NONE; } static int _ecore_con_ssl_client_read_gnutls(Ecore_Con_Client *cl, unsigned char *buf, int size) { int num; num = gnutls_record_recv(cl->session, buf, size); if (num > 0) return num; if ((num == GNUTLS_E_AGAIN) || (num == GNUTLS_E_REHANDSHAKE) || (num == GNUTLS_E_INTERRUPTED)) return 0; return -1; } static int _ecore_con_ssl_client_write_gnutls(Ecore_Con_Client *cl, unsigned char *buf, int size) { int num; num = gnutls_record_send(cl->session, buf, size); if (num > 0) return num; if ((num == GNUTLS_E_AGAIN) || (num == GNUTLS_E_REHANDSHAKE) || (num == GNUTLS_E_INTERRUPTED)) return 0; return -1; } #elif USE_OPENSSL /* * OpenSSL */ static Ecore_Con_Ssl_Error _ecore_con_ssl_init_openssl(void) { SSL_library_init(); SSL_load_error_strings(); return ECORE_CON_SSL_ERROR_NONE; } static Ecore_Con_Ssl_Error _ecore_con_ssl_shutdown_openssl(void) { // FIXME nothing to do ? return ECORE_CON_SSL_ERROR_NONE; } static void _ecore_con_ssl_server_prepare_openssl(Ecore_Con_Server *svr) { svr->ssl = NULL; svr->ssl_ctx = NULL; svr->ssl_err = SSL_ERROR_NONE; } static Ecore_Con_Ssl_Error _ecore_con_ssl_server_init_openssl(Ecore_Con_Server *svr) { switch (svr->type & ECORE_CON_SSL) { case ECORE_CON_USE_SSL2: /* Unsafe version of SSL */ if (!(svr->ssl_ctx = SSL_CTX_new(SSLv2_client_method()))) return ECORE_CON_SSL_ERROR_SERVER_INIT_FAILED; break; case ECORE_CON_USE_SSL3: if (!(svr->ssl_ctx = SSL_CTX_new(SSLv3_client_method()))) return ECORE_CON_SSL_ERROR_SERVER_INIT_FAILED; break; case ECORE_CON_USE_TLS: if (!(svr->ssl_ctx = SSL_CTX_new(TLSv1_client_method()))) return ECORE_CON_SSL_ERROR_SERVER_INIT_FAILED; break; default: return ECORE_CON_SSL_ERROR_NONE; } if (!(svr->ssl = SSL_new(svr->ssl_ctx))) { SSL_CTX_free(svr->ssl_ctx); return ECORE_CON_SSL_ERROR_SERVER_INIT_FAILED; } SSL_set_fd(svr->ssl, svr->fd); return ECORE_CON_SSL_ERROR_NONE; } static Ecore_Con_Ssl_Error _ecore_con_ssl_server_shutdown_openssl(Ecore_Con_Server *svr) { if (svr->ssl) { if (!SSL_shutdown(svr->ssl)) SSL_shutdown(svr->ssl); SSL_free(svr->ssl); } if (svr->ssl_ctx) SSL_CTX_free(svr->ssl_ctx); _ecore_con_ssl_server_prepare_openssl(svr); return ECORE_CON_SSL_ERROR_NONE; } /* Tries to connect an Ecore_Con_Server to an SSL host. * Returns 1 on success, -1 on fatal errors and 0 if the caller * should try again later. */ static Ecore_Con_State _ecore_con_ssl_server_try_openssl(Ecore_Con_Server *svr) { int res, flag = 0; if ((res = SSL_connect(svr->ssl)) == 1) return ECORE_CON_CONNECTED; svr->ssl_err = SSL_get_error(svr->ssl, res); switch (svr->ssl_err) { case SSL_ERROR_NONE: return ECORE_CON_CONNECTED; case SSL_ERROR_WANT_READ: flag = ECORE_FD_READ; break; case SSL_ERROR_WANT_WRITE: flag = ECORE_FD_WRITE; break; default: return ECORE_CON_DISCONNECTED; } if (svr->fd_handler && flag) ecore_main_fd_handler_active_set(svr->fd_handler, flag); return ECORE_CON_INPROGRESS; } static int _ecore_con_ssl_server_read_openssl(Ecore_Con_Server *svr, unsigned char *buf, int size) { int num; num = SSL_read(svr->ssl, buf, size); svr->ssl_err = SSL_get_error(svr->ssl, num); if (svr->fd_handler) { if (svr->ssl && svr->ssl_err == SSL_ERROR_WANT_READ) ecore_main_fd_handler_active_set(svr->fd_handler, ECORE_FD_READ); else if (svr->ssl && svr->ssl_err == SSL_ERROR_WANT_WRITE) ecore_main_fd_handler_active_set(svr->fd_handler, ECORE_FD_WRITE); } if ((svr->ssl_err == SSL_ERROR_ZERO_RETURN) || (svr->ssl_err == SSL_ERROR_SYSCALL) || (svr->ssl_err == SSL_ERROR_SSL)) return -1; if (num < 0) return 0; return num; } static int _ecore_con_ssl_server_write_openssl(Ecore_Con_Server *svr, unsigned char *buf, int size) { int num; num = SSL_write(svr->ssl, buf, size); svr->ssl_err = SSL_get_error(svr->ssl, num); if (svr->fd_handler) { if (svr->ssl && svr->ssl_err == SSL_ERROR_WANT_READ) ecore_main_fd_handler_active_set(svr->fd_handler, ECORE_FD_READ); else if (svr->ssl && svr->ssl_err == SSL_ERROR_WANT_WRITE) ecore_main_fd_handler_active_set(svr->fd_handler, ECORE_FD_WRITE); } if ((svr->ssl_err == SSL_ERROR_ZERO_RETURN) || (svr->ssl_err == SSL_ERROR_SYSCALL) || (svr->ssl_err == SSL_ERROR_SSL)) return -1; if (num < 0) return 0; return num; } static void _ecore_con_ssl_client_prepare_openssl(Ecore_Con_Client *cl) { cl->ssl = NULL; cl->ssl_ctx = NULL; cl->ssl_err = SSL_ERROR_NONE; } static Ecore_Con_Ssl_Error _ecore_con_ssl_client_init_openssl(Ecore_Con_Client *cl) { switch (cl->server->type & ECORE_CON_SSL) { case ECORE_CON_USE_SSL2: /* Unsafe version of SSL */ if (!(cl->ssl_ctx = SSL_CTX_new(SSLv2_client_method()))) return ECORE_CON_SSL_ERROR_SERVER_INIT_FAILED; break; case ECORE_CON_USE_SSL3: if (!(cl->ssl_ctx = SSL_CTX_new(SSLv3_client_method()))) return ECORE_CON_SSL_ERROR_SERVER_INIT_FAILED; break; case ECORE_CON_USE_TLS: if (!(cl->ssl_ctx = SSL_CTX_new(TLSv1_client_method()))) return ECORE_CON_SSL_ERROR_SERVER_INIT_FAILED; break; default: return ECORE_CON_SSL_ERROR_NONE; } if (!(cl->ssl = SSL_new(cl->ssl_ctx))) { SSL_CTX_free(cl->ssl_ctx); return ECORE_CON_SSL_ERROR_SERVER_INIT_FAILED; } SSL_set_fd(cl->ssl, cl->fd); return ECORE_CON_SSL_ERROR_NONE; } static Ecore_Con_Ssl_Error _ecore_con_ssl_client_shutdown_openssl(Ecore_Con_Client *cl) { if (cl->ssl) { if (!SSL_shutdown(cl->ssl)) SSL_shutdown(cl->ssl); SSL_free(cl->ssl); } if (cl->ssl_ctx) SSL_CTX_free(cl->ssl_ctx); _ecore_con_ssl_client_prepare_openssl(cl); return ECORE_CON_SSL_ERROR_NONE; } static int _ecore_con_ssl_client_read_openssl(Ecore_Con_Client *cl, unsigned char *buf, int size) { int num; num = SSL_read(cl->ssl, buf, size); cl->ssl_err = SSL_get_error(cl->ssl, num); if (cl->fd_handler) { if (cl->ssl && cl->ssl_err == SSL_ERROR_WANT_READ) ecore_main_fd_handler_active_set(cl->fd_handler, ECORE_FD_READ); else if (cl->ssl && cl->ssl_err == SSL_ERROR_WANT_WRITE) ecore_main_fd_handler_active_set(cl->fd_handler, ECORE_FD_WRITE); } if ((cl->ssl_err == SSL_ERROR_ZERO_RETURN) || (cl->ssl_err == SSL_ERROR_SYSCALL) || (cl->ssl_err == SSL_ERROR_SSL)) return -1; if (num < 0) return 0; return num; } static int _ecore_con_ssl_client_write_openssl(Ecore_Con_Client *cl, unsigned char *buf, int size) { int num; num = SSL_write(cl->ssl, buf, size); cl->ssl_err = SSL_get_error(cl->ssl, num); if (cl->fd_handler) { if (cl->ssl && cl->ssl_err == SSL_ERROR_WANT_READ) ecore_main_fd_handler_active_set(cl->fd_handler, ECORE_FD_READ); else if (cl->ssl && cl->ssl_err == SSL_ERROR_WANT_WRITE) ecore_main_fd_handler_active_set(cl->fd_handler, ECORE_FD_WRITE); } if ((cl->ssl_err == SSL_ERROR_ZERO_RETURN) || (cl->ssl_err == SSL_ERROR_SYSCALL) || (cl->ssl_err == SSL_ERROR_SSL)) return -1; if (num < 0) return 0; return num; } #else /* * No Ssl */ static Ecore_Con_Ssl_Error _ecore_con_ssl_init_none(void) { return ECORE_CON_SSL_ERROR_NONE; } static Ecore_Con_Ssl_Error _ecore_con_ssl_shutdown_none(void) { return ECORE_CON_SSL_ERROR_NONE; } static void _ecore_con_ssl_server_prepare_none(Ecore_Con_Server *svr) { } static Ecore_Con_Ssl_Error _ecore_con_ssl_server_init_none(Ecore_Con_Server *svr) { return ECORE_CON_SSL_ERROR_NOT_SUPPORTED; } static Ecore_Con_Ssl_Error _ecore_con_ssl_server_shutdown_none(Ecore_Con_Server *svr) { return ECORE_CON_SSL_ERROR_NOT_SUPPORTED; } /* Tries to connect an Ecore_Con_Server to an SSL host. * Returns 1 on success, -1 on fatal errors and 0 if the caller * should try again later. */ static Ecore_Con_State _ecore_con_ssl_server_try_none(Ecore_Con_Server *svr) { return ECORE_CON_DISCONNECTED; } static int _ecore_con_ssl_server_read_none(Ecore_Con_Server *svr, unsigned char *buf, int size) { return -1; } static int _ecore_con_ssl_server_write_none(Ecore_Con_Server *svr, unsigned char *buf, int size) { return -1; } static void _ecore_con_ssl_client_prepare_none(Ecore_Con_Client *cl) { return; } static Ecore_Con_Ssl_Error _ecore_con_ssl_client_init_none(Ecore_Con_Client *cl) { return ECORE_CON_SSL_ERROR_NOT_SUPPORTED; } static Ecore_Con_Ssl_Error _ecore_con_ssl_client_shutdown_none(Ecore_Con_Client *cl) { return ECORE_CON_SSL_ERROR_NOT_SUPPORTED; } static int _ecore_con_ssl_client_read_none(Ecore_Con_Client *cl, unsigned char *buf, int size) { return -1; } static int _ecore_con_ssl_client_write_none(Ecore_Con_Client *cl, unsigned char *buf, int size) { return -1; } #endif
2.046875
2
2024-11-18T21:10:11.672027+00:00
2019-07-08T13:20:36
be66f0dce2a466fe7c12ea5678165a9b632383be
{ "blob_id": "be66f0dce2a466fe7c12ea5678165a9b632383be", "branch_name": "refs/heads/master", "committer_date": "2019-07-08T13:20:36", "content_id": "c765ee6fac5761211369718ff5a1046344502d4e", "detected_licenses": [ "MIT" ], "directory_id": "726d8b758ed3c18cb26b34203caebac3387e9c03", "extension": "h", "filename": "queue2.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 195790789, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 605, "license": "MIT", "license_type": "permissive", "path": "/exercise/queue2.h", "provenance": "stackv2-0065.json.gz:29734", "repo_name": "errikosg/WebServer_Crawler", "revision_date": "2019-07-08T13:20:36", "revision_id": "68adbc33ab105f0442e6bad55887a588fd2bcb0c", "snapshot_id": "73bf4f4e4181e65b92d109ddb5acce7eb2c475c6", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/errikosg/WebServer_Crawler/68adbc33ab105f0442e6bad55887a588fd2bcb0c/exercise/queue2.h", "visit_date": "2020-06-17T04:08:26.293371" }
stackv2
#ifndef QUEUE2_H #define QUEUE2_H //this is Queue implemented with linked list -->use for url queue of webcrawler //(header of queue2.c) typedef struct QueueNodeType* q_lnk; struct QueueNodeType{ char *item; q_lnk next; }; typedef struct{ q_lnk front; q_lnk rear; int count; }url_queue; //functions void uqueue_initialize(url_queue *); int uqueue_isEmpty(url_queue *); void uqueue_insert(url_queue *, char *); void uqueue_remove(url_queue *, char **); //here we extract the item. void uqueue_print(url_queue *); int uqueue_search(url_queue *, char *); void uqueue_freeQ(url_queue *); #endif
2.21875
2
2024-11-18T21:10:12.207312+00:00
2015-05-03T09:28:43
aa7c132a6676907d56d8924fb95098af9c4d298f
{ "blob_id": "aa7c132a6676907d56d8924fb95098af9c4d298f", "branch_name": "refs/heads/master", "committer_date": "2015-05-03T09:28:43", "content_id": "508472d84f3ebe7e20759bbd2a9f08251f32ffa5", "detected_licenses": [ "MIT" ], "directory_id": "4d676e4bb9e956c57d5d9dbd921d385def523c4f", "extension": "h", "filename": "cls.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 29463147, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3008, "license": "MIT", "license_type": "permissive", "path": "/imp/cls.h", "provenance": "stackv2-0065.json.gz:30633", "repo_name": "wcy123/voba_value", "revision_date": "2015-05-03T09:28:43", "revision_id": "658a22db2b9c497c0deefd6a45190c59236fb964", "snapshot_id": "8dff51f6630f3296561738b7e5fe16d986de9784", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/wcy123/voba_value/658a22db2b9c497c0deefd6a45190c59236fb964/imp/cls.h", "visit_date": "2021-01-23T06:44:37.822167" }
stackv2
#pragma once /**@file cls === The first user defined data type is a cls itself. here is a table of all built-in class | var name | note | |------------------------|--------------------------------------| | voba_cls_func | function object, see fun.h | | voba_cls_symbol | symbol, see symbol.h | | voba_cls_tuple | tuple, see tuple.h | | voba_cls_closure | closure, see closure.h | | voba_cls_pair | pair, see pair.h | | voba_cls_str | str, see str.h | | voba_cls_nil | nil, see small.h | | voba_cls_bool | bool, see small.h | | voba_cls_u8 | unsigned 8-bit integer, see small.h | | voba_cls_i8 | signed 8-bit integer, see small.h | | voba_cls_u16 | unsigned 16-bit integer, see small.h | | voba_cls_i16 | signed 16-bit integer, see small.h | | voba_cls_u32 | unsigned 32-bit integer, see small.h | | voba_cls_i32 | sigend 32-bit integer, see small.h | | voba_cls_float | float, see small.h | | voba_cls_short_symbol | short symbol, see small.h | | voba_cls_undef | VOBA_UNDEF, see small.h | | voba_cls_done | VOBA_DONE, see small.h | | voba_cls_hashtable | hash table, see hash.h | | voba_cls_symbol_table | symbol table, see symbol_table.h | | voba_cls_voba_array | array, see array.h | | voba_cls_voba_gf | generic function, see gf.h | | voba_cls_voba_la_t | list view, see la.h | | voba_cls_cg_t | generator, see generator.h | */ extern voba_value_t voba_cls_cls; /*!< the class object associated with \a cls itself */ typedef struct voba_cls_s voba_cls_t; /** */ struct voba_cls_s { size_t size; /*!< the size of user defined object*/ const char * name; /*!< the name of class */ }; extern voba_cls_t * the_voba_class_table; extern int32_t the_voba_class_table_length; /** @return a \a cls obejct which represents the class of the object \a v*/ INLINE voba_value_t voba_get_class(voba_value_t v) __attribute__((always_inline)); /** @return the name of the class object */ INLINE const char * voba_get_class_name(voba_value_t v); #define VOBA_DEF_CLS(xsize,xname) \ voba_value_t voba_cls_##xname = VOBA_UNDEF; \ EXEC_ONCE_PROGN \ { \ voba_cls_##xname = voba_make_cls(xsize,#xname); \ } INLINE int32_t voba_class_id(voba_value_t cls) __attribute__((always_inline)); INLINE const char* voba_cls_name(voba_value_t cls); INLINE size_t voba_cls_size(voba_value_t cls);
2.015625
2
2024-11-18T21:10:12.296509+00:00
2023-03-08T20:42:48
5da4cb0edc17b0499fb266b9e76d644668fbc36c
{ "blob_id": "5da4cb0edc17b0499fb266b9e76d644668fbc36c", "branch_name": "refs/heads/master", "committer_date": "2023-03-08T20:42:48", "content_id": "0c0f70a7d43a70e24d6dfee25b5b7a8be3f49865", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "0ab78d9b913d22b626508ab993367555cc099fcb", "extension": "h", "filename": "libchash.h", "fork_events_count": 43, "gha_created_at": "2014-03-18T22:38:20", "gha_event_created_at": "2023-01-31T20:21:38", "gha_language": "C++", "gha_license_id": "BSD-2-Clause", "github_id": 17884512, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12377, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/benchmark/lib/google/libchash.h", "provenance": "stackv2-0065.json.gz:30762", "repo_name": "amadvance/tommyds", "revision_date": "2023-03-08T20:42:48", "revision_id": "97ff74356f6d5ae899b9cb672deb803da01270ca", "snapshot_id": "b6da1248ca72fa8a708bd4b5a9e852ef693b1613", "src_encoding": "UTF-8", "star_events_count": 214, "url": "https://raw.githubusercontent.com/amadvance/tommyds/97ff74356f6d5ae899b9cb672deb803da01270ca/benchmark/lib/google/libchash.h", "visit_date": "2023-03-21T14:16:20.853027" }
stackv2
/* Copyright (c) 1998 - 2005, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * --- * Author: Craig Silverstein * * This library is intended to be used for in-memory hash tables, * though it provides rudimentary permanent-storage capabilities. * It attempts to be fast, portable, and small. The best algorithm * to fulfill these goals is an internal probing hashing algorithm, * as in Knuth, _Art of Computer Programming_, vol III. Unlike * chained (open) hashing, it doesn't require a pointer for every * item, yet it is still constant time lookup in practice. * * Also to save space, we let the contents (both data and key) that * you insert be a union: if the key/data is small, we store it * directly in the hashtable, otherwise we store a pointer to it. * To keep you from having to figure out which, use KEY_PTR and * PTR_KEY to convert between the arguments to these functions and * a pointer to the real data. For instance: * char key[] = "ab", *key2; * HTItem *bck; HashTable *ht; * HashInsert(ht, PTR_KEY(ht, key), 0); * bck = HashFind(ht, PTR_KEY(ht, "ab")); * key2 = KEY_PTR(ht, bck->key); * * There are a rich set of operations supported: * AllocateHashTable() -- Allocates a hashtable structure and * returns it. * cchKey: if it's a positive number, then each key is a * fixed-length record of that length. If it's 0, * the key is assumed to be a \0-terminated string. * fSaveKey: normally, you are responsible for allocating * space for the key. If this is 1, we make a * copy of the key for you. * ClearHashTable() -- Removes everything from a hashtable * FreeHashTable() -- Frees memory used by a hashtable * * HashFind() -- takes a key (use PTR_KEY) and returns the * HTItem containing that key, or NULL if the * key is not in the hashtable. * HashFindLast() -- returns the item found by last HashFind() * HashFindOrInsert() -- inserts the key/data pair if the key * is not already in the hashtable, or * returns the appropraite HTItem if it is. * HashFindOrInsertItem() -- takes key/data as an HTItem. * HashInsert() -- adds a key/data pair to the hashtable. What * it does if the key is already in the table * depends on the value of SAMEKEY_OVERWRITE. * HashInsertItem() -- takes key/data as an HTItem. * HashDelete() -- removes a key/data pair from the hashtable, * if it's there. RETURNS 1 if it was there, * 0 else. * If you use sparse tables and never delete, the full data * space is available. Otherwise we steal -2 (maybe -3), * so you can't have data fields with those values. * HashDeleteLast() -- deletes the item returned by the last Find(). * * HashFirstBucket() -- used to iterate over the buckets in a * hashtable. DON'T INSERT OR DELETE WHILE * ITERATING! You can't nest iterations. * HashNextBucket() -- RETURNS NULL at the end of iterating. * * HashSetDeltaGoalSize() -- if you're going to insert 1000 items * at once, call this fn with arg 1000. * It grows the table more intelligently. * * HashSave() -- saves the hashtable to a file. It saves keys ok, * but it doesn't know how to interpret the data field, * so if the data field is a pointer to some complex * structure, you must send a function that takes a * file pointer and a pointer to the structure, and * write whatever you want to write. It should return * the number of bytes written. If the file is NULL, * it should just return the number of bytes it would * write, without writing anything. * If your data field is just an integer, not a * pointer, just send NULL for the function. * HashLoad() -- loads a hashtable. It needs a function that takes * a file and the size of the structure, and expects * you to read in the structure and return a pointer * to it. You must do memory allocation, etc. If * the data is just a number, send NULL. * HashLoadKeys() -- unlike HashLoad(), doesn't load the data off disk * until needed. This saves memory, but if you look * up the same key a lot, it does a disk access each * time. * You can't do Insert() or Delete() on hashtables that were loaded * from disk. */ #include <sys/types.h> /* includes definition of "ulong", we hope */ #define ulong u_long #define MAGIC_KEY "CHsh" /* when we save the file */ #ifndef LOG_WORD_SIZE /* 5 for 32 bit words, 6 for 64 */ #if defined (__LP64__) || defined (_LP64) #define LOG_WORD_SIZE 6 /* log_2(sizeof(ulong)) [in bits] */ #else #define LOG_WORD_SIZE 5 /* log_2(sizeof(ulong)) [in bits] */ #endif #endif /* The following gives a speed/time tradeoff: how many buckets are * * in each bin. 0 gives 32 buckets/bin, which is a good number. */ #ifndef LOG_BM_WORDS #define LOG_BM_WORDS 0 /* each group has 2^L_B_W * 32 buckets */ #endif /* The following are all parameters that affect performance. */ #ifndef JUMP #define JUMP(key, offset) ( ++(offset) ) /* ( 1 ) for linear hashing */ #endif #ifndef Table #define Table(x) Sparse##x /* Dense##x for dense tables */ #endif #ifndef FAST_DELETE #define FAST_DELETE 0 /* if it's 1, we never shrink the ht */ #endif #ifndef SAMEKEY_OVERWRITE #define SAMEKEY_OVERWRITE 1 /* overwrite item with our key on insert? */ #endif #ifndef OCCUPANCY_PCT #define OCCUPANCY_PCT 0.5 /* large PCT means smaller and slower */ #endif #ifndef MIN_HASH_SIZE #define MIN_HASH_SIZE 512 /* ht size when first created */ #endif /* When deleting a bucket, we can't just empty it (future hashes * * may fail); instead we set the data field to DELETED. Thus you * * should set DELETED to a data value you never use. Better yet, * * if you don't need to delete, define INSERT_ONLY. */ #ifndef INSERT_ONLY #define DELETED -2UL #define IS_BCK_DELETED(bck) ( (bck) && (bck)->data == DELETED ) #define SET_BCK_DELETED(ht, bck) do { (bck)->data = DELETED; \ FREE_KEY(ht, (bck)->key); } while ( 0 ) #else #define IS_BCK_DELETED(bck) 0 #define SET_BCK_DELETED(ht, bck) \ do { fprintf(stderr, "Deletion not supported for insert-only hashtable\n");\ exit(2); } while ( 0 ) #endif /* We need the following only for dense buckets (Dense##x above). * * If you need to, set this to a value you'll never use for data. */ #define EMPTY -3UL /* steal more of the bck->data space */ /* This is what an item is. Either can be cast to a pointer. */ typedef struct { ulong data; /* 4 bytes for data: either a pointer or an integer */ ulong key; /* 4 bytes for the key: either a pointer or an int */ } HTItem; struct Table(Bin); /* defined in chash.c, I hope */ struct Table(Iterator); typedef struct Table(Bin) Table; /* Expands to SparseBin, etc */ typedef struct Table(Iterator) TableIterator; /* for STORES_PTR to work ok, cchKey MUST BE DEFINED 1st, cItems 2nd! */ typedef struct HashTable { ulong cchKey; /* the length of the key, or if it's \0 terminated */ ulong cItems; /* number of items currently in the hashtable */ ulong cDeletedItems; /* # of buckets holding DELETE in the hashtable */ ulong cBuckets; /* size of the table */ Table *table; /* The actual contents of the hashtable */ int fSaveKeys; /* 1 if we copy keys locally; 2 if keys in one block */ int cDeltaGoalSize; /* # of coming inserts (or deletes, if <0) we expect */ HTItem *posLastFind; /* position of last Find() command */ TableIterator *iter; /* used in First/NextBucket */ FILE *fpData; /* if non-NULL, what item->data points into */ char * (*dataRead)(FILE *, int); /* how to load data from disk */ HTItem bckData; /* holds data after being loaded from disk */ } HashTable; /* Small keys are stored and passed directly, but large keys are * stored and passed as pointers. To make it easier to remember * what to pass, we provide two functions: * PTR_KEY: give it a pointer to your data, and it returns * something appropriate to send to Hash() functions or * be stored in a data field. * KEY_PTR: give it something returned by a Hash() routine, and * it returns a (char *) pointer to the actual data. */ #define HashKeySize(ht) ( ((ulong *)(ht))[0] ) /* this is how we inline */ #define HashSize(ht) ( ((ulong *)(ht))[1] ) /* ...a la C++ :-) */ #define STORES_PTR(ht) ( HashKeySize(ht) == 0 || \ HashKeySize(ht) > sizeof(ulong) ) #define KEY_PTR(ht, key) ( STORES_PTR(ht) ? (char *)(key) : (char *)&(key) ) #ifdef DONT_HAVE_TO_WORRY_ABOUT_BUS_ERRORS #define PTR_KEY(ht, ptr) ( STORES_PTR(ht) ? (ulong)(ptr) : *(ulong *)(ptr) ) #else #define PTR_KEY(ht, ptr) ( STORES_PTR(ht) ? (ulong)(ptr) : HTcopy((char *)ptr)) #endif /* Function prototypes */ unsigned long HTcopy(char *pul); /* for PTR_KEY, not for users */ struct HashTable *AllocateHashTable(int cchKey, int fSaveKeys); void ClearHashTable(struct HashTable *ht); void FreeHashTable(struct HashTable *ht); HTItem *HashFind(struct HashTable *ht, ulong key); HTItem *HashFindLast(struct HashTable *ht); HTItem *HashFindOrInsert(struct HashTable *ht, ulong key, ulong dataInsert); HTItem *HashFindOrInsertItem(struct HashTable *ht, HTItem *pItem); HTItem *HashInsert(struct HashTable *ht, ulong key, ulong data); HTItem *HashInsertItem(struct HashTable *ht, HTItem *pItem); int HashDelete(struct HashTable *ht, ulong key); int HashDeleteLast(struct HashTable *ht); HTItem *HashFirstBucket(struct HashTable *ht); HTItem *HashNextBucket(struct HashTable *ht); int HashSetDeltaGoalSize(struct HashTable *ht, int delta); void HashSave(FILE *fp, struct HashTable *ht, int (*write)(FILE *, char *)); struct HashTable *HashLoad(FILE *fp, char * (*read)(FILE *, int)); struct HashTable *HashLoadKeys(FILE *fp, char * (*read)(FILE *, int));
2.0625
2
2024-11-18T21:10:12.974885+00:00
2021-01-25T15:01:34
2ec1bd7ef87ddbafef9c51abf64d1240ebf3eb4a
{ "blob_id": "2ec1bd7ef87ddbafef9c51abf64d1240ebf3eb4a", "branch_name": "refs/heads/master", "committer_date": "2021-01-25T15:01:34", "content_id": "d41da8a11fdbc05a2836e961ae9d10b1ccc05032", "detected_licenses": [ "curl" ], "directory_id": "551d4aba84f5fba010e14a7bb8a5d8e75db38bd7", "extension": "c", "filename": "ftp-wildcard.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": 4245, "license": "curl", "license_type": "permissive", "path": "/docs/examples/ftp-wildcard.c", "provenance": "stackv2-0065.json.gz:30892", "repo_name": "cmoesgaard/carl", "revision_date": "2021-01-25T15:01:34", "revision_id": "35381d1b7c6bd41ce9eb0f87a1b9b2273d8ef4a4", "snapshot_id": "8865ea3ed164c2e07743651e4d3a2ba5e63ab521", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cmoesgaard/carl/35381d1b7c6bd41ce9eb0f87a1b9b2273d8ef4a4/docs/examples/ftp-wildcard.c", "visit_date": "2023-02-23T20:55:59.821757" }
stackv2
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://carl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* <DESC> * FTP wildcard pattern matching * </DESC> */ #include <carl/carl.h> #include <stdio.h> struct callback_data { FILE *output; }; static long file_is_coming(struct carl_fileinfo *finfo, struct callback_data *data, int remains); static long file_is_downloaded(struct callback_data *data); static size_t write_it(char *buff, size_t size, size_t nmemb, void *cb_data); int main(int argc, char **argv) { /* carl easy handle */ CARL *handle; /* help data */ struct callback_data data = { 0 }; /* global initialization */ int rc = carl_global_init(CARL_GLOBAL_ALL); if(rc) return rc; /* initialization of easy handle */ handle = carl_easy_init(); if(!handle) { carl_global_cleanup(); return CARLE_OUT_OF_MEMORY; } /* turn on wildcard matching */ carl_easy_setopt(handle, CARLOPT_WILDCARDMATCH, 1L); /* callback is called before download of concrete file started */ carl_easy_setopt(handle, CARLOPT_CHUNK_BGN_FUNCTION, file_is_coming); /* callback is called after data from the file have been transferred */ carl_easy_setopt(handle, CARLOPT_CHUNK_END_FUNCTION, file_is_downloaded); /* this callback will write contents into files */ carl_easy_setopt(handle, CARLOPT_WRITEFUNCTION, write_it); /* put transfer data into callbacks */ carl_easy_setopt(handle, CARLOPT_CHUNK_DATA, &data); carl_easy_setopt(handle, CARLOPT_WRITEDATA, &data); /* carl_easy_setopt(handle, CARLOPT_VERBOSE, 1L); */ /* set an URL containing wildcard pattern (only in the last part) */ if(argc == 2) carl_easy_setopt(handle, CARLOPT_URL, argv[1]); else carl_easy_setopt(handle, CARLOPT_URL, "ftp://example.com/test/*"); /* and start transfer! */ rc = carl_easy_perform(handle); carl_easy_cleanup(handle); carl_global_cleanup(); return rc; } static long file_is_coming(struct carl_fileinfo *finfo, struct callback_data *data, int remains) { printf("%3d %40s %10luB ", remains, finfo->filename, (unsigned long)finfo->size); switch(finfo->filetype) { case CARLFILETYPE_DIRECTORY: printf(" DIR\n"); break; case CARLFILETYPE_FILE: printf("FILE "); break; default: printf("OTHER\n"); break; } if(finfo->filetype == CARLFILETYPE_FILE) { /* do not transfer files >= 50B */ if(finfo->size > 50) { printf("SKIPPED\n"); return CARL_CHUNK_BGN_FUNC_SKIP; } data->output = fopen(finfo->filename, "wb"); if(!data->output) { return CARL_CHUNK_BGN_FUNC_FAIL; } } return CARL_CHUNK_BGN_FUNC_OK; } static long file_is_downloaded(struct callback_data *data) { if(data->output) { printf("DOWNLOADED\n"); fclose(data->output); data->output = 0x0; } return CARL_CHUNK_END_FUNC_OK; } static size_t write_it(char *buff, size_t size, size_t nmemb, void *cb_data) { struct callback_data *data = cb_data; size_t written = 0; if(data->output) written = fwrite(buff, size, nmemb, data->output); else /* listing output */ written = fwrite(buff, size, nmemb, stdout); return written; }
2.375
2
2024-11-18T21:10:13.594529+00:00
2017-06-18T09:13:57
eaf36038867051f8b97af523073f3f4bd27de240
{ "blob_id": "eaf36038867051f8b97af523073f3f4bd27de240", "branch_name": "refs/heads/master", "committer_date": "2017-06-18T09:13:57", "content_id": "9a9f46ce18c5a7f9e4461b0ed94590fd3747c054", "detected_licenses": [ "Apache-2.0" ], "directory_id": "496bea0ce91fd2f009daaef6c5b70f2c5bf7c8fc", "extension": "c", "filename": "lockf.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 92806901, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 886, "license": "Apache-2.0", "license_type": "permissive", "path": "/bin/lockf.c", "provenance": "stackv2-0065.json.gz:31405", "repo_name": "torao/quebic", "revision_date": "2017-06-18T09:13:57", "revision_id": "7362cc3509dd5b466f3030e2037edb2ea0c27b4d", "snapshot_id": "7f0fd15a430b7c04c7066eb1459abf77f0cbc2f0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/torao/quebic/7362cc3509dd5b466f3030e2037edb2ea0c27b4d/bin/lockf.c", "visit_date": "2021-01-23T00:20:31.864804" }
stackv2
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> int main(int argc, char** argv){ char* file_name = NULL; int seconds = 10; if(argc <= 1){ fprintf(stderr, "USAGE: %s [file] {[sec]}\n", argv[0]); return EXIT_FAILURE; } else { file_name = argv[1]; if(argc == 3){ seconds = atoi(argv[2]); } else if(argc != 2){ fprintf(stderr, "ERROR: unknown option %s\n", argv[3]); return EXIT_FAILURE; } } int fd = open(file_name, O_RDONLY); if(fd == -1){ fprintf(stderr, "ERROR: fail to open file %s\n", file_name); return EXIT_FAILURE; } if(lockf(fd, F_LOCK, 0) < 0){ fprintf(stderr, "ERROR: fail to lock file %s\n", file_name); close(fd); return EXIT_FAILURE; } sleep(seconds); lockf(fd, F_ULOCK, 0); close(fd); return EXIT_SUCCESS; }
2.875
3
2024-11-18T21:10:15.531978+00:00
2021-07-16T20:44:46
e8851adff4a34fd3e211f88ed2a715c7625d8272
{ "blob_id": "e8851adff4a34fd3e211f88ed2a715c7625d8272", "branch_name": "refs/heads/master", "committer_date": "2021-07-16T20:44:46", "content_id": "7b96951953fb6d6eb8df28330028a4ac6a5b886c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c975a1e1d213ae87e2e106b72854f60ba6d7b8d9", "extension": "h", "filename": "log.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": 7550, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/utils/log.h", "provenance": "stackv2-0065.json.gz:31791", "repo_name": "robolover99/ECCSI-SAKKE", "revision_date": "2021-07-16T20:44:46", "revision_id": "c2a6afbb6506cb03953adf05360309746fa3ba04", "snapshot_id": "f9a884f63e0f3915b7dba8dc8e1a3fa8b792f419", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/robolover99/ECCSI-SAKKE/c2a6afbb6506cb03953adf05360309746fa3ba04/src/utils/log.h", "visit_date": "2023-06-18T14:33:04.121393" }
stackv2
/******************************************************************************/ /* Logging. */ /* */ /* Copyright 2015 Jim Buller */ /* */ /* 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. */ /******************************************************************************/ /***************************************************************************//** * @file log.h * @brief Logging. ******************************************************************************/ #ifndef __ES_LOG__ #define __ES_LOG__ #ifdef __cplusplus extern "C" { #endif #include "utils.h" #define ES_MAX_LOG_LINE 1200 /*!< Maximum log output line length, increased for GCC7+ warnings. */ #define ES_OUTPUT_DEBUG /*!< Comment this line out to disable DEBUG output at * compilation. */ /* Added to handle later GCC7+ compiler errors. */ #ifndef __FUNCTION__ #define __FUNCTION__ __func__ #endif /***************************************************************************//** * Log type identifiers. ******************************************************************************/ enum logType_e { ES_LOGGING_ERROR = 1, ES_LOGGING_LOG = 2, ES_LOGGING_INFO = 3, ES_LOGGING_DEBUG = 4 }; /***************************************************************************//** * Output ERROR message. * * @param[in] a_format The output format. * @param[in] vargs A list of arguments to output. ******************************************************************************/ #define ES_ERROR(a_format, vargs...) { \ char outBuff_a[ES_MAX_LOG_LINE]; \ snprintf(outBuff_a, sizeof(outBuff_a), a_format, ## vargs); \ fprintf(stdout, "ES ERROR: %s\n", outBuff_a); \ } /***************************************************************************//** * Output LOG message. * * @param[in] a_format The output format. * @param[in] vargs A list of arguments to output. ******************************************************************************/ #define ES_LOG(a_format, vargs...) { \ char outBuff_a[ES_MAX_LOG_LINE]; \ snprintf(outBuff_a, sizeof(outBuff_a), a_format, ## vargs); \ fprintf(stdout, "ES LOG: %s\n", outBuff_a); \ } /***************************************************************************//** * Output INFO message. * * @param[in] a_format The output format. * @param[in] vargs A list of arguments to output. ******************************************************************************/ #define ES_INFO(a_format, vargs...) { \ char outBuff_a[ES_MAX_LOG_LINE]; \ snprintf(outBuff_a, sizeof(outBuff_a), a_format, ## vargs); \ fprintf(stdout, "ES INFO: %s\n", outBuff_a); \ } /* Only allow debug messages when DEBUG flag is set */ #ifdef ES_OUTPUT_DEBUG /***************************************************************************//** * Output DEBUG message. * * @param[in] a_format The output format. * @param[in] vargs A list of arguments to output. ******************************************************************************/ #define ES_DEBUG(a_format, vargs...) { \ char outBuff_a[ES_MAX_LOG_LINE]; \ snprintf(outBuff_a, sizeof(outBuff_a), a_format, ## vargs); \ fprintf(stdout, "ES DEBUG: %s\n", outBuff_a); \ } #else #define ES_DEBUG(section, vargs...) {} #endif /***************************************************************************//** * Output HASH as a DEBUG message. * * @param[in] section The code section the call to output came from. * @param[in] vargs A list of arguments to output. ******************************************************************************/ #define ES_DEBUG_DISPLAY_HASH(section, vargs...) { \ utils_displayHash(ES_LOGGING_DEBUG, section, ## vargs); \ } /***************************************************************************//** * Output BIGNUM as a DEBUG message. * * @param[in] section The code section the call to output came from. * @param[in] vargs A list of arguments to output. ******************************************************************************/ #define ES_DEBUG_DISPLAY_BN(section, vargs...) { \ utils_BNdump(ES_LOGGING_DEBUG, section, ## vargs); \ } /***************************************************************************//** * Output Affine Coordinates as a DEBUG message. * * @param[in] section The code section the call to output came from. * @param[in] vargs A list of arguments to output. ******************************************************************************/ #define ES_DEBUG_DISPLAY_AFFINE_COORDS(section, vargs...) { \ utils_displayAffineCoordinates(ES_LOGGING_DEBUG, section, ## vargs); \ } /***************************************************************************//** * Output Octet String in formatted fashion as a DEBUG message. * * @param[in] section The code section the call to output came from. * @param[in] vargs A list of arguments to output. ******************************************************************************/ #define ES_DEBUG_PRINT_FORMATTED_OCTET_STRING(section, vargs...) { \ utils_printFormattedOctetString(ES_LOGGING_DEBUG, section, ## vargs); \ } /***************************************************************************//** * Output Octet String in formatted fashion as a INFO message. * * @param[in] section The code section the call to output came from. * @param[in] vargs A list of arguments to output. ******************************************************************************/ #define ES_INFO_PRINT_FORMATTED_OCTET_STRING(section, vargs...) { \ utils_printFormattedOctetString(ES_LOGGING_INFO, section, ## vargs); \ } /***************************************************************************//** * Output User-ID as a DEBUG message. * * @param[in] section The code section the call to output came from. * @param[in] vargs A list of arguments to output. ******************************************************************************/ #define ES_DEBUG_PRINT_ID(section, vargs...) { \ utils_printUserId(ES_LOGGING_DEBUG, section, ## vargs); \ } #ifdef __cplusplus } #endif #endif /* __ES_LOG__ */ /******************************************************************************/ /* End of file */ /******************************************************************************/
2.015625
2
2024-11-18T21:10:16.037204+00:00
2021-05-27T17:36:34
46f1949b7b37d7673a59d6f7fb30d2160bf64d6b
{ "blob_id": "46f1949b7b37d7673a59d6f7fb30d2160bf64d6b", "branch_name": "refs/heads/main", "committer_date": "2021-05-27T17:36:34", "content_id": "1f8dfaadd624466c42ca125eca49562b5bffeaea", "detected_licenses": [ "MIT" ], "directory_id": "7e9707d31d0ad035c7e47ab20bde16c645597e70", "extension": "h", "filename": "type_size.h", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 18575196, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1405, "license": "MIT", "license_type": "permissive", "path": "/src/platform/type_size.h", "provenance": "stackv2-0065.json.gz:32431", "repo_name": "schanur/libplatform", "revision_date": "2021-05-27T17:36:34", "revision_id": "e430a50f1b0c1e1c7ead432e44209d16925cf2ac", "snapshot_id": "74a4652b732dcaabea9e7b443b7104107c186621", "src_encoding": "UTF-8", "star_events_count": 15, "url": "https://raw.githubusercontent.com/schanur/libplatform/e430a50f1b0c1e1c7ead432e44209d16925cf2ac/src/platform/type_size.h", "visit_date": "2021-07-22T10:13:20.928476" }
stackv2
#ifndef PLATFORM_TYPE_SIZE_H #define PLATFORM_TYPE_SIZE_H #include "inttypes_wrapper.h" #include "os_detect.h" /*#include "inttypes_wrapper.h"*/ #include <limits.h> #ifdef PLATFORM_LINUX #if UINT_MAX == UINTMAX_C(4294967295) #define INT_SIZE UINT8_C(4) #else #if UINT_MAX == UINTMAX_C(18446744073709551615) #define INT_SIZE UINT8_C(8) #else #error Unknown integer width. #endif #endif #if UINTPTR_MAX == UINTMAX_C(4294967295) #define SIZE_T_SIZE UINT8_C(4) #else #if UINTPTR_MAX == UINTMAX_C(18446744073709551615) #define SIZE_T_SIZE UINT8_C(8) #else #error Unknown integer width. #endif #endif #else #ifdef PLATFORM_WINDOWS #ifndef NO_C_STD_COMPLIANT_STDINT_HEADER /* #error NO_C_STD_COMPLIANT_STDINT_HEADER not set. */ #endif #if UINT_MAX == 0xffffffffUL #define INT_SIZE 4 #else #if UINT_MAX == 0xffffffffffffffffULL #define INT_SIZE 8 #else #error Unknown integer width. #endif #endif #if UINTPTR_MAX == 0xffffffffULL #define SIZE_T_SIZE 4 #else #if UINTPTR_MAX == 0xffffffffffffffffULL #define SIZE_T_SIZE 8 #else /* FIXME */ #define SIZE_T_SIZE 4 /* #error Unknown integer width. */ #endif #endif #else #error Unsupported platform. #endif #endif #endif /* PLATFORM_TYPE_SIZE_H */
2.03125
2
2024-11-18T21:10:16.201266+00:00
2020-10-14T11:12:26
edf36f7b4b184069030dccbc1141659d02364a01
{ "blob_id": "edf36f7b4b184069030dccbc1141659d02364a01", "branch_name": "refs/heads/master", "committer_date": "2020-10-14T11:12:26", "content_id": "a5ca89e5733459bdf8e392ba28bbb99ce340660c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "ef111a7c8d8d4d10697f24fc0103090d17f1af47", "extension": "c", "filename": "posix_file_utils.c", "fork_events_count": 1, "gha_created_at": "2016-03-06T04:01:27", "gha_event_created_at": "2022-11-24T04:28:42", "gha_language": "Java", "gha_license_id": "Apache-2.0", "github_id": 53236772, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2213, "license": "Apache-2.0", "license_type": "permissive", "path": "/client/client-multi/client-c/src/kaa/platform-impl/posix/posix_file_utils.c", "provenance": "stackv2-0065.json.gz:32688", "repo_name": "liuhu/Kaa", "revision_date": "2020-10-14T11:12:26", "revision_id": "3aed26cb2b81b07036ac3afb780fc33a0519e610", "snapshot_id": "83f3cfc94915e52b8a756fedc3f55056ef91c52a", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/liuhu/Kaa/3aed26cb2b81b07036ac3afb780fc33a0519e610/client/client-multi/client-c/src/kaa/platform-impl/posix/posix_file_utils.c", "visit_date": "2022-11-27T00:05:34.686997" }
stackv2
/** * Copyright 2014-2016 CyberVision, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "posix_file_utils.h" #include <stdint.h> #include "../../platform/stdio.h" #include "../../utilities/kaa_mem.h" #include "../../kaa_common.h" int posix_binary_file_read(const char *file_name, char **buffer, size_t *buffer_size, bool *needs_deallocation) { KAA_RETURN_IF_NIL4(file_name, buffer, buffer_size, needs_deallocation, -1); *buffer = NULL; *buffer_size = 0; *needs_deallocation = true; FILE* file = fopen(file_name, "rb"); KAA_RETURN_IF_NIL(file, -1); fseek(file, 0, SEEK_END); size_t result_size = ftell(file); if (result_size <= 0) { fclose(file); return -1; } char *result_buffer = (char *) KAA_MALLOC(result_size * sizeof(char)); if (!result_buffer) { fclose(file); return -1; } fseek(file, 0, SEEK_SET); if (fread(result_buffer, result_size, 1, file) == 0) { KAA_FREE(result_buffer); fclose(file); return -1; } *buffer = result_buffer; *buffer_size = result_size; fclose(file); return 0; } int posix_binary_file_store(const char *file_name, const char *buffer, size_t buffer_size) { KAA_RETURN_IF_NIL3(file_name, buffer, buffer_size, -1); FILE* status_file = fopen(file_name, "wb"); if (status_file) { fwrite(buffer, buffer_size, 1, status_file); fclose(status_file); return 0; } return -1; } int posix_binary_file_delete(const char *file_name) { FILE *file = fopen(file_name, "r"); if (file) { fclose(file); return remove(file_name); } return -1; }
2.046875
2
2024-11-18T21:10:16.274589+00:00
2023-08-18T12:54:06
f4156afb1eabe2466d307332d4d10423b6eca97b
{ "blob_id": "f4156afb1eabe2466d307332d4d10423b6eca97b", "branch_name": "refs/heads/master", "committer_date": "2023-08-18T12:54:06", "content_id": "8730420b43f59d60d02cbc0c7e0accbc5561ee88", "detected_licenses": [ "MIT" ], "directory_id": "22446075c2e71ef96b4a4777fe966714ac96b405", "extension": "c", "filename": "main.c", "fork_events_count": 68, "gha_created_at": "2020-09-30T10:18:15", "gha_event_created_at": "2023-09-08T12:56:11", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 299882138, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2614, "license": "MIT", "license_type": "permissive", "path": "/clicks/magneticrotary4/example/main.c", "provenance": "stackv2-0065.json.gz:32818", "repo_name": "MikroElektronika/mikrosdk_click_v2", "revision_date": "2023-08-18T12:54:06", "revision_id": "49ab937390bef126beb7b703d5345fa8cd6e3555", "snapshot_id": "2cc2987869649a304763b0f9d27c920d42a11c16", "src_encoding": "UTF-8", "star_events_count": 77, "url": "https://raw.githubusercontent.com/MikroElektronika/mikrosdk_click_v2/49ab937390bef126beb7b703d5345fa8cd6e3555/clicks/magneticrotary4/example/main.c", "visit_date": "2023-08-21T22:15:09.036635" }
stackv2
/*! * @file main.c * @brief MagneticRotary4 Click example * * # Description * This example demonstrates the use of Magnetic Rotary 4 click board by reading * and displaying the magnet (potentiometer) angular position in degrees. * * The demo application is composed of two sections : * * ## Application Init * Initializes the driver, sets the rotation direction, and calibrates the sensor * for potentiometer zero position. * * ## Application Task * Reads the magnet (potentiometer) angular position in degrees every 100ms * and displays the results on the USB UART. * * @author Stefan Filipovic * */ #include "board.h" #include "log.h" #include "magneticrotary4.h" static magneticrotary4_t magneticrotary4; static log_t logger; void application_init ( void ) { log_cfg_t log_cfg; /**< Logger config object. */ magneticrotary4_cfg_t magneticrotary4_cfg; /**< Click config object. */ /** * Logger initialization. * Default baud rate: 115200 * Default log level: LOG_LEVEL_DEBUG * @note If USB_UART_RX and USB_UART_TX * are defined as HAL_PIN_NC, you will * need to define them manually for log to work. * See @b LOG_MAP_USB_UART macro definition for detailed explanation. */ LOG_MAP_USB_UART( log_cfg ); log_init( &logger, &log_cfg ); log_info( &logger, " Application Init " ); // Click initialization. magneticrotary4_cfg_setup( &magneticrotary4_cfg ); MAGNETICROTARY4_MAP_MIKROBUS( magneticrotary4_cfg, MIKROBUS_1 ); if ( SPI_MASTER_ERROR == magneticrotary4_init( &magneticrotary4, &magneticrotary4_cfg ) ) { log_error( &logger, " Communication init." ); for ( ; ; ); } if ( MAGNETICROTARY4_ERROR == magneticrotary4_set_rotation_direction ( &magneticrotary4, MAGNETICROTARY4_DIRECTION_CW ) ) { log_error( &logger, " Set rotation direction." ); for ( ; ; ); } if ( MAGNETICROTARY4_ERROR == magneticrotary4_calibrate_zero_position ( &magneticrotary4 ) ) { log_error( &logger, " Calibrate zero position." ); for ( ; ; ); } log_info( &logger, " Application Task " ); } void application_task ( void ) { float angle; if ( MAGNETICROTARY4_OK == magneticrotary4_get_angle ( &magneticrotary4, &angle ) ) { log_printf( &logger, " Angle: %.1f degrees\r\n\n", angle ); Delay_ms ( 100 ); } } void main ( void ) { application_init( ); for ( ; ; ) { application_task( ); } } // ------------------------------------------------------------------------ END
3.125
3
2024-11-18T21:10:16.397136+00:00
2021-03-03T02:01:32
7e312bf08b84ea07ccb5c2275e62b349afc8c857
{ "blob_id": "7e312bf08b84ea07ccb5c2275e62b349afc8c857", "branch_name": "refs/heads/master", "committer_date": "2021-03-03T02:01:32", "content_id": "032507e09d6011ec70b96b39b9ebe96c29360e18", "detected_licenses": [ "MIT" ], "directory_id": "135dc036d1a10b1672efd2cb10166578e9b7439d", "extension": "h", "filename": "common.h", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 100192911, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 517, "license": "MIT", "license_type": "permissive", "path": "/bench/double/common.h", "provenance": "stackv2-0065.json.gz:32949", "repo_name": "jdh8/metallic", "revision_date": "2021-03-03T02:01:32", "revision_id": "a9e3ec4c9c36196dfd0ee1849da3cce04e681025", "snapshot_id": "4fd1ad8f8f0bde50bddab8983c2c2a21a2d73ba9", "src_encoding": "UTF-8", "star_events_count": 44, "url": "https://raw.githubusercontent.com/jdh8/metallic/a9e3ec4c9c36196dfd0ee1849da3cce04e681025/bench/double/common.h", "visit_date": "2021-06-04T17:55:27.991041" }
stackv2
#include "src/math/reinterpret.h" #include <time.h> #include <stdint.h> static double bench(double f(double)) { volatile double dummy; clock_t start = clock(); for (uint64_t i = 0x7FF8000000000000; i <= 0xFFF0000000000000; i += 0x0000000893205C62) { double x = reinterpret(double, i); dummy = f(x); dummy = f(-x); } return (double)(clock() - start) / CLOCKS_PER_SEC; dummy; } #define BENCH(f) int main(void) { printf("%9f\n%9f\n", bench(metallic_##f), bench(f)); }
2.375
2
2024-11-18T21:10:16.591042+00:00
2021-08-26T11:18:55
d8b15cbd92bafce36d575f14c0ec9c506e04c0b2
{ "blob_id": "d8b15cbd92bafce36d575f14c0ec9c506e04c0b2", "branch_name": "refs/heads/master", "committer_date": "2021-08-26T11:18:55", "content_id": "1ec4709a9b628f70514924c9ff9661e49853c16e", "detected_licenses": [ "MIT" ], "directory_id": "ae8047ad8a872854fd2299351b97aef959a5031b", "extension": "c", "filename": "uart.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": 2486, "license": "MIT", "license_type": "permissive", "path": "/x86/uart.c", "provenance": "stackv2-0065.json.gz:33205", "repo_name": "reymontero/SynnixOS", "revision_date": "2021-08-26T11:18:55", "revision_id": "c26993479d78eae3881bdbad147b5bb4b5704844", "snapshot_id": "241ac3d92cfa678b5a807da382b526208cd76622", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/reymontero/SynnixOS/c26993479d78eae3881bdbad147b5bb4b5704844/x86/uart.c", "visit_date": "2023-07-14T01:10:18.895693" }
stackv2
#include <basic.h> #include <snx/fs.h> #include <snx/irq.h> #include <snx/panic.h> #include <snx/thread.h> #include <snx/tty.h> #include <stdio.h> #include <x86/cpu.h> #include <x86/pic.h> #include <x86/uart.h> #define UART_DATA 0 #define UART_INTERRUPT_ENABLE 1 #define UART_BAUD_LOW 0 #define UART_BAUD_HIGH 1 #define UART_FIFO_CTRL 2 #define UART_LINE_CTRL 3 #define UART_MODEM_CTRL 4 #define UART_LINE_STATUS 5 #define UART_MODEM_STATUS 6 static bool is_transmit_empty(port_addr_t com) { return (inb(com + UART_LINE_STATUS) & 0x20) != 0; } static bool is_data_available(port_addr_t com) { return (inb(com + UART_LINE_STATUS) & 0x01) != 0; } static void wait_for_transmit_empty(port_addr_t com) { while (!is_transmit_empty(com)) {} } static void wait_for_data_available(port_addr_t com) { while (!is_data_available(com)) {} } void x86_uart_write_byte(port_addr_t p, const char b) { wait_for_transmit_empty(p); outb(p + UART_DATA, b); } void x86_uart_write(port_addr_t p, const char *buf, size_t len) { for (size_t i = 0; i < len; i++) x86_uart_write_byte(p, buf[i]); } char x86_uart_read_byte(port_addr_t p) { wait_for_data_available(p); return inb(p + UART_DATA); } void x86_uart_enable_interrupt(port_addr_t com) { outb(com + UART_INTERRUPT_ENABLE, 0x9); } void x86_uart_disable_interrupt(port_addr_t com) { outb(com + UART_INTERRUPT_ENABLE, 0x0); } void x86_uart_irq_handler(interrupt_frame *r, void *serial_port) { port_addr_t port = (port_addr_t)(intptr_t)serial_port; char f = x86_uart_read_byte(port); switch (port) { case COM1: write_to_serial_tty(&dev_serial, f); break; case COM2: write_to_serial_tty(&dev_serial2, f); break; case COM3: write_to_serial_tty(&dev_serial3, f); break; case COM4: write_to_serial_tty(&dev_serial4, f); break; } } static void x86_uart_setup(port_addr_t p) { outb(p + 1, 0x00); outb(p + 3, 0x80); outb(p + 0, 0x03); outb(p + 1, 0x00); outb(p + 3, 0x03); outb(p + 2, 0xC7); outb(p + 4, 0x0B); x86_uart_enable_interrupt(p); } void x86_uart_init() { x86_uart_setup(COM1); x86_uart_setup(COM2); x86_uart_setup(COM3); x86_uart_setup(COM4); irq_install(IRQ_SERIAL1, x86_uart_irq_handler, (void *)COM1); irq_install(IRQ_SERIAL2, x86_uart_irq_handler, (void *)COM2); // irq_install(4, x86_uart_irq_handler, (void *)0x3E8); // irq_install(3, x86_uart_irq_handler, (void *)0x2E8); }
2.4375
2
2024-11-18T21:10:16.674628+00:00
2018-07-23T14:46:06
7eb71ae41b846a984810d0c22535029af66acaf5
{ "blob_id": "7eb71ae41b846a984810d0c22535029af66acaf5", "branch_name": "refs/heads/master", "committer_date": "2018-07-23T14:46:06", "content_id": "40935e886d3207a3b25e48fccde29730594ec6a7", "detected_licenses": [ "MIT" ], "directory_id": "8bbeb7b5721a9dbf40caa47a96e6961ceabb0128", "extension": "c", "filename": "36.Valid Sudoku(有效的数独).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": 12385, "license": "MIT", "license_type": "permissive", "path": "/c/36.Valid Sudoku(有效的数独).c", "provenance": "stackv2-0065.json.gz:33333", "repo_name": "lishulongVI/leetcode", "revision_date": "2018-07-23T14:46:06", "revision_id": "6731e128be0fd3c0bdfe885c1a409ac54b929597", "snapshot_id": "bb5b75642f69dfaec0c2ee3e06369c715125b1ba", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lishulongVI/leetcode/6731e128be0fd3c0bdfe885c1a409ac54b929597/c/36.Valid Sudoku(有效的数独).c", "visit_date": "2020-03-23T22:17:40.335970" }
stackv2
/* <p>Determine if a&nbsp;9x9 Sudoku board&nbsp;is valid.&nbsp;Only the filled cells need to be validated&nbsp;<strong>according to the following rules</strong>:</p> <ol> <li>Each row&nbsp;must contain the&nbsp;digits&nbsp;<code>1-9</code> without repetition.</li> <li>Each column must contain the digits&nbsp;<code>1-9</code>&nbsp;without repetition.</li> <li>Each of the 9 <code>3x3</code> sub-boxes of the grid must contain the digits&nbsp;<code>1-9</code>&nbsp;without repetition.</li> </ol> <p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png" style="height:250px; width:250px" /><br /> <small>A partially filled sudoku which is valid.</small></p> <p>The Sudoku board could be partially filled, where empty cells are filled with the character <code>&#39;.&#39;</code>.</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> [ [&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;], [&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;], [&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;], [&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;], [&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;], [&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;], [&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;], [&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;], [&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;] ] <strong>Output:</strong> true </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> [ &nbsp; [&quot;8&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;], &nbsp; [&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;], &nbsp; [&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;], &nbsp; [&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;], &nbsp; [&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;], &nbsp; [&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;], &nbsp; [&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;], &nbsp; [&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;], &nbsp; [&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;] ] <strong>Output:</strong> false <strong>Explanation:</strong> Same as Example 1, except with the <strong>5</strong> in the top left corner being modified to <strong>8</strong>. Since there are two 8&#39;s in the top left 3x3 sub-box, it is invalid. </pre> <p><strong>Note:</strong></p> <ul> <li>A Sudoku board (partially filled) could be valid but is not necessarily solvable.</li> <li>Only the filled cells need to be validated according to the mentioned&nbsp;rules.</li> <li>The given board&nbsp;contain only digits <code>1-9</code> and the character <code>&#39;.&#39;</code>.</li> <li>The given board size is always <code>9x9</code>.</li> </ul> <p>判断一个&nbsp;9x9 的数独是否有效。只需要<strong>根据以下规则</strong>,验证已经填入的数字是否有效即可。</p> <ol> <li>数字&nbsp;<code>1-9</code>&nbsp;在每一行只能出现一次。</li> <li>数字&nbsp;<code>1-9</code>&nbsp;在每一列只能出现一次。</li> <li>数字&nbsp;<code>1-9</code>&nbsp;在每一个以粗实线分隔的&nbsp;<code>3x3</code>&nbsp;宫内只能出现一次。</li> </ol> <p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png" style="height: 250px; width: 250px;"></p> <p><small>上图是一个部分填充的有效的数独。</small></p> <p>数独部分空格内已填入了数字,空白格用&nbsp;<code>&#39;.&#39;</code>&nbsp;表示。</p> <p><strong>示例&nbsp;1:</strong></p> <pre><strong>输入:</strong> [ [&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;], [&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;], [&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;], [&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;], [&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;], [&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;], [&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;], [&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;], [&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;] ] <strong>输出:</strong> true </pre> <p><strong>示例&nbsp;2:</strong></p> <pre><strong>输入:</strong> [ &nbsp; [&quot;8&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;], &nbsp; [&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;], &nbsp; [&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;], &nbsp; [&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;], &nbsp; [&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;], &nbsp; [&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;], &nbsp; [&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;], &nbsp; [&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;], &nbsp; [&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;] ] <strong>输出:</strong> false <strong>解释:</strong> 除了第一行的第一个数字从<strong> 5</strong> 改为 <strong>8 </strong>以外,空格内其他数字均与 示例1 相同。 但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。</pre> <p><strong>说明:</strong></p> <ul> <li>一个有效的数独(部分已被填充)不一定是可解的。</li> <li>只需要根据以上规则,验证已经填入的数字是否有效即可。</li> <li>给定数独序列只包含数字&nbsp;<code>1-9</code>&nbsp;和字符&nbsp;<code>&#39;.&#39;</code>&nbsp;。</li> <li>给定数独永远是&nbsp;<code>9x9</code>&nbsp;形式的。</li> </ul> <p>判断一个&nbsp;9x9 的数独是否有效。只需要<strong>根据以下规则</strong>,验证已经填入的数字是否有效即可。</p> <ol> <li>数字&nbsp;<code>1-9</code>&nbsp;在每一行只能出现一次。</li> <li>数字&nbsp;<code>1-9</code>&nbsp;在每一列只能出现一次。</li> <li>数字&nbsp;<code>1-9</code>&nbsp;在每一个以粗实线分隔的&nbsp;<code>3x3</code>&nbsp;宫内只能出现一次。</li> </ol> <p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png" style="height: 250px; width: 250px;"></p> <p><small>上图是一个部分填充的有效的数独。</small></p> <p>数独部分空格内已填入了数字,空白格用&nbsp;<code>&#39;.&#39;</code>&nbsp;表示。</p> <p><strong>示例&nbsp;1:</strong></p> <pre><strong>输入:</strong> [ [&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;], [&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;], [&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;], [&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;], [&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;], [&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;], [&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;], [&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;], [&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;] ] <strong>输出:</strong> true </pre> <p><strong>示例&nbsp;2:</strong></p> <pre><strong>输入:</strong> [ &nbsp; [&quot;8&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;], &nbsp; [&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;], &nbsp; [&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;], &nbsp; [&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;], &nbsp; [&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;], &nbsp; [&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;], &nbsp; [&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;], &nbsp; [&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;], &nbsp; [&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;] ] <strong>输出:</strong> false <strong>解释:</strong> 除了第一行的第一个数字从<strong> 5</strong> 改为 <strong>8 </strong>以外,空格内其他数字均与 示例1 相同。 但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。</pre> <p><strong>说明:</strong></p> <ul> <li>一个有效的数独(部分已被填充)不一定是可解的。</li> <li>只需要根据以上规则,验证已经填入的数字是否有效即可。</li> <li>给定数独序列只包含数字&nbsp;<code>1-9</code>&nbsp;和字符&nbsp;<code>&#39;.&#39;</code>&nbsp;。</li> <li>给定数独永远是&nbsp;<code>9x9</code>&nbsp;形式的。</li> </ul> */ bool isValidSudoku(char** board, int boardRowSize, int boardColSize) { }
2.796875
3
2024-11-18T21:10:17.143055+00:00
2023-02-23T13:08:52
5d7663c133313e904255fe22106e87898347fb12
{ "blob_id": "5d7663c133313e904255fe22106e87898347fb12", "branch_name": "refs/heads/master", "committer_date": "2023-02-23T13:08:52", "content_id": "6ac41a93501ca273f9dfe1683d3f7e771c5f2822", "detected_licenses": [ "MIT" ], "directory_id": "722c0a166c811e66a4a77f6cd985e0ecf5140123", "extension": "c", "filename": "test_strcat_s.c", "fork_events_count": 69, "gha_created_at": "2017-04-13T05:29:04", "gha_event_created_at": "2022-10-06T11:44:57", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 88128310, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8737, "license": "MIT", "license_type": "permissive", "path": "/tests/test_strcat_s.c", "provenance": "stackv2-0065.json.gz:34104", "repo_name": "rurban/safeclib", "revision_date": "2023-02-23T13:08:52", "revision_id": "3e943f7317448ab98046ed99d86d45e300224d12", "snapshot_id": "0fcb1f505cff4c4ff0a765e4ea9ff6b9082dfa72", "src_encoding": "UTF-8", "star_events_count": 282, "url": "https://raw.githubusercontent.com/rurban/safeclib/3e943f7317448ab98046ed99d86d45e300224d12/tests/test_strcat_s.c", "visit_date": "2023-08-23T22:30:47.117025" }
stackv2
/*------------------------------------------------------------------ * test_strcat_s * File 'str/strcat_s.c' * Lines executed:90.16% of 61 * *------------------------------------------------------------------ */ #include "test_private.h" #include "safe_str_lib.h" #if defined(TEST_MSVCRT) && defined(HAVE_STRCAT_S) #undef HAVE_CT_BOS_OVR #undef strcat_s EXTERN errno_t strcat_s(char *restrict dest, rsize_t dmax, const char *restrict src); #endif #ifdef HAVE_STRCAT_S #define HAVE_NATIVE 1 #else #define HAVE_NATIVE 0 #endif #include "test_msvcrt.h" #define LEN (128) static char str1[LEN]; static char str2[LEN]; int test_strcat_s(void); int test_strcat_s(void) { errno_t rc; int32_t len1; int32_t len2; int32_t len3; int errs = 0; /*--------------------------------------------------*/ strcpy(str1, ""); strcpy(str2, "aaaa"); #if defined(TEST_MSVCRT) && defined(HAVE_STRNCPY_S) use_msvcrt = true; #endif print_msvcrt(use_msvcrt); #ifndef HAVE_CT_BOS_OVR EXPECT_BOS("empty dest") rc = strcat_s(NULL, LEN, str2); init_msvcrt(rc == ESNULLP, &use_msvcrt); ERR_MSVC(ESNULLP, EINVAL); EXPSTR(str1, ""); /*--------------------------------------------------*/ strcpy(str1, "aaaa"); EXPECT_BOS("empty src") rc = strcat_s(str1, LEN, NULL); ERR_MSVC(ESNULLP, EINVAL); EXPSTR(str1, ""); CHECK_SLACK(str1, LEN); /*--------------------------------------------------*/ strcpy(str1, "aaaa"); EXPECT_BOS("empty dest or dmax") rc = strcat_s(str1, 0, str2); ERR_MSVC(ESZEROL, EINVAL); EXPSTR(str1, "aaaa"); /*--------------------------------------------------*/ strcpy(str1, "abc"); /*printf("** bos(str1) %ld [%s:%u]\n", BOS(str1), __FUNCTION__, __LINE__);*/ if (_BOS_KNOWN(str1)) { EXPECT_BOS("dest overflow") rc = strcat_s(str1, LEN + 1, str2); ERR(EOVERFLOW); /* dmax exceeds dest */ if (!use_msvcrt) { EXPSTR(str1, ""); /* cleared */ CHECK_SLACK(str1, 4); } rc = strcat_s(str1, LEN, str2); ERR(0); } else { #ifdef HAVE___BUILTIN_OBJECT_SIZE debug_printf("%s %u Error unknown str1 object_size\n", __FUNCTION__, __LINE__); errs++; #endif } strcpy(str1, "a"); EXPECT_BOS("dest overflow") rc = strcat_s(str1, (RSIZE_MAX_STR + 1), str2); ERR_MSVC(ESLEMAX, 0); /* some not so good compilers have destbos == BOS_UNKNOWN, like pgcc. hence they do just CHK_DMAX_MAX, and don't clear str1 at all */ if (_BOS_KNOWN(str1)) EXPSTR(str1, !use_msvcrt ? "" : "aaaaa") #endif /*--------------------------------------------------*/ strcpy(str1, "aaaaaaaaaa"); strcpy(str2, "keep it simple"); GCC_PUSH_WARN_DMAX rc = strcat_s(str1, 1, str2); #ifdef HAVE_CT_BOS_OVR init_msvcrt(rc == ESUNTERM, &use_msvcrt); #endif GCC_POP_WARN_DMAX ERR_MSVC(ESUNTERM, ERANGE); EXPNULL(str1) CHECK_SLACK(str1, 1); /*--------------------------------------------------*/ strcpy(str1, "aaaaaaaaaa"); strcpy(str2, "keep it simple"); GCC_PUSH_WARN_DMAX rc = strcat_s(str1, 2, str2); GCC_POP_WARN_DMAX ERR_MSVC(ESUNTERM, ERANGE); EXPNULL(str1) CHECK_SLACK(str1, 2); /*--------------------------------------------------*/ strcpy(str1, "abcd"); GCC_PUSH_WARN_DMAX rc = strcat_s(&str1[0], 8, &str1[3]); GCC_POP_WARN_DMAX ERR_MSVC(ESOVRLP, ERANGE); EXPNULL(str1); CHECK_SLACK(str1, 8); strcpy(str1, "abcd"); GCC_PUSH_WARN_DMAX rc = strcat_s(&str1[0], 4, &str1[3]); GCC_POP_WARN_DMAX ERR_MSVC(ESOVRLP, ERANGE); EXPNULL(str1); CHECK_SLACK(str1, 4); /*--------------------------------------------------*/ strcpy(str1, "abcdefgh"); GCC_PUSH_WARN_DMAX rc = strcat_s(&str1[3], 5, &str1[0]); GCC_POP_WARN_DMAX ERR_MSVC(ESUNTERM, ERANGE); EXPNULL(&str1[3]) CHECK_SLACK(&str1[3], 5); /*--------------------------------------------------*/ strcpy(str1, "abcdefgh"); GCC_PUSH_WARN_DMAX rc = strcat_s(&str1[3], 12, &str1[0]); GCC_POP_WARN_DMAX ERR_MSVC(ESOVRLP, ERANGE); EXPNULL(&str1[3]); CHECK_SLACK(&str1[3], 12); /*--------------------------------------------------*/ strcpy(&str1[0], "aaaaaaaaaa"); strcpy(&str2[0], "keep it simple"); len1 = strlen(str1); len2 = strlen(str2); rc = strcat_s(str1, LEN, str2); ERR(EOK) len3 = strlen(str1); if (len3 != (len1 + len2)) { debug_printf("%s %u lengths wrong: %u %u %u \n", __FUNCTION__, __LINE__, len1, len2, len3); errs++; } CHECK_SLACK(&str1[len3], LEN - len3); /*--------------------------------------------------*/ str1[0] = '\0'; strcpy(str2, "keep it simple"); GCC_PUSH_WARN_DMAX rc = strcat_s(str1, 1, str2); GCC_POP_WARN_DMAX ERR_MSVC(ESNOSPC, ERANGE); EXPNULL(str1) CHECK_SLACK(str1, 1); /*--------------------------------------------------*/ str1[0] = '\0'; strcpy(str2, "keep it simple"); GCC_PUSH_WARN_DMAX rc = strcat_s(str1, 2, str2); GCC_POP_WARN_DMAX ERR_MSVC(ESNOSPC, ERANGE); EXPNULL(str1) CHECK_SLACK(str1, 2); /*--------------------------------------------------*/ str1[0] = '\0'; strcpy(str2, "keep it simple"); rc = strcat_s(str1, LEN, str2); ERR(EOK) EXPSTR(str1, str2) len1 = strlen(str1); CHECK_SLACK(&str1[len1], LEN - len1); /*--------------------------------------------------*/ str1[0] = '\0'; str2[0] = '\0'; rc = strcat_s(str1, LEN, str2); ERR(EOK) EXPNULL(str1) CHECK_SLACK(str1, LEN); /*--------------------------------------------------*/ str1[0] = '\0'; strcpy(str2, "keep it simple"); rc = strcat_s(str1, LEN, str2); ERR(EOK) EXPSTR(str1, str2) len1 = strlen(str1); CHECK_SLACK(&str1[len1], LEN - len1); /*--------------------------------------------------*/ strcpy(str1, "qqweqq"); strcpy(str2, "keep it simple"); rc = strcat_s(str1, LEN, str2); ERR(EOK) EXPSTR(str1, "qqweqqkeep it simple") len1 = strlen(str1); CHECK_SLACK(&str1[len1], LEN - len1); /*--------------------------------------------------*/ strcpy(str1, "1234"); strcpy(str2, "keep it simple"); GCC_PUSH_WARN_DMAX rc = strcat_s(str1, 12, str2); GCC_POP_WARN_DMAX ERR_MSVC(ESNOSPC, ERANGE); EXPNULL(str1) CHECK_SLACK(str1, 12); /*--------------------------------------------------*/ strcpy(str1, "1234"); strcpy(str2, "keep it simple"); rc = strcat_s(str1, LEN, str2); ERR(EOK) EXPSTR(str1, "1234keep it simple") len1 = strlen(str1); CHECK_SLACK(&str1[len1], LEN - len1); /*--------------------------------------------------*/ strcpy(str1, "12345678901234567890"); GCC_PUSH_WARN_DMAX rc = strcat_s(str1, 8, &str1[7]); GCC_POP_WARN_DMAX ERR_MSVC(ESOVRLP, ERANGE); EXPNULL(str1) CHECK_SLACK(str1, 8); /*--------------------------------------------------*/ strcpy(str1, "123456789"); GCC_PUSH_WARN_DMAX rc = strcat_s(str1, 9, &str1[8]); GCC_POP_WARN_DMAX ERR_MSVC(ESOVRLP, ERANGE); EXPNULL(str1) CHECK_SLACK(str1, 9); /*--------------------------------------------------*/ strcpy(str1, "12345678901234567890"); rc = strcat_s(str1, LEN, &str1[4]); ERR_MSVC(ESOVRLP, ERANGE); EXPNULL(str1) CHECK_SLACK(str1, LEN); /*--------------------------------------------------*/ strcpy(str1, "12345678901234567890"); len1 = strlen(str1); rc = strcat_s(&str1[5], LEN - 5, &str1[4]); ERR_MSVC(ESOVRLP, ERANGE); EXPNULL(&str1[5]) CHECK_SLACK(&str1[5], LEN - 5); /*--------------------------------------------------*/ strcpy(str2, "123"); strcpy(str1, "keep it simple"); rc = strcat_s(str2, LEN, &str1[0]); ERR(EOK) EXPSTR(str2, "123keep it simple") len2 = strlen(str2); CHECK_SLACK(&str2[len2], LEN - len2); /*--------------------------------------------------*/ strcpy(str2, "1234"); strcpy(str1, "56789"); GCC_PUSH_WARN_DMAX rc = strcat_s(str2, 10, str1); GCC_POP_WARN_DMAX ERR(EOK) EXPSTR(str2, "123456789") len2 = strlen(str2); CHECK_SLACK(&str2[len2], 10 - len2); /*--------------------------------------------------*/ return (errs); } #ifndef __KERNEL__ /* simple hack to get this to work for both userspace and Linux kernel, until a better solution can be created. */ int main(void) { return (test_strcat_s()); } #endif
2.34375
2
2024-11-18T21:10:17.206990+00:00
2021-04-22T07:33:05
1b72c9ebe35e9c365aa54e707dcb692877eaaca5
{ "blob_id": "1b72c9ebe35e9c365aa54e707dcb692877eaaca5", "branch_name": "refs/heads/develop", "committer_date": "2021-04-22T07:33:05", "content_id": "47376be9a28e2573b3bbede05f8db8013bb806b7", "detected_licenses": [ "MIT" ], "directory_id": "466dd8e02ecf9ebf2147e2423d9b7daa30883983", "extension": "c", "filename": "device_info.c", "fork_events_count": 0, "gha_created_at": "2021-04-22T07:23:02", "gha_event_created_at": "2021-04-22T07:31:02", "gha_language": null, "gha_license_id": "MIT", "github_id": 360428845, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 843, "license": "MIT", "license_type": "permissive", "path": "/snippets/device_info.c", "provenance": "stackv2-0065.json.gz:34232", "repo_name": "vsanisimova/lwgsm", "revision_date": "2021-04-22T07:33:05", "revision_id": "d6573a19149c249b05bb9df2b6e7d7c7987927ef", "snapshot_id": "2e448cf0be8eaf15320b693a340f664326e5140d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/vsanisimova/lwgsm/d6573a19149c249b05bb9df2b6e7d7c7987927ef/snippets/device_info.c", "visit_date": "2023-04-10T00:35:44.965163" }
stackv2
/* * Read device information */ #include "lwgsm/lwgsm.h" /** * \brief Device info string array */ static char dev_str[20]; /** * \brief Start SMS send receive procedure */ void read_device_info(void) { /* Read information */ /* Read device manufacturer */ lwgsm_device_get_manufacturer(dev_str, sizeof(dev_str), NULL, NULL, 1); printf("Manuf: %s\r\n", dev_str); /* Read device model */ lwgsm_device_get_model(dev_str, sizeof(dev_str), NULL, NULL, 1); printf("Model: %s\r\n", dev_str); /* Read device serial number */ lwgsm_device_get_serial_number(dev_str, sizeof(dev_str), NULL, NULL, 1); printf("Serial: %s\r\n", dev_str); /* Read device revision */ lwgsm_device_get_revision(dev_str, sizeof(dev_str), NULL, NULL, 1); printf("Revision: %s\r\n", dev_str); }
2.359375
2
2024-11-18T21:10:17.525150+00:00
2022-11-24T19:58:32
c0e27fdc505ad914bd23546944a2b3fa3c219f7e
{ "blob_id": "c0e27fdc505ad914bd23546944a2b3fa3c219f7e", "branch_name": "refs/heads/master", "committer_date": "2022-11-24T19:58:32", "content_id": "de837952d9adcee930da23aa83fb9d87b87a7024", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "ae41a6e8b1033015a5a622e4e7b5f90453632741", "extension": "h", "filename": "poison.h", "fork_events_count": 40, "gha_created_at": "2017-08-05T15:20:13", "gha_event_created_at": "2022-11-24T19:58:33", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 99430730, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 398, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/include/linux/poison.h", "provenance": "stackv2-0065.json.gz:34489", "repo_name": "PikoRT/pikoRT", "revision_date": "2022-11-24T19:58:32", "revision_id": "3783e0d9c7fe3533a73db3a91b0caf9817cc78de", "snapshot_id": "8ac985e89fd640e965f59a651366b67ac996ceea", "src_encoding": "UTF-8", "star_events_count": 127, "url": "https://raw.githubusercontent.com/PikoRT/pikoRT/3783e0d9c7fe3533a73db3a91b0caf9817cc78de/include/linux/poison.h", "visit_date": "2022-11-27T16:28:24.808521" }
stackv2
#ifndef LINUX_POISON_H #define LINUX_POISON_H /* * These are non-NULL pointers that will result in page faults * under normal circumstances, used to verify that nobody uses * non-initialized list entries. * Make sure the values raise faults when these addresses are * read/written. */ #define LIST_POISON1 ((void *) 0x100) #define LIST_POISON2 ((void *) 0x200) #endif /* !LINUX_POISON_H */
2.15625
2
2024-11-18T21:10:17.757335+00:00
2023-02-06T19:13:47
b555c4766e133afeaa8cdba3cadeb01eba14c319
{ "blob_id": "b555c4766e133afeaa8cdba3cadeb01eba14c319", "branch_name": "refs/heads/master", "committer_date": "2023-02-06T19:13:47", "content_id": "f1e00c43a9d9a931d8f48e936e06f317319c5c55", "detected_licenses": [ "MIT" ], "directory_id": "951708999ab2f394416d8f3cc07898d9fbb24689", "extension": "c", "filename": "mptobe.c", "fork_events_count": 4, "gha_created_at": "2020-03-31T04:19:16", "gha_event_created_at": "2022-08-25T03:23:57", "gha_language": "C", "gha_license_id": "MIT", "github_id": 251499058, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 584, "license": "MIT", "license_type": "permissive", "path": "/libmp/mptobe.c", "provenance": "stackv2-0065.json.gz:34748", "repo_name": "Plan9-Archive/drawterm-metal-cocoa", "revision_date": "2023-02-06T19:13:47", "revision_id": "854cc64113a25a0044552adff981c7a0eb2a9b5c", "snapshot_id": "d8b5a919340c20f5672375a5f3743dd3d2cab91d", "src_encoding": "UTF-8", "star_events_count": 14, "url": "https://raw.githubusercontent.com/Plan9-Archive/drawterm-metal-cocoa/854cc64113a25a0044552adff981c7a0eb2a9b5c/libmp/mptobe.c", "visit_date": "2023-02-22T18:33:44.013787" }
stackv2
#include "os.h" #include <mp.h> #include "dat.h" // convert an mpint into a big endian byte array (most significant byte first; left adjusted) // return number of bytes converted // if p == nil, allocate and result array int mptobe(mpint *b, uchar *p, uint n, uchar **pp) { uint m; m = (mpsignif(b)+7)/8; if(m == 0) m++; if(p == nil){ n = m; p = malloc(n); if(p == nil) sysfatal("mptobe: %r"); setmalloctag(p, getcallerpc(&b)); } else { if(n < m) return -1; if(n > m) memset(p+m, 0, n-m); } if(pp != nil) *pp = p; mptober(b, p, m); return m; }
2.421875
2
2024-11-18T21:10:18.018705+00:00
2022-06-06T11:41:15
942de373aabdde9416a2d05b60ba8593a35c1b10
{ "blob_id": "942de373aabdde9416a2d05b60ba8593a35c1b10", "branch_name": "refs/heads/master", "committer_date": "2022-06-06T11:41:15", "content_id": "7c9a4b00ed8347ecceb363a6453db9440efcce04", "detected_licenses": [ "MIT" ], "directory_id": "f1fff1ec58708a7770bdd5491ff54349587530e9", "extension": "c", "filename": "struct_init.c", "fork_events_count": 11, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 171113310, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 587, "license": "MIT", "license_type": "permissive", "path": "/various/DY_C_NOTES/struct_init.c", "provenance": "stackv2-0065.json.gz:34878", "repo_name": "chgogos/oop", "revision_date": "2022-06-06T11:41:15", "revision_id": "8f8e9d7f2abd58acf48c2adce6550971c91cfcf7", "snapshot_id": "a7077e7c3bfab63de03eb02b64f77e097484589f", "src_encoding": "UTF-8", "star_events_count": 16, "url": "https://raw.githubusercontent.com/chgogos/oop/8f8e9d7f2abd58acf48c2adce6550971c91cfcf7/various/DY_C_NOTES/struct_init.c", "visit_date": "2022-06-28T03:44:37.732713" }
stackv2
#include <stdio.h> struct color { int R; int G; int B; }; struct color blue = {.B = 255}; // initialize specific structure fields void print_color_info(struct color *c) { printf("%d %d %d\n", c->R, c->G, c->B); }; struct color f(int x, int y, int z) { return (struct color){.R = x, .G = y, .B = z}; }; int main() { // 1. print_color_info(&blue); // 2. print_color_info(&(struct color){ .G = 255}); // create a structure right in the function arguments // 3. struct color c = f(100, 100, 100); print_color_info(&c); } /* 0 0 255 0 255 0 100 100 100 */
3.609375
4
2024-11-18T21:10:18.303204+00:00
2018-06-17T06:30:47
d7f5788dd4e1a795c4afca9ed8bcef897fd29360
{ "blob_id": "d7f5788dd4e1a795c4afca9ed8bcef897fd29360", "branch_name": "refs/heads/master", "committer_date": "2018-06-17T06:30:47", "content_id": "0e285db2b694fac4f31978cfb4c10d40535d41e9", "detected_licenses": [ "MIT" ], "directory_id": "ece52181d25c29873552819266ac03062bb604aa", "extension": "c", "filename": "execv_syscall.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7235, "license": "MIT", "license_type": "permissive", "path": "/kern/syscall/execv_syscall.c", "provenance": "stackv2-0065.json.gz:35392", "repo_name": "DavideAlta/os161", "revision_date": "2018-06-17T06:30:47", "revision_id": "9db7d16582f011400852e935ae5a9407b24b13c1", "snapshot_id": "3df9ff3fcff7b9e054342a1c8199b766fe8708cc", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/DavideAlta/os161/9db7d16582f011400852e935ae5a9407b24b13c1/kern/syscall/execv_syscall.c", "visit_date": "2023-03-19T01:13:07.775496" }
stackv2
/* * definition for execv syscall * */ #include <types.h> #include <limits.h> #include <kern/errno.h> #include <proc.h> #include <proc_table.h> #include <thread.h> #include <current.h> #include <syscall.h> #include <vnode.h> #include <vfs.h> #include <addrspace.h> #include <copyinout.h> #include <files_table.h> #define ALIGN sizeof(char *) #define PAD(X) (((X) % ALIGN == 0) ? 0 : (ALIGN - ((X) % ALIGN))) /* * get_argc - return total number of arguments * this includes program name itself * get_argc doesn't fail * */ static int get_argc(char **args) { int argc; char **tracer; argc = 0; tracer = args; /* first argument is alraedy program name. so no need */ // argc++; /* for program name arg */ while (*tracer++) argc++; return argc; } /* * free_args - free arguments pointed by args * */ static void free_args(int argc, char **args) { int i; char **tracer; tracer = args; for (i = 0; i < argc; ++i) kfree(*tracer++); /* finally free args itself */ kfree(args); } /* * check_and_copy_args - check if arguments size exceeds ARG_MAX * size calculation includes argument size, * padding (to allign to 4 bytes [typical pointer size]), * and pointer size (that points to argument) * And copy arguments to kernel space. * on success, argc contains total number of arguments * and argv contains array of arguments. * Also, argv args are **not** alligned to 4 bytes. * this includes program name * returns proper error code on failure * */ static int check_and_copy_args(char **args, int *argc, char ***argv, int *size) { int i, result, nargs, args_size, pad_size; size_t str_size; char **head, **kdst, **usrc; KASSERT (curproc != NULL); i = 0; args_size = 0; pad_size = 0; usrc = args; nargs = get_argc(args); /* head to keep track of start of argv in kernel space */ head = kdst = kmalloc(sizeof(char *) * (nargs + 1)); /* extra 1 for termination */ if (kdst == NULL) return ENOMEM; kdst[nargs] = NULL; /* define argv end */ args_size += sizeof(userptr_t); while(*usrc) { /* check if userptr is a valid ptr */ // result = check_userptr ((const_userptr_t) *usrc); if ((!as_is_addr_valid(curproc->p_addrspace, (vaddr_t) *usrc))) { // if (result) { free_args(i, head); return EFAULT; } str_size = strlen(*usrc) + 1; /* account for \0 */ pad_size = PAD(str_size); args_size += str_size + pad_size + sizeof(userptr_t); /* include pointers too */; *kdst = kmalloc(sizeof(char) * str_size); if (*kdst == NULL) { free_args(i, head); return ENOMEM; } ++i; /* str_size works because char is 1 byte */ result = copyin((const_userptr_t) *usrc, *kdst, str_size); if (result) { free_args(i, head); return result; } /* unlikely */ if (args_size >= ARG_MAX) { free_args(i, head); return E2BIG; } usrc++; kdst++; } *argc = nargs; *argv = head; /* triple ref pointer casue, why not! */ *size = args_size; return 0; } /* * put_args_to_userspace_stack - copy arguments from kernel space to * to userspace stack * on success, uargs points to start of args * in userspace stack. Also, stackptr is updated. * returns proper error code on failure * * * before: * ----------------- 0x800000000 * | | <------------ Stackptr, head * | | * /\ | | | * | | | | * copyout | | | | stack grows down * copies | | | | * up | | | \| * | | * | | * | | <------------ tail (args_size) * | | * ----------------- 0x000000000 (STACK_SIZE) * * * after: * ----------------- 0x800000000 * | | * | "arg0" | * /\ | | | * | | "arg1" | | * copyout | | | | stack grows down * copies | | | | * up | | "arg2" | \| * | argv[2] | <------------ tail (argc pointers copied) * | argv[1] | * | argv[0] | <------------ Stackptr, head (args_size) * | | * ----------------- 0x000000000 (STACK_SIZE) * */ static int put_args_to_userspace_stack (char **kargs, int args_size, vaddr_t *stackptr, userptr_t *uargs) { KASSERT(kargs != NULL); KASSERT(stackptr != NULL); int result; char **tracer; size_t str_size, pad_size; userptr_t head, tail; head = (userptr_t) *stackptr; tail = (userptr_t) (*stackptr - args_size); tracer = kargs; while (*tracer) { str_size = strlen(*tracer) + 1; /* account for \0 */ pad_size = PAD(str_size); if (pad_size) { head -= pad_size; bzero(head, pad_size); } head -= str_size; result = copyout(*tracer, head, str_size); if (result) return result; result = copyout(&head, tail, sizeof(userptr_t)); if (result) return result; tail += sizeof(userptr_t); tracer++; } /* terminate argv */ bzero(tail, sizeof(userptr_t)); *stackptr -= args_size; *uargs = (userptr_t) *stackptr; return 0; } int sys_execv (const char *program, char **args, int32_t *retval) { int result, kargc, args_size; char *pname, **kargs; size_t psize; struct vnode *v; struct addrspace *as; vaddr_t entrypoint, stackptr; userptr_t uargs; KASSERT (curproc != NULL); *retval = -1; if ((!as_is_addr_valid(curproc->p_addrspace, (vaddr_t) program)) || (!as_is_addr_valid(curproc->p_addrspace, (vaddr_t) args))) return EFAULT; psize = strlen(program) + 1; pname = kmalloc(psize); if (pname == NULL) return ENOMEM; result = copyin((const_userptr_t) program, pname, psize); if (result) { kfree(pname); return result; } /* copy args to kernel space */ result = check_and_copy_args(args, &kargc, &kargs, &args_size); if (result) { kfree(pname); return result; } /* *kargs points to program name copied to kernel space */ result = vfs_open(pname, O_RDONLY, 0, &v); if (result) { free_args(kargc, kargs); kfree(pname); return result; } /* free program name */ kfree(pname); /* destroy previous address space. */ as = proc_getas(); KASSERT(as != NULL); as_destroy(as); as = NULL; /* Create a new address space. */ as = as_create(); if (as == NULL) { vfs_close(v); free_args(kargc, kargs); return ENOMEM; } /* Switch to it and activate it. */ proc_setas(as); as_activate(); /* Load the executable. */ result = load_elf(v, &entrypoint); if (result) { /* p_addrspace will go away when curproc is destroyed */ vfs_close(v); free_args(kargc, kargs); return result; } /* Done with the file now. */ vfs_close(v); /* Define the user stack in the address space */ result = as_define_stack(as, &stackptr); if (result) { free_args(kargc, kargs); /* p_addrspace will go away when curproc is destroyed */ return result; } result = put_args_to_userspace_stack(kargs, args_size, &stackptr, &uargs); if (result) { free_args(kargc, kargs); return result; } /* free kargs */ free_args(kargc, kargs); /* Warp to user mode. */ enter_new_process(kargc /*argc*/, uargs /*userspace addr of argv*/, NULL /*userspace addr of environment*/, stackptr, entrypoint); /* enter_new_process does not return. */ panic("[!] sys_execv: enter_new_process returned\n"); return EINVAL; }
2.609375
3
2024-11-18T21:10:18.887797+00:00
2018-11-15T18:54:18
71ec0889e9031a93a7b5c95a3da4a8d88056ddd4
{ "blob_id": "71ec0889e9031a93a7b5c95a3da4a8d88056ddd4", "branch_name": "refs/heads/master", "committer_date": "2018-11-15T18:54:18", "content_id": "e06e26078b76eee215273156cb54cbcfd4dbbe52", "detected_licenses": [ "BSD-3-Clause", "BSD-3-Clause-Open-MPI" ], "directory_id": "c609337f8d919e5e1e267758e822510bff6ffd5f", "extension": "c", "filename": "c11_test_shmem_atomic_cswap.c", "fork_events_count": 0, "gha_created_at": "2018-11-15T22:02:45", "gha_event_created_at": "2018-11-15T22:02:46", "gha_language": null, "gha_license_id": null, "github_id": 157778368, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6539, "license": "BSD-3-Clause,BSD-3-Clause-Open-MPI", "license_type": "permissive", "path": "/test/unit/c11_test_shmem_atomic_cswap.c", "provenance": "stackv2-0065.json.gz:35650", "repo_name": "minsii/tests-sos", "revision_date": "2018-11-15T18:54:18", "revision_id": "147e61470d2679db0082248a41362336ffea1feb", "snapshot_id": "6bae8556514873422058ca296de6f2a111d0d5f3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/minsii/tests-sos/147e61470d2679db0082248a41362336ffea1feb/test/unit/c11_test_shmem_atomic_cswap.c", "visit_date": "2021-06-24T06:41:46.239155" }
stackv2
/* * This test program is derived from a unit test created by Nick Park. * The original unit test is a work of the U.S. Government and is not subject * to copyright protection in the United States. Foreign copyrights may * apply. * * Copyright (c) 2017 Intel Corporation. All rights reserved. * This software is available to you under the BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * 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 <stdint.h> #include <stdbool.h> #include <stdio.h> #include <shmem.h> #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L enum op { CSWAP = 0, ATOMIC_COMPARE_SWAP, CTX_ATOMIC_COMPARE_SWAP }; #ifdef ENABLE_DEPRECATED_TESTS #define DEPRECATED_CSWAP shmem_cswap #else #define DEPRECATED_CSWAP shmem_atomic_compare_swap #endif #define TEST_SHMEM_CSWAP(OP, TYPE) \ do { \ static TYPE remote; \ TYPE old; \ const int mype = shmem_my_pe(); \ const int npes = shmem_n_pes(); \ remote = npes; \ shmem_barrier_all(); \ switch (OP) { \ case CSWAP: \ old = DEPRECATED_CSWAP(&remote, (TYPE)npes, (TYPE)mype, \ (mype + 1) % npes); \ break; \ case ATOMIC_COMPARE_SWAP: \ old = shmem_atomic_compare_swap(&remote, (TYPE)npes, \ (TYPE)mype, (mype + 1) % npes); \ break; \ case CTX_ATOMIC_COMPARE_SWAP: \ old = shmem_atomic_compare_swap(SHMEM_CTX_DEFAULT, &remote, \ (TYPE)npes, (TYPE)mype, \ (mype + 1) % npes); \ break; \ default: \ printf("invalid operation (%d)\n", OP); \ shmem_global_exit(1); \ } \ shmem_barrier_all(); \ if (remote != (TYPE)((mype + npes - 1) % npes)) { \ printf("PE %i observed error with TEST_SHMEM_CSWAP(%s, %s)\n", \ mype, #OP, #TYPE); \ rc = EXIT_FAILURE; \ } \ if (old != (TYPE) npes) { \ printf("PE %i error inconsistent value of old (%s, %s)\n", \ mype, #OP, #TYPE); \ rc = EXIT_FAILURE; \ } \ } while (false) #else #define TEST_SHMEM_CSWAP(OP, TYPE) #endif int main(int argc, char* argv[]) { shmem_init(); int rc = EXIT_SUCCESS; #ifdef ENABLE_DEPRECATED_TESTS TEST_SHMEM_CSWAP(CSWAP, int); TEST_SHMEM_CSWAP(CSWAP, long); TEST_SHMEM_CSWAP(CSWAP, long long); TEST_SHMEM_CSWAP(CSWAP, unsigned int); TEST_SHMEM_CSWAP(CSWAP, unsigned long); TEST_SHMEM_CSWAP(CSWAP, unsigned long long); TEST_SHMEM_CSWAP(CSWAP, int32_t); TEST_SHMEM_CSWAP(CSWAP, int64_t); TEST_SHMEM_CSWAP(CSWAP, uint32_t); TEST_SHMEM_CSWAP(CSWAP, uint64_t); TEST_SHMEM_CSWAP(CSWAP, size_t); TEST_SHMEM_CSWAP(CSWAP, ptrdiff_t); #endif /* ENABLE_DEPRECATED_TESTS */ TEST_SHMEM_CSWAP(ATOMIC_COMPARE_SWAP, int); TEST_SHMEM_CSWAP(ATOMIC_COMPARE_SWAP, long); TEST_SHMEM_CSWAP(ATOMIC_COMPARE_SWAP, long long); TEST_SHMEM_CSWAP(ATOMIC_COMPARE_SWAP, unsigned int); TEST_SHMEM_CSWAP(ATOMIC_COMPARE_SWAP, unsigned long); TEST_SHMEM_CSWAP(ATOMIC_COMPARE_SWAP, unsigned long long); TEST_SHMEM_CSWAP(ATOMIC_COMPARE_SWAP, int32_t); TEST_SHMEM_CSWAP(ATOMIC_COMPARE_SWAP, int64_t); TEST_SHMEM_CSWAP(ATOMIC_COMPARE_SWAP, uint32_t); TEST_SHMEM_CSWAP(ATOMIC_COMPARE_SWAP, uint64_t); TEST_SHMEM_CSWAP(ATOMIC_COMPARE_SWAP, size_t); TEST_SHMEM_CSWAP(ATOMIC_COMPARE_SWAP, ptrdiff_t); TEST_SHMEM_CSWAP(CTX_ATOMIC_COMPARE_SWAP, int); TEST_SHMEM_CSWAP(CTX_ATOMIC_COMPARE_SWAP, long); TEST_SHMEM_CSWAP(CTX_ATOMIC_COMPARE_SWAP, long long); TEST_SHMEM_CSWAP(CTX_ATOMIC_COMPARE_SWAP, unsigned int); TEST_SHMEM_CSWAP(CTX_ATOMIC_COMPARE_SWAP, unsigned long); TEST_SHMEM_CSWAP(CTX_ATOMIC_COMPARE_SWAP, unsigned long long); TEST_SHMEM_CSWAP(CTX_ATOMIC_COMPARE_SWAP, int32_t); TEST_SHMEM_CSWAP(CTX_ATOMIC_COMPARE_SWAP, int64_t); TEST_SHMEM_CSWAP(CTX_ATOMIC_COMPARE_SWAP, uint32_t); TEST_SHMEM_CSWAP(CTX_ATOMIC_COMPARE_SWAP, uint64_t); TEST_SHMEM_CSWAP(CTX_ATOMIC_COMPARE_SWAP, size_t); TEST_SHMEM_CSWAP(CTX_ATOMIC_COMPARE_SWAP, ptrdiff_t); shmem_finalize(); return rc; }
2.1875
2
2024-11-18T21:10:19.168105+00:00
2019-07-07T10:31:15
9cb27b103304ca35c57338028634432b48d7ea7f
{ "blob_id": "9cb27b103304ca35c57338028634432b48d7ea7f", "branch_name": "refs/heads/master", "committer_date": "2019-07-07T10:31:15", "content_id": "f6213b781bf7336f315f63b38cc7f98898ede35c", "detected_licenses": [ "Apache-2.0", "MIT" ], "directory_id": "660f68ac120169d35485e448b3558b2fbb389ae2", "extension": "h", "filename": "carp_float.h", "fork_events_count": 0, "gha_created_at": "2019-07-07T10:30:48", "gha_event_created_at": "2019-07-07T10:31:16", "gha_language": "Haskell", "gha_license_id": "NOASSERTION", "github_id": 195638268, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1927, "license": "Apache-2.0,MIT", "license_type": "permissive", "path": "/core/carp_float.h", "provenance": "stackv2-0065.json.gz:35907", "repo_name": "0xflotus/Carp", "revision_date": "2019-07-07T10:31:15", "revision_id": "d1f525a6f0258e21f454c118f4fea3f066d5ad18", "snapshot_id": "28ca64d9eeebf2783cf09dd0bbe0cbca3ad55ad2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/0xflotus/Carp/d1f525a6f0258e21f454c118f4fea3f066d5ad18/core/carp_float.h", "visit_date": "2020-06-16T16:38:33.521301" }
stackv2
#include <limits.h> #include <math.h> #include "carp_stdbool.h" float Float__PLUS_(float x, float y) { return x + y; } float Float__MINUS_(float x, float y) { return x - y; } float Float__MUL_(float x, float y) { return x * y; } float Float__DIV_(float x, float y) { return x / y; } bool Float__LT_(float x, float y) { return x < y; } bool Float__GT_(float x, float y) { return x > y; } bool Float__EQ_(float x, float y) { return x == y; } float Float_neg(float x) { return -x; } float Float_copy(const float *x) { return *x; } int Float_to_MINUS_int(float x) { return (int)x; } float Float_from_MINUS_int(int x) { return (float)x; } int Float_to_MINUS_bytes(float x) { int y; memcpy(&y, &x, sizeof(float)); return y; } float Float_abs(float x) { return fabs(x); } float Float_acos(float x) { return acos(x); } float Float_asin(float x) { return asin(x); } float Float_atan(float x) { return atan(x); } float Float_atan2(float y, float x) { return atan2(y, x); } float Float_cos(float x) { return cos(x); } float Float_cosh(float x) { return cosh(x); } float Float_sin(float x) { return sin(x); } float Float_sinh(float x) { return sinh(x); } float Float_tanh(float x) { return tanh(x); } float Float_exp(float x) { return exp(x); } float Float_frexp(float x, int* exponent) { return frexpf(x, exponent); } float Float_ldexp(float x, int exponent) { return ldexp(x, exponent); } float Float_log(float x) { return log(x); } float Float_log10(float x) { return log10(x); } float Float_modf(float x, float * integer) { return modff(x, integer); } float Float_pow(float x, float y) { return pow(x, y); } float Float_sqrt(float x) { return sqrt(x); } float Float_ceil(float x) { return ceil(x); } float Float_floor(float x) { return floor(x); } float Float_mod(float x, float y) { return fmod(x, y); }
2.75
3
2024-11-18T21:10:19.270951+00:00
2012-09-07T01:20:24
df7fdf2d800674eae0932f8c5e112ccc3efa8731
{ "blob_id": "df7fdf2d800674eae0932f8c5e112ccc3efa8731", "branch_name": "refs/heads/master", "committer_date": "2012-09-07T01:20:24", "content_id": "83704b48c8b38d39d401f1e2e122e6455966ad59", "detected_licenses": [ "Apache-2.0" ], "directory_id": "27889c6ea594acf18c0425812c9b3ff484f72e7e", "extension": "c", "filename": "queue.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 56109785, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13729, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/queue.c", "provenance": "stackv2-0065.json.gz:36035", "repo_name": "tizenorg/framework.telephony.libtcore", "revision_date": "2012-09-07T01:20:24", "revision_id": "253db8b09b28f351937c4fb2566d963419f3842d", "snapshot_id": "be1b8a26c71b13792eefac2d8b32e813b2cf4289", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tizenorg/framework.telephony.libtcore/253db8b09b28f351937c4fb2566d963419f3842d/src/queue.c", "visit_date": "2020-12-31T06:22:26.237181" }
stackv2
/* * libtcore * * Copyright (c) 2012 Samsung Electronics Co., Ltd. All rights reserved. * * Contact: Ja-young Gu <[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 <stdio.h> #include <string.h> #include <pthread.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #include <glib.h> #include "tcore.h" #include "plugin.h" #include "queue.h" #include "hal.h" #include "user_request.h" #include "core_object.h" struct tcore_queue_type { TcoreHal *hal; GQueue *gq; unsigned int next_id; }; struct tcore_pending_type { unsigned int id; TcorePendingSendCallback on_send; void *on_send_user_data; TcorePendingTimeoutCallback on_timeout; void *on_timeout_user_data; TcorePendingResponseCallback on_response; void *on_response_user_data; enum tcore_pending_priority priority; void *data; unsigned int data_len; gboolean enable; unsigned int timeout; time_t timestamp; gboolean flag_sent; gboolean flag_received_response; gboolean flag_auto_free_after_sent; guint timer_src; UserRequest *ur; TcorePlugin *plugin; CoreObject *co; TcoreQueue *queue; }; enum search_field { SEARCH_FIELD_ID_ALL = 0x01, SEARCH_FIELD_ID_WAIT = 0x11, SEARCH_FIELD_ID_SENT = 0x21, SEARCH_FIELD_COMMAND_ALL = 0x02, SEARCH_FIELD_COMMAND_WAIT = 0x12, SEARCH_FIELD_COMMAND_SENT = 0x22, }; static gboolean _on_pending_timeout(gpointer user_data) { TcorePending *p = user_data; dbg("pending timeout!!"); if (!p) return FALSE; tcore_pending_emit_timeout_callback(p); p->on_response = NULL; tcore_hal_dispatch_response_data(p->queue->hal, p->id, 0, NULL); return FALSE; } TcorePending *tcore_pending_new(CoreObject *co, unsigned int id) { TcorePending *p; p = calloc(sizeof(struct tcore_pending_type), 1); if (!p) return NULL; p->id = id; time(&p->timestamp); p->on_send = NULL; p->on_send_user_data = NULL; p->on_response = NULL; p->on_response_user_data = NULL; p->on_timeout = NULL; p->on_timeout_user_data = NULL; p->data = NULL; p->data_len = 0; p->timeout = 0; p->priority = TCORE_PENDING_PRIORITY_DEFAULT; p->flag_sent = FALSE; p->co = co; p->plugin = tcore_object_ref_plugin(co); return p; } void tcore_pending_free(TcorePending *pending) { if (!pending) return; dbg("pending(0x%x) free, id=0x%x", (unsigned int)pending, pending->id); if ((tcore_hal_get_mode(pending->queue->hal) != TCORE_HAL_MODE_AT) && (tcore_hal_get_mode(pending->queue->hal) != TCORE_HAL_MODE_TRANSPARENT)) { if (pending->data) free(pending->data); } if (pending->timer_src) { g_source_remove(pending->timer_src); } free(pending); } unsigned int tcore_pending_get_id(TcorePending *pending) { if (!pending) return 0; return pending->id; } TReturn tcore_pending_set_auto_free_status_after_sent(TcorePending *pending, gboolean flag) { if (!pending) return TCORE_RETURN_EINVAL; pending->flag_auto_free_after_sent = flag; return TCORE_RETURN_SUCCESS; } gboolean tcore_pending_get_auto_free_status_after_sent(TcorePending *pending) { if (!pending) return FALSE; return pending->flag_auto_free_after_sent; } TReturn tcore_pending_set_request_data(TcorePending *pending, unsigned int data_len, void *data) { if (!pending) return TCORE_RETURN_EINVAL; if (pending->data) { if (pending->data_len != 0) { free(pending->data); pending->data = NULL; } } pending->data_len = data_len; if (pending->data_len > 0) { pending->data = calloc(data_len, 1); if (!pending->data) return TCORE_RETURN_ENOMEM; memcpy(pending->data, data, data_len); } else { pending->data = data; } return TCORE_RETURN_SUCCESS; } void *tcore_pending_ref_request_data(TcorePending *pending, unsigned int *data_len) { if (!pending) return NULL; if (data_len) *data_len = pending->data_len; return pending->data; } TReturn tcore_pending_set_priority(TcorePending *pending, enum tcore_pending_priority priority) { if (!pending) return TCORE_RETURN_EINVAL; pending->priority = priority; return TCORE_RETURN_SUCCESS; } TReturn tcore_pending_get_priority(TcorePending *pending, enum tcore_pending_priority *result_priority) { if (!pending || !result_priority) return TCORE_RETURN_EINVAL; *result_priority = pending->priority; return TCORE_RETURN_SUCCESS; } TReturn tcore_pending_set_timeout(TcorePending *pending, unsigned int timeout) { if (!pending) return TCORE_RETURN_EINVAL; pending->timeout = timeout; return TCORE_RETURN_SUCCESS; } TReturn tcore_pending_get_send_status(TcorePending *pending, gboolean *result_status) { if (!pending || !result_status) return TCORE_RETURN_EINVAL; *result_status = pending->flag_sent; return TCORE_RETURN_SUCCESS; } TReturn tcore_pending_set_send_callback(TcorePending *pending, TcorePendingSendCallback func, void *user_data) { if (!pending) return TCORE_RETURN_EINVAL; pending->on_send = func; pending->on_send_user_data = user_data; return TCORE_RETURN_SUCCESS; } TReturn tcore_pending_set_timeout_callback(TcorePending *pending, TcorePendingTimeoutCallback func, void *user_data) { if (!pending) return TCORE_RETURN_EINVAL; pending->on_timeout = func; pending->on_timeout_user_data = user_data; return TCORE_RETURN_SUCCESS; } TReturn tcore_pending_set_response_callback(TcorePending *pending, TcorePendingResponseCallback func, void *user_data) { if (!pending) return TCORE_RETURN_EINVAL; pending->on_response = func; pending->on_response_user_data = user_data; return TCORE_RETURN_SUCCESS; } TReturn tcore_pending_emit_send_callback(TcorePending *pending, gboolean result) { if (!pending) return TCORE_RETURN_EINVAL; pending->flag_sent = TRUE; if (pending->on_send) pending->on_send(pending, result, pending->on_send_user_data); if (result == TRUE) { if (pending->flag_auto_free_after_sent == FALSE && pending->timeout > 0) { /* timer */ dbg("start pending timer! (%d secs)", pending->timeout); pending->timer_src = g_timeout_add_seconds(pending->timeout, _on_pending_timeout, pending); } } return TCORE_RETURN_SUCCESS; } TReturn tcore_pending_emit_timeout_callback(TcorePending *pending) { if (!pending) return TCORE_RETURN_EINVAL; if (pending->on_timeout) pending->on_timeout(pending, pending->on_timeout_user_data); return TCORE_RETURN_SUCCESS; } TReturn tcore_pending_emit_response_callback(TcorePending *pending, int data_len, const void *data) { if (!pending) return TCORE_RETURN_EINVAL; if (pending->on_response) pending->on_response(pending, data_len, data, pending->on_response_user_data); return TCORE_RETURN_SUCCESS; } CoreObject *tcore_pending_ref_core_object(TcorePending *pending) { if (!pending) return NULL; return pending->co; } TcorePlugin *tcore_pending_ref_plugin(TcorePending *pending) { if (!pending) return NULL; return pending->plugin; } TReturn tcore_pending_link_user_request(TcorePending *pending, UserRequest *ur) { if (!pending) return TCORE_RETURN_EINVAL; pending->ur = ur; return TCORE_RETURN_SUCCESS; } UserRequest *tcore_pending_ref_user_request(TcorePending *pending) { if (!pending) return NULL; return pending->ur; } TcoreQueue *tcore_queue_new(TcoreHal *h) { TcoreQueue *queue; queue = calloc(sizeof(struct tcore_queue_type), 1); if (!queue) return FALSE; queue->hal = h; queue->gq = g_queue_new(); if (!queue->gq) { free(queue); return FALSE; } g_queue_init(queue->gq); return queue; } void tcore_queue_free(TcoreQueue *queue) { if (!queue) return; if (queue->gq) g_queue_free(queue->gq); free(queue); } static void _tcore_queue_push_head(TcoreQueue *queue, TcorePending *pending) { int i = -1; TcorePending *tmp; do { i++; tmp = g_queue_peek_nth(queue->gq, i); if (!tmp) { break; } if (tmp->priority == TCORE_PENDING_PRIORITY_IMMEDIATELY) continue; break; } while (1); g_queue_push_nth(queue->gq, pending, i); } TReturn tcore_queue_push(TcoreQueue *queue, TcorePending *pending) { enum tcore_pending_priority priority; if (!queue || !pending) return TCORE_RETURN_EINVAL; if (pending->id == 0) { pending->id = queue->next_id; queue->next_id++; } tcore_pending_get_priority(pending, &priority); switch (priority) { case TCORE_PENDING_PRIORITY_IMMEDIATELY: case TCORE_PENDING_PRIORITY_HIGH: pending->queue = queue; _tcore_queue_push_head(queue, pending); break; case TCORE_PENDING_PRIORITY_DEFAULT: case TCORE_PENDING_PRIORITY_LOW: pending->queue = queue; g_queue_push_tail(queue->gq, pending); break; default: return TCORE_RETURN_EINVAL; break; } dbg("pending(0x%x) push to queue. queue length=%d", (unsigned int)pending, g_queue_get_length(queue->gq)); return TCORE_RETURN_SUCCESS; } TcorePending *tcore_queue_pop(TcoreQueue *queue) { if (!queue) return NULL; return g_queue_pop_head(queue->gq); } TcorePending *tcore_queue_pop_by_pending(TcoreQueue *queue, TcorePending *pending) { TcorePending *tmp; int i = 0; if (!queue) return NULL; do { tmp = g_queue_peek_nth(queue->gq, i); if (!tmp) return NULL; if (tmp == pending) { g_queue_pop_nth(queue->gq, i); return tmp; } i++; } while(1); return NULL; } TcorePending *tcore_queue_pop_timeout_pending(TcoreQueue *queue) { int i = 0; TcorePending *pending = NULL; time_t cur_time = 0; time(&cur_time); do { pending = g_queue_peek_nth(queue->gq, i); if (!pending) return NULL; if (cur_time - pending->timestamp >= (int)pending->timeout) { pending = g_queue_pop_nth(queue->gq, i); break; } i++; } while (pending != NULL); return pending; } TcorePending *tcore_queue_ref_head(TcoreQueue *queue) { if (!queue) return NULL; return g_queue_peek_head(queue->gq); } TcorePending *tcore_queue_ref_tail(TcoreQueue *queue) { if (!queue) return NULL; return g_queue_peek_tail(queue->gq); } static TcorePending *_tcore_queue_search_full(TcoreQueue *queue, unsigned int id, enum tcore_request_command command, enum search_field field, gboolean flag_pop) { TcorePending *pending = NULL; int i = 0; UserRequest *ur; if (!queue) return NULL; do { pending = g_queue_peek_nth(queue->gq, i); if (!pending) return NULL; if ((field & 0xF0) == 0x10) { /* search option is wait pending */ if (pending->flag_sent) { i++; continue; } } else if ((field & 0xF0) == 0x20) { /* search option is sent pending */ if (pending->flag_sent == FALSE) { i++; continue; } } if ((field & 0x0F) == SEARCH_FIELD_ID_ALL) { if (pending->id == id) { if (flag_pop == TRUE) { pending = g_queue_pop_nth(queue->gq, i); } break; } } else if ((field & 0x0F) == SEARCH_FIELD_COMMAND_ALL) { ur = tcore_pending_ref_user_request(pending); if (tcore_user_request_get_command(ur) == command) { if (flag_pop == TRUE) { pending = g_queue_pop_nth(queue->gq, i); } break; } } i++; } while (pending != NULL); return pending; } TcorePending *tcore_queue_search_by_command(TcoreQueue *queue, enum tcore_request_command command, gboolean flag_sent) { if (flag_sent) return _tcore_queue_search_full(queue, 0, command, SEARCH_FIELD_COMMAND_SENT, FALSE); return _tcore_queue_search_full(queue, 0, command, SEARCH_FIELD_COMMAND_WAIT, FALSE); } TcorePending *tcore_queue_pop_by_id(TcoreQueue *queue, unsigned int id) { if (!queue) return NULL; return _tcore_queue_search_full(queue, id, 0, SEARCH_FIELD_ID_ALL, TRUE); } TcorePending *tcore_queue_ref_pending_by_id(TcoreQueue *queue, unsigned int id) { if (!queue) return NULL; return _tcore_queue_search_full(queue, id, 0, SEARCH_FIELD_ID_ALL, FALSE); } TcorePending *tcore_queue_ref_next_pending(TcoreQueue *queue) { TcorePending *pending = NULL; int i = 0; if (!queue) return NULL; do { pending = g_queue_peek_nth(queue->gq, i); if (!pending) { return NULL; } /* skip already sent immediately pending */ if (pending->priority == TCORE_PENDING_PRIORITY_IMMEDIATELY) { if (pending->flag_sent == FALSE) { break; } i++; continue; } else { break; } i++; } while (pending != NULL); if (pending->flag_sent == TRUE) { dbg("pending(0x%x) is waiting state.", (unsigned int)pending); return NULL; } return pending; } unsigned int tcore_queue_get_length(TcoreQueue *queue) { if (!queue) return 0; return g_queue_get_length(queue->gq); } TcoreHal *tcore_queue_ref_hal(TcoreQueue *queue) { if (!queue) return NULL; return queue->hal; } TReturn tcore_queue_cancel_pending_by_command(TcoreQueue *queue, enum tcore_request_command command) { TcorePending *pending; if (!queue) return TCORE_RETURN_EINVAL; while (1) { pending = _tcore_queue_search_full(queue, 0, command, SEARCH_FIELD_COMMAND_ALL, FALSE); if (!pending) break; dbg("pending(0x%x) cancel", pending); if (queue->hal) { tcore_hal_dispatch_response_data(queue->hal, pending->id, 0, NULL); } else { pending = tcore_queue_pop_by_pending(queue, pending); tcore_pending_emit_response_callback(pending, 0, NULL); tcore_user_request_unref(tcore_pending_ref_user_request(pending)); tcore_pending_free(pending); } } return TCORE_RETURN_SUCCESS; }
2.140625
2
2024-11-18T21:10:19.335171+00:00
2023-08-14T02:54:21
3c955557705bec29ed970d72bf814c4a4029260b
{ "blob_id": "3c955557705bec29ed970d72bf814c4a4029260b", "branch_name": "refs/heads/main", "committer_date": "2023-08-14T02:54:21", "content_id": "8c1d13fdfb5bc8c0e2b984b89f1050cf528d88ae", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "7d614bd11481c2097962f9eb67e7afd9701922e7", "extension": "c", "filename": "mktags.c", "fork_events_count": 142, "gha_created_at": "2010-03-12T07:53:48", "gha_event_created_at": "2022-10-27T19:04:33", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 558926, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1809, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/mktags.c", "provenance": "stackv2-0065.json.gz:36163", "repo_name": "Orc/discount", "revision_date": "2023-08-14T02:54:21", "revision_id": "a096c1a3aa0727791aefa52e3ed982cfae9fb5ba", "snapshot_id": "edcd52857870d4625fcc6bb55619f8ae1deba091", "src_encoding": "UTF-8", "star_events_count": 661, "url": "https://raw.githubusercontent.com/Orc/discount/a096c1a3aa0727791aefa52e3ed982cfae9fb5ba/mktags.c", "visit_date": "2023-09-01T20:50:19.346150" }
stackv2
/* block-level tags for passing html blocks through the blender */ #include <stdio.h> #define __WITHOUT_AMALLOC 1 #include "config.h" #include "cstring.h" #include "tags.h" STRING(struct kw) blocktags; /* define a html block tag */ static void define_one_tag(char *id, int selfclose) { struct kw *p = &EXPAND(blocktags); p->id = id; p->size = strlen(id); p->selfclose = selfclose; } /* case insensitive string sort (for qsort() and bsearch() of block tags) */ static int casort(struct kw *a, struct kw *b) { if ( a->size != b->size ) return a->size - b->size; return strncasecmp(a->id, b->id, b->size); } /* stupid cast to make gcc shut up about the function types being * passed into qsort() and bsearch() */ typedef int (*stfu)(const void*,const void*); /* load in the standard collection of html tags that markdown supports */ int main(void) { int i; #define KW(x) define_one_tag(x, 0) #define SC(x) define_one_tag(x, 1) KW("STYLE"); KW("SCRIPT"); KW("ADDRESS"); KW("BDO"); KW("BLOCKQUOTE"); KW("CENTER"); KW("DFN"); KW("DIV"); KW("OBJECT"); KW("H1"); KW("H2"); KW("H3"); KW("H4"); KW("H5"); KW("H6"); KW("LISTING"); KW("NOBR"); KW("FORM"); KW("UL"); KW("P"); KW("OL"); KW("DL"); KW("PLAINTEXT"); KW("PRE"); KW("TABLE"); KW("WBR"); KW("XMP"); SC("HR"); KW("IFRAME"); KW("MAP"); qsort(T(blocktags), S(blocktags), sizeof(struct kw), (stfu)casort); printf("static struct kw blocktags[] = {\n"); for (i=0; i < S(blocktags); i++) printf(" { \"%s\", %d, %d },\n", T(blocktags)[i].id, T(blocktags)[i].size, T(blocktags)[i].selfclose ); printf("};\n\n"); printf("#define NR_blocktags %d\n", S(blocktags)); exit(0); }
2.625
3
2024-11-18T21:10:19.993359+00:00
2022-02-18T02:38:28
6e9c4c895843f32854df3bd0ce0422691b1e9711
{ "blob_id": "6e9c4c895843f32854df3bd0ce0422691b1e9711", "branch_name": "refs/heads/master", "committer_date": "2022-02-18T02:38:28", "content_id": "44a2804a498de08c9417f2442a85c39371be8a5d", "detected_licenses": [ "Apache-2.0" ], "directory_id": "ece93d5aa02aaa405c1f1be552c61914a84c7703", "extension": "c", "filename": "output_print.c", "fork_events_count": 561, "gha_created_at": "2013-01-16T09:13:55", "gha_event_created_at": "2022-02-18T02:38:29", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 7642569, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 39349, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/output_print.c", "provenance": "stackv2-0065.json.gz:36678", "repo_name": "alibaba/tsar", "revision_date": "2022-02-18T02:38:28", "revision_id": "0224ccbf81982b46f600048311f87cb1b5bc8e8f", "snapshot_id": "d642ccbaa79de1e9bfb30cc2d198d9e0a24b318c", "src_encoding": "UTF-8", "star_events_count": 1899, "url": "https://raw.githubusercontent.com/alibaba/tsar/0224ccbf81982b46f600048311f87cb1b5bc8e8f/src/output_print.c", "visit_date": "2023-08-04T09:35:39.873509" }
stackv2
/* * (C) 2010-2011 Alibaba Group Holding Limited * * 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 "tsar.h" #include <fnmatch.h> /* * adjust print opt line */ void adjust_print_opt_line(char *n_opt_line, const char *opt_line, int hdr_len) { int pad_len; char pad[LEN_128] = {0}; if (hdr_len > strlen(opt_line)) { pad_len = (hdr_len - strlen(opt_line)) / 2; memset(pad, '-', pad_len); strcat(n_opt_line, pad); strcat(n_opt_line, opt_line); memset(pad, '-', hdr_len - pad_len - strlen(opt_line)); strcat(n_opt_line, pad); } else { strncat(n_opt_line, opt_line, hdr_len); } } /* * print header and update mod->n_item */ void print_header() { int i; char header[LEN_1M] = {0}; char opt_line[LEN_1M] = {0}; char hdr_line[LEN_1M] = {0}; char opt[LEN_256] = {0}; char n_opt[LEN_256] = {0}; char mod_hdr[LEN_256] = {0}; char *token, *s_token, *n_record; struct module *mod = NULL; if (conf.running_mode == RUN_PRINT_LIVE) { sprintf(opt_line, "Time %s", PRINT_SEC_SPLIT); sprintf(hdr_line, "Time %s", PRINT_SEC_SPLIT); } else { sprintf(opt_line, "Time %s", PRINT_SEC_SPLIT); sprintf(hdr_line, "Time %s", PRINT_SEC_SPLIT); } for (i = 0; i < statis.total_mod_num; i++) { mod = mods[i]; if (!mod->enable) { continue; } memset(n_opt, 0, sizeof(n_opt)); memset(mod_hdr, 0, sizeof(mod_hdr)); get_mod_hdr(mod_hdr, mod); if (strpbrk(mod->record, ITEM_SPLIT) && MERGE_NOT == conf.print_merge) { n_record = strdup(mod->record); /* set print opt line */ token = strtok(n_record, ITEM_SPLIT); int count = 0; mod->p_item = -1; while (token) { s_token = strpbrk(token, ITEM_SPSTART); if (s_token) { memset(opt, 0, sizeof(opt)); memset(n_opt, 0, sizeof(n_opt)); strncat(opt, token, s_token - token); if (*mod->print_item != 0 && fnmatch(mod->print_item, opt, 0)) { token = strtok(NULL, ITEM_SPLIT); count++; continue; } mod->p_item = count++; adjust_print_opt_line(n_opt, opt, strlen(mod_hdr)); strcat(opt_line, n_opt); strcat(opt_line, PRINT_SEC_SPLIT); strcat(hdr_line, mod_hdr); strcat(hdr_line, PRINT_SEC_SPLIT); } token = strtok(NULL, ITEM_SPLIT); } free(n_record); n_record = NULL; } else { memset(opt, 0, sizeof(opt)); /* set print opt line */ adjust_print_opt_line(opt, mod->opt_line, strlen(mod_hdr)); /* set print hdr line */ strcat(hdr_line, mod_hdr); strcat(opt_line, opt); } strcat(hdr_line, PRINT_SEC_SPLIT); strcat(opt_line, PRINT_SEC_SPLIT); } sprintf(header, "%s\n%s\n", opt_line, hdr_line); printf("%s", header); } void printf_result(double result) { if (conf.print_detail) { printf("%6.2f", result); printf("%s", PRINT_DATA_SPLIT); return; } if ((1000 - result) > 0.1) { printf("%6.2f", result); } else if ( (1000 - result / 1024) > 0.1) { printf("%5.1f%s", result / 1024, "K"); } else if ((1000 - result / 1024 / 1024) > 0.1) { printf("%5.1f%s", result / 1024 / 1024, "M"); } else if ((1000 - result / 1024 / 1024 / 1024) > 0.1) { printf("%5.1f%s", result / 1024 / 1024 / 1024, "G"); } else if ((1000 - result / 1024 / 1024 / 1024 / 1024) > 0.1) { printf("%5.1f%s", result / 1024 / 1024 / 1024 / 1024, "T"); } printf("%s", PRINT_DATA_SPLIT); } void print_array_stat(const struct module *mod, const double *st_array) { int i; struct mod_info *info = mod->info; for (i = 0; i < mod->n_col; i++) { if (mod->spec) { /* print null */ if (!st_array || !mod->st_flag || st_array[i] < 0) { /* print record */ if (((DATA_SUMMARY == conf.print_mode) && (SPEC_BIT == info[i].summary_bit)) || ((DATA_DETAIL == conf.print_mode) && (SPEC_BIT == info[i].summary_bit))) { printf("------%s", PRINT_DATA_SPLIT); } } else { /* print record */ if (((DATA_SUMMARY == conf.print_mode) && (SPEC_BIT == info[i].summary_bit)) || ((DATA_DETAIL == conf.print_mode) && (SPEC_BIT == info[i].summary_bit))) { printf_result(st_array[i]); } } } else { /* print null */ if (!st_array || !mod->st_flag || st_array[i] < 0) { /* print record */ if (((DATA_SUMMARY == conf.print_mode) && (SUMMARY_BIT == info[i].summary_bit)) || ((DATA_DETAIL == conf.print_mode) && (HIDE_BIT != info[i].summary_bit))) { printf("------%s", PRINT_DATA_SPLIT); } } else { /* print record */ if (((DATA_SUMMARY == conf.print_mode) && (SUMMARY_BIT == info[i].summary_bit)) || ((DATA_DETAIL == conf.print_mode) && (HIDE_BIT != info[i].summary_bit))) { printf_result(st_array[i]); } } } } } /* print current time */ void print_current_time() { char cur_time[LEN_32] = {0}; time_t timep; struct tm *t; time(&timep); t = localtime(&timep); if (conf.running_mode == RUN_PRINT_LIVE) { strftime(cur_time, sizeof(cur_time), "%d/%m/%y-%T", t); } else { strftime(cur_time, sizeof(cur_time), "%d/%m/%y-%R", t); } printf("%s%s", cur_time, PRINT_SEC_SPLIT); } void print_record() { int i, j; double *st_array; struct module *mod = NULL; /* print summary data */ for (i = 0; i < statis.total_mod_num; i++) { mod = mods[i]; if (!mod->enable) { continue; } if (!mod->n_item) { print_array_stat(mod, NULL); printf("%s", PRINT_SEC_SPLIT); } else { for (j = 0; j < mod->n_item; j++) { if (*mod->print_item != 0 && (mod->p_item != j)) { continue; } st_array = &mod->st_array[j * mod->n_col]; print_array_stat(mod, st_array); printf("%s", PRINT_SEC_SPLIT); } if (mod->n_item > 1) { printf("%s", PRINT_SEC_SPLIT); } } } printf("\n"); } /* running in print live mode */ void running_print_live() { int print_num = 1, re_p_hdr = 0, cost_time = 0, to_sleep = 0; struct timeval tv_begin, tv_end; gettimeofday(&tv_begin, NULL); collect_record(); /* print header */ print_header(); /* set struct module fields */ init_module_fields(); /* skip first record */ if (collect_record_stat() == 0) { do_debug(LOG_INFO, "collect_record_stat warn\n"); } gettimeofday(&tv_end, NULL); cost_time = (tv_end.tv_sec - tv_begin.tv_sec)*1000000 + (tv_end.tv_usec - tv_begin.tv_usec); to_sleep = conf.print_interval*1000000 - cost_time; if (to_sleep > 0) { usleep(to_sleep); } /* print live record */ while (1) { gettimeofday(&tv_begin, NULL); collect_record(); if (!((print_num) % DEFAULT_PRINT_NUM) || re_p_hdr) { /* get the header will print every DEFAULT_PRINT_NUM */ print_header(); re_p_hdr = 0; print_num = 1; } if (!collect_record_stat()) { re_p_hdr = 1; continue; } /* print current time */ print_current_time(); print_record(); fflush(stdout); print_num++; /* sleep every interval */ gettimeofday(&tv_end, NULL); cost_time = (tv_end.tv_sec - tv_begin.tv_sec)*1000000 + (tv_end.tv_usec - tv_begin.tv_usec); to_sleep = conf.print_interval*1000000 - cost_time; if (to_sleep > 0) { usleep(to_sleep); } } } /* find where start printting * number:the suffix number of record data (tsar.data.number) * return * 0 ok * 1 need find last tsar.data file * 2 find error, find time is later than the last line at tsar.data.x, should stop find any more * 3 find error, tsar haved stopped after find time, should stop find it * 4 find error, data not exist, tsar just lost some time data which contains find time * 5 log format error * 6 other error */ int find_offset_from_start(FILE *fp, int number) { long fset, fend, file_len, off_start, off_end, offset, line_len; char *p_sec_token; time_t now, t_token, t_get; struct tm stm; static char line[LEN_10M] = {0}; /* get file len */ if (fseek(fp, 0, SEEK_END) != 0 ) { do_debug(LOG_FATAL, "fseek error:%s", strerror(errno)); } if ((fend = ftell(fp)) < 0) { do_debug(LOG_FATAL, "ftell error:%s", strerror(errno)); } if (fseek(fp, 0, SEEK_SET) != 0) { do_debug(LOG_FATAL, "fseek error:%s", strerror(errno)); } if ((fset = ftell(fp)) < 0) { do_debug(LOG_FATAL, "ftell error:%s", strerror(errno)); } file_len = fend - fset; memset(&line, 0, LEN_10M); if (!fgets(line, LEN_10M, fp)) { do_debug(LOG_FATAL, "fgets error:%s", strerror(errno)); } line_len = strlen(line); /* get time token */ time(&now); if (conf.print_day > conf.print_max_day) { /*get specify date by --date/-d*/ stm.tm_year = conf.print_day / 10000 - 1900; stm.tm_mon = conf.print_day % 10000 / 100 - 1; stm.tm_mday = conf.print_day % 100; stm.tm_hour = 0; stm.tm_min = 0; stm.tm_sec = 0; stm.tm_isdst = -1; t_token = mktime(&stm); conf.print_day = (now - t_token) / (24 * 60 * 60); } if (conf.print_day >= 0) { if (conf.print_day > conf.print_max_day) { conf.print_day = conf.print_max_day; } /* get day's beginning plus 8 hours.Set start and end time for print*/ now = now - now % (24 * 60 * 60) - (8 * 60 * 60); t_token = now - conf.print_day * (24 * 60 * 60) - (60 * conf.print_nline_interval); conf.print_start_time = t_token; conf.print_end_time = t_token + 24 * 60 * 60 + (60 * conf.print_nline_interval); } else { /* set max days for print 6 months*/ if (conf.print_ndays > conf.print_max_day) { conf.print_ndays = conf.print_max_day; } now = now - now % (60 * conf.print_nline_interval); if (conf.running_mode == RUN_WATCH) { if (conf.print_nminute > (conf.print_max_day * 24 * 60)) { conf.print_nminute = conf.print_max_day * 24 * 60; } t_token = now - (60 * conf.print_nminute) - (60 * conf.print_nline_interval); } else { t_token = now - conf.print_ndays * (24 * 60 * 60) - (60 * conf.print_nline_interval); } conf.print_start_time = t_token; conf.print_end_time = now + (60 * conf.print_nline_interval); } offset = off_start = 0; off_end = file_len; while (1) { offset = (off_start + off_end) / 2; memset(&line, 0, LEN_10M); if (fseek(fp, offset, SEEK_SET) != 0) { do_debug(LOG_FATAL, "fseek error:%s", strerror(errno)); } if (!fgets(line, LEN_10M, fp) && errno != 0) { do_debug(LOG_FATAL, "fgets error:%s", strerror(errno)); } memset(&line, 0, LEN_10M); if (!fgets(line, LEN_10M, fp) && errno != 0) { do_debug(LOG_FATAL, "fgets error:%s", strerror(errno)); } if (0 != line[0] && offset > line_len) { p_sec_token = strpbrk(line, SECTION_SPLIT); if (p_sec_token) { *p_sec_token = '\0'; t_get = atol(line); if (labs(t_get - t_token) <= 60) { conf.print_file_number = number; return 0; } /* Binary Search */ if (t_get > t_token) { off_end = offset; } else if (t_get < t_token) { off_start = offset; } } else { /* fatal error, log format error happen. */ return 5; } } else { if (off_end == file_len) { if (number > 0) { conf.print_file_number = number - 1; /* at the end of tsar.data.%d have some data lost during data rotate. stat from previous log file";*/ return 2; } else { /* researching tsar.data to end and not find log data you need.";*/ return 3; } } if (off_start == 0) { conf.print_file_number = number; /* need to research tsar.data.number+1; */ return 1; } /* here should not be arrived. */ return 6; } if (offset == (off_start + off_end) / 2) { if (off_start != 0) { /* tsar has been down for a while, so the following time's stat we can provied only; */ conf.print_file_number = number; return 4; } return 6; } } } /* * set and print record time */ long set_record_time(const char *line) { char *token, s_time[LEN_32] = {0}; static long pre_time, c_time = 0; /* get record time */ token = strpbrk(line, SECTION_SPLIT); memcpy(s_time, line, token - line); /* swap time */ pre_time = c_time; c_time = atol(s_time); c_time = c_time - c_time % 60; pre_time = pre_time - pre_time % 60; /* if skip record when two lines haveing same minute */ if (!(conf.print_interval = c_time - pre_time)) { return 0; } else { return c_time; } } /* * check time if corret for pirnt from tsar.data */ int check_time(const char *line) { char *token, s_time[LEN_32] = {0}; long now_time = 0; static long pre_time; /* get record time */ token = strpbrk(line, SECTION_SPLIT); if (token == NULL) { return 1; } if ((token - line) < 32) { memcpy(s_time, line, token - line); } now_time = atol(s_time); /* check if time is over print_end_time */ if (now_time >= conf.print_end_time) { return 3; } /* if time is divide by conf.print_nline_interval*/ now_time = now_time - now_time % 60; if (!((now_time - conf.print_start_time) % ( 60 * conf.print_nline_interval)) && now_time > pre_time) { /* check now and last record time interval */ if (pre_time && now_time - pre_time == ( 60 * conf.print_nline_interval)) { pre_time = now_time; return 0; } pre_time = now_time; return 1; } else { return 1; } } void print_record_time(long c_time) { char s_time[LEN_32] = {0}; struct tm *t; t = localtime(&c_time); strftime(s_time, sizeof(s_time), "%d/%m/%y-%R", t); printf("%s%s", s_time, PRINT_SEC_SPLIT); } void print_tail(int tail_type) { int i, j, k; double *m_tail; struct module *mod = NULL; switch (tail_type) { case TAIL_MAX: printf("MAX %s", PRINT_SEC_SPLIT); break; case TAIL_MEAN: printf("MEAN %s", PRINT_SEC_SPLIT); break; case TAIL_MIN: printf("MIN %s", PRINT_SEC_SPLIT); break; default: return; } /* print summary data */ for (i = 0; i < statis.total_mod_num; i++) { mod = mods[i]; if (!mod->enable) { continue; } switch (tail_type) { case TAIL_MAX: m_tail = mod->max_array; break; case TAIL_MEAN: m_tail = mod->mean_array; break; case TAIL_MIN: m_tail = mod->min_array; break; default: return; } k = 0; for (j = 0; j < mod->n_item; j++) { if (*mod->print_item != 0 && (mod->p_item != j)) { k += mod->n_col; continue; } int i; struct mod_info *info = mod->info; for (i=0; i < mod->n_col; i++) { /* print record */ if (mod->spec) { if (((DATA_SUMMARY == conf.print_mode) && (SPEC_BIT == info[i].summary_bit)) || ((DATA_DETAIL == conf.print_mode) && (SPEC_BIT == info[i].summary_bit))) { printf_result(m_tail[k]); } } else { if (((DATA_SUMMARY == conf.print_mode) && (SUMMARY_BIT == info[i].summary_bit)) || ((DATA_DETAIL == conf.print_mode) && (HIDE_BIT != info[i].summary_bit))) { printf_result(m_tail[k]); } } k++; } printf("%s", PRINT_SEC_SPLIT); } if (mod->n_item != 1) { if (!m_tail) { print_array_stat(mod, NULL); } printf("%s", PRINT_SEC_SPLIT); } } printf("\n"); } /* * init_running_print, if sucess then return fp, else return NULL */ FILE * init_running_print() { int i=0, k=0; FILE *fp, *fptmp; char filename[LEN_128] = {0}; static char line[LEN_10M] = {0}; /* will print tail*/ conf.print_tail = 1; fp = fopen(conf.output_file_path, "r"); if (!fp) { do_debug(LOG_FATAL, "unable to open the log file %s\n", conf.output_file_path); } /*log number to use for print*/ conf.print_file_number = -1; /* find start offset will print from tsar.data */ k=find_offset_from_start(fp, i); if (k == 1) { /*find all possible record*/ for (i=1; ; i++) { memset(filename, 0, sizeof(filename)); sprintf(filename, "%s.%d", conf.output_file_path, i); fptmp = fopen(filename, "r"); if (!fptmp) { conf.print_file_number = i - 1; break; } k=find_offset_from_start(fptmp, i); if (k==0 || k==4) { if (fclose(fp) < 0) { do_debug(LOG_FATAL, "fclose error:%s", strerror(errno)); } fp=fptmp; break; } if (k== 2) { if (fseek(fp, 0, SEEK_SET) != 0) { do_debug(LOG_FATAL, "fseek error:%s", strerror(errno)); } if (fclose(fptmp) < 0) { do_debug(LOG_FATAL, "fclose error:%s", strerror(errno)); } break; } if (k == 1) { if (fclose(fp) < 0) { do_debug(LOG_FATAL, "fclose error:%s", strerror(errno)); } fp=fptmp; continue; } if (k == 5 || k == 6) { do_debug(LOG_FATAL, "log format error or find_offset_from_start have a bug. error code=%d\n", k); } } } if (k == 5 || k == 6) { do_debug(LOG_FATAL, "log format error or find_offset_from_start have a bug. error code=%d\n", k); } /* get record */ if (!fgets(line, LEN_10M, fp)) { do_debug(LOG_FATAL, "can't get enough log info\n"); } /* read one line to init module parameter */ read_line_to_module_record(line); /* print header */ print_header(); /* set struct module fields */ init_module_fields(); set_record_time(line); return fp; } /* * print mode, print data from tsar.data */ void running_print() { int print_num = 1, re_p_hdr = 0; char filename[LEN_128] = {0}; long n_record = 0, s_time; FILE *fp; static char line[LEN_10M] = {0}; /*find the position of the first record to be printed. (eg: middle of tsar.data.2)*/ fp = init_running_print(); /* skip first record */ if (collect_record_stat() == 0) { do_debug(LOG_INFO, "collect_record_stat warn\n"); } /*now ,print all printable records*/ /*(eg: second half of tsar.data.2, then all of tsar.data.1, then tsar.data)*/ while (1) { if (!fgets(line, LEN_10M, fp)) { if (conf.print_file_number <= 0) { break; } else { conf.print_file_number = conf.print_file_number - 1; memset(filename, 0, sizeof(filename)); if (conf.print_file_number == 0) { sprintf(filename, "%s", conf.output_file_path); } else { sprintf(filename, "%s.%d", conf.output_file_path, conf.print_file_number); } if (fclose(fp) < 0) { do_debug(LOG_FATAL, "fclose error:%s", strerror(errno)); } fp = fopen(filename, "r"); if (!fp) { do_debug(LOG_FATAL, "unable to open the log file %s.\n", filename); } continue; } } int k = check_time(line); if (k == 1) { continue; } if (k == 3) { break; } /* collect data then set mod->summary */ read_line_to_module_record(line); if (!(print_num % DEFAULT_PRINT_NUM) || re_p_hdr) { /* get the header will print every DEFAULT_PRINT_NUM */ print_header(); re_p_hdr = 0; print_num = 1; } /* exclued the two record have same time */ if (!(s_time = set_record_time(line))) { continue; } /* reprint header because of n_item's modifing */ if (!collect_record_stat()) { re_p_hdr = 1; continue; } print_record_time(s_time); print_record(); n_record++; print_num++; memset(line, 0, sizeof(line)); } if (n_record) { printf("\n"); print_tail(TAIL_MAX); print_tail(TAIL_MEAN); print_tail(TAIL_MIN); } if (fclose(fp) < 0) { do_debug(LOG_FATAL, "fclose error:%s", strerror(errno)); } fp = NULL; } char * trim(char* src, int max_len) { int cur_len = 0; char *index=src; while (*index == ' ' && cur_len<max_len) { index++; cur_len++; } return index; } int seek_tail_lines(FILE *fp, int n, int len[]) { int total_num = 0; /* find two \n from end*/ if (fseek(fp, -1, SEEK_END) != 0) { do_debug(LOG_FATAL, "fseek error:%s", strerror(errno)); } while (1) { if (fgetc(fp) == '\n') { ++total_num; len[n - total_num] = 0; } else { ++len[n - total_num]; } if (total_num > n) { break; } if (fseek(fp, -2, SEEK_CUR) != 0) { /* goto file head */ if (fseek(fp, 0, SEEK_SET) != 0) { do_debug(LOG_FATAL, "fseek error:%s", strerror(errno)); } break; } } return total_num; } void running_check(int check_type) { int total_num, len[2] = {0}, i, j, k; FILE *fp; char filename[LEN_128] = {0}; char tmp[10][LEN_4096]; char host_name[LEN_64] = {0}; struct module *mod = NULL; struct stat statbuf; time_t nowtime, ts[2] = {0}; double *st_array; char *line[2]; static char check[LEN_4096 * 11] = {0}; /* get hostname */ if (0 != gethostname(host_name, sizeof(host_name))) { do_debug(LOG_FATAL, "tsar -check: gethostname err, errno=%d", errno); } i = 0; while (host_name[i]) { if (!isprint(host_name[i++])) { host_name[i-1] = '\0'; break; } } sprintf(filename, "%s", conf.output_file_path); fp = fopen(filename, "r"); if (!fp) { do_debug(LOG_FATAL, "unable to open the log file %s.\n", filename); } /* check file update time */ stat(filename, &statbuf); time(&nowtime); if (nowtime - statbuf.st_mtime > 300) { do_debug(LOG_FATAL, "/var/log/tsar.data is far away from now, now time is %d, last time is %d", nowtime, statbuf.st_mtime); } /*FIX ME*/ total_num = seek_tail_lines(fp, 2, len); if (total_num == 0) { if (fclose(fp) < 0) { do_debug(LOG_FATAL, "fclose error:%s", strerror(errno)); } sprintf(filename, "%s.1", conf.output_file_path); fp = fopen(filename, "r"); if (!fp) { do_debug(LOG_FATAL, "unable to open the log file %s.\n", filename); } /* count tsar.data.1 lines */ total_num = seek_tail_lines(fp, 2, len); if (total_num < 2) { do_debug(LOG_FATAL, "not enough lines at log file %s.\n", filename); } line[0] = malloc(len[0] + 2); if (!fgets(line[0], len[0] + 2, fp)) { do_debug(LOG_FATAL, "fgets error:%s", strerror(errno)); } line[1] = malloc(len[1] + 2); if (!fgets(line[1], len[1] + 2, fp)) { do_debug(LOG_FATAL, "fgets error:%s", strerror(errno)); } } else if (total_num == 1) { line[1] = malloc(len[1] + 2); if (!fgets(line[1], len[1] + 2, fp)) { do_debug(LOG_FATAL, "fgets error:%s", strerror(errno)); } if (fclose(fp) < 0) { do_debug(LOG_FATAL, "fclose error:%s", strerror(errno)); } sprintf(filename, "%s.1", conf.output_file_path); fp = fopen(filename, "r"); if (!fp) { do_debug(LOG_FATAL, "unable to open the log file %s\n", filename); } /* go to the start of the last line at tsar.data.1 */ total_num = seek_tail_lines(fp, 1, len); if (total_num < 1) { do_debug(LOG_FATAL, "not enough lines at log file %s\n", filename); } line[0] = malloc(len[0] + 2); if (!fgets(line[0], len[0] + 2, fp)) { do_debug(LOG_FATAL, "fgets error:%s", strerror(errno)); } } else { line[0] = malloc(len[0] + 2); if (!fgets(line[0], len[0] + 2, fp)) { do_debug(LOG_FATAL, "fgets error:%s", strerror(errno)); } line[1] = malloc(len[1] + 2); if (!fgets(line[1], len[1] + 2, fp)) { do_debug(LOG_FATAL, "fgets error:%s", strerror(errno)); } } /*as fp is not used after here,close it */ if (fclose(fp) < 0) { do_debug(LOG_FATAL, "fclose error:%s", strerror(errno)); } fp = NULL; /* set struct module fields */ init_module_fields(); /* read one line to init module parameter */ ts[0] = read_line_to_module_record(line[0]); free(line[0]); collect_record_stat(); ts[1] = read_line_to_module_record(line[1]); free(line[1]); if (ts[0] && ts[1]) { conf.print_interval = ts[1] - ts[0]; if (conf.print_interval == 0) { do_debug(LOG_FATAL, "running tsar -c too frequently"); return; } } collect_record_stat(); /*display check detail*/ /* ---------------------------RUN_CHECK_NEW--------------------------------------- */ if (check_type == RUN_CHECK_NEW) { printf("%s\ttsar\t", host_name); for (i = 0; i < statis.total_mod_num; i++) { mod = mods[i]; if (!mod->enable) { continue; } struct mod_info *info = mod->info; /* get mod name */ char *mod_name = strstr(mod->opt_line, "--"); if (mod_name) { mod_name += 2; } char opt[LEN_128] = {0}; char *n_record = strdup(mod->record); char *token = strtok(n_record, ITEM_SPLIT); char *s_token; for (j = 0; j < mod->n_item; j++) { memset(opt, 0, sizeof(opt)); if (token) { s_token = strpbrk(token, ITEM_SPSTART); if (s_token) { strncat(opt, token, s_token - token); strcat(opt, ":"); } } st_array = &mod->st_array[j * mod->n_col]; for (k=0; k < mod->n_col; k++) { if (mod->spec) { if (!st_array || !mod->st_flag) { if (((DATA_SUMMARY == conf.print_mode) && (SPEC_BIT == info[k].summary_bit)) || ((DATA_DETAIL == conf.print_mode) && (SPEC_BIT == info[k].summary_bit))) { printf("%s:%s%s=-%s", mod_name, opt, trim(info[k].hdr, LEN_128), " "); } } else { if (((DATA_SUMMARY == conf.print_mode) && (SPEC_BIT == info[k].summary_bit)) || ((DATA_DETAIL == conf.print_mode) && (SPEC_BIT == info[k].summary_bit))) { printf("%s:%s%s=", mod_name, opt, trim(info[k].hdr, LEN_128)); printf("%0.1f ", st_array[k]); } } } else { if (!st_array || !mod->st_flag) { if (((DATA_SUMMARY == conf.print_mode) && (SUMMARY_BIT == info[k].summary_bit)) || ((DATA_DETAIL == conf.print_mode) && (HIDE_BIT != info[k].summary_bit))) { printf("%s:%s%s=-%s", mod_name, opt, trim(info[k].hdr, LEN_128), " "); } } else { if (((DATA_SUMMARY == conf.print_mode) && (SUMMARY_BIT == info[k].summary_bit)) || ((DATA_DETAIL == conf.print_mode) && (HIDE_BIT != info[k].summary_bit))) { printf("%s:%s%s=", mod_name, opt, trim(info[k].hdr, LEN_128)); printf("%0.1f ", st_array[k]); } } } } if (token) { token = strtok(NULL, ITEM_SPLIT); } } if (n_record) { free(n_record); n_record = NULL; } } printf("\n"); return; } #ifdef OLDTSAR /*tsar -check output similar as: v014119.cm3 tsar apache/qps=5.35 apache/rt=165.89 apache/busy=2 apache/idle=148 cpu=3.58 mem=74.93% load1=0.22 load5=0.27 load15=0.20 xvda=0.15 ifin=131.82 ifout=108.86 TCPretr=0.12 df/=4.04% df/home=10.00% df/opt=71.22% df/tmp=2.07% df/usr=21.27% df/var=5.19% */ /* ------------------------------RUN_CHECK------------------------------------------- */ if (check_type == RUN_CHECK) { //memset(tmp, 0, 10 * LEN_4096); sprintf(check, "%s\ttsar\t", host_name); for (i = 0; i < statis.total_mod_num; i++) { mod = mods[i]; if (!mod->enable){ continue; } if (!strcmp(mod->name, "mod_apache")) { for (j = 0; j < mod->n_item; j++) { st_array = &mod->st_array[j * mod->n_col]; if (!st_array || !mod->st_flag) { sprintf(tmp[0], " apache/qps=- apache/rt=- apache/busy=- apache/idle=-"); } else { sprintf(tmp[0], " apache/qps=%0.2f apache/rt=%0.2f apache/busy=%0.0f apache/idle=%0.0f", st_array[0], st_array[1], st_array[3], st_array[4]); } } } if (!strcmp(mod->name, "mod_cpu")) { for (j = 0; j < mod->n_item; j++) { st_array = &mod->st_array[j * mod->n_col]; if (!st_array || !mod->st_flag) { sprintf(tmp[1], " cpu=-"); } else { sprintf(tmp[1], " cpu=%0.2f", st_array[5]); } } } if (!strcmp(mod->name, "mod_mem")) { for (j = 0; j < mod->n_item; j++) { st_array = &mod->st_array[j * mod->n_col]; if (!st_array || !mod->st_flag) { sprintf(tmp[2], " mem=-"); } else { sprintf(tmp[2], " mem=%0.2f%%", st_array[5]); } } } if (!strcmp(mod->name, "mod_load")) { for (j = 0; j < mod->n_item; j++) { st_array = &mod->st_array[j * mod->n_col]; if (!st_array || !mod->st_flag) { sprintf(tmp[3], " load1=- load5=- load15=-"); } else { sprintf(tmp[3], " load1=%0.2f load5=%0.2f load15=%0.2f", st_array[0], st_array[1], st_array[2]); } } } if (!strcmp(mod->name, "mod_io")) { char opt[LEN_128] = {0}; char item[LEN_128] = {0}; char *n_record = strdup(mod->record); char *token = strtok(n_record, ITEM_SPLIT); char *s_token; for (j = 0; j < mod->n_item && token != NULL; j++) { s_token = strpbrk(token, ITEM_SPSTART); if (s_token) { memset(opt, 0, sizeof(opt)); strncat(opt, token, s_token - token); st_array = &mod->st_array[j * mod->n_col]; if (!st_array || !mod->st_flag) { sprintf(item, " %s=-", opt); } else { sprintf(item, " %s=%0.2f", opt, st_array[10]); } strcat(tmp[4], item); } token = strtok(NULL, ITEM_SPLIT); } if (n_record) { free(n_record); n_record = NULL; } } if (!strcmp(mod->name, "mod_traffic")) { for (j = 0; j < mod->n_item; j++) { st_array = &mod->st_array[j * mod->n_col]; if (!st_array || !mod->st_flag) { sprintf(tmp[5], " ifin=- ifout=-"); } else { sprintf(tmp[5], " ifin=%0.2f ifout=%0.2f", st_array[0] / 1000, st_array[1] / 1000); } } } if (!strcmp(mod->name, "mod_tcp")) { for (j = 0; j < mod->n_item; j++) { st_array = &mod->st_array[j * mod->n_col]; if (!st_array || !mod->st_flag) { sprintf(tmp[6], " TCPretr=-"); } else { sprintf(tmp[6], " TCPretr=%0.2f", st_array[7]); } } } if (!strcmp(mod->name, "mod_partition")) { char opt[LEN_128] = {0}; char item[LEN_128] = {0}; char *n_record = strdup(mod->record); char *token = strtok(n_record, ITEM_SPLIT); char *s_token; for (j = 0; j < mod->n_item && token != NULL; j++) { s_token = strpbrk(token, ITEM_SPSTART); if (s_token) { memset(opt, 0, sizeof(opt)); strncat(opt, token, s_token - token); st_array = &mod->st_array[j * mod->n_col]; if (!st_array || !mod->st_flag) { sprintf(item, " df%s=-", opt); } else { sprintf(item, " df%s=%0.2f%%", opt, st_array[3]); } strcat(tmp[7], item); } token = strtok(NULL, ITEM_SPLIT); } if (n_record) { free(n_record); n_record = NULL; } } if (!strcmp(mod->name, "mod_nginx")){ for (j = 0; j < mod->n_item; j++) { st_array = &mod->st_array[j * mod->n_col]; if (!st_array || !mod->st_flag) { sprintf(tmp[8], " nginx/qps=- nginx/rt=-"); } else { sprintf(tmp[8], " nginx/qps=%0.2f nginx/rt=%0.2f", st_array[7], st_array[8]); } } } if (!strcmp(mod->name, "mod_swap")) { for (j = 0; j < mod->n_item; j++) { st_array = &mod->st_array[j * mod->n_col]; if (!st_array || !mod->st_flag) { sprintf(tmp[9], " swap/total=- swap/util=-"); } else { sprintf(tmp[9], " swap/total=%0.2f swap/util=%0.2f%%", st_array[2] / 1024 / 1024, st_array[3]); } } } } for (j = 0; j < 10; j++) { strcat(check, tmp[j]); } printf("%s\n", check); } #endif } /*end*/
2
2
2024-11-18T21:10:20.055422+00:00
2019-02-26T23:00:28
94ba710297db5b8bac4e22252dbdc90eb22e10db
{ "blob_id": "94ba710297db5b8bac4e22252dbdc90eb22e10db", "branch_name": "refs/heads/master", "committer_date": "2019-02-26T23:00:28", "content_id": "79c1b85e68bbec3b9d5ac5a436c543ac73a3a3cd", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "b0c89db4f26c3e0867c9b9031319a727e015db11", "extension": "h", "filename": "stack.h", "fork_events_count": 4, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 54828001, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1852, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/include/ft/cols/stack.h", "provenance": "stackv2-0065.json.gz:36807", "repo_name": "TeskaLabs/Frame-Transporter", "revision_date": "2019-02-26T23:00:28", "revision_id": "da06009e49a733f44612372599db7176d8c49c96", "snapshot_id": "f6152c047c9f228895056549499863a8fb6d54e1", "src_encoding": "UTF-8", "star_events_count": 11, "url": "https://raw.githubusercontent.com/TeskaLabs/Frame-Transporter/da06009e49a733f44612372599db7176d8c49c96/include/ft/cols/stack.h", "visit_date": "2022-01-11T19:59:44.354288" }
stackv2
#ifndef FT_COLS_STACK_H_ #define FT_COLS_STACK_H_ // Lock-free (!) stack // // A lock-free stack doesn’t require the use of mutex locks. // More generally, it’s a data structure that can be accessed from multiple threads without blocking. // Lock-free data structures will generally provide better throughput than mutex locks. // And it’s usually safer, because there’s no risk of getting stuck on a lock that will never be freed, such as a deadlock situation. // On the other hand there’s additional risk of starvation (livelock), where a thread is unable to make progress. // // Heavily inspired by http://nullprogram.com/blog/2014/09/02/ (Chris Wellons) struct ft_stack; struct ft_stack_node { struct ft_stack_node * next; char data[]; }; static inline struct ft_stack_node * ft_stack_node_new(size_t payload_size) { struct ft_stack_node * this = malloc(sizeof(struct ft_stack_node) + payload_size); if (this != NULL) { this->next = NULL; } return this; } static inline void ft_stack_node_del(struct ft_stack_node * this) { free(this); } struct ft_stack_head { uintptr_t aba; struct ft_stack_node * node; }; typedef void (* ft_stack_on_remove_callback)(struct ft_stack * stack, struct ft_stack_node * node); struct ft_stack { struct ft_stack_node *node_buffer; _Atomic struct ft_stack_head head; _Atomic size_t size; ft_stack_on_remove_callback on_remove_callback; }; static inline size_t ft_stack_size(struct ft_stack * this) { assert(this != NULL); return atomic_load(&this->size); } bool ft_stack_init(struct ft_stack *, ft_stack_on_remove_callback on_remove_callback); void ft_stack_fini(struct ft_stack *); size_t ft_stack_clear(struct ft_stack *); bool ft_stack_push(struct ft_stack *, struct ft_stack_node * node); struct ft_stack_node * ft_stack_pop(struct ft_stack *); #endif // FT_COLS_STACK_H_
2.671875
3
2024-11-18T21:10:20.140332+00:00
2017-12-04T01:37:28
485bb33267a47690c110904295b9735230f9ca9e
{ "blob_id": "485bb33267a47690c110904295b9735230f9ca9e", "branch_name": "refs/heads/master", "committer_date": "2017-12-04T01:37:28", "content_id": "d698746c0684b32732ebb7617923b0e0ed3a03a3", "detected_licenses": [ "MIT" ], "directory_id": "954f27cf9a743b511a05ff9142e11d32cfe23456", "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": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7518, "license": "MIT", "license_type": "permissive", "path": "/src/client/client.c", "provenance": "stackv2-0065.json.gz:36936", "repo_name": "gustavo-oliveira-mendonca/tp_redes_3", "revision_date": "2017-12-04T01:37:28", "revision_id": "cbd541fb0c81085302f5cdd32b7f7e2b00a854c1", "snapshot_id": "2509998d8b7f59104517475887fb49c89475798a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gustavo-oliveira-mendonca/tp_redes_3/cbd541fb0c81085302f5cdd32b7f7e2b00a854c1/src/client/client.c", "visit_date": "2021-08-23T06:59:52.543285" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <limits.h> #include <string.h> #include <time.h> #include <sys/time.h> #include <netinet/in.h> #include "fsmCliente.h" #include "../commom/tp_socket.h" #include "../commom/arquivo.h" #include "../commom/pacote.h" #include "../commom/transacao.h" #define DEBUG // #define IMPRIME_DADOS_DO_PACOTE // #define STEP #ifdef STEP void aguardaEnter(); #endif #define TAM_PORTA 6 #define TAM_NOME_ARQUIVO 32 #define TAM_HOST 16 long getTime(); long timeDiff(long, long); void inicializa(int*, char**); void carregaParametros(int*, char**, char*, short int*, char*, int*, short int*); void estadoEnviaReq(int*); void estadoRecebeArq(int*); void estadoErro(int*); void estadoEnviaAck(int*); void estadoTermino(int*); int tamMaxMsg; transacao *t; short int porta; short int tamJanela; char host[TAM_HOST]; int contaBytes = 0; //variaveis para o tempo struct timeval inicio_tempo, fim_tempo; long t_total; long t_t0; long t_tf; int main(int argc, char* argv[]){ printf("Cliente iniciado\n"); //inicializa programa: carrega parâmetros, inicializa variáveis, aloca memória... inicializa(&argc, argv); // double comeco, duracao; int estadoAtual = ESTADO_ENVIA_REQ; int operacao; // opera FSM que rege o comportamento do sistema while (1){ switch(estadoAtual){ case ESTADO_ENVIA_REQ: estadoEnviaReq(&operacao); break; case ESTADO_RECEBE_ARQ: estadoRecebeArq(&operacao); break; case ESTADO_ERRO: estadoErro(&operacao); break; case ESTADO_ENVIA_ACK: estadoEnviaAck(&operacao); break; case ESTADO_TERMINO: estadoTermino(&operacao); break; } transita(&estadoAtual, &operacao); } exit(EXIT_SUCCESS); } void estadoEnviaReq(int *operacao){ #ifdef DEBUG printf("\n[FSM] ENVIA_REQ\n"); #endif int status; t->envio = criaPacoteVazio(); t->envio->opcode = (uint8_t)REQ; strcpy(t->envio->nomeArquivo, t->nomeArquivo); montaMensagemPeloPacote(t->bufEnvio, t->envio); // forma endereço para envio do pacote ao servidor if (tp_build_addr(&t->toAddr, host, porta) < 0){ perror("Erro no envio do pacote de requisicao de arquivo"); // TODO: tratar erro } #ifdef DEBUG printf("[DEBUG] Pacote a ser enviado:\n"); imprimePacote(t->envio, 0); #endif #ifdef STEP aguardaEnter(); #endif // inicia a contagem do tempo t_t0 = getTime(); //envia requisição ao servidor status = tp_sendto(t->socketFd, t->bufEnvio, tamMaxMsg, &t->toAddr); // verifica estado do envio if (status > 0){ *operacao = OPERACAO_OK; } else { *operacao = OPERACAO_NOK; } destroiPacote(t->envio); } void estadoRecebeArq(int *operacao){ #ifdef DEBUG printf("\n[FSM] RECEBE_ARQ\n"); #endif int bytesRecebidos = 0; bytesRecebidos = tp_recvfrom(t->socketFd, t->bufRecebimento, tamMaxMsg, &t->toAddr); contaBytes += bytesRecebidos; montaPacotePelaMensagem(t->recebido, t->bufRecebimento, bytesRecebidos); #ifdef DEBUG printf("Pacote recebido:\n"); imprimePacote(t->recebido, 1); #endif if (t->recebido->opcode == (uint8_t)DADOS){ // verifica se bloco é o esperado if (t->recebido->numBloco != t->numBlocoEsperado){ // ignora mensagem *operacao = OPERACAO_IGNORA; return; } if (!t->arquivoAberto){ t->arquivo = abreArquivoParaEscrita(t->nomeArquivo); t->arquivoAberto = t->arquivo != NULL; } escreveBytesEmArquivo(t->recebido->dados, t->arquivo , t->recebido->cargaUtil); *operacao = OPERACAO_OK; t->numBlocoEsperado++; return; } if (t->recebido->opcode == (uint8_t)FIM){ fechaArquivo(t->arquivo); *operacao = OPERACAO_TERMINO; return; } // carrega erro na transação t->codErro = t->recebido->codErro; strcpy(t->mensagemErro, t->recebido->mensagemErro); *operacao = OPERACAO_NOK; } void estadoErro(int *operacao){ #ifdef DEBUG printf("\n[FSM] ERRO\n"); #endif //exibe mensagem de erro printf("\n[ERRO]> codigo: %d\nmensagem: %s\n", t->codErro, t->mensagemErro); destroiTransacao(t); } void estadoEnviaAck(int *operacao){ #ifdef DEBUG printf("\n[FSM] ENVIA_ACK\n"); #endif int status; t->envio = criaPacoteVazio(tamMaxMsg); t->envio->opcode = (uint8_t)ACK; t->envio->numBloco = t->recebido->numBloco + 1; montaMensagemPeloPacote(t->bufEnvio, t->envio); #ifdef DEBUG printf("[DEBUG] Pacote a ser enviado:\n"); imprimePacote(t->envio, 0); #endif #ifdef STEP aguardaEnter(); #endif status = tp_sendto(t->socketFd, t->bufEnvio, tamMaxMsg, &t->toAddr); // verifica estado do envio if (status > 0){ *operacao = OPERACAO_OK; } else { *operacao = OPERACAO_NOK; } destroiPacote(t->envio); } void estadoTermino(int *operacao){ #ifdef DEBUG printf("\n[FSM] TERMINO\n"); #endif t_tf = getTime(); printf("inicio %ld, fim %ld\n",t_t0, t_tf); t_total = (timeDiff(t_t0, t_tf)/* / 1000000000*/); printf("inicio %ld, fim %ld\n",t_t0, t_tf); //imprime os parametros exigidos printf("Buffer = %d byte(s), %10.2f KBps (%u KBytes em %3.6f s)\n", tamMaxMsg, (float)(contaBytes / 1024) / ((float)t_total / 1000000000), contaBytes / 1024, (float)t_total / 1000000000); printf("Saindo...\n"); exit(EXIT_SUCCESS); } void inicializa(int *argc, char* argv[]){ char *nomeArquivo = calloc(TAM_NOME_ARQUIVO, sizeof nomeArquivo); // alimenta numero da porta e tamanho do buffer pelos parametros recebidos carregaParametros(argc, argv, host, &porta, nomeArquivo, &tamMaxMsg, &tamJanela); t = inicializaTransacao(tamMaxMsg, 0, tamJanela); // TODO: verificar se nao é porta inves de 0 strcpy(t->nomeArquivo, nomeArquivo); free(nomeArquivo); // chamada de função de inicialização para ambiente de testes tp_init(); } // UTIL void carregaParametros(int* argc, char** argv, char* host, short int* porta, char* arquivo, int* tamBuffer, short int* tamJanela){ #ifdef DEBUG printf("[DEBUG] numero de parametros recebidos: %d\n", *argc); #endif char *ultimoCaractere; // verifica se programa foi chamado com argumentos corretos if (*argc != 6){ fprintf(stderr, "ERRO-> parametros invalidos! Uso: %s [host] [porta] [nome_arquivo] [tam_buffer] [tam_janela]\n", argv[0]); exit(EXIT_FAILURE); } else { errno = 0; *tamBuffer = strtoul(argv[4], &ultimoCaractere, 10); if ((errno == ERANGE && (*tamBuffer == LONG_MAX || *tamBuffer == LONG_MIN)) || (errno != 0 && *tamBuffer == 0)){ perror("strtoul"); exit(EXIT_FAILURE); } } *porta = atoi(argv[2]); memset(host, '\0', TAM_HOST); strcpy(host, argv[1]); memset(arquivo, '\0', TAM_NOME_ARQUIVO); strcpy(arquivo, argv[3]); *tamJanela = atoi(argv[5]); #ifdef DEBUG printf("[DEBUG] Parametros recebidos-> host: %s porta: %d nome_arquivo: %s tamBuffer: %d tamJanela: %d\n", host, *porta, arquivo, *tamBuffer, *tamJanela); #endif } long getTime(){ struct timespec tempo; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &tempo); return tempo.tv_nsec; } // retorna diferença em nanosegundos long timeDiff(long start, long end){ long temp; if ((end - start) < 0){ temp = 1000000000 + end - start; } else { temp = end - start; } return temp; } #ifdef STEP void aguardaEnter(){ printf("pressione Enter para continuar..."); while (getchar() != '\n'); } #endif
2.359375
2
2024-11-18T21:10:20.204166+00:00
2015-03-15T21:09:15
82895ca545cfb4eca1dc2b8ddb491a2892f49895
{ "blob_id": "82895ca545cfb4eca1dc2b8ddb491a2892f49895", "branch_name": "refs/heads/master", "committer_date": "2015-03-15T21:09:24", "content_id": "b5606d6165bcab7fb165bf61582b8046a3aa700f", "detected_licenses": [ "Apache-2.0" ], "directory_id": "21c99b5150004b2d2b532b41a625414277118a80", "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": 31946451, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1009, "license": "Apache-2.0", "license_type": "permissive", "path": "/Laboratory 2/src/main.c", "provenance": "stackv2-0065.json.gz:37065", "repo_name": "macisamuele/QueueSimulator", "revision_date": "2015-03-15T21:09:15", "revision_id": "398ced3b3d69b8987dc6ceab4a59f3714f5c5749", "snapshot_id": "462250a75298f6613639c6762c5a7f766ee4dad4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/macisamuele/QueueSimulator/398ced3b3d69b8987dc6ceab4a59f3714f5c5749/Laboratory 2/src/main.c", "visit_date": "2020-06-02T07:50:32.965392" }
stackv2
/* * Copyright 2014 Samuele Maci ([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 <stdio.h> #include "QueueNetwork.h" int main(int argc, char *argv[]) { QueueNetwork queuenetwork; queuenetwork = queuenetwork_init_from_command_line(argc-1, argv+1); queuenetwork_run(queuenetwork); queuenetwork_inputs(stdout, queuenetwork);fflush(stdout); queuenetwork_outputs(stdout, queuenetwork); queuenetwork_free(queuenetwork); return 0; }
2.109375
2
2024-11-18T21:10:20.278563+00:00
2023-08-17T16:08:06
faedc6aabe5bbe47df67206e0ddf1a9163a6e6db
{ "blob_id": "faedc6aabe5bbe47df67206e0ddf1a9163a6e6db", "branch_name": "refs/heads/main", "committer_date": "2023-08-17T16:08:06", "content_id": "1b542e2f4035d7ded4fbfebe82732a6ad150d079", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "eecd5e4c50d8b78a769bcc2675250576bed34066", "extension": "c", "filename": "ex2.c", "fork_events_count": 169, "gha_created_at": "2013-03-10T20:55:21", "gha_event_created_at": "2023-03-29T11:02:58", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 8691401, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1490, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/src/vec/is/is/tests/ex2.c", "provenance": "stackv2-0065.json.gz:37193", "repo_name": "petsc/petsc", "revision_date": "2023-08-17T16:08:06", "revision_id": "9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9", "snapshot_id": "3b1a04fea71858e0292f9fd4d04ea11618c50969", "src_encoding": "UTF-8", "star_events_count": 341, "url": "https://raw.githubusercontent.com/petsc/petsc/9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9/src/vec/is/is/tests/ex2.c", "visit_date": "2023-08-17T20:51:16.507070" }
stackv2
/* Formatted test for ISStride routines. */ static char help[] = "Tests IS stride routines.\n\n"; #include <petscis.h> #include <petscviewer.h> int main(int argc, char **argv) { PetscInt i, n, start, stride; const PetscInt *ii; IS is; PetscBool flg; PetscFunctionBeginUser; PetscCall(PetscInitialize(&argc, &argv, (char *)0, help)); /* Test IS of size 0 */ PetscCall(ISCreateStride(PETSC_COMM_SELF, 0, 0, 2, &is)); PetscCall(ISGetSize(is, &n)); PetscCheck(n == 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "ISCreateStride"); PetscCall(ISStrideGetInfo(is, &start, &stride)); PetscCheck(start == 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "ISStrideGetInfo"); PetscCheck(stride == 2, PETSC_COMM_SELF, PETSC_ERR_PLIB, "ISStrideGetInfo"); PetscCall(PetscObjectTypeCompare((PetscObject)is, ISSTRIDE, &flg)); PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_PLIB, "ISStride"); PetscCall(ISGetIndices(is, &ii)); PetscCall(ISRestoreIndices(is, &ii)); PetscCall(ISDestroy(&is)); /* Test ISGetIndices() */ PetscCall(ISCreateStride(PETSC_COMM_SELF, 10000, -8, 3, &is)); PetscCall(ISGetLocalSize(is, &n)); PetscCall(ISGetIndices(is, &ii)); for (i = 0; i < 10000; i++) PetscCheck(ii[i] == -8 + 3 * i, PETSC_COMM_SELF, PETSC_ERR_PLIB, "ISGetIndices"); PetscCall(ISRestoreIndices(is, &ii)); PetscCall(ISDestroy(&is)); PetscCall(PetscFinalize()); return 0; } /*TEST test: output_file: output/ex1_1.out TEST*/
2.078125
2
2024-11-18T21:10:20.365621+00:00
2016-05-13T07:24:43
d362b6a42bc303d3edb3f990f342639b77bbac29
{ "blob_id": "d362b6a42bc303d3edb3f990f342639b77bbac29", "branch_name": "refs/heads/master", "committer_date": "2016-05-13T07:24:43", "content_id": "33a1ba9b2ff6a16bc0a4247f930bb673297989e8", "detected_licenses": [ "MIT" ], "directory_id": "050d7d2439bdef7379ee52ae2fbce79ac0c8052b", "extension": "c", "filename": "save_name.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 50793456, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1772, "license": "MIT", "license_type": "permissive", "path": "/2016-02-02_hw/save_name.c", "provenance": "stackv2-0065.json.gz:37321", "repo_name": "ak9999/UNIX_assignments", "revision_date": "2016-05-13T07:24:43", "revision_id": "723e239d023735b933fc555df559dfc6960c4e21", "snapshot_id": "2973e5b192bd813ee3c5472342c1e5a15371ce92", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ak9999/UNIX_assignments/723e239d023735b933fc555df559dfc6960c4e21/2016-02-02_hw/save_name.c", "visit_date": "2021-01-19T10:34:13.055283" }
stackv2
/* * Author: Abdullah Khan * Date: 2016-01-30 * Program: save_name.c * Description: save_name takes an input from stdin (standard input). * Build instructions: make */ #include <fcntl.h> /* For creating, reading, and writing to files. */ #include <stdio.h> /* For standard input and output functions. */ #include <stdlib.h> /* For exit() */ #include <unistd.h> /* POSIX API */ #include <string.h> /* For string functions. */ #include <sys/stat.h> /* For mode_t */ int main(int argc, char ** argv) { if(argc != 2) { printf("Usage: %s \"name\"\n", argv[0]); exit(1); } /* Copy the name to sized buffer; Overflow safe. */ int name_size = strlen(argv[1]); char name[name_size]; strncpy(name, argv[1], name_size); /* Set file permission mode. * S_IRUSR: Read permission for file owner. * S_IWUSR: Write permission for file owner. * S_IRGRP: Read permission for group. * S_IROTH: Read permission for other. */ mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; /* Create file. */ /* O_WRONLY: Open for write only. * O_CREAT: Create file if it doesn't already exist. * O_EXCL: If file already exists, open fails. */ int file_desc = open("output.txt", O_WRONLY | O_CREAT | O_EXCL, mode); /* Check if open was successful, if not, exit. */ if(file_desc == -1) { printf("Couldn\'t open file. Exiting.\n"); exit(1); } /* Finally write the name to the file. */ write(file_desc, name, name_size); //printf("Writing name to %s", output_file); /* Close the file. */ int close_success = close(file_desc); if(close_success != 0) { printf("Error closing file.\n"); exit(1); } exit(0); }
3.609375
4
2024-11-18T21:10:20.920019+00:00
2017-12-20T10:53:30
cbfc09496116c58dba799834a425e53cd43e3bce
{ "blob_id": "cbfc09496116c58dba799834a425e53cd43e3bce", "branch_name": "refs/heads/master", "committer_date": "2017-12-20T10:53:30", "content_id": "4a78929b7eb169c0a229d66bf142bbe28404a21e", "detected_licenses": [ "MIT" ], "directory_id": "e63ef51866c08a1525ec086b5bdbb8b4bbb2e4b2", "extension": "c", "filename": "init.c", "fork_events_count": 20, "gha_created_at": "2017-09-23T16:13:04", "gha_event_created_at": "2018-01-22T22:04:55", "gha_language": "HTML", "gha_license_id": "MIT", "github_id": 104580871, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 687, "license": "MIT", "license_type": "permissive", "path": "/nikkochetkov/Lab1_BasicIO.X/init.c", "provenance": "stackv2-0065.json.gz:37962", "repo_name": "kpi-keoa/TheConnectedMCU_Labs", "revision_date": "2017-12-20T10:53:30", "revision_id": "6e0f3ec9efd101d002e09250b183c3ae857038ea", "snapshot_id": "c5315fb9c0dee773bd63b21ef16c19966b78c28b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kpi-keoa/TheConnectedMCU_Labs/6e0f3ec9efd101d002e09250b183c3ae857038ea/nikkochetkov/Lab1_BasicIO.X/init.c", "visit_date": "2021-09-05T06:38:29.883222" }
stackv2
#include "lab1.h" //INITIALIZATION void init(void){ //turning off analog mode for used ports LD1_ANSEL &= ~(1 << LD1); LD2_ANSEL &= ~(1 << LD2); LD3_ANSEL &= ~(1 << LD3); LD4_ANSEL &= ~(1 << LD4); BTN1_ANSEL &= ~(1 << BTN1); BTN2_ANSEL &= ~(1 << BTN2); //setting directions for each port //led ports to output (TRIS = 0) LD1_TRIS &= ~(1 << LD1); LD2_TRIS &= ~(1 << LD2); LD3_TRIS &= ~(1 << LD3); LD4_TRIS &= ~(1 << LD4); //button ports to input (TRIS = 1) BTN1_TRIS |= 1 << BTN1; BTN2_TRIS |= 1 << BTN2; //setting default conditions for leds (OFF = LAT=0) LD1_LAT &= ~(1 << LD1); LD2_LAT &= ~(1 << LD2); LD3_LAT &= ~(1 << LD3); LD4_LAT &= ~(1 << LD4); }
2.5625
3
2024-11-18T21:10:21.196412+00:00
2018-06-28T06:47:30
91693608b14611ba36813cc78f6ff65805ffb583
{ "blob_id": "91693608b14611ba36813cc78f6ff65805ffb583", "branch_name": "refs/heads/master", "committer_date": "2018-06-28T06:47:30", "content_id": "78412177acf4bb8dfff4d03ee28779a996150d24", "detected_licenses": [ "MIT" ], "directory_id": "accff61eec00c60211568d9ea1315fca36b84f18", "extension": "h", "filename": "RayMarch.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": 7593, "license": "MIT", "license_type": "permissive", "path": "/VolumetricClouds/RayMarch.h", "provenance": "stackv2-0065.json.gz:38351", "repo_name": "lanyu8/volumetric-cloud", "revision_date": "2018-06-28T06:47:30", "revision_id": "ff72ec81e4fc4b9e4127e37bad74e069b23aa04b", "snapshot_id": "c288036d3ec9b3f0664ca20daf5b638c1527b0fe", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lanyu8/volumetric-cloud/ff72ec81e4fc4b9e4127e37bad74e069b23aa04b/VolumetricClouds/RayMarch.h", "visit_date": "2022-01-12T06:20:51.591400" }
stackv2
#ifndef RAYMARCH_H_ #define RAYMARCH_H_ #include "algebra3.h" #include "VoxelGrid.h" double RayCubeSlabsIntersection(vec3 const& ro, vec3 const& rd, mat4 const& t_inv, mat4 const& tstar_inv); void MarchRay(vec3 orig, vec3 dir, VoxelGrid *grid, double step, vector<vec3> &points) { double t = RayCubeSlabsIntersection(orig, dir, grid->getTInv(), grid->getTStarInv()); // Check if ray hits the grid if (t < EPSILON) { points.push_back(vec3(-1, -1, -1)); return; } // If ray is outside of grid if (!grid->isInsideGrid(orig)) { orig = orig + (t + EPSILON)*dir; } // Ray is in the grid while (grid->isInsideGrid(orig)) { points.push_back(orig); orig = orig + step*dir; } } void MarchRayVoxel(vec3 orig, vec3 dir, VoxelGrid *grid, vector<vec3> &points) { double t = RayCubeSlabsIntersection(orig, dir, grid->getTInv(), grid->getTStarInv()); // Check if ray hits the grid if (t < EPSILON) { points.push_back(vec3(-1, -1, -1)); return; } vec3 start, end; // Get entering and exiting points if (!grid->isInsideGrid(orig)) { start = orig + (t + EPSILON)*dir; end = orig + (RayCubeSlabsIntersection(start, dir, grid->getTInv(), grid->getTStarInv()) + EPSILON)*dir; } else { start = orig; end = orig + (t + EPSILON)*dir; } vec3 point = start; double voxelSize = grid->getVoxelSize(); // Ratio to decrease number of division double dirX, dirY, dirZ; if (dir[0] != 0) dirX = 1/dir[0]; if (dir[1] != 0) dirY = 1/dir[1]; if (dir[2] != 0) dirZ = 1/dir[2]; // Get root position of current voxel in world coordinate vec3 voxel = grid->world2voxel(point); vec3 voxel0 = grid->voxel2world(voxel); vec3 voxel1 = grid->voxel2world(voxel + vec3(1, 1, 1)); // Distance to reach the next voxel in x, y, z direction double tMaxX = 1000000; double tMaxY = 1000000; double tMaxZ = 1000000; if (dir[0] < 0.0) tMaxX = (voxel0[0] - point[0])*dirX; if (dir[0] > 0.0) tMaxX = (voxel1[0] - point[0])*dirX; if (dir[1] < 0.0) tMaxY = (voxel0[1] - point[1])*dirY; if (dir[1] > 0.0) tMaxY = (voxel1[1] - point[1])*dirY; if (dir[2] < 0.0) tMaxZ = (voxel0[2] - point[2])*dirZ; if (dir[2] > 0.0) tMaxZ = (voxel1[2] - point[2])*dirZ; // Step size in x, y, z direction double stepX = (dir[0] < 0.0) ? -voxelSize : voxelSize; double stepY = (dir[1] < 0.0) ? -voxelSize : voxelSize; double stepZ = (dir[2] < 0.0) ? -voxelSize : voxelSize; // Distance to move one voxel width in x, y, z direction double tDeltaX = voxelSize*fabs(dirX); double tDeltaY = voxelSize*fabs(dirY); double tDeltaZ = voxelSize*fabs(dirZ); do { // Take steps in the smallest of x, y, z at each iteration until out of voxel space points.push_back(point); if (tMaxX < tMaxY) { if (tMaxX < tMaxZ) { point[0] = point[0] + stepX; tMaxX = tMaxX + tDeltaX; } else { point[2] = point[2] + stepZ; tMaxZ = tMaxZ + tDeltaZ; } } else { if (tMaxY < tMaxZ) { point[1] = point[1] + stepY; tMaxY = tMaxY + tDeltaY; } else { point[2] = point[2] + stepZ; tMaxZ = tMaxZ + tDeltaZ; } } } while ((grid->isInsideGrid(point))); } void MarchRayVoxelBresenham(vec3 orig, vec3 dir, VoxelGrid *grid, vector<vec3> &points) { double t = RayCubeSlabsIntersection(orig, dir, grid->getTInv(), grid->getTStarInv()); // Check if ray hits the grid if (t < EPSILON) { points.push_back(vec3(-1, -1, -1)); return; } vec3 start, end; // Get entering and exiting points if (!grid->isInsideGrid(orig)) { start = orig + (t + EPSILON)*dir; end = orig + (RayCubeSlabsIntersection(start, dir, grid->getTInv(), grid->getTStarInv()) + EPSILON)*dir; } else { start = orig; end = orig + (t + EPSILON)*dir; } vec3 point = start; double err_1, err_2; // Delta x, y, z double dx = end[0] - start[0]; double dy = end[1] - start[1]; double dz = end[2] - start[2]; double inc = grid->getVoxelSize(); // Voxel size double x_inc = (dx < 0) ? -inc : inc; // Get x direction double y_inc = (dy < 0) ? -inc : inc; // Get y direction double z_inc = (dz < 0) ? -inc : inc; // Get z direction // Get total x, y, z, length to travel double x_length = fabs(dx); double y_length = fabs(dy); double z_length = fabs(dz); // Multiply by 2 from original integral algorithm double dx2 = dx*2; double dy2 = dy*2; double dz2 = dz*2; // If x distance is largest if ((x_length >= y_length) && (x_length >= z_length)) { err_1 = dy2 - x_length; err_2 = dz2 - x_length; // Step through total x length one voxel at a time for (double ii = 0; ii < x_length; ii += inc) { points.push_back(point); if (err_1 > 0) { point[1] += y_inc; err_1 -= dx2; } if (err_2 > 0) { point[2] += z_inc; err_2 -= dx2; } err_1 += dy2; err_2 += dz2; point[0] += x_inc; } } // If y distance is largest else if ((y_length >= x_length) && (y_length >= z_length)) { err_1 = dx2 - y_length; err_2 = dz2 - y_length; // Step through total y length one voxel at a time for (double ii = 0; ii < y_length; ii += inc) { points.push_back(point); if (err_1 > 0) { point[0] += x_inc; err_1 -= dy2; } if (err_2 > 0) { point[2] += z_inc; err_2 -= dy2; } err_1 += dx2; err_2 += dz2; point[1] += y_inc; } } // If z distance is largest else { err_1 = dy2 - z_length; err_2 = dx2 - z_length; // Step through total z length one voxel at a time for (double ii = 0; ii < z_length; ii += inc) { points.push_back(point); if (err_1 > 0) { point[1] += y_inc; err_1 -= dz2; } if (err_2 > 0) { point[0] += x_inc; err_2 -= dz2; } err_1 += dy2; err_2 += dx2; point[2] += z_inc; } } // Get last point points.push_back(point); } double RayCubeSlabsIntersection(vec3 const& ro, vec3 const& rd, mat4 const& t_inv, mat4 const& tstar_inv) { vec3 o = t_inv*ro; vec3 d = tstar_inv*rd; vec3 dn = d.normalized(); double t = -1.0; double t_min = -100000; double t_max = 100000; int nside; // To check which side the normal is pointing out of vec3 ac = vec3(0, 0, 0); vec3 p = ac - o; for (int ii = 0; ii < 3; ii++) { double e = p[ii]; double f = dn[ii]; // Check if ray direction is perpendicular to the normal direction of the slab if (fabs(f) > EPSILON) { double fdiv = 1/f; // Division optimization double t1 = (e + 0.5)*fdiv; double t2 = (e - 0.5)*fdiv; // Ensures the minimum of t1 and t2 is stored in t1 if (t1 > t2) swap(t1, t2); if (t1 > t_min) { t_min = t1; nside = (ii + 1); } if (t2 < t_max) { t_max = t2; } if (t_min > t_max || t_max < 0) return t; // Ray misses the box or box is behind ray } // If ray is parallel to the slab else if (-e - 0.5 > 0 || -e + 0.5 < 0) return t; } if (t_min > EPSILON) { t = t_min/d.length(); nside *= 1; } else { t = t_max/d.length(); nside *= -1; } // Get the normal in world coordinate vec3 n3o(0, 0, 0); switch (nside) { case 1: n3o = vec3( 1, 0, 0); break; case -1: n3o = vec3(-1, 0, 0); break; case 2: n3o = vec3(0, 1, 0); break; case -2: n3o = vec3(0, -1, 0); break; case 3: n3o = vec3(0, 0, 1); break; case -3: n3o = vec3(0, 0, -1); break; default: break; } return t; } #endif
2.5625
3
2024-11-18T21:10:21.272560+00:00
2020-07-01T12:19:34
ea2283646f3e7162bf9160d2dbdeef75e3e095f0
{ "blob_id": "ea2283646f3e7162bf9160d2dbdeef75e3e095f0", "branch_name": "refs/heads/master", "committer_date": "2020-07-01T12:19:34", "content_id": "8e251116009fb384ba694e6015c2265fbfb83d53", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "directory_id": "bbf91cfe87a36779afbc43b5392abc0722363870", "extension": "h", "filename": "scale.h", "fork_events_count": 0, "gha_created_at": "2020-06-06T20:03:26", "gha_event_created_at": "2020-06-06T20:03:26", "gha_language": null, "gha_license_id": "MIT", "github_id": 270090369, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 571, "license": "BSD-3-Clause,MIT", "license_type": "permissive", "path": "/tos/system/scale.h", "provenance": "stackv2-0065.json.gz:38479", "repo_name": "ioteleman/InternetOfThings", "revision_date": "2020-07-01T12:19:34", "revision_id": "a87c1e2a243d06574d08645f8c5fe82f005c0da3", "snapshot_id": "df9792b2d38527bcd418d976c72fbb60e6ae5ccc", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ioteleman/InternetOfThings/a87c1e2a243d06574d08645f8c5fe82f005c0da3/tos/system/scale.h", "visit_date": "2022-11-06T06:22:16.304317" }
stackv2
#ifndef SCALE_H #define SCALE_H /* * Multiply x by a/b while avoiding overflow when possible. Requires that * a*b <= max value of from_t, and assumes unsigned arithmetic. * * @param x Number to scale * @param a Numerator of scaling value * @param b Denominator of scaling value * @return round(x * a/b) */ inline uint32_t scale32(uint32_t x, uint32_t a, uint32_t b) { uint32_t x_over_b = x / b; uint32_t x_mod_b = x % b; x_mod_b *= a; // on a separate line just in case some compiler goes weird return x_over_b * a + (x_mod_b + (b>>1)) / b; } #endif
2.671875
3
2024-11-18T21:10:21.800873+00:00
2018-06-19T00:55:17
9fa0563b0fa4923e303b054c7ce3146aba71bbe1
{ "blob_id": "9fa0563b0fa4923e303b054c7ce3146aba71bbe1", "branch_name": "refs/heads/master", "committer_date": "2018-06-19T00:55:17", "content_id": "ecdbfabcfbce03c95ff734fff4bac31bf8b1196b", "detected_licenses": [ "MIT" ], "directory_id": "70ae819d024aab57d3f11af006acc884b4a2b843", "extension": "c", "filename": "command_interpreter.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 131331983, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1138, "license": "MIT", "license_type": "permissive", "path": "/SPI/comunicacion-esp8266/lib/custom/command_interpreter.c", "provenance": "stackv2-0065.json.gz:38738", "repo_name": "Waaflee/TPs-Microcontroladores", "revision_date": "2018-06-19T00:55:17", "revision_id": "5e9a3aaee67cd7a4cdba90c9271ef77f935b8d18", "snapshot_id": "aad2e5f2faea741987f04e8b1085943481f39c0e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Waaflee/TPs-Microcontroladores/5e9a3aaee67cd7a4cdba90c9271ef77f935b8d18/SPI/comunicacion-esp8266/lib/custom/command_interpreter.c", "visit_date": "2020-03-13T23:15:57.170994" }
stackv2
#include "command_interpreter.h" void checkData(char data[]) { char temp[15]; int rotation; uint8_t direction; int speed; int coord; // printf("%s %s\n", "data: ", UARTData); switch (data[0]) { case 'r': direction = data[2] == 'f' ? FORWARD : BACKWARD; for (uint8_t i = 4; i < UARTcount; i++) { temp[i - 4] = data[i]; } rotation = atoi(temp); rotateNSteps(rotation, PAParray[atoi(&data[1])], direction); break; case 's': for (uint8_t i = 4; i < UARTcount; i++) { temp[i - 4] = data[i]; } speed = atoi(temp); setSpeed(speed, PAParray[atoi(&data[1])]); break; case 'b': stopPololu(PAParray[atoi(&data[1])]); break; case 'w': printf("PAP[%s] located in: %d\n", &data[1], PAParray[atoi(&data[1])]->motor->location); break; case 'p': for (uint8_t i = 4; i < UARTcount; i++) { temp[i - 4] = data[i]; } coord = atoi(temp); switch (data[2]) { case 'r': goTorel(coord, PAParray[atoi(&data[1])]); break; case 'a': goToabs(coord, PAParray[atoi(&data[1])]); break; } break; } }
2.359375
2
2024-11-18T21:10:22.255777+00:00
2016-07-13T13:50:42
636b3134659c245efc45c43fba8418b63bf2dcce
{ "blob_id": "636b3134659c245efc45c43fba8418b63bf2dcce", "branch_name": "refs/heads/master", "committer_date": "2016-07-13T13:50:42", "content_id": "817916f93e4ad39143ba5f2e4b4cb29d43901fcd", "detected_licenses": [ "MIT" ], "directory_id": "cd004ef6ad32218c7153bd8c06cc83818975154a", "extension": "h", "filename": "TradeSide.h", "fork_events_count": 0, "gha_created_at": "2016-07-16T05:51:14", "gha_event_created_at": "2016-07-16T05:51:14", "gha_language": null, "gha_license_id": null, "github_id": 63467798, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 403, "license": "MIT", "license_type": "permissive", "path": "/FDK/AggrProvider/TradeSide.h", "provenance": "stackv2-0065.json.gz:39122", "repo_name": "marmysh/FDK", "revision_date": "2016-07-13T13:50:42", "revision_id": "cc6696a8eded9355e4789b0193872332f46cb792", "snapshot_id": "11b7890c26f7aa024af8ea82fcb7c141326d2e6f", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/marmysh/FDK/cc6696a8eded9355e4789b0193872332f46cb792/FDK/AggrProvider/TradeSide.h", "visit_date": "2020-12-14T18:56:28.229987" }
stackv2
#pragma once enum TradeSide { TradeSide_None = 0, TradeSide_Buy = 1, TradeSide_Sell = 2, TradeSide_Last = INT_MAX }; inline ostream& operator << (ostream& stream, TradeSide& side) { if (TradeSide_None == side) { stream<<"none"; } else if (TradeSide_Buy == side) { stream<<"buy"; } else if (TradeSide_Sell == side) { stream<<"sell"; } stream<<'('<<(int)side<<')'; return stream; }
2.3125
2
2024-11-18T21:10:22.953258+00:00
2021-04-23T18:40:53
99711d7a766c1bfc1c162572ee588fed5548d305
{ "blob_id": "99711d7a766c1bfc1c162572ee588fed5548d305", "branch_name": "refs/heads/master", "committer_date": "2021-04-23T18:40:53", "content_id": "67c35f4385ee1ae4bde1be4120c87f8819091601", "detected_licenses": [ "MIT" ], "directory_id": "a37d6a5d606298f41eae3f70f82fd9b001f5bfc9", "extension": "h", "filename": "crc32.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": 845, "license": "MIT", "license_type": "permissive", "path": "/lib/crc32/crc32.h", "provenance": "stackv2-0065.json.gz:40146", "repo_name": "hemi454/specter-bootloader", "revision_date": "2021-04-23T18:40:53", "revision_id": "6fa6157906dcb0018781432daac4a22e1bba86d7", "snapshot_id": "927bfb304a6820714f6ceba1067fba39fa0d8aa9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/hemi454/specter-bootloader/6fa6157906dcb0018781432daac4a22e1bba86d7/lib/crc32/crc32.h", "visit_date": "2023-04-08T23:34:01.855843" }
stackv2
/** * @file crc32.h * @brief API for the "Fast CRC32" implementation by Stephan Brumme * @author Mike Tolkachev <[email protected]> * @copyright Copyright 2020 Crypto Advance GmbH. All rights reserved. */ #ifndef CRC32_H_INCLUDED /// Avoids multiple inclusion of header file #define CRC32_H_INCLUDED #include <stdint.h> #include <stddef.h> #ifdef __cplusplus extern "C" { #endif /** * Computes CRC32 using the fastest algorithm for large datasets on modern CPUs * * @param data data block to process * @param length length of data block to brocess * @param previousCrc32 previous CRC value or 0 for the first block * @return uint32_t */ uint32_t crc32_fast(const void* data, size_t length, uint32_t previousCrc32); #ifdef __cplusplus } // extern "C" #endif #endif // CRC32_H_INCLUDED
2.375
2
2024-11-18T21:10:23.134392+00:00
2016-06-19T14:54:33
81696adf098aaa8b137dc30eefa6708eeef451b5
{ "blob_id": "81696adf098aaa8b137dc30eefa6708eeef451b5", "branch_name": "refs/heads/master", "committer_date": "2016-06-19T15:00:00", "content_id": "632674bd4997dbc9cf33608163d649142a33328e", "detected_licenses": [ "MIT" ], "directory_id": "03d472aac184531216e3d0a3c0f3c8c171dc6e06", "extension": "c", "filename": "py_driver_wrapper.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 53605834, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1033, "license": "MIT", "license_type": "permissive", "path": "/source/py_driver_wrapper.c", "provenance": "stackv2-0065.json.gz:40275", "repo_name": "freedom27/MyPyDHT", "revision_date": "2016-06-19T14:54:33", "revision_id": "4ea1cedeb12ba59beba5c93f2523c304361ef8ad", "snapshot_id": "aab1fdc02f76d9f938df923faa73083ab0ea5551", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/freedom27/MyPyDHT/4ea1cedeb12ba59beba5c93f2523c304361ef8ad/source/py_driver_wrapper.c", "visit_date": "2021-01-21T01:58:29.202766" }
stackv2
#include <Python.h> #include "MyDHT_RPi_Driver/dht_driver.h" static PyObject *sensor_read(PyObject *self, PyObject *args) { int sensor_type, gpio_pin; int result; if (!PyArg_ParseTuple(args, "ii", &sensor_type, &gpio_pin)) return NULL; struct dht_sensor_data data; result = dht_read(sensor_type, gpio_pin, &data); if(result < 0) data.humidity = data.temperature = 0.0f; return Py_BuildValue("iff", result, data.humidity, data.temperature); } static PyMethodDef DHTMethods[] = { {"_dht_read", sensor_read, METH_VARARGS, "Read sensor data!"}, {NULL, NULL, 0, NULL} }; static struct PyModuleDef mypydhtmodule = { PyModuleDef_HEAD_INIT, "dht_driver", /* name of module */ NULL, /* module documentation, may be NULL */ -1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */ DHTMethods }; PyMODINIT_FUNC PyInit_dht_driver(void) { return PyModule_Create(&mypydhtmodule); }
2.15625
2